code: arr = np.hstack((t[:, None], data[:, None])).astype(np.dtype([('t', 'f8'), ('data', 'i2')]))

rawDescription: how to make a numpy recarray from column arrays

description: Make a numpy recarray from column arrays


rawDescription: My spider doesn't follow links

description: My spider doesn't follow links


code:
@pytest.yield_fixture(scope="class")
def oneTimeSetUp(request, browser):
    print("Running one time setUp")
    if browser == 'firefox':
        driver = webdriver.Firefox()
        driver.maximize_window()
        driver.implicitly_wait(3)
        print("Running tests on FF")
    else:
        driver = webdriver.Chrome()
        print("Running tests on chrome")

    if request.cls is not None:
        request.cls.driver = driver
        request.cls.abc = ABC(driver) # <-- here

    yield driver
    print("Running one time tearDown")

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

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


code:
from selenium import webdriver

import pandas as pd

driver = webdriver.PhantomJS()
driver.get("http://www.oddsportal.com/hockey/usa/nhl-2014-2015/results/#/page/2.html")

data = []
for match in driver.find_elements_by_css_selector("div#tournamentTable tr.deactivate"):
    home, away = match.find_element_by_class_name("table-participant").text.split(" - ")
    date = match.find_element_by_xpath(".//preceding::th[contains(@class, 'first2')][1]").text

    if " - " in date:
        date, event = date.split(" - ")
    else:
        event = "Not specified"

    data.append({
        "home": home.strip(),
        "away": away.strip(),
        "date": date.strip(),
        "event": event.strip()
    })

driver.close()

df = pd.DataFrame(data)
print(df)

rawDescription: Reformatting scraped selenium table

description: Reformatting scraped selenium table


code: factor = 60.0 / time_interval

rawDescription: Division by Zero Errors

description: Division by Zero Errors


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

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


code:
with open('text.txt') as f:
    # sequence of all words in all lines
    words = (word for line in f for word in line.split())
    # consume the first 2 items from the words sequence
    word1 = next(words)
    word2 = next(words)

rawDescription: Reading two strings from file

description: Reading two strings from file


code:
#All the stuff earlier in the program
plt.imshow(matrix, interpolation='nearest', cmap=plt.cm.ocean, extent=(0.5,10.5,0.5,10.5))
plt.colorbar()
plt.show()

rawDescription: Matplotlib plot numpy matrix as 0 index

description: Matplotlib plot numpy matrix as 0 index


rawDescription: Python: slicing a multi-dimensional array


code: [{u'pass': 2087, u'username': u'abhi'}]

rawDescription: replace text from list of dictionary python

description: Replace text from list of dictionary python


code:
@app.context_processor
def inject_variable():
    return dict(variable=1)

rawDescription: How to show widgets on pages in Flask?

description: Show widgets on pages in Flask


code:
#...
class FakeSMTPServer(smtpd.SMTPServer):
    def process_message(self, peer, mailfrom, rcpttos, data):
        # ...
        self.data = data
        # ...

if __name__ == "__main__":
    smtp_server = FakeSMTPServer(('0.0.0.0', 25), None)
    try:
        asyncore.loop()
    except KeyboardInterrupt:
        smtp_server.close()
    # smtp_server.data contains text of message

rawDescription: How to scan python smtpd server for text

description: Scan python smtpd server for text


code:
class AnotherClass(BaseClass):
    def __init__(self):
        self.some_class_member += (6, 7,)

rawDescription: Python: appending to a base class list/tuple member


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


rawDescription: Best way to reduce dictionary of lists

description: Reduce dictionary of lists


rawDescription: Python transforming one dimensional array into two dimensional array


code:
t1=AKSO.OL, t2=BWLPG.OL
t1=AKSO.OL, t2=DETNOR.OL
t1=AKSO.OL, t2=DNB.OL
t1=AKSO.OL, t2=DNO.OL
t1=AKSO.OL, t2=FOE.OL
t1=AKSO.OL, t2=FRO.OL
t1=BWLPG.OL, t2=AKSO.OL
t1=BWLPG.OL, t2=DETNOR.OL
t1=BWLPG.OL, t2=DNB.OL
t1=BWLPG.OL, t2=DNO.OL
t1=BWLPG.OL, t2=FOE.OL
t1=BWLPG.OL, t2=FRO.OL
t1=DETNOR.OL, t2=AKSO.OL
t1=DETNOR.OL, t2=BWLPG.OL
t1=DETNOR.OL, t2=DNB.OL
t1=DETNOR.OL, t2=DNO.OL
t1=DETNOR.OL, t2=FOE.OL
t1=DETNOR.OL, t2=FRO.OL
t1=DNB.OL, t2=AKSO.OL
t1=DNB.OL, t2=BWLPG.OL
t1=DNB.OL, t2=DETNOR.OL
t1=DNB.OL, t2=DNO.OL
t1=DNB.OL, t2=FOE.OL
t1=DNB.OL, t2=FRO.OL
t1=DNO.OL, t2=AKSO.OL
t1=DNO.OL, t2=BWLPG.OL
t1=DNO.OL, t2=DETNOR.OL
t1=DNO.OL, t2=DNB.OL
t1=DNO.OL, t2=FOE.OL
t1=DNO.OL, t2=FRO.OL
t1=FOE.OL, t2=AKSO.OL
t1=FOE.OL, t2=BWLPG.OL
t1=FOE.OL, t2=DETNOR.OL
t1=FOE.OL, t2=DNB.OL
t1=FOE.OL, t2=DNO.OL
t1=FOE.OL, t2=FRO.OL
t1=FRO.OL, t2=AKSO.OL
t1=FRO.OL, t2=BWLPG.OL
t1=FRO.OL, t2=DETNOR.OL
t1=FRO.OL, t2=DNB.OL
t1=FRO.OL, t2=DNO.OL
t1=FRO.OL, t2=FOE.OL

rawDescription: python function taking arguments from list

description: Python function taking arguments from list


code: sorted(mylist, key=lambda d: month_to_index[d['month'][:3]])

rawDescription: list of dictionary Sorting in python

description: List of dictionary Sorting in python


code:
a = A()
a.foo() #prints 'Foo'
a.bar('Arg!') #prints 'Bar Arg!'

rawDescription: Python calling method in class

description: Python calling method in class


code:
class_filenames = ['Class X.txt', 'Class Y.txt', 'Class Z.txt']

for class_file in class_filenames:
    with open(class_file, 'r') as f:
        ...

rawDescription: Python - Highest with alphabetical order from text file


code: drawTop()

rawDescription: Clear only part of the screen in Python

description: Clear only part of the screen in Python


code:
class Time:
    def __init__(self, hours=0, minutes=0, seconds=0, time_now=''):
        if hours == 'now':
            tmp_t = now()
            self.hour = tmp_t.hour
            self.min = tmp_t.min
            self.sec = tmp_t.sec
        else:
            t = abs(3600*hours + 60*minutes + seconds)
            self.hour = t//3600
            self.min = t//60%60
            self.sec = t%60

rawDescription: Accept a single string instead of normal parameters


code:
my_variable = 'some_name'
data['A']['B'][my_variable]['maindata'][0]['Info']

rawDescription: Find a value within nested json dictionary in python


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

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


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

rawDescription: Shifted difference between columns respecting grouping


code: 'passcode' 'passcode\n'

rawDescription: Test if user has entered a word equal to a word in a text file


code: from MyProduct import MyCoreBindings as SDK

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


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

description: Convert a string to a function in python


rawDescription: Pandas extract dataframe time series

description: Pandas extract dataframe time series


rawDescription: QTableWidget Integer

description: QTableWidget Integer


code:
def chunkRecords(records):
    record = []
    for r in records:
        if r[-1] == ':':
            if record:
                yield record
            record = [r[:-1]]
        else:
            record.append(r)
    if record:
        yield record

rawDescription: chunking list by delimiter in Python

description: Chunking list by delimiter in Python


code:
from mock import patch

@patch('this.is.my.module.logger')
def test_check_logging_message(self, mock_logger):
    mock_logger.error.assert_called_with("Your log message here")

rawDescription: How do I test if a certain log message is logged in a Django test case?

description: Test if a certain log message is logged in a Django test case


code:
from itertools import islice

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

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

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


code:
def annotate(self, ax):
    """Draws and hides the annotation box for the given axis "ax"."""
    annotation = ax.annotate(self.template, xy=(0, 0), ha='right',
            xytext=self.offsets, textcoords='offset points', va='bottom',
            bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
            arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')
            )
    # Put the annotation in the figure instead of the axes so that it will be on
    # top of other subplots.
    ax.figure.texts.append(ax.texts.pop())

    annotation.set_visible(False)
    return annotation

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

description: Prevent a matplotlib annotation being clipped by other axes


code:
class SiteForm(ModelForm):
    class Meta:
        model = Site

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(SiteForm, self).__init__(*args, **kwargs)
        self.fields['trip'].queryset = Trip.objects.filter(id__in=user.site_set.values_list(trip, flat=True))

rawDescription: Only Allow ForeignKey Selection of User Values


rawDescription: Is there any relationship between model's clean() method and form's clean() method?


rawDescription: Django permissions mixin on CBV, how to apply on 'publish blog' method


code:
with open('largefilename', 'r') as largefile:
    output_file.writelines(islice(largefile, N))

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

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


code:
infile = open('data')
lines = infile.readlines()
infile.seek(0)
print(lines)
words = infile.read()
infile.seek(0)

chars = infile.read()
infile.close()
print("line count:", len(lines))
print("word count:", len(words.split()))
print("character counter:", len(chars))

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


rawDescription: Fastest way to iterate through a pandas dataframe?


code: [(i, j) for i in firstList for j in secondList]

rawDescription: Merge two lists into a list of tuples with custom condition


code:
adict = {1: set(['a', 'b']), 2: set(['b', 'c'])}
inverse = {}
for key, values in adict.items():
    for value in values:
        inverse.setdefault(value, set()).add(key)
inverse

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

description: Inverse sort a dictionary that has sets as values


code:
import scipy.interpolate as inter
import numpy as np
import pylab as plt

