rawDescription: Splitting self-intersecting polygon only returned one polygon in shapely in Python


code:
with open(filename, 'rb') as csvfile:
    reader = csv.reader(csvfile)
    fieldnames = remap(next(reader))
    for row in reader:
        row = dict(zip(fieldnames, row))

rawDescription: How to handle csv file with duplicate fieldnames when reading with csv.DictReader?

description: Handle csv file with duplicate fieldnames when reading with csv.DictReader


code:
a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
a
a[a[:,0] > 3] # select rows where first column is greater than 3
a[a[:,0] > 3][:,np.array([True, True, False, True])] # select columns
a[np.ix_(a[:,0] > 3, np.array([True, True, False, True]))]

rawDescription: Select certain rows (condition met), but only some columns in Python/Numpy


rawDescription: How to avoid redundancy when sending commands via pexpect?

description: Avoid redundancy when sending commands via pexpect


rawDescription: Django sub-directory views and import all files from __init__.py


code:
import numpy
mesh_x = numpy.array([0.5,1.0,1.5])
myValues = numpy.zeros_like( mesh_x )
para = [5.8780046, 0.714285714, 2.819250868]
mask = mesh_x > para[1]
myValues[mask] = para[0] * numpy.power(mesh_x[mask] - para[1], para[2])
print(myValues)

rawDescription: Numpy array variable avoid bad calculations


rawDescription: Sharing data between two lists

description: Sharing data between two lists


code:
def merge(a, b):
    if a[-1] not in b:
        return a + b
    ...

rawDescription: Pythonic way to merge two overlapping lists, preserving order


code:
from django.shortcuts import render as render_original
def view_for_all_pages ( request, url_param ):
    render (request, "template.html", { "url_param" : url_param })

rawDescription: How can I get Django to create a unique URL view and page for each URLField entered

description: Get Django to create a unique URL view and page for each URLField entered


code:
p = argparse.ArgumentParser()
subparsers = p.add_subparsers()

option1_parser = subparsers.add_parser('option1')
# Add specific options for option1 here, but here's
# an example
option1_parser.add_argument('param1')
option1_parser.set_defaults(func=do_option1)

option2_parser = subparsers.add_parser('option2')
# Add specific options for option1 here
option2_parser.set_defaults(func=do_option2)

option3_parser = subparsers.add_parser('option3')
# Add specific options for option3 here
option3_parser.set_defaults(func=do_option3)

args = p.parse_args()
args.func(args)

rawDescription: Python Command Line Arguments: Calling a function


code:
items[223] #<-- This is the "Hat" item
items[225] #<-- This is the "Shirt" item

rawDescription: function and classes, usage of __str__

description: Function and classes, usage of __str__


code:
r = np.sqrt((x - pixel_x)**2 + (y - pixel_y)**2)
single_image = fmax * np.exp(-al * r)

rawDescription: Issues with isolating color channels in Pylab


code:
{'Monday':  False,
        'Tuesday': True,
        'Wednesday': False,
        'Thursday': False,
        'Friday': True,
        'Saturday': False,
        'Sunday': True,
    }['Friday']

rawDescription: What kind of return is that?

description: What kind of return is that


code:
from math import sin, cos, atan2, sqrt, degrees, radians, pi
from geopy.distance import great_circle as distance
from geopy.point import Point

def midpoint(a, b):
    a_lat, a_lon = radians(a.latitude), radians(a.longitude)
    b_lat, b_lon = radians(b.latitude), radians(b.longitude)
    delta_lon = b_lon - a_lon
    B_x = cos(b_lat) * cos(delta_lon)
    B_y = cos(b_lat) * sin(delta_lon)
    mid_lat = atan2(
        sin(a_lat) + sin(b_lat),
        sqrt(((cos(a_lat) + B_x)**2 + B_y**2))
    )
    mid_lon = a_lon + atan2(B_y, cos(a_lat) + B_x)
    # Normalise
    mid_lon = (mid_lon + 3*pi) % (2*pi) - pi
    return Point(latitude=degrees(mid_lat), longitude=degrees(mid_lon))

rawDescription: Calculate distance between a point and a line segment in latitude and longitude


code: arr[i][j] = abs(hypot(i-s1x,j-s1y) - hypot(i-s2x,j-s2y))

rawDescription: Python optimization problem?

description: Python optimization problem


rawDescription: How to unpack a tuple into more values than the tuple has?

description: Unpack a tuple into more values than the tuple has


code:
def make_callback(m_type, other_type):
    def callback(msg):
        m = m_type(msg)
        a = other_type()
        for attr in other_type._fields_:
            setattr(a, attr, getattr(m, attr))
        pub2.publish(a)
    return callback

callback1 = make_callback(MsgX, msg_type_a)
callback2 = make_callback(MsgY, msg_type_b)

rawDescription: How to avoid similar function definitions in Python?

description: Avoid similar function definitions in Python


rawDescription: How to plot beautifully the segmentation of time series (pandas dataframe)

description: Plot beautifully the segmentation of time series (pandas dataframe)


code: re.search(r'(\d+)/python', s).group(1)

rawDescription: Kill a port that is listening with regex


code:
via_cdf = scipy.stats.norm.cdf(6)-scipy.stats.norm.cdf(5)
via_quad = scipy.integrate.quad(scipy.stats.norm.pdf, 5, 6)[0]
import mpmath
mpmath.mp.dps = 100
def cdf(x): return 0.5 * (1 + mpmath.erf(x/mpmath.sqrt(2)))
highres = cdf(6)-cdf(5)
highres
float((highres - via_quad)/highres)
float((highres - via_cdf)/highres)

rawDescription: Accuracy of deriving the CDF using integration


code:
p = re.compile(r'\w+(?:-\w+)*')
test_str = "sample sentence---such as well-being {   "

re.findall(p, test_str)

rawDescription: python regular expressions -- split on non-word char or consecutive dashes, but not on single dash

description: Python regular expressions -- split on non-word char or consecutive dashes, but not on single dash


code:
class Element:
    def __init__(self, key, value):
        self.key = key
        self.value = value

    def __eq__(self, other):
        return self.key == other.key

rawDescription: Check if heapq contains value

description: Check if heapq contains value


code:
data = '''4x23x21
20x29x30
23x11x5
'''

def func(a, b, c):
    print('a=', a, 'b=', b, 'c=', c, 'sum=', a + b + c)

for row in data.splitlines():
    a, b, c = [int(u) for u in row.split('x')]
    func(a, b, c)

rawDescription: How to pass several arguments to a function from a list in Python line by line

description: Pass several arguments to a function from a list in Python line by line


code:
from twisted.internet import reactor
#
#
#
reactor.connectTCP('localhost', 80, SomeProtocolFactory())

rawDescription: How do Twisted python Factory and Protocol interfaces work?


code: result = re.findall(r'<a href="(.*?)".+?(.*?)', info, re.DOTALL)

rawDescription: I use regular expression to extract info from a web page in python, but fail when I meet "return"?


code:
@celery.task(bind=True)
def counter(self):
    for i in xrange(100):
        time.sleep(1)
        self.update(state='PROGRESS', meta={'current': i})
    return {'status': 'complete'}

rawDescription: How to retrieve meta from celery backend storage

description: Retrieve meta from celery backend storage


code: [zip(*i) for i in data]

rawDescription: PYTHON: Finding the average of values of a nested list


code:
def show(text):
    return some_gui_stuff.confirm(text)

rawDescription: How to suppress execution of statement in script called with execfile?

description: Suppress execution of statement in script called with execfile


code: [pat.split(m) for m in main]

rawDescription: append match to new list and delete match from original list

description: Append match to new list and delete match from original list


code: db = getattr(connection,dbname)

rawDescription: Set a mongo database in pymongo without eval(). Maybe setattr()?


rawDescription: Need a way to load embedded, escaped JSON strings in Python


code: [l[i:i+n] for i in xrange(0, len(l), n)]

rawDescription: How do you split a list into evenly sized chunks in Python?

description: Split a list into evenly sized chunks in Python


code:
from os.path import expanduser
expanduser("~")

rawDescription: PyQt: QFileDialog.getExistingDirectory using a default directory, user independant


rawDescription: Accessing original decorated function for test purposes


code:
import numpy as np
a = np.array([[1, 2], [3, 4]])
z = np.zeros((2, 3), dtype=a.dtype)
np.c_[a, z]

rawDescription: Good ways to "expand" a numpy ndarray?

description: Good ways to "expand" a numpy ndarray


rawDescription: output of numpy.where(condition) is not an array, but a tuple of arrays: why?

description: Output of numpy.where(condition) is not an array, but a tuple of arrays: why


rawDescription: Creating formula based on binary tree leaves


code:
a = sps.csr_matrix([1,2,3,4])
a.data
a.indices
a.indptr
b = sps.csr_matrix((np.array([1, 2, 3, 4, 5]),
                    np.array([0, 1, 2, 3, 0]),
                    np.array([0, 5])), shape=(1, 4))
b
b.todense()

rawDescription: Adding a very repetitive matrix to a sparse one in numpy/scipy?


code: llong = range(longmin, longmax, longstepx)

rawDescription: Loop through list and changing indexes

description: Loop through list and changing indexes


rawDescription: Iterate with binary structure over numpy array to get cell sums


rawDescription: Slicing a string with standard indexing

description: Slicing a string with standard indexing


rawDescription: cut the python string

description: Cut the python string


code: result = result.unstack()

rawDescription: pandas - group and count nunique values

description: Pandas - group and count nunique values


code:
mask = a == 0 #entire array of bools
mask = np.nonzero(a)

rawDescription: Difference between nonzero(a), where(a) and argwhere(a). When to use which?


code:
import operator
sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)

rawDescription: sort csv by column

description: Sort csv by column


rawDescription: python regular expressions in find and replace

description: Python regular expressions in find and replace


rawDescription: How to extract method using Suds in Python

description: Extract method using Suds in Python


rawDescription: Make special diagonal matrix in Numpy

description: Make special diagonal matrix in Numpy


code:
my_dynamic_vars = dict()
string = 'someString'

my_dynamic_vars.update({string: dict()})

rawDescription: Usng the value of a string as a variable name


code:
column_elms = []
tcolumn = E("table-column",{"column-width":"41mm"})
for i in range(COLUMNS):
    column_elms.append(tcolumn)

rawDescription: Why are my Python arguments not unpacking?


rawDescription: How to reference an element of a list inside itself?

description: Reference an element of a list inside itself


code: moo()

rawDescription: Python, need to input csv file into a loop


code:
# Imports for creating fake data
from random import random
from random import choice

# Setup the sample data
A = pd.DataFrame({'TimeStamp':range(20), 'Source':[choice(others) for i in range(20)]})
# Create the MultiIndex on A
A.set_index(['TimeStamp', 'Source'], inplace=True)
A['Bar'] = [np.nan] * len(A)
A['Foo'] = [np.nan] * len(A)

B = pd.DataFrame({'TimeStamp':range(5),
                  'Foo':[random()*5+5 for i in range(5)],
                  'Bar':[random()*5+5 for i in range(5)]})
C = pd.DataFrame({'TimeStamp':range(5,10),
                  'Foo':[random()*5+5 for i in range(5)],
                  'Bar':[random()*5+5 for i in range(5)]})
D = pd.DataFrame({'TimeStamp':range(10,15),
                  'Foo':[random()*5+5 for i in range(5)],
                  'Bar':[random()*5+5 for i in range(5)]})

sources = {'B':B, 'C':C, 'D':D}

# create the MultiIndex on the Source data sets
for s, df in sources.items():
    df['Source'] = [s]*len(df)
    df.set_index(['TimeStamp', 'Source'], inplace=True)

rawDescription: Conditional merge of other multiple Pandas DataFrames


code: name, = (name for name in ('bob','bob') if name=='bob')

rawDescription: select single item from a collection : Python

