code:
[('<username two places above>', score),
 ('<username one place above>', score),
 ('<instance username>', score),
 ('<username one place below>', score),
 ('<username two places below>', score)]

rawDescription: Django Get Range in Queryset

description: Django Get Range in Queryset


code:
import urllib2
from lxml import etree

url =  "http://www.example.com/servlet/av/ResultTemplate=AVResult.html"
response = urllib2.urlopen(url)
htmlparser = etree.HTMLParser()
tree = etree.parse(response, htmlparser)
tree.xpath(xpathselector)

rawDescription: can we use xpath with BeautifulSoup?

description: Can we use xpath with BeautifulSoup


code:
from collections import defaultdict
import re
s = 'label("id1","A") label("id1","B") label("id2", "C") label("id2","A") label("id2","D") label("id3","A")'
regex = re.compile(r'label\("([^"]*)",\s*"([^"]*)"\)')
results = defaultdict(list)
for id_, tag in regex.findall(s):
    results[id_].append(tag)

results.items()

rawDescription: Grouping elements based on an identifier in regular expression (Python)


code:
#!/usr/bin/env python
from datetime import datetime
import parsedatetime as pdt # $ pip install parsedatetime

cal = pdt.Calendar()
now = datetime.now()
print("now: %s" % now)
for time_string in ["tomorrow at 6am", "next moday at noon",
                    "2 min ago", "3 weeks ago", "1 month ago"]:
   print("%s:\t%s" % (time_string, cal.parseDT(time_string, now)[0]))

rawDescription: Is there any python library for parsing dates and times from a natural language?


code:
import code
import sys
from contextlib import contextmanager

try:
    from StringIO import StringIO
except ImportError: # Python 3
    from io import StringIO

try:
    from contextlib import redirect_stdout
except ImportError: # Python < 3.4
    @contextmanager
    def redirect_stdout(new_target):
        old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
        try:
            yield new_target # run some code with the replaced stdout
        finally:
            sys.stdout = old_target # restore to the previous value

f = StringIO()
with redirect_stdout(f):
    console = code.InteractiveConsole()
    console.push('print("hello world")')
    console.push('i = int(input("give me a number"))')
    console.push('sq = i*i')
    console.push('print("%d squared is %d" % (i, sq))')
print("Got: %r" % f.getvalue())

rawDescription: Redirect output from stdin using code module in python?


code:
commands = {
    "circle": draw_circle,
    "square": draw_square
}

rawDescription: How To create a shortcut for a command in python 3.3


code:
filepath = os.path.join(filespath, file)
im = Image.open(filepath)

rawDescription: Open process and save specific images in related folder


code: outfile = open("output/report.html", "w+")

rawDescription: How to use String format to create HTML report

description: Use String format to create HTML report


code:
def is_antonym(a,b):
    for x,y in antonyms():
        if a == x and b == y:
            return True
    return False

rawDescription: Reading from a python file

description: Reading from a python file


code:
def changebg(x,y):
    entryList[x][y]['bg']='yellow'

for x in range(4):
    for y in range(4):
        entryList[x][y].after(300,changebg(x,y))
        #Same result with root.after(300,changebg(x,y))

rawDescription: Python: change entry colour dynamically with Tkinter


code:
# draw player 1's view  to the top left corner
screen.blit(canvas, (0,0), p1_camera)
# player 2's view is in the top right corner
screen.blit(canvas, (400, 0), p2_camera)
# player 3's view is in the bottom left corner
screen.blit(canvas, (0, 300), p3_camera)
# player 4's view is in the bottom right corner
screen.blit(canvas, (400, 300), p4_camera)

# then you update the display
# this can be done with either display.flip() or display.update(), the
# uses of each are beyond this question
display.flip()

rawDescription: how to create a 4-way split screen in pygame

description: Create a 4-way split screen in pygame


rawDescription: Python, Tkinter: How to get the handle of all canvas objects using their IDs or tags?


code:
args = ['--solr-url', 'http://127.0.0.1:8983/solr/collection1',
    '--type', 'opinions']
kwargs = {
    'update': True,
    'everything': True,
    'do_commit': True,
    'traceback': True,
}
call_command('cl_update_index', *args, **kwargs)

rawDescription: call_command argument is required

description: Call_command argument is required


code: list(set(mammals) & set(apes))

rawDescription: Cross Reference 2 lists in Python 2.x

description: Cross Reference 2 lists in Python 2.x


code:
now = datetime.datetime.now(pytz.utc)
youngest = max(dt for dt in datetimes if dt < now)

rawDescription: Find oldest/youngest datetime object in a list


code:
df1 = df1.set_index('ID')
df2 = df2.set_index('ID')

df3 = (df1['Subject'].str
                     .replace(r'[^a-zA-Z\s]' , '')
                     .str
                     .lower()
                     .str
                     .split('\s+', expand=True)
                     .stack()
                     .reset_index(drop=True, level=1)
                     .reset_index(name='val'))

df4 = (df2['Subject'].str
                     .replace(r'[^a-zA-Z\s]' , '')
                     .str
                     .lower()
                     .str
                     .split('\s+', expand=True)
                     .stack()
                     .reset_index(drop=True, level=1)
                     .reset_index(name='val'))

rawDescription: Python Pandas - compare column text and provide matched word count


code:
frame2 = pd.concat([recode(frame[col], 3) for col in frame], axis=1)
frame2

rawDescription: Column recoding based on count of distincts


code:
import pickle
obj = 1
serialized = pickle.dumps(obj)
serialized
pickle.loads(serialized)

rawDescription: reconstituting a class full of data from MySQL BLOB object in python

description: Reconstituting a class full of data from MySQL BLOB object in python


rawDescription: Index a Pandas dataframe grouped by date and aggregated?


code:
from django.contrib.admin.views.decorators import staff_member_required as _staff_reqd

def staff_member_required(patterns):  # make an include decorator with a familiar name
    return decorate(_staff_reqd, patterns)

...
urls('^foo/', staff_member_required(include('fooapp.urls'))),

rawDescription: reusable apps and access control

description: Reusable apps and access control


code: data = [['H EL LO', 'h el lo'], ['W OR L D', 'w or l d']]

rawDescription: Split element in string into segments

description: Split element in string into segments


code:
from datetime import datetime, timedelta

START, END = xrange(2)
def tparse(timestring):
    return datetime.strptime(timestring, '%H:%M')

def sum_intervals(intervals):
    times = []
    for interval in intervals:
        times.append((tparse(interval[START]), START))
        times.append((tparse(interval[END]), END))
    times.sort()

    started = 0
    result = timedelta()
    for t, type in times:
        if type == START:
            if not started:
                start_time = t
            started += 1
        elif type == END:
            started -= 1
            if not started:
               result += (t - start_time)
    return result

rawDescription: python time interval algorithm sum

description: Python time interval algorithm sum


code:
plt.text(1.065, .5, cbar_title,  fontsize=fs,
verticalalignment='center',rotation = 90, transform = ax.transAxes)

rawDescription: How can I keep the bbox tight on 3 sides and constant for different plots using colorbar

description: Keep the bbox tight on 3 sides and constant for different plots using colorbar


code:
import matplotlib.pyplot as plt

def assignIDs(list):
    '''Take a list of strings, and for each unique value assign a number.
    Returns a map for "unique-val"->id.
    '''
    sortedList = sorted(list)

    #taken from
    #http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order/480227#480227
    seen = set()
    seen_add = seen.add
    uniqueList =  [ x for x in sortedList if x not in seen and not seen_add(x)]

    return  dict(zip(uniqueList,range(len(uniqueList))))

def plotData(inData,color):
    x,y = zip(*inData)

    xMap = assignIDs(x)
    xAsInts = [xMap[i] for i in x]

    plt.scatter(xAsInts,y,color=color)
    plt.xticks(xMap.values(),xMap.keys())

DATA = [
    ('a', 4),
    ('b', 5),
    ('c', 5),
    ('d', 4),
    ('e', 2),
    ('f', 5),
]

DATA2 = [
    ('a', 3),
    ('b', 4),
    ('c', 4),
    ('d', 3),
    ('e', 1),
    ('f', 4),
    ('a', 5),
    ('b', 7),
    ('c', 7),
    ('d', 6),
    ('e', 4),
    ('f', 7),
]

plotData(DATA,'blue')
plotData(DATA2,'red')

plt.gcf().savefig("correlation.png")

rawDescription: Drawing a correlation graph in matplotlib


code:
def __getitem__(self,n):
    while len(self) <= n:
        self.append(self.dft)
    return super(ilist, self).__getitem__(n)

rawDescription: Is there a simple way to override the list object's method __getitem__?


rawDescription: append multiple results from one list to another

description: Append multiple results from one list to another


rawDescription: Finding occurence in list of lists

description: Finding occurence in list of lists


rawDescription: Python: Find Unique XML Attributes

description: Python: Find Unique XML Attributes


code: np.allclose(ny, ny2)

rawDescription: Fast interpolation over 3D array for 3D origin x


code:
DATABASES = {
    'default': {
        'NAME': 'celerybeat.db',
        'ENGINE': 'django.db.backends.sqlite3',
    },
}
INSTALLED_APPS = ('djcelery', )

rawDescription: How to dynamically add / remove periodic tasks to Celery (celerybeat)

description: Dynamically add / remove periodic tasks to Celery (celerybeat)


code:
import threading
lock = threading.Lock()
lock.acquire()
lock.acquire()

rawDescription: Lock variable in python in a loop

description: Lock variable in python in a loop


code:
strpression = ['dummyfunction',1,2,3]
getattr(myobj,strpression[0])(*strpression[1:])

rawDescription: getting string representation of function from a list having function name and arguments

description: Getting string representation of function from a list having function name and arguments


code:
with open('input2') as ifd, open('output', 'w') as ofd:
    for line in ifd:
        ofd.write('    '.join(replace.get(idt, idt) for idt in line.split()))

rawDescription: Multiple word replacement by list - duplicates creation


code:
['First list title Additional info\n
\n
List element 1 additional info\n  ',
 'Second list title Additional info\n
\n
List element 1 additional info1\n
List element 2 additional info2\n
List element 3 additional info3\n
List element 4 additional info4\n  ']

rawDescription: Python regex findall to capture repeated groups


code:
var=0
def f():
    var=1
f()
print(var)
# 0  <---- the var outside the "def f" block is unaffected

rawDescription: Python: Difference between 'global' & globals().update(var)


code: result = [x for x in (transform(y) for y in some_iterable) if condition(x)]

rawDescription: How to filter on results of a comprehension?

description: Filter on results of a comprehension


code:
class foo(object):
    def __init__(self):
        self.dates = []

    def _makeRangeDates(self,desde,ultima_carga):

        for fechaRequest in rrule(DAILY, dtstart=desde, until=ultima_carga):
            self.dates.append(fechaRequest)
        return self.dates

rawDescription: what is the correct way to return a value inside of a method? in python

description: What is the correct way to return a value inside of a method? in python


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

A = np.random.random_integers(0, 10, 100).reshape(10, 10)
B = np.random.random_integers(0, 10, 100).reshape(10, 10)

fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)

mapable = ax1.imshow(A, interpolation="nearest")
cax = ax2.imshow(A, interpolation="nearest")

# set the tickmarks *if* you want cutom (ie, arbitrary) tick labels:
cbar = fig.colorbar(cax, ax=None)

fig = plt.figure(2)
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
mapable = ax1.imshow(A, interpolation="nearest")
cax = ax2.imshow(A, interpolation="nearest")
# on the figure total in precent l    b      w , height
ax3 = fig.add_axes([0.1, 0.1, 0.8, 0.05]) # setup colorbar axes.
# put the colorbar on new axes
cbar = fig.colorbar(mapable,cax=ax3,orientation='horizontal')

plt.show()

rawDescription: How to add a single colobar that will show the data from 2 different subplot

