code:
class WorkloadPutSerializer(serializers.Serializer):

    vdi = VdiSerializer(required = False)
    db = DbSerializer(required = False)
    pk = serializers.IntegerField(read_only=True)

    def validate(self, data):
        """
        Check if at least one of data['vdi'] or data['vm']
        exists and then return the data. Otherwise raise
        ValidationError.
        """
        if data['vdi'] or data['vm']:
            return data
        else:
            raise serializers.ValidationError("No No No")

rawDescription: Relational condition check in Django Rest Framework


code:
from Bio import PDB

class OnlyACAResideus(PDB.Select):
    def accept_residue(self, res):
        return res in residuesACA

io = PDBIO()

# Presumably, you still have the structure, but you can unfold it like so:
struct = PDB.Selection.unfold_entities(residuesACA, 'S')[0]
io.set_structure(struct)
io.save("struct.pdb", select=OnlyACAResidues())

rawDescription: Align & save structure segment only

description: Align & save structure segment only


code:
day_dictionary={'mon':0,'tues':0,'wed':0,'thurs':0,'fri':0,'sat':0,'sun':0}
for i in random_day_list:
     for position, day in enumerate(i):
         if day in day_dictionary:
             day_dictionary[day] += (6 - position)

rawDescription: Tuples of list and string

description: Tuples of list and string


code:
class Store(models.Model):
    ...

class Applicant(models.Model):
    name = models.CharField(max_length=200)
    ...
    was_completed = models.BooleanField(default=False)

    stores = ManyToManyField(Store, related_name='applicants')

rawDescription: Create a MultipleChoiceField using rows from another model,


rawDescription: How do I prevent Qt buttons from appearing in a separate frame?

description: Prevent Qt buttons from appearing in a separate frame


code:
import subprocess

def launchWithoutConsole(command, args):
    """Launches 'command' windowless and waits until finished"""
    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    return subprocess.Popen([command] + args, startupinfo=startupinfo).wait()

if __name__ == "__main__":
    # test with "pythonw.exe"
    launchWithoutConsole("d:\\bin\\gzip.exe", ["-d", "myfile.gz"])

rawDescription: Running a process in pythonw with Popen without a console


code:
strings = Series(['om', 'foo_nom', 'nom', 'bar_foo', 'foo','blah'])
ending_strings = ("nom", "foo")
strings.str.endswith(ending_strings)

rawDescription: Pandas: fastest way to check if words in Series A endswith one word of Series B


code:
def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bisect_right(a, x)
    if i != len(a):
        return a[i]
    raise ValueError

rawDescription: Finding the index of an element in a sorted list efficiently


code:
import csv

with open(filename, 'rU') as f:
   reader = csv.reader(f, delimiter=',')
   next(reader)
   for row in reader:
      print(row[1])  # Column 'B'

rawDescription: select specific col of a CSV file for tokenization

description: Select specific col of a CSV file for tokenization


code:
import pylab as plt
import numpy as np

Z=np.array(((1,2,3,4,5),(4,5,6,7,8),(7,8,9,10,11)))
im = plt.imshow(Z, cmap='hot')
plt.colorbar(im, orientation='horizontal')
plt.show()

rawDescription: How can I display a np.array with pylab.imshow()

description: Display a np.array with pylab.imshow()


code:
import urllib.request
myurl = 'http://blahblah/acsvfile.csv'
myreq = urllib.request.urlopen(myurl)
mydata = myreq.read()
with open('mydata.html', 'wb') as ofile:
    ofile.write(mydata)

rawDescription: save a url to a file and keep it in memory

description: Save a url to a file and keep it in memory


code:
from operator import itemgetter
import datetime

starts = [
{'start_count': 33, 'month': datetime.datetime(2016, 5, 1, 0, 0)},
{'start_count': 79, 'month': datetime.datetime(2016, 4, 1, 0, 0)},
{'start_count': 72, 'month': datetime.datetime(2016, 3, 1, 0, 0)}
]

# dummy data
ends = [
{'end_count': 122, 'month': datetime.datetime(2016, 5, 1, 0, 0)},
{'end_count': 213, 'month': datetime.datetime(2016, 4, 1, 0, 0)},
{'end_count': 121, 'month': datetime.datetime(2016, 3, 1, 0, 0)}
]

starts = dict(map(itemgetter('month', 'start_count'), starts))
ends = dict(map(itemgetter('month', 'end_count'), ends))

joined = [{'month': m, 'start_count': s,  'end_count': ends.get(m, None)}
    for m, s in starts.items()]

rawDescription: How to merge list of dicts based on dict attribute uniquely

description: Merge list of dicts based on dict attribute uniquely


code:
for i, customer in enumerate(cust):
  if custname == customer:
    curCustIndex = i

rawDescription: Using a list index in a variable in python 3.3


code:
addthis = "INSERT INTO my_table (something) VALUES (%s);"
mark.execute(addthis, ('a string you wish to insert',))

rawDescription: Forming an insert statement with single quotes in Python with Postgres


rawDescription: Assign multiple values in range

description: Assign multiple values in range


rawDescription: Why does a χ² test in scipy return a lesser test statistic?


code:
years = range(2012, 2016)
txt = " UNION ALL ".join("SELECT {} AS Year".format(y) for y in years)
stmt = text(txt).columns(Year=Integer) # @note: works only on sqlachemy >= 0.9
# stmt = text(txt, typemap={'Year': Integer}) # note: fall back for SA version < 0.9
q = session.query(MyClass, stmt) # @note: since there is no JOIN, it will return cartesian product
for row in q.all():
    print(row)

rawDescription: sqlalchemy create a list of integers as a subquery

description: Sqlalchemy create a list of integers as a subquery


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

# your x data
x = np.arange(10)

# your y data
data = np.arange(1,4)[:,None] * np.arange(10)[None,:]

# your colors
color = ['k','r','g']

fig,ax = plt.subplots(1)

for y,c in itertools.izip(data,color):
    ax.step(x,y,c)

plt.show()

rawDescription: Python matplotlib set color of graphs

description: Python matplotlib set color of graphs


code:
mapping = [[one, two, three], [four, five, six], [seven, eight, nine]]

for i in range(0, 9):
    for j in range(0, 9):
        square = mapping[i/3][j/3]
        square.append(sudoku[i][j])

rawDescription: How can I refactor this line of code:

description: Refactor this line of code:


code:
#!/usr/bin/env python
class O(object):
    def __repr__(self):
        return '<%s.%s object at 0x%x>'%(self.__module__,self.__class__.__name__,id(self))
o=O()
print(repr(o))

# <__main__.O object at 0xb7e7d0cc>

rawDescription: Rolling my own __repr__

description: Rolling my own __repr__


code:
sum = 0
count = 0
integer = eval(input("Enter an integer; end with 0 when done: "))
if integer == 0:
    print("You didn't enter any integers.")
else:
    while integer != 0:
        sum += integer
        count += 1
        integer = eval(input("Enter an integer; end with 0 when done: "))

# Now calculate your average and print the results.

rawDescription: Python Hep with loops and strings?

description: Python Hep with loops and strings


code: l = list(t)

rawDescription: Python: unpack to unknown number of variables?


code:
import numpy as np
big = np.array([10**100, 10**101, 10**102], dtype='object')
big
big + np.array([1, 2, 3])

rawDescription: Is there a numpy biginteger?

description: Is there a numpy biginteger


code:
@receiver(pre_save, sender=Country)
def country_presave_callback(sender, instance, *args, **kwargs):
    ...

rawDescription: Pre save a slug on creation results in a 'LogEntry' object has no attribute pre_save


code:
import tables
import numpy as np
param = 10
with tables.open_file('save.hdf','w') as saveFile:
    tabledef = {'var1':tables.Float64Col(shape=(param))}
    table = saveFile.create_table(saveFile.root,'test',tabledef)
    tablerow = table.row
    tablerow['var1'] = np.array([1,2,3,4,5,6,7,8,9,0])
    tablerow.append()
    table.flush()
with tables.open_file('save.hdf','r') as sv:
    sv.root.test.read()

rawDescription: How can the shape of a pytables table column be defined by a variable?


rawDescription: Is there an equivalent of PHP's hash_hmac in Python/Django?


code:
def power_two(n):
    return int(math.log(n, 2))

rawDescription: find largest power of two less than X number?

description: Find largest power of two less than X number


code:
from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.checkbox = QtGui.QCheckBox('Delete')
        self.button = QtGui.QPushButton('Open', self)
        self.button.clicked.connect(self.openDialog)
        layout = QtGui.QHBoxLayout(self)
        layout.addWidget(self.checkbox)
        layout.addWidget(self.button)

    def openDialog(self):
        widget = QtGui.QDialog(self)
        if (self.checkbox.isChecked() and
            not widget.testAttribute(QtCore.Qt.WA_DeleteOnClose)):
            widget.setAttribute(QtCore.Qt.WA_DeleteOnClose)
            for child in self.findChildren(QtGui.QDialog):
                if child is not widget:
                    child.deleteLater()
        label = QtGui.QLabel(widget)
        button = QtGui.QPushButton('Close', widget)
        button.clicked.connect(widget.close)
        layout = QtGui.QVBoxLayout(widget)
        layout.addWidget(label)
        layout.addWidget(button)
        objects = self.findChildren(QtCore.QObject)
        label.setText('Objects = %d' % len(objects))
        print(objects)
        widget.show()

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 100, 50)
    window.show()
    sys.exit(app.exec_())

rawDescription: Is deleteLater() necessary in PyQt/PySide?


code:
cols_retained = ['column_a','column_e','column_wa']
_ = [df.drop([c for c in df if c not in cols_retained], axis='columns', inplace=True)
     for df in df_list]

rawDescription: Select colunms of a Data Frame in a loop


code:
def split_dataframe(df, size):

    # size of each row
    row_size = df.memory_usage().sum() / len(df)

    # maximum number of rows of each segment
    row_limit = size // row_size

    # number of segments
    seg_num = (len(df) + row_limit - 1) // row_limit

    # split df
    segments = [df.iloc[i*row_limit : (i+1)*row_limit] for i in range(seg_num)]

    return segments

rawDescription: Pandas dataframe split by memory usage

description: Pandas dataframe split by memory usage


code:
class UploadHandler(webapp.RequestHandler):
    def post(self):
        mime_type = self.request.headers['X-File-Type']
        name = self.request.headers['X-File-Name']
        file_name = files.blobstore.create(mime_type=mime_type,
                                           _blobinfo_uploaded_filename=name)
        with files.open(file_name, 'a') as f:
            f.write(self.request.body)
        files.finalize(file_name)
        blob_key = files.blobstore.get_blob_key(file_name)

rawDescription: How to receive an uploaded file to store it using Blobstore API

description: Receive an uploaded file to store it using Blobstore API


code:
import pymel.core as pc
transforms = pc.listTransforms(vtx.node())
transform = transforms[0] #in case there is only one.

rawDescription: How to select geo when you have a component of that geo?

description: Select geo when you have a component of that geo


code:
class Person:
     id = Column(Integer, primary_key=True)
     todays_events = relationship('Event', primaryjoin='and_(Person.id == Event.person_id, cast(Event.start, Date) == func.current_date()')

rawDescription: Current Date in SQLAlchemy ORM relationship


code:
import cv2
import sys
from datetime import datetime

# Initialize variables
camSource = -1
running = True
saveCount = 0
nSecond = 0
totalSec = 3
strSec = '321'
keyPressTime = 0.0
startTime = 0.0
timeElapsed = 0.0
startCounter = False
endCounter = False

# Start the camera
camObj = cv2.VideoCapture(camSource)
if not camObj.isOpened():
    sys.exit('Camera did not provide frame.')

frameWidth = int(camObj.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH))
frameHeight = int(camObj.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT))

# Start video stream
while running:
    readOK, frame = camObj.read()

    # Display counter on screen before saving a frame
    if startCounter:
        if nSecond < totalSec:
            # draw the Nth second on each frame
            # till one second passes
            cv2.putText(img = frame,
                        text = strSec[nSecond],
                        org = (int(frameWidth/2 - 20),int(frameHeight/2)),
                        fontFace = cv2.FONT_HERSHEY_DUPLEX,
                        fontScale = 6,
                        color = (255,255,255),
                        thickness = 5,
                        lineType = cv2.CV_AA)

            timeElapsed = (datetime.now() - startTime).total_seconds()