description: Select single item from a collection : Python


code:
import re
rx = re.compile("[^\W\d_]+", re.UNICODE)
rx.findall(u"abc_def,k9")

rawDescription: python-re: How do I match an alpha character

description: Python-re: How do I match an alpha character


code:
#if isinstance(f, models.ManyToManyField):
#    raise ImproperlyConfigured("'%s.list_display[%d]', '%s' is a ManyToManyField which is not supported."
#        % (cls.__name__, idx, field))

rawDescription: What's the straightforward way to implement one to many editing in list_editable in django admin?


code:
mytime=np.tile( np.arange(0,10) , 2 )
myids=np.repeat( [123,456], [10,10] )
myvalues=np.random.random_integers(20,30,10*2)

df=pd.DataFrame()
df['myids']=myids
df['mytime']=mytime
df['myvalues']=myvalues

groups = df.groupby('myids')
df['run_max_group'] = groups['myvalues'].transform(np.maximum.accumulate)

rawDescription: Python: Running maximum by another column?


code:
import wx
a = wx.App(redirect=False)
d = wx.MessageBox("Hello World!!","Hello!")

rawDescription: How do I start and use wxPython?

description: Start and use wxPython


code: sentence = 'Your new contact email %s has been confirmed' % address

rawDescription: How to account for string formatting in Python variable assignment?

description: Account for string formatting in Python variable assignment


code:
if any(findWholeWord(s)(line) != None for s in strings):
    jd = json.loads(line)
    print (jd['user_id'], jd['text'])

rawDescription: Python iterative loop

description: Python iterative loop


code: print('`draw` has been called {} times'.format(draw.counter))

rawDescription: Count number of times function with varying arguments executed, then reset count when ENTER key pressed


code: Class.method(instance, argument)

rawDescription: Python: How to distinguish between inherited methods


code:
def construct_projection(label):
    r1 = r2 = 0.5
    theta = math.pi / 6
    phi = math.pi / 3
    x = int( 'p' in label) + r1 * math.cos(theta) * int('r' in label) - r2 * math.cos(phi) * int('s' in label)
    y = int( 'q' in label) + r1 * math.sin(theta) * int('r' in label) + r2 * math.sin(phi) * int('s' in label)
    return (x,y)

rawDescription: How to reshape a networkx graph in Python?

description: Reshape a networkx graph in Python


code:
def flatten_lists(a):
    if isinstance(a, list):
        for b in a:
            for x in flatten_lists(b):
                yield x
    else:
        yield a

rawDescription: How to flatmap list of lists of lists of tuples in Python?

description: Flatmap list of lists of lists of tuples in Python


code: variety = df_eating.groupby("customer_id")["fruit"].apply( lambda x: len(np.unique(x)))

rawDescription: Pandas merging a Dataframe and a series

description: Pandas merging a Dataframe and a series


code:
import json
data = {'jsonKey': None}
json.dumps(data)
json.loads(json.dumps(data))

rawDescription: converting json to string in python

description: Converting json to string in python


code:
country = session.query(Country).filter_by(name='Spain').one()
country.users.add(User(name='Johnny'))

rawDescription: SQLAlchemy ORM Insertion based on related object


code:
import wx
a =wx.App()
x = wx.GetTextFromUser("Enter X:")

rawDescription: How to make a simple GUI for inputting a single variable in Python?

description: Make a simple GUI for inputting a single variable in Python


code:
first_cut_new = first_cut-res
first_cut_depth[first_cut_depth>min_value+150]=0
first_cut_depth[first_cut_depth>0]=1
first_cut_final = first_cut_depth[...,None]*first_cut_new

rawDescription: Combining steps

description: Combining steps


code:
def selective_merge(base_obj, delta_obj):
    if not isinstance(base_obj, dict):
        return delta_obj
    common_keys = set(base_obj).intersection(delta_obj)
    new_keys = set(delta_obj).difference(common_keys)
    for k in common_keys:
        base_obj[k] = selective_merge(base_obj[k], delta_obj[k])
    for k in new_keys:
        base_obj[k] = delta_obj[k]
    return base_obj

rawDescription: Python/JSON: Merge default and user configuration


code:
import xlwt, xlrd
from xlutils.copy import copy as copy
from time import time

def add_stats_record():
    #Open for read
    start_time = time()
    rb = xlrd.open_workbook(STATS_FILE, formatting_info=True)
    sheet_records_original = rb.sheet_by_index(0)
    print('Elapsed time for opening:            %.2f' % (time()-start_time))
    #Record_id
    start_time = time()
    START_ROW = sheet_records_original.nrows
    SHEET_RECORDS_COLS = sheet_records_original.ncols
    try:
        record_id = int(sheet_records.cell(START_ROW - 1, 0).value) + 1
    except:
        record_id = 1
    print('Elapsed time for record ID:          %.2f' % (time()-start_time))
    #Open for write
    start_time = time()
    wb = copy(rb)
    sheet_records = wb.get_sheet(0)
    print('Elapsed time for write:              %.2f' % (time()-start_time))
    #Set normal style
    style_normal = xlwt.XFStyle()
    normal_font = xlwt.Font()
    style_normal.font = normal_font

    #Read all the data and get some stats
    start_time = time()
    max_col = {}
    start_time = time()
    for col_idx in range(0,16):
        max_value = 0
        for row_idx in range(START_ROW):
            if sheet_records_original.cell(row_idx, col_idx).value:
                val = float(sheet_records_original.cell(row_idx, col_idx).value)
                if val > max_value:
                    max_col[col_idx] = str(row_idx) + ';' + str(col_idx)

    text_cells = [[0 for x in range(15)] for y in range(START_ROW)]
    for col_idx in range(16,31):
        max_value = 0
        for row_idx in range(START_ROW):
            if sheet_records_original.cell(row_idx, col_idx).value:
                val = str(sheet_records_original.cell(row_idx, col_idx).value).replace('text', '').count(str(col_idx))
                if val > max_value:
                    max_col[col_idx] = str(row_idx) + ';' + str(col_idx)
    print('Elapsed time for reading data/stats: %.2f' % (time()-start_time))
    #Write the stats row
    start_time = time()
    for i in range(SHEET_RECORDS_COLS):
        sheet_records.write(START_ROW, i, max_col[i], style_normal)

    start_time = time()
    wb.save(STATS_FILE)
    print('Elapsed time for writing:            %.2f' % (time()-start_time))

if __name__ == '__main__':
    STATS_FILE = 'output.xls'
    start_time2 = time()
    add_stats_record()
    print ('Total time:                         %.2f' % (time() - start_time2))

rawDescription: Optimize add row in xls file with xlwt

description: Optimize add row in xls file with xlwt


code:
keys = dictionary.keys()
random.shuffle(keys)
values = [dictionary[i]*3 for i in keys]
keys = [i * 3 for i in keys]

rawDescription: Extracting keys-values from dictionary

description: Extracting keys-values from dictionary


code: ['Passport_Mike.pdf', 'David-Passport.pdf', 'Iain ID Card.pdf', 'CopyPassport Michael.pdf']

rawDescription: How to search items of a list within strings in Python

description: Search items of a list within strings in Python


code:
# Create server
server = MyXMLRPCServer(("localhost", 7789))
server.register_introspection_functions()

rawDescription: Python server that shuts itself after some time being idle


code:
np.random.choice(np.arange(0, 101), replace=False, size=(50, 50))
# ValueError: Cannot take a larger sample than population when 'replace=False'

rawDescription: Using Numpy Array to Create Unique Array


code:
l = [0,2,3,4,0]
l = [np.nan if x == 0 else x for x in l]
l

rawDescription: replace all 0's in a list with numpy.nan

description: Replace all 0's in a list with numpy.nan


code: p3 = PointOnUnitCircle.from_angle(pi/4)

rawDescription: Use inherited class method within __init__


rawDescription: convert JPG to txt causes change in file size in python

description: Convert JPG to txt causes change in file size in python


code:
def wrapper_function(instance):
    result = instance.Addition()
    myfile = open(r"C:\...\testboostexample.txt", "w")
    output = 'First variable is {0}, second variable is {1} and finally the addition is {2}'.format(instance.Value1, instance.Value2, result)
    myfile .write(output)
    myfile .close()

rawDescription: How to expose a C++ class to Python without building a module

description: Expose a C++ class to Python without building a module


code:
class PrimaryKeyRelatedByUser(serializers.PrimaryKeyRelatedField):
    def get_queryset(self):
        return super().get_queryset().filter(user=self.context['request'].user)

rawDescription: Limit choices and validate django's foreign key to related objects (also in REST)


code:
# -*- coding: utf-8 -*-

import threading
import sys
import time
import os

spinner="▏▎▍▌▋▊▉█▉▊▌▍▎" #utf8

#convert the utf8 spinner string to a list
chars=[c.encode("utf-8") for c in unicode(spinner,"utf-8")]

class spin(threading.Thread):   # not sure what to put in the brackets was (threading.Thread, but now im not sure whether to use processes or not)

    def __init__(self):
        super(spin,self).__init__() # dont understand what this does
        self._stop = False

    def run (self):
        pos=0
        while not self._stop:
            sys.stdout.write("\r"+chars[pos])
            sys.stdout.flush()
            time.sleep(.15)
            pos+=1
            pos%=len(chars)

    def cursor_visible(self):
        os.system("tput cvvis")
    def cursor_invisible(self):
        os.system("tput civis")
    def stop(self):
        self._stop = True  #the underscore makes this a private variable ?
    def stopped(self):
        return self._stop == True

if __name__ == "__main__":
    s = spin()
    s.cursor_invisible()
    s.start()
    a = raw_input("")
    s.stop()
    s.cursor_visible()

rawDescription: implementing a spinner type object in a class as a subprocess

description: Implementing a spinner type object in a class as a subprocess


code: y = lfilter(b, a, s)

rawDescription: python recursive vectorization with timeseries

description: Python recursive vectorization with timeseries


code:
import cgi
import wsgiref.handlers
import webapp2

class DDTHandler(webapp2.RequestHandler):

    def __start_display(self):
        self.response.out.write("<!--\n")

    def __end_display(self):
        self.response.out.write("-->\n")

    def __show_dictionary_items(self,dictionary,title):
        if (len(dictionary) > 0):
            request = self.request
            out = self.response.out
            out.write("\n" + title + ":\n")
            for key, value in dictionary.iteritems():
                out.write(key + " = " + value + "\n")

    def __show_request_members(self):
        request = self.request
        out = self.response.out
        out.write(request.url+"\n")
        out.write("Query = "+request.query_string+"\n")
        out.write("Remote = "+request.remote_addr+"\n")
        out.write("Path = "+request.path+"\n\n")
        out.write("Request payload:\n")
        if (len(request.arguments()) > 0):
            for argument in request.arguments():
                value = cgi.escape(request.get(argument))
                out.write(argument+" = "+value+"\n")
        else:
            out.write("Empty\n")

        self.__show_dictionary_items(request.headers, "Headers")
        self.__show_dictionary_items(request.cookies, "Cookies")

    def view_request(self):
        self.__start_display()
        self.__show_request_members()
        self.__end_display()

    def view(self, aString):
        self.__start_display()
        self.response.out.write(aString+"\n")
        self.__end_display()

rawDescription: Header Check in Python (GAE)

description: Header Check in Python (GAE)


code:
clientEndpoint = TCP4ClientEndpoint(reactor, "1.2.3.4", 12345)
serverEndpoint = TCP4ServerEndpoint(reactor, 12345)

rawDescription: Can Perspective Broker be used over stdio instead of TCP?


rawDescription: How to select min record by user in a Pandas data frame while accounting for multiple matches when you only want one

description: Select min record by user in a Pandas data frame while accounting for multiple matches when you only want one


code:
from datetime import datetime, timedelta
year = 2016
decimal_days = 12.375
datetime(year, 1, 1) + timedelta(decimal_days - 1)