description: Add a single colobar that will show the data from 2 different subplot


code:
from bokeh.embed import components
script, div_dict = components({"plot": plot, "table": table})

rawDescription: Embedding bokeh plot and datatable in flask


code:
import pandas
from io import StringIO

datastring = StringIO("""\
Country  Metric           2011   2012   2013  2014
USA     GDP               7      4     0      2
USA     Pop.              2      3     0      3
GB      GDP               8      7     0      7
GB      Pop.              2      6     0      0
FR      GDP               5      0     0      1
FR      Pop.              1      1     0      5
""")
data = pandas.read_table(datastring, sep='\s\s+')
data.set_index(['Country', 'Metric'], inplace=True)

rawDescription: MultiIndex Group By in Pandas Data Frame


rawDescription: PYTHON: Inserting all lines into array/list after specific symbol


rawDescription: Python parsing list of string

description: Python parsing list of string


code:
try:
   avg = (float(row[1].replace(',', '.')) + float(row[2].replace(',', '.')))/2
except ValueError:
   avg = 0 # for cases with empty strings or commas

rawDescription: Python - Read and assign data from a .csv to pre-defined variables


code:
words = ('FillLevel[', 'CycleMAX[', 'CycleMIN[')  # etc.

for b in results:
    if not any(word in str(b) for word in words):
        new_list.append(b)

rawDescription: Loop - If one from several conditions is True append to new list


code:
from itertools import islice

combos = combinations(range(y + 1), 11)
data = [list(combo) for combo in islice(combos, 100)]

rawDescription: Storing First X Items of a Large List (Python)


code:
class dynamicObject(object):
    pass

def someMethod(self):
    print('Hi there!')

someObject=dynamicObject()
dynamicObject.someMethod=someMethod
someObject.someMethod()
# Hi there!

rawDescription: Python: using Self and adding methods to an object on the fly


code:
def dot_notation(obj, prefix=''):
     if isinstance(obj, dict):
         if prefix: prefix += '.'
         for k, v in obj.items():
             for res in dot_notation(v, prefix+str(k)):
                 yield res
     elif isinstance(obj, list):
         for i, v in enumerate(obj):
             for res in dot_notation(v, prefix+'['+str(i)+']'):
                 yield res
     else:
         yield prefix

rawDescription: Return a list of all variable names in a python nested dict/json document in dot notation


code:
import gmpy2
from gmpy2 import mpz

def factors(n):
    result = set()
    n = mpz(n)
    for i in range(1, gmpy2.isqrt(n) + 1):
        div, mod = divmod(n, i)
        if not mod:
            result |= {mpz(i), div}
    return result

print(factors(12345678901234567))

rawDescription: Most efficient way to find all factors with GMPY2 (or GMP)?


code: ax.margins(0.01, None)

rawDescription: Add padding between bars and Y-Axis

description: Add padding between bars and Y-Axis


code:
import logging
import logging.handlers
import os
import time
import sys

import cv2
import numpy as np

from vehicle_counter import VehicleCounter

# ============================================================================

IMAGE_DIR = "images"
IMAGE_FILENAME_FORMAT = IMAGE_DIR + "/frame_%04d.png"

# Support either video file or individual frames
CAPTURE_FROM_VIDEO = False
if CAPTURE_FROM_VIDEO:
    IMAGE_SOURCE = "traffic.avi" # Video file
else:
    IMAGE_SOURCE = IMAGE_FILENAME_FORMAT # Image sequence

# Time to wait between frames, 0=forever
WAIT_TIME = 1 # 250 # ms

LOG_TO_FILE = True

# Colours for drawing on processed frames
DIVIDER_COLOUR = (255, 255, 0)
BOUNDING_BOX_COLOUR = (255, 0, 0)
CENTROID_COLOUR = (0, 0, 255)

# ============================================================================

def init_logging():
    main_logger = logging.getLogger()

    formatter = logging.Formatter(
        fmt='%(asctime)s.%(msecs)03d %(levelname)-8s [%(name)s] %(message)s'
        , datefmt='%Y-%m-%d %H:%M:%S')

    handler_stream = logging.StreamHandler(sys.stdout)
    handler_stream.setFormatter(formatter)
    main_logger.addHandler(handler_stream)

    if LOG_TO_FILE:
        handler_file = logging.handlers.RotatingFileHandler("debug.log"
            , maxBytes = 2**24
            , backupCount = 10)
        handler_file.setFormatter(formatter)
        main_logger.addHandler(handler_file)

    main_logger.setLevel(logging.DEBUG)

    return main_logger

# ============================================================================

def save_frame(file_name_format, frame_number, frame, label_format):
    file_name = file_name_format % frame_number
    label = label_format % frame_number

    log.debug("Saving %s as '%s'", label, file_name)
    cv2.imwrite(file_name, frame)

# ============================================================================

def get_centroid(x, y, w, h):
    x1 = int(w / 2)
    y1 = int(h / 2)

    cx = x + x1
    cy = y + y1

    return (cx, cy)

# ============================================================================

def detect_vehicles(fg_mask):
    log = logging.getLogger("detect_vehicles")

    MIN_CONTOUR_WIDTH = 21
    MIN_CONTOUR_HEIGHT = 21

    # Find the contours of any vehicles in the image
    contours, hierarchy = cv2.findContours(fg_mask
        , cv2.RETR_EXTERNAL
        , cv2.CHAIN_APPROX_SIMPLE)

    log.debug("Found %d vehicle contours.", len(contours))

    matches = []
    for (i, contour) in enumerate(contours):
        (x, y, w, h) = cv2.boundingRect(contour)
        contour_valid = (w >= MIN_CONTOUR_WIDTH) and (h >= MIN_CONTOUR_HEIGHT)

        log.debug("Contour #%d: pos=(x=%d, y=%d) size=(w=%d, h=%d) valid=%s"
            , i, x, y, w, h, contour_valid)

        if not contour_valid:
            continue

        centroid = get_centroid(x, y, w, h)

        matches.append(((x, y, w, h), centroid))

    return matches

# ============================================================================

def filter_mask(fg_mask):
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))

    # Fill any small holes
    closing = cv2.morphologyEx(fg_mask, cv2.MORPH_CLOSE, kernel)
    # Remove noise
    opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel)

    # Dilate to merge adjacent blobs
    dilation = cv2.dilate(opening, kernel, iterations = 2)

    return dilation

# ============================================================================

def process_frame(frame_number, frame, bg_subtractor, car_counter):
    log = logging.getLogger("process_frame")

    # Create a copy of source frame to draw into
    processed = frame.copy()

    # Draw dividing line -- we count cars as they cross this line.
    cv2.line(processed, (0, car_counter.divider), (frame.shape[1], car_counter.divider), DIVIDER_COLOUR, 1)

    # Remove the background
    fg_mask = bg_subtractor.apply(frame, None, 0.01)
    fg_mask = filter_mask(fg_mask)

    save_frame(IMAGE_DIR + "/mask_%04d.png"
        , frame_number, fg_mask, "foreground mask for frame #%d")

    matches = detect_vehicles(fg_mask)

    log.debug("Found %d valid vehicle contours.", len(matches))
    for (i, match) in enumerate(matches):
        contour, centroid = match

        log.debug("Valid vehicle contour #%d: centroid=%s, bounding_box=%s", i, centroid, contour)

        x, y, w, h = contour

        # Mark the bounding box and the centroid on the processed frame
        # NB: Fixed the off-by one in the bottom right corner
        cv2.rectangle(processed, (x, y), (x + w - 1, y + h - 1), BOUNDING_BOX_COLOUR, 1)
        cv2.circle(processed, centroid, 2, CENTROID_COLOUR, -1)

    log.debug("Updating vehicle count...")
    car_counter.update_count(matches, processed)

    return processed

# ============================================================================

def main():
    log = logging.getLogger("main")

    log.debug("Creating background subtractor...")
    bg_subtractor = cv2.BackgroundSubtractorMOG()

    log.debug("Pre-training the background subtractor...")
    default_bg = cv2.imread(IMAGE_FILENAME_FORMAT % 119)
    bg_subtractor.apply(default_bg, None, 1.0)

    car_counter = None # Will be created after first frame is captured

    # Set up image source
    log.debug("Initializing video capture device #%s...", IMAGE_SOURCE)
    cap = cv2.VideoCapture(IMAGE_SOURCE)

    frame_width = cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)
    frame_height = cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)
    log.debug("Video capture frame size=(w=%d, h=%d)", frame_width, frame_height)

    log.debug("Starting capture loop...")
    frame_number = -1
    while True:
        frame_number += 1
        log.debug("Capturing frame #%d...", frame_number)
        ret, frame = cap.read()
        if not ret:
            log.error("Frame capture failed, stopping...")
            break

        log.debug("Got frame #%d: shape=%s", frame_number, frame.shape)

        if car_counter is None:
            # We do this here, so that we can initialize with actual frame size
            log.debug("Creating vehicle counter...")
            car_counter = VehicleCounter(frame.shape[:2], frame.shape[0] / 2)

        # Archive raw frames from video to disk for later inspection/testing
        if CAPTURE_FROM_VIDEO:
            save_frame(IMAGE_FILENAME_FORMAT
                , frame_number, frame, "source frame #%d")

        log.debug("Processing frame #%d...", frame_number)
        processed = process_frame(frame_number, frame, bg_subtractor, car_counter)

        save_frame(IMAGE_DIR + "/processed_%04d.png"
            , frame_number, processed, "processed frame #%d")

        cv2.imshow('Source Image', frame)
        cv2.imshow('Processed Image', processed)

        log.debug("Frame #%d processed.", frame_number)

        c = cv2.waitKey(WAIT_TIME)
        if c == 27:
            log.debug("ESC detected, stopping...")
            break

    log.debug("Closing video capture device...")
    cap.release()
    cv2.destroyAllWindows()
    log.debug("Done.")

# ============================================================================

if __name__ == "__main__":
    log = init_logging()

    if not os.path.exists(IMAGE_DIR):
        log.debug("Creating image directory `%s`...", IMAGE_DIR)
        os.makedirs(IMAGE_DIR)

    main()

rawDescription: Counting Cars OpenCV + Python Issue

description: Counting Cars OpenCV + Python Issue


code:
import re

s = '''bla bla bla ||NULL||abc-swf||NULL||NULL
bla bla bla ||NULL||cdacda-swfend%23wrapclass||NULL||NULL
bla bla bla ||NULL||bgdbgdbgd-swf%28ML%29endBeliefnet.Web.UI.S||NULL||NULL'''

# bad_regex = re.compile(r'(?<=swf)[^|]+') # will stop at a single pipe character |
regex = re.compile(r'(?<=-swf).*?(?=\|\|)') # matches everything between -swf and ||
regex.sub('', s)

rawDescription: Python Regex Replace Matching Text

description: Python Regex Replace Matching Text


code:
from your_models.teacher import Teacher
from sqlalchemy.exc import NoSuchTableError

try:
    teacher = session.query(Teacher).filter(Teacher.id==42).first()
except NoSuchTableError:
    teacher = Teacher('Unknown')

rawDescription: Pyramid: modifying site content based on settings


rawDescription: How to calculate difference on previous within set of grouped rows in a dataframe

description: Calculate difference on previous within set of grouped rows in a dataframe


rawDescription: Parallel Python - create objects into another class in parallel execution


rawDescription: Is it possible to use a PositiveIntegerField as a foreign key in Django?


code:
[['Sentence 1.', 'And Sentence 2.', 'Or Sentence 3.'],
 ['New Sentence 4.'],
 ['New Sentence 5.', 'And Sentence 6.']]

rawDescription: Recursively group sentences based on conjunctions


code:
_number    # key is always `_number`
_number
name = 100
number = 100

rawDescription: python scope issue with anonymous lambda in metaclass

description: Python scope issue with anonymous lambda in metaclass