x = np.array([13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
y = np.array([2.404070, 1.588134, 1.760112, 1.771360, 1.860087,
          1.955789, 1.910408, 1.655911, 1.778952, 2.624719,
          1.698099, 3.022607, 3.303135])
xx = np.arange(1,13.01,0.1)
s1 = inter.InterpolatedUnivariateSpline (x, y)
s1rev = inter.InterpolatedUnivariateSpline (x[::-1], y[::-1])
# Use a smallish value for s
s2 = inter.UnivariateSpline (x[::-1], y[::-1], s=0.1)
s2crazy = inter.UnivariateSpline (x[::-1], y[::-1], s=5e8)
plt.plot (x, y, 'bo', label='Data')
plt.plot (xx, s1(xx), 'k-', label='Spline, wrong order')
plt.plot (xx, s1rev(xx), 'k--', label='Spline, correct order')
plt.plot (xx, s2(xx), 'r-', label='Spline, fit')
# Uncomment to get the poor fit.
#plt.plot (xx, s2crazy(xx), 'r--', label='Spline, fit, s=5e8')
plt.minorticks_on()
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.show()

rawDescription: Fitting data using UnivariateSpline in scipy python


code:
replacement_rows = array2[non_zero_values-1]
replacement_values = array2[non_zero_values-1, 2] # third element of that row!

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


rawDescription: GAE Datastore ndb models accessed in 5 different ways


code:
def decode(values):
    filters = []
    for f in values:
        filter = {}
        for text in f:
            words = text.split(':')
            if len(words)==1:
                words = ['include']+words
            files = words[1].split(',')
            if words[0] == 'include':
                filter['include'] = files
            elif words[0] == 'exclude':
                filter['exclude'] = files
            else:
                filter['unknown'] = files
        filters.append(filter)
    return filters

rawDescription: Handling string with delimiters in argparse


code:
import re
import lxml.html as LH

url = u"http://hkdramas.se/fashion-war-%E6%BD%AE%E6%B5%81%E6%95%99%E4%B8%BB-episode-20/"
xpath = u"""//script[contains(.,'label:"360p"')]"""
root = LH.parse(url)
for elt in root.xpath(xpath):
    for url in re.findall(r'"(http[^"]+)"', elt.text):
        print(url)

rawDescription: using python lxml+xpath to get videos from a page, get a list but can't print out the result?

description: Using python lxml+xpath to get videos from a page, get a list but can't print out the result


code:
from collections import OrdererdDict
sorted_author = OrderedDict(sorted(author.iteritems()))

rawDescription: Python,Sorting a dictionary

description: Python,Sorting a dictionary


code:
# Store this code in the file MyMainWindow.py
from PyQt4.QtGui import *

class MyMainWindow(QMainWindow):
    def __init__(self, ui_layout):
        QMainWindow.__init__(self)

        self.ui = ui_layout
        ui_layout.setupUi(self)

rawDescription: How to run the program generated by pyuic4?

description: Run the program generated by pyuic4


code: logging.addHandler( logging.StreamHandler( someStreamlikeObject ) )

rawDescription: Python script, log to screen and to file


rawDescription: Using URL in Django Views? Possible?

description: Using URL in Django Views? Possible


code: heatmap_color = [[cmap.to_rgba(r, alpha=0.5, bytes=True) for r in c] for c in heatmap]

rawDescription: Python: Optimise For loops using list-comprehension


code:
temp = a
a = b
b = temp

rawDescription: Shuffling a list

description: Shuffling a list


rawDescription: Why doesn't the Python 2D array index order matter when used with colon ( : )


code:
def split_sequence(seq, chunks):
    for splits in itertools.combinations(range(1, len(seq)), chunks - 1):
        left = (None,) + splits
        right = splits + (None,)
        yield [seq[l:r] for l, r in zip(left, right)]

rawDescription: Yield sub combinations with constraint on lenght of output list


code:
data = [['Title\nPage', 'Name', 'Exists'],  # note the newline character
        ['', 'George', 'True']]
t = Table(data, style=style_)
...

rawDescription: How to insert a carriage return in a ReportLab paragraph?

description: Insert a carriage return in a ReportLab paragraph


code:
query = {'x': 1}
if checkbox == 'checked':
    query['y'] = 2

results = db.collection.find(query)

rawDescription: Dynamically building queries in pymongo

description: Dynamically building queries in pymongo


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


code: df = pd.Panel.from_dict(d).to_frame()

rawDescription: Dict of dicts of dicts to DataFrame

description: Dict of dicts of dicts to DataFrame


code:
from multiprocessing import Pool, cpu_count
pool = Pool(processes=cpu_count())

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

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


code:
weight = ProductWeight(product=product_one, weight=3.55)
weight.save()

rawDescription: How do you implement multiple data types for an object in Django?

description: Implement multiple data types for an object in Django


code:
objs = [list-of-objects]
used = set()
for obj in objs:
    used.update(obj.callSomeFunc(used))

rawDescription: Idiomatic way to build list with successive function calls on that list


code: idx = next(i for (i, (a, b)) in enumerate(zip(w1, w2)) if a != b)

rawDescription: Python: How to find the position of the character that makes the levenshtein distance


code:
@ndb.tasklet
def get_urls(urls):
  ctx = ndb.get_context()
  result = yield map(ctx.urlfetch, urls)
  contents = [r.content for r in result if r.status_code==200]
  raise ndb.Return('\n'.join(contents))

rawDescription: GAE - How can I combine the results of several asynchronous url fetches?


code: table = sum(zip(*colors), ())

rawDescription: Using the Image.point() method in PIL to manipulate pixel data


code: zip(*l)

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


code:
def in_order(a,b):
    j = iter(b)
    for i in a:
        while True:
            try:
                j_ = j.next()
            except StopIteration:
                return False
            if i == j_:
                break
    return True

rawDescription: Checking if a lists' items are in the same order in another list


code: map(list.extend, T, B)

rawDescription: Appending first value of a list into the first value of another list; python


rawDescription: What is an alternative to sorted() in this situation? Or can this be managed?


code:
from werkzeug import BaseRequest

class Request(BaseRequest):
    pass

rawDescription: What is a mixin, and why are they useful?


code:
from collections import Counter

answers = [
    {'Question 1': {'Job': 'job1', 'Country': 'USA', 'Car': 'Porche'}},
    {'Question 1': {'Job': 'job2', 'Country': 'UK',  'Car': 'Nissan'}},
    {'Question 3': {'Job': 'job8', 'Country': 'GR',  'Car': 'Toyota'}},
    {'Question 4': {'Job': 'job1', 'Country': 'USA', 'Car': 'Toyota'}},
    {'Question 4': {'Job': 'job5', 'Country': 'USA', 'Car': 'Toyota'}},
    {'Question 4': {'Job': 'job5', 'Country': 'USA', 'Car': 'Porche'}},
]

counted = Counter([item for q in answers for answer in q.values() for item in answer.items()])

rawDescription: Search in a python list

description: Search in a python list


rawDescription: How to change the data type from integer to float after applying a function in python

description: Change the data type from integer to float after applying a function in python


code:
# this function is applied to all buyers
def find_good_buyers(buyer):
    # which dates the buyer has made a purchase
    buyer_dates = buyer.groupby('date')
    # a string representing the unique items purchased at each date
    items_on_date = buyer_dates.agg({'item_id': lambda x: '-'.join(x.unique())})
    # if there is more than 1 combination of item_id, then it means that
    # the buyer has purchased different things in different dates
    # so this buyer must be flagged to 1
    good_buyer = (len(items_on_date.groupby('item_id').groups) > 1) * 1
    return good_buyer

df['item_id'] = df['item_id'].astype('S')
buyers = df.groupby('buyer_id')

good_buyer = buyers.apply(find_good_buyers)
df.set_index('buyer_id', inplace=True)
df['good_buyer'] = good_buyer
df.reset_index(inplace=True)

rawDescription: how to groupby pandas dataframe on some condition

description: Groupby pandas dataframe on some condition


code: p = Popen('/usr/bin/python /apps/sample.py {} {}'.format(var1, var2), shell=True)

rawDescription: Python: Passing value of a string variable as argument in Popen


code:
dic = {'y':True, 'n':False}
d['bool'] = d['bool'].apply(lambda x: dic[x])
trigger = d[d['bool']].sort('date').drop_duplicates('Group').drop('bool', axis=1)
d = d.merge(trigger, how='left', on='Group', suffixes=['','_trigger'])

rawDescription: Assigning a column for a modified dataframe back to original dataframe in pandas


code:
primes = []
for n in range(2, 10):
    for m in range(2, n):
        if not(n % m):
            break
    else:
        primes.append(n)

rawDescription: Prime generator in python returns multiple composites instead of primes


code:
txtarea = self.documentElement.findFirst('textarea[name="someTextArea"]')
txtarea.evaluateJavascript('this.focus()')

rawDescription: How to click text area in Qwebview and python

description: Click text area in Qwebview and python


code:
import csv
w = csv.writer(open("some_file.txt","w"))
w.writerows(zip(*list_of_cols))

rawDescription: Write to csv with columns as list in python?


code:
import email

msg = email.message_from_string(emailstr)

if (msg.is_multipart() and len(msg.get_payload()) > 1 and
    msg.get_payload(1).get_content_type() == 'message/delivery-status'):
    # email is DSN
    print(msg.get_payload(0).get_payload()) # human-readable section

    for dsn in msg.get_payload(1).get_payload():
        print('action: %s' % dsn['action']) # e.g., "failed", "delivered"

    if len(msg.get_payload()) > 2:
        print(msg.get_payload(2)) # original message

rawDescription: Detecting if an email is a "Delivery Status Notification" and extract information - Python


code:
from collections import deque
def generate_list():
    que = deque([1,1,1],3)
    yield 1
    yield 1
    yield 1
    while True:
        out = que[-3]+que[-2]
        yield out
        que.append(out)

rawDescription: Formula to Generate List of Specific Numbers


rawDescription: What method to use to figure out if user is connected to facebook


code:
command = queue.popleft()
command()

rawDescription: Using Deque.popleft as args for function


code:
data = 'EV|0|EV|1|OD;OD|0|OD|1|EV'

# output: {even: {0:even, 1:odd}, odd: {0:odd, 1:even}}

information = data.split(';')
output = {}
for piece in information:  # Each piece is like EV|0|EV|1|OD
    parts = piece.split('|')
    head = parts[0]  # Our dictionary key, eg. [EV]
    tail = parts[1:]  # Stuff that makes up the inner dict, e.g. [0, EV, 1, OD]

    # Use step = 2 to get key:value pairs from tail:
    inner = {tail[i]: tail[i+1] for i in range(0, len(tail)-1, 2)}

    if head not in output:
        output[head] = inner
    else:
        # What do we do here?
        pass

print(output)

rawDescription: Automatic in python

description: Automatic in python


code:
arguments = ["arg1", "arg1", "arg3"]
print(*arguments)

rawDescription: How to get all items from a list in Python 2

description: Get all items from a list in Python 2


code:
from collections import defaultdict
import logging
import threading

class ContextAwareFormatter(logging.Formatter):
    """
    Makes use of get_context() to populate the record attributes.
    """

    def format(self, record):
        # Using defaultdict to avoid KeyErrorS when a key is not in the context.
        def factory():
            return ""
        record.__dict__ = defaultdict(factory, record.__dict__)

        for k, v in get_context().iteritems():
            if not hasattr(record, k):
                setattr(record, k, v)
        return logging.Formatter.format(self, record)

THREADLOCAL_ATTR = "logging_context"
_threadlocal = threading.local()

def get_context():
    result = getattr(_threadlocal, THREADLOCAL_ATTR, None)
    if result is None:
        result = {}
        setattr(_threadlocal, THREADLOCAL_ATTR, result)
    return result

def set_context(**context):
    c = get_context()
    c.clear()
    c.update(**context)
    return c

def update_context(**context):
    c = get_context()
    c.update(**context)
    return c

rawDescription: Defining a logger for every thread

description: Defining a logger for every thread


rawDescription: Simple PyQt Function Evaluator

description: Simple PyQt Function Evaluator


code:
from http import cookies
cookie = cookies.SimpleCookie()
cookie["varname"] = 'value'
print(cookie.output())

rawDescription: Python Setting and Recalling Cookies

description: Python Setting and Recalling Cookies


code: sys.ps1 = 'something else '

rawDescription: Python import and module scoping (specifically sys.ps1)


code:
drop = rn.range(0,n) #choose a random integer to drop

with open('my_file.txt','w') as f:
    for ind,ele in enumerate(xrange(n)):
        if ind == drop: #do not write the element to txt file
            pass
        else:
            f.write(str(ele) + '\n') #write every except for one element to txt file

with open('my_file.txt','a') as f:
    for ele in xrange(n):
        f.write(str(ele) + '\n') # write every element to txt file

rawDescription: how to generate random num with conditions

description: Generate random num with conditions


code:
players=int(input("How many players?\n"))
player_names=set()
while len(player_names)<players:
  player_names.add(input("What is player {}'s name?\n".format(len(player_names)+1)))

rawDescription: Doesn't accept the list index?

description: Doesn't accept the list index


code:
class MyModel(models.Model):
    file = PastebinModelField()

rawDescription: Passing an input to a service and saving the result to DB in Django


code:
import re, itertools
my_list = ['ab','cde']
keywords = ['ab','cd','de']

indices = {}
pats = [re.compile(i) for i in keywords]
for pat in pats:
    for i in my_list:
        indices.setdefault(i, [])
        for m in re.finditer(pat, i):
            a = list((m.start(),m.end()))
            indices[i].append(a)
print(indices)

rawDescription: Nesting lists in for loop in python

description: Nesting lists in for loop in python


code:
handints = [int(i[:-1]) for i in hand]
handints

rawDescription: Taking Elements From a List

description: Taking Elements From a List


code:
x = """<score-partwise>
      <attributes>
        <transpose>
          <diatonic>-5</diatonic>
          <chromatic>-9</chromatic>
          </transpose>
        </attributes>
      </score-partwise>"""

import xml.etree.ElementTree as et
xml = et.fromstring(x)

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

print(et.tostring(xml))

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

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


code:
from contextlib import contextmanager
import sys

class Prefixer(object):
    def __init__(self, prefix, orig):
        self.prefix = prefix
        self.orig = orig
    def write(self, text):
        self.orig.write(self.prefix + text)
    def __getattr__(self, attr):
        return getattr(self.orig, attr)

@contextmanager
def prefix_stdout(prefix):
    current_out = sys.stdout
    try:
        sys.stdout = Prefixer(prefix, current_out)
        yield
    finally:
        sys.stdout = current_out

rawDescription: Change python's print behaviour in a context


code:
string_values = returned_string_from_API.split(',')
string_values

rawDescription: CSV string to decimal in python list

description: CSV string to decimal in python list


rawDescription: Finding remainder mod involving exponent and division involving huge numbers


rawDescription: python merging dictionary of lists of lists/tuples

description: Python merging dictionary of lists of lists/tuples


rawDescription: Assign Different Types to Python List in Advance


rawDescription: Cache the result of a MySQLdb database query in memory


code:
df['Names'] = [[n for n in names if n.split()[1][0] == x] for x in df['Letters']]
df

rawDescription: python list comprehension return names based on letter

description: Python list comprehension return names based on letter


rawDescription: print memory address of Python variable

description: Print memory address of Python variable


code:
from bottle import template
template('{{locals()["list" + str(i)]}}', i=1, list1=[1,2,3,4])

rawDescription: Passing variable in Python Bottle in Iteration


code:
class Student(models.Model):
   # Removing the tests field. Rather add `student` field in `Test` model
   # tests = models.ManyToManyField(Test)
   title = models.CharField(max_length=3,default="mr",blank=False)
   name = models.CharField(max_length=50,default='',blank=False)
   address = models.CharField(max_length=200,default='',blank=False)
   city = models.ForeignKey(City)

rawDescription: Consuming api from django rest framework


rawDescription: Python list of sets to dictionary

description: Python list of sets to dictionary


code: random.sample(xrange(1, y), z)

rawDescription: list of random integers without zero Python

description: List of random integers without zero Python


code:
import numpy as np
np.random.seed(2015)

m, n = 10000, 5000
# Note A may contain duplicate rows,
# so don't use assume_unique=True for these benchmarks.
# In this case, using assume_unique=False does not improve the speed much anyway.
A = np.random.randint(10, size=(2*m,3))
# make A not C_CONTIGUOUS; the view methods fail for non-contiguous arrays
A = A[::2]
B = A[np.random.choice(m, n, replace=False)]

def using_view(A, B, assume_unique=False):
    Ad = np.ascontiguousarray(A).view([('', A.dtype)] * A.shape[1])
    Bd = np.ascontiguousarray(B).view([('', B.dtype)] * B.shape[1])
    return ~np.in1d(Ad, Bd, assume_unique=assume_unique)

from scipy.spatial import distance
def using_distance(A, B):
    return ~np.any(distance.cdist(A,B)==0,1)

from functools import reduce
def using_loop(A, B):
    pred = lambda i: A[:, i:i+1] == B[:, i]
    return ~reduce(np.logical_and, map(pred, range(A.shape[1]))).any(axis=1)

from pandas.core.groupby import get_group_index, _int64_overflow_possible
from functools import partial
def using_pandas(A, B):
    shape = [1 + max(A[:, i].max(), B[:, i].max()) for i in range(A.shape[1])]
    assert not _int64_overflow_possible(shape)

    encode = partial(get_group_index, shape=shape, sort=False, xnull=False)
    a1, b1 = map(encode, (A.T, B.T))
    return ~np.in1d(a1, b1)

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

# Sanity check: make sure all the functions return the same result
for func in (using_distance, using_loop, using_pandas, using_void):
    assert (func(A, B) == using_view(A, B)).all()

rawDescription: Matrix row difference, output a boolean vector


code:
for i in range(timesteps):
    fig = pyplot.figure()
    ...
    fig.savefig(filepath)

rawDescription: Plotting in a loop (with basemap and pyplot)....problems with pyplot.clf()


code:
from collections import Counter
from itertools import islice

def window(seq, n=2):
    "Returns a sliding window (of width n) over data from the iterable"
    "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result

minimum_size = 2
counts = Counter()

with open(filename) as infh:
    for line in infh:
        parts = line.strip().split('-')
        # count substrings of various sizes
        counts.update('-'.join(sp)
                      for size in range(minimum_size, len(parts) + 1)
                      for sp in window(parts, size))

rawDescription: Top of the most frequent substrings in file of sequences


rawDescription: Feeding a Python array into a Perl script


rawDescription: Combine multidimensional array by group python


code:
class Person(models.Model):
    id = models.IntegerField(primary_key=True)
    person_id = models.OneToOneField(User, related_name='person')
    birthdate = models.DateTimeField(blank=True, null=True)
    ...

rawDescription: DRF relate single field from model

description: DRF relate single field from model


code:
import gzip, pickle

output = gzip.open('pickled.gz', 'wb', compresslevel=9)

for x in range(10):
     output.write(pickle.dumps(range(10)) + '\n\n')
output.close()

rawDescription: How to write lists "one by one" to a binary file in python?

description: Write lists "one by one" to a binary file in python


code:
# read in the transactions
with open('blah.txt') as file_obj:
    raw_data = file_obj.readlines()

inventory = {} # initialize your outer dictionary

# parse the transactions and update the inventory
for line in raw_data:
    if not line.strip():
        continue
    name, region, amount = line.strip().split()

    # is r2 the same as R2?
    region = region.lower()
    # we'd like to manipulate amount as a number not a string
    amount = float(amount)

    # create a new inner dictionary for this name, if not one already
    if not name in inventory:
        inventory[name] = {}

    # update the total for that region for that name
    inventory[name][region] = inventory[name].get(region, 0) + amount

# with the data stored this way, you can easily query
# or calculate any totals you want, e.g.
def total_per_person_per_region(inv, name, region):
    return inv[name][region]

def total_per_person(inv, name):
    return sum(inv[name].values())

def grand_total(inv):
    return sum(total_per_person(inv, name) for name in inv)

rawDescription: Python: Building a dictionary list based on a key and sub keys and totalling up the results based on name, region, region total and grand total


code:
def flatten(iterables):
    return (elem for iterable in iterables for elem in iterable)

rawDescription: Python idiom to chain (flatten) an infinite iterable of finite iterables?


code:
import itertools

sequence = "abccabac"

subsequence = "abc"

for combo in itertools.combinations(enumerate(sequence), len(subsequence)):
    if "".join(pair[1] for pair in combo) == subsequence:
        print([pair[0] for pair in combo])

rawDescription: Python: Sub sequence search

description: Python: Sub sequence search


code:
def is_unique(n):
    if n > 9999999999:
        return False
    st = set()
    while n:
        n, rem = divmod(n, 10)
        if rem in st:
            return False
        st.add(rem)
    return True

rawDescription: Finding prime numbers between any range and how to pick out non repeat numbers in python


code:
from itertools import chain, combinations
def all_subsets(ss):
    return chain(*map(lambda x: combinations(ss, x), range(0, len(ss)+1)))

rawDescription: Django cooking recipes site model structure


code:
def palindrome(word):
    return word == word[::-1]

# split sentence into words and filter out the non palindromes
sentence = [w for w in input("Enter a sentence: ").split() if palindrome(w)]

print(" There are {} palindromes in your sentence\n.".format(len(sentence)))
# print each palindrome from our list
for pal in sentence:
    print("{} is a palindrome".format(pal))

rawDescription: Python Palindrome Help: Count palindromes in a sentence


code:
s = ['manny',
     'mo',
     'jack',
     'roger',
]

rawDescription: Why does Python allow a trailing comma in list?


code:
Problem #3: Check if there's any special characters in the header:
charset = re.compile(r'\w*')
for i in csv[0]:
    if charset.match(i).end() != len(i):
        print("found a header item that contains special characters.")

rawDescription: Python- Check in the CSV file the Header value and data value is equal


rawDescription: Python Networkx detecting loops/circles

description: Python Networkx detecting loops/circles


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

# create a bit more realistic-looking data
# - looks complicated, but just has a constant switch-off and switch-on probabilities
#   per column
# - the result is a 20 x 500 array of booleans
p_switchon = 0.02
p_switchoff = 0.05
data = np.empty((20,500), dtype='bool')
data[:,0] = np.random.random(20) < .2
for c in range(1, 500):
    r = np.random.random(20)
    data[data[:,c-1],c] = (r > p_switchoff)[data[:,c-1]]
    data[-data[:,c-1],c] = (r < p_switchon)[-data[:,c-1]]

# create some labels
labels = [ "label_{0:d}".format(i) for i in range(20) ]

# create a color map with random colors
colmap = matplotlib.colors.ListedColormap(np.random.random((21,3)))
colmap.colors[0] = [0,0,0]

# create some colorful data:
data_color = (1 + np.arange(data.shape[0]))[:, None] * data

# this is the real plotting part
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data_color, aspect='auto', cmap=colmap, interpolation='nearest')
ax.set_yticks(np.arange(len(labels)))
ax.set_yticklabels(labels)

rawDescription: Matplot: How to plot true/false or active/deactive data?


code:
et = pytz.timezone('America/New_York')
ct = pytz.timezone('America/Chicago')
mt = pytz.timezone('America/Denver')
pt = pytz.timezone('America/Los_Angeles')

rawDescription: Python - Convert time to different time zone with am/pm


code: l = dicts[0].keys() + l

rawDescription: list of dicts to memory for csv reader

description: List of dicts to memory for csv reader


code: return sum(column_title_list, [])

rawDescription: Partially flattening a list

description: Partially flattening a list


code:
it = iter(a)
prev = next(it)
result = []

result

rawDescription: Linking two related lists of different lengths in python


code:
def findObjectByName(self, name):
    if self.name == name:
        return self
    else:
        for child in self.children:
            match = child.findObjectByName(name)
            if match:
                return match

rawDescription: Looping through tree hierarchy in python?


code:
from bs4 import BeautifulSoup
api_url = 'http://beta.content.guardianapis.com/football/premierleague'
payload = {
    'api-key':              '',
    'page-size':            10,
    'show-editors-picks':   'true',
    'show-elements':        'image',
    'show-fields':          'all'

    }
response = requests.get(api_url, params=payload).content
soup = BeautifulSoup(response)

text = [''.join(s.findAll(text=True))for s in soup.findAll('p')]

rawDescription: HTML clean up code not quite working

description: HTML clean up code not quite working


code:
eps = 1e-12 * h
f = fmod(xmax - x0, h)
if abs(f) < eps or abs(f - h) < eps:
    pass

rawDescription: Determining if a Variable is Numerically an Integer in Python


code:
AEI
BFJ
CGK
DHL

rawDescription: python combine array item by item

description: Python combine array item by item


code:
import pandas
matrix = pandas.DataFrame(index=['a','b','c'], columns=['one','two'])

rawDescription: Assign values in matrix via indexing

description: Assign values in matrix via indexing


code: main()

rawDescription: python line break by 10 elements

description: Python line break by 10 elements


code:
from PyQt4 import QtCore
id = QtCore.QMetaType.type('MyClass')

rawDescription: Sending custom PyQt signals?

description: Sending custom PyQt signals


code:
list_A = [0,0,0,1.0,2.0,3.0,2.0,1.0,0,0,0]
filtered_lst = [(x,y) for x,y in enumerate(list_A) if y > 0]
max(filtered_lst)
min(filtered_lst)

rawDescription: Python find the indexes of a list given a condition


code: "C:\Python27\python.exe" "%1"

rawDescription: python configuration on windows

description: Python configuration on windows


code: numbers[start:] + numbers[:start]

rawDescription: Iterate through each value of list in order, starting at random value


code:
## Create the "map"
Room("warehouse",{'n':'house','w':'pond'})
Room("pond",{'e':'warehouse'})
Room("house",{'s':'warehouse'})

rawDescription: Relationships between variables

description: Relationships between variables


code: tree_path__contains = ('%%0%ii' % COMMENT_PATH_DIGITS % int(baseT.comment_ptr_id))

rawDescription: How to filter with "contains"?

description: Filter with "contains"


code:
def foo(a):
    for b in a:
        yield b

rawDescription: Returning every element from a list (Python)


code: c2_low = float(self.c2_low.get())

rawDescription: Using Tkinter user input for variables in functions


code:
import sqlalchemy as sa

eng = sa.create_engine("mysql+pymysql://chiptest:fryisthedevil@database/bench_drylake")
eng.execute("create table if not exists foo (x double not null)")
eng.execute("insert into foo (x) values (0.1)")

md = sa.MetaData(bind=eng)
md.reflect()
foo = md.tables["foo"]

# this needs to happen before any queries
for table in md.tables.values():
    for column in table.columns.values():
        if isinstance(column.type, sa.Numeric):
            column.type.asdecimal = False

res = eng.execute(foo.select())
row = res.fetchone()
print(type(row.x))
print(repr(foo.c.x.type))

rawDescription: How to make sqlalchemy return float instead of Decimal when reflecting tables?

description: Make sqlalchemy return float instead of Decimal when reflecting tables


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


code:
numerical=['D','E']
categorical=list(set(list(df_t.columns.values))-set(numerical))

mapper = DataFrameMapper([
(categorical, None),
(numerical,StandardScaler())])

explanatory_variables_columns=categorical+numerical
X = np.array(mapper.fit_transform(df_t),dtype=float)

rawDescription: Is there a way to track which DataFrame Column corresponds to which Array Column(s) after LabelBinarizer Transform in sklearn?


code:
import platform
platform.architecture()

rawDescription: How to find system type using Python?

description: Find system type using Python


code:
Arguments = {
    'pos_hint': {'center_x': 0.5, 'center_y': 0.5},
    'size_hint': (1, 1),
    'duration': 2
}

function1(**Arguments)
function2(**Arguments)
function3(**Arguments)

rawDescription: How do I store identical arguments to be used by multiple functions

description: Store identical arguments to be used by multiple functions


code: re.sub(r'(\\u[0-9A-Fa-f]+)', lambda matchobj: chr(int(matchobj.group(0)[2:], 16)), t)

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


code:
from string import lowercase
dict((j,i) for i,j in enumerate(lowercase, 1))

rawDescription: Efficient way to write this expression: English alphabets dictionary


code:
from urllib import FancyURLopener
class MyOpener(FancyURLopener):
    version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'

myopener = MyOpener()
myopener.retrieve('http://upload.wikimedia.org/wikipedia/en/4/44/Zindagi1976.jpg', 'Zindagi1976.jpg')

rawDescription: How to use urllib to download image from web

description: Use urllib to download image from web


code:
sql='SELECT regexp_replace(location, %s, %s, %s)  from foo'
cursor.execute(sql,[r'\(|\)','','g'])

rawDescription: Literal parentheses in postgres query, pgadmin vs. psycopg2


code: ['Linux', 'ESX', 'Windows']

rawDescription: How to parse same argument twice or more than once to python script?

description: Parse same argument twice or more than once to python script


code:
try:
    {k: v for k, v in ENROLLMENT_STATUS}[self.enrollment_status]
except ValueError:
    raise # or whatever

rawDescription: Translating choices in Django without using loops?


code:
def LEN(a,b):
        'str,int==>int'
        'returns the number of words that have a len of b'
        c= a.split()
        res = 0
        for i in c:
            if len(i)==b:
                res= res + 1
        return(res) # return at the end

rawDescription: how do i find the number of times a word is of len n in python?

description: Find the number of times a word is of len n in python


code:
store.select('df', where=c)
c
c.values

rawDescription: Selecting rows from an HDFStore by index using where


rawDescription: Extract hexadecimal number from string

description: Extract hexadecimal number from string


code:
import os

from django.conf import settings

rawDescription: Django app initialization process

description: Django app initialization process


code:
Dict = {'1': 'one', '2': 'three'}

Tuple = ({'1': 'one', '5': 'five'}, {'4': 'four', '2': 'two'})
for d in Tuple:
    if "2" in d:
        Dict["2"] = d["2"]
        break # get first match

rawDescription: Iteration Through tuple of dictionaries in Python


code: foo.b = 5

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


code:
class Occurence(models.Model):
    datetime = models.DateTimeField()

    class Meta:
        ordering = ('datetime',)

class Series(models.Model):
    first_occurence = models.DateTimeField(null=True, blank=True)
    last_occurence = models.DateTimeField(null=True, blank=True)
    occurences = models.ManyToManyField(Occurence, null=True, blank=True)

my_series = Series.objects.get(...)
first = my_series.objects.earliest()
latest = my_series.objects.latest()

rawDescription: Override save method force me to save twice in the admin thing


code:
from scipy import signal
res = signal.fftconvolve(c_contig_store_array, c_contig_weigh_array[::-1], mode="valid")

rawDescription: Why assign values to C-contiguous array is slow in my case using Cython


code:
import xml.etree.ElementTree as ET
tree = ET.parse("test.xml")
a=tree.find('parent')
for b in a.findall('child'):
    if b.text.strip() == 'Jay/Doctor':
        break
else:
    ET.SubElement(a,"child").text="Jay/Doctor"
tree.write("test.xml")

rawDescription: Modify a XML using ElementTree

description: Modify a XML using ElementTree


rawDescription: How to generate documentation from python code looking like "python shell output"

description: Generate documentation from python code looking like "python shell output"


code: eps = np.finfo(np.float32).eps

rawDescription: Matlab range in Python

description: Matlab range in Python


rawDescription: How can I keep a vector in the same order after removing an element in Python

description: Keep a vector in the same order after removing an element in Python


code:
df = df.stack().reset_index()
#     level_0 level_1        0
# 0         0      ×2  (Blank)
# 1         1      ×4      LSU
# 2         1      ×6      NRT
# 3         1      ×8        O
# 4         1      ×9       AI
# 5         1     ×12        E
# 6         2      ×3        G
# 7         2      ×4        D
# 8         3      ×2     BCMP
# 9         4      ×2    FHVWY
# 10        5      ×1        K
# 11        8      ×1       JX
# 12       10      ×1       QZ

rawDescription: Pandas: transform a DataFrame by splitting each value into multiple values


code:
running = True
stage = 1

while running:

    screen.fill(black)
    screen.blit(bg, (0, 0))
    screen.blit(label, (65, 420))

    if stage == 1:
        screen.blit(bg2, (37, 30))
    else:
        screen.blit(bg3, (37, 30))

    pygame.display.update()

    for event in pygame.event.get():

        if event.type == QUIT or \
                (event.type == pygame.KEYDOWN and event.key == K_ESCAPE):
            pygame.quit()
            sys.exit()

        if event.type == pygame.KEYDOWN and event.key == K_SPACE:
            stage += 1

rawDescription: pygame - how to change an image/blit over previous one?

description: Pygame - how to change an image/blit over previous one


code:
{u'Alphabet overtakes Apple in market value - for now': 'https://in.finance.yahoo.com/news/alphabet-overtakes-apple-market-value-140918508.html',
 u'Alphabet passes Apple to become most valuable traded U.S. company': 'https://in.finance.yahoo.com/news/alphabet-passes-apple-become-most-012844730.html',
 u'Apple bets new 4-inch iPhone to draw big-screen converts in China, India': 'https://in.finance.yahoo.com/news/apple-bets-4-inch-iphone-112024627.html',
 u'Apple iPhone sales weaker than expected': 'https://in.finance.yahoo.com/news/apple-iphone-sales-weaker-expected-221908381.html',
 u'Apple likely to invoke free-speech rights in encryption fight': 'https://in.finance.yahoo.com/news/apple-likely-invoke-free-speech-030713050.html',
 u'Apple sees first sales dip in more than a decade as super-growth era falters': 'https://in.finance.yahoo.com/news/apple-sells-fewer-iphones-expected-213516373.html',
 u'Apple shares fall most in two years in wake of earnings report': 'https://in.finance.yahoo.com/news/apple-shares-seen-staying-muted-132628994.html',
 u"Apple's new iPhone faces challenge measuring up in China, India": 'https://in.finance.yahoo.com/news/apples-iphone-faces-challenge-measuring-002248597.html',
 u"Bad run continues for 'Freedom 251', website down again on second day": 'https://in.finance.yahoo.com/news/bad-run-continues-freedom-251-092804374.html',
 u"EXCLUSIVE - Common mobile software could have opened San Bernardino shooter's iPhone": 'https://in.finance.yahoo.com/news/common-mobile-software-could-opened-030713243.html',
 u'Foxconn says in talks with Sharp over deal hitch; hopes for agreement': 'https://in.finance.yahoo.com/news/sharp-shares-plunge-foxconn-puts-031032213.html',
 u'Older Headlines': '/q/h?s=AAPL&t=2016-01-27T03:49:08+05:30',
 u'Samsung Elec warns of difficult 2016 as smartphone troubles spread': 'https://in.finance.yahoo.com/news/samsung-electronics-warns-difficult-2016-003517395.html',
 u'Samsung wins appeal in patent dispute with Apple': 'https://in.finance.yahoo.com/news/samsung-wins-appeal-patent-dispute-022120916.html',
 u"Signs of life for Apple's stock as Wall St eyes new iPhone": 'https://in.finance.yahoo.com/news/signs-life-apples-stock-wall-165820189.html',
 u'Solid support for Apple in iPhone encryption fight - Reuters/Ipsos': 'https://in.finance.yahoo.com/news/solid-support-apple-iphone-encryption-121255578.html',
 u'U.S. appeals court upholds Apple e-book settlement': 'https://in.finance.yahoo.com/news/u-appeals-court-upholds-apple-164738354.html',
 u'U.S., Apple ratchet up rhetoric in fight over encryption': 'https://in.finance.yahoo.com/news/u-apple-ratchet-rhetoric-fight-030713673.html',
 u'With China weakening, Apple turns to India': 'https://in.finance.yahoo.com/news/china-weakening-apple-turns-india-032020575.html'}

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


code:
# -*- coding: utf-8 -*-
# myapp/management/commands/scrapy.py

from __future__ import absolute_import
from django.core.management.base import BaseCommand

class Command(BaseCommand):

    def run_from_argv(self, argv):
        self._argv = argv
        self.execute()

    def handle(self, *args, **options):
        from scrapy.cmdline import execute
        execute(self._argv[1:])

rawDescription: Django custom management command running Scrapy: How to include Scrapy's options?


code:
result = {}
for obj in json_obj:
    if obj['type'] == 'email_response':
        result[obj['case_id']] = result.get(obj['case_id'], 0) + 1

result

rawDescription: How do you find the number of occurrence within a list of dictionaries

description: Find the number of occurrence within a list of dictionaries


code:
urlpatterns = [
    url(r'^$', hello_world),
]

rawDescription: Can you have a view function in your URLS.py file

description: Have a view function in your URLS.py file


code:
from itertools import chain

class AutoDecorate(type):
    def __new__(metacls, name, bases, dct):
        if "_decorator" not in dct:
            dct["_decorator"] = lambda x: x # NOP decorator
        all_bases = list(chain(base.__mro__ for base in bases))
        for base in all_bases:
            if not "_auto_decorate" in base.__dict__:
                continue
            for method_name in base.auto_decorate:
                if method_name not in dct:
                    dct[method_name] = dct["_decorator"](getattr(base, method_name))
        return super().__new__(name, bases, dct)

class cls_with_basic_method(metaclass=AutoDecorate):
    _auto_decorate = set(("basic_method", ...))

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

class cls_with_basic_method_and_decoratorA(class_with_basic_method):
    _decorator = decoratorA

class cls_with_basic_method_and_decoratorB(class_with_basic_method):
    _decorator = decoratorB

rawDescription: Dynamically assigning sub class dependent decorators


code:
def label_race (row):
   if row['eri_hispanic'] == 1 :
      return 'Hispanic'
   if row['eri_afr_amer'] + row['eri_asian'] + row['eri_hawaiian'] + row['eri_nat_amer'] + row['eri_white'] > 1 :
      return 'Two Or More'
   if row['eri_nat_amer'] == 1 :
      return 'A/I AK Native'
   if row['eri_asian'] == 1:
      return 'Asian'
   if row['eri_afr_amer']  == 1:
      return 'Black/AA'
   if row['eri_hawaiian'] == 1:
      return 'Haw/Pac Isl.'
   if row['eri_white'] == 1:
      return 'White'
   return 'Other'

rawDescription: pandas create new column based on values from other columns

description: Pandas create new column based on values from other columns


code:
s = "I've used google https://google.com and found a regular expression pattern to find links here http://stackoverflow.com/questions/6883049/regex-to-find-urls-in-string-in-python"
pattern.sub('', s)

rawDescription: How to remove words containing a substring in a python string?

description: Remove words containing a substring in a python string


code:
def foo(bar, baz=default, **quux):
    pass

rawDescription: Passing as kwargs, reading as args - a special or temporary feature?


code:
with open("file.txt", "w") as f:
    f.write(soup.prettify())

rawDescription: How can I Extract Specific xml tags from a local xml file using python?


code:
reader = csv.reader(open('dict.csv', 'rb'))
mydict = dict(reader)

rawDescription: Python: Writing a dictionary to a csv file with one line for every 'key: value'


code:
from nose.tools import with_setup

def my_setup():
   ...

@with_setup(my_setup)
def test_one():
    ...

@with_setup(my_setup)
def test_two():
    ...

rawDescription: How can I define one setup function for all nosetests tests?

description: Define one setup function for all nosetests tests


code:
while power < 6:
    if root ** power == num:
        break

rawDescription: Nested while loops in Python 2

description: Nested while loops in Python 2


code:
for key,value in defaults.iteritems():
    assigned.setdefault(key,value)

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


code:
roots = list(set([a[0] for a in tuple(os.walk(r"C:\example"))]))
roots = [a[0] for a in os.walk(r"C:\example")]

rawDescription: List all branches of subfolders in directory with python


code:
class Book(db.Model):
    #isbn is key, so it shouldn't be a property
    category = db.StringProperty()
    author = db.StringProperty()
    title = db.StringProperty()

new_book = Book(category="fantasy,comedy", title="The Light Fantastic", author="TerryPratchett", key_name=isbn_number)

rawDescription: How to get a list of key names in Python/Google app engine?

description: Get a list of key names in Python/Google app engine


code:
del a_module.func1_implementation
del a_module.func2_implementation

rawDescription: Binding functions (`exec`uted at runtime) to a module (created at runtime)


code: len(list(filter(lambda x: x['age'] == 10, a)))

rawDescription: how to find the number of dictionaries with a particular value in an array of dictionaries?

description: Find the number of dictionaries with a particular value in an array of dictionaries


code: apply(foo, args, kwargs)

rawDescription: Lisp's apply and funcall vs Python's apply


rawDescription: how to use groupby to avoid loop in python

description: Use groupby to avoid loop in python


code:
boost_turns = 0
while True:
    attack = raw_input('What attack shall you choose?')
    if attack == 'boost accuracy':
        boost_turns = 3
    if boost_turns:
        accuracy = 100
        boost_turns -= 1
    else:
        accuracy = 0
    # attack

rawDescription: Python: change variable for specific number of iterations in a loop


code:
path = 'csvs/'
for infile in glob.glob( os.path.join(path, '*csv') ):
    output = infile + '.out'
    with open(infile, 'r') as source:
        readr = csv.reader(source)
        with open(output,"w") as result:
            writr = csv.writer(result)
            for r in readr:
                writr.writerow((r[4], r[2]))

rawDescription: Loop through multiple csv files, copying only certain columns to new files


code:
from tornado.options import options, define

define("host", default="localhost", help="app host", type=str)
define("port", default=3000, help="app port", type=int)

class WebsocketHandler(tornado.web.RequestHandler):

    def get(self):
        self.render(
            "index_websocket.html",
            server_url=options.host,
            server_port=options.port
        )

options.parse_command_line()  # don't forget to parse command line
app = tornado.web.Application(...)
app.listen(options.port)
tornado.ioloop.IOLoop.instance().start()

rawDescription: Get server url and port from Tornado Web Framework


rawDescription: Extremely slow sum row operation in Sparse LIL matrix in Python


code:
import itertools

def find_target(lst, target):
    target = tuple(target)
    i, maxidx, maxcnt = 0, -1, 0
    for key, grp in itertools.groupby(lst, key=tuple):
        cnt = sum(1 for _ in grp)
        if key == target and cnt > maxcnt:
            maxidx, maxcnt = i, cnt
        i += cnt
    return maxidx

rawDescription: Python: Index in a list of lists

description: Python: Index in a list of lists


rawDescription: Convert float64 numpy array to floats not in scientific notation


code:
import os

def build_G(csv_file):

    #init graph dict
    g={}

    #here we open csv file
    with open(csv_file,'r') as f:
        cont=f.read()

    #here we get field content
    for line in cont.split('\n'):
        if line != '':

            fields=line.split(';')

            #build origin node
            if g.has_key(fields[0])==False:
                g[fields[0]]={}

            #build destination node
            if g.has_key(fields[1])==False:
                g[fields[1]]={}

            #build edge origin>destination
            if g[fields[0]].has_key(fields[1])==False:
                g[fields[0]][fields[1]]=float(fields[2])

    return g

def main():

    #filename
    csv_file="mynode.csv"

    #build graph
    G=build_G(csv_file)

    #G is now a python dict
    #G={'27': {}, '75': {'14': 2.85, '23': 0.9}, '89': {}, '14': {'75': 2.9}, '23': {'27': 4.9, '89': 3.49, '14': 1.29}}

    #write to file
    f = open('dotgraph.txt','w')
    f.writelines('digraph G {\nnode [width=.3,height=.3,shape=octagon,style=filled,color=skyblue];\noverlap="false";\nrankdir="LR";\n')
    f.writelines

    for i in G:
        for j in G[i]:
            #get weight
            weight = G[i][j]
            s= '      '+ i
            s +=  ' -> ' +  j + ' [dir=none,label="' + str(G[i][j]) + '",penwidth='+str(weight)+',color=black]'
            if s!='      '+ i:
                s+=';\n'
                f.writelines(s)

    f.writelines('}')
    f.close()

    #generate graph image from graph text file
    os.system("dot -Tjpg -omyImage.jpg dotgraph.txt")

main()

rawDescription: Creating Network Graphs

description: Creating Network Graphs


code:
def word_generator():
    word = ""
    with open("text.txt", "r") as file:
        file.read(1)
        for line in file:
            for char in line:
                if char != " ":
                    word += char
                if char == " ":
                    yield word
                    word = ""

rawDescription: Python: How to retrieve second word from the text


code:
xl = Dispatch('Excel.Application')
wb = xl.Workbooks.Open('New Workbook.xlsx')
# do some stuff
wb.Close(True) # save the workbook

rawDescription: python win32 COM closing excel workbook

description: Python win32 COM closing excel workbook


code:
from scipy.misc import comb

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

    # Code 3
    c = comb(hi+lo, lo, exact=True)
    # print c

rawDescription: Placing of modulo operation in code

description: Placing of modulo operation in code


code: regex = re.compile("guys(?:.|\n)*$")

rawDescription: Fetching a part of a string using regex starting from a given word untill the end of the string(one that includes newlines)


code:
# Change these based on your definition of a 'high' value and a 'low' value (or the min/max of the data)
minflux = data[:][5].min()
maxflux = data[:][5].max()

for i in range(len(data)):
    ra,dec,maj,minor,ang,flux =data[i][0],data[i][1],data[i][2],data[i][3],data[i][4],data[i][5]

    # Normalise the flux value to the range 0-1
    normflux = (flux - minflux) / (maxflux - minflux)
    # RGB tuple. This will be yellow for min value and blue for max value
    fluxcolor = (1.-normflux, 1.-normflux, normflux)

    ellipse = Ellipse(xy=(ra, dec), width=maj, height=minor, angle=ang, edgecolor=fluxcolor, lw=3, fc='None')
    ax.add_patch(ellipse)

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


rawDescription: Pandas temporal cumulative sum by group

description: Pandas temporal cumulative sum by group


code: 'asdf hjkl'.replace(' ', '\s')[4]

rawDescription: String replace with backslashes in Python


rawDescription: need to create a list which appends previous and current stddev calculation to it

description: Need to create a list which appends previous and current stddev calculation to it


code: ''.join(random.sample(E*N, N))

rawDescription: Most Pythonic Way to Generate Random Strings of Fixed Length From Given Characters


code:
all_paths = []
find(element_to_search,j,'',all_paths)

rawDescription: JSON get key path in nested dictionary

description: JSON get key path in nested dictionary


code: import this

rawDescription: Python: load variables in a dict into namespace


code: from django.conf import settings

rawDescription: Django: get the path to the current django app


code:
import pandas as pd
import matplotlib.pyplot as plt

# Plot the Raw Data
plt.plot(rawdata[0:500], 'r-')
plt.ylabel('Lightpower (V)')

smooth_data = pd.rolling_mean(ts,5).plot(style='k')
plt.show()

rawDescription: How to average a signal to remove noise with Python

description: Average a signal to remove noise with Python


code: b = sorted(a, key=lambda x: int(x.split("NR;")[-1].split(";")[0]))

rawDescription: Python sort list by regular expression

description: Python sort list by regular expression


code: thread_handler = CallThreads(someFunction, phrase, num)

rawDescription: Sending arguments to Python threads blocks other threads


code:
from pyspark.sql.functions import udf, col
from pyspark.sql.types import BooleanType

# Of you can replace `in` with a regular expression
contains = udf(lambda s, q: q in s, BooleanType())

like_with_python_udf = (documents_df.join(keywords_df)
    .where(contains(col("document_text"), col("keyword")))
    .select(col("document_id"), col("keyword")))
like_with_python_udf.show()

## +-----------+-------+
## |document_id|keyword|
## +-----------+-------+
## |          1|  spark|
## |          2| erlang|
## |          3|haskell|
## +-----------+-------+

rawDescription: How can we JOIN two Spark SQL dataframes using a SQL-esque "LIKE" criterion?


code:
import numpy as np
from scipy.signal.sigtools import _correlateND

def calcM(filtertaps, n, m, keep_indices, V):
    k = keep_indices.shape[1]
    M = np.zeros((n, m), dtype=np.float32)
    ej = np.zeros((m,), dtype=np.float32)

    slice_obj = [slice(None, None, -1)] * len(filtertaps.shape)
    sliced_filtertaps_view = filtertaps[slice_obj]

    ps = ej.shape[0] + sliced_filtertaps_view.shape[0] - 1
    in1zpadded = np.zeros(ps, ej.dtype)
    out = np.empty(ps, ej.dtype)

    for rowidx in range(n):
        for colidx in range(m):
            in1zpadded[colidx] = 1

            convolution = _correlateND(in1zpadded, sliced_filtertaps_view, out, 2)

            for kidx in range(k):
                M[rowidx, colidx] += convolution[keep_indices[rowidx, kidx]] * V[rowidx, kidx]

            in1zpadded[colidx] = 0

    return M

rawDescription: Unexpectedly slow cython convolution code


code: buf.raw + sdata.tostring()

rawDescription: python concatenate ctype struct and array

description: Python concatenate ctype struct and array


code:
numstring = "1,2,3,4,5,1,6,7,1,8,9,10,11,12,1,1,2"
numlist = numstring.split(',')
numcount = dict((num, numlist.count(num)) for num in set(numlist))

rawDescription: python - Count number of occurences of each number

description: Python - Count number of occurences of each number


code:
d = dict.fromkeys('abcdef', [])
[id(x) for x in d.values()]

rawDescription: How to update values for specific keys in dict in Python

description: Update values for specific keys in dict in Python


rawDescription: Sort dict list with itemgetter

description: Sort dict list with itemgetter


code:
parser = etree.HTMLParser(encoding="utf-8")
page = html.parse(url,parser)

rawDescription: Output doesn't display all utf-8 correctly


code: os.path.join(dircheck, "")

rawDescription: Checking if path ends in separation

description: Checking if path ends in separation


code:
from collections import OrderedDict
my_dict=OrderedDict((i,j) for i,*j in [l[i:i+4] for i in range(0,len(l),4)])
my_dict

rawDescription: Python 3.4: List to Dictionary

description: Python 3.4: List to Dictionary


code:
def home(request):
    dog_list = dog.objects.all()
    template = 'home.html'
    return render(request, template, {'dogs' : dog_list})

def dog_view(request, slug):
    dog_view = get_object_or_404(dog, slug=slug)
    return render(request, 'profile.html', {'dog_view' : dog_view})

rawDescription: Django – create pages along with the objects using the same template


code:
class ExampleForm(forms.ModelForm):
    ...
    def __init__(self, *args, **kwargs):
        some_variable = kwargs.pop('some_variable')
        super(ExampleForm, self).__init__(*args, **kwargs)
        self.fields['date_field'].widget = SelectDateWidget(
                                                 years=year_range(some_variable))

rawDescription: Pass values into Django form before form is made


code:
os.system("pyrcc4.exe -o ui/images_rc.py ui/images/images.qrc")
uic.compileUiDir(appDir + '/ui', True)

rawDescription: Using QTDesigner with PyQT and Python 2.6


code: list1, list2 = list2, [0]*len(list2)

rawDescription: Swap two lists in python

description: Swap two lists in python


code:
import mymodule
mymodule.do_the_thing()

rawDescription: Exit to command line in Python

description: Exit to command line in Python


code:
from curses import *
def main(stdscr):
    start_color()
    stdscr.clear()  # clear above line.
    stdscr.addstr(0, 0, "Fig: SQUARE", A_UNDERLINE|A_BOLD)
    init_pair(1, COLOR_RED, COLOR_WHITE)
    init_pair(2, COLOR_BLUE, COLOR_WHITE)
    pair = 1
    for x in range(3, 3 + 5): # horizontal c
      for y in range(4, 4 + 5): # verticale r
        pair = 1 if pair == 2 else 2
        stdscr.addstr(y, x, '#', color_pair(pair))
    stdscr.addstr(11, 0, 'Press Key to exit: ')
    stdscr.refresh()
    stdscr.getkey()
wrapper(main)

rawDescription: What's the short way to add same symbol at the specified place in ncurses?


rawDescription: Python Argparser show parser from instancemethod


code:
blacklisted = ('.bar.com', '@bar.com', '.baz.com', '@baz.com')
email = 'x@foobar.com'
email.endswith(blacklisted)

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

description: Filter out emails and domains in python


code: DF = pd.read_csv("Test.csv").query("A == 'Y'")

rawDescription: Python Pandas memory - subsetting and releasing main data frame


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

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


code:
def nonblank_lines(f):
    for l in f:
        line = l.rstrip()
        if line:
            yield line

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


code:
class funcdec(object):
    pass
funcdec = globaldec(funcdec)

rawDescription: Python "Multi-Level Decorator" - how does this work?


rawDescription: iterating through folder for files and add up values within the columned file in Python

description: Iterating through folder for files and add up values within the columned file in Python


code:
example = requests.get("https://periscope.tv/couchmode", allow_redirects=True)
example.status_code
example.history
example.history[0].url
example.url

rawDescription: Detect URLs changes in python

description: Detect URLs changes in python


code: np.array([[array1]], dtype=object)

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

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


code:
isinstance([1, 2, 3], collections.Iterable)
isinstance(np.arange(10), collections.Iterable)
isinstance(1, collections.Iterable)

rawDescription: What is the most pythonic way to use len on a scalar?


code:
from ctypes import *

class object_t(Structure):
    _fields_ = [
        ('a', c_uint8),
        ('b', c_uint8),
        ('c', c_uint32),
        ('d', POINTER(c_uint8)),
    ]

rawDescription: How to access data from pointer in struct from Python with ctypes?

description: Access data from pointer in struct from Python with ctypes


code:
from itertools import combinations
x = [0,1,2,3,4,5]
list(combinations(x,2))

rawDescription: How to compute skipgrams in python?

description: Compute skipgrams in python


code:
# in the "only once" part:
spread = ql.SimpleQuote()
discount_curve = ql.ZeroSpreadedTermStructure(jibarTermStructure,ql.QuoteHandle(spread))
discountStructure.linkTo(discount_curve)

# pricing:
def price_floater(myqlvalDate,jibar_curve,credit_spread):
    ql.Settings.instance().evaluationDate = myqlvalDate
    jibarTermStructure.linkTo(jibar_curve)
    spread.setValue(credit_spread)
    return [bond.NPV() ,bond.cleanPrice()]

rawDescription: Daily Pricing of a Bond with QuantLib using Python


code:
cmds.displayColor("gridAxis" , q=True)
cmds.displayColor("gridHighlight" , q=True)
cmds.displayColor("grid" , q=True)

rawDescription: Maya - How to access grid colors through script commands?


code: [operation(fruit_name) for fruit_name in fruit_stand]

rawDescription: Breaking down instances of classes into lists, or: a better way to sum class variables?


code:
from collections import deque

d = deque(chars)
d

d.rotate(1)
d
d.rotate(-1)
d
d.rotate(3)
''.join(list(d))

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


rawDescription: Dice generator, Picking number of sides in PYTHON 3.3.4


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

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


rawDescription: Matching sequentially repeated brackets with Python Regex


code:
class OnlyAssings(ast.NodeTransformer):

    def generic_visit( self, node ):
        return None  #throw other things away

    def visit_Module( self, node ):
        #We need to visit Module and pass it
        return ast.NodeTransformer.generic_visit( self, node )

    def visit_Assign(self, node):
        if node.targets[0].id == 'animals': # this you may want to change
            return node #pass it
        return None # throw away

config= OnlyAssings().visit(config)

rawDescription: Python text processing and parsing

description: Python text processing and parsing


code:
self.seq = '%010d' % (int(self.seq) + 1)
return self.seq

rawDescription: How to increment a numeric string '0000000001' in python?

description: Increment a numeric string '0000000001' in python


rawDescription: How to make Text scroll down automatically whenever text overcomes the visual area?

description: Make Text scroll down automatically whenever text overcomes the visual area


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

def haversine(lat1, long1, lat2, long2, EARTH_RADIUS_KM=6372.8):

    # get distance between the points
    phi_Lat = radians(lat2 - lat1)
    phi_Long = radians(long2 - long1)

    lat1 = radians(lat1)
    lat2 = radians(lat2)

    a = sin(phi_Lat/2)**2 + \
        cos(lat1) * cos(lat2) * \
        sin(phi_Long/2)**2

    c = 2 * asin(sqrt(a))
    return EARTH_RADIUS_KM * c

rawDescription: how to find user location within 500 meters from given lat and long in python

description: Find user location within 500 meters from given lat and long in python


code:
from nltk.data import load

# Standard treebank POS tagger
_POS_TAGGER = 'taggers/maxent_treebank_pos_tagger/english.pickle'
def pos_tag(tokens):
    """
    Use NLTK's currently recommended part of speech tagger to
    tag the given list of tokens.

        >>> from nltk.tag import pos_tag # doctest: +SKIP
        >>> from nltk.tokenize import word_tokenize # doctest: +SKIP
        >>> pos_tag(word_tokenize("John's big idea isn't all that bad.")) # doctest: +SKIP
        [('John', 'NNP'), ("'s", 'POS'), ('big', 'JJ'), ('idea', 'NN'), ('is',
        'VBZ'), ("n't", 'RB'), ('all', 'DT'), ('that', 'DT'), ('bad', 'JJ'),
        ('.', '.')]

    :param tokens: Sequence of tokens to be tagged
    :type tokens: list(str)
    :return: The tagged tokens
    :rtype: list(tuple(str, str))
    """
    tagger = load(_POS_TAGGER)
    return tagger.tag(tokens)

rawDescription: Unknown symbol in nltk pos tagging for Arabic


code:
Person = collections.namedtuple('Person', ['Name', 'Age'])
dictionary = {'Thomas': Person('Thomas', 30), 'Steven': Person('Steven', 50), 'Pauly D': Person('Pauly D', 29)}

rawDescription: Find a strings location in a list - Python


code: [{'id': k, 's': max(v)} for k, v in id_to_scores.iteritems()]

rawDescription: python: remove duplicate elements based on score

description: Python: remove duplicate elements based on score


code:
from collections import defaultdict
from operator import itemgetter

scores = defaultdict(int)
with open('my_file.txt') as fobj:
    for line in fobj:
        name, score = line.split()
        scores[name] += int(score)

rawDescription: Efficiently processing data in text file


code:
list1 = ['A', 'B']
list2 = ['Apple', 'Banana', 'Balloon', 'Boxer', 'Crayons', 'Elephant']
list2_map = {}
for word in list2:
    list2_map.setdefault(word[0], []).append(word)
['{}:{}'.format(l, ','.join(list2_map.get(l, []))) for l in list1]

rawDescription: Only using items from one list once in nested list comprehension


rawDescription: matplotlib: setting xticklabels returned some "help" output

description: Matplotlib: setting xticklabels returned some "help" output


code:
import collections
names = ["gymnastics_school", "participant_name", "all_around_points_earned"]
Data = collections.namedtuple("Data", names)

data = []

with open('state_meet.txt','r') as f:
    for line in f:
        line = line.strip()
        items = line.split(',')
        items[2] = float(items[2])
        data.append(Data(*items))

# max value
max_one = max(data, key=lambda d:d.all_around_points_earned)
print(max_one.all_around_points_earned)

# min value
min_one = min(data, key=lambda d:d.all_around_points_earned)
print(min_one.all_around_points_earned)

# mean value
total = sum(d.all_around_points_earned for d in data)
mean_val = total/len(data)
print(mean_val)

# median value
sorted_data = sorted(data, key=lambda d:d.all_around_points_earned)
if len(data)%2==0:
    a = sorted_data[len(data)//2].all_around_points_earned
    b = sorted_data[len(data)//2-1].all_around_points_earned
    median_val = (a+b)/2
else:
    median_val = sorted_data[(len(data)-1)//2].all_around_points_earned
print(median_val)

rawDescription: opening txt file and creating list and getting basic stats

description: Opening txt file and creating list and getting basic stats


code:
import bokeh.models as bkm
import bokeh.plotting as bkp

source = bkm.ColumnDataSource(data=your_frame)
p = bkp.figure(tools='add the tools you want here, but no hover!')
g1 = bkm.Cross(x='col1', y='col2')
g1_r = p.add_glyph(source_or_glyph=source, glyph=g1)
g1_hover = bkm.HoverTool(renderers=[g1_r],
                         tooltips=[('x', '@col1'), ('y', '@col2')])
p.add_tools(g1_hover)

# now repeat the above for the next sets of glyphs you want to add.
# for those you don't want tooltips to show when hovering over, just don't
# add hover tool for them!

rawDescription: Bokeh Plotting: Enable tooltips for only some glyphs


code: table = (experiment[:,0]**2 + experiment[:,1]**2 <= 1).astype(int)

rawDescription: python(numpy) -- create array and how to implement an expression

description: Python(numpy) -- create array and how to implement an expression


code:
def would_be(tagged):
    return any(['would', 'be', 'JJ'] == [tagged[i][0], tagged[i+1][0], tagged[i+2][1]] for i in xrange(len(tagged) - 2))

rawDescription: detecting POS tag pattern along with specified words

description: Detecting POS tag pattern along with specified words


code:
def calc(x):
    newname = name.replace("x", str(x))
    calc.__name__ = newname
    return eval(name)

calc.__name__ = name
return calc

rawDescription: how to set .__name__ in python?

description: Set .__name__ in python


rawDescription: Is copy.copy different from assignment in python


code:
counter = 0
for question, options, correct in question_list:
    print(question)
    print(options)
    if counter == 5 and age <= 5:
     #if you reach the 5th question then you want to break the for loop.
        break

    #increment the variable to keep track of position
    counter +=1

rawDescription: wanting to add an age gate to my quiz

description: Wanting to add an age gate to my quiz


rawDescription: Alternative to contextlib.nested with variable number of context managers


rawDescription: Sorting a list of tuples such that grouping by key is not desired


rawDescription: Can I have 3 elements in a dictionary

description: Have 3 elements in a dictionary


rawDescription: How to convert 32-bit binary to float

description: Convert 32-bit binary to float


code:
new_result = []
for x in result:
    for y in pool:
        new_result.append(x+[y])
result = new_result

rawDescription: How do I convert Python's itertools.product library from a list comprehension to normal for loops?

description: Convert Python's itertools.product library from a list comprehension to normal for loops


code:
def dostuff(s):
    s = s.strip('0')
    if len(s) > 0 and s[-1] == '.':
        s = s[:-1]
    return s

rawDescription: Removing zeros from a numeric string in Python


code:
class Individualist(object):
  def __init__(self):
    self.__class__ = type('GottaBeMe', (self.__class__, object), {})

a = Individualist()
b = Individualist()
a.__class__.__int__ = lambda self: 23
b.__class__.__int__ = lambda self: 42
int(a)
int(b)

rawDescription: Dynamically assign special methods to objects but not classes in Python


code:
class MyPdf(object):
    def __init__(self, custom_data):
        self.custom_data = custom_data
        self.doc = ... # your doc

    def _header_footer(self, canvas, doc):
        # you can access self.custom_data here
        ...

    def build(self):
        ...
        self.doc.build(elements, onFirstPage=self._header_footer)

# Usage
my_pdf = MyPdf(custom_data)
my_pdf.build()

rawDescription: Parameter to reportlab header using Django


code:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/db_name'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username

admin = User('admin', 'admin@example.com')

db.create_all() # In case user table doesn't exists already. Else remove it.

db.session.add(admin)

db.session.commit() # This is needed to write the changes to database

User.query.all()

User.query.filter_by(username='admin').first()

rawDescription: Switching from SQLite to MySQL with Flask SQLAlchemy


code:
doc = """
Usage:
   test.py balance= <b1> <b2>
   test.py

Options:
   --cite -c           Cite option
   --arbitrary -a      Arbitrary option
"""

rawDescription: Multiple command line arguments

description: Multiple command line arguments


rawDescription: Extract Information From a File

description: Extract Information From a File


code:
zero_data = data.fillna(0)
distance = lambda column1, column2: (column1 - column2).abs().sum() / len(column1)
result = zero_data.apply(lambda col1: zero_data.apply(lambda col2: distance(col1, col2)))
result.head()

rawDescription: Distance matrix for rows in pandas dataframe


code:
def getAFval(self):
    self._AF.getval()

rawDescription: How to set functions for a property()?

description: Set functions for a property()


code:
pdf = self.switch_backends(FigureCanvasPdf)
return pdf.print_pdf(*args, **kwargs)

rawDescription: What limits does the matplotlib backend place on rendering formats?


code:
iso_8859_2 = {chr(i).decode('iso-8859-2') for i in xrange(0xff)}
iso_8859_5 = {chr(i).decode('iso-8859-5') for i in xrange(0xff)}
combined = iso_8859_2 | iso_8859_5

rawDescription: In python replacing characters from multiple char maps


code:
e1.bind("<FocusOut>", test1)
e2.bind("<FocusOut>", test2)

rawDescription: how handle events on every individual entry

description: How handle events on every individual entry


rawDescription: Pandas dataframe - running sum within cluster


code:
C_csc=current_flows.tocsc()
R_csc=result_flows.tocsc()
with_coo(C_csc, R_csc).tocsc().A

rawDescription: Adding two `csc` sparse matrices of different shapes in python


code: plt.figlegend( lines, labels, loc = 'lower center', ncol=5, labelspacing=0. )

rawDescription: how do I make a single legend for many subplots with matplotlib?

description: Make a single legend for many subplots with matplotlib


code:
class User:
    is_superuser = True
    is_active = True
    is_staff = True
    id = 1

def return_true(*args, **kwargs):
    return True
User.has_module_perms = return_true
User.has_perm = return_true

class Middleware(object):
    def process_request(self, request):
        request.user = User()

rawDescription: Django Admin without Authentication

description: Django Admin without Authentication


code: df = pd.read_csv('/localpath/data.tsv', sep='\t', skiprows=[1,2,3])

rawDescription: how to load/export CSV/TSV files from Pig to Pandas?

description: Load/export CSV/TSV files from Pig to Pandas


code:
import pandas as pd

df = pd.DataFrame({'foo':['100-200','1000-1100','1100-1200','200-300']})
order = sorted(range(len(df)),
               key=lambda idx: map(int, df.ix[idx, 'foo'].split('-')))
df = df.take(order)
print(df)

rawDescription: Numbers with hyphens or strings of numbers with hyphens


code:
messagePayload = dict(split for split in
    (item.split(": ") for item in messagePayload.split("; "))
if len(split)>1)

rawDescription: Conditionally Convert a String to a Dictionary in Python


code:
import numpy as np

rchdecay=N_DATA['column_name']
rchdcayf=np.exp(-rchdecay*0.008)

rawDescription: how to do math calculation on each number in a specific column in panda

description: Do math calculation on each number in a specific column in panda


code:
from nltk.corpus import wordnet as wn
from nltk.corpus import sentiwordnet as swn
from nltk import word_tokenize
from nltk.wsd import lesk
sent = word_tokenize("He should be happy".lower())
lesk(sent, 'be', 'v')

rawDescription: I am having problems doing Word Sense Disambiguation in Python using Lesk algorithm


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

W = 512
H = 256

hsls = np.zeros((H, W, 3), dtype=float)

baseCol = np.linspace(0, 1, H)
hsls[:, :, 0] = baseCol[:, np.newaxis]
hsls[:, :, 1:3] = 0.5

vfunc = np.vectorize(colorsys.hsv_to_rgb)
rgbs = np.dstack(vfunc(hsls[:, :, 0], hsls[:, :, 1], hsls[:, :, 2]))

fig, ax = plt.subplots()
im = ax.imshow(rgbs, interpolation='nearest', aspect='auto')
plt.colorbar(im, orientation='horizontal')
ax.invert_yaxis()
plt.show()

rawDescription: Draw NxMx3 ndarray as image using matplotlib imshow


code: set(a_nums) & set(b_nums)

rawDescription: comparing numbers in 2 string A and B

description: Comparing numbers in 2 string A and B


code:
def myFunc(context, parm):
  import lxml.html
  return lxml.html.fragments_fromstring('some sample text')

rawDescription: How can I return a text fragment from an XPath function?

description: Return a text fragment from an XPath function


code:
db.reflect()
db.drop_all()

rawDescription: How to relate APScheduler JobStore with SQLAlchemy Models (foreign key) - Python Flask

description: Relate APScheduler JobStore with SQLAlchemy Models (foreign key) - Python Flask


code:
random.shuffle(words)
words

rawDescription: Print a list of words in random order - Python


rawDescription: Randomly replace 2 values in python dictionary


code: str(b'GET http://...')

rawDescription: Python socket data returns <byte> object. How to regexp it?


code:
[[{'some': 'thing'}, None, None],
 [None, None, {'something': 'else'}],
 [None, {'another': 'thing'}, None]]

rawDescription: Remove row or column from 2D list if all values (in that row or column) are None


code: arv = {}

rawDescription: list problem in Python

description: List problem in Python


code:
def find_vga():
    vga = subprocess.check_output("lspci -v -s `lspci | awk '/VGA/{print $1}'`", shell=True, executable='/bin/bash')
    return vga

print(find_vga())

rawDescription: Python, In linux obtain VGA specifications via lspci or HAL?


rawDescription: Delete Multiple Django Model Attributes

description: Delete Multiple Django Model Attributes


code:
def _get_recursive_results(d, iter_key, get_keys, h=None):
    if h is None:
        h = []
    h.append({k: d.get(k) for k in get_keys})
    for k in iter_key:
        if not d:
            continue
        d = d.get(k)
    for td in d:
        d3 = td
        for k in iter_key:
            if not d3:
                continue
            d3 = d3.get(k)
        if d3:
            return _get_recursive_results(td, iter_key, get_keys, h)
        h.append({k: td.get(k) for k in get_keys})
    else:
        return h

rawDescription: Python Recursive Search of Dict with Nested Keys


code:
lower = 1,2,3
upper = 5,2,7
xyz = 2,3,4

all(u <= j <= v for u, j, v in zip(lower, xyz, upper))

rawDescription: Python Tuple Comparison not working for multiple less than, more than


code:
text = '''email_message#: 1
email_message_sent: 10/10/1991 02:31:01
From: tomf@abc.com| Tom Foo |abc company|
To: adee@abc.com| Alex Dee |abc company|
To: benfor12@xyz.com| Ben For |xyz company|
email_message#: 2
email_message_sent: 10/12/1991 01:28:12
From: timt@abc.com| Tim Tee |abc company|
To: tomf@abc.com| Tom Foo |abc company|
To: adee@abc.com| Alex Dee |abc company|
To: benfor12@xyz.com| Ben For|xyz company|'''

rawDescription: Read data from text format into Python Pandas dataframe


code:
import matplotlib.pyplot as plt

def boxplot_data(self, parameters_file):
    data = read_csv(parameters_file)
    header = data.keys()
    number_of_full_subplots = len(header)/16

    for i in range(number_of_full_subplots):
        plt.figure(i)
        for j in range(16):
            plt.subplot(4, 4, j)
            boxplot(data[header[16*i+j]])

rawDescription: Producing boxplot figures dynamically depending on number of columns in data


code:
import string
remove = dict.fromkeys(map(ord, '\n ' + string.punctuation))
sample = 'The quick brown fox, like, totally jumped, man!'
sample.translate(remove)

rawDescription: How to strip punctuation from a text file

description: Strip punctuation from a text file


code: someRegion = App.focusedWindow() # for the frontmost window

rawDescription: Using Sikuli to take automated screenshots of a window?


code: print([d["NODE"] for d in node.values() if "NODE" in d])

rawDescription: Grab Values Within a Dictionary in a Dictionary


code: b = '\n'.join('\t'.join('%0.3f' %x for x in y) for y in a)

rawDescription: convert 2d numpy array to string

description: Convert 2d numpy array to string


code:
source
import threading, time

def flagger_thread(event):
    time.sleep(2)
    event.set()

def waiter_thread(event):
    print("Waiting for event")
    if event.wait(5):
        print("event set.")
    else:
        print("Timed out.")

stop_event = threading.Event()
threading.Thread(target=flagger_thread, args=[stop_event]).start()
threading.Thread(target=waiter_thread, args=[stop_event]).start()

for t in threading.enumerate():
    if t != threading.current_thread():
        t.join()

rawDescription: Wait for class variable to change using threads


code:
import sqlite3
# Create your temporary database
connection = sqlite3.connect(":memory:")
cursor = connection.cursor()
# Set up a place to hold the data fetched previously
_ = cur.execute("CREATE TABLE t(x INTEGER, y INTEGER)")
# Dump all the data into the database
for column_1, column_2 in data:
  _ = cursor.execute("INSERT INTO t VALUES (?, ?)", [column_1, column_2])
# Now you can run queries against the new view of your data
sql = "SELECT t.column_1, t.count(*) FROM t GROUP BY t.column_1"

rawDescription: Creation pyodbc cursor to multiple databases


code: rules.casefold() == rulesa.casefold()

rawDescription: Python - Ignore letter case

description: Python - Ignore letter case


code: len(letters) != len(set(letters))

rawDescription: Python Check if Variable is Duplicated in list


rawDescription: Transforming a list

description: Transforming a list


code:
type(42) == int
type(42) == "<type 'int'>"

rawDescription: Understanding Python Attributes and Methods


rawDescription: Python Regex match a mac address from the end?


code:
iid = 1
def next_id():
    global iid
    res = iid
    iid += 1
    return res

rawDescription: Python - Global counter

description: Python - Global counter


code:
movedmsg = "object moved from = %s to = %s"
print(movedmsg % (object.location, new_location))

rawDescription: python 3: log function signature problem

description: Python 3: log function signature problem


rawDescription: Extracting data from a mongo collection

description: Extracting data from a mongo collection


code: tempBoard = copy.deepcopy(genBoard)

rawDescription: Generate list of possible moves Python Tic-Tac-Toe


code: B = A * (np.abs(scipy.ndimage.laplace(A)) > 0)

rawDescription: Scipy label erosion

description: Scipy label erosion


rawDescription: Pandas best practice to select multiple column data


code:
from Tkinter import *

movieList = ["1 Frozen 06/15 11:35 95", "3 Frozen 06/18 11:35 95",
        "4 Frozen 06/30 11:25 95", "5 Frozen 07/02 11:45 95",
        "6 Frozen 07/05 12:30 95"]

master = Tk()

option = StringVar(master)
option.set(movieList[0]) # Set the first value to be the default option

w = apply(OptionMenu, (master, option) + tuple(movieList))
w.pack()

mainloop()

rawDescription: How do I populate tkinter drop-down box with data retrieved from my SQLite database?

description: Populate tkinter drop-down box with data retrieved from my SQLite database


code: df = df.groupby(['code', 'colour']).apply(lambda x:x.set_index('id').to_dict('dict')['amount'])

rawDescription: Pandas: transforming the DataFrameGroupBy object to desired format


code:
class MyClass(object):
    a = {}
    def __init__(self):
        ...
    ...

rawDescription: Is embedded python Py_Finalize() blocking?


code: private_count = sum(ipaddress in IPv4Network(r) for r in ranges)

rawDescription: How best to iterate over a list when a each list item will be passed to a function?


code:
0.973290762737
{'estimator__kernel': 'poly', 'estimator__C': 1, 'estimator__degree': 2}

rawDescription: GridSearch for an estimator inside a OneVsRestClassifier


code: used, free = psutil.swap_memory()[1:3]

rawDescription: When calling a function from a module can you say what is returned? (Python)


code: [print(x) for x in range(5)]

rawDescription: python in-line for loops

description: Python in-line for loops


rawDescription: How to sort a list based on the output of numpy's argsort function

description: Sort a list based on the output of numpy's argsort function


code: some_id = sub.id

rawDescription: PRAW: serializing Comment and Submission objects as JSON


rawDescription: Proper way to deal with string which looks like json object but it is wrapped with single quote


code:
from random import shuffle

foo = []
foo.append([1, 2, 3])
foo.append([4, 5, 6])
foo.append([7, 8, 9])

shuffle(foo)
for ii, sublist in enumerate(foo):
    shuffle(foo[ii])

print(foo)

rawDescription: How do I shuffle a multidimensional list in Python

description: Shuffle a multidimensional list in Python


code:
from pandas.tseries.offsets import MonthEnd

df['Date'] = pd.to_datetime(df['Date'], format="%Y%m") + MonthEnd(1)

rawDescription: Find the end of the month Pandas DataFrame Series


code:
FunctionsWithDf = {function:df[df['Gene'].isin(genes)]
    for function, genes in FunctionsWithGenes.iteritems()}

rawDescription: Pandas: Splitting and editing file based on dictionary


code:
decorator = my_decorator(5)

@decorator
def function():
    return 5

rawDescription: Why are Python decorators with arguments syntactically different from those without?


code:
import os.path

filesList = None
dir = 'C:\FDF'
for root, dirs, files in os.walk(dir):
    for file in files:
        filesList.append(os.path.join(root, file))
print(filesList)

rawDescription: not listing entire directory

description: Not listing entire directory


code:
for i in range(5):
 if i%2==0:
  x = i
  print(x)
 else:
  print(x)

rawDescription: Variable assignments inside for and then if loops


code:
links = list(get_links())
len(links)
print(links)

rawDescription: Python expanding YouTube uploads

description: Python expanding YouTube uploads


rawDescription: Using Python List Comprehension to match values that exist in a 2d array and simple list


code:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')

rawDescription: Plot specific data sets from arrays - Python


code:
a = np.array([[1, 2], [2, 3], [1, 3]])
a = a.ravel().view((np.str, a.itemsize*a.shape[1]))
a.dtype
a.shape
a

rawDescription: test for membership in a 2d numpy array

description: Test for membership in a 2d numpy array


rawDescription: Computing future value of an account, when the user enters in the present value, interest rate, and number of years


code:
print(np.greater_equal(a,b).all())

print(np.all(a >= b))

rawDescription: Python: pairwise comparison between two lists: list a >= list b?


code:
counts = collections.defaultdict(int)
for event in Event.all().fetch(1000):
    counts[event.doe.date()] += 1

rawDescription: Counts of events grouped by date in python?


code:
import time
import os

start = time.time()

os.system("tar -cvf name.tar /path/to/directory")

end = time.time()
print("Elapsed time: %s"%(end - start,))

rawDescription: Faster way to compress folder in python

description: Faster way to compress folder in python


code:
for i, j, k in zip(list1[1:], list2[1:], list2):
    if i > k:
        print(i, j)

rawDescription: Iterate over two lists while i-1 condition is met in python


code:
import random

def shaperand(s):
    return [shaperand(e) if isinstance(e, list) else random.random() for e in s]

rawDescription: numpy random numpers in specified shape of any complexity

description: Numpy random numpers in specified shape of any complexity


code:
min1=open(output1,"w")

oh_reader = open(filename, 'r')

countmin = 0

for line in oh_reader:
    #min1
    if countmin <=60000:
        hrvalue= int(line)
        ibihr = line
        print(line)
        print(countmin)
        min1.write(ibihr)
        min1.write("\n")
        countmin += hrvalue  # += operator is equal to a = a + b
min1.close()

rawDescription: Writing to txt in python

description: Writing to txt in python


rawDescription: Can't get pygame font to render on image


code:
forms.py
from django import forms

class TotalSumForm(forms.Form):
    venue = forms.ModelChoiceField(queryset=Venue.objects.all(), required=True)
    decoration = forms.ModelChoiceField(
        queryset=Decoration.objects.all(), required=True)

    def get_total(self):
        # send email using the self.cleaned_data dictionary
        return self.cleaned_data['venue'].rent +\
               self.cleaned_data['decoration'].rate

rawDescription: How create a custom form in django with database values


code: now - yest

rawDescription: time series in python up to microseconds

description: Time series in python up to microseconds


code:
control = Controller()
btn1 = Button(tk, text="Start Recording", width=16, height=5, command=control.combine)
btn1.grid(row=2,column=0)
btn2 = Button(tk, text="Stop Recording", width=16, height=5, command=control.stop)
btn2.grid(row=3,column=0)

rawDescription: Terminate the Thread by using buttion in Tkinter


code: X

rawDescription: Subsetting DataFrame using ix in Python

description: Subsetting DataFrame using ix in Python


code:
s = r'\n'
print(s)
# -> \n

rawDescription: Unescaping escaped characters in a string using Python 3.2


code:
Code
def heapSort3(a):
    def sift(start, count):
        root = start
        while root * 3 + 1 < count:
            r3 = root * 3
            upper = min(count - r3, 4)
            children = list(range(r3 + 1, r3 + upper))
            min_child = min((a[i], i) for i in children)
            v, i = min_child
            if a[root] > a[i]:
                a[root], a[i] = a[i], a[root]
                root = i
            else:
                break
    count = len(a)
    for start in reversed(range(count // 3 + 2)):
        sift(start, count)
    for end in reversed(range(count)):
        a[end], a[0] = a[0], a[end]
        sift(0, end)
    return a

rawDescription: Ternary heapsort in python 2.7

description: Ternary heapsort in python 2.7


code:
import A

var = A.something()

rawDescription: Python within python

description: Python within python


code: pc = pcap.pcapObject()

rawDescription: 'module' object has no attribute 'pcapObject'


code:
df[pd.isnull(df2)] = np.nan
df

rawDescription: day is out of range for month python

description: Day is out of range for month python


code:
characters = ['A', 'B', 'C', 'D', 'E']
list(itertools.combinations(characters, 2))

rawDescription: Python fastest method to group pairs from a list of items


code:
for i in range(0, len(inputstring), 8):
    print(chr(int(inputstring[i:i + 8], 2)), end='')

rawDescription: How can I convert a binary value to text or ascii in python 3?

description: Convert a binary value to text or ascii in python 3


code:
from queue import Queue

class StreamWriter(object):
    def __init__(self):
        self.queue = Queue()

    def write(self, str):
        self.queue.put(str)

    def read(self):
        str = self.queue.get()
        self.queue.task_done()
        if str == '~':
            return None
        return str

    def close(self):
        self.write('~')  # indicate EOF

rawDescription: Flask: Streaming data by writing to client?


code:
class RGB(object):
    def __init__(self, red, blue, green):
        super(RGB, self).__init__()
        self._red = red
        self._blue = blue
        self._green = green

    def _color(self, type):
        return getattr(self, type)

    @property
    def red(self): return self._color('_red')
    @property
    def blue(self): return self._color('_blue')
    @property
    def green(self): return self._color('_green')

rawDescription: functools.partial on class method

description: Functools.partial on class method