rawDescription: Convert TLE times (decimal days) to seconds after epoch


code:
import my_module # A module I just created that contains the "Line" class
help(my_module)

# Returned documentation containing:
# FILE
# /home/<my user name>/Programming/Python/my_module.py

rawDescription: Finding function declarations in Ubuntu on Python


code:
import numpy as np

def group(xs, start=1):
    last_sum = 0
    for stop, acc in enumerate(np.add.accumulate(xs), start):
        if acc - last_sum >= 1:
            yield list(range(start, stop))
            last_sum = acc
            start = stop
    if start < stop:
        yield list(range(start, stop))

probs = np.random.dirichlet(np.ones(50) * 100, size=1)
logs = -np.log2(1 - probs[0])
print(list(group(logs)))

rawDescription: Grouping tuple columns so their sum is less than 1


code:
im_temp = Image.open(Path-To-Photo)
im_temp = im_temp.resize((250, 250), Image.ANTIALIAS)
im_temp.save("ArtWrk.ppm", "ppm") ## The only reason I included this was to convert
#The image into a format that Tkinter woulden't complain about
self.photo = PhotoImage(file="artwrk.ppm")##Open the image as a tkinter.PhotoImage class()
self.Artwork.destroy() #erase the last drawn picture (in the program the picture I used was changing)
self.Artwork = Label(self.frame, image=self.photo) #Sets the image too the label
self.Artwork.photo = self.photo ##Make the image actually display (If I dont include this it won't display an image)
self.Artwork.pack() ##repack the image

rawDescription: Resizing pictures in PIL in Tkinter

description: Resizing pictures in PIL in Tkinter


code:
for i in range(17106):
    session.add_all([Propagation() for i in range(19)])
    session.commit()

rawDescription: LOTS of call to the expire method of the SQLAlchemy's InstanceState class


rawDescription: Filter a pandas dataframe using values from a dict


code: new.append(undersc if j > i else 'Z')

rawDescription: Adding a value to each column sequentially


rawDescription: xpath not contains A and B

description: Xpath not contains A and B


code:
professional = CommonUser.create_child(Professional, {'id': 1})
client = CommonUser.create_child(Client, {'id': 2})

rawDescription: "Create" child model from base model in django


code: fab -i /path/to/priv/key

rawDescription: Using fabric to copy file from one remote server to another remote server?


code:
from concurrent.futures import ProcessPoolExecutor
from functools import partial

inited = False
initresult = None

def initwrapper(initfunc, initargs, f, x):
    # This will be called in the child. inited
    # Will be False the first time its called, but then
    # remain True every other time its called in a given
    # worker process.
    global inited, initresult
    if not inited:
        inited = True
        initresult = initfunc(*initargs)
    return f(x)

def do_init(a,b):
    print('ran init {} {}'.format(a,b))
    return os.getpid() # Just to demonstrate it will be unique per process

def f(x):
    print("Hey there {}".format(x))
    print('initresult is {}'.format(initresult))
    return x+1

def initmap(executor, initializer, initargs, f, it):
    return executor.map(partial(initwrapper, initializer, initargs, f), it)

if __name__ == "__main__":
    with ProcessPoolExecutor(4) as executor:
        out = initmap(executor, do_init, (5,6), f, range(10))
    print(list(out))

rawDescription: Python, launch concurrent.futures.ProcessPoolExecutor with initialization?


code:
from subprocess import check_output as qx

output = qx(['pcregrep', '-M', '-n', r'INSTANCE {}((?!^\)).*\n)+'.format(arg),
             path_to_sdf])

rawDescription: Python multi-line pattern matching

description: Python multi-line pattern matching


code:
matrix = [
    list('001001'),
    list('010000'),
    list('001110'),
    list('110000'),
]

starting_point = find_a_1()

walk_the_matrix(starting_point)

if find_1() is None:
    print("The matrix is connected")
else:
    print("The matrix is not connected")

rawDescription: Check if matrix elements are continuous

description: Check if matrix elements are continuous


code:
import csv
import re

with open('input.csv', 'r') as f_input, open('output.csv', 'wb') as f_output:
    csv_input = csv.reader(f_input, skipinitialspace=True)
    csv_output = csv.writer(f_output)
    keep = re.compile(r'[^0-9a-zA-Z\s,.:]')

    for cols in csv_input:
        cols = [keep.sub('', col) for col in cols]
        csv_output.writerow(cols)

rawDescription: Seaching .csv for unwanted string and delete


code: sum(i.freq for i in items[0:41])

rawDescription: Python: Summing class instances inside a list


code:
# collect index arrays
one_or_less = cf_array <= 1
from_2_to_4 = (1 < cf_array) & (cf_array <= 4)
greater_4 = cf_array > 4

# now modify target array
cf_array[one_or_less] = 5
cf_array[from_2_to_4] = 6
cf_array[greater_4] = 7

rawDescription: Reclassify raster values using python, numpy


code:
# Make sure everything in `cells` is a string
ESC = chr(27)

for y in xrange(20):
    outp = (cells['x{}y{}'.format(x,y)] for x in xrange(60))
    print('{}[{};{}f{}'.format(ESC, y, x, ''.join(outp)), end='')

rawDescription: printing out dictionnaires

description: Printing out dictionnaires


code:
def palindromic_substrings(s):
    if not s:
        yield []
        return
    for i in range(len(s), 0, -1):
        sub = s[:i]
        if sub == sub[::-1]:
            for rest in palindromic_substrings(s[i:]):
                yield [sub] + rest

rawDescription: Find all combinations of palindromic substrings


code: sys.stdout = codecs.open('DBScriptOutput.txt', 'w', 'utf8')

rawDescription: IronPython stack trace cites a line in "except" block


code:
class A(object):

    @classmethod
    def make(cls, value):
        if isinstance(value, cls): return value
        return cls(value)

    def __init__(self, value):
        self.attribute = value

rawDescription: Python assignment to self in constructor does not make object the same


code:
import collections
def is_listlike(x):
    return isinstance(x, collections.Iterable) and not isinstance(x, basestring)

def flat(S):
    result = []
    for item in S:
        if is_listlike(item) and len(item) > 0 and not is_listlike(item[0]):
            result.append(item)
        else:
            result.extend(flat(item))
    return result

tests = [ [[[[1,2,3] , ['a','b','c']]]],
          [[[1,2,3] , ['a','b','c']]],
          [[[1,2,3]] , [['a','b','c']]] ]

for S in tests:
    print(flat(S))

rawDescription: python: flatten to a list of lists but no more

description: Python: flatten to a list of lists but no more


code: d

rawDescription: Convert sets to frozensets as values of a dictionary


code:
main()
while(answer == "y"):
    main()

rawDescription: Global variable not working?

description: Global variable not working


rawDescription: pandas - groupby by partial string

description: Pandas - groupby by partial string


rawDescription: First common element from different lists of numbers


code: characters = [str(test[character]) for character in x]

rawDescription: How do I make a 'while' loop print the results of the loop's conditional into a single line(concatenated)?

description: Make a 'while' loop print the results of the loop's conditional into a single line(concatenated)


code:
socket.send("w")
socket.send("s")

rawDescription: Sending websocket message to client with parameter


code: [(k, [(n, sum(t)/float(len(t))) for n,t in v.items()]) for k,v in d.items()]

rawDescription: Merging part of tuples in Python

description: Merging part of tuples in Python


code:
regex = re.compile('[^a-zA-Z]')
#First parameter is the replacement, second parameter is your input string
regex.sub('', 'ab3d*E')
#Out: 'abdE'

rawDescription: Python, remove all non-alphabet chars from string


code:
mlb = MultiLabelBinarizer()
new_array = mlb.fit_transform(feature)

rawDescription: Forming a sparse feature matrix data frame in Pandas


code:
wire1 : [('module1', 'instance1', 'connectionwire1'), ('module2', 'instance2', 'newconnectionwire1')]
wire2 : [('module1', 'instance1', 'connectionwire2'), ('module2', 'instance2', 'newconnectionwire2')]
wire100 : [('module1', 'instance1', 'connectionwire100')]

rawDescription: pattern to dictionary of lists Python

description: Pattern to dictionary of lists Python


code:
for index, element in enumerate(my_array):
    if element["extension"] == ".py":
        return index

rawDescription: How to get an object inside an array list by its property value in Python

description: Get an object inside an array list by its property value in Python


code: ['Director', 'Screenwriter', 'Screenwriter', 'Producer']

rawDescription: get multiple tag values, except one

description: Get multiple tag values, except one


code:
def webmethod(f):
    f.is_webmethod = True
    return f

rawDescription: Use python decorators on class methods and subclass methods


code:
from selenium import webdriver

firefox_profile = webdriver.FirefoxProfile()
firefox_profile.set_preference("browser.privatebrowsing.autostart", True)

driver = webdriver.Firefox(firefox_profile=firefox_profile)

rawDescription: Python/Selenium incognito/private mode

description: Python/Selenium incognito/private mode


rawDescription: Difference between @classmethod and a method in python


code:
import Queue

myQueue = Queue.Queue()
for i in range(1,100):
    myQueue.put(i)
amount = [i for i in range(1,10)]
map(myQueue.get, amount)  # that will result in removing the 10 oldest elements

rawDescription: How to remove a lot of elements from a multithread queue without using a for loop

description: Remove a lot of elements from a multithread queue without using a for loop


rawDescription: How to group key:value pairs in a python dictionary based on certain range or interval?

description: Group key:value pairs in a python dictionary based on certain range or interval


code:
class APIKeyAuthentication(BaseAuthentication):

    def authenticate(self, request):
        """
        Check if there is an api key in the request and match it
        to the api keys we have. If it matches or is empty allow entrance.
        """
        api_key = request.META.get('HTTP_X_APIKEY', None)
        if not api_key:
            # if api key not in headers try get params
            api_key = request.GET.get("apikey", request.GET.get("api_key", None))

        if not api_key:
            # no api key in request
            raise PermissionDenied(
                detail="No API key send. Use the header \"X-APIKey\" "
                       "or the GET parameter \"apikey\""
            )

        auth_user = get_user_from_django_oauth_toolkit()

        if api_key == settings.APIKEYS["internal"]:
            request.is_internal = True

        return auth_user, None

rawDescription: Using Django Scopes to distinguish between user and client


code:
class Bar(Foo):
    pass

rawDescription: How does python prevent a class from being subclassed?


rawDescription: Mapping pandas DataFrame rows to a pandas Series


code:
pushback_enabled_iterator = PushbackWrapper(original_iterator)

item = next(pushback_enabled_iterator)
if went_too_far(item):
    pushback_enabled_iterator.pushback(item)
    break;

rawDescription: Iterator that supports pushback

description: Iterator that supports pushback


code: my_list=list(set(i[:3] for i in dems))

rawDescription: check if a string is in a list, and if not append it to that list

description: Check if a string is in a list, and if not append it to that list


code: recordString += getattr(classobj, variable)

rawDescription: Get the value of variables in dir(class)


code: from kivy.properties import NumericProperty

rawDescription: How do I change the color of my widget in Kivy at run time?

description: Change the color of my widget in Kivy at run time


code:
for line in infile: #loop through every line in infile
    outfile.write(line) #write this line to outfile
    print(line.rstrip("\n")) #print this line, but don't print the \n. that's why you were having multiple line breaks before

rawDescription: How do I make my program so that the user can specify a file name?

description: Make my program so that the user can specify a file name


code:
choices = [item.GetName() for item in items if item.GetSlot() == 'Head']
self.chHead = wx.Choice(self.nbItemPane, -1, choices=choices)

rawDescription: wxpython: How to create wxChoice contents from a list?

description: Wxpython: How to create wxChoice contents from a list


code:
import numpy as np
import os
import sys
...

rawDescription: Python: Write function in module to import packages


code:
import trace
from recurse import recurse