code:
from SimpleXMLRPCServer import SimpleXMLRPCServer
server = SimpleXMLRPCServer(("localhost", 9876))

def my_func(a,b):
    return a + b

server.register_function(my_func)
server.serve_forever()

rawDescription: Network programming in Python

description: Network programming in Python


code:
temp[1][0]=100
temp
board

rawDescription: Python - Function has a list as argument. How to return another list without changing the first?


code: {"df{0:d}.Close".format(idx+1): df["Close"] for idx, df in enumerate(dflist)}

rawDescription: Merging multiple, unaligned data-frames into single pandas data-frame


code:
from operator import itemgetter
sorted(sorted(example), key=itemgetter(1), reverse=True)

rawDescription: How to sort list depending on values in sublists?

description: Sort list depending on values in sublists


code:
a = sorted(list('hello'))
a

rawDescription: Is there a version of list.sort() that returns the sorted list?


code:
class create_db(object):

    def __init__(self):
        import psycopg2 as pq
        self.cn = pq.connect('dbname=mydb user=me')
        self.cr = self.cn.cursor()

    def execute(self, query, *args):

        results = self.cr.execute(query, args)

        return results

rawDescription: Python: Passing a cursor back from a class for a dbi instance


code:
STATIC_URL = "http://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)
STATICFILES_STORAGE = 'app_name.custom_storages.StaticStorage'

rawDescription: Using S3 as media storage for Django on python 3.3 hosting Openshift


code:
def is_multiple(m, n):
    return is_factor(n, m)

rawDescription: Finding a multiple function keeps returning true and is there a simpler way to write this function in python


code:
from PIL import Image
import numpy as np

im = Image.open("test.png")
pix = np.asarray(im)

pix = pix[:,:,0:3] # Drop the alpha channel
idx = np.where(pix-255)[0:2] # Drop the color when finding edges
box = map(min,idx)[::-1] + map(max,idx)[::-1]

region = im.crop(box)
region_pix = np.asarray(region)

rawDescription: Use Python / PIL or similar to shrink whitespace


code:
Background [u'x0', u'x1']
Innovation [u'x2', u'x3', u'x4']
Activities [u'x5', u'x6']

rawDescription: Using BeautifulSoup to parse multiple paragraphs in Python


code:
class History(object):

    def __init__(self):
        self.l = ['']
        self.i = 0

    def next(self):
        if self.i == len(self.l):
            return None
        self.i += 1
        return self.l[self.i]

    def prev(self):
        if self.i == 0:
            return None
        self.i -= 1
        return self.l[self.i]

    def add(self, s):
        del self.l[self.i+1:]
        self.l.append(s)
        self.i += 1

    def current(self):
        return self.l[self.i]

rawDescription: Undo and Redo in an Tkinter Entry widget?


code: script.pl < input > output             # 0 args, redirects stdin and stdout

rawDescription: Running a perl script in python and storing the output in a file


code:
annualInterestRate = .1
balance = 1000

def balance_after_one_year(balance, annualInterestRate, payment):
    '''Calculate the balance after one year of interest and payments.

    balance --> int or float
    annualInterestRate --> float between 0 and 1
    payment --> float

    returns float
    '''
    for _ in xrange(12):
        balance = (balance - payment) * (1 + annualInterestRate / 12.0)
    return balance

def min_payment(balance, annualInterestRate, tolerance = .01):
    '''Find the minimum payment to pay off a loan.

    Uses a bisection search.
    Ensures balance is not positive.

    balance --> float, int
    annualInterestRate --> float less than one
    tolerance --> float
   '''

    # we want the tolerance to be negative
    # this isn't strictly a tolerance, it is a lower limit
    tolerance = -abs(tolerance)

    hi = balance
    lo = 0
    while True:
        payment = (hi + lo) / 2.0
        tmp_balance = balance_after_one_year(balance, annualInterestRate, payment)
        if tmp_balance < tolerance:
            hi = payment
        # ensure balance is not positive
        elif tmp_balance > 0:
            lo = payment
        else:
            return payment, tmp_balance

rawDescription: Get my search to solve only if solution is negative (MIT6.00)


code: df = pd.concat([df, new])

rawDescription: Insert rows according to value of columns in pandas dataframes


rawDescription: regex patterns and lists in python

description: Regex patterns and lists in python


code: [sum(x, []) for a in list2 for x in a]

rawDescription: Python - Flatten lists of lists of two different types in one function


code:
for i in xs:
  outputfilename = 'results/'+str(i)
  new_func = redirect_output(outputfilename)(somefunc)
  #or call it directly
  #redirect_output(outputfilename)(somefunc)(i)
  new_func(i)

rawDescription: Pipe console outputs from a specific function into a file - python


code:
with open('data.txt', 'r') as f:
    col2 = [line.split()[1] for line in f]
    data2 = list(map(float, col2 [1:]))   # apply float to each item using `map`
                                          # as `map` returns a `map` object in py3.x
                                          # you have to pass it to list()
with open('data.txt', 'r') as f:
    col3 = [line.split()[2] for line in f]
    data3 = list(map(float, col3 [1:]))
    print (data3)

rawDescription: from list of strings into list of floats

description: From list of strings into list of floats


code: #ThIsPlAcE

rawDescription: Ordering a string based on another string


code:
wanted = "A"
def tuple_wanted(tpl):
   return wanted in tpl

rawDescription: Python - using dictionary to count keys and values


code:
l = []
while len(l) < 52:
    number = random.randint(1, 13)
    suit = random.choice(['hearts', 'clubs', 'diamonds', 'spades'])
    card = (number, suit)
    if card not in l:
        l.append(card)

rawDescription: Randomizing a list of tuples without random.shuffle() python


code:
xmlbody = '<stuff>\
<my_element>\
    <blablabla href="docs/MyBlank.htm" />\
</my_element>\
<!--\
<my_element>\
    <blablabla href="secretwebhacking/MySecrectBankLogin.htm" />\
</my_element>\
-->\
</stuff>'

from bs4 import BeautifulSoup, Comment
soup = BeautifulSoup(xmlbody, "lxml")

# Find all comments
comments = soup.findAll(text=lambda text:isinstance(text, Comment))
for comment in comments:
  # Create new soup object from comment contents
  commentsoup = BeautifulSoup(comment, "lxml")
  # Find the tag we want
  blatag = commentsoup.find('blablabla')
  # Check if it is the one we need
  if(blatag['href']=="secretwebhacking/MySecrectBankLogin.htm"):
    # If so, insert the element within the comment into the document
    comment.insert_after(commentsoup.find('body').find('my_element'))
    # And remove the comment
    comment.extract()

# Find all my_elements
my_elements = soup.findAll('my_element')
for tag in my_elements:
  # Check if it's the one we want
  if(tag.find('blablabla')['href'] == "docs/MyBlank.htm"):
    # If so, insert a commented version
    tagcomment = soup.new_string(str(tag), Comment)
    tag.insert_after(tagcomment)
    # And remove the tag
    tag.extract()

print(soup.find('html').find('body').prettify().replace("<body>\n","").replace("\n</body>",""))

rawDescription: Comment out and uncomment an xml element


code:
tempList = [(i[0], i[2]) for i in data if i[1] == 'fruit']
tempList = [i[:1]+i[2:] for i in data if i[1] == 'fruit']

rawDescription: python conditional list creation from 2D lists

description: Python conditional list creation from 2D lists


code:
my_data = {'time, s': [0,1,2,3], 'x temp, C':[0,10,20,30],
 'x pressure, kPa': [0,100,200,300]}
import csv
with open('outfile.csv', 'w') as outfile:
   writer = csv.writer(outfile)
   writer.writerow(my_data.keys())
   writer.writerows(zip(*my_data.values()))

rawDescription: Syntax - saving a dictionary as a csv file


code:
import matplotlib.ticker as mticker

cb = fig.colorbar(im, ticks=mticker.AutoLocator())

rawDescription: How to get colorbar ticks at multiples of 1, 2, 5, 10, 20 in Matplotlib

description: Get colorbar ticks at multiples of 1, 2, 5, 10, 20 in Matplotlib


code:
import itertools as IT
import pandas as pd

def valid(chunks):
    for chunk in chunks:
        mask = chunk['B'] < 10
        if mask.all():
            yield chunk
        else:
            yield chunk.loc[mask]
            break

chunksize = 10 ** 5
chunks = pd.read_csv(filename, chunksize=chunksize, header=None)
df = pd.concat(valid(chunks))

rawDescription: conditional row read of csv in pandas

description: Conditional row read of csv in pandas


rawDescription: how to use pygame set_alpha() on a picture

description: Use pygame set_alpha() on a picture


code:
nOcc = 30
nVir = 120
Ew = np.random.rand(nOcc+nVir)
Ew[:nOcc]*=-1
Ia = np.random.rand(nOcc)
Ib = np.random.rand(nVir)
I = np.einsum('a,b,c,d->abcd',Ia,Ib,Ia,Ib)

rawDescription: Are there function calls that can replace the for loops in this code?


code:
for i in range(0,3): # assume I would like to write to 3 files
    for n in range(len(links)):
        navigation[0].append(links[n])
    output = navigation[0].prettify(formatter=None)
    soup2 = BeautifulSoup(output)
    mylist = soup2.find_all('li')
    mylist[i]['class'] = 'active'
    filee = open(str(i) + '.html', 'w') # I changed it to filee to avoid confusion with the file function
    filee.write(str(soup2))
    filee.close()
    navigation[0].clear()

rawDescription: How to add html attributes using python and BeautifulSoup

description: Add html attributes using python and BeautifulSoup


code:
safe = ['savory', 'dessert', 'cake', 'soup', 'drink']

category = raw_input().lower()
if category in safe:
    print(os.listdir(category))
else:
    print('You have typed an invalid category')

rawDescription: Making Python display .txt files from directories


rawDescription: Python compresses entire directory rather than the sole files


rawDescription: split csv column entry on space using python

description: Split csv column entry on space using python


code:
dump_file = open("home/user/dump.sql", "r")
sh.mysql(_in=dump_file)
dump_file.close()

rawDescription: Python Sh Library for MySQL dump import using output redirection (<) pipes


code:
from random import random
from multiprocessing import Pool
from time import sleep

def add_something(i):

    # Sleep to simulate the long calculation
    sleep(random() * 30)
    return i + 1

def run_my_process():

    # Create a process pool
    pool = Pool(100)

    # Callback function that checks results and kills the pool
    def check_result(result):
        print(result)
        if result == 90:
            pool.terminate()

    # Start up all of the processes
    for i in range(100):
        pool.apply_async(add_something, args=[i], callback=check_result)

    pool.close()
    pool.join()

if __name__ == '__main__':
    run_my_process()

rawDescription: Python Multiprocessing help exit on condition


code:
def passer(self, *args, **kw):
    self.assertEqual(1, 1)
passer.__test__ = 1

def failer(self, *args, **kw):
    self.assertEqual(1, 2)
failer.__test__ = 1

rawDescription: Run specific Django tests (with django-nose?)


code:
def list_words(trie):
    my_list = []
    for k,v in trie.items():
        if k != '_':
            for el in list_words(v):
                my_list.append(k+el)
        else:
            my_list.append('')
    return my_list

rawDescription: Python Trie, Unable to list from trie

description: Python Trie, Unable to list from trie


code:
import dateutil.rrule as rrule
import datetime

def hours_aligned(start, end, inc = True):
    if inc: yield start
    rule = rrule.rrule(rrule.HOURLY, byminute = 0, bysecond = 0, dtstart=start)
    for x in rule.between(start, end, inc = False):
        yield x
    if inc: yield end

d = datetime.datetime(2012, 9, 8, 18, 53, 34)
td = datetime.timedelta(hours=2, minutes=34, seconds=5)

for x in hours_aligned(d,d+td):
    print(x)