#            print 'timeElapsed: {}'.format(timeElapsed)

            if timeElapsed >= 1:
                nSecond += 1
#                print 'nthSec:{}'.format(nSecond)
                timeElapsed = 0
                startTime = datetime.now()

        else:
            cv2.imwrite('img' + str(saveCount) + '.jpg', frame)
#            print 'saveTime: {}'.format(datetime.now() - keyPressTime)

            saveCount += 1
            startCounter = False
            nSecond = 1

    # Get user input
    keyPressed = cv2.waitKey(3)
    if keyPressed == ord('s'):
        startCounter = True
        startTime = datetime.now()
        keyPressTime = datetime.now()
#        print 'startTime: {}'.format(startTime)
#        print 'keyPressTime: {}'.format(keyPressTime)

    elif keyPressed == ord('q'):
        # Quit the while loop
        running = False
        cv2.destroyAllWindows()

    # Show video stream in a window
    cv2.imshow('video', frame)

camObj.release()

rawDescription: python opencv display time countdown using putText in webcam video

description: Python opencv display time countdown using putText in webcam video


code:
with open(adresse,"r") as f:
    reader = csv.reader(f,delimiter = ",")
    data = list(reader)
    row_count = len(data)

rawDescription: Row count in a csv file

description: Row count in a csv file


code:
# if alice win
alice, bob = rate_1vs1(alice, bob)
# if bob win
bob, alice = rate_1vs1(bob, alice)
# if drawn
alice, bob = rate_1vs1(alice, bob, drawn=True)  # order doesn't matter in this case

rawDescription: From match results to rating using Trueskill (in Python)


code:
a = np.arange(8)[:,None].repeat(8,axis=1)
a
b = a.reshape(2,4,2,4)
b
b.transpose(0,2,1,3)

rawDescription: Using reshape in Python to reshape an array


code:
@route('/upload')
def upload():
    #Upload-Form
    return static_file('upload_form.html', root='html')

@post('/load_from_file')
def load_from_file():
    #Actual Uploading
    if request.POST.Upload == 'Submit Query':
        try:
            data = request.POST.Filedata.file
            filename = request.POST.Filename
            filepath = os.path.join(settings.FOLDERS["TEMP_WORKING"], filename)
            with open(filepath, "wb") as file_object:
                while True:
                    datachunk = data.file.read(1024)
                    if not datachunk:
                        break
                    file_object.write(datachunk)
            process_files_upload(filepath)
        except:
            print(traceback.format_exc())
        #Check if only uploaded or already finished
        return "Upload Finished"
    else:
        redirect('/upload')

rawDescription: jquploader + bottle.py -Can't get it to work :(

description: Jquploader + bottle.py -Can't get it to work :(


code:
import uuid

uuid.uuid5(uuid.NAMESPACE_OID, 'your string here')

rawDescription: Hash function that protects against collisions, not attacks. (Produces a random UUID-size result space)


code:
class Message(models.Model):
   date = models.DateField()
   text = models.CharField(max_length=255)
   users = models.ManyToManyField('auth.User')

rawDescription: Many to many reverse relationship Django


code:
print("""
something.......something...
{0}
and then again some string......
""".format(abs(-10.5)))

rawDescription: calling function in print(""" """)

description: Calling function in print(""" """)


code:
import inspect

def magical_way(f):
    return inspect.getargspec(f)[0]

rawDescription: Python list function argument names

description: Python list function argument names


code:
def test_foo():
    tries_so_far = 0

    def get(arg1):
        nonlocal tries_so_far
        if tries_so_far < 3:
            tries_so_far += 1
            print("do something special here")
        else:
            print("do something else here")
        return "some return val"

    foo(get, "some arg")

rawDescription: Python: modify method-local variable inside inner method


code:
from datetime import datetime, timedelta
last_month = datetime.today() - timedelta(days=30)
items = Item.objects.filter(my_date__gte=last_month).order_by(...)

rawDescription: Getting all items less than a month old

description: Getting all items less than a month old


rawDescription: Split string into letters and numbers

description: Split string into letters and numbers


code:
import tkinter as tk
from tkinter import ttk

LARGE_FONT = ("Verdana", 14)
ANSWER_FONT = ("Verdana", 20, "bold")

class myApp(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        container = ttk.Frame(self)
        container.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in [StartPage, PageOne]:
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class StartPage(ttk.Frame):

    def __init__(self, parent, controller):

        ttk.Frame.__init__(self, parent)
        self.controller = controller
        label = ttk.Label(self, text="StartPage", font=LARGE_FONT)
        label.pack(padx=10, pady=10)

        but_1 = ttk.Button(self, text="Page 1",
                            command=self.page_one_command)
        but_1.pack(padx=10, pady=10)

    def page_one_command(self):
        self.controller.show_frame(PageOne)
        self.controller.frames[PageOne].set_unanswer()  # Only after calling the show_frame you call the set method that will set the focus and the textvariable.

class PageOne(ttk.Frame):

    def __init__(self, parent, controller):

        ttk.Frame.__init__(self, parent)

        label = ttk.Label(self, text="Page One", font=LARGE_FONT)
        label.pack(pady=10, padx=10)

        frame_answ = ttk.Frame(self)
        frame_answ.pack(side=tk.TOP, fill=tk.X)

        self.useranswer = tk.StringVar()
        self.entry_answ = ttk.Entry(self, textvariable=self.useranswer, font=ANSWER_FONT, justify=tk.CENTER)
        self.entry_answ.pack(fill=tk.X)

        frame_button = ttk.Frame(self)
        frame_button.pack(padx=10, pady=10)
        but_next = ttk.Button(frame_button, text="back", state=tk.NORMAL,
                                command=lambda: controller.show_frame(StartPage))
        but_next.pack(side=tk.LEFT)

    def set_unanswer(self):
        self.useranswer.set("a default value")
        self.entry_answ.focus_set()

app = myApp()
app.geometry("300x150+300+300")
app.mainloop()

rawDescription: OOP tkinter: How to set focus (and add text) to entry?


code:
while running:
    rect = pygame.Rect(10, 20, 30, 30)
    pygame.draw.rect(screen, (255,0,0), rect)
    pygame.display.flip()

    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pressed = True
        if event.type == pygame.QUIT:
            running = False

    while mouse_pressed:
        # do your stuff
        mouse_pressed = False

rawDescription: Pygame: getting a loop to run after mouse click


code:
fig, ax = plt.subplots()
data = np.random.rand(4,4)
pcolor(data)
colorbar()

rawDescription: Plot background and labels in the same graph-matplotlib


code:
import traceback

def foo():
    bar()

def bar():
    baz()

def baz():
    traceback.print_stack()
    # or trace = traceback.extract_stack()

foo()

rawDescription: How to backtrace a function in python 2.7?

description: Backtrace a function in python 2.7


code:
import time
from threading import Thread

stop = False

def print_loop():
    num = 0
    while not stop:
        num = num + 1
        print(num)
        time.sleep(1)

thread = Thread(target=print_loop)
thread.start()

time.sleep(10)

stop = True
thread.join()

rawDescription: How properly close thread in Python

description: How properly close thread in Python


code:
mydict = {'Jack': {'age': 15, 'location': 'UK'},
          'Jill': {'age': 23, 'location': 'US'}}

datalist = []

for name in mydict:
  data = mydict[name]
  data['name'] = name
  datalist.append(data)

rawDescription: Converting a dict of dicts into a spreadsheet


code:
import webapp2

import copy
import decimal
import logging
import random
import string

from google.appengine.api import datastore_errors
from google.appengine.datastore import entity_pb
from google.appengine.ext import deferred
from google.appengine.ext import ndb

TEST_BATCH_SIZE = 250
TEST_NAME_LEN = 12

class DecimalProperty(ndb.Property):
    """A Property whose value is a decimal.Decimal object."""

    def _datastore_type(self, value):
      return str(value)

    def _validate(self, value):
      if not isinstance(value, decimal.Decimal):
        raise datastore_errors.BadValueError('Expected decimal.Decimal, got %r'
                                             % (value,))
      return value

    def _db_set_value(self, v, p, value):
        value = str(value)
        v.set_stringvalue(value)
        if not self._indexed:
            p.set_meaning(entity_pb.Property.TEXT)

    def _db_get_value(self, v, _):
        if not v.has_stringvalue():
            return None
        value = v.stringvalue()
        return decimal.Decimal(value)

class BatchInProgress(ndb.Model):
    """Use a scheduler to delete batches in progress after a certain time"""

    started = ndb.DateTimeProperty(auto_now=True)

    def clean_up(self):
        qry = Shard.query().filter(Shard.batch_key == self.key)
        keys = qry.fetch(keys_only=True)
        while keys:
            ndb.delete_multi(keys)
            keys = qry.fetch(keys_only=True)

def cleanup_failed_batch(batch_key):
    batch = batch_key.get()

    if batch:
        batch.clean_up()
        batch.delete()

class Shard(ndb.Model):
    """Shards for each named counter"""

    counter_key = ndb.KeyProperty(name='c')
    batch_key = ndb.KeyProperty(name='b')
    count = DecimalProperty(name='v', default=decimal.Decimal('0.00'),
                            indexed=False)

class Counter(ndb.Model):
    """Tracks the number of shards for each named counter"""

    @property
    def shards(self):
        qry = Shard.query().filter(Shard.counter_key == self.key)
        results = qry.fetch(use_cache=False, use_memcache=False)
        return filter(None, results)

    @property
    def total(self):
        count = decimal.Decimal('0.00') # Use initial value if no shards

        for shard in self.shards:
            count += shard.count

        return count

    @ndb.tasklet
    def incr_async(self, value, batch_key):
        index = batch_key.id()
        name = self.key.id() + str(index)

        shard = Shard(id=name, count=value,
                      counter_key=self.key, batch_key=batch_key)

        yield shard.put_async(use_cache=False, use_memcache=False)

    def incr(self, *args, **kwargs):
        return self.incr_async(*args, **kwargs).get_result()

@ndb.tasklet
def increment_batch(data_set):
    batch_key = yield BatchInProgress().put_async()
    deferred.defer(cleanup_failed_batch, batch_key, _countdown=3600)

    # NOTE: mapping is modified in place, hence copying
    mapping = copy.copy(data_set)

    # (1/3) filter and fire off counter gets
    #       so the futures can autobatch
    counters = {}
    ctr_futs = {}
    ctr_put_futs = []
    zero_values = set()
    for name, value in mapping.iteritems():
        if value != decimal.Decimal('0.00'):
            ctr_fut = Counter.get_by_id_async(name) # Use cache(s)
            ctr_futs[name] = ctr_fut
        else:
            # Skip zero values because...
            zero_values.add(name)
            continue

    for name in zero_values:
        del mapping[name] # Remove all zero values from the mapping
    del zero_values

    while mapping: # Repeat until all transactions succeed

        # (2/3) wait on counter gets and fire off increment transactions
        #       this way autobatchers should fill time
        incr_futs = {}
        for name, value in mapping.iteritems():
            counter = counters.get(name)
            if not counter:
                counter = counters[name] = yield ctr_futs.pop(name)
            if not counter:
                logging.info('Creating new counter %s', name)
                counter = counters[name] = Counter(id=name)
                ctr_put_futs.append(counter.put_async())
            else:
                logging.debug('Reusing counter %s', name)
            incr_fut = counter.incr_async(value, batch_key)
            incr_futs[(name, value)] = incr_fut

        # (3/3) wait on increments and handle errors
        #       by using a tuple key for variable access
        for (name, value), incr_fut in incr_futs.iteritems():
            counter = counters[name]
            try:
                yield incr_fut
            except:
                pass
            else:
                del mapping[name]

        if mapping:
            logging.warning('%i increments failed this batch.' % len(mapping))

    yield batch_key.delete_async(), ctr_put_futs

    raise ndb.Return(counters.values())

class ShardTestHandler(webapp2.RequestHandler):

    @ndb.synctasklet
    def get(self):
        if self.request.GET.get('delete'):
            ndb.delete_multi_async(Shard.query().fetch(keys_only=True))
            ndb.delete_multi_async(Counter.query().fetch(keys_only=True))
            ndb.delete_multi_async(BatchInProgress.query().fetch(keys_only=True))
        else:
            data_set_test = {}
            for _ in xrange(TEST_BATCH_SIZE):
                name = ''
                for _ in xrange(TEST_NAME_LEN):
                    name += random.choice(string.letters)
                value = decimal.Decimal('{0:.2f}'.format(random.random() * 100))
                data_set_test[name] = value
            yield increment_batch(data_set_test)
        self.response.out.write("Done!")

app = webapp2.WSGIApplication([('/shard_test/', ShardTestHandler)], debug=True)
app = ndb.toplevel(app.__call__)

rawDescription: Reliable way to execute thousands of independent transaction?


code:
from enum import Enum

states = Enum('<a descriptive name>', 'one two three four')

rawDescription: elixir like atomics in python?

description: Elixir like atomics in python


code:
a = np.array([1,2,4,5,1,4,2,1])
b = np.array([1,2]) # Your test array
np.in1d(a,b)

rawDescription: How to construct logical expression for advanced slicing

description: Construct logical expression for advanced slicing


code:
df
df.columns = df.columns.map("".join)
df

rawDescription: Reset index on multilevel columns in pandas so that higher index perfaces lower index


rawDescription: Launch an exernal program with Python, but without waiting


rawDescription: snmpwalk : get list of integers not string

description: Snmpwalk : get list of integers not string


code:
import matplotlib.pyplot as plt
ax = plt.subplot(111, frame_on=False)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)