tracer = trace.Trace(count=False, trace=True, countfuncs=True)
tracer.run('recurse(2)')
tracer.results().write_results()

rawDescription: Python's trace module and filepaths

description: Python's trace module and filepaths


code:
import datetime as DT
import dateutil.tz as tz
import dateutil

current_time = DT.datetime.utcnow().replace(tzinfo=tz.gettz('Asia/Calcutta'))
print(current_time)
# 2013-05-12 18:33:19.368122+05:30

offset = current_time.utcoffset()
naive_time = current_time.replace(tzinfo=None)
print(naive_time)
# 2013-05-12 18:33:19.368122
print(naive_time + offset)
# 2013-05-13 00:03:19.368122

rawDescription: Get new datetime object according to timezone difference


code: d3 = {k1+'_'+k2:v1+v2 for k1,v1 in d1.iteritems() for k2,v2 in d2.iteritems() }

rawDescription: Combining keys and values of two different dicts


code:
new_list = []

# init random list
num_list = [random.randrange(0, 11) for _ in range(10)]

# while condition will evaluate to False
# only when num_list is empty

while num_list:
    # find index of maximum item
    max_index = num_list.index(max(num_list))

    # remove item with pop() and append to sorted list
    new_list.append(num_list.pop(max_index))

rawDescription: Order a list from largest to smallest using insertion sort


code:
values = [3, 5, 0, 3, 5, 1, 4, 0, 9]

def zero_to_nan(values):
    """Replace every 0 with 'nan' and return a copy."""
    return [float('nan') if x==0 else x for x in values]

print(zero_to_nan(values))

rawDescription: Not plotting 'zero' in matplotlib or change zero to None [Python]


code:
hor = self.canvas.create_line(hstart, hend, tags=("hor_line",))
ver = self.canvas.create_line(vstart, vend, tags=("ver_line",))
...
self.canvas.coords("hor_line", e.x, 0, e.x, 1000)
self.canvas.coords("ver_line", 0, e.y, 1000, e.y)

rawDescription: How do I delete and create new lines simultaneously

description: Delete and create new lines simultaneously


code:
data.loc[
    (data.index.get_level_values('jersey').isin([71, 84])
     & data.index.get_level_values('team').isin(['Dodgers', 'Mets'])),
    data.columns.get_level_values('observer').isin(['John', 'Ralph'])
]

rawDescription: Using boolean indexing for row and column MultiIndex in Pandas


code:
LOGGING = {
    'formatters': {
        'utc': {
            '()': 'my.package.UtcFormatter',
            'format': '...',
            'datefmt': '...',
        }
    }
}

rawDescription: django: keep UTC time in logging while changing the TIME_ZONE settings

description: Django: keep UTC time in logging while changing the TIME_ZONE settings


code:
indices = [m.start() + 1 for m in re.finditer("CAC", letterstring)]
all(letterlist[i] == "A" for i in indices)

rawDescription: how to find a pattern of string elements in a list?

description: Find a pattern of string elements in a list


code:
import storage
import json
import falcon
import random

class Flow(object):

    def on_get(self, req, resp):
        storage_value = storage.main_queque.qsize()
        msg = {"qsize": storage_value}
        resp.body = json.dumps(msg, sort_keys=True, indent=4)
        resp.status = falcon.HTTP_200

    #curl -H "Content-Type: application/json" -d '{}'  http://10.206.102.81:8888/flow
    def on_post(self, req, resp):
        r = random.randint(1, 10000000000000)
        cmd = 'sleep 1;echo "ss %s"' % str(r)
        storage.main_queque.put(cmd)
        storage_value = cmd
        msg = {"value": storage_value}
        resp.body = json.dumps(msg, sort_keys=True, indent=4)
        resp.status = falcon.HTTP_200

rawDescription: How to store response when http client closed a connection?

description: Store response when http client closed a connection


code:
jinja_env = Environment(...)
jinja_env.globals['url_for'] = url_for

rawDescription: Accessing global attributes from inside a macro in Jinja2


code:
for i in xrange(N-1):
    ax.plot(x[i:i+2], y[i:i+2], z[i:i+2], color=plt.cm.jet(255*i/N))

rawDescription: Line colour of 3D parametric curve in python's matplotlib.pyplot


code:
reader.next() # read next line so header will be accessed
rfd_header = reader.fieldnames

rawDescription: csvreader.fieldnames not recognized as an attribute of a csv reader object in python

description: Csvreader.fieldnames not recognized as an attribute of a csv reader object in python


code: (parameter, value) = line.split('=')

rawDescription: Parsing Lines in Python: Use RE or Not?

description: Parsing Lines in Python: Use RE or Not


code: timevalue = datetime.strptime(timecomponent, '%I:%M%p').time()

rawDescription: Strings with start and end time to datetime


code: a, b, c, d = map(f, xrange(1, 5))

rawDescription: How to pass an integer series as argument to a python function?

description: Pass an integer series as argument to a python function


code: Foo.__str__ is not object.__str__

rawDescription: How to check if __str__ is implemented by an object

description: Check if __str__ is implemented by an object


code: df.plot('hour', 'activity', kind='bar')

rawDescription: How to plot histogram with data prepared in Pandas DataFrame?

description: Plot histogram with data prepared in Pandas DataFrame


rawDescription: Generating a list of repetitions regardless of the order


code:
I = np.eye(states, dtype=bool)
bool_index = ~I & (z != 0) & (m < 0.0)

m[I] += (bool_index * m).sum(axis=1)
m[bool_index] = 0.0
z[bool_index] = 0

rawDescription: How can I optimize this double-loop over an array using numpy?

description: Optimize this double-loop over an array using numpy


code:
while not results.empty():
    ip = results.get()
    print(ip)

rawDescription: Documentation for understanfing

description: Documentation for understanfing


code:
class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()

class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()

getch = _Getch()

rawDescription: how to change some words color real time while accepting input in python

description: Change some words color real time while accepting input in python


code:
import copy
x = [1,2,3, [4,5]]
y = copy.copy(x)
id(x)
id(y)
x.append(10)
x
y
x[3].append(20)
x
y
z = copy.deepcopy(x)
z
x[3].append(50)
x
z

rawDescription: Python 3.4 What is this list doing?

description: Python 3.4 What is this list doing


code:
from Tkinter import *  # or tkinter if you use Python3

root = Tk()

label_1 = Label(master=root, text='Name 1')
label_2 = Label(master=root, text='Name 2')
label_3 = Label(master=root, text='Name 3')
label_4 = Label(master=root, text='Name 4')

label_1.grid(row=0)
label_2.grid(row=1)
label_3.grid(row=2)  # this is the 2nd
label_4.grid(row=4)  # this is the 4th

root.rowconfigure(index=3, weight=1)  # add weight to the 3rd!
root.mainloop()

rawDescription: How to use the grid() python

description: Use the grid() python


code:
import re
from bs4 import BeautifulSoup, Comment

soup = BeautifulSoup(myhtml)
comments = soup.find_all(text=lambda text: isinstance(text, Comment))

rawDescription: How do I only select DIV with similar ID

description: Only select DIV with similar ID


code:
def test(lst, start, end):
    lst.insert(start+1, lst[start])
    lst.insert(end+1, lst[end])
    print(lst)
    lst[start] = lst[end+1]
    lst[end] = lst[start+1]
    print(lst)
    del lst[start+1]
    del lst[end+1]
    print(lst)

rawDescription: Replacing two elements of a list in place with a function [python 3]


code:
data = []
keys = ['Name', 'Gender', 'Age']
persons = (("Josh", "Male", 22), )
for person in persons:
    data.append(dict(zip(keys, person)))

rawDescription: Data type to save a table

description: Data type to save a table


code:
from functools import wraps

def with_descriptor_defaults(*defaultargs, **defaultkeywords):
    def decorator(fn):
        @wraps(fn)
        def wrapper(self, *args, **kwargs):
            args = [a.__get__(self, type(self)) if hasattr(a, '__get__') else a
                    for a in defaultargs] + list(args)
            kw = {k: v.__get__(self, type(self)) if hasattr(v, '__get__') else v for k, v in defaultkeywords.items()}
            kw.update(kwargs)
            return fn(self, *args, **kw)
        return wrapper
    return decorator

rawDescription: How to access a class's property using a partialmethod?

description: Access a class's property using a partialmethod


code:
class User(db.Model):
    __tablename__ = 'user'

    user_id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), nullable=False)
    created_at = db.Column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP"))
    updated_at = db.Column(db.DateTime, nullable=False, server_default=db.text("CURRENT_TIMESTAMP"))

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

    @classmethod
    def create(cls, **kw):
        obj = cls(**kw)
        db.session.add(obj)
        db.session.commit()

rawDescription: How to add a custom function/method in sqlalchemy model to do CRUD operations?

description: Add a custom function/method in sqlalchemy model to do CRUD operations


code:
connection = reader.createConnection()
connection.connect()
data, sw1, sw2 = connection.transmit(cmd)

rawDescription: Howto list files on a smartcard with pyscard


code:
childbr.tail = "world"
lxml.etree.tostring(root)

rawDescription: Replace text with HTML tag in LXML text element


code:
config_root = {
    '/' : {
        'tools.zkauth.on': True,
        'tools.sessions.on': True,
        'tools.sessions.name': 'zknsrv',
        }
    }

rawDescription: How do you use cookies and HTTP Basic Authentication in CherryPy?

description: Use cookies and HTTP Basic Authentication in CherryPy


code:
from random import sample
picked = sample(randomnumbers, 5)

rawDescription: how to generate 5 numbers from a list?

description: Generate 5 numbers from a list


code:
def manage(request):
    group_list = Group.objects.order_by('name').filter(user=request.user)
    return render(request, 'manage.html', {'group_list': group_list})

rawDescription: Iterate Items in Their Specific Groups in Django


code:
class UpdateTimeViewSet(ViewSet):

    def list(self, request, format=None):
        latest_publish = Publish.objects.latest('created_time')
        latest_meeting = Meeting.objects.latest('created_time')
        latest_training = Training.objects.latest('created_time')
        latest_exhibiting = Exhibiting.objects.latest('created_time')

        return Response({
            "publish_updatetime": latest_publish.created_time,
            "meeting_updatetime": latest_meeting.created_time,
            "training_updatetime": latest_training.created_time,
            "exhibiting_updatetime": latest_exhibiting.created_time,
        })

rawDescription: How can I register a single view (not a viewset) on my router?

description: Register a single view (not a viewset) on my router


code:
class Foo:
    a = None

    @property
    def a(self):
        pass

    @a.setter
    def a(self, v):
        '''
        >>> 1 == 1
        False
        '''
        pass

    a = property(a.fget, a.fset, doc=a.fset.__doc__)

rawDescription: python-2.7: doctests ignored in setter method of a class

description: Python-2.7: doctests ignored in setter method of a class


code: [f for _, f in foo.__dict__.iteritems() if callable(f)]

rawDescription: How to iterate through a module's functions

description: Iterate through a module's functions


code:
decimals = 5
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimals))

rawDescription: Two Decimals in Python?

description: Two Decimals in Python


rawDescription: What is the best way to create a moving window in 2D array ond order pixels


code:
newDailyFile = path+day
with open(newDailyFile, "a") as file:
    for i in creatures:
        dump({'name':name, 'numbers':n, 'strings':s, 'x':x, 'y':y}, file) #removed indent so each one is online
        file.write("\n")#or else they will all be on the same line

rawDescription: python, loading multiple instances of something

description: Python, loading multiple instances of something


code:
import re
p = re.compile('([+-])(\w,]+)')
tempString = '+foo,   bar -baz'
p.findall(tempString.replace(' ', ''))

rawDescription: Difficulty getting python regular expression to work


code:
import xml.etree.ElementTree as ET

xmlns_uris = {'p': 'http://myhost.com/p.xsd',
              'q': 'http://myhost.com/q.xsd'}