rawDescription: Splitting a Python datetime into hour-aligned chunks


code:
import pandas as pd

x = [1.0, 2.0, "a", 3.0]
y = ["b", 5.0, 3.0, 7.0]

df = pd.DataFrame({"x":x, "y":y})
df.convert_objects(convert_numeric=True).dropna()

rawDescription: Filtering out values in specific columns with Pandas


code:
index=pd.MultiIndex.from_product([gender_weights.index, age_weights.index], names=["gender","age"])
gender_weights = gender_weights.reindex(index, level=0)
age_weights = age_weights.reindex(index, level=1)
age_weights

rawDescription: Weighting values based on variables

description: Weighting values based on variables


rawDescription: How to convert a python string

description: Convert a python string


rawDescription: Split a string with python re

description: Split a string with python re


code:
import requests
r = requests.get('http://httpbin.org/relative-redirect/4')
r.history
r.history[2].url

rawDescription: I can not get the whole url when the server redirect me by using urllib2.urlopen(url).geturl()


code:
def isdescendant(self, tree):
    """Return True if this tree is a descendant of the specified tree."""
    return tree.isancestor(self)

rawDescription: Trade off between code duplication and performance


code: plot(time1, pl)

rawDescription: Plotting resulting fitted curve with scipy


rawDescription: Search neighboring points using k-d trees


code:
for name in names:
    with open("output.txt", "a") as f:
        f.writelines(name)

rawDescription: Writing a results to a .txt file using csv


code:
import Tkinter as tk
import tkFont

def make_bold():
    current_tags = aText.tag_names("sel.first")
    if "bt" in current_tags:
        aText.tag_remove("bt", "sel.first", "sel.last")
    else:
        aText.tag_add("bt", "sel.first", "sel.last")

lord = tk.Tk()

aText = tk.Text(lord, font=("Georgia", "12"))
aText.grid()

aButton = tk.Button(lord, text="bold", command=make_bold)
aButton.grid()

bold_font = tkFont.Font(aText, aText.cget("font"))
bold_font.configure(weight="bold")
aText.tag_configure("bt", font=bold_font)

lord.mainloop()

rawDescription: Set to bold the selected text using tags


rawDescription: How to optimize math operations on matrix in python

description: Optimize math operations on matrix in python


rawDescription: Associating units with Pandas DataFrame

description: Associating units with Pandas DataFrame


code:
template = 'prefix%s_' % day + '%s'
timeit.timeit("[template % s for s in signals]", 'from __main__ import template, signals')

rawDescription: Python, optimizing a list comprehension for string concatenation


code:
from bokeh.plotting import figure
from bokeh.resources import CDN
from bokeh.embed import components

plot = figure()
plot.circle([1,2], [3,4])

script, div = components(plot, CDN)

rawDescription: Supplemental JavaScript for Bokeh Plot

description: Supplemental JavaScript for Bokeh Plot


code:
config = {
   'webapp2_extras.jinja2': {
     'template_path': 'path/containing/my/templates',
     'environment_args': {
       # Keep generated HTML short
       'trim_blocks': True,
       'extensions': [
         # Support auto-escaping for security
         'jinja2.ext.autoescape',
         # Handy but might not be needed for you
         'jinja2.ext.with_'
         # ... other extensions? ...
       ],
       # Auto-escape by default for security
       'autoescape': True
     },
     # .. other configuration options for jinja2 ...
   },
   # ... other configuration for the app ...
},
# ...
app = webapp2.WSGIApplication(routes, is_debug_enabled, config)

rawDescription: Send HTML email in Appengine [PYTHON] using HTML file


code:
norse = parser.add_argument_group('Norse')
norse.add_argument('-n', '--norse', required=False, help='Run the Norse IPViking scan.', action='store_true')
norse.add_argument('--threshold', required=False, type=int, choices=range(0,101),
                   metavar="[0-100]",
                   help='Threshold (0-100) denoting at what threat level to provide additional data on an IP \
                        address. Default is 49.', default=49)

rawDescription: Python argparse value range help message appearance


code: cv2.imwrite('output.png', out)

rawDescription: Extracting polygon given coordinates from an image using OpenCV


code:
def nonconsecutive_combinations(r, n):
  # first combination, startng at 1, step-size 2
  combination = range(1, r*2, 2)
  # as long as all items are less than or equal to n
  while combination[r-1] <= n:
    yield tuple(combination)
    p = r-1 # pointer to the element we will increment
    a = 1   # number that will be added to the last element
    # find the rightmost element we can increment without
    # making the last element bigger than n
    while p > 0 and combination[p] + a > n:
      p -= 1
      a += 2
    # increment the item and
    # fill the tail of the list with increments of two
    combination[p:] = range(combination[p]+1, combination[p] + 2*(r-p), 2)

rawDescription: Generating non-consecutive combinations

description: Generating non-consecutive combinations


code:
id(y)
id(z)
id(x)

rawDescription: python function incrementing variable in list for no obvious reason

description: Python function incrementing variable in list for no obvious reason


code:
def local_maxima(xval, yval):
    xval = np.asarray(xval)
    yval = np.asarray(yval)

    sort_idx = np.argsort(xval)
    yval = yval[sort_idx]
    gradient = np.diff(yval)
    maxima = np.diff((gradient > 0).view(np.int8))
    return np.concatenate((([0],) if gradient[0] < 0 else ()) +
                          (np.where(maxima == -1)[0] + 1,) +
                          (([len(yval)-1],) if gradient[-1] > 0 else ()))

rawDescription: Finding local maxima of xy data point graph with numpy?


rawDescription: separate a string with multiple seperators AND extract single characters only

description: Separate a string with multiple seperators AND extract single characters only


code:
import json
y = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'grault', 'garply', 'waldo']
json.dumps({'Names': y})

rawDescription: Python - How do I add the backslash characters when formatting a JSON string?


code:
df.set_index('sell_date', inplace=True)
resampled = df.resample('7D', [sum, len])

rawDescription: Creating time series DataFrame from event data


code:
from __future__ import division  # if you still work with Python 2
import datetime

run = 1
enter = '23:59:20'
ext = '00:00:00'
time_format = '%H:%M:%S'
enter_time = datetime.datetime.strptime(enter, time_format)
ext_time = datetime.datetime.strptime(ext, time_format)
if enter_time > ext_time:
    ext_time += datetime.timedelta(hours=24)
t_diff = ext_time - enter_time
elapsed_time = t_diff.total_seconds() / 3600
speed = run / elapsed_time
print(speed)

rawDescription: How to add 24 to the %H part of the enter variable, then store it as the same variable?

description: Add 24 to the %H part of the enter variable, then store it as the same variable


code:
from myapp import app

# logging stuff
# app.logger.setHandler(...)

# more configuration

# do some stuff for apache (?)

rawDescription: Flask application logfile is not written under Apache deployment


code:
x = np.arange(1000)
print(x.flags.owndata)      # x "owns" its data
# True
print(x.base is None)       # its base is therefore 'None'
# True

a = x.reshape(100, 10)      # a is a reshaped view onto x
print(a.flags.owndata)      # it therefore "borrows" its data
# False
print(a.base is x)          # its .base is x
# True

rawDescription: Size of numpy strided array/broadcast array in memory?


code:
L = []

for index,row in d.columns:
    c = str(index) + '/' + str(row)
    L.append(c)

rawDescription: Reshaping pandas DataFrame

description: Reshaping pandas DataFrame


code: s = u''.join(unichr(c) for c in xrange(0x10ffff+1))

rawDescription: In Python, how to list all characters matched by POSIX extended regex `[:space:]`?


code:
output = list(gen1())
for index, value in enumerate(gen2()):
    output[index] += value

rawDescription: Adding the results of multiple functions


rawDescription: Text parsing convert equation blocks to Python statements


code: gene = this_re.group(1)

rawDescription: Which python re module to pick for translating a perl regular expression


rawDescription: How to make if-elif conditionals shorter for parsing

description: Make if-elif conditionals shorter for parsing


code:
class Bar(object):
  def __init__(self, v=42):
    self.val = v

rawDescription: Get fully qualified class name of an object in python


code:
class Base(object):
    def get_crumbs(self):
        crumbs = []
        for cls in type(self).__mro__:
            crumbs.extend(getattr(cls, 'crumbs', ()))
        return tuple(crumbs)
class A(Base):
    crumbs = ('un chasseur',)
class B(A):
    crumbs = ('sachant chasser',)
class C(B):
    crumbs = ('sans son chien', 'est un bon chasseur')
c = C()
c.get_crumbs()

rawDescription: Concatenate class variable through inheritance?


code:
def use_multinomial(length, num_points):
    probs = ones(length)/float(length)
    return multinomial(1, probs, num_points)

def use_rand(length, num_points):
    return [randint(1,length) for _ in range(num_points)]

rawDescription: sampling integers uniformly efficiently in python using numpy/scipy

description: Sampling integers uniformly efficiently in python using numpy/scipy


code:
from sklearn.datasets import load_iris
iris = load_iris
type(iris.data)

rawDescription: Remove a specific feature in scikit learn


code:
import urllib2
handlerClass = getattr(urllib2, 'HTTPHandler')

rawDescription: Initialise class object by name

description: Initialise class object by name


code:
from string import digits
from random import choice
''.join(choice(digits) for i in xrange(4))

rawDescription: what is the best way to generate a reset token in python?

description: What is the best way to generate a reset token in python


code:
with open('path/to/file') as infile:
    keys = infile.readline().split()
    values = infile.readline().strip().split('\t')

    answer = {}
    for i,key in enumerate(keys):
        answer[key] = values[i]

rawDescription: Reading key value pair from a tab delimited file in python


code: line.split(None, 5)

rawDescription: extract a number and the string after it

description: Extract a number and the string after it


code:
marked = Required('name')
marked == 'name'
d = {}
d[marked] = 'hello'
d['name']
isinstance(marked, Required)

rawDescription: Thin proxy class for hashables

description: Thin proxy class for hashables


code:
P[np.arange(M)[:, None, None], np.arange(N)[:, None], np.arange(2),
  indices[..., None]]

rawDescription: Correctly indexing a multidimensional Numpy array with another array of indices


code: from socketserver import TCPServer, ForkingTCPServer

rawDescription: Python: one single module (file .py) for each class?


code:
checkbox_1 = Checkbutton(root, text='1   ', command=checkbutton_value)
checkbox_1.pack()

rawDescription: Python, Tkinter, Checkbutton: Is there a way to check on/off value


code:
class Neg():
    def __init__(self, x):
        self.x = x

    def __cmp__(self, other):
        return -cmp(self.x, other.x)

def maxheappush(heap, item):
    heapq.heappush(heap, Neg(item))

def maxheappop(heap):
    return heapq.heappop(heap).x

rawDescription: built-in max heap API in Python

description: Built-in max heap API in Python


code:
counts = collections.defaultdict(int) # Available since 2.5
for quals in qualsin:
    counts[quals] += 1

rawDescription: Iterate over a list that contain duplicate elements


code:
def do_request(url, token, json_data=None, mode="get"):
    res, code = do_raw_request(url, token, json_data, mode)
    if code == 200:
       return (json.dumps(r.json(), indent=2), r.status_code)
    return res, code

rawDescription: Better way to write this Python function because of If conditions


rawDescription: Constructing String Without Concatenation in Python 2.7


code:
#creating the table
op.create_table(
    'srv_feed_return_type',
    sa.Column('id', sa.Integer, Sequence('srv_feed_r_t_seq'),primary_key=True),
    sa.Column('name', sa.String(50), nullable=False),
    sa.Column('created', sa.DateTime, server_default=func.now(), nullable=False),
    sa.Column('created_by', sa.String(50), nullable=False),
    sa.Column('last_updated', sa.DateTime, nullable=False),
    sa.Column('last_updated_by', sa.String(50), nullable=False)
)