the_table = plt.table(cellText=table_vals,
    colWidths = [0.5]*len(col_labels),
    rowLabels=row_labels, colLabels=col_labels,
    cellLoc = 'center', rowLoc = 'center')

plt.show()

rawDescription: Plot table and display Pandas Dataframe

description: Plot table and display Pandas Dataframe


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

class MyTransform(mpl.transforms.Transform):
  input_dims = 2
  output_dims = 2
  def __init__(self, base_point, base_transform, offset, *kargs, **kwargs):
    self.base_point = base_point
    self.base_transform = base_transform
    self.offset = offset
    super(mpl.transforms.Transform, self).__init__(*kargs, **kwargs)
  def transform_non_affine(self, values):
    new_base_point = self.base_transform.transform(self.base_point)
    t = mpl.transforms.Affine2D().translate(-new_base_point[0], -new_base_point[1])
    values = t.transform(values)
    x = values[:, 0:1]
    y = values[:, 1:2]
    r = np.sqrt(x**2+y**2)
    new_r = r-self.offset
    new_r[new_r<0] = 0.0
    new_x = new_r/r*x
    new_y = new_r/r*y
    return t.inverted().transform(np.concatenate((new_x, new_y), axis=1))

def my_plot(X,Y):
  ax = plt.gca()
  line, = ax.plot(X, Y, marker='o', linestyle='')
  color = line.get_color()

  size = X.size
  for i in range(1,size):
    mid_x = (X[i]+X[i-1])/2
    mid_y = (Y[i]+Y[i-1])/2

    # this transform takes data coords and returns display coords
    t = ax.transData

    # this transform takes display coords and
    # returns them shifted by `offset' towards `base_point'
    my_t = MyTransform(base_point=(mid_x, mid_y), base_transform=t, offset=10)

    # resulting combination of transforms
    t_end = t + my_t

    line, = ax.plot(
      [X[i-1], X[i]],
      [Y[i-1], Y[i]],
      linestyle='-', color=color)
    line.set_transform(t_end)

fig = plt.figure(figsize=(8,6))
axes = plt.subplot(111)

X = np.linspace(0,2*np.pi, 8)
Y = np.sin(X)
my_plot(X,Y)
plt.show()

rawDescription: Custom plot linestyle in matplotlib

description: Custom plot linestyle in matplotlib


rawDescription: Python equivalence of default in C#

description: Python equivalence of default in C#


code:
if X < i:
 register_mean[i] = np.mean(register[:i])

rawDescription: Compute mean of last X elements of a list in Python2.7


code:
class MyModelView(BaseModelView):
    form_widget_args = {
        'description': {
            'rows': 10,
            'class': 'input-xlarge'
        }
    }

rawDescription: Modify input field sizes in Flask-Admin

description: Modify input field sizes in Flask-Admin


code:
def extract_field(form_data, clean, fieldname, optional=('info', 'instruction')):
   if fieldname+'field' in form_data:
       infofield = { 'field': fieldname }
       for opt in optional:
           optname = '{}field_{}'.format(fieldname, opt)
           if optname in form_data:
              infofield[opt] = form_data[optname]
       clean.append(infofield)

extract_field(form_data, cleaned_data['infofields'], 'email')
extract_field(form_data, cleaned_data['infofields'], 'address')
extract_field(form_data, cleaned_data['infofields'], 'phone')

rawDescription: How to avoid repetitive if statements in python dictionaries

description: Avoid repetitive if statements in python dictionaries


code:
def composition(seq):
    seq = tuple(seq)
    for i in range(2**(len(seq)-1)):
        result = [[seq[0]]]
        for j in range(len(seq)-1):
            if i & (1<<j):
                result.append([seq[j+1]])
            else:
                result[-1].append(seq[j+1])
        yield result

if __name__=="__main__":
    from pprint import pprint
    pprint(list(composition('ABCD')))

rawDescription: Recursively generate Compositions from an ordered list


code:
plt.plot(x, y1, label='Line One')
plt.plot(x, y2, label='Line Two')
plt.legend(loc='best')

rawDescription: Matplotlib Legend Subtitles

description: Matplotlib Legend Subtitles


code:
def check_internal_ij(A,i,j):
    """ checks internal list i against internal list j """
    if A[i][0:2] == A[j][0:2]:
        new = [x+y for x,y in zip( A[i], A[j] )]
        new[0:2] = A[i][0:2]
        return new
    else:
        return None

rawDescription: Python: Adding list values to each other in a list of lists


code:
from django.templatetags.static import static
' '.format(static("image.png"))

rawDescription: Reference static files in django in .py files ( NOT in templates)


code:
import xlrd
mainData_book = xlrd.open_workbook("IEsummary.xls", formatting_info=True)
mainData_sheet = mainData_book.sheet_by_index(0)
for row in range(1, 101):
    rowValues = mainData_sheet.row_values(row, start_colx=0, end_colx=8)
    company_name = rowValues[0]

    link = mainData_sheet.hyperlink_map.get((row, 0))
    url = '(No URL)' if link is None else link.url_or_path
    print(company_name.ljust(20) + ': ' + url)

rawDescription: Getting a hyperlink URL from an Excel document


code:
import struct
"%x:%x:%x:%x:%x:%x" % struct.unpack("BBBBBB",your_variable_with_mac)

rawDescription: Python. Print mac address out of 6 byte string


code:
for elm in soup.select('div[class^="wallpapers-box"] > a[href*=wallpapers]'):
    print(elm.get_text())

rawDescription: how to extract text using Beautifulsoup

description: Extract text using Beautifulsoup


code:
from selenium import webdriver

ff = webdriver.Firefox()
ff.implicitly_wait(10) # seconds
ff.get("http://somedomain/url_that_delays_loading")
myDynamicElement = ff.find_element_by_id("myDynamicElement")

rawDescription: Selenium determine browser is frozen

description: Selenium determine browser is frozen


code:
tiddata = '<Mkey3><456><Mkey2><Mval2><MKey1><MVal1>'
t = tiddata.strip('<>').split('><')
output = {t[i]: t[i+1] for i in range(0, len(t), 2)}

rawDescription: Extract a dictionary from <key><val>...<key><val> wiredata


code: (tck, u), fp, ier, msg = interpolate.splprep([[1.,2.,3.,4.,5.]], full_output=True)

rawDescription: Get spline fit residual from scipy.interpolate.splprep()


code:
num_labels = 10

# label_batch is a tensor of numeric labels to process
# 0 <= label < num_labels

sparse_labels = tf.reshape(label_batch, [-1, 1])
derived_size = tf.shape(label_batch)[0]
indices = tf.reshape(tf.range(0, derived_size, 1), [-1, 1])
concated = tf.concat(1, [indices, sparse_labels])
outshape = tf.pack([derived_size, num_labels])
labels = tf.sparse_to_dense(concated, outshape, 1.0, 0.0)

rawDescription: Tensorflow One Hot Encoder?

description: Tensorflow One Hot Encoder


code: [0 if type(i) is str else i for i in h]

rawDescription: Find string values in list and replace them


code:
locale.setlocale(locale.LC_ALL, '')
locale.format("%.4f", 12345.678912, grouping=True)

rawDescription: How to format a number with comma and specified precision digits in Python

description: Format a number with comma and specified precision digits in Python


code:
from tkinter import Tk, Frame, Label, Entry, Button

class App(Frame):
    def __init__(root, master):
        Frame.__init__(root, master)
        root.grid()
        root.create_widgets()

    def get_values(root):
        return [float(entry.get()) for entry in root.entries]

    def calc_CR(root):
        answer = sum(root.get_values()) #Replace with your own calculations
        root.answer.config(text=str(answer))

    def create_widgets(root):
        root.entries = []
        for i in range(20):
            label = Label(root, text=str(i))
            label.grid(row=i, column=0)

            entry = Entry(root, width=8)
            entry.grid(row=i, column=1)
            entry.insert(0, '0.00')
            root.entries.append(entry)

        root.calc_button = Button(root, text='Calculate C/R', command=root.calc_CR)
        root.calc_button.grid(row=20, column=0)

        root.answer = Label(root, text='0')
        root.answer.grid(row=20, column=1)

    def run(root):
        root.mainloop()

root = Tk()
root.title('C/R Calculator')

app = App(root)
app.run()

rawDescription: How to store values from an Entry widget for loop in tkinter?

description: Store values from an Entry widget for loop in tkinter


code:
def myfunc(request, id):
    form = NameForm(request.GET or None)
    if form.is_valid():
        key = form.cleaned_data['key']
        value = form.cleaned_data['value']
        # do something with key and value

rawDescription: Creating a simple django form

description: Creating a simple django form


code:
doc = {
  'script' : 'ctx._source.age = 30'
}
es.update(index="panavstream", doc_type='panav', id="123", body=doc)

rawDescription: elasticsearch python api overwrites the existing field

description: Elasticsearch python api overwrites the existing field


code:
class NamedPopen(Popen):
    def __init__(self, cargs, *args):
        Popen.__init__(self, cargs, *args)
        self.args = cargs

x = NamedPopen("ls")
x.args

rawDescription: Python: get command name of Popen instance


rawDescription: How to have unicode characters in Django model choices?

description: Have unicode characters in Django model choices


code:
import sys
from PyQt4.QtCore import QSettings
from PyQt4.QtGui import (QApplication, QWidget, QCheckBox, QPushButton,
                         QVBoxLayout)

RUN_PATH = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"

class MainWidget(QWidget):

    def __init__(self,parent=None):
        super(MainWidget, self).__init__(parent)
        self.settings = QSettings(RUN_PATH, QSettings.NativeFormat)
        self.setupUi()
        # Check if value exists in registry
        self.checkbox.setChecked(self.settings.contains("MainWidget"))

    def setupUi(self):
        self.checkbox = QCheckBox("Boot at Startup", self)
        button = QPushButton("Close", self)
        button.clicked.connect(self.close)
        layout = QVBoxLayout(self)
        layout.addWidget(self.checkbox)
        layout.addWidget(button)

    def closeEvent(self, event):
        if self.checkbox.isChecked():
            self.settings.setValue("MainWidget",sys.argv[0]);
        else:
            self.settings.remove("MainWidget");
        event.accept()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWidget()
    w.show()
    app.exec_()

rawDescription: PyQt: best way to do the trick "start at boot" for my program in Windows