def dump_to_XML():
  root_node = ET.Element("root")
  c1_node = ET.SubElement(root_node, "child1")
  c1_node.text = "foo"
  c2_node = ET.SubElement(root_node, "child2")
  gc1_node = ET.SubElement(c2_node, "grandchild1")
  gc1_node.text = "bar"
  annotate_with_XMLNS_prefixes(gc1_node, 'q', False)
  annotate_with_XMLNS_prefixes(root_node, 'p')
  add_XMLNS_attributes(root_node, xmlns_uris)
  return ET.tostring(root_node, encoding='UTF-8', method='xml')

def annotate_with_XMLNS_prefixes(tree, xmlns_prefix, skip_root_node=True):
    if not ET.iselement(tree):
        tree = tree.getroot()
    iterator = tree.iter()
    if skip_root_node: # Add XMLNS prefix also to the root node?
        iterator.next()
    for e in iterator:
        if not ':' in e.tag:
            e.tag = xmlns_prefix + ":" + e.tag

def add_XMLNS_attributes(tree, xmlns_uris_dict):
    if not ET.iselement(tree):
        tree = tree.getroot()
    for prefix, uri in xmlns_uris_dict.items():
        tree.attrib['xmlns:' + prefix] = uri

rawDescription: Python: specify XMLNS on xml.etree elements


code:
c = A()
t1 = c.method1()
t1.join() # wait for it to finish
t2 = c.method2()
# ...

rawDescription: Threads with decorators

description: Threads with decorators


code:
import math

a = (4, 31)
b = (0, 29)
c = (1, 31)

print(int(math.ceil(sum(a) / 7.)))
print(int(math.ceil(sum(b) / 7.)))
print(int(math.ceil(sum(c) / 7.)))

rawDescription: Facing issue while rounidng up a value in python


code:
import numpy as np

def asvoid(arr):
    """View the array as dtype np.void (bytes)
    This collapses ND-arrays to 1D-arrays, so you can perform 1D operations on them.
    http://stackoverflow.com/a/16216866/190597 (Jaime)"""
    arr = np.ascontiguousarray(arr)
    return arr.view(np.dtype((np.void, arr.dtype.itemsize * arr.shape[-1])))

def find_index(arr, x):
    arr_as1d = asvoid(arr)
    x = asvoid(x)
    return np.nonzero(arr_as1d == x)[0]

arr = np.array([[  1,  15,   0,   0],
                [ 30,  10,   0,   0],
                [ 30,  20,   0,   0],
                [1, 2, 3, 4],
                [104, 139, 146,  75],
                [  9,  11, 146,  74],
                [  9, 138, 146,  75]], dtype='uint8')

arr = np.tile(arr,(1221488,1))
x = np.array([1,2,3,4], dtype='uint8')

print(find_index(arr, x))

rawDescription: Fast way to find index of array in array of arrays


code:
from datetime import datetime, timedelta
import praw

# assuming you run this script every hour
an_hour_ago = datetime.utcnow() - timedelta(hours=1)
r = praw.Reddit(user_agent='soc')
submissions = r.get_subreddit('soccer').get_new()
submissions_list = [
    # iterate through the submissions generator object
    x for x in submissions
    # add item if item.created_utc is newer than an hour ago
    if datetime.utcfromtimestamp(x.created_utc) >= an_hour_ago
]

rawDescription: Praw: How to filter search results based on created date?


rawDescription: Python file delimited with double tabs

description: Python file delimited with double tabs


rawDescription: Python- Count the frequency of messages within a date range within per dynamic interval


code: [[d['a'] for d in lst if d['b']==b] for b in bs]

rawDescription: Breaking a list in to parts by subject

description: Breaking a list in to parts by subject


code: Text: XYZ

rawDescription: Using \b in python 3

description: Using \b in python 3


code:
class Resource(db.Model):
    # .... your existing code
    @staticmethod
    def customq(limit, offset):
        """This method returns an instance of flask_sqlalchemy.BaseQuery"""
        return Resource.query.filter_by(is_active=1).limit(limit).offset(offset)

rawDescription: Default scope for queries using Python + Flask-SqlAlchemy


code:
class FooAdmin(admin.ModelAdmin):
    list_display = ['other_field', 'my_task_init']

    class Media:
        js = (
            'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js',
            '/static/js/admin_tasks.js',
        )

    def get_urls(self):
        urls = super(FooAdmin, self).get_urls()
        extra_urls = patterns('',
            (r'^my-task/$', self.admin_site.admin_view(self.parse_view))
        )
        return extra_urls + urls

    # optionally decorated by celery
    def task_view(self, request):
        if not request.is_ajax():
            raise Http404
        task_id = request.GET.get('task_id')
        # your logic
        return HttpResponse('Success')

rawDescription: Django: How to call management custom command execution from admin interface?


code:
from collections import defaultdict
d = defaultdict(set)
d[key].add(value)

rawDescription: Creating a dictionary and adding a set as its value


code:
new_crit = input("Enter a name for your new critter: ")
for i in noc:
    if i.name == new_crit:  # name is a parameter used in the class Critter
        print("That critter already exists")
        return

# we can only get here if no such name was found, otherwise the function
# would have exited at the `return`
Critter.noc.append(Critter(new_crit))
print("New critter has been created. the critter is named: ", new_crit)

rawDescription: using if...then...else in to check if an object already exists

description: Using if...then...else in to check if an object already exists


code: data = line.split(',')

rawDescription: How can I make this search faster in python?

description: Make this search faster in python


code:
import csv
from itertools import islice,ifilter
from collections import OrderedDict

MAINDIR = "../"
with  open(MAINDIR + "atp_players.csv") as pf,  open(MAINDIR + "atp_rankings_current.csv") as rf:
    players = OrderedDict((row[0],row) for row in csv.reader(pf))
    rankings = csv.reader(rf)
    for i in islice(rankings, None, 10):
        # now constant work getting row as opposed to 0(n)
        player = players.get(i[2])

rawDescription: Python large multi-list efficient query

description: Python large multi-list efficient query


code:
my_list = [[10]] * 3
my_list
my_list[0][0] = 5
my_list

rawDescription: Initialize list with same bool value

description: Initialize list with same bool value


code:
df
df['pos'] = group_position(df['Z'], df['A'])
df.set_index(['Z', 'A', 'pos']).unstack('pos')

rawDescription: Multiindex from array in Pandas with non unique data


code:
import subprocess

output = subprocess.check_output('fst-mor', 'NOUN.A')

rawDescription: Calling multi-level commands/programs from python


rawDescription: How to convert mongodb document to binary in Python?

description: Convert mongodb document to binary in Python


code:
import functools
from tornado import gen
from tornado.ioloop import IOLoop

@functools.lru_cache(maxsize=100)
@gen.coroutine
def expensive_function():
    print('starting expensive_function')
    yield gen.sleep(5)
    return 1, 2, 3

@gen.coroutine
def get_x():
    print('starting get_x')
    x, y, z = yield expensive_function()
    return x

@gen.coroutine
def get_y():
    print('starting get_y')
    x, y, z = yield expensive_function()
    return y

@gen.coroutine
def get_z():
    print('starting get_z')
    x, y, z = yield expensive_function()
    return z

@gen.coroutine
def main():
    x, y, z = yield [get_x(), get_y(), get_z()]
    print(x, y, z)

if __name__ == '__main__':
    IOLoop.current().run_sync(main)

rawDescription: Caching and reusing a function result in Tornado


code:
xlist = [(1, 1.1), (2, 1.2), (3, 1.3)]
dt=np.dtype('int,float')
np.array(xlist,dtype=dt)
xarr = np.array(xlist,dtype=dt)
xarr['f0']
xarr['f1']

rawDescription: convert list of tuples to structured numpy array

description: Convert list of tuples to structured numpy array


code: ProdType= namedtuple('ProdType', 'Cmdty Eqty Fixed', verbose=True)

rawDescription: accessing custom python type properties by name

description: Accessing custom python type properties by name


code:
import numpy as np
from scipy.stats import logistic

def func1(y, X, thresholds):
    ll = 0.0
    for row in zip(y, X):
        if row[0] == 0:
            ll += logistic.logcdf(thresholds[0] - row[1])
        elif row[0] == len(thresholds):
            ll += logistic.logcdf(row[1] - thresholds[-1])
        else:
            diff_prob = logistic.cdf(thresholds[row[0]] - row[1]) - \
                         logistic.cdf(thresholds[row[0] - 1] - row[1])
            diff_prob = 10 ** -5 if diff_prob < 10 ** -5 else diff_prob
            ll += np.log(diff_prob)
    return ll

y = np.array([0, 1, 2])
X = [2, 2, 2]
thresholds = np.array([2, 3])
print(func1(y, X, thresholds))

rawDescription: How to speed up my numpy loop using numpy.where()

description: Speed up my numpy loop using numpy.where()


code:
[[[(a,b,c) for a in A] for b in B] for c in C]
            #SAME AS#
def fC(c):
    def fB(b,c):
        def fA(a,b,c):
            return (a,b,c)
        yield [f(a,b,c) for a in A]
    yield [fB(b,c) for b in B]
[fC(c) for c in C]
            #SAME AS#
Cs = []
for c in C:
    Bs = []
    for b in B:
        As = []
        for a in A:
            As += [a]
        Bs += [As]
    Cs += [Bs]
return Cs

rawDescription: What's wrong with this nested list comprehension?


code:
this = soup.new_string(this)
is_my = soup.new_string(is_my)

rawDescription: BeautifulSoup: How to replace value in an element with an element tag?


rawDescription: Strip the html comment tags within an xml file using beautifulsoup


code:
from awesome_module import *
foo_vector = VectorOfFoo()
foo_vector.extend(Foo(arg) for arg in arglist)
bar(foo_vector)

rawDescription: Passing Python list to C++ vector using Boost.python


code:
#!/usr/bin/env python
"""Clear screen in the terminal."""
import curses
import os
import sys

curses.setupterm()
e3 = curses.tigetstr('E3') or b''
clear_screen_seq = curses.tigetstr('clear') or b''
os.write(sys.stdout.fileno(), e3 + clear_screen_seq)

rawDescription: Python - Clearing the terminal screen more elegantly


rawDescription: Evaluation order of positional and keyword arguments


rawDescription: How to evaluate arbitrary code in Python?

description: Evaluate arbitrary code in Python


code:
import sys

with open("log.txt", "w") as logfile:
    sys.stdout, sys.stderr = logfile, logfile

    # do your stuff here, e.g. import the module that you want to log

rawDescription: Python log-the-display problems

description: Python log-the-display problems


code:
import datetime
from south.db import dbs # Import dbs instead of db
from south.v2 import DataMigration
from django.db import models
from django.core.management import call_command # Add this import

class Migration(DataMigration):
    def forwards(self, orm):
        call_command('createcachetable', 'cache', database='other_database')

    def backwards(self, orm):
        dbs['other_database'].delete_table('cache')

    ...

rawDescription: Creating Django Cache table using South?

description: Creating Django Cache table using South


code:
__import__('math').factorial(10)
sum(int(number) for number in str(__import__('math').factorial(10)))

rawDescription: usage of str() to convert number in int() in Python

description: Usage of str() to convert number in int() in Python


code:
x = [1,2,3,4]
[n for n in x for _ in range(4)]

rawDescription: How can I increase the size of, and pad, a python list?

description: Increase the size of, and pad, a python list


code:
on,to,112
four,FIVE,seven

rawDescription: Seaching .csv for unwanted string and delete


code: (2*np.pi + angles) * (angles < 0) + angles*(angles > 0)

rawDescription: Numpy converting range of angles from (-Pi, Pi) to (0, 2*Pi)


code:
myrange(10, 2, 5)
list(myrange(10, 2, 5))

rawDescription: Python range function: defining the length of sequence instead of the step size