rawDescription: alembic and getting the last inserted value

description: Alembic and getting the last inserted value


rawDescription: Choosing random items from a Spark GroupedData Object


code: retVal = retVal.strftime('desired format')

rawDescription: converting a datetime object

description: Converting a datetime object


rawDescription: Evaluating values within a dictionary for different keys


rawDescription: python- pandas read_excel getting wrong numbers for index_col

description: Python- pandas read_excel getting wrong numbers for index_col


code:
for n in range(1, 8):
  linecache.getline('file.txt', n)

rawDescription: Count line no. using python

description: Count line no. using python


code:
def new_hand(self):
    with self.condition:
        while len(self.players) < 2:
            self.condition.wait()
        players = self.players
    # all your existing sequential logic

rawDescription: Multiplayer Gaming via python

description: Multiplayer Gaming via python


code:
def recursive_element_count(ob):
    if isinstance(ob, list):
        return sum(recursive_element_count(elem) for elem in ob)
    return 1

a = [1, 2, [3, 4], 5]
recursive_element_count(a)

rawDescription: count number of elements with a list that also contains a list

description: Count number of elements with a list that also contains a list


code:
import re

soup.findAll('a', {'onclick': re.compile(r'importantline')})

rawDescription: Passing partial attributes into Beautiful Soup findall Function


code:
from functools import wraps

def ajax_login_required(view_func):
    @wraps(view_func)
    def wrapper(request, *args, **kwargs):
        if request.user.is_authenticated():
            return view_func(request, *args, **kwargs)
        json = simplejson.dumps({ 'not_authenticated': True })
        return HttpResponse(json, mimetype='application/json')
    return wrapper

rawDescription: Django authentication and Ajax - URLs that require login


code:
s.index = pd.to_datetime(s.index)
s.index

rawDescription: How to combine a hierarchical date and time index into a single datetime index in Pandas?

description: Combine a hierarchical date and time index into a single datetime index in Pandas


rawDescription: How to quickly grab specific indices from a numpy array?

description: Quickly grab specific indices from a numpy array


code: np.linspace(min(days), max(days), 6)

rawDescription: Assigning histogram bin to each data point


code:
self.struct1 = self.struct1()
self.struct2 = self.struct2()

rawDescription: How to handle data in python similar to IDL structures?

description: Handle data in python similar to IDL structures


code: c.groupby(['GeoName', 'IndustryClassification', 'Description', 'ComponentName']).size().nlargest(3)

rawDescription: pandas: Perform multiple commands with a for loop

description: Pandas: Perform multiple commands with a for loop


rawDescription: How does a for loop containing a function work?


code:
blocks_to_read = 3
blk_begin = 'A'
blk_end = '$$'

with open('35916503.txt', 'r') as f:
    fn = 1
    data = []
    write_block = False
    for line in f:
        if fn > blocks_to_read:
            break
        line = line.strip()
        if line == blk_begin:
            write_block = True
        if write_block:
            data.append(line)
        if line == blk_end:
            write_block = False
            with open(str(fn) + '.txt', 'w') as fout:
                fout.write('\n'.join(data))
                data = []
            fn += 1

rawDescription: How can I split a text file into multiple text files using python?

description: Split a text file into multiple text files using python


rawDescription: Get levels (contour) of a scalar field (Matplotlib / Python)


rawDescription: How to Open, Read, and Write files in Python 2.7 -- Converting code from fortran 90 to Python


code: a2.extend(x + '_111' for x in a1 if all(x not in y for y in a2))

rawDescription: partial match between two arrays in python

description: Partial match between two arrays in python


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://justbet.co.ke/index.php?option=com_justbet&league=58&Itemid=1")

# wait for the page to load
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".razrada")))

for row in driver.find_elements_by_css_selector(".razrada > tbody > tr"):
    print([td.text.replace("\n", " ")
           for td in row.find_elements_by_css_selector("table.options td.option")])

rawDescription: Selenium and phantomjs not opening javascript page


rawDescription: reshaping data frame in pandas

description: Reshaping data frame in pandas


code:
import threading
from dns import resolver

class Resolver(threading.Thread):
    def __init__(self, address, result_dict):
        threading.Thread.__init__(self)
        self.address = address
        self.result_dict = result_dict

    def run(self):
        try:
            result = resolver.query(self.address)[0].to_text()
            self.result_dict[self.address] = result
        except resolver.NXDOMAIN:
            pass

def main():
    infile = open("domainlist", "r")
    intext = infile.readlines()
    threads = []
    results = {}
    for address in [address.strip() for address in intext if address.strip()]:
        resolver_thread = Resolver(address, results)
        threads.append(resolver_thread)
        resolver_thread.start()

    for thread in threads:
        thread.join()

    outfile = open('final.csv', 'w')
    outfile.write("\n".join("%s,%s" % (address, ip) for address, ip in results.iteritems()))
    outfile.close()

if __name__ == '__main__':
    main()

rawDescription: Increasing throughput in a python script


code:
class PerlLikeDict( dict ):
    pattern_type= type(re.compile(""))
    def __getitem__( self, key ):
        if key in self:
            return super( PerlLikeDict, self ).__getitem__( key )
        for k in self:
            if type(k) == self.pattern_type:
                if k.match(key):
                    return self[k]
        raise KeyError( "key %r not found" % ( key, ) )

rawDescription: How can I read Perl data structures from Python?

description: Read Perl data structures from Python


code:
import argparse

def create_parser():
    parser = argparse.ArgumentParser(description="Args for B.py")
    parser.add_argument("--param1B", type=int)
    parser.add_argument("--param2B", type=int)
    return parser

rawDescription: Python: "importing" input arguments

description: Python: "importing" input arguments


rawDescription: How can i split a string into two on the first occurrence of a character

description: Split a string into two on the first occurrence of a character


code:
from random import random, randint, choice

def randomExpression(prob):
    p = random()
    if p > prob:
        return Number(randint(1, 100))
    elif randint(0, 1) == 0:
        return ParenthesizedExpression(randomExpression(prob / 1.2))
    else:
        left = randomExpression(prob / 1.2)
        op = choice(["+", "-", "*", "/"])
        right = randomExpression(prob / 1.2)
        return BinaryExpression(left, op, right)

for i in range(10):
    print(randomExpression(1))

rawDescription: Is there a way to autogenerate valid arithmetic expressions?


code:
from difflib import SequenceMatcher

max_ratio = 0.9

c = [i for i, v in enumerate(a)
     if not any(map(lambda x: SequenceMatcher(None, v, x).ratio()>=max_ratio, b))]

rawDescription: Subtract List B from List A, but keeping the List A index and using difflib string similarity


code:
names = ['john', 'peter', 'olive']
order = [2, 1, 0]
decorated = zip(order, names)
decorated
sorted_decorated = sorted(decorated)
sorted_decorated
undecorated = zip(*sorted_decorated)[1]
undecorated

rawDescription: How can I sort list by second element without using lambda?

description: Sort list by second element without using lambda


code:
import matplotlib
from matplotlib import pyplot as plt
from pylab import *

img = ones((5,5))
img[1][1] = 2

cdict = {'red': ((0.0, 0.0, 0.0),
                (0.5, 1.0, 0.7),
                     (1.0, 1.0, 1.0)),
             'green': ((0.0, 0.0, 0.0),
                       (0.5, 1.0, 0.0),
                       (1.0, 1.0, 1.0)),
             'blue': ((0.0, 0.0, 0.0),
                      (0.5, 1.0, 0.0),
                     (1.0, 0.5, 1.0))}

my_cmap = matplotlib.colors.LinearSegmentedColormap('my_colormap',cdict,256)
plt.pcolor(img,cmap=my_cmap)
plt.colorbar()
plt.show()

rawDescription: Customize colorbar in matplotlib

description: Customize colorbar in matplotlib


code:
with open("file.txt", "w") as f:
    print("Hello World!", file=fd)

rawDescription: Better method of writing stdout to file

description: Better method of writing stdout to file


code:
def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

rawDescription: How can I find all the combinations of elements in a set of arrays?

description: Find all the combinations of elements in a set of arrays


code:
def get_latest_comments(request, seconds_old):
    """
    Returns comments that have been created since the last given number of seconds
    have elapsed.
    """

    # Query comments since the past X seconds
    comments_since = datetime.datetime.now() - datetime.timedelta(seconds=seconds_old)
    comments = Comments.objects.filter(created__gte=comments_since)

    # Return serialized data or whatever you're doing with it
    return HttpResponse(simplejson.dumps(comments),mimetype='application/json')

rawDescription: how to auto-update a Django page only when required?

description: Auto-update a Django page only when required


code: eval('lambda: a', ...)

rawDescription: Why are closures broken within exec?

description: Why are closures broken within exec


code:
import os
os.environ['PYTHONINSPECT'] = '1'

rawDescription: tell whether python is in -i mode

description: Tell whether python is in -i mode


code: "this is224$# a ths".translate(None,punctuation)

rawDescription: How to delete certain words from a variable or a list python

description: Delete certain words from a variable or a list python


code: circle._circumference_is_set = True

rawDescription: Using descriptor class to raise RuntimeError when user tries to change object's value


code: counts = collections.Counter(itertools.chain.from_iterable(set(l) for l in words))

rawDescription: How do I create something similiar to a "set intersection" that allows for an item to be missing from individual sets n / 1-or-more times?

description: Create something similiar to a "set intersection" that allows for an item to be missing from individual sets n / 1-or-more times


rawDescription: Pandas newbie: How do I assign values based on content of columns?


rawDescription: Django region data MultiPolygonField

description: Django region data MultiPolygonField


code:
# Uncomment the next line if using Python 2.x...
# from __future__ import division
class Rand48(object):
    def __init__(self, seed):
        self.n = seed
    def seed(self, seed):
        self.n = seed
    def srand(self, seed):
        self.n = (seed << 16) + 0x330e
    def next(self):
        self.n = (25214903917 * self.n + 11) & (2**48 - 1)
        return self.n
    def drand(self):
        return self.next() / 2**48
    def lrand(self):
        return self.next() >> 17
    def mrand(self):
        n = self.next() >> 16
        if n & (1 << 31):
            n -= 1 << 32
        return n

rawDescription: is there any drand48() equivalent in python or a wrapper to it?

description: Is there any drand48() equivalent in python or a wrapper to it


code: np.arange(3)[:, None]

rawDescription: Index 2D numpy array by a 2D array of indices without loops


code:
data.columns = cols      # we need the old col names for concat
out_df = pd.concat([header,data])    # do the concat
out_df = out_df.reset_index(drop = True)  # reset index (if you want to)
out_df.to_csv("out.csv")   #write it. out_df.to_csv("out.csv", index = False) if you don't want index in output

rawDescription: Pandas - read_table read selected lines

description: Pandas - read_table read selected lines


code: set(x) == set(y)

rawDescription: Determine if 2 lists have the same elements, regardless of order?


code:
Code
import math, sys

def stringcount(v):
    """mac"""
    return len(bin(v)) - 3

def log_2(v):
    """mac"""
    return int(round(math.log(v, 2), 0)) # 2**101 generates 100.999999999

def log_e(v):
    """bp on mac"""
    return int(round(math.log(v)/0.69314718055994529, 0))  # 0.69 == log(2)

def bitcounter(v):
    """John Y on mac"""
    r = 0
    while v > 1 :
        v >>= 1
        r += 1
    return r

def olgn(n) :
    """outis"""
    if n < 1:
        return -1
    low = 0
    high = sys.getsizeof(n)*8 # not the best upper-bound guesstimate, but...
    while True:
        mid = (low+high)//2
        i = n >> mid
        if i == 1:
            return mid
        if i == 0:
            high = mid-1
        else:
            low = mid+1

def hashlookup(v):
    """mac on brone -- limit: v < 2**131"""