code:
import json
translation = json.loads("""{
 "data": {
  "translations": [
   {
    "translatedText": "Toute votre base sont appartiennent  nous"
   },
   {
    "translate": "¡Qué bien!"
   }
  ]
 }
}
""")
translation
translation[u'data'][u'translations'][0][u'translatedText']
translation[u'data'][u'translations'][1][u'translate']

rawDescription: Get the value of specific JSON element in Python


code: df['Hour'] = df.index.hour

rawDescription: How to select weekday / hour in pandas when doing iteration

description: Select weekday / hour in pandas when doing iteration


code:
import os
import glob
import csv
from xlsxwriter.workbook import Workbook

for csvfile in glob.glob(os.path.join('.', '*.csv')):
    workbook = Workbook(csvfile + '.xlsx')
    worksheet = workbook.add_worksheet()
    with open(csvfile, 'rb') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                worksheet.write(r, c, col)
    workbook.close()

rawDescription: Python convert csv to xlsx

description: Python convert csv to xlsx


code:
from StringIO import StringIO

txt = """a       b       c       d
eggs    ham     1.0     0.0
eggs    ham     0.0     0.5
spam    eggs    0.0     1.0
spam    eggs    0.0     1.0"""

df = pd.read_csv(StringIO(txt), sep="\\s+")
df.groupby(["a","b"], as_index=False).mean()

rawDescription: Selecting and averaging values in pandas data frames


code:
def btest(i, pos):
    return i & (1 << pos)

rawDescription: Btest function in fortran, is there any equivalent in python?


code:
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = True
wb = excel.Workbooks.Add()
ws = wb.Worksheets('Sheet1')
ws.Range("A1:A4").Value = [[i] for i in range(1,5)]

rawDescription: how to fill values to one single column efficiently in excel file using pywin32?

description: Fill values to one single column efficiently in excel file using pywin32


code:
import numpy as np
from shapely.geometry.polygon import LinearRing

def ellipse_polyline(ellipses, n=100):
    t = linspace(0, 2*np.pi, n, endpoint=False)
    st = np.sin(t)
    ct = np.cos(t)
    result = []
    for x0, y0, a, b, angle in ellipses:
        angle = np.deg2rad(angle)
        sa = np.sin(angle)
        ca = np.cos(angle)
        p = np.empty((n, 2))
        p[:, 0] = x0 + a * ca * ct - b * sa * st
        p[:, 1] = y0 + a * sa * ct + b * ca * st
        result.append(p)
    return result

def intersections(a, b):
    ea = LinearRing(a)
    eb = LinearRing(b)
    mp = ea.intersection(eb)

    x = [p.x for p in mp]
    y = [p.y for p in mp]
    return x, y

ellipses = [(1, 1, 2, 1, 45), (2, 0.5, 5, 1.5, -30)]
a, b = ellipse_polyline(ellipses)
x, y = intersections(a, b)
plot(x, y, "o")
plot(a[:,0], a[:,1])
plot(b[:,0], b[:,1])

rawDescription: Finding intersection points of two ellipses (Python)


code:
from Crypto.PublicKey import RSA
from Crypto import Random
rng = Random.new().read
RSAkey = RSA.generate(1024, rng)

rawDescription: Pycrypto - Using Crypto.Random to generate a secret key and an initialisation vector


code:
import sys
import os
import os.path

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        template_menu = self.menuBar().addMenu('&Templates')
        menus = {'templates': template_menu}

        for dirpath, dirnames, filenames in os.walk('templates'):
            current = menus[dirpath]
            for dn in dirnames:
                menus[os.path.join(dirpath, dn)] = current.addMenu(dn)
            for fn in filenames:
                current.addAction(fn)

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

rawDescription: Building menu of files in folder hierarchy


code:
import _winreg as registry

proxy_server = 'some_proxy_server'  # dummy value
proxy_port = 'some_proxy_port'      # dummy value

key = registry.OpenKey(
    registry.HKEY_CURRENT_USER,
    r"Software\Microsoft\Windows\CurrentVersion\Internet Settings",
    0, registry.KEY_ALL_ACCESS)
proxy = proxy_server + ":" + proxy_port

# don't work for some reason...
#registry.SetValue(key, '_ProxyEnable', registry.REG_SZ, 'dword:00000001')
#registry.SetValue(key, '_ProxyServer', registry.REG_SZ, proxy)

# alternative that does work
registry.SetValueEx(key, "_ProxyEnable", 0, registry.REG_SZ, "dword:00000001")
registry.SetValueEx(key, "_ProxyServer", 0, registry.REG_SZ, proxy)

rawDescription: Registry change through python working incorrectly


code:
def get_level1_locations(lat_lng):
    elems = lat_lng.split(',')
    url = "http://maps.googleapis.com/maps/api/geocode/json?"
    url += "latlng=%s,%s&sensor=false" % (float(elems[0]), float(elems[1]))
    v = urlopen(url).read()
    j = json.loads(v)
    if len(j['results'])>0:
      components = j['results'][0]['address_components']
      location_list=[]
      for c in components:
          if "locality" in c['types']:
            location_list.append(c['long_name'])
          if "administrative_area_level_1" in c['types']:
            location_list.append(c['long_name'])
          if "country" in c['types']:
            location_list.append(c['long_name'])
      location = ', '.join(filter(None, location_list))
      return location
    return ''

rawDescription: GeocoderServiceError for geopy

description: GeocoderServiceError for geopy


code:
import StringIO

stream = StringIO.StringIO()
stream.write('...√#,›o~ño\Ä¶˚ﬂy™Ω.…Õo)Ú∞L∂W_≤Ï~˛⁄...')

image = wx.ImageFromStream(stream)

rawDescription: Add image to python script?

description: Add image to python script


rawDescription: Pandas Python - Create dummy variables for multiple conditions


code:
import random

number = random.randint(1, 10)
found = False

while  not found:
    try:
        guess = int(input("Guess a number between 1 and 10: "))
        if guess > number:
            print("Your guess is too high!")
        elif guess < number:
            print("That's too low.")
        elif guess == number:
            print("Thats's right!")
            found = True
    except ValueError:
        print("Please enter a number.")

rawDescription: Python "guess the number" game always returns the same answer


code:
import tkinter

class Creator(object):

    def __init__(self):

        root = self.root = tkinter.Tk()

        # Main Frame
        f_main = tkinter.Frame(root, borderwidth=6, relief='flat')
        f_main.grid(row=0, column=0, sticky='nsew')

        # Text widget and frame
        f_txt = tkinter.Frame(f_main, borderwidth=2, relief="sunken")
        f_txt.config(width=768, height=768)
        f_txt.pack(padx=4, pady=4, side="bottom", fill="both", expand=True)

        my_txt = self.text = tkinter.Text(f_txt)
        my_txt.config(undo=True, wrap='word')
        my_txt.grid(row=0, column=0, sticky="nsew")
        my_txt.focus_set()

GUI = Creator()
GUI.root.tk.eval("catch {tcl_endOfWord}")
GUI.root.tk.eval("catch {tcl_startOfPreviousWord}")
GUI.root.tk.eval("set tcl_wordchars {[[:alnum:]']}")
GUI.root.tk.eval("set tcl_nonwordchars {[^[:alnum:]']}")
GUI.root.mainloop()

rawDescription: defining what characters are selected when double clicking in a Text widget

description: Defining what characters are selected when double clicking in a Text widget


code: os.rename(thisFile, os.path.splitext(thisFile)[0] + ".doc")

rawDescription: How to add/replace a filename's extension in python?

description: Add/replace a filename's extension in python


code:
import datetime

print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Date now: %s' % datetime.datetime.now())
print('Date today: %s' % datetime.date.today())

today = datetime.date.today()
print("Today's date is {:%b, %d %Y}".format(today))

schedule = '{:%b, %d %Y}'.format(today) + ' - 6 PM to 10 PM Pacific'
schedule2 = '{:%B, %d %Y}'.format(today) + ' - 1 PM to 6 PM Central'
print('Maintenance: %s' % schedule)
print('Maintenance: %s' % schedule2)

rawDescription: How can I create basic timestamps or dates? (Python 3.4)

description: Create basic timestamps or dates? (Python 3.4)


code:
########### spawn all tasks at launch! ############
localmess = locals().values()
for obj in localmess:
    if isclass(obj):
        if obj is not PeriodicTask and issubclass(obj, PeriodicTask):
            instance = obj()
            logger.info('running {0}'.format(obj))
            try:
                instance.run()
            except:
                logger.info('SHIT!!! task FAIL!!! {0}'.format(obj))
                pass

######## all tasks must be decleared above! ########

rawDescription: celery beat schedule: run task instantly when start celery beat?

description: Celery beat schedule: run task instantly when start celery beat


code:
import pickle

# Save the DataFrame
pickle.dump(df, open( "dataFrame.p", "wb" ))

# Load the DataFrame
df_read =pickle.load( open( "dataFrame.p", "rb"))

rawDescription: How to edit data in a text file using python?

description: Edit data in a text file using python


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

im = np.flipud(plt.imread('so.jpg'))
plt.subplot(2, 1, 1)
plt.imshow(im)
plt.subplot(2, 1, 2)
plt.imshow(np.fliplr(im))
plt.show()

rawDescription: Flipping a picture across the vertical axis in python


code:
dic=[{'a':1,'b':2,'c':3},{'a':9,'b':2,'c':2},{'a':5,'b':1,'c':2}]

filt_dic = []
for d in dic:
    if not any(d[k] in seen[k] for k in d):
        filt_dic.append(d)
        for k in d:
            seen[k].add(d[k])

print(filt_dic)

rawDescription: Filter list of dictionaries with duplicate values at a certain key


code:
from django.forms import ModelForm
from .models import TwilioMessage

class MessageForm(ModelForm):
    pass

    class Meta:
        model = ReactionEvent
        # include all fields you're saving from the form here
        fields = ['body', 'to', 'from_', 'signature',]

rawDescription: Django QueryDict empty with request.POST but populated in request.GET


code:
blue  = colors[0]
green = colors[1]
red   = colors[2]
#or
b, g, r = colors

rawDescription: meanColor() get BGR simpleCV

description: MeanColor() get BGR simpleCV


code:
from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def main():
    return 'You could import render_template at the top, and use that here instead'

@app.route('/do_stuff', methods=['POST'])
def do_stuff():
    return 'You posted' + request.form.get('your string')

app.run('127.0.0.1', port=5555, debug=True)

rawDescription: Web application with python

description: Web application with python


code:
#!/usr/bin/env python
#

import os
import urllib

from google.appengine.ext import blobstore
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

class MainHandler(webapp.RequestHandler):
    def get(self):
        upload_url = blobstore.create_upload_url('/upload')
        self.response.out.write('')
        self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
        self.response.out.write("""Upload File: <input type="file" name="file">
 <input type="submit"
            name="submit" value="Submit"> </form>""")

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_uploads('file')  # 'file' is file upload field in the form
        blob_info = upload_files[0]
        self.redirect('/serve/%s' % blob_info.key())

class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, resource):
        resource = str(urllib.unquote(resource))
        blob_info = blobstore.BlobInfo.get(resource)
        self.send_blob(blob_info)

def main():
    application = webapp.WSGIApplication(
          [('/', MainHandler),
           ('/upload', UploadHandler),
           ('/serve/([^/]+)?', ServeHandler),
          ], debug=True)
    run_wsgi_app(application)

if __name__ == '__main__':
  main()

rawDescription: Upload a file in Google App Engine and making it downloadable


code:
from numpy import linspace
linspace(-7.5, 0.1, 6)
linspace(-7.5, 0.1, 6).tolist()

rawDescription: Calculating a range of an exact number of values in Python


rawDescription: Python replace / with \

description: Python replace / with \


rawDescription: Export QT Menu to text

description: Export QT Menu to text


code:
#updated
L = []
for index, line in enumerate(open('data.txt')):
    if index <= 4: #skip first 5 lines
        continue
    else:
         L.append(line.split()[2]) #split on whitespace and append value from third columns to list.
print(L)
#[6.0, 5.0, 7.0]