code:
@do_profile_all_methods(DO_PROFILE)
class myApp(object):
    def foo_method(self):
        pass

rawDescription: how can I profile class methods of my python app?

description: Profile class methods of my python app


code:
for i in reversed([ i for (i,o) in enumerate(self.list) if o.mycond() ]):
    del self.list[i]

rawDescription: How to delete list elements while cycling the list itself without duplicate it

description: Delete list elements while cycling the list itself without duplicate it


code: elapsed_time = 0

rawDescription: Flash an image in pygame

description: Flash an image in pygame


code:
def names(request):
    to_delete = request.POST.getlist('to_delete')
    if to_delete:
        Clash.objects.filter(pk__in=to_delete).delete()

    return render_to_response("names.html", locals() , context_instance = RequestContext(request))

rawDescription: How to retrieve max (pk) in python from a table database?

description: Retrieve max (pk) in python from a table database


code:
import lxml.html as LH

html_table='''

'''

nums=['1','2','20','47','50']
doc=LH.fromstring(html_table)
for tr,n in zip(doc.xpath('//tr'),nums):
    tr.attrib['id']=n
print(LH.tostring(doc,pretty_print=True))

rawDescription: Iterating through a list of numbers and adding them to <tr> tags


code:
import pystache
renderer = pystache.Renderer()
renderer.render_path('layout.mustache', {'name': 'test'})

rawDescription: Rendering Multiple Files with pystache

description: Rendering Multiple Files with pystache


code:
M = G2.ecount()
m = len(sorted_tuples)
G2.add_edges(sorted_tuples)
G2.es[M:(M+m)] = sorted_weights

rawDescription: iGraph Python, convert edge list to tuple and add.edges

description: IGraph Python, convert edge list to tuple and add.edges


code:
from django.contrib.gis.geos import Polygon, Point, MultiPoint, GeometryCollection
poly = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )
gc = GeometryCollection(Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly)
gc.geojson

rawDescription: Building a GeoJSON with Python

description: Building a GeoJSON with Python


code:
import ast
result = ast.literal_eval("{" + s.replace(" ", ", ") + "}")

rawDescription: Whether eval() better than self-analysis?


code:
import math

initMsg = '11101000110100001100101...'  # truncated due post limits.
decMsg = '11101000110100001100101...'

# Only printing the first 25 chars of the message for bevity:

a = int(initMsg,2)
print(a.to_bytes(math.ceil(a.bit_length()/8),'big')[:25])

a = int(decMsg,2)
print(a.to_bytes(math.ceil(a.bit_length()/8),'big')[:25])

a = int(decMsg+'0000000',2)
print(a.to_bytes(math.ceil(a.bit_length()/8),'big')[:25])

a = int(decMsg[:-1],2)
print(a.to_bytes(math.ceil(a.bit_length()/8),'big')[:25])

rawDescription: Python3 Unicode Decode Error

description: Python3 Unicode Decode Error


code:
def encrypt(message, key):
    result = ""
    for char in message:
        if (ord(char) + key > 126):
            result += chr(ord(char) + key - 127 + 32)
        else:
            result += chr(ord(char) + key)
    return result

rawDescription: How can I tackle this cryptography?

description: Tackle this cryptography


code:
for item in alist:
    exec(item + " = []")

rawDescription: Create empty lists with name of attributes of other lists


code:
import nose.tools as nt

from checkers import is_triangle

def test_is_triangle():
    # Define test_a, test_b, and test_c here such that they should produce a
    # return value of False.
    nt.assert_false(is_triangle(test_a, test_b, test_c))

    # Redefine test_a, test_b, and test_c here such that they should produce a
    # return value of True.
    nt.assert_true(is_triangle(test_a, test_b, test_c))

rawDescription: Python. Function testing using Nose

description: Python. Function testing using Nose


code:
import shutil

shutil.move("temp.txt","in.txt")

rawDescription: Not Recognizing Loop Variable in Python

description: Not Recognizing Loop Variable in Python


code: reviews.sort(key=lambda i: i['datePublished'], reverse=True)

rawDescription: beautifulsoup with internal javascript

description: Beautifulsoup with internal javascript


code:
h ={ "X-MicrosoftAjax":"Delta = true",
"X-Requested-With":"XMLHttpRequest",
     "User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36"
}

d = {"ctl00$ctl13": "ctl00$ctl13|ctl00$MainContent$physicianSearchView$btnSearch",
     "ctl00$MainContent$physicianSearchView$txtLastName": "Train",
     'ctl00$MainContent$physicianSearchView$txtFirstName': "Anthony",
     'ctl00$MainContent$physicianSearchView$txtCity': "Calgary",
     'ctl00$MainContent$physicianSearchView$rblGender': "Male",
     "__EVENTTARGET": "ctl00$MainContent$physicianSearchView$btnSearch",
     'ctl00$MainContent$physicianSearchView$hfPrefetchUrl': "http://service.cpsa.ca/OnlineService/OnlineService.svc/Services/GetAlbertaCities?name=",
     'ctl00$MainContent$physicianSearchView$hfRemoveUrl': "http://service.cpsa.ca/OnlineService/OnlineService.svc/Services/GetAlbertaCities?name=%QUERY",
     '__ASYNCPOST': 'true'}

with requests.session() as s:
    r = s.get("http://search.cpsa.ca/PhysicianSearch",headers=h)
    soup = BeautifulSoup(r.content,"lxml")
    ev = soup.select("#__EVENTVALIDATION" )[0]["value"]
    vs = soup.select("#__VIEWSTATE")[0]["value"]
    d["__EVENTVALIDATION"] = ev
    d["__VIEWSTATE"] = vs
    r = requests.post('http://search.cpsa.ca/PhysicianSearch', data=d,headers=h)
    print(r.content)

rawDescription: python - POST request doesn't work

description: Python - POST request doesn't work


code:
rc[:].push(dict(
    f1=f1,
    f2=f2,
    const=const,
))

rawDescription: Best way to pass local variables to ipyparallel cluster

description: Pass local variables to ipyparallel cluster


code: b = a

rawDescription: Python assignment to self in constructor does not make object the same


code:
In [97]: abbrevs['America/Los_Angeles']
Out[97]: {'LMT', 'PDT', 'PPT', 'PST', 'PWT'}

rawDescription: Python: All possible Timezone Abbreviations for given Timezone Name (and vise versa)


rawDescription: Python strip a string from config file

description: Python strip a string from config file


code:
from collections import defaultdict
from functools import partial
from itertools import count
from random import choice
fruits = ['apple', 'banana', 'pear', 'cherry', 'melon', 'kiwi', 'pineapple']
listFruit = [choice(fruits) for _ in xrange(100)]
unique_count = defaultdict(partial(next, count(1)))
[unique_count[el] for el in listFruit]
unique_count

rawDescription: Any quick way to labelize a list in Python?


code: ['hallo', 'hello', 'hillo', 'hollo', 'hullo', 'hella', 'helle', 'helli', 'hello', 'hellu']

rawDescription: Finding all combinations of vowel replacements


code:
import re
s = '(M:2,Seq0:2):10,Seq1:20,(Seq2:40,Seq3:40)'
def repl(match):
    return match.group(1) + str(int(match.group(2)) + 10)
re.sub(r'(\w+(?!1:)\d+:)(\d+)', repl, s)

rawDescription: Substitution of certain occurences of a string with another string in python


code:
from mako.template import Template
from mako.runtime import Context

tpl_xml = '''
<doc>
% for i in data:
<p>${i}</p>
% endfor
</doc>
'''

tpl = Template(tpl_xml)

with open('output.xml', 'w') as f:
    ctx = Context(f, data=xrange(10000000))
    tpl.render_context(ctx)

rawDescription: Generating very large XML files in Python?


code: any(x > 10 for x in l)

rawDescription: How to achieve python's any() with a custom predicate?

description: Achieve python's any() with a custom predicate


code: iter_mystate = iter(getstate, object())

rawDescription: python: iterator from a function

description: Python: iterator from a function


code:
import grp

try:
    grp.getgrnam('somegrp')
except KeyError:
    print('Group somegrp does not exist.')

rawDescription: Tell if a given login exists in Linux using Python


code:
def set_params(self, **params):
    """Set the parameters of this estimator.
    The method works on simple estimators as well as on nested objects
    (such as pipelines). The former have parameters of the form
    ``<component>__<parameter>`` so that it's possible to update each
    component of a nested object.
    Returns
    -------
    self
    """
    if not params:
        # Simple optimisation to gain speed (inspect is slow)
        return self
    valid_params = self.get_params(deep=True)
    for key, value in six.iteritems(params):
        split = key.split('__', 1)
        if len(split) > 1:
            # nested objects case
            name, sub_name = split
            if name not in valid_params:
                raise ValueError('Invalid parameter %s for estimator %s. '
                                 'Check the list of available parameters '
                                 'with `estimator.get_params().keys()`.' %
                                 (name, self))
            sub_object = valid_params[name]
            sub_object.set_params(**{sub_name: value})
        else:
            # simple objects case
            if key not in valid_params:
                raise ValueError('Invalid parameter %s for estimator %s. '
                                 'Check the list of available parameters '
                                 'with `estimator.get_params().keys()`.' %
                                 (key, self.__class__.__name__))
            setattr(self, key, value)
    return self

rawDescription: Python TfidfVectorizer : Is conditional re-initialization possible?


code: percentOfPathElement = [(b - a) / pathLength for a, b in zip(elementList, elementList[1:])]

rawDescription: Iterate through list and going back one item


code: data3['bins_spd'] = pd.qcut(data3['spd_pct'], 5, labels=False)

rawDescription: Python Pandas Create New Bin/Bucket Variable with pd.qcut


code:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.Qt import *
from PyQt5.QtCore import *

class MyWindow(QMainWindow):
    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        qp.setBrush(QColor(200, 0, 0))
        qp.drawRect(a, b, x, y)
        qp.end()

def updateValues():
    global a, x
    a += 1
    x += 1
    mw.update()  # <-- update the window!

a = 10
b = 15
x = 90
y = 60

app = QApplication(sys.argv)

mw = MyWindow()
mw.setWindowTitle('PyQt5 - Main Window')
mw.setWindowIcon(QIcon("icon.jpg"))
mw.resize(300,100)

timer = QTimer()
timer.timeout.connect(updateValues)
timer.start(33)

mw.show()
sys.exit(app.exec_())

rawDescription: Animating a rectangle in PyQT5: Why is QtCore not defined?


code:
import re
string = 'abc10ghi44'
re.search('abc(\d+)', string).group(1)

rawDescription: Nested regular expression

description: Nested regular expression


code:
df = pd.read_csv("factories.csv")
by_factory = df.groupby("Factory")["Cost"].sum()

rawDescription: Python - sumif from csv

description: Python - sumif from csv


code:
def gen_subsets_special(full_set, M, seed=123456):
    # generate randomish M-subsets of full_set, "far apart".
    import random
    from random import sample
    random.seed(seed)
    elements = list(full_set)
    allix = set(range(len(elements)))
    takefrom = allix.copy()

    def destructive_sample(n):
        # Remove a random n-subset from takefrom, & return it.
        s = set(sample(takefrom, n))
        takefrom.difference_update(s)
        return s

    while True:
        if len(takefrom) >= M:
            # Get everything from takefrom.
            ix = destructive_sample(M)
        else:
            # We need to take all of takefrom, and more.
            ix = takefrom
            takefrom = allix - ix
            ix |= destructive_sample(M - len(ix))
        assert len(ix) == M
        yield set(elements[i] for i in ix)

rawDescription: Deterministic python generator for K disparate M-sized subsets of a set


code:
def __init__(self):
    self._UUID = None

    self.PartNumber = CustomParameter("Part Number", "V_ID")
    self.Name = CustomParameter("Name", "V_name")
    self.StandardPart = CustomParameter("Standard Part", "V508_isStandardPart")
    self.PartType = CustomParameter("Part Type", "V511_PartType")
    self.ControlledBy = CustomParameter("ControlledBy", "V511_ControlledBy")
    self.PIN = CustomParameter("PIN", "BOECACPinItemNumber")