#    def prepareTable(max_log2=130) :
#        hash_table = {}
#        for p in range(1, max_log2) :
#            hash_table[2**p] = p
#        return hash_table

    global hash_table
    return hash_table[v]

def lookup(v):
    """brone -- limit: v < 2**11"""
#    def prepareTable(max_log2=10) :
#        log2s_table=[0]*((1<<max_log2)+1)
#        for i in range(max_log2+1):
#            log2s_table[1<<i]=i
#        return tuple(log2s_table)

    global log2s_table
    return log2s_table[v]

def bitwise(v):
    """Mark Byers -- limit: v < 2**32"""
    b = (0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000)
    S = (1, 2, 4, 8, 16)
    r = 0
    for i in range(4, -1, -1) :
        if (v & b[i]) :
            v >>= S[i];
            r |= S[i];
    return r

def unrolled_bitwise(v):
    """x4u on Mark Byers -- limit:   v < 2**33"""
    r = 0;
    if v > 0xffff :
        v >>= 16
        r = 16;
    if v > 0x00ff :
        v >>=  8
        r += 8;
    if v > 0x000f :
        v >>=  4
        r += 4;
    if v > 0x0003 :
        v >>=  2
        r += 2;
    return r + (v >> 1)

def ilog(v):
    """Gregory Maxwell - (Original code: B. Terriberry) -- limit: v < 2**32"""
    ret = 1
    m = (not not v & 0xFFFF0000) << 4;
    v >>= m;
    ret |= m;
    m = (not not v & 0xFF00) << 3;
    v >>= m;
    ret |= m;
    m = (not not v & 0xF0) << 2;
    v >>= m;
    ret |= m;
    m = (not not v & 0xC) << 1;
    v >>= m;
    ret |= m;
    ret += (not not v & 0x2);
    return ret - 1;

# following table is equal to "return hashlookup.prepareTable()"
hash_table = {...} # numbers have been cut out to avoid cluttering the post

# following table is equal to "return lookup.prepareTable()" - cached for speed
log2s_table = (...) # numbers have been cut out to avoid cluttering the post

rawDescription: Finding the exponent of n = 2**x using bitwise operations [logarithm in base 2 of n]


rawDescription: How to read in metadata (with tags) from a text file using Python

description: Read in metadata (with tags) from a text file using Python


code:
def int_to_bool_list(num):
   bin_string = format(num, '04b')
   return [x == '1' for x in bin_string[::-1]]

rawDescription: Convert 4-bit integer into Boolean list

description: Convert 4-bit integer into Boolean list


code:
[[('Rami', 'PERSON'), ('Eid', 'PERSON')], [('Stony', 'ORGANIZATION'), ('Brook', 'ORGANIZATION'), ('University', 'ORGANIZATION')], [('NY', 'LOCATION')]]

['Rami Eid', 'Stony Brook University', 'NY']

[('Rami Eid', 'PERSON'), ('Stony Brook University', 'ORGANIZATION'), ('NY', 'LOCATION')]

rawDescription: Extract list of Persons and Organizations using Stanford NER Tagger in NLTK


rawDescription: What is the client for spyne with json document protocol?


code:
numbers = ['10', '8', '918', '101010']
numbers = sorted(numbers, key=int)
print(numbers)

rawDescription: Python: sorting string numbers not lexicographically


code:
import os
os.system("ssh pi@theraspberrypi ./myscript")

rawDescription: How to run a bash script from another computer?

description: Run a bash script from another computer


code:
if List[listpos] < 35:
    print("Pink")
elif List[listpos] < 65:
    ...

rawDescription: PYTHON parameter passing with lists

description: PYTHON parameter passing with lists


code: '<table border="1" class="dataframe my_class" id = "my_id">...'

rawDescription: JS dataTables from pandas

description: JS dataTables from pandas


code: ABCDEFGHIJKL

rawDescription: Python mmap.move()

description: Python mmap.move()


code:
class PrintObject(object):
    def __repr__(self):
        return 'repr'

    def __str__(self):
        return 'str'

    def __unicode__(self):
        return 'unicode'

rawDescription: What is the difference between these codes, and what does the repr do?


code:
Parent.fields
Child.fields
Child.fields is Parent.fields
Child.fields['name'] = 'Child'
Child.fields
Parent.fields

rawDescription: How to inherit a class attribute that is a dict and make it unique?

description: Inherit a class attribute that is a dict and make it unique


rawDescription: Python current timestamp for UTC with milisecond accuracy


code:
[xx,yy] = np.meshgrid(xvalues, yvalues)

plt.plot(x,y, marker='.', color='k', linestyle='none')

rawDescription: What is purpose of meshgrid in Python?

description: What is purpose of meshgrid in Python


code:
from cStringIO import StringIO
import csv
out = StringIO()
writer = csv.writer(out)
writer.writerow(['Data with , commas and nested " quotes', 'works just fine'])
out.getvalue()