rawDescription: Reading a specific row & columns of data in a text file


code:
root = session.query(MyModel
).options(subqueryload('my_rel').subqueryload('sub_rel'))

rawDescription: SqlAlchemy ORM eager load an object's relationships


code:
z_bin = numpy.linspace(0.0, 10.0, 21)

for i in range(len(z_bin)-1):
    zmin = z_bin[i]
    zmax = z_bin[i+1]

    # do some things with zmin/zmax

rawDescription: using python numpy linspace in for loop

description: Using python numpy linspace in for loop


code: body = re.sub("$","</p>",re.sub("^", "<p>", body, flags=re.M),flags=re.M)

rawDescription: Insert <p> at the starting of each line and </p> at ending of each line in multi line string of Python using Regular Expression?


code:
class Category(models.Model):
    instrumentCategory=models.CharField(max_length=50,blank=True,null=True)

    def __unicode__(self):
        return self.instrumentCategory

rawDescription: Django populating ChoiceField with attributes from a ForeignKey


code:
cxy, _ = mlab.cohere(y1, y2, window=np.hamming(16), NFFT=16, noverlap=0, Fs=1)
print(cxy)

rawDescription: Why is cohere function in matplotlib (python) give answer different from mscohere function in MATLAB?


code:
import asyncio

@asyncio.coroutine
def some_task(name, number):
    print('task ', name, ' started')
    yield from asyncio.sleep(number)
    print('task ', name, ' finished')

@asyncio.coroutine
def loop_executer(loop):
    # you could use even while True here
    while loop.is_running():
        tasks = [
            some_task("A", 2),
            some_task("B", 5),
            some_task("C", 4)
        ]
        yield from asyncio.wait(tasks)

ev_loop = asyncio.get_event_loop()
ev_loop.create_task(loop_executer(ev_loop))
ev_loop.run_forever()

rawDescription: Forever repeat of an eventloop after each loop completion, in python 3.4


code: any('4110964_se' in f for f in files) # check if the string is in any of the list items

rawDescription: How to check for part of a string within a list?

description: Check for part of a string within a list


code:
while True:
  if first_number == second_number:
    do_something()
    break
  time.sleep(0.1)

rawDescription: Python: Most efficient loop until condition


code:
df = pd.DataFrame(np.reshape(np.arange(10), (5,2)), columns = ['A', 'B'])
df.iloc[2,1] = np.nan
df.iloc[3,1] = np.nan
df['C'] = df['B']/df['A']
df['C'] = df['C'].ffill()
nan= df[pd.isnull(df).any(1) == True]
nan['B'] = (nan['C'])*(nan['A'])
bla = pd.merge(df, nan, how = 'left', left_index=True, right_index=True)
bla['B_x'][bla['B_x'].isnull()] = bla['B_y'][bla['B_x'].isnull()]

rawDescription: How to specify the method for fillna in pandas

description: Specify the method for fillna in pandas


code:
from __future__ import print_function #needed python 2.7 only

import random
example_expression = lambda: random.random()

a = [0]
b = [-1]

[ print(a[0])
  for i in iter(int,1) #causes an infinite loop
  if  not a.__setitem__(0,example_expression()) #__setitem__ will return None
  and a[0]>b[0]
  and not b.__setitem__(0,a[0])  ]

rawDescription: Infinite loop in a lambda, print only maximum values?


code:
from sys import *
import re

lines = []
tokens = ["PRINT"]

def open_file(filename):
    data = open(filename, "r")
    for line in data.readlines():
        lines.append(line.replace('\n', ''))
    with open (filename, "r") as filecontents:
        data = filecontents.read().replace('\n', ' ')
    return data

def lex(filecontents):
    words = filecontents.split(" ")
    filecontents = list(filecontents)
    word = []
    states = 0
    statesRun = False
    statesBool = True
    string = ""
    stringAmount = 0
    toks = ""
    i = 0.0
    z = 0
    for i in range(len(words)):
        if words[int(i)].upper() == tokens[0].upper():
            word.append("PRINT")
            for char in lines[z]:
                toks += char
                if char == "\"":
                    if states == 0:
                        statesRun = True
                        if char == "\"" and statesBool == False:
                            states = 1
                            string += char
                            statesRun = False
                        statesBool = False
                    elif states == 1:
                        statesRun = False
                if statesRun:
                    string += char
            stringAmount += 1
            word.append("STRING:" + string)
            string = ""
            statesBool = True
            statesRun = False
            states = 0
            z += 1
    return word

def parse(toks):
    i = 0
    while(i < len(toks)):
        if toks[i].upper() + " " + toks[i+1][0:6].upper() == "PRINT STRING":
            print(toks[i+1][7:])
            i+=2

def run():
    data = open_file(argv[1])
    toks = lex(data)
    parse(toks)

run()

rawDescription: How to make my Python code read from the second line for my lexer

description: Make my Python code read from the second line for my lexer


rawDescription: How to clear text field part of ttk.Combobox?

description: Clear text field part of ttk.Combobox


code:
# in models.py
class Node(models.Model):
    parent = ForeignKey('Node')
    name = models.CharField(max_length = 256)

# in forms.py
from models import Node
from django.forms import ModelForm
from ajax_filtered_fields.forms import ForeignKeyByLetter

class NodeForm(ModelForm):
    class Meta:
        model = Node
    parent = ForeignKeyByLetter(Node, field_name = "name")

rawDescription: How to reference self as a model with django-ajax-related-fields

description: Reference self as a model with django-ajax-related-fields


code:
import paramiko
import time

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('localhost', username='user', password='password')

transport = ssh.get_transport()
channel = transport.open_session()
channel.exec_command('./exec_test.py')

status = channel.recv_exit_status()

rawDescription: How do I know the remote process is running, or complete?

description: Know the remote process is running, or complete


code:
pizza_act = use_action(function = mechanics.test()) #Wrong!
pizza_act = use_action(function = mechanics.test)  #Right

rawDescription: Timed Threaded function as an attribute in a class


code:
class Tester(object):
  def mymethod(self):
    return True

hasattr(Tester, 'mymethod')
hasattr(Tester.mymethod, 'im_func')

rawDescription: Rewrite python function without inspect module


code:
eula = dr.find_element_by_id('eulaFrame')
dr.execute_script('arguments[0].scrollTop = arguments[0].scrollHeight', eula)

rawDescription: Selenium Firefox webdrive, using Python, scrolling in div


code:
import cv2
import numpy as np

def nothing(x):
    pass

#image window
cv2.namedWindow('image')
cv2.namedWindow('image2')

# create trackbars for color change
cv2.createTrackbar('mask','image',1,10,nothing)
cv2.createTrackbar('mask2','image2',1,10,nothing)

#loading images
img = cv2.imread('VfgSN.png')     # load your image with path
gray_im = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

while True:
    # get current positions of trackbars
    m = cv2.getTrackbarPos('mask','image')
    m2 = cv2.getTrackbarPos('mask2','image2')
    median = cv2.medianBlur(gray_im,(2*m+1))
    median2 = cv2.medianBlur(img,(2*m2+1))
    cv2.imshow('image',median)
    cv2.imshow('image2',median2)
    #press ESC to stop
    k = cv2.waitKey(1) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()

rawDescription: What filter is used to remove corner effect on result


code:
#!/usr/local/env python

import pygtk
pygtk.require('2.0')
import gtk

def motion_cb(wid, context, x, y, time):
    l.set_text('\n'.join([str(t) for t in context.targets]))
    context.drag_status(gtk.gdk.ACTION_COPY, time)
    # Returning True which means "I accept this data".
    return True

def drop_cb(wid, context, x, y, time):
    # Some data was dropped, get the data
    wid.drag_get_data(context, context.targets[-1], time)
    return True

def got_data_cb(wid, context, x, y, data, info, time):
    # Got data.
    l.set_text(data.get_text())
    context.finish(True, False, time)

w = gtk.Window()
w.set_size_request(200, 150)
w.drag_dest_set(0, [], 0)
w.connect('drag_motion', motion_cb)
w.connect('drag_drop', drop_cb)
w.connect('drag_data_received', got_data_cb)
w.connect('destroy', lambda w: gtk.main_quit())
l = gtk.Label()
w.add(l)
w.show_all()

gtk.main()

rawDescription: Python GTK Drag and Drop - Get URL

description: Python GTK Drag and Drop - Get URL


code:
#!/usr/bin/python
#-*- coding:utf-8 -*-

import xlwt

base = xlwt.Workbook()

b = ['company1','company2']
a = ['a', 'b', 'c']

for name in b:
    n = 0
    s = base.add_sheet(name);
    for v in a:
        s.write(n, 0, v)
        n += 1

base.save('C:\\test.xls')

rawDescription: Writing data to excel iteratively

description: Writing data to excel iteratively


rawDescription: Python Format string "}" fill

description: Python Format string "}" fill


code:
n=raw_input("n:")
m=raw_input("m:")
k=0
res=''
if len(m)>len(n):
    n,m = m,n #this will swap
k=0
m = "0" * (len(n)-len(m)) + m #append zeroes to m at the begining
for i in range(len(n)-1,-1,-1):
    a=int(n[i])
    b = int(m[i])
    k=int(k)
    res+=str(int((a+b+k)%10))
    if a+b+k>9:
        k=1
    else:
        k=0

#add the remainder
if (k !=0) :
    res += str(k)

print(res[::-1])

rawDescription: Adding large numbers on python with an algorithm, not with standard calculating


code:
import os, subprocess

# Choose your PostgreSQL version here
os.environ['PATH'] += r';C:\Program Files (x86)\PostgreSQL\8.4\bin'
# http://www.postgresql.org/docs/current/static/libpq-envars.html
os.environ['PGHOST'] = 'localhost'
os.environ['PGPORT'] = '5432'
os.environ['PGUSER'] = 'someuser'
os.environ['PGPASSWORD'] = 'clever password'
os.environ['PGDATABASE'] = 'geometry_database'

base_dir = r"c:\shape_file_repository"
full_dir = os.walk(base_dir)
shapefile_list = []
for source, dirs, files in full_dir:
    for file_ in files:
        if file_[-3:] == 'shp':
            shapefile_path = os.path.join(base_dir, file_)
            shapefile_list.append(shapefile_path)
for shape_path in shapefile_list:
    cmds = 'shp2pgsql "' + shape_path + '" new_shp_table | psql '
    subprocess.call(cmds, shell=True)

rawDescription: Python Scripts to ingest a shapefile into a PostgreSQL/PostGIS database utilizing shp2pgsql.exe on windows


code:
coord_mask = (x_coords < 799) & (y_coords < 799)
for i in xrange(len(coord_mask)):
    distance = 0
    row_mask = coord_mask[i]
    row_x = x_coords[i, row_mask]
    row_y = y_coords[i, row_mask]
    mapvals = self.map[row_x, row_y] # advanced indexing
    ray_values, = (mapvals <= 0).nonzero()
    ...

rawDescription: Optimize numpy array maniplation for ray tracing


code:
import clips
clips.Load("classes.clp")
clips.Eval("(make-instance Fred of PERSON)")
clips.Eval("(make-instance Toyota of CAR)")
name_of_existing_person = "Fred"
name_of_existing_car = "Toyota"
clips_person_instance = clips.FindInstance(name_of_existing_person)
clips_car_instance = clips.FindInstance(name_of_existing_car)
list_of_cars = clips_person_instance.Slots["cars"]
list_of_cars.append(clips_car_instance.Name)
clips_person_instance.Slots["cars"] = list_of_cars
clips_person_instance.Slots["cars"]

rawDescription: Create multislot / multifield containing references to other clips instances


code:
def create(self, validated_data):
    obj = OriginalModel.objects.create(**validated_data)
    obj.save(foo=validated_data['foo'])
    return obj

rawDescription: Django rest framework: override create() in ModelSerializer passing an extra parameter


code:
from itertools import chain
[round(x, 4) for x in chain(*chain(*rlist))]

rawDescription: Python: an elegant way to extract floats from list?