rawDescription: Why do my nested python class instances become tuples?


code:
def truncate(sio):
    sio.truncate(0)
    sio.seek(0)
    return sio

def new(sio):
    return StringIO()

rawDescription: how do I clear a stringio object?

description: Clear a stringio object


code: print(func)

rawDescription: Python multiprocessing Pool Interaction With Namespace At Creation


code:
from itertools import chain

[r[:1] + tuple(chain(*re.findall(r'(\w+)\s*=\s*(\w+)', r[1])))
 for r in re.findall(r"{% url '(\w+)'((?:\s+\w+\s*=\s*\w+)*) \s*%}", inputtext)]

rawDescription: python 3.3 RE How to grab possible groups?

description: Python 3.3 RE How to grab possible groups


rawDescription: How do I build a python string from a raw (binary) ctype buffer?

description: Build a python string from a raw (binary) ctype buffer


code:
properties = []
for property in driver.find_elements_by_css_selector('table.property div.property'):
    title = property.find_element_by_css_selector('div.title h2')
    location = property.find_element_by_css_selector('div.title h4')
    marketing_package = property.find_element_by_partial_link_text('Marketing Package')

    properties.append({
        'title': title.text,
        'location': location.text,
        'marketing_package_url': marketing_package.getAttribute('href')
    })

rawDescription: Checking Websites for Updates (Web Automation with Python + Selenium)


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

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


code: from numpy import *

rawDescription: Relationship between scipy and numpy

description: Relationship between scipy and numpy


code: QComboBox

rawDescription: PySide / PyQt QStyledItemDelegate list in table


code:
import pandas
import numpy

df = pandas.DataFrame({'user_id':[1,2,1,4],'value':[100,100,200,200]})

# Get unique users and unique features
num_rows = len(df['user_id'].unique())
num_features = len(df['value'].unique())
unique_users = df['user_id'].unique().copy()
unique_features = df['value'].unique().copy()
unique_users.sort()
unique_features.sort()

# assign each user_id to a row_number
user_lookup = pandas.DataFrame({'uid':range(num_rows), 'user_id':unique_users})

vec_dict = {}

# Create a sparse vector for each feature
for i in range(num_features):
    users_with_feature = df[df['value']==unique_features[i]]['user_id']

    uid_rows = user_lookup[user_lookup['user_id'].isin(users_with_feature)]['uid']

    vec = numpy.zeros(num_rows)
    vec[uid_rows] = 1

    sparse_vec = pandas.Series(vec).to_sparse(fill_value=0)

    vec_dict[unique_features[i]] = sparse_vec

my_pandas_frame = pandas.DataFrame(vec_dict)
my_pandas_frame = my_pandas_frame.set_index(user_lookup['user_id'])

rawDescription: How to efficiently create a SparseDataFrame from a long table?

description: Efficiently create a SparseDataFrame from a long table


rawDescription: extracting specific rows of Nx3 array whereby each column satisfies condition

description: Extracting specific rows of Nx3 array whereby each column satisfies condition


code:
import re  # for the re.IGNORECASE flag
df['Key'].str.contains('our', re.IGNORECASE).groupby(df['GridCode']).sum()

rawDescription: pandas - groupby by partial string

description: Pandas - groupby by partial string


code:
mask = pixel_array == paddingVal
byte_array[mask] = 0
byte_array[~mask] = np.round(255.0 * (pixel_array[~mask] - minVal) / (maxVal - minVal - 1.0))

rawDescription: What is an efficient way to scale a int16 numpy array to a int8 numpy array


rawDescription: I am losing unicode characters somewhere (Python3)


code: r = urlopen("{0}?{1}".format(url, encodeddata))

rawDescription: Sending javascript form data in python (post request)?


code:
def func(**kwargs):
    """Some function to do stuff to arbitrary keyword arguments.

    Args:
      **kwargs: Arbitrary keyword arguments.

    """
    ...

rawDescription: How to add python docstring for dict

description: Add python docstring for dict


code:
class _CharField( models.CharField ):
   def __init__( self ):
       #remember this calls with self as the child class
       self.max_length = self.patterns_field[ 'max' ]
       #or for equivelent of EmailField.patterns_field (assuming you dont know EmailField) refer to self.__class__
       self.max_length = self.__class__.patterns_field[ 'max' ]
       #self.__class__ is the Class of the caller(in this case the child)

rawDescription: How to access a 'static' field of a child class in a base class?

description: Access a 'static' field of a child class in a base class


code:
import paramiko
ssh = paramiko.SSHClient()
# Uncomment the following line for the equivalent of -oStrictHostKeyChecking=no
#ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('103.116.140.151', username='user', password='diana_123')
stdin, stdout, stderr = ssh.exec_command("date")
date = stdout.read()
print(date)

rawDescription: python + auto ssh proccess to get date info

description: Python + auto ssh proccess to get date info


code:
import csv
import itertools

with open("dedup.csv", newline="") as fp_in, open("dedup_out.csv", "w", newline="") as fp_out:
    reader = csv.DictReader(fp_in)
    writer = csv.DictWriter(fp_out, reader.fieldnames)
    writer.writeheader()
    for key, group in itertools.groupby(reader, key=lambda row: row["ORIG"]):
        group = list(group)
        if len(group) == 2:
            group = [row for row in group if not float(row["SEQ_TIME"]) == 0]
        writer.writerows(group)

rawDescription: What's the most elegant, Pythonic way to deduplicate two sequential records in a CSV and retaining one record?


rawDescription: Match string between special characters

description: Match string between special characters


code:
import sqlite3

conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE words (word UNIQUE)')

with open('A.txt') as file_a, conn:
    cursor = conn.cursor()
    for line in file_a:
        cursor.execute('INSERT OR IGNORE INTO words VALUES (?)', (line.strip(),))

rawDescription: check whether a string is in a 2-GB list of strings in python

description: Check whether a string is in a 2-GB list of strings in python


rawDescription: Counting how many unique identifiers there are by merging two columns of data?


code:
person, john, smith, 1, 2, 3
person, anne, frank, 4, 5, 6
person, bob, macdonald, 7, 8, 9

rawDescription: Compare entries in columns from CSV files and extract matched - python


code:
proc = subprocess.Popen('./scriptname', shell = True,
                       cwd = tests)
proc.communicate()

rawDescription: seg fault when called from python, but runs normally from the command line

description: Seg fault when called from python, but runs normally from the command line


code: notification.send(Users.objects.all(), "friends_invite", {"from_user": from_user})

rawDescription: reusable application for django site wide announcements that displays a message only once per user

description: Reusable application for django site wide announcements that displays a message only once per user


code:
class WhoLikes(db.Model):
    users = db.StringListProperty()

rawDescription: modelling the google datastore/python

description: Modelling the google datastore/python


code:
f = get_multivar_lambda('foo')
f(1)
f(1, 2)
f(x=100)

rawDescription: Python - Exact Number of Arguments Defined by Variable


rawDescription: Python lists and ctypes

description: Python lists and ctypes


code: '\tdemo with some leading  \t and trailing whitespace\n'.split()

rawDescription: What happens if we split by a delimiter yet have multiple of those delimiters in a row?


code:
from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User)

    def __unicode__(self):
        return self.user.get_full_name()

rawDescription: Connect to User Model in Django

description: Connect to User Model in Django


code: sortedWords = {}

rawDescription: Print different results in Python a dictionary


code:
with open(csv_file, 'w') as f:
    for line in table:
        line = '|'.join([c.strip() for c in line.split('|')])
        f.write(line + '\n')

rawDescription: remove leading and trailing spaces but not in between the words

description: Remove leading and trailing spaces but not in between the words


code:
class dform(forms.Form):
    location = forms.ModelChoiceField(queryset = Location.objects.all())

rawDescription: update django choice field with database results

description: Update django choice field with database results


code:
from random import seed, random

# should all be the same value, whatever that is.
seed(1)
print(random())
seed(1)
print(random())
seed(1)
print(random())

# should be two different values (and different from above)
print(random())
print(random())

# should be same as first three values
seed(1)
print(random())

rawDescription: How do I randomize a list of strings with random.seed?

description: Randomize a list of strings with random.seed


rawDescription: Cumulative addition whilst looping over a list


code: n2 = NavigationNode(_('Item 1'), "item1/", 2, attr={'class': 'item1-class'})

rawDescription: Adding CSS item to Django menu

description: Adding CSS item to Django menu


code: (df[column] == -1).sum()

rawDescription: Find the count of -1 in each column

description: Find the count of -1 in each column


code: number = float(filename[7:-2])

rawDescription: Extract number from file name in python

description: Extract number from file name in python


code:
import readline

DEFAULT_TEXT = ''

def default_hook():
    """Insert some default text into the raw_input."""
    readline.insert_text(default_hook.default_text)
    readline.redisplay()

readline.set_pre_input_hook(default_hook)

def raw_input_default(prompt, default=None):
    """Take raw_input with a default value."""
    default_hook.default_text = DEFAULT_TEXT if default is None else default
    return raw_input(prompt)

rawDescription: Pre-initialize raw_input with default value


code:
avg = lambda lst: float(sum(lst))/len(lst)
result = {item: avg(values) for item, values in items.items()}

rawDescription: Link two dictionaries lists and calculate average values


code:
if whatever:
   self.methodA()
else:
   self.methodB()

rawDescription: Calling parent class with multiple inheritance in python


code: A - mean[:, None]

rawDescription: Remove mean from numpy matrix

description: Remove mean from numpy matrix


code: fm  = pd.fama_macbeth(y=df['y'],x=df[['x']],intercept=False)

rawDescription: Fama Macbeth Regression in Python (Pandas or Statsmodels)


code: theset = set(k.lower() for k in thedict)

rawDescription: Case insensitive dictionary search with Python


code:
df_copy.loc[df['D']=='Test', 'A'] = df['B']
df_copy.loc[df['D']=='Other', 'A'] = df['C']

rawDescription: Copy value from one column based on the value of another column


code:
import random
[random.randint(2, 5) for _ in range(random.randint(15, 20))]
[random.randint(2, 5) for _ in range(random.randint(15, 20))]
[random.randint(2, 5) for _ in range(random.randint(15, 20))]
[random.randint(2, 5) for _ in range(random.randint(15, 20))]

rawDescription: Using a While loop to generate ints to append?


code: [func(a[lbl == i]) for i in index]

rawDescription: Python - Apply a function over a labeled multidimensional array


code: cumtrapz(y, x=x, axis=0, initial=0)

rawDescription: Working with multiple columns from a data file


code:
if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()

rawDescription: Python Ternary Style: Is this good or bad style?


code:
class BlogPost(Document):
    tags = ListField(StringField())
    last_tag = StringField()
    # other things

rawDescription: How to prepend an element to a list in Mongoengine

description: Prepend an element to a list in Mongoengine


code:
for line in wordlist:
    if not line.startswith(word):
        wordlist.remove(line)

rawDescription: Python- The Word Game "Ghost", File I/O, and List question


code:
import turtle
import time

t = turtle.Turtle()
win = turtle.Screen()

for i in range(100):
    t.fd(100)
    t.hideturtle()
    time.sleep(1)
    t.showturtle()

rawDescription: How do I make turtle objects in python appear and disappear again with a while loop?

description: Make turtle objects in python appear and disappear again with a while loop


code:
t = tf.constant(42.0)
sess = tf.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.get_default_session()
    assert t.eval() == sess.run(t)

rawDescription: In TensorFlow, what is the difference between Session.run() and Tensor.eval()?


code:
def pattern(n):
  for i in range(1,n+1,2):
      print (i*str(i))

rawDescription: Number patterns in Python3x