rawDescription: How do I write a comma as a normal text in a CSV file?(the double quote method doesn't work)

description: Write a comma as a normal text in a CSV file?(the double quote method doesn't work)


code:
list(zip([1, 3, 5], [2, 4, 6]))
tmp = itertools.izip(*[itertools.islice(lst, i, None, 2) for i in range(2)])
tmp
list(tmp)

rawDescription: Python: How to transform a 'flat' sequence into a sequence of tuples?


code:
import numpy as np
import cv2

image_src = cv2.imread("input.png")
gray = cv2.cvtColor(image_src, cv2.COLOR_BGR2GRAY)
ret, gray = cv2.threshold(gray, 250,255,0)

image, contours, hierarchy = cv2.findContours(gray, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
largest_area = sorted(contours, key=cv2.contourArea)[-1]
mask = np.zeros(image_src.shape, np.uint8)
cv2.drawContours(mask, [largest_area], 0, (255,255,255,255), -1)
dst = cv2.bitwise_and(image_src, mask)
mask = 255 - mask
roi = cv2.add(dst, mask)

roi_gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
ret, gray = cv2.threshold(roi_gray, 250,255,0)
image, contours, hierarchy = cv2.findContours(gray, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

max_x = 0
max_y = 0
min_x = image_src.shape[1]
min_y = image_src.shape[0]

for c in contours:
    if 150 < cv2.contourArea(c) < 100000:
        x, y, w, h = cv2.boundingRect(c)
        min_x = min(x, min_x)
        min_y = min(y, min_y)
        max_x = max(x+w, max_x)
        max_y = max(y+h, max_y)

roi = roi[min_y:max_y, min_x:max_x]
cv2.imwrite("roi.png", roi)

rawDescription: How to extract white region in an image

description: Extract white region in an image


code:
class MyJSONEncoder(DjangoJSONEncoder):
    def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.isoformat()
        else:
            return super(MyJSONEncoder, self).default(o)

rawDescription: Changing default date printing format in python


rawDescription: How to get full windows path in python

description: Get full windows path in python


code:
inds = np.array(inds)
inds

rawDescription: How to extract a list of elements given by their indices from a numpy array efficiently?

description: Extract a list of elements given by their indices from a numpy array efficiently


code:
import datetime
start_date = datetime.date(2015, 12, 16)
end_date = start_date + datetime.timedelta(days=7)
person_1.tests.filter(date__range=(start_date, end_date))

rawDescription: django sort the query elements in a weekly monthly daily fashion

description: Django sort the query elements in a weekly monthly daily fashion


code:
import re

d = {'100022441':{'@frankgaffney': 0, '@DavidBartonWB': 0}}
e = r'(@\w+)'

def parser(line):
   key, tweet = line.split('\t')
   data = d.get(key)
   if data:
      mentions = re.findall(e, tweet)
      for mention in mentions:
          if mention in data.keys():
              d[key][mention] += 1

with open('~/File.txt') as f:
    for line in f:
       parser(line)

print(d)

rawDescription: Python multiprocessing: Reading a file and updating a dictionary


code:
prog = re.compile('^.*' + re.escape(MAC) + '.*$', re.MULTILINE)
lines = prog.findall(all_blocks)

rawDescription: searching a string and printing the complete line containing that string

description: Searching a string and printing the complete line containing that string


code:
adds = ['', ',', '.', '?', '!', ':']
newlist = [item+add for item in oldlist for add in adds]

rawDescription: Extend every single string in a list with punctuation


code:
# Write a conditional format over a range DOES NOT WORK
worksheet1.conditional_format('A1:K12', {'type': 'cell',
                                         'criteria': '=MOD(ROW(),2)',
                                         'value': 0,
                                         'format': format1})

# Write another conditional format over the same range also DOES NOT WORK
worksheet1.conditional_format('A1:K12', {'type': 'cell',
                                         'criteria': '=MOD(ROW(),2)',
                                         'value': 1,
                                         'format': format2})

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


code:
''' Print text in a scrolling region of the terminal above a fixed line for input

    Written by PM 2Ring 2016.05.29

    Python 2 / 3 version
'''

from __future__ import print_function
import sys
import readline
from time import sleep

if sys.version_info > (3,):
    # Get the (current) number of lines in the terminal
    import shutil
    height = shutil.get_terminal_size().lines - 1

    stdout_write_bytes = sys.stdout.buffer.write
else:
    height = 40
    input = raw_input
    stdout_write_bytes = sys.stdout.write

# Some ANSI/VT100 Terminal Control Escape Sequences
CSI = b'\x1b['
CLEAR = CSI + b'2J'
CLEAR_LINE = CSI + b'2K'
SAVE_CURSOR = CSI + b's'
UNSAVE_CURSOR = CSI + b'u'

GOTO_INPUT = CSI + b'%d;0H' % (height + 1)

def emit(*args):
    stdout_write_bytes(b''.join(args))

def set_scroll(n):
    return CSI + b'0;%dr' % n

emit(CLEAR, set_scroll(height))

try:
    while True:
        #Get input
        emit(SAVE_CURSOR, GOTO_INPUT, CLEAR_LINE)
        try:
            n = int(input('Number: '))
        except ValueError:
            continue
        finally:
            emit(UNSAVE_CURSOR)

        #Display some output
        for i in range(n):
            print(i)
            sleep(0.1)

except KeyboardInterrupt:
    #Disable scrolling, but leave cursor below the input row
    emit(set_scroll(0), GOTO_INPUT, b'\n')

rawDescription: Print text before input() prompt in python


code:
class ServiceAdmin(admin.ModelAdmin):
    [...]

class VariationAServiceAdmin(admin.ModelAdmin):
    [...]

class VariationBServiceAdmin(admin.ModelAdmin):
    [...]

rawDescription: If I use Multi Table Inheritance for a set of related classes can they have separate admins?


code: caps = re.findall(b'data-name="([^"]*?)"', website.content)

rawDescription: Find all text in HTML web scrape after a specific string (python3)


rawDescription: Separate list in equal steps

description: Separate list in equal steps


code:
Scores = [3, 7, 3, 2, 1, 5, 1]
Scores = [i-0.5 if i<3 else i for i in Scores]

animalIDs = [1, 2, 3, 4, 5, 6, 7]
animals2Delete = [id for id, score in zip(animalIDs, Scores) if score < 2]
#this could be made in a number of ways, this is just one way.

rawDescription: How to use python's list comprehensions to execute the following matlab code?

description: Use python's list comprehensions to execute the following matlab code


code: p = regex.compile(u"\p{Lu}")

rawDescription: Python regex for unicode capitalized words


code:
import string

f = file("/file.txt",'r') #Opens the file
data = f.read() #reads the file into data
if not len(data) > 4: #Checks if anything is in the file, if not creates the variables (doesn't have to be four)

    variable1 = "fi"
    variable2 = 2
else:
    data = string.split(data,"\n") #Splits up the data in the file with the new line and removes the new line
    variable1 = data[0] #the first part of the split
    variable2 = int(data[1]) #Converts second part of strip to the type needed

rawDescription: Change variable permanently

description: Change variable permanently


code:
def atoi(s):
    rtr, sign=0, 1
    s=s.strip()
    if s[0] in '+-':
        sc, s=s[0], s[1:]
        if sc=='-':
            sign=-1

    for c in s:
        rtr=rtr*10 + ord(c) - ord('0')

    return sign*rtr

rawDescription: Convert String to Int without int()

description: Convert String to Int without int()


code:
                              #vvv
self.fileOpen = Gtk.ToolButton.new(
        Gtk.Image.new_from_icon_name("document-open",
                                     Gtk.IconSize.LARGE_TOOLBAR),
        "Open")
self.fileOpen.connect("clicked", self.on_FileOpenStandard_activate)
toolbar.insert(self.fileOpen, -1)

rawDescription: What is the non-deprecated way to display a stock icon in GTK3?


rawDescription: How to edit audio files in Python?

description: Edit audio files in Python


code:
import subprocess
subprocess.check_output('cat /etc/hosts | grep dahn', shell=True)

rawDescription: Python resolve shell backquoted string

description: Python resolve shell backquoted string


code:
import numpy as np

Scores = np.array( [3, 7, 3, 2, 1, 5, 1] )
Scores[ Scores < 3 ] = Scores[ Scores < 3 ] - 0.5

animalIDs = np.array( [1, 2, 3, 4, 5, 6, 7] )
animals2Delete = animalIDs[ Scores < 2 ]
#Again, just one way to do it.


code:
# plain NumPy version
import numpy as np

def foobar(mixinsize, count, xs, mixins, acc):
    for i in xrange(count):
        k = xs[i]
        acc[k:k + mixinsize] += mixins[i,:]

# LLVM compiled version
from numba import jit, void, int64, double
signature = void(int64,int64,int64[:],double[:,:],double[:])
foobar_jit = jit(signature)(foobar)

rawDescription: How to shove this loop into numpy?

description: Shove this loop into numpy


code:
import inspect
import types

class Constructor(object):
    def __init__(self, memoize_for_request=True, params=None):
        self.memoize_for_request = memoize_for_request
        self.params = params
    def __call__(self):
        def key_func():
            print('key_func called with params:')
            for k, v in self.params.items():
                print('  {}: {!r}'.format(k, v))
        key_func()

def cache_response(key_func):
    def decorator(fn):
        def decorated(*args, **kwargs):
            key_func()
            fn(*args, **kwargs)
        return decorated
    return decorator

def example_class_decorator(cls):
    key_func = Constructor(  # define key_func here using cls.key
        memoize_for_request=True,
        params={'updated_at': cls.key} # use decorated class's attribute
    )
    # create and apply cache_response decorator to marked methods
    # (in Python 3 use types.FunctionType instead of types.UnboundMethodType)
    decorator = cache_response(key_func)
    for name, fn in inspect.getmembers(cls):
        if isinstance(fn, types.UnboundMethodType) and hasattr(fn, 'marked'):
            setattr(cls, name, decorator(fn))
    return cls

def decorate_me(fn):
    setattr(fn, 'marked', 1)
    return fn

class CacheMix(object):
    def __init__(self, *args, **kwargs):
        super(CacheMix, self).__init__(*args, **kwargs)

    @decorate_me
    def list(self, *args, **kwargs):
        classname = self.__class__.__name__
        print('list() method of {} object called'.format(classname))

@example_class_decorator
class ListView(CacheMix):
    key = 'test_key'

listview = ListView()
listview.list()

rawDescription: How to pass self into a decorator?

description: Pass self into a decorator


code:
def specType(SpT):
    return '{}{}'.format('MLTY'[int(SpT//10)], SpT % 10) if 0.0 <= SpT <= 39.9 else SpT

rawDescription: Python one-liner to convert float to string


code:
# file env_set.py
import os
import sys

if sys.argv[0] and "SETENV" in os.environ:
  setenv = os.environ["SETENV"]
  del os.environ["SETENV"]
  os.execvp("bash", ["bash", "-c",
        "source " + setenv + "; exec python " + sys.argv[0] + ' "${@}"',
        "--"] + sys.argv[1:])

rawDescription: How to get the environment variable set by a bash script from inside a python script?

description: Get the environment variable set by a bash script from inside a python script


code:
import numpy as np
import matplotlib.pyplot as plt
from geopandas import GeoDataFrame
from matplotlib.mlab import griddata
from shapely.geometry import Polygon, MultiPolygon

def collec_to_gdf(collec_poly):
    """Transform a `matplotlib.contour.QuadContourSet` to a GeoDataFrame"""
    polygons, colors = [], []
    for i, polygon in enumerate(collec_poly.collections):
        mpoly = []
        for path in polygon.get_paths():
            try:
                path.should_simplify = False
                poly = path.to_polygons()
                # Each polygon should contain an exterior ring + maybe hole(s):
                exterior, holes = [], []
                if len(poly) > 0 and len(poly[0]) > 3:
                    # The first of the list is the exterior ring :
                    exterior = poly[0]
                    # Other(s) are hole(s):
                    if len(poly) > 1:
                        holes = [h for h in poly[1:] if len(h) > 3]
                mpoly.append(Polygon(exterior, holes))
            except:
                print('Warning: Geometry error when making polygon #{}'
                      .format(i))
        if len(mpoly) > 1:
            mpoly = MultiPolygon(mpoly)
            polygons.append(mpoly)
            colors.append(polygon.get_facecolor().tolist()[0])
        elif len(mpoly) == 1:
            polygons.append(mpoly[0])
            colors.append(polygon.get_facecolor().tolist()[0])
    return GeoDataFrame(
        geometry=polygons,
        data={'RGBA': colors},
        crs={'init': 'epsg:4326'})

data = np.genfromtxt('temp.csv', delimiter=',')
x = data[..., 1]
y = data[..., 2]
z = data[..., 3]
xi = np.linspace(x.min(), x.max(), 200)
yi = np.linspace(y.min(), y.max(), 200)
zi = griddata(x, y, z, xi, yi, interp='linear') # You could also take a look to scipy.interpolate.griddata

nb_class = 15 # Set the number of class for contour creation
# The class can also be defined by their limits like [0, 122, 333]
collec_poly = plt.contourf(
    xi, yi, zi, nb_class, vmax=abs(zi).max(), vmin=-abs(zi).max())

gdf = collec_to_gdf(collec_poly)
gdf.to_json()
# Output your collection of features as a GeoJSON:
# '{"type": "FeatureCollection", "features": [{"type": "Feature", "geometry": {"type": "Polygon", "coordinates": [[[51.563214073747474,
# (...)

rawDescription: Contour plot data (lat,lon,value) within boundaries and export GeoJSON


code: [' '.join(i.split('_')) for i in current_list.split()]

rawDescription: How to add space between strings in Python List without the underscore

description: Add space between strings in Python List without the underscore


rawDescription: pandas DataFrame delete contiguous duplicates

description: Pandas DataFrame delete contiguous duplicates


code:
parent = node()
fchild = node()
schild = node()
wchild = node()
cchild = node()

rawDescription: Python: Parent and Child responding to child-specific changes in boolean values. Why is this happening?


code:
from requests import get
from bs4 import BeautifulSoup
soup = BeautifulSoup(get(url).content)
print(soup.select("#cuerpo div[class^=x]")[:2])

rawDescription: BeautifulSoup: scrape HTML only accessible after clicking "Accept" in the same URL


code:
LofL=[['CAA46951&Homeobox domain&192:248&F&#CDC1C5&NULL&PFAM&Y&433&'],
      ['CAA46951&Homeodomain-like&165:252&S&#CD5B45&NULL&SCOP&Y&433&'],
      ['5330400P12&WD domain, G-beta repeat&131:168&F&#FF8C69&NULL&PFAM&Y&296&'],
      ['5330400P12&WD domain, G-beta repeat&173:210&F&#FF8C69&NULL&PFAM&Y&296&'],
      ['5330400P12&WD40-repeat&1:296&S&#00FF7F&NULL&SCOP&Y&296&'],
      ['AAH62206&Cell division protein&38:311&S&#00CED1&NULL&PFAM&Y&425&'],
      ['AAH62206&P-loop containing nucleoside triphosphate hydrolases&36:279&S&#00FFFF&NULL&SCOP&Y&425&']]

newL=[]
for L in LofL:
    newSubL=[]
    for e in L:
        for s in e.split('&'):
            if s:
                newSubL.append(s)
    newL.append(newSubL)

rawDescription: Finding and splitting at a character from a string inside a list of lists


code:
from pygame.locals import *

import pygame
import sys

GRAVITY = 1.2

class Player:
    def __init__(self, x, y):
        self.rect = pygame.Rect(x, y, 25, 25)
        self.yvel = 0

    def tick(self):
        self.yvel += GRAVITY

        self.rect.y += int(self.yvel)

        if self.rect.y >= 475:
            self.rect.y = 475
            self.yvel = 0

    def set(self, y):
        if y:
            self.yvel = y

class Block:
    def __init__(self, x, y, w, h):
        self.rect = pygame.Rect(x, y, w, h)

class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((500, 500))
        self.player = Player(0, 0)
        self.block = Block(225, 400, 50, 50)

    def main(self):
        right = left = False
        while True:
            self.screen.fill((230, 230, 230))
            pygame.draw.rect(self.screen, (40, 40, 40), self.block.rect)
            pygame.draw.rect(self.screen, (100, 200, 100), self.player.rect)

            pygame.display.flip()
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit(0)
                elif event.type == KEYDOWN:
                    if event.key == K_SPACE:
                        self.player.set(-20)
                    elif event.key == K_RIGHT:
                        right = True
                    elif event.key == K_LEFT:
                        left = True
                elif event.type == KEYUP:
                    if event.key == K_RIGHT:
                        right = False
                    elif event.key == K_LEFT:
                        left = False

            if right:
                self.player.rect.x += 5
                while self.player.rect.colliderect(self.block.rect):
                    self.player.rect.x -= 1
            if left:
                self.player.rect.x -= 5
                while self.player.rect.colliderect(self.block.rect):
                    self.player.rect.x += 1
            self.player.tick()
            if self.player.yvel > 0:
                while self.player.rect.colliderect(self.block.rect):
                    self.player.rect.y -= 1
                    self.player.yvel = 0
            elif self.player.yvel < 0:
                while self.player.rect.colliderect(self.block.rect):
                    self.player.rect.y += 1
                    self.player.yvel = 0

game = Game()
game.main()

rawDescription: Trying to make a "solid" block in pygame but it doesnt work


code:
if (t >=4) and (t < 8):
    if clear_keys:
        event.getKeys()
        clear_keys = False
    else:
        theseKeys = event.getKeys(keyList=['y', 'n'])
        if 'y' in theseKeys:
            Yes.color = 'red'
            No.color = 'white'
        elif 'n' in theseKeys:
            Yes.color = 'white'
            No.color = 'red'

rawDescription: Make text appear based on key press (give user real time feedback) in psychopy


code:
names = ['apple', 'banana', 'orange']
prices1 = ['0.40', '1.20', '0.35']
prices2 = ['0.43', '1.21', '0.34']

fruits = {}     # fruits is now a dictionary, which is indicated by the curly braces
for i in range(len(names)):
    fruits[ names[i] ] = [ prices1[i], prices2[i] ]

print(fruits)

rawDescription: How do I generate a list for each list item

description: Generate a list for each list item


code:
rng = rng[rng.weekday<5]
rng

rawDescription: Pandas: Generate Sequential Timestamp with Jump


rawDescription: python, numpy boolean array: negation in where statement

description: Python, numpy boolean array: negation in where statement


code:
df1["new_column"] = in_both.astype(int).replace({True: 1, False: 2})
df1.head(5)

rawDescription: How to search the elements in a column of a csv in a column of another csv file using python?

description: Search the elements in a column of a csv in a column of another csv file using python


code:
def parse_group(group):
    return [float(n) for n in group.split('\n')]

def get_numbers(string, separator='\n\n'):
    groups = str.split(separator)
    return [parse_group(group) for group in groups]

rawDescription: How to parse a list of list of floats in python?

description: Parse a list of list of floats in python


rawDescription: Python regex list using list

description: Python regex list using list


rawDescription: Relation between 2D KDE bandwidth in sklearn vs bandwidth in scipy


code:
a = np.arange(2*3*4).reshape(2, 3, 4)
a
b = np.arange(3)
np.random.shuffle(b)
b
np.take(a, b, axis=1)

rawDescription: Sort N-D numpy array by another 1-D array


code:
#string = the example you gave
import re
sections = [x.strip() for x in re.split(r'Users of.*',string) if x != '']

rawDescription: parse text using bash/python

description: Parse text using bash/python


code:
if hasattr(obj, "__getitem__"):
    print("Supports")

rawDescription: Check for [] operator

description: Check for [] operator


code:
from bs4 import BeautifulSoup
xml = urllib2.urlopen('http://freegeoip.net/xml/192.168.1.1').read()
soup = BeautifulSoup(xml)
soup.ip.text

rawDescription: Easiest way to sort XML in Python? [Skype Bot]


code:
import itertools as it
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return it.izip_longest(fillvalue=fillvalue, *args)

rawDescription: write a new line text file python every 4 tabs

description: Write a new line text file python every 4 tabs


code: cur.execute( 'SELECT * FROM ipaddr' ).fetchall( )

rawDescription: Python - writing out the result of Popen into a mysql table


code: ui = 1 - 0.5*sum(abs(z_vals - np.average(z_vals)))/(len(z_vals)*np.average(z_vals))

rawDescription: Does NumPy have a Uniformity function?

description: Does NumPy have a Uniformity function


rawDescription: Why isn't my tkinter scrollbar working?

description: Why isn't my tkinter scrollbar working


rawDescription: Regex - Python: Capture three (3) words after a specific word


rawDescription: Algorithm to invert strings of algebraic expressions in Python


code:
import matplotlib.cm as cm
import matplotlib.pyplot as plt
plt.imshow(train_x[0].reshape((28, 28)), cmap = cm.Greys_r)
plt.show()

rawDescription: how to unpack pkl file

description: Unpack pkl file


rawDescription: writing to CSV in python

description: Writing to CSV in python


code:
class Symbol(Basic):
    ...
    def __eq__(self, other):
        if type(self) == type(other):
            return repr(self) == repr(other)
        else:
            return False
    ...

rawDescription: How does sympy work? How does it interact with the interactive Python shell, and how does the interactive Python shell work?


code:
class BaseModel(models.Model):
    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

rawDescription: DRY way to add created/modified by and time


code:
import yaml
try:
    from yaml import CLoader as Loader
except ImportError:
    from yaml import Loader

config_file = "test.yaml"

stream = open(config_file, "r")
sensors = yaml.load(stream, Loader=Loader)

rawDescription: Why is PyYAML spending so much time in just parsing a YAML File?


code:
[([0, 1, 2], [3]),  # idxs of first split as (train, test) tuple
 ([2, 3], [4, 5])]  # idxs of second split as (train, test) tuple

rawDescription: scikit-learn cross validation custom splits for time series data

description: Scikit-learn cross validation custom splits for time series data


rawDescription: How to update a Tix.ComboBox's text?

description: Update a Tix.ComboBox's text


code:
import signal
signal.alarm(TIME_TO_DIE)
# your code goes on

rawDescription: Kill Python script after 60 second in simplest way


code:
def nesting(match): # `match' is a match object like your `m' variable
    ret = 'value'
    for key in match.groups():
        ret = {key: ret}
    return ret

rawDescription: dynamically nesting a python dictionary

description: Dynamically nesting a python dictionary


code: _thread_local = threading.local()

rawDescription: Set global constant cross all the view

description: Set global constant cross all the view


code:
first_n(xrange(100), 10)
list(first_n(xrange(100), 10))

rawDescription: Truncating a python generator

description: Truncating a python generator


rawDescription: python: How to compare values in a list by row?

description: Python: How to compare values in a list by row


code:
for a, b, sum_ab, sum_as_str in sorted(sums, key = lambda x: x[2]):
    print(sum_as_str)

rawDescription: How to store multiple numbers and then add to each individual one

description: Store multiple numbers and then add to each individual one


code:
def isnull2(list1, list2):
    for i, x in enumerate(list1):
        if not x:
            yield list2[i]
        else:
            yield x

list(isnull2(list1, list2))

rawDescription: Python: merge lists or data frames and overwrite missing values


rawDescription: MultiIndex from product of unique values of two indexes


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

# Make the original line...
x = np.linspace(0, 10, 100)
y = np.cos(x)
thickness = 0.01 * x

plt.fill_between(x, y - thickness, y + thickness, color='blue')
plt.show()

rawDescription: How do you make the linewidth of a single line change as a function of x in matplotlib?

description: Make the linewidth of a single line change as a function of x in matplotlib


code: myobj = WrapObj(Command())

rawDescription: Queuing methods to be run on an object by different threads in Python


code: (a['href'] if a else '`NULL`')

rawDescription: TypeError: unsupported operand type(s) for +: 'Tag' and 'str'


code:
indices = np.nonzero(boo[1:] != boo[:-1])[0] + 1
b = np.split(a, indices)
b = b[0::2] if boo[0] else b[1::2]

rawDescription: Splitting numpy array according bool

description: Splitting numpy array according bool


rawDescription: Regex URL Help: Word or Phrase

description: Regex URL Help: Word or Phrase


code:
from operator import mul
from itertools import starmap, izip
sum(starmap(mul, izip(left, right)))
735

rawDescription: Multiply two equal-sized list and sum the result (dot product)


code: "this is the song that never ends"[::-1]

rawDescription: How do I loop a set of strings in reverse in Python?

description: Loop a set of strings in reverse in Python


code:
from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Chrome()  # use Chrome driver for example
driver.get('http://www.marunadanmalayali.com/')

soup = BeautifulSoup(driver.page_source, "html.parser")
l = [i.get('src') for i in soup.find_all('script') if i.get('src')]

__import__('pprint').pprint(l)

rawDescription: Get all the javascript file name and its contents in python perfectly


rawDescription: Reshaping a numpy array in python

description: Reshaping a numpy array in python


code:
for c in self.controls:
    c['cb'].Destroy()
    c['label'].Destroy()
    c['input'].Destroy()

self.controls = []

rawDescription: Best way to remove controls from a wx panel

description: Remove controls from a wx panel


code:
import mock
import unittest
import helper

class HelperTests(unittest.TestCase):
    def test_10_9_utility_is_correct(self):
        with mock.patch('platform.mac_ver', return_value=('10.9', 'foo', 'foo')):
            helper.init_module()
            result = helper.run_utility1()
            print(result)
            assert result == 'Running utility 1 for 10.9 and below'

    def test_10_10_utility_is_correct(self):
        with mock.patch('platform.mac_ver', return_value=('10.10', 'foo', 'foo')):
            helper.init_module()
            result = helper.run_utility1()
            print(result)
            assert result == 'Running utility 1 for 10.10 and above'

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

rawDescription: Testing branches in module-level code in python


code:
broadcasted_x, broadcasted_y = np.broadcast_arrays(x[:, np.newaxis], y)
broadcasted_x
broadcasted_y

rawDescription: Difference between every row and column in two DataFrames (Python / Pandas)


code:
dict1 = {'a': 'first', 'b': 'second', 'c': 3, 'd': ['the', 'fourth']}
dict2 = {'a': 1, 'b':2, 'c':3, 'd':4}
dict3 = {'a': '1', 'b':'two', 'c':'three', 'd': 'fourth'}
list_of_keys = ['a','b','c','d']

pprint_multilines(linelen=15, separator=' ', align='left', align_char=' ',
                  line_separator='-',
                  lists=[[dict1[key] for key in list_of_keys],
                         [dict2[key] for key in list_of_keys],
                         [dict3[key] for key in list_of_keys]])
print

pprint_multilines(linelen=15, separator=' ', align='left', align_char=' ',
                  lists=[[dict1[key] for key in list_of_keys],
                         [dict2[key] for key in list_of_keys],
                         [dict3[key] for key in list_of_keys]])
print

pprint_multilines(linelen=25, separator=' ', align='left', align_char=' ',
                  line_separator='',
                  lists=[[dict1[key] for key in list_of_keys],
                         [dict2[key] for key in list_of_keys],
                         [dict3[key] for key in list_of_keys]])
print

pprint_multilines(linelen=45, separator=' ', align='left', align_char='_',
                  lists=[[dict1[key] for key in list_of_keys],
                         [dict2[key] for key in list_of_keys],
                         [dict3[key] for key in list_of_keys]])
print

pprint_multilines(linelen=45, separator=' ', align='right', align_char=' ',
                  lists=[[dict1[key] for key in list_of_keys],
                         [dict2[key] for key in list_of_keys],
                         [dict3[key] for key in list_of_keys]])

rawDescription: In python, how can I print all the values for the same key from different dictionaries on top of one another?


code:
template = open("fortram_template.for", "rt").read()
data = {"alpha": 0.5, "beta": 100}

with open("fortram_1.for", "wt") as output:
    output.write (template % data)

rawDescription: How to duplicate a file but change a few parameters inside?

description: Duplicate a file but change a few parameters inside


code:
dictionaryNumbers = {'a':10,'b':10,'c':1,'d':1,'e':5,'f':1}
dictionaryNumbers['a'] += 5
dictionaryNumbers['a']

rawDescription: What is an efficient way to increase and set the value of a dictionary key using python?


code: F2 = interp2d(x, y, -z)

rawDescription: Use optimize.minimize from scipy with 2 variables and interpolated function


code:
for n, v in zip(names, values):
    locals()[n] = v

rawDescription: creating variables from external data in python script

description: Creating variables from external data in python script


rawDescription: Python: How to convert array of 4 digits to a larger number, bitwise?


code:
increments = [10, 5, 4, 2, 1]
tenSplits = orderedPossibleSplits(10, increments)
fourSplits = orderedPossibleSplits(4, increments)
results = []
for tenSplit in tenSplits:
    for fourSplit in fourSplits:
        results.append(tenSplit + fourSplit)

rawDescription: How to break down a number with another from list?

description: Break down a number with another from list


rawDescription: Reorder and select subset from dataframe based on other dataframe pandas


code:
values = { 'minute' : 10, 'hour' : 5 }
[ getattr(pd.offsets,k.capitalize())(v) for k,v in values.items() ]

rawDescription: How to construct a TimeGrouper with a DateOffset?

description: Construct a TimeGrouper with a DateOffset


code:
def quicksort(A):
    if len(A) > 1:
        pivot = A[0]
        L = []
        E = []
        R = []
        for i in A:
            if i < pivot:
                L.append(i)
            elif i == pivot:
                E.append(i)
            else:
                R.append(i)
        L = quicksort(L)
        R = quicksort(R)
        return L + E + R
    return A

rawDescription: Python QuickSort returning original input


code:
@classmethod
def test_func(cls, x):
    return cls.cache.setdefault(x, "CACHE STORE")

rawDescription: Have exception hit two except blocks in python


code: '\n\n'.join(a.strip() for a in s1.split(':'))

rawDescription: Parsing string in Python

description: Parsing string in Python


rawDescription: groupby in pandas with different functions for different columns

description: Groupby in pandas with different functions for different columns


code:
def main(argv=None):
    if argv is None:
        argv = sys.argv

rawDescription: Setting the default value of a function input to equal another input in Python


code:
for list3 in ([c[1]/d[1] for c in a for d in b]
                 for a in list1 for b in list2):
  list3function()

rawDescription: Processing list comprehension output element-by-element