code:
def main():
    with open("in.txt", "rb") as f, open('out.txt','w') as output:
        byte = f.read(1)
        while byte != "":
            output.write(str(ord(byte)))
            byte = f.read(1)

if __name__ == '__main__':
    main()

rawDescription: Writing to txt file in Python

description: Writing to txt file in Python


code:
import httplib2
http = httplib2.Http()

f = open('Tea.rdf')
body = f.read()
url = 'http://localhost:8080/openrdf-sesame/repositories/rep/statements'
headers = {'Content-type': 'application/rdf+xml;charset=utf-8'}
resp, content = http.request(url, 'PUT', body=body, headers=headers)
# resp will contain headers and status, content the response body

rawDescription: Alternative to PycURL?

description: Alternative to PycURL


code: pipe = subprocess.Popen("./args/Release/arg_count -arg", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

rawDescription: python subprocess missing arguments

description: Python subprocess missing arguments


code:
open_name = '%s.open' % __name__
with patch(open_name, create=True) as mock_open:
    mock_open.return_value = MagicMock(spec=file)
    with open('/some/path', 'w') as f:
        f.write('something')
file_handle = mock_open.return_value.__enter__.return_value
file_handle.write.assert_called_with('something')

rawDescription: How do I mock an open used in a with statement (using the Mock framework in Python)?

description: Mock an open used in a with statement (using the Mock framework in Python)


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

def main():
    data = read_data('test.dat', 512, 512)
    visualize(data)

def read_data(filename, width, height):
    with open(filename, 'r') as infile:
        # Skip the header
        infile.seek(512)
        data = np.fromfile(infile, dtype=np.uint16)
    # Reshape the data into a 3D array. (-1 is a placeholder for however many
    # images are in the file... E.g. 2000)
    return data.reshape((width, height, -1))

def visualize(data):
    # There are better ways to do this, but let's keep it simple
    plt.ion()
    fig, ax = plt.subplots()
    im = ax.imshow(data[:,:,0], cmap=plt.cm.gray)
    for i in xrange(data.shape[-1]):
        image = data[:,:,i]
        im.set(data=image, clim=[image.min(), image.max()])
        fig.canvas.draw()

main()

rawDescription: Displaying data from binary file in python


code:
from Tkinter import *

app = Tk()    #app is a variable, so in the future, you can define Tk() as anything you want. Most people call it root
frame = Frame(app)
frame.pack()

bottomframe = Frame(app)
bottomframe.pack( side = BOTTOM )

redbutton = Button(frame, text="Red", fg="red")
redbutton.pack( side = LEFT)

greenbutton = Button(frame, text="Brown", fg="brown")
greenbutton.pack( side = LEFT )

bluebutton = Button(frame, text="Blue", fg="blue")
bluebutton.pack( side = LEFT )

blackbutton = Button(bottomframe, text="Black", fg="black")
blackbutton.pack( side = BOTTOM)

app.mainloop()

rawDescription: Python GUI Constructor

description: Python GUI Constructor


code:
def get_last2d(data):
    if data.ndim <= 2:
        return data
    slc = [0] * (data.ndim - 2)
    slc += [slice(None), slice(None)]
    return data[slc]

rawDescription: numpy slice to return last two dimensions

description: Numpy slice to return last two dimensions


code:
import subprocess
from cStringIO import StringIO

input = StringIO(source_code) # source_code is a string with the source code.
output = StringIO()

process = subprocess.Popen(['sed', '/path/to/remccoms3.sed'],
    input=input, output=output)
return_code = process.wait()

stripped_code = output.getvalue()

rawDescription: Python snippet to remove C and C++ comments


code:
from bs4 import BeautifulSoup
html = '''

        text
        text

'''
soup = BeautifulSoup(html)
soup.select('a[title]')

rawDescription: python - bs4 grab only certain links

description: Python - bs4 grab only certain links


code:
qry = Person.query(Person.age > 20)
n_people_older_than_20 = qry.count()

rawDescription: How to use Google Datastore Satistics

description: Use Google Datastore Satistics


code:
import re
re.findall('"([^"]*)"', 'SetVariables "a" "b" "c" ')

rawDescription: Extract string from between quotations

description: Extract string from between quotations


code:
from werkzeug.serving import WSGIRequestHandler

# Your Flask code here...

if __name__ == "__main__":
    WSGIRequestHandler.wbufsize = -1
    app.run()

rawDescription: POST to Flask from espduino timing out

description: POST to Flask from espduino timing out


code:
#!/usr/bin/python
# EASY-INSTALL-ENTRY-SCRIPT: 'distribute==0.6.14','console_scripts','easy_install'
__requires__ = 'distribute==0.6.14'
import sys
from pkg_resources import load_entry_point

if __name__ == '__main__':
    sys.exit(
        load_entry_point('distribute==0.6.14', 'console_scripts', 'easy_install')()
    )

rawDescription: Does python's setuptools support the `__name__ == "__main__"` style of execution?


rawDescription: How to "collapse" rows that meet logic criteria in GroupBy


code:
from array import *

bin_array = array('B')

bin_array.append(int('011',2))
bin_array.append(int('010',2))
bin_array.append(int('110',2))

f = file('binary.mydata','wb')
bin_array.tofile(f)
f.close()

rawDescription: Write a binary integer or string to a file in python


code:
Complete_data = []
for currentrow in data:
    Product = currentrow[8].read()
    fixed_data = ([currentrow[0], currentrow[1], currentrow[2], currentrow[3], currentrow[4], currentrow[5], currentrow[6], currentrow[7], Product, currentrow[9]])
    Complete_data.append(fixed_data)

rawDescription: appending rows to a list as part of a loop Python

description: Appending rows to a list as part of a loop Python


code:
from types import GeneratorType

elementChosen = QtCore.pyqtSignal(GeneratorType)

rawDescription: Setting A Generator As The Argument Of A PyQt4 Signal


code:
def processURL(link):
    open_url = urllib2.urlopen(link).read()
    item_soup = BeautifulSoup(open_url)
    item_div = item_soup.find('div',{'id': 'transcript'},{'class': 'displaytext'})
    item_str = item_div.text.lower()
    item_str_processed = punctuation.sub('',item_str)
    item_str_processed_final = item_str_processed.replace('—',' ')

    splitlink = link.split("/")
    president = splitlink[4]
    speech_num = splitlink[-1].split("-")[1]
    filename = "{0}_{1}".format(president, speech_num)

    return filename, item_str_processed_final # returning a tuple

for link in every_link:
    filename, content = processURL(link) # yay tuple unpacking
    with open(filename, 'w') as f:
        f.write(content)

rawDescription: Writing items from function to separate text files?


rawDescription: List comprehension to normalize values in a matrix


rawDescription: Python Printing and multiplying strings in Print statement


code:
for child in tree.get_children():
    print(tree.item(child)["values"])

rawDescription: Python Tkinter Treeview - Iterating 'get_children' output


code:
import numpy as np
import pylab as pl

def f(x,b):
    return np.sin(x*b)*b

def draw(b):
    X = np.linspace(0,10,1000)
    F = f(X,b)
    ax1.plot(X, F, label='b = %f' %b)

# Main program
fig = pl.figure(figsize=(12, 16), num="My sine")
ax1 = pl.subplot2grid((4,3), (0,0), colspan=2)

for b in [0.4, 0.5, 0.6]:
    draw(b)

pl.legend(loc="best")
pl.show()

rawDescription: python: Multiple plotting in one subplot2grid-image

description: Python: Multiple plotting in one subplot2grid-image


code:
quit = False
while True:
    for event in pygame.event.get():
            if event.type == QUIT:
                quit = True
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                quit = True
    if quit is True:
        return

rawDescription: Stop a python program without signing out, Ctrl C, Alt F4, without use of mouse


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

H = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12],
              [13, 14, 15, 16]])  # added some commas and array creation code

fig = plt.figure(figsize=(6, 3.2))

ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')

cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()

rawDescription: Colorplot of 2D array matplotlib

description: Colorplot of 2D array matplotlib


code:
books = None

def getRandomBook():
    global books
    if books is None:
        books = list(getBookSet())
    return random.choice(books)

rawDescription: get random int from a set in python and how to improve performance

description: Get random int from a set in python and how to improve performance


code:
from itertools import chain

for paragraph in chain(doc.paragraphs, (paragraph for table in doc.tables for row in table.rows for cell in row.cells for paragraph in cell.paragraphs)):
    paragraph.replace("oldtext1","Something")
    paragraph.replace("oldtext2","Somethingelse")

rawDescription: Python Combine For-Loops

description: Python Combine For-Loops


code:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://example.com')
element = driver.find_element_by_class_name("yourClassName") #or find by text or etc
element.click()

rawDescription: How to scrape dynamic webpages by Python

description: Scrape dynamic webpages by Python


code: Pict1 = Slide1.Shapes.AddPicture(FileName=pictName, LinkToFile=False, SaveWithDocument=True, Left=100, Top=100, Width=200, Height=200)

rawDescription: Insert images to powerpoint slide using python (win32com.client)


code:
import csv
with open('/home/test/kelvin1/add.csv', 'wb') as csvfile:
    kev = csv.writer(csvfile, delimiter=' ',
                 quotechar='|', quoting=csv.QUOTE_MINIMAL)
    k ={'ID1':{'sam':1,'maj':5,'tif':7,'paul':1},'ID2':{'maj':4,'bib':5}}
    for i in k:
          kev.writerow(i)
          for j in k[i]:
              kev.writerow(j)
              kev.writerow('%d' % (k[i][j]))

rawDescription: How can I write a dictionary within another dictionary to a CSV file in Python

description: Write a dictionary within another dictionary to a CSV file in Python


rawDescription: Slicing of python os.listdir()

description: Slicing of python os.listdir()


code: new = [(i, i - 1) for i in lst if i - 1 in lst]

rawDescription: Comparing items within a list with each other


code:
start = datetime(2012, 1, 1)
end = datetime(2012, 10, 6)
delta = timedelta(days=1)
d = start
diff = 0
weekend = set([5, 6])
while d <= end:
    if d.weekday() not in weekend:
        diff += 1
    d += delta

rawDescription: Loop through dates except for weekends

description: Loop through dates except for weekends


code:
import wx
import wx.richtext
import wx.gizmos

def create(parent):
        return myFrame(parent)

[wxID_MYFRAME, wxID_MYFRAMEMYEITABLELISTBOX, wxID_MYFRAMEMYFRAME_PANEL,
 wxID_MYFRAMERICHTEXTCTRL1,
] = [wx.NewId() for _init_ctrls in range(4)]

class myFrame(wx.Frame):
    def _init_ctrls(self, prnt):

        wx.Frame.__init__(self, id=wxID_MYFRAME, name=u'myFrame', parent=prnt,
          pos=wx.Point(551, 188), size=wx.Size(500, 500),
          style=wx.DEFAULT_FRAME_STYLE, title=u'myPanel')
        self.SetClientSize(wx.Size(498, 466))
        self.SetInitialSize(wx.Size(500, 500))

        self.myFrame_panel = wx.Panel(id=wxID_MYFRAMEMYFRAME_PANEL,
              name=u'myFrame_panel', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(498, 466), style=wx.TAB_TRAVERSAL)

        self.myEitableListBox = wx.gizmos.EditableListBox(id=wxID_MYFRAMEMYEITABLELISTBOX,
              label=u'myEitableListBox', name=u'myEitableListBox',
              parent=self.myFrame_panel, pos=wx.Point(8, 56), size=wx.Size(200,
          248))
        self.myEitableListBox.SetStrings(['this', 'that', 'other'])

        self.richTextCtrl1 =    wx.richtext.RichTextCtrl(id=wxID_MYFRAMERICHTEXTCTRL1,
              parent=self.myFrame_panel, pos=wx.Point(224, 64),
              size=wx.Size(248, 240), style=wx.richtext.RE_MULTILINE,
              value=u'')
        self.richTextCtrl1.SetLabel(u'')

        self.myEitableListBox.ListCtrl.Bind(
            wx.EVT_LIST_ITEM_SELECTED, self.on_listbox)

    def __init__(self, parent):
        self._init_ctrls(parent)

    def on_listbox(self, event):
        text = '{}\n'.format(event.Text)
        self.richTextCtrl1.AppendText(text)