description: Number patterns in Python3x


code: set(x for x in mylist if mylist.count(x) >= 2)

rawDescription: Why doesn't this set comprehension work?

description: Why doesn't this set comprehension work


code:
def RobotBox():
    Price = PositiveValuedProperty("Price")
    Weight = PositiveValuedProperty("Weight")

rawDescription: Python 3.4 - How to create a template property for many classes


code: d1 = d.set_index("hw0"); d1

rawDescription: csv parsing and manipulation using python

description: Csv parsing and manipulation using python


code:
import pygame,random
from pygame.locals import *
from collections import namedtuple
import shelve

pygame.init()
clock=pygame.time.Clock()
screen=pygame.display.set_mode((640,480))

max_gravity = 100

class Block(object):
    sprite = pygame.image.load("dirt.png").convert_alpha()
    def __init__(self, x, y):
        self.rect = self.sprite.get_rect(centery=y, centerx=x)

class Player(object):
    sprite = pygame.image.load("dirt.png").convert()
    sprite.fill((0,255,0))
    def __init__(self, x, y):
        self.rect = self.sprite.get_rect(centery=y, centerx=x)
        # indicates that we are standing on the ground
        # and thus are "allowed" to jump
        self.on_ground = True
        self.xvel = 0
        self.yvel = 0
        self.jump_speed = 10
        self.move_speed = 8

    def update(self, move, blocks):

        # check if we can jump
        if move.up and self.on_ground:
            self.yvel -= self.jump_speed

        # simple left/right movement
        if move.left: self.xvel = -self.move_speed
        if move.right: self.xvel = self.move_speed

        # if in the air, fall down
        if not self.on_ground:
            self.yvel += 0.3
            # but not too fast
            if self.yvel > max_gravity: self.yvel = max_gravity

        # if no left/right movement, x speed is 0, of course
        if not (move.left or move.right):
            self.xvel = 0

        # move horizontal, and check for horizontal collisions
        self.rect.left += self.xvel
        self.collide(self.xvel, 0, blocks)

        # move vertically, and check for vertical collisions
        self.rect.top += self.yvel
        self.on_ground = False;
        self.collide(0, self.yvel, blocks)

    def collide(self, xvel, yvel, blocks):
        # all blocks that we collide with
        for block in [blocks[i] for i in self.rect.collidelistall(blocks)]:

            # if xvel is > 0, we know our right side bumped
            # into the left side of a block etc.
            if xvel > 0: self.rect.right = block.rect.left
            if xvel < 0: self.rect.left = block.rect.right

            # if yvel > 0, we are falling, so if a collision happpens
            # we know we hit the ground (remember, we seperated checking for
            # horizontal and vertical collision, so if yvel != 0, xvel is 0)
            if yvel > 0:
                self.rect.bottom = block.rect.top
                self.on_ground = True
                self.yvel = 0
            # if yvel < 0 and a collision occurs, we bumped our head
            # on a block above us
            if yvel < 0: self.rect.top = block.rect.bottom

colliding = False
Move = namedtuple('Move', ['up', 'left', 'right'])

def load():
    try:
        f = shelve.open("save.bin")
        return f['player'], f['blocks']
    except KeyError:
        return None
    finally:
        f.close()

def save(player, blocks):
    f = shelve.open("save.bin")
    f['player'] = player
    f['blocks'] = blocks
    f.close()

player, blocklist = load() or (None, [])

while True:
    screen.fill((25,30,90))
    mse = pygame.mouse.get_pos()
    key = pygame.key.get_pressed()

    for event in pygame.event.get():
        if event.type == QUIT:
            save(player, blocklist)
            exit()

        if key[K_LSHIFT]:
            if event.type==MOUSEMOTION:
                if not any(block.rect.collidepoint(mse) for block in blocklist):
                    x=(int(mse[0]) / 32)*32
                    y=(int(mse[1]) / 32)*32
                    blocklist.append(Block(x+16,y+16))
        else:
            if event.type == pygame.MOUSEBUTTONUP:
                if event.button == 1:
                    to_remove = [b for b in blocklist if b.rect.collidepoint(mse)]
                    for b in to_remove:
                        blocklist.remove(b)

                    if not to_remove:
                        x=(int(mse[0]) / 32)*32
                        y=(int(mse[1]) / 32)*32
                        blocklist.append(Block(x+16,y+16))

                elif event.button == 3:
                    x=(int(mse[0]) / 32)*32
                    y=(int(mse[1]) / 32)*32
                    player=Player(x+16,y+16)

    move = Move(key[K_UP], key[K_LEFT], key[K_RIGHT])

    for b in blocklist:
        screen.blit(b.sprite, b.rect)

    if player:
        player.update(move, blocklist)
        screen.blit(player.sprite, player.rect)

    clock.tick(60)
    pygame.display.flip()

rawDescription: Save a list of objects on exit of pygame game


code:
fruits = [Fruit('apple', 'red'), Fruit('banana', 'yellow')]

print("An apple is %s" % fruits[fruits.index('apple')].color)

rawDescription: Accessing list of Python objects by object attribute


code:
s = 'fakeline\nfirstline\nsecondline\nthirdline'
s[s.index('\n')+1:] # add 1 to get the character after the newline

rawDescription: Best way to remove all characters of a string until new line character is met python?

description: Remove all characters of a string until new line character is met python


code:
result = {}
for e in wp_users:
    for k, v in zip(('ID', 'post_author'), e):
        result[k] = v

rawDescription: multiple key value pairs in dict comprehension

description: Multiple key value pairs in dict comprehension


rawDescription: Python compare list and store in new variable


code:
def triu(A, k=0, format=None):
    A = coo_matrix(A, copy=False)
    mask = A.row + k <= A.col
    row = A.row[mask]
    col = A.col[mask]
    data = A.data[mask]
    return coo_matrix((data,(row,col)), shape=A.shape).asformat(format)

rawDescription: Python Scipy How to traverse upper/lower trianglar portion non-zeros from csr_matrix


code: execfile('tokens/acc1.py', globals())

rawDescription: Can't make execfile() variables be global instead of local


code: datetime.timedelta( someSeconds/86400 )

rawDescription: How to put timedelta in django model?

description: Put timedelta in django model


rawDescription: Python- Split out src IP, src Port, dest IP, dest Port and create a dictionary


code:
parser.add_argument('-s', "--startdate", help="The Start Date - format YYYY-MM-DD ",
                    required=True, type=valid_date)

rawDescription: Specify format for input arguments argparse python


rawDescription: how to make kivy widgets make a pause

description: Make kivy widgets make a pause


code: l3 = list(map(deepcopy,(list1, list2)))

rawDescription: 2d list to 3d list in python

description: 2d list to 3d list in python


rawDescription: Python: Read binary file into buffer as integer then Slice


code:
result = {}
for key, v1, v2 in inputlist:
    minimum, maximum = result.get(key, (float('inf'), float('-inf')))
    if v1 < minimum:
        minimum = v1
    if v2 > maximum:
        maximum = v2
    result[key] = (minimum, maximum)

rawDescription: Can Python's comprehensions make groups?

description: Can Python's comprehensions make groups


rawDescription: Python Django - Load column from Database into list


code:
import subprocess
child = subprocess.Popen(['vlc', '-I', 'rc', '--novideo', '--noaudio',
                          '--rc-fake-tty', '-q', 'udp://@1.2.3.4:1234'],
                         stdin=PIPE, stdout=PIPE)
def split_on_prompts():
    rbuf = ''
    while True:
        newbuf = child.stdout.read()
        rbuf += newbuf
        out, prompt, rest = rbuf.partition('\n>')
        if prompt:
            yield out
            rbuf = rest
        if not newbuf:
            yield rest
            return
output = split_on_prompts()
banner = next(output)
child.stdin.write('info\n')
response = next(output)
# etc.

rawDescription: run command in interactive opend bash with python

description: Run command in interactive opend bash with python


code:
data = {"foo": {"bar": {"baz": 1}}}
lookup = {
  'customfield': ("foo", "bar", "baz" )
}
def nest(data, name):
  path = lookup[name]
  d = data
  for p in path:
    d = d[p]
  return d
nest(data, 'customfield')

rawDescription: How to handle dictionary attributes at arbitrarily nested depths?

description: Handle dictionary attributes at arbitrarily nested depths


code: fn = lambda x: x if True else lambda x: x*x

rawDescription: anonymous function assignment using a one line if statement

description: Anonymous function assignment using a one line if statement


code:
def f(low, high):
    ranges = collections.deque([(low, high)])
    while ranges:
        low, high = ranges.popleft()
        mid = (low + high) // 2
        yield mid
        if low < mid:
            ranges.append((low, mid))
        if mid + 1 < high:
            ranges.append((mid + 1, high))

rawDescription: Binary selection process

description: Binary selection process


code:
@root.setter
def root(self,value):
    self._root = BSTNode(value)

rawDescription: Confusion with recursion and property setters in Python


rawDescription: Sorting a list inside dictionary keys

description: Sorting a list inside dictionary keys


code:
class Computer(object):
    def __init__(self, name, status, date, kind):
        self.name   = name
        self.status = status
        self.date   = date
        self.kind   = kind

    @classmethod    # convenience method for not repeating the name
    def new_to_dict(cls, name, status, date, kind, dictionary):
        dictionary[name] = cls(name, status, date, kind)

rawDescription: What is a better way to store a list of properties against one item in Python?


rawDescription: How to select columns from frame in HDFStore

description: Select columns from frame in HDFStore


code:
fig = plt.figure()
for i in range(6):
    ax = fig.add_subplot(3,2,i)
    ax.plot(linspace(-1,1),sin(2*pi*linspace(-1,1)))
    draw()
    frame_range = [[]]

    ax.set_aspect(1)
    ax.set_xticks([])
    ax.set_yticks([])
#    ax.set_frame_on(False)
#    ax.add_patch(dt.PolygonPatch(provs[0],fc = 'None', ec = 'black'))

fig.tight_layout(pad=0,w_pad=0, h_pad=0)
subplots_adjust(left=0.25,right=0.75,wspace=0, hspace=0)

rawDescription: matplotlib: remove horizontal gap between axes?

description: Matplotlib: remove horizontal gap between axes


code:
category.most_common()
for value, count in category.most_common():
    print(value, count)

rawDescription: Formatting output of Counter

description: Formatting output of Counter


code:
from django.shortcuts import render_to_response
import feedparser

def index(content):
    entries = feedparser.parse ("http://news.yahoo.com/rss/").entries
    return render_to_response('index.html', {'entries': entries})

rawDescription: Displaying view function in Django

description: Displaying view function in Django


code:
import inspect
import importlib
import ast

def get_call_lines(mod):
    mod = importlib.import_module(mod)
    p = ast.parse(inspect.getsource(mod))
    for n in p.body:
        if isinstance(n, ast.Expr):
            for node in ast.walk(n):
                if isinstance(node, ast.Call):
                    yield(node.lineno)

from StringIO import StringIO
new = StringIO()
with open("test1.py") as f:
    st = set(get_call_lines("test1"))
    for ind, line in enumerate(f, 1):
        if ind not in st:
            new.write(line)

new.seek(0)
print(new.read())

rawDescription: Comment Python function calls in a string with source code


code:
d = datetime.strptime(StartPostingDateFilter, "%Y-%m-%d")

sub = d.replace(year=d.year - 1) if (d.month != 2 and d.day) != 29 else datetime(d.year-1, 2, 28)

rawDescription: Separate one year from a data value; taking care of leap years


code:
counts_and_means = \
    my_data.groupby("Category").agg (
        {
            "Category"  : np.count_nonzero ,
            "val_1"     : np.mean ,
            "val_2"     : [np.mean,lambda arr : stats.ttest_1samp(arr, popmean=0)[1]]
        }
    )

rawDescription: Pandas: Aggregating and applying multiple functions to same column