if __name__ == '__main__':
    app = wx.App()
    frame = create(None)
    frame.Show()

    app.MainLoop()

rawDescription: wx.python bind event to editableListBox list item's

description: Wx.python bind event to editableListBox list item's


code:
def intro():
    w.pack()
    intro = Tkinter.PhotoImage(file=r'intro.ppm')
    root.intro = intro
    w.create_image((0,0), image=intro, anchor='nw', tags=("intro"))
    w.after(3000, w.delete, "intro")

rawDescription: Python 2.7 time.sleep() with Canvas Tkinter (OS X)


rawDescription: PHP empty function in python

description: PHP empty function in python


code:
from django.db.models import Q

def search_items_and_exact(term):
    """Returns items with all searchable attributes exactly equals to term"""
    filters = {}
    for search_attr in Item.searchable():
        filters[search_attr] = term
    return Item.objects.filter(**filters)

def search_items_or_exact(term):
    """Returns items with any searchable attributes exactly equals to term"""
    q_seq = Q()
    for search_attr in Item.searchable():
        filters = {search_attr: term}
        q_seq = q_seq | Q(**filters)
    return Item.objects.filter(q_seq)

def search_items_and_contains(term, ignore_case=False):
    """Returns items with all searchable attributes contains term"""
    if ignore_case:
        contains = 'icontains'
    else:
        contains = 'contains'
    filters = {}
    for search_attr in Item.searchable():
        filters["{0}__{1}".format(search_attr, contains)] = term
    return Item.objects.filter(**filters)

def search_items_or_contains(term, ignore_case=False):
    """Returns items with any searchable attributes contains term"""
    if ignore_case:
        contains = 'icontains'
    else:
        contains = 'contains'
    q_seq = Q()
    for search_attr in Item.searchable():
        filters = {"{0}__{1}".format(search_attr, contains): term}
        q_seq = q_seq | Q(**filters)
    return Item.objects.filter(q_seq)

rawDescription: evaluate list to Object attributes in python / django

description: Evaluate list to Object attributes in python / django


code:
import matplotlib.pyplot as plt
from pylab import plot,axis,show,pcolor,colorbar,bone
import numpy as np

axiss = [(0, 0), (0, 1), (0, 0), (2, 2), (0, 2), (2, 2), (2, 0), (0, 2), (1, 2), (2, 0)]

# get unique elements
axiss_unique = list(set(axiss))
# get number of data at each datapoint
axiss_count = [axiss.count(x) for x in axiss_unique]

sc = 100 # scale up the datapoints for scatter
labels = [] # label each point according to number of data there
annotates = [] # intereactively label each point according to the datapoint name
for i in range(len(axiss_count)):
    labels.append('%i'%axiss_count[i])
    annotates.append( ' '.join(['u'+str(k) for k, j in enumerate(axiss) if j == axiss_unique[i]]))
    axiss_count[i] *= sc

x,y = zip(*axiss_unique)

fig, ax = plt.subplots()
# get offsets of the labels to each point
x_os, y_os = max(x)/20., max(y)/20.
ax.scatter(x, y, axiss_count)
for i, txt in enumerate(labels):
    ax.annotate(txt, (x[i]+x_os,y[i]+y_os), fontsize=15)

# interactive annotation
import interactive_annotations

af =  interactive_annotations.AnnoteFinder(x,y, annotates)
connect('button_press_event', af)

show()

rawDescription: Plot counter of data points in matlpotlib


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

fig, ax = plt.subplots(1,1)
N = 10
bar = ax.bar(range(N),np.random.normal(size=N))
mpld3.save_html(fig,'./out.html')

rawDescription: Plotting a bar chart from data in a python dictionary


code:
import itertools

max_length = 10
result = (''.join(word) for word in
             itertools.chain.from_iterable(
                 itertools.product(alphabet, repeat = i)
                     for i in range(1, max_length + 1)))

rawDescription: Enumerator for an alphabet in python

description: Enumerator for an alphabet in python


code: obj, created = Person.objects.get_or_create(first_name='John', last_name='Lennon', defaults={'birthday': date(1940, 10, 9)})

rawDescription: How to update/add data to Django application without deleting data

description: Update/add data to Django application without deleting data


code:
def mapValues(values):
    values = [float(i.split('%')[0]) for i in values]
    colorMap = np.array(['#F8696B', '#FFEB84', '#63BE7B'])
    #colorMap = np.array(["low", "mid", "high"])
    values = np.asarray(values)
    _, bins = np.histogram(values, 2)
    mapped = np.digitize(values, bins)
    return list(colorMap[mapped - 1])

def mapAndAdd(finalList, tempList, v1,v2,v3):
    v1 = mapValues(v1)
    v2 = mapValues(v2)
    v3 = mapValues(v3)
    for i,j in enumerate(newList):
        finalList.append(j + [v1[i] , v2[i] , v3[i]])

uniqueDataSet = set()

finalList = []
for index, DataSet in enumerate(lst):
    if (DataSet[0] + DataSet[1]) in uniqueDataSet:
        v1.append(DataSet[2])
        v2.append(DataSet[3])
        v3.append(DataSet[4])
        newList.append(DataSet)
    else:
        if (index != 0):
            mapAndAdd(finalList, newList, v1,v2,v3)

        uniqueDataSet.add(DataSet[0] + DataSet[1])
        newList = [DataSet]
        v1 = [DataSet[2]]
        v2 = [DataSet[3]]
        v3 = [DataSet[4]]

mapAndAdd(finalList, newList, v1,v2,v3)

rawDescription: "Conditional formatting" in python for each dataset in a list appending the hex colors


code:
s = u"→"
s
import lxml.html

my_string = "
I have a dream → Hello!
"
elem = lxml.html.fromstring(my_string)

if u'\u2192' in elem.text:
    print("bar")

rawDescription: Search for special HTML characters in text of lxml.html elements


code:
import re

s = "abc proxy=123&456"                 # Test string

mat = re.search(r'proxy=([^&]*)', s)
print(mat.group(1))                     # 123

rawDescription: Calling `sed` from inside a python program


code:
import board
import heuristic
import validation

...

class CNurikabe:     # the explicit (object) base class is not needed in Python 3
    def someFunc(self):
        for i in range(board.dimensionx):
            heuristics.doSomeStuff()
            validation.doSomeMore()

rawDescription: Python, correct approach for instancing classes once and using them within other classes


code:
Field('title', 'text', label=T('Please enter something:'),
      widget=lambda f, v: SQLFORM.widgets.text.widget(f, v, _rows=5))

rawDescription: Is there a way to pass parameter for textarea-rows from database to html


code:
number = 10
total_sum = int()
guess = int(input("Please enter an integer: "))
while guess != number:
    total_sum += guess
    if total_sum == number:
        print("Your have guessed the number {}!".format(number))
        break
    elif total_sum > number:
        print("Your sum of guesses, {}, exceeds the "\
              "number {}!".format(total_sum, number))
        break
    guess = int(input("Please enter an integer: "))

rawDescription: How do I get user input (int) to sum

description: Get user input (int) to sum


code:
class MapProperty2Argument(object):
    def __init__(self, fn):
        self.fn = fn

    def __getattr__(self, name):
        return self.fn(name)

class Performance(object):
    @property
    def time_frame_return(self):
        return MapProperty2Argument(
            PerformanceAnalysisMixin().return_over_time_frame)

rawDescription: Python: using a class to handle method calls as if class attributes were method arguments


code: np.einsum('ij,ikj->ik', a, b)

rawDescription: Dot products of columns of mixed shaped arrays


code:
S('2/4',evaluate=False)
srepr(_)

rawDescription: SymPy, how to perform exact symbolic representation (Rational Issue)?


code:
tmp = newMail.Body.split('<body>')
# split by a known HTML tag with only one occurrence then rejoin
newMail.Body = '<body>'.join([tmp[0],yourString + tmp[1]])

rawDescription: Prepend text to existing mail body

description: Prepend text to existing mail body


rawDescription: Concatenating all elements in list into a string python


code:
from django.core.files.base import ContentFile
from PIL import ImageOps, Image as pil_image
import os.path
import json

def ajax_upload(request):
    if request.method == 'POST':
        newfile = Image()
        newfile.user = request.user
        file_content = ContentFile(request.raw_post_data)
        file_name = request.GET.get('file')

        newfile.image.save(file_name, file_content)
        newfile.thumbnail.save(file_name, file_content)

        #opening and resizing the thumbnail
        path = os.path.join(settings.MEDIA_ROOT, newfile.thumbnail.url)
        thumb_file = pil_image.open(path)

        if thumb_file.mode not in ("L", "RGB"):
            thumb_file = thumb_file.convert("RGB")

        thumb_image_fit = ImageOps.fit(thumb_file, (100, 100), pil_image.ANTIALIAS)
        thumb_image_fit.save(path)

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

        results = {
                    'image':
                        {
                            'url': newfile.image.path,
                            'width': newfile.image.width,
                            'height': newfile.image.height
                        },
                    'thumbnal':
                         {
                            'url': newfile.thumbnail.path,
                            'width': newfile.thumbnail.width,
                            'height': newfile.thumbnail.height
                         }
                    }
        return HttpResponse(json.dumps(results))
    raise Http404

rawDescription: python pil image to django imagefield convert

description: Python pil image to django imagefield convert


code:
from copy import copy, deepcopy
y = deepcopy(x)

rawDescription: How to make a copy of a 2D array in Python?

description: Make a copy of a 2D array in Python


code:
storage_profile = azure.mgmt.compute.StorageProfile(
    os_disk=azure.mgmt.compute.OSDisk(
        caching=azure.mgmt.compute.CachingTypes.none,
        create_option=azure.mgmt.compute.DiskCreateOptionTypes.from_image,
        name=OS_DISK_NAME,
        virtual_hard_disk=azure.mgmt.compute.VirtualHardDisk(
            uri='https://{0}.blob.core.windows.net/vhds/{1}.vhd'.
            format(STORAGE_NAME, OS_DISK_NAME),
        ),
        operating_system_type='Linux',
        source_image=azure.mgmt.compute.VirtualHardDisk(
            uri='https://{0}.blob.core.windows.net/{1}/{2}'.format(
                STORAGE_NAME, CUSTOM_IMAGE_PATH, CUSTOM_IMAGE_VHD),
        ),
    ),
)

rawDescription: How to create a VM with a custom image using azure-sdk-for-python?

description: Create a VM with a custom image using azure-sdk-for-python


code:
a=np.argmax(b, axis=0)
b[a] = -1
b

rawDescription: python replace values in 2d numpy array

description: Python replace values in 2d numpy array


code:
import sys
sys.stdout.close()
sys.stderr.close()

rawDescription: how to tell cgi to stop waiting

description: Tell cgi to stop waiting


code: dt = dt.replace(microsecond = (dt.microsecond / 1000) * 1000)

rawDescription: Python datetime precision

description: Python datetime precision


code:
from __future__ import division

import inspect
import os.path

class pprint(object):
    def __init__(self, name, path=None):
        self.name = name
        if path == None:
           path = inspect.getouterframes(inspect.currentframe())[1][3]

        self.path = path
        self.complete_name = os.path.join(path, name)
        self.f = open(complete_name, "w")
        ...

rawDescription: Find the path of the previous function on the stack python


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

origin = 'lower'
#origin = 'upper'

delta = 0.025

x = y = np.arange(-3.0, 3.01, delta)
X, Y = np.meshgrid(x, y)
Z1 = plt.mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = plt.mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10 * (Z1 - Z2)

levels = np.linspace(-3,2,50)
Vmin   = -1.
Vmax   = 1.
M = np.ma.array(Z, mask=((Z<Vmin)|(Z>Vmax)))

#levels = np.hstack(([Vmin], levels, [Vmax]))

f, (ax1, cax1, ax2, cax2) = plt.subplots(1,4,gridspec_kw={'width_ratios':[9,1,9,1]})
cf1 =  ax1.contourf(X, Y, M, levels=levels)
plt.colorbar(cf1, cax=cax1)
cf2 = ax2.contourf(X, Y, M*0.5, levels=levels)
plt.colorbar(cf2, cax=cax2)

rawDescription: Keeping the color scaling the same for different plots - Python


code:
b = []
for x in a:
    if isinstance(x[0], tuple):
        b.extend([list(y) for y in x])
    else:
        b.append(x)

rawDescription: List of lists with tuples to list of lists


code:
def dfs(initial, goal, capacity):
    # These three variables form the "stack".
    closed_set = {initial}
    stack = [initial]
    gens = [_generate_states(initial, capacity)]

    while stack:
        cur = stack[-1]
        gen = gens[-1]
        try:
            state = next(gen)
        except StopIteration:
            # This node is done
            closed_set.discard(cur)
            gens.pop()
            stack.pop()
            continue

        if state == goal:
            return stack

        if state not in closed_set:
            closed_set.add(state)
            stack.append(state)
            gens.append(_generate_states(state, capacity))

    return None

rawDescription: Avoiding Python's Stack

description: Avoiding Python's Stack


code:
import re
re.sub(r'[^\x00-\x7f]+', " ", inputString)

rawDescription: Removing strings containing ASCII

description: Removing strings containing ASCII


code:
df2 = df.set_index('Date and Time')
df2['Volume'] = df2.groupby(pd.TimeGrouper('D'))['Volume'].cumsum()
df2

rawDescription: How to perform cumulative calculations in pandas that restart with each change in date?

description: Perform cumulative calculations in pandas that restart with each change in date


code:
def get_object(self):
    return self.model.get(pk=self.request.user.pk)

rawDescription: Override get_object() and manually set PK


code:
from PIL import Image

img = Image.open('img.png')
img = img.convert("RGBA")
datas = img.getdata()

newData = []
for item in datas:
    if item[0] == 255 and item[1] == 255 and item[2] == 255:
        newData.append((255, 255, 255, 0))
    else:
        newData.append(item)

img.putdata(newData)
img.save("img2.png", "PNG")

rawDescription: Using PIL to make all white pixels transparent?


code:
barbs = m.quiver(x, y, u[0, :], v[0, :], scale = 100)
for i in range(365):
     barbs.set_UVC(u[i,:],v[i,:])
     #save the figure or something

rawDescription: using matplotlib's quiver in a loop efficiently

description: Using matplotlib's quiver in a loop efficiently


rawDescription: parameterizing column name

description: Parameterizing column name


code:
from collections import defaultdict
result = defaultdict(list)
current_key = "ERROR - MISSING TITLE"
with open('youfile.txt', 'r') as f:
    for line in f:
        item = line.strip()
        if item.strip('[]') != item:
            current_key = item.strip('[]')
        else:
            result[current_key].append(item)

rawDescription: split a list with title value: pythonic way

description: Split a list with title value: pythonic way


code:
s="""$asdfasdfasdfasdfasdfasdf
ABCSLKDJFLAJSDJLAJSDLFJALJSDLKJLAJLSKDJFLAJSD
LKAJSDLJFALSJDFLJALSJDFLASDLFJLAJSDLFJALSDFAS
LLASJLKDFJLASDFASKLDFLASDFJALSDJFLAJSDLFJALKS
ALKSDJLFKJASLDJFLAJSDLFJALSJDFLJASLDJJASDLFJF
$aWEOUUEWOEUowuerotueworutowueortuo
ABCSLKDJFLAJSDJLAJSDLFJALJSDLKJLAJLSKDJFLAJSD
LKAJSDLJFALoqiweoituoiwueoruweuroouqweoruuqowuieoFAS
LLASJLKDFJLASDFASKLDFLASDFJALSDJFLAJSDLFJALKS
ALKSDJLFKJASLDJFLAJSDLFJALSJDFLJASLDJJASDLFJFsdfs
"""

import re

li=re.finditer(r'\$[^\n]*([^$]+)',s)
[i.group(1).replace('\n','') for i in li]

rawDescription: Python parsing file line by line with special characters


code:
next = Picture.objects.filter(Q(created_at__lt=image.created_at) | Q(created_at=image.created_at, id__lt=image.id))

if next:
    next = next.order_by("-created_at", "id")[0]

rawDescription: Best way to get next and previous images Django

description: Get next and previous images Django


code:
from bson import BSON
with open('dump/coll.bson', 'rb') as f:
    coll_raw = f.read()

coll = bson.decode_all(coll_raw)

rawDescription: Python, Convert bson output of mongodump to array of json objects (dictionaries)


code:
if title and articleNumber in listOfData:
    listOfData[articleNumber] = (title, articleNumber, None, oldvariants + variants)
else:
    listOfData.append((title, articleNumber, None, variants))

rawDescription: Update tuple in list

description: Update tuple in list


code:
import os
import sys
sys.path.append('/path/towhere/myproject/')

os.environ['DJANGO_SETTINGS_MODULE'] = 'project_path.settings'

from app_path.models import *

#write your cron job.

rawDescription: Background jobs in Django

description: Background jobs in Django


code:
# Given the posts, fetches all the data the template will need
# with just 2 key-only loads from the datastore.
posts = get_the_posts()

author_keys = [Post.author.get_value_for_datastore(x) for x in posts]
authors = db.get(author_keys)

city_keys = [Author.city.get_value_for_datastore(x) for x in authors]
cities = db.get(city_keys)

for post, author, city in zip(posts, authors, cities):
  post.author = author
  author.city = city

rawDescription: Speeding up templates in GAE-Py by aggregating RPC calls


code: line = ax.plot(...)[0]

rawDescription: python-using comma's when implementing before animation

description: Python-using comma's when implementing before animation


code: map(len, re.split(r"(?<=[^ ]) ", head))

rawDescription: Python: Generic Algorithmic to determine fixed length columns


code:
decimal_places = 2
ndigits = decimal_places - 6
assert ndigits < 0
d = d.replace(microsecond=round(d.microsecond, ndigits))
print(d.strftime('%d-%m-%Y %H:%M:%S.%f')[:ndigits])
# -> 2014-10-27 11:59:53.87

rawDescription: Formatting microseconds to 2 decimal places ( in fact converting microseconds into tens of microseconds )


rawDescription: Python striping a variable everything after - dash


code:
def __repr__(self):
        return "Rxns catalyzed: %s, Specificity: %s \n" %(self._rxns_cat, ['%.3f' % spec for spec in self._specif])

rawDescription: Formatting Dictionary Within Object in Python


code:
...
with open(i, 'w', newline='') as fp:
    writer = csv.writer(fp, delimiter = ';')
    writer.writerow(['Number', number])
    writer.writerow(['Head','N', 'E', 'El'])

    row_label_map = {0:'Begin',len_x-2:'End'}
    for l in range(len_x):
        row_label = row_label_map.get(l,"")
        writer.writerow([row_label, coord_x[l], coord_y[l], coord_z[l]])

    writer.writerow(['BeginR', 'Ok'])
    writer.writerow(['EndR'])

rawDescription: Writing list in CSV to create a model file


rawDescription: Python BeautifulSoup find element that contains text


code:
d = datetime.datetime(2009, 11, 12, 12)
for post in posts.find({"date": {"$lt": d}}).sort("author"):
  post

rawDescription: How do I do greater than/less than using MongoDB?

description: Do greater than/less than using MongoDB


code: SECURE_SSL_REDIRECT = True

rawDescription: Django defaulting to HTTPS

description: Django defaulting to HTTPS


code:
import __future__
__future__.all_feature_names
__future__.unicode_literals

rawDescription: What __future__ features should I import in Python v2.6.2?


code:
# X= your Geo Array

# Standardize features by removing the mean and scaling to unit variance
X = StandardScaler().fit_transform(X)

# Compute DBSCAN
db = DBSCAN(eps=0.3, min_samples=3).fit(X)

# HERE
# eps -- The maximum distance between two samples
#  for them to be considered as in the same neighborhood.
# min_samples -- The number of samples in a neighborhood for a point
#  to be considered as a core point.

core_samples = db.core_sample_indices_
labels = db.labels_

# Number of clusters in labels, ignoring noise if present.
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)

rawDescription: Binning/grouping a dataset of geographic coordinates


code:
lis = [10, 20, 30, 30, 40, 50, 50, 50, 60, 70]

for idx1, el1 in enumerate(lis):
    sum_ = el1
    for  idx2, el2 in enumerate(lis):
        if idx1 != idx2:
             sum_ += (50 - (el2 - el1)/2) * 0.13
        print("score of %d is %f"%(idx1, sum_))

rawDescription: Position in Python Lists

description: Position in Python Lists


code:
class ProductAdmin(admin.ModelAdmin):
    ...
    def get_queryset(self, request):
      ...
      return qs.filter(brand__brand_name = request.user)

rawDescription: Specific user content Add, Edit, Delete particular data for particular user


code:
from urlparse import urljoin

from bs4 import BeautifulSoup
import requests

with requests.Session() as session:
    r = session.get("http://example_website.com")
    data = r.text
    soup = BeautifulSoup(data)

    base_url = "http://example_website.com"
    for link in soup.find_all('a'):
        url = urljoin(base_url, link.get('href'))

        r = session.get(url)
        # parse the subpage

rawDescription: Accessing tabular data via hyperlinks with BeautifulSoup


code: params = "mv /full_path_to_folder_source/*.nib /full_path_to_folder_target/"

rawDescription: Calling 'mv' from Python Popen with wildcard


code:
x = {'id': 10, 'color_menu': [{'color': 'blue', 'name': 'Sandra'}, {'color': 'red', 'name': 'Lisa'}]}
x["color_menu"][0]["color"]

rawDescription: Get specific value by key from nested dictionaries/lists


code:
import BeautifulSoup
import urllib2
connection = urllib2.urlopen('http://kuler.adobe.com/path/to/rss.xml')
html_data = connection.read()
connection.close()
soup = BeautifulSoup.BeautifulSoup(html_data)
themes = soup.findAll('kuler:themeitem') # Note: all lower-case element names
themes[0].find('kuler:themeid').contents[0]
themeswatches = themes[0].find('kuler:themeswatches')
colors = [color.contents[0] for color in
themeswatches.findAll('kuler:swatchhexcolor')]
colors

rawDescription: Reading collections of extended elements in an RSS feed with Universal Feed Parser


code:
d = {}
d[a] = a
retrieved_a = d[b]

rawDescription: Python: Access members of a set

description: Python: Access members of a set


code:
import sys

sys.dont_write_bytecode = True

rawDescription: Is it possible to stop Django from creating .pyc files, whilst in development?


code:
d = {3: 9, 'apple': 'orange'}
s = str(d)
s
import ast
x = ast.literal_eval(s)
x

rawDescription: Passing dictionaries to a Python script through the command line


code:
class ExampleForm(ModelForm):
    displayed_fields = MultipleChoiceField(choices=ExamplePlugin.COLUMN_CHOICES, help_text="Select columns that you would like to appear.", initial=['name', 'office', 'phone'])

    def __init__(self, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)

    class Meta:
        model = ExamplePlugin

rawDescription: Initializing a MultipleChoiceField in Django CMS


code:
def callback(event):
    print(event.char, event.keysym, event.keycode)

root = Tk()
root.bind('<Key>', callback)
root.mainloop()

rawDescription: Python - Bind all events from single object


code:
import random
import struct

floatlist = [random.random() for _ in range(10**5)]
buf = struct.pack('%sf' % len(floatlist), *floatlist)

rawDescription: Fastest way to pack a list of floats into bytes in python


code:
from numpy import array, arange, ix_
a = arange(25).reshape(5,5)
Xinds = array([1,2,3])
Yinds = array([1,2,3])
a
a[ix_(Xinds, Yinds)]
a[ix_(Xinds+1, Yinds)]
Y2inds = array([1,3,4])
a[ix_(Xinds, Y2inds)]
a[ix_(Xinds, Y2inds-1)]

rawDescription: How to cleanly index numpy arrays with arrays (or anything else that supports addition so that it can be offset)

description: Cleanly index numpy arrays with arrays (or anything else that supports addition so that it can be offset)