code:
# OLVcheckboxes.py

import wx
from ObjectListView import ObjectListView, ColumnDefn

########################################################################
class Results(object):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, tin, zip_code, plus4, name, address):
        """Constructor"""
        self.tin = tin
        self.zip_code = zip_code
        self.plus4 = plus4
        self.name = name
        self.address = address

########################################################################
class ProvPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)

        mainSizer = wx.BoxSizer(wx.VERTICAL)

        self.columns = {0: 'tin',
                        1: 'zip_code',
                        2: 'plus4',
                        3: 'name',
                        4: 'address'}

        self.test_data = [Results("123456789", "50158", "0065", "Patti Jones",
                                  "111 Centennial Drive"),
                          Results("978561236", "90056", "7890", "Brian Wilson",
                                  "555 Torque Maui"),
                          Results("456897852", "70014", "6545", "Mike Love",
                                  "304 Cali Bvld")
                          ]
        self.resultsOlv = ObjectListView(self, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
        self.resultsOlv.cellEditMode = ObjectListView.CELLEDIT_SINGLECLICK

        self.setResults()

        self.column_cbo = wx.ComboBox(self, value='tin',
                                      choices=self.columns.values())
        modify_btn = wx.Button(self, label='Modify Column 1 Cells')
        modify_btn.Bind(wx.EVT_BUTTON, self.onModify)

        mainSizer.Add(self.resultsOlv, 1, wx.EXPAND|wx.ALL, 5)
        mainSizer.Add(self.column_cbo, 0, wx.CENTER|wx.ALL, 5)
        mainSizer.Add(modify_btn, 0, wx.CENTER|wx.ALL, 5)
        self.SetSizer(mainSizer)

    #----------------------------------------------------------------------
    def onModify(self, event):
        """
        Modify cells
        """
        objects = self.resultsOlv.GetObjects()
        column = self.column_cbo.GetValue()
        for obj in objects:
            value = 'Row #%s' % self.resultsOlv.GetIndexOf(obj)
            setattr(obj, column, value)
            self.resultsOlv.RefreshObject(obj)

    #----------------------------------------------------------------------
    def setResults(self):
        """"""
        self.resultsOlv.SetColumns([
            ColumnDefn("TIN", "left", 100, "tin"),
            ColumnDefn("Zip", "left", 75, "zip_code"),
            ColumnDefn("+4", "left", 50, "plus4"),
            ColumnDefn("Name", "left", 150, "name"),
            ColumnDefn("Address", "left", 200, "address")
        ])
        self.resultsOlv.CreateCheckStateColumn()
        self.resultsOlv.SetObjects(self.test_data)

########################################################################
class ProvFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        title = "OLV Checkbox Tutorial"
        wx.Frame.__init__(self, parent=None, title=title, size=(1024, 768))
        panel = ProvPanel(self)

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = ProvFrame()
    frame.Show()
    app.MainLoop()

rawDescription: How to change value of existing item's string in wxPython ObjectListView list_ctrl

description: Change value of existing item's string in wxPython ObjectListView list_ctrl


rawDescription: pandas timeseries with relative time

description: Pandas timeseries with relative time


code:
class LabelMapperProxy(object):
   def __init__(self, mapper): self.mapper = mapper

   def __setattr__(self, key, val):
       if key == 'mapper':
           return super(LabelMapperProxy, self).__setattr__(key, val)
       self.mapper[key] = val

rawDescription: Proxy class for accessing other class' items as attributes (__getitem__ infinite recursion)


rawDescription: Values between repeating string parts

description: Values between repeating string parts


code:
from M2Crypto import SSL
ctx = SSL.Context('sslv3')
ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, depth=9)
if ctx.load_verify_locations('ca.pem') != 1:
   raise Exception('No CA certs')

c = SSL.Connection(ctx)
c.connect(('www.google.com', 443)) # automatically checks cert matches host
c.send('GET / \n')
c.close()

rawDescription: urllib2/pycurl in Django: Fetch XML, check HTTP status, check HTTPS connection

description: Urllib2/pycurl in Django: Fetch XML, check HTTP status, check HTTPS connection


code:
data = b''
while True:
    buf = f.read(8192)
    if not buf:
        process(data)
        break
    data += buf
    chunks = data.split(b'\0')
    for chunk in chunks[:-1]:
        process(chunk)
    data = chunks[-1]

rawDescription: Process large data in python

description: Process large data in python


code:
import time
time.strftime('%F %T %Z')

rawDescription: Equivalent of GNU coreutils /bin/date output with Python2 (timezone)


code: author = ndb.KeyProperty(required = True)

rawDescription: Assigning an author to an entity during its creation


code:
from random import shuffle

with open('names.txt', 'r') as f:
    names = [name.strip() for name in f]

shuffle(names)

pairs = zip(names[::2], names[1::2])

rawDescription: Pairing a name from one text file with a random name from the same text file


code:
# Find the last tweet
for page in tweepy.Cursor(api.user_timeline, id="253346744").pages(1):
    for item in page:
        if item.in_reply_to_user_id_str == "151791801":
            last_tweet = item

rawDescription: Tweepy Twitter get all tweet replies of particular user


code:
Parameters = collections.OrderedDict(
    (("current", '50mA'), ("voltage", '230'), ("resistance", '40 ohms'))
)
Parameters["inductance"] = "37"
Parameters["power"] = "100 watt"

rawDescription: How to retain the order of items in dictionary?

description: Retain the order of items in dictionary


code:
import io

from django.core.files import File
from django.forms import Textarea, CharField

class PastebinFormField(CharField):
    widget = Textarea

    def prepare_value(self, value):
        if value is None or isinstance(value, str):
            return value
        # value is expected to be a PastebinContentCachingFieldFile instance
        return value.cached_get_pastebin_content()

    def to_python(self, data):
        data = super(PastebinFormField, self).to_python(data)
        if data is not None:
            mem_stream = io.StringIO(data)
            mem_stream.name = 'unused'
            mem_stream.mode = 'rb'
            data = File(mem_stream)
        return data

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


code:
for i, _ in enumerate(lines_list):
    lines_list[i] = lines_list[i].strip()

rawDescription: Python: list items are not changed in for loop


code:
def renameHeader(self, index):
    oldHeader = self.table.horizontalHeaderItem(index).text()
    newHeader, confirm = QtGui.QInputDialog.getText(self,
                                                   'Rename Header',
                                                   '',
                                                   QtGui.QLineEdit.Normal,
                                                   oldHeader)
    if confirm:
        self.table.horizontalHeaderItem(index).setText(newHeader)

rawDescription: Changing column headers after plotting table using Qt4


code: dict((k, [v, v/var1, v/var1+var2]) for k, v in band1.iteritems())

rawDescription: adding arithmetic values to dictionary?

description: Adding arithmetic values to dictionary


code:
import itertools
list(itertools.chain(*[i.split("\n") for i in a]))

rawDescription: How do I split a list into a list of lists on a specific character in the elements?

description: Split a list into a list of lists on a specific character in the elements


code:
ls = ['qa','uat','prod','dev']
ls.sort(key=lambda x: (1,x) if x=='dev' else (0,x))
ls

rawDescription: How to sort a list with user defined condition in python?

description: Sort a list with user defined condition in python


code:
# Select whichever rows you want in whatever order you like
c.execute('select id, forename, surname, email from contacts')

writer = UnicodeWriter(open("export.csv", "wb"))

# Make sure the list of column headers you pass in are in the same order as your SELECT
writer.writerow(["ID", "Forename", "Surname", "Email"])
writer.writerows(c)

rawDescription: It is possible export table sqlite3 table to csv or similiar?


code:
sequence = "aaaabbababbbbabbabb"
Counter(len(list(it)) for k, it in groupby(sequence))

rawDescription: Counting same length items in a list

description: Counting same length items in a list


code:
def resize(self):
    """
    Called when we know the data table has been setup by Qt so we are
    guaranteed that the headers now have a width, etc.

    There is no other way to guarantee that your elements have been sized,
    etc. by Qt other than this event.
    """

    # Make the width of the vertical headers on the header table the same
    # size as the initialized width of the data table (data table widths
    # are setup automatically to fit the content)
    width = self._data_table.verticalHeader().width()
    self._header_table.verticalHeader().setFixedWidth(width)

rawDescription: Create QTableWidget with 2 or more header rows


rawDescription: Python lists indexes

description: Python lists indexes


code:
ax = df['corr'].plot()

ticklabels = df.index.strftime('%Y.%m.%d')
ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))
plt.show()

rawDescription: How can I change date type for graph labels

description: Change date type for graph labels


code: cast = [list(entry) for entry in L]

rawDescription: Python list index splitting and manipulation


code:
def add_item(self, item):
    # You could use append here, and it'd be faster
    temporary_list = list(self.items) + [item]
    self.items = type(self.items)(temporary_list)

rawDescription: Adding an element to a collection type without changing the collection type in Python


code:
N
M
X,Y = np.meshgrid(N,M[::-1])
X
Y

rawDescription: Repeating rows and columns in Python

description: Repeating rows and columns in Python


code:
cols = df.columns[df.columns == 'X']
df[cols] = df[cols].replace({'True': True, 'False': False})

rawDescription: Pandas read_csv dtype specify all columns but one


code:
from functools import wraps

class StateMachineWrongState(Exception):
    def __init__(self, shouldbe, current):
        self.shouldbe = shouldbe
        self.current = current
        super().__init__((shouldbe, current))

def statemachine(shouldbe, willbe):
    def decorator(f):
        @wraps(f)
        def wrapper(self, *args, **kw):
            if self.state != shouldbe:
                raise StateMachineWrongState(shouldbe, self.state)
            try:
                return f(self, *args, **kw)
            finally:
                self.state = willbe
        return wrapper
    return decorator

rawDescription: Implementing a state machine with decorators


code:
df['tick'].fillna(method='ffill', inplace=True)
df
df['days'] = df.index.values - df['tick']
df

rawDescription: In python/pandas how to search for nearest value?


code: datetime.datetime.now().replace(day=1, hour=0, minute=0, second=0)

rawDescription: Python parsedatetime: get current month / first of the month


code:
def mouseOver(self, event):
    if event.widget == self.backupBtn:
        self.status['text'] = "Backs up the selected database."
    elif event.widget == self.connectBtn:
        self.status['text'] = "Connects to the selected database."
    ...

rawDescription: Multiple Buttons In One Method Python 3

description: Multiple Buttons In One Method Python 3


code:
from cPickle import Pickler

p = Pickler(open('data2.pkl', 'wb'))
p.dump(lst)

rawDescription: Storing a list, then reading it as integer


code:
class CommercialPack(object):
    def __init__(self, pack):
        self.__dict__.update(pack.__dict__)

rawDescription: Object type casting in Python (design suggestion)


code:
import PySide.QtCore as QtCore
import PySide.QtGui as QtGui

class Dialog(QtGui.QDialog):
    value = 1.00
    def __init__(self, parent=None):
        QtGui.QDialog .__init__(self, parent)
        mainLayout = QtGui.QVBoxLayout()

        self.lineedit = QtGui.QLineEdit()
        self.setValues()
        mainLayout.addWidget(self.lineedit)
        button = QtGui.QPushButton('Calculate')
        button.clicked.connect(self.buttonClicked)
        mainLayout.addWidget(button)
        self.setLayout(mainLayout)

    def setValues(self):
        self.lineedit.setText('progress %s'%self.value)
        palette = self.lineedit.palette()
        QRectF = QtCore.QRectF(self.lineedit.rect())
        gradient = QtGui.QLinearGradient(QRectF.topLeft(), QRectF.topRight())
        gradient.setColorAt(self.value-0.001, QtGui.QColor('#ffffff'))
        gradient.setColorAt(self.value, QtGui.QColor('#f99e41'))
        gradient.setColorAt(self.value+0.001, QtGui.QColor('#f99e41'))
        palette.setBrush(QtGui.QPalette.Base, QtGui.QBrush(gradient))
        self.lineedit.setPalette(palette)

    def buttonClicked(self):
        if self.value <0.1:
            self.value = 1.00
        else:
            self.value=self.value-0.1

        self.setValues()

if __name__ == '__main__':
    app = QtGui.QApplication([])
    window = Dialog()
    window.resize(300, 50)
window.show()
app.exec_()

rawDescription: How to turn QLineEdit background into a Progress Bar

description: Turn QLineEdit background into a Progress Bar


rawDescription: Python - list of same columns / rows from matrix


rawDescription: Memos in python (Think Python exercise 11.6)


code:
my_dict = {"eigentlich":"basically", 'Eins': 'one',
           'Zwei': 'two', 'Drei': 'three', 'Vier':
           'four', 'fünf': 'five', 'sechs': 'six',
           'sieben': 'seven', 'acht': 'eight',
           'neun': 'nine', 'zehn': 'ten'}

rawDescription: Python dictionary random key print

description: Python dictionary random key print


code:
MATLAB
save('example.mat','-v7.3')
Python
matdata = hdf5storage.loadmat('example.mat')

rawDescription: Creating a .mat file of v7.3 in python

description: Creating a .mat file of v7.3 in python


code:
def removew(d):
    return   {k.strip():removew(v)
             if isinstance(v, dict)
             else v.strip()
             for k, v in d.iteritems()}
removew(dict1)

rawDescription: Remove white spaces from dict : Python

description: Remove white spaces from dict : Python


code: max_len = max(max(map(len,l)) for l in zip(COLUMN_1,COLUMN_2))

rawDescription: How to center align columns of different lengths using numpy.savetxt in Python?

description: Center align columns of different lengths using numpy.savetxt in Python


code:
list2 = np.zeros(len(lis))
list2.fill(lis)

rawDescription: fastest way to populate a 1D numpy array

description: Fastest way to populate a 1D numpy array


code:
x = np.zeros((10, 10), dtype='f')
x[:] = np.random.randn(*x.shape)

rawDescription: Can I specify a numpy dtype when generating random values?

description: Specify a numpy dtype when generating random values


code:
import random

class WeightedRandomizer:

    def __init__(self, weights):
        self.__max = .0
        self.__weights = []
        for value, weight in weights.items():
            self.__max += weight
            self.__weights.append((self.__max, value))

    def take(self, amount):
        ret = []
        while True:
            item = self.random()
            if item in ret:
                continue
            ret.append(item)
            if len(ret) == amount:
                return ret

    def random(self):
        r = random.random() * self.__max
        for ceil, value in self.__weights:
            if ceil > r:
                return value

range_size = 0
if range_size == 0:
    try:
        rSize = int(input('Size of your Range?: '))
        setSize = int(input('Size of your Sets?: '))
        numSets = int(input('How many sets?: '))
    except ValueError:
        print('That was not an integer!')
        range_size = 0

base_value = 100 / rSize
num_weighted = [base_value] * rSize
num_weighted[0] = round(base_value * 2.2, 1)
num_weighted[1] = round(base_value * 1.8, 1)
num_weighted[2] = round(base_value * 1.8, 1)
num_weighted[3] = round(base_value * 1.5, 1)
num_weighted[4] = round(base_value * 1.4, 1)
num_weighted[5] = round(base_value * 1.3, 1)

# redistribute the difference of top 6 and rest of range
top6 = (sum(num_weighted[0:6]))
not_top6 = rSize - 6
pts_alloc = round((100 - top6) / not_top6, 1)

num_weighted[6:] = [pts_alloc for i in range(len(num_weighted) - 6)]

keys = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight',
        'Nine', 'Ten', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen']

dictionary = dict(zip(keys, num_weighted))

wr = WeightedRandomizer(dictionary)

x = [wr.take(setSize) for j in range(numSets)]

print(x)

rawDescription: Unique value in nested list - random

description: Unique value in nested list - random


code:
from itertools import groupby
from operator import itemgetter

pets = [('dog',12,2), ('cat',15,1), ('dog',11,1), ('cat',15,2), ('dog',10,3), ('cat',16,3)]

def my_reduce(obj1, obj2):
    return (obj1[0],max(obj1[1],obj2[1]),min(obj1[2],obj2[2]))

rawDescription: Reduce by key in python

description: Reduce by key in python


rawDescription: How to print every 5 characters in a sequence of 'X' characters?

description: Print every 5 characters in a sequence of 'X' characters


code:
class UpdateText(webapp2.RequestHandler):
     def post(self):
         greeting_key = ndb.Key(urlsafe=self.request.get('update'))
         event = greeting_key.get();
         if(self.request.get('newContent') != ''):
           event.content = self.request.get('newContent');
           event.put();
         self.redirect('/events');

rawDescription: Cancel a form to be submitted, do not change the data of the entity


code: doc_has_word = [ (index[word].keys(),word) for word in wordlist ]

rawDescription: Searching a normal query in an inverted index


code: matching = [l for l, b in zip(L, B) if l > float(b * 1.1)]

rawDescription: to check a condition for all the items in two list in python

description: To check a condition for all the items in two list in python


rawDescription: Having issues with Python xpath scraping


code: sum(p*c for p,c in primesToCounts.items())

rawDescription: Multiply keys*values in a dict?

description: Multiply keys*values in a dict


code:
x = Decimal('2606.8950000000001')
int((x*100).quantize(1, rounding=ROUND_HALF_EVEN))

rawDescription: Rounding a number in python but keeping ending zeros


code: dtype = np.dtype([('re', np.int16), ('im', np.int16)])

rawDescription: Is it possible to create a numpy.ndarray that holds complex integers?


code: print ("{:3}".format(p), end="")

rawDescription: How to print a list of integers in 10 columns?

description: Print a list of integers in 10 columns


code:
maxes = df2.groupby('B')['C'].idxmax()
df2.loc[maxes]

rawDescription: Selecting max within partition for pandas dataframe


code:
old_detector.reverse() # reverse it in place
new_detector = reverse(old_detector) # return a new detector object with the string reversed

rawDescription: Is it legal to define two methods with the same name but different returning types?


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

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


code:
mv = memoryview(value).cast('H')
mv[0], mv[1], mv[2]

rawDescription: How to split a byte string into separate bytes in python

description: Split a byte string into separate bytes in python


code:
...
cowhands ['chow']
credentials ['reticle', 'tiercel']
custodians ['coitus']
cyanids ['icy']
daftness ['efts', 'fest', 'fets']
dahoons ['oho', 'ooh']
daikons ['koi']
daintiness ['seniti']
daintinesses ['sienites']
dalapons ['opal']
dalesman ['alme', 'lame', 'male', 'meal']
...

rawDescription: How do I remove 1 instance of x characters in a string and find the word it makes in Python3?

description: Remove 1 instance of x characters in a string and find the word it makes in Python3


code:
df['swim'] = np.where(
    (df.groupby('Site').EnteroCount.transform(max) > 110) |
    (df.groupby('Site').EnteroCount.transform(lambda group: gmean(group.nlargest(5))) > 30),
    'unacceptable', 'acceptable')

rawDescription: Create complicated conditional column (geometric mean) Python


code:
from collections import Counter
from itertools import chain
from collections import Counter
root_hypernyms_of_verbs = Counter(chain(*[ss.root_hypernyms() for ss in wn.all_synsets(pos='v')]))
root_hypernyms_of_verbs.most_common(10)
root_hypernyms_of_verbs.keys() # This will return all root_hypernyms.

rawDescription: NLTK WordNet verb hierarchy

description: NLTK WordNet verb hierarchy


code:
def triadicIteractionFirstPrinciple(signsQty):
    signs = [-1 for _ in range(signsQty)]
    comb = int(3**signsQty-1)

    def addOne(idx=0):
        if signs[idx] < 1:
            signs[idx] += 1
        else:
            signs[idx] = -1
            addOne(idx+1)

    while (comb >= 0):
        printIfTargetHit(signs)
        if comb > 0: addOne()
        comb = comb - 1

rawDescription: Why is triadic iteration 2 times slower than the recursion?


rawDescription: How to get top-level protobuf enum value name by number in python?

description: Get top-level protobuf enum value name by number in python


rawDescription: generate lists from 3 dimensional array

description: Generate lists from 3 dimensional array


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

ax1 = plt.subplot(111,projection='3d')
plt.ion()
plt.show()

t = np.linspace(0,10,40)

for index,delay in enumerate(np.linspace(0,1,20)):
    y = np.sin(t+delay)
    z = np.sin(t+delay)

    if delay > 0:
        line.remove()
        ax1.collections.remove(linecol)

    line, = ax1.plot(t,y,z,color='r',lw=2)
    linecol = ax1.quiver(t,y,z, t*0,y,z)

    plt.savefig('images/Frame%03i.gif'%index)
    plt.draw()

plt.ioff()
plt.show()

rawDescription: How to update 3D arrow animation in matplotlib

description: Update 3D arrow animation in matplotlib


code: count = db.Query().filter('when >', two_minutes_ago).filter('when <', one_minute_ago).count()

rawDescription: GAE datastore - count records between one minute ago and two minutes ago?


code:
class CommaFloatFormatter:
    def __mod__(self, x):
        return str(x).replace('.',',')

df.to_clipboard(float_format=CommaFloatFormatter())

rawDescription: Pandas(Python) to_clipboard with comma decimal parameter


code:
def foo(request):
    if request.method == "POST":
        unique_id = request.POST.get('per_id','')
        request.session["unique_id"] = unique_id
        baz = get_object_or_404(Name, pk=unique_id)
        return render(request, 'details/guy.html', {'baz': baz})
    return render(request, 'details/person.html')

def bar(request):
    if request.method == "POST":
        baz = get_object_or_404(Name, pk=request.session["unique_id"])
        del request.session["unique_id"]
        return render(request, 'details/guy.html', {'baz': baz})
    return render(request, 'details/guy.html')

rawDescription: How do I send a variable from one function to another function?

description: Send a variable from one function to another function


code:
cc_number = input("8-digit credit card number: ").replace(" ", "")
total1 = 0
total2 = 0

for digit in cc_number[-1::-2]:
    total1 += int(digit)

for digit in cc_number[-2::-2]:
    total2 += sum(int(x) for x in str(int(digit)*2))

remainder = (total1 + total2) % 10

if remainder == 0:
    print("Card is valid!")
else:
    invalid_check_digit = int(cc_number[-1])

    if invalid_check_digit - remainder < 0:
        valid_check_digit = invalid_check_digit + (10 - remainder)
    else:
        valid_check_digit = invalid_check_digit - remainder

    print("Card is invalid - the correct check digit is {}".format(valid_check_digit))

rawDescription: Using loops in python to configure credit card number


code: {{ grid }}

rawDescription: Get django to render python generated html passed via context parameter?


code:
class Foo(models.Model):
    name = models.CharField('...............')
    bar = models.ForeignKey(Bar, editable=False, verbose_name=_('Bar'))

    def __init__(self, *args, bar=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.bar = bar

rawDescription: Django TypeError: 'bar' is an invalid keyword argument for this function


code:
def add(x, y):
    return x+y
# etc.

rawDescription: How to go back to a specific line

description: Go back to a specific line


code:
class TokenDataType:
    LIST = "list"
    DICT = "dict"

def _select_key(keyitt, data):
    try:
        new_key = keyitt.next()
    except StopIteration:
        return data
    if new_key["t"] == TokenDataType.DICT:
        return _select_key(keyitt, data[new_key["k"]])
    elif new_key["t"] == TokenDataType.LIST:
        return _select_key(keyitt, data[new_key["i"]])

def tokenize_query(query):
    tokens = []
    for token in query.split("."):
        token = token.strip()
        if token:
            ttype = TokenDataType.LIST if "[" in token else TokenDataType.DICT
            if ttype == TokenDataType.LIST:
                index = None
                if len(token) >= 3:
                    index = int(token.replace("[", "").replace("]", ""))
                tokens.append({"k":token, "t":ttype, "i":index})
            else:
                tokens.append({"k":token, "t":ttype})
    return tokens

def normalize_query(query=None, tokens=None):
    if tokens == None:
        tokens = tokenize_query(query)
    return ".".join([token["k"] for token in tokens])

def select(query, data, throw_exception_on_key_not_found=False):
    tokens = tokenize_query(query)
    try:
        return _select_key(iter(tokens), data)
    except Exception as e:
        if throw_exception_on_key_not_found:
            raise e
        return None

DQ = select

if __name__ == "__main__":
    test = {"bla":1, "foo":{"bar":2}, "baz":[{"x":1}, {"x":2}]}
    print(DQ(".bla", test))
    print(DQ("bla", test))
    print(DQ("nothere", test))
    print(DQ(".foo", test))
    print(DQ("foo.bar", test))
    print(DQ("baz", test))
    print(DQ("baz.[0]", test))
    print(DQ("baz.[1].x", test))
    print(DQ("baz.[2].x", test))

rawDescription: How to combine try/except in python into a pretty one liner?

description: Combine try/except in python into a pretty one liner


code:
import numpy
from matplotlib import pyplot as plt
from numpy.core.umath_tests import inner1d

width, height = 300, 500

xs, ys = numpy.mgrid[:width, :height]
coordinates = numpy.dstack([xs, ys])

light_sources = {
    (0, 0): (0, 0, 0),
    (300, 0): (0, 0, 0),
    (0, 0): (0, 0, 0),
    (300, 500): (0, 0, 0),
    (100, 0): (0, 0, 200),
    (200, 150): (100, 70, 0),
    (220, 400): (255, 255, 255),
    (80, 220): (255, 0, 0),
}

weights = numpy.zeros([width, height])
values = numpy.zeros([width, height, 3])

rawDescription: Plotting sort of a heatmap whose colors are a result of a function x,y -> r,g,b


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

n_points = 10
a = np.linspace(-5, 5, n_points)
b = np.linspace(-1.5, 1.5, n_points)
a, b = np.meshgrid(b, a)

z = a + b # Vectorize your cost function

fig, ax = plt.subplots()
im = ax.pcolormesh(a, b, z)
fig.colorbar(im)

ax.axis('tight')
plt.show()

rawDescription: heat map using matplotlib

description: Heat map using matplotlib


code:
def yahtzee():
    dice = [random.randrange(1, 6) for _ in range(5)]
    print('Your roll is: ', *dice)
    reroll = input('Which dice should I roll again?: ')
    for i in reroll:
        dice[int(i) - 1] = random.randrange(1, 6)
    print('Your roll is: ', *dice)

rawDescription: Freezing dice rolled?

description: Freezing dice rolled


code:
import re
def split_string(source,separators):
    return re.split('[{0}]'.format(re.escape(separators)),source)

rawDescription: Splitting Strings in Python with Separator variable


code:
import cookielib
...

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))

rawDescription: How to store cookie jar to be used between functions inside class?

description: Store cookie jar to be used between functions inside class


code:
def func(a, b, c):
    return a + b + c
dct = {'a':1, 'b':2, 'c':3}
func(**dct)

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

description: Store identical arguments to be used by multiple functions


code:
class Item(models.Model):
    name = models.CharField(max_length = 200, blank = False)

class Player(models.Model):
    items = models.ManyToManyField(Item, through='PlayerItem')

class PlayerItem(models.Model):
    player = models.ForeignKey(Player)
    item = models.ForeignKey(Item)
    quantity = models.IntegerField(default=1)

    class Meta:
        unique_together = ('player', 'item')

rawDescription: Django - How to model this correctly?

description: Django - How to model this correctly


code:
if args.outputfile is None:
    args.outputfile = os.path.splitext(args.inputfile)[0] + '.xml'

rawDescription: Using argparse to convert csv to xml in python


code:
D = {
    'Resent-Bcc': [],
    'Delivered-To': [],
    'From': {'Name': 'Steve Watson', 'Address': 'steve.watson@example.org'},
    'Cc': [],
    'Resent-Cc': [],
    'Bcc': [ {'Name': 'Daryl Hurstbridge', 'Address': 'daryl.hurstbridge@example.org'},
             {'Name': 'Sally Hervorth', 'Address': 'sally.hervorth@example.org'},
             {'Name': 'Mike Merry', 'Address': 'mike.merry@example.org'},
             {'Name': 'Jenny Callisto', 'Address': 'jenny.callisto@example.org'}
           ],
    'To': {'Name': 'Darius Jedburgh', 'Address': 'darius.jedburgh@example.org'}
}
L = [v if type(v) is list else [v] for v in D.values()]
[(d["Name"], d["Address"]) for item in L for d in item ]

rawDescription: What is the Pythonic way to iterate over a dict of dicts and lists?


code:
class Page(object):
    def __init__(self, name, title):
        self.name   = name
        self.title  = title
        self.selected = False

    def select(self):
        for Page in Pages:
            Page.selected = False
        self.selected = True

rawDescription: Accessing outer class from inner python

description: Accessing outer class from inner python


code: #!/usr/bin/python

rawDescription: How do I alias a command line command? (Mac)

description: Alias a command line command? (Mac)


rawDescription: Python - Add boolean condition to generator


code:
class Article(models.Model):
    date_published = models.DateTimeField()

rawDescription: django pre and next page

description: Django pre and next page


rawDescription: Python: how to generate a unique identifier for an XML document?


code:
def function():
    while True:
        x = 5
        break
    def nested():
        print(x)
    nested() # prints 5
    x = 10
    nested() # prints 10

rawDescription: Why can I access a non-global variable in one module from another in python?


code:
from ftplib import FTP
ftp = FTP('ftp.ncbi.nlm.nih.gov')
ftp.login() # Username: anonymous password: anonymous@

# Setup a cheap way to catch the data (could use StringIO too)
data = []
def handle_binary(more_data):
    data.append(more_data)

resp = ftp.retrbinary("RETR pub/pmc/PMC-ids.csv.gz", callback=handle_binary)
data = "".join(data)

rawDescription: Read a file in buffer from FTP python

description: Read a file in buffer from FTP python


code:
from google.appengine.ext import ndb
ndb.Query(kind=clss)

rawDescription: How To Use NDB Query Without Knowing Class Name


code:
with open("file", "r") as myfile:
    lines = myfile.readlines()
    for line in lines:
        m = line.split()
        for i in m[1:]:
            print(m[0], i)

rawDescription: Converting different length sentences in .txt to .csv file with 2 columns in Python


code:
import array

class A:
    def __init__(self):

        # This will work in Cython
        self.S=array.array("l", range(8))

    def test(self):
         self.S[0]+=1

rawDescription: Cython and arrays

description: Cython and arrays


code:
import numpy as np

@profile
def calc(x,y):
    z = np.arange(nrow)
    a = x[z,y.T].T  # mine, with the suggested speed up
    b = x[:,y].diagonal().T  # Christoph Terasa
    c = np.array([i[j] for i, j in zip(x, y)])  # tobias_k

    return (a,b,c)

ncol = 5  # 10 in your case
nrow = 10  # 500 in your case

x = np.arange(ncol*nrow).reshape(nrow,ncol)
y = (ncol * np.random.random_sample((nrow, 1))).astype(int)

a, b, c = calc(x,y)
print(a==b)
print(b==c)

rawDescription: Multi-dimensional array indexing using a single dimensional array in Python


code:
import numpy as np
from multiprocessing import Pool

def f(x,y):
    return x * y

# this helper function is needed because map() can only be used for functions
# that take a single argument (see http://stackoverflow.com/q/5442910/1461210)
def splat_f(args):
    return f(*args)

# a pool of 8 worker processes
pool = Pool(8)

def parallel(M, N):
    results = pool.map(splat_f, ((i, j) for i in range(M) for j in range(N)))
    return np.array(results).reshape(M, N)

def nonparallel(M, N):
    out = np.zeros((M, N), np.int)
    for i in range(M):
        for j in range(N):
            out[i, j] = f(i, j)
    return out

def broadcast(M, N):
    return np.prod(np.ogrid[:M, :N])

rawDescription: How to apply a function to a 2D numpy array with multiprocessing

description: Apply a function to a 2D numpy array with multiprocessing


code:
def _mute(fabric_cmd, *args):
    with settings(warn_only='true'):
        with hide('running', 'stdout', 'stderr', 'warnings'):
            return fabric_cmd(*args)

def some_remote_task():
    # Run a remote task silently
    output = _mute(remote, 'uname -a')

rawDescription: What's the pythonic way to wrap several functions in the same with statements


code:
from itertools import accumulate, chain
result_iterator = accumulate(chain([some_initial_theta], stuff), update_theta)

rawDescription: Python: Functionally Merging Two Iterators Where One is Recursive


rawDescription: How to figure out if a word in spelled in alphabetical order in Python

description: Figure out if a word in spelled in alphabetical order in Python


rawDescription: Fast interpolation of regularly sampled 3D data with different intervals in x,y, and z


code:
import numpy as np

data = np.recfromcsv('iris.csv')

# In this case, it's just all but the last, but we could be more general
# This must be a list and not a tuple, though.
float_fields = list(data.dtype.names[:-1])

float_dat = data[float_fields]

# Now we just need to view it as a "regular" 2D array...
float_dat = float_dat.view(np.float).reshape((data.size, -1))

# And we can normalize columns as usual.
normalized = (float_dat - float_dat.min(axis=0)) / float_dat.ptp(axis=0)

rawDescription: Normalize/Standardize a numpy recarray

description: Normalize/Standardize a numpy recarray


code:
def move_without_copying_stat(src,dst):
    old= shutil.copy2
    shutil.copy2= shutil.copy
    shutil.move(src,dst)
    shutil.copy2= old

rawDescription: Move from local linux folder to a windows share mounted with cifs


code: e = np.dot(a[:, None], b[None, :])

rawDescription: Vector-vector multiplication to create a matrix


code:
df = pd.DataFrame(...)
all_tags = [...]
groups = df.tags.map(lambda cell: tuple(tag in cell for tag in all_tags))
df.index = pd.MultiIndex.from_tuples(groups.values, names=all_tags)
for t in all_tags:
    print(t, df.xs(True, level=t).views.sum())

rawDescription: Groupby items within a list in a Pandas DataFrame


code: a = t.toarray()

rawDescription: Numpy: Transform sparse matrix to ndarray


code:
qs = Paciente.objects.all()
fecha_desde = request.GET.get('fechadesde', None)
fecha_hasta = request.GET.get('fechahasta', None)
if fecha_desde:
    qs = qs.filter(fecha__gte=fecha_desde)
if fecha_hasta:
    qs = qs.filter(fecha__lte=fecha_hasta)
context = {'consultas': qs}

rawDescription: HOW TO Configure url and view for filter between two dates


code:
import re

src = open('input.txt')
output = open('output.txt', 'w')

pat = r'([^,]*\|[^,]*)'

for line in src:
    the_search = re.search(pat, line) # Search the line for something containing '|'
    if the_search:
        the_group = the_search.group(0) # Grab the capture group
        value = the_group.split("|")[0] # Grab the first item after splitting based on '|'
        new_line = re.sub(pat, value, line) # Use re.sub to replace that entire pattern with the value
        output.write(new_line)

src.close()
output.close()

rawDescription: implement python split on individual columnar values of a csv

description: Implement python split on individual columnar values of a csv


code:
Point = namedtuple('Point','x y')
pp = Point(1,2)
ppp = pickle.dumps(pp)

rawDescription: Use of class typenames in python

description: Use of class typenames in python


rawDescription: generating all permutations of 2 ones and 3 zeroes with itertools

description: Generating all permutations of 2 ones and 3 zeroes with itertools


code: arr

rawDescription: How to add a new row to an empty numpy array

description: Add a new row to an empty numpy array


code:
for i in range(1, 100):
        print(valor)
        valor = valor *2

rawDescription: Multiprocessing in Python to process a list of parameters


code:
for output in stack.outputs:
    print('%s=%s (%s)' % (output.key, output.value, output.description))

rawDescription: How to read the describe_stack Output attribute

description: Read the describe_stack Output attribute


code: parser.add_argument('-f', '--foo')

rawDescription: An easy way to set up abbreviations with argh


rawDescription: wxpython auinotebook close tab event

description: Wxpython auinotebook close tab event


code:
fruits = [Fruit(id=1, name="apple"),
          Fruit(id=2, name="banana"),
          Fruit(id=3, name="orange"),]

serializer = FruitSerializer(fruits, many=True)
serializer.data
# [
#     {'id': 1, 'name': 'apple'},
#     {'id': 2, 'name': 'banana'},
#     {'id': 3, 'name': 'orange'}
# ]

rawDescription: Rest_framework datas from list

description: Rest_framework datas from list


code:
db = sqlite3.connect('test.db.temp')
db.executescript('CREATE TABLE foo (bar);')
db.close()
os.rename('test.db.temp', 'test.db')

rawDescription: WindowsError moving sqlite3 database after closing


code:
#Program that reads each player's name and golf score as input
#Save to golf.txt
outfile = open('golf.txt', 'w')

#Enter input, leave blank to quit program
while True:
    name = input("Player's name(leave blank to quit):")
    if name == "":
        break
    score = input("Player's score:")

#write to file golf.txt
    outfile.write(name + "\n")

    outfile.write(str(score) + "\n")

outfile.close()

rawDescription: Golf scores python program

description: Golf scores python program


rawDescription: How to read data table column by column from a txt in python

description: Read data table column by column from a txt in python


code:
mask = numpy.array((True, True, False, False))
b[mask] += a[mask]

rawDescription: how to add two numpy.array with indices or mask

description: Add two numpy.array with indices or mask


code:
s = '{"hits": 22, "page": 3, "somehhtml": "
Something

More Stuff
\\n\\n
More after some linebreaks.
"}'
JSON.parse(s)
eval('(' + s + ')')

rawDescription: How do I deserialise (deserialize) HTML fragments in JSON from simplejson.dumps?

description: Deserialise (deserialize) HTML fragments in JSON from simplejson.dumps


rawDescription: How can I implement "weak" edges with NetworkX?

description: Implement "weak" edges with NetworkX


code:
plot([-100], 'ro', label='Lenovo')
...
ax.set_ylim(bottom=0)
legend()

rawDescription: How do I assign different dots different colors in a scatter plot made with MatPlotLib?

description: Assign different dots different colors in a scatter plot made with MatPlotLib


code: bound_mth = getattr(an_instance_of_MyClass, "mymethodname")

rawDescription: Python: how does inspect.ismethod work?

description: Python: how does inspect.ismethod work


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('''\

    Price: $790
     (Out of stock)

''')
soup.span.strong
soup.span.strong.next_sibling
soup.span.strong.next_sibling.strip()

rawDescription: Accessing text in html using BeautifulSoup


code:
class MyTableModel(QtCore.QAbstractTableModel):
    def __init__(self, parent, mylist, header, *args):
        super(MyTableModel, self).__init__(parent, *args)
        self.mylist = mylist
        self.header = header

    def rowCount(self, parent=QtCore.QModelIndex()):
        return len(self.mylist)

    def columnCount(self, parent=QtCore.QModelIndex()):
        return len(self.mylist[0])

    def data(self, index, role):
        if not index.isValid():
            return None
        elif role != QtCore.Qt.DisplayRole:
            return None
        return self.mylist[index.row()][index.column()]

    def headerData(self, col, orientation, role):
        if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
            return self.header[col]
        return None

class MyDelegate(QtGui.QItemDelegate):

    treeViewHeightChanged = QtCore.pyqtSignal(QtGui.QWidget)

    def createEditor(self, parent, option, index):

        editor = MyQTreeView(index.data(), parent)
        editor.collapsed.connect(self.sizeChanged)
        editor.expanded.connect(self.sizeChanged)

        return editor

    def sizeChanged(self):
        self.treeViewHeightChanged.emit(self.sender())

class MyTableView(QtGui.QTableView):
    def __init__(self, data_list, header, *args):
        super(MyTableView, self).__init__(*args)

        #---- set up model ----

        model = MyTableModel(self, data_list, header)
        self.setModel(model)

        #---- set up delegate in last column ----

        delegate = MyDelegate()

        self.setItemDelegateForColumn(3, delegate)
        for row in range(model.rowCount()):
            self.openPersistentEditor(model.index(row, 3))

        #---- set up font and resize calls ----

        self.setFont(QtGui.QFont("Courier New", 14))
        self.resizeColumnsToContents()
        delegate.treeViewHeightChanged.connect(self.resizeRowsToContents)

rawDescription: How to add QTreeView in a QTableView column

description: Add QTreeView in a QTableView column


code:
s = set(range(3))
s.update(range(4))
s

rawDescription: Quick way to extend a set if we know elements are unique


code: months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

rawDescription: Sort list according given text of months


rawDescription: How do I define custom function to be called from IPython's prompts?

description: Define custom function to be called from IPython's prompts


rawDescription: Numpy matrices - how to handle arbitrary size


code:
def h(x, k):
    if k == 1:
        return f(x)/g(x)
    return diff(h(x, k - 1), x)/g(x)

rawDescription: Define functions recursively with derivative in Python


code:
bars = pd.DataFrame(
    zip(*df.groupby(
            (df.market_open != df.market_open.shift())
            .cumsum()
             ).apply(ohlc))).T

bars.columns = ['bar_close_time', 'Open', 'High', 'Low', 'Close', 'Up', 'Down', 'bar_count', 'market_open']

rawDescription: Select CONSECUTIVE rows from a DataFrame based on values in a column in Pandas with Groupby


code:
id = ind_x*3 + ind_y # Generate 1D linear index IDs for use with bincount

box_sum = np.bincount(id,values,minlength=9).reshape(3,3)
box_nb = np.bincount(id,minlength=9).reshape(3,3)

rawDescription: Grid distribution with numpy

description: Grid distribution with numpy


rawDescription: Unwrapping Numpy "object" dtypes

description: Unwrapping Numpy "object" dtypes


code:
from someobjectmodule import SomeObject

def method_to_test():
    obj = SomeObject(arg1='foo', arg2='bar', arg3='baz')
    return obj.method_inside_someobject()

rawDescription: Python mock object instantiation

description: Python mock object instantiation


code: a[:, changeIndex] = 0

rawDescription: How to set multiple columns in a 2D numpy array without for-loop?

description: Set multiple columns in a 2D numpy array without for-loop


rawDescription: Organizing two related lists into chunks


code:
myBaseMap.plot(x_values, y_values, alpha=0.7, c=(1.,0,0), zorder=0)
myBaseMap.scatter(x_values, y_values, marker='x', color=(1.,0,0), zorder=1)

rawDescription: How does vary the brightness of markers on a Matplotlib basemap?


code:
if event.type == pygame.KEYDOWN and event.key == pygame.K_a:
    diceRoll = random.randint(1, 4)

    window.fill(grey) # <--- fills the entire surface with a solid color!

rawDescription: Why is python skipping these lines of code?


rawDescription: Using set in Python inside a loop

description: Using set in Python inside a loop


code:
import ast
d = ["'WORKSHOP'", "'KIDS'", "'EXHIBITION'", "'FANTASY'", "'FESTIVAL'"]
result = map(ast.literal_eval, d)
result

rawDescription: using ast_literal_eval in python

description: Using ast_literal_eval in python


code:
sets = (frozenset(d.items()) for d in list_of_dicts)
unique_sets = unique_everseen(sets, key=operator.itemgetter(key))
unique_dicts = [dict(s) for s in unique_sets]

rawDescription: How to remove duplicate dictionaries from a list in Python?

description: Remove duplicate dictionaries from a list in Python


code:
for x in range(23,42): # horizontal c
  for y in range(5,24): # verticale r
    stdscr.addstr(y, x, '#')

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


code:
from datetime import timedelta

class YouTubeVideo(object):
    def __init__(self, id, width=400, height=300, start=timedelta()):
        self.id = id
        self.width = width
        self.height = height
        self.start = start.total_seconds()

    def _repr_html_(self):
        return """
            <iframe
                width="%i"
                height="%i"
                src="http://www.youtube.com/embed/%s?start=%i"
                frameborder="0"
                allowfullscreen
            ></iframe>
        """%(self.width, self.height, self.id, self.start)

rawDescription: Can the ipython notebook YouTubeVideo class play from time offset


code:
deals_in_books = driver.find_element_by_css_selector("[alt=\"Deals in Books\"]")

actions = ActionChains(driver)
actions.move_to_element(deals_in_books).click().perform()

rawDescription: Python selenium didn't find css element

description: Python selenium didn't find css element


code:
from scrapy.item import ScrapedItem

class FeedItem(ScrapedItem):
    pass

rawDescription: Python Scrapy , how to define a pipeline for an item?


code:
g = GrandChild()
g.findall()

rawDescription: How can one locate where an inherited variable comes from in Python?


code:
r_tot = []

for r_i in however_many_rs_there_are: # each r_i contains an array of 6 values
    r_tot.append(r_i)

rawDescription: Create a matrix with solution arrays in it


rawDescription: compiling regexes within a frequently-called function

description: Compiling regexes within a frequently-called function


rawDescription: Create hourly/minutely time range using pandas


code:
consecutive_values([1]*5)
consecutive_values([1]*5 + [0]*4 + [1]*3)
m = np.array([[1]*8]*8)
diagonals = map(m.diagonal, range(len(m)))
map(consecutive_values, diagonals)

rawDescription: How can I get step jump in for loop when it has a while conditioned on the for loop's variable

description: Get step jump in for loop when it has a while conditioned on the for loop's variable


code:
for i in range(len(splitfoo)):
    splitedfootmp = sorted(splitfoo[i])

for item in splitfoo:
    splitedfootmp = sorted(item)

rawDescription: For loop - Sorting each character alphabetically within a list of words


rawDescription: Python - Go through list without last element


code:
cut_weight, partitions = nx.minimum_cut(G, 0, 4, capacity='weight')
edge_cut_list = []
for p1_node in partitions[0]:
    for p2_node in partitions[1]:
        if G.has_edge(p1_node,p2_node):
            edge_cut_list.append((p1_node,p2_node))

rawDescription: Minimum s-t Edge cut which takes edge weight into consideration


code:
class MetaBase(object):
    def _check(self, attr, value):
        if attr in self.defaults:
            if not isinstance(value, self.defaults[attr]):
                raise TypeError('%s cannot be %s' % (attr, type(value)))
        else:
            self.defaults[attr] = type(value)
    def __setattr__(self, attr, value):
        self._check(attr, value)
        super(MetaBase, self).__setattr__(attr, value)

class Meta(type):
    def __new__(meta, name, bases, dict):
        cls = type.__new__(meta, name, (MetaBase,) + bases, dict)
        cls.defaults = {name: type(value) for name, value in dict.items()}
        return cls

class Image(object):
    __metaclass__ = Meta
    height = 0
    width = 0
    path = '/tmp'
    size = 0

rawDescription: Restricting attribute type with metaclass


code:
# Inputs
R
np.einsum('ij,jik->ik',I,l)

rawDescription: Given a List of Matrices, Sum Them but Ignore Some Matrix's Rows


code:
from decimal import Decimal
int(Decimal('0.00'))

rawDescription: ValueError: invalid literal for int() with base 10: '0.00'


code: ['foo', 'saks']

rawDescription: Filter using lambda function python

description: Filter using lambda function python


code:
from lxml.html import fromstring

data = """

    Jason Weston
    Pierre Baldi
    Yair Weiss
    Peter Belhumeur
    Serge Belongie

"""

tree = fromstring(data)

for item in tree.xpath("//a"):
    print(item.xpath("@href|text()"))

rawDescription: Get value to 2 attribute from a xpath node for anchor tag


code:
sorted(a, key=lambda x: x[0])
[['abc', 5], ['xyz', 2]]

sorted(a, key=lambda x: x[1])
[['xyz', 2], ['abc', 5]]

rawDescription: Python: sorting a list by "column"

description: Python: sorting a list by "column"


rawDescription: python: convert list to dictionary

description: Python: convert list to dictionary


code:
from blist import blist

seq = blist([None])
seq *= 2**30    # create a 2**30 element blist. Instantaneous!

rawDescription: Better to use dict of integer keys or a very long list?


code: X.T * W

rawDescription: Multiply Dense Rectangular Matrix by Sparse Matrix


code:
import pygame
pygame.init()

display = pygame.display.set_mode((100,100))

while True:
    #wait for a single event from the queue
    pygame.event.wait()
    keypressed = pygame.key.get_pressed()

    if keypressed[pygame.K_w]:
        print("it worked")
    else:
        print("It didn't work")

rawDescription: Why is pygame.key.get_pressed not working as expected?


code:
import numpy as np
import scipy.interpolate as inter
import matplotlib.pyplot as plt

A = np.array([[4, 2, 6, 4],
            [4, 34, 6, 2],
            [2, 11, 3, 4],
            [2, 4, 22, 4],
            [2, 1, 35, 255],
            [1, 3, 4, 54],
            [22, 1, 4, 5]])
vals = np.reshape(A, (28))
pts = np.array([[i,j] for i in np.linspace(0,1,4) for j in np.linspace(0,1,7)] )
grid_x, grid_y = np.mgrid[0:1:20j, 0:1:30j]
grid_z = inter.griddata(pts, vals, (grid_x, grid_y), method='linear')

plt.matshow(A)
plt.matshow(grid_z)
plt.show()

rawDescription: python - Extend 2-d array and interpolate the missing values

description: Python - Extend 2-d array and interpolate the missing values


code:
def add_subplot(self, data=[]):
    rows = len(self.figure.axes) + 1
    for index, axes in enumerate(self.figure.axes, start=1):
        axes.change_geometry(rows, 1, index)

    ax = self.figure.add_subplot(rows, 1, index+1)
    ax.plot(data)
    self.figure.set_figheight(self.figure.get_figheight()*1.25)
    self.draw()

rawDescription: PyQt4 + matplotlib in a QScrollWidget

description: PyQt4 + matplotlib in a QScrollWidget


code:
from itertools import takewhile
list(takewhile(lambda e:e>=26, [30.1, 29.7, 28.5, 27.1, 20, 17, 16]))

rawDescription: python: finding a continuous list of values, matching a condition, starting from the first element

description: Python: finding a continuous list of values, matching a condition, starting from the first element


code:
class Hero(object):
    def attack(self, enemy, damage,app): #change the defenition
        Hero.hits+=1
        if self.hits==0:
            attack = "{}, attacks our enemy {}. Producing {} points of damage.\n".format(
                      self.__name, enemy.creature, truncate(damage))
            # I use code like this in the Application definition.
            app.output_text.insert(END, attack)

rawDescription: Connecting a method of an imported class with a class of the main script


code:
currencies = {}
currencies['USD'] = 1.64
currencies['EUR'] = 1.20552
currencies['JPY'] = 171.181
currencies['GBP'] = 1.

number = currencies[currency2]

rawDescription: using subroutines in python instead of if statements

description: Using subroutines in python instead of if statements


code: add_button = Button(wrapper, text="add", command=lambda:addmeter(wrapper))

rawDescription: Calling an global function from inside a class. Python 2.7 using Tkinter


rawDescription: Alphanumeric generator with restrictions


code:
position = Window.list_2.index(item_selected)
Window.list_2[position] += "(selected)"

rawDescription: delete items from 3 different lists

description: Delete items from 3 different lists


code: df

rawDescription: pandas dataframe: return column that is a compression of other columns

description: Pandas dataframe: return column that is a compression of other columns


code:
from eventlet import wsgi
import eventlet

from pprint import pformat

def show_env(env, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    return ['%s\r\n' % pformat(env)]

wsgi.server(eventlet.listen(('', 8090)), show_env)

rawDescription: Obtaining Client IP address from a WSGI app using Eventlet


rawDescription: How to make random.shuffle truly random?

description: Make random.shuffle truly random


rawDescription: Function application over numpy's matrix row/column


code:
from io import StringIO
import pandas

datatable = StringIO("""\
datadate  | id | Value
1999-12-31 | 01 |  1.0
1999-12-31 | 02 |  0.5
1999-12-31 | 03 |  3.2
2000-01-04 | 01 |  1.0
2000-01-04 | 02 |  0.7
2000-01-04 | 03 |  3.2""")

fullindex = pandas.DatetimeIndex(freq='1D', start='1999-12-31', end='2000-01-06')
df = (
    pandas.read_table(datatable, sep='\s+\|\s+', parse_dates=['datadate'])
          .set_index(['datadate', 'id'])
          .unstack(level='id')
          .reindex(fullindex)
          .fillna(method='ffill')
          .stack()
          .reset_index()
          .rename(columns={'level_0': 'date'})
)

print(df)

rawDescription: Best Way To Unpivot a Pandas Dataframe

description: Best Way To Unpivot a Pandas Dataframe


rawDescription: Python :getting the count for the adjectives in a string


code: Nooooo

rawDescription: Python - How to check if the text is in a file txt?


code:
#!/usr/bin/env python3
# coding: utf-8

# use json module to handle json-formatted data in python
import json

new_entry = {"header": "The story to be added",
    "author": "me",
    "team": "editor",
    "date": ["2015", "12", "13"],
    "paragraphs": ["First para", "Second para"],
    "images": []
    }

update_entry = {"header": "Formerly written by John",
    "author": "me"
    }

# Use `with open()` in order to open a file and close it automatically after all operations are done.
with open('blog_entries.json') as f:
    existing_entries = json.load(f)

# Before starting any manipulation print the existing blog entries in order to double-check.
# Use `json.dumps()` in order to get a nicely formatted output
print(json.dumps(existing_entries, sort_keys=True, indent=4))

# Since `json.load()` converts the json data to the appropiate Python datatype (list or dict) we can use Python's
# standard operations for those datatypes.
# `exiting_blogs` will be a list since it's an array in the json-formatted file (an object would become a dict),
# so we append the new blog entry and print it again in order to double-check
existing_entries.append(new_entry)
print(json.dumps(existing_entries, sort_keys=True, indent=4))

# OK, let's say we want to manipulate the blog entry which was written by John.
# First, we have to find the desired data in the list.
for entry in existing_entries:
    if entry['author'] == 'John':
        # Update the existing entry (of datatype dict) with the new elements which will overwrite the old ones.
        entry.update(update_entry)
    else:
        # We did not find any entry written by John. Think about this error case later...
        pass

# This output will show that the entry written by John was updated with the data given in `update_enry`.
print(json.dumps(existing_entries, sort_keys=True, indent=4))

# Write the manipulated data to a new file.
# For sure, we could use the same file as we read from, but this would make comparing the file contents somehow
# difficult
with open('new_blog_entries.json', 'w') as f:
    json.dump(existing_entries, f)

rawDescription: Python: How do I make changes and add onto in json


code:
def reverse(number):
     reverse=''
     while number>0:
        reverse = reverse + str(number % 10)
        number=number//10
     return reverse

rawDescription: Python main function dealing with true and false


code:
#!/usr/bin/env python
"""Continuation-passing style (CPS) script.

Usage:

   $ python cps.py script1.py arg1 arg2 -- script2.py a b c -- script3.py ...
"""
import platform
import sys
from subprocess import call

if len(sys.argv) < 2:
    sys.exit() # nothing to do

# define a command that starts new terminal
if platform.system() == "Windows":
    new_window_command = "cmd.exe /c start cmd.exe /c".split()
else:  #XXX this can be made more portable
    new_window_command = "x-terminal-emulator -e".split()

# find where script args end
end = sys.argv.index('--') if '--' in sys.argv else len(sys.argv)

# call script; wait while it ends; ignore errors
call([sys.executable] + sys.argv[1:end])

# start new window; call itself; pass the rest; ignore errors
rest = sys.argv[end+1:]
if rest:
    call(new_window_command + [sys.executable, sys.argv[0]] + rest)

print("Press Enter to exit") #NOTE: to avoid raw_input/input py3k shenanigans
sys.stdin.readline()

rawDescription: keep multiple cmd windows open from batch

description: Keep multiple cmd windows open from batch


code:
def f(array1, array2) :
    return np.dot(array1, array2)

rawDescription: How to apply function of multiple matrices to each element of a list of matrices with python numpy?

description: Apply function of multiple matrices to each element of a list of matrices with python numpy


code:
multilevel_indices = {'foo': ['A', 'B', 'C'], 'bar': ['X', 'Y'], 'baz': []}
column_data_1      = {'foo': [2, 4, 5],       'bar': [2, 3], 'baz': []}

pd.concat([pd.Series(column_data_1[k], index=multilevel_indices[k]) for k in multilevel_indices],
          keys=multilevel_indices.keys())

rawDescription: Creating a Multi-Index / Hierarchical DataFrame from Dictionaries


code:
import re
from BeautifulSoup import BeautifulSoup

html = '
Chinese New Year Sale
February 8, 2013 - February 10, 2013
'
date_span = BeautifulSoup(html).findAll('h2', {'class' : 'pointer'})[0].findAll('span')[0]
date = re.findall(r'(.+?)', str(date_span))[0]

rawDescription: How to parse html using beautifulsoap/python?

description: Parse html using beautifulsoap/python


code:
from baseclass_entity import Entity

class MyEntity(Entity):

    def OnCollision(self):
        print("I did it!")

my_entity = MyEntity()
my_entity.OnCollision()

rawDescription: Calling Entity's function with a derived class


rawDescription: Copied dictionary via numpy.copy. Now is ndarray; how to recover the original dictionary?


code:
a, b, c, d, score = izip(*sorted(izip(a, b, c, d, score), reverse=True,
                         key=lambda x: x[4]))

rawDescription: sorting multiple lists in python based on sorting of a single list

description: Sorting multiple lists in python based on sorting of a single list


rawDescription: How to get an inheritance tree from AST?

description: Get an inheritance tree from AST


rawDescription: numpy 1.6.1 argsort() strange behaviour?

description: Numpy 1.6.1 argsort() strange behaviour


code:
# Executes functions contained in expressions
class EvalFunction(object):
  pop_ = {}
  def __init__(self, tokens):
    self.func_ = tokens.funcname
    self.field_ = tokens.arg
  def eval(self):
      # Get the name of the requested field and source db
      # Functions can only be called on dbRef so this always done
      v = self.field_.value
      fieldRef = v.split(':')
      source = fieldRef[0]
      field = fieldRef[1]

      # Evaluate the dbRef (get the value from the db)
      val = self.field_.eval()

      if self.func_ == 'Avg':
        rec = db['Stats'].find_one({'_id' : field})
        return rec['value']['avg']
      elif self.func_ == 'Root':
          return math.sqrt(val)

rawDescription: Evaluating functions within arithmetic grammar of a DSL


code:
class Foo(object):
    def __init__(self):
        self.list_one = [1, 2, 3]

class Bar(Foo):
    def init(self):
        super(Bar, self).__init__()
        self.list_two = self.list_one + [4, 5, 6]
        # if you want to discard list_one, you can, but that seems wrong somehow
        # del self.list_one

rawDescription: Merge two lists inside __init__ without instantiation. Python


code:
T2 = leg.texts[1]
T2.set_y(-2)

rawDescription: offset one of matplotlib's legend items

description: Offset one of matplotlib's legend items


code: copy = dictionary1

rawDescription: Randomly replace 2 values in python dictionary


code:
x = y = 30
w = h = 100

mask = np.zeros(img.shape[:2],np.uint8)
mask[y:y+h,x:x+w] = 255
res = cv2.bitwise_and(img,img,mask = mask)

rawDescription: OpenCV via python: Is there a fast way to zero pixels outside a set of rectangles?


code:
data = dfnew.astype(float).values
extent = [float(dfnew.columns[0]),
          float(dfnew.columns[-1]),
          float(dfnew.index[0]),
          float(dfnew.index[-1])]
import matplotlib.pyplot as plt
plt.imshow(data, extent=extent, origin='lower')
plt.xlabel('Time')
plt.ylabel('Y')

rawDescription: Use Python and Pandas to split data in a text file


code:
class BaseBarFormSet(BaseInlineFormSet):
    def __init__(self, other_model_queryset, *args, **kwargs):
        super(BaseInlineFormSet, self).__init__(*args, **kwargs)

        for form in self.forms:
            form.fields['other_field'].queryset = other_model_queryset

rawDescription: Change queryset of model field in inlineformset of non parent model


code:
class SubProfileMiddleware(object):

    def process_request(self, request):
        subprofile = request.GET.get('subprofile', None)
        if subprofile:
            # it's important to check for user here or malicious users will be
            # able to use Subprofiles of other users
            subprofile = Subprofile.objects.filter(user=request.user, id=subprofile)
            # This can also be written
            # subprofile = request.user.subprofile_set.filter(id=subprofile)
            if not subprofile:
                # this is a malicious user
                raise Http403
            else:
                request.user.subprofile = subprofile
        else:
             # set default subprofile
             request.user.subprofile = self.user.default_subprofile

rawDescription: Python: How to "fork" a session in django


code: response['X-Accel-Redirect'] = url

rawDescription: Django: Unicode Filenames with ASCII headers?


rawDescription: Connect double-click event of QListView with method in PyQt4


code: pos = numpy.random.multivariate_normal(mean, C, size=Nwalkers)

rawDescription: Truncated multivariate normal in SciPy?

description: Truncated multivariate normal in SciPy


code:
def summaryStats():
    filename = input("Enter a file name: ")
    with open(filename) as f:
        data = [int(line) for line in f]

    print("The minimum value is ", min(data))
    print("The maximum value is ", max(data))
    print("The average value is ", sum(data)/len(data))

rawDescription: How to find the average of values in a .txt file

description: Find the average of values in a .txt file


code:
from itertools import *
def ilen(iterable): return sum(1 for _ in iterable)
def group(table, column): return groupby(table, itemgetter(column))
[(k, ilen(g)) for k, g in group(people, 'last')]
def glen(kg): return kg[0], sum(1 for _ in kg[1])
[glen(g) for g in group(people, 'last')]
def gsum(kg, column): return kg[0], sum(int(x[column]) for x in kg[1])
[gsum(g, 'age') for g in group(people, 'last')]

rawDescription: Are there a tools that can help to treat files as tables in a database?


code:
import argparse

# parse arguments from commandline if available
parser = argparse.ArgumentParser()
parser.add_argument('-cl', '--column_names', default=None, nargs='+', type=str)
parser.add_argument('-vl', '--fill_values', default=None,  nargs='+', type=str)

extra_headers = parser.parse_args().column_names
col_fill = parser.parse_args().fill_values

# make sure col_fill is the same length as extra_headers
if len(col_fill) == len(extra_headers):
    raise ValueError('Wrong number of column fills for number of headers!')
header.extend(extra_headers)

writer = csv.DictWriter(outcsv, fieldnames = header)
writer.writeheader()

# extend p with two columns of blank data
writer.writerows({col: row_item for row_item,col in zip(row+col_fill,header)} for row in p)

rawDescription: How to fill new columns in a csv file through command line

description: Fill new columns in a csv file through command line


code:
with open("in.txt") as f:
    prev = f.read(1)
    c = Counter()
    for ch in chain.from_iterable(f):
        c[prev + ch] += 1
        prev = ch
print(c)

rawDescription: Counting Occurrences of Letter Combinations


code:
import pandas as pd
frame = pd.read_csv('test.csv')
frame
type(frame)
hdf5store = pd.HDFStore('mydata.h5')
hd5store['frame'] = frame
hdf5store
list(hdf5store.items())
hdf5store.close()

rawDescription: Converting a dataset into an HDF5 dataset


code:
import numpy as np

def slow(a):
    b = np.array(zip(a.T,a.T))
    b.shape = (2*len(a[0]), 2)
    return b.T

def fast(a):
    return a.repeat(2).reshape(2, 2*len(a[0]))

def faster(a):
    # compliments of WW
    return a.repeat(2, axis=1)

rawDescription: Interleave a numpy array with itself

description: Interleave a numpy array with itself


code:
from random import randint

ListA = [(randint(0,1000),randint(0,1000)) for i in range(5000)]
ListB = [(randint(0,1000),randint(0,1000)) for i in range(5000)]

rawDescription: How to find the point pairs in two point lists with min distance in a efficent way?

description: Find the point pairs in two point lists with min distance in a efficent way


code:
def getOdds(p,q):
    """ prints all of the odd numbers between integers p & q """

    print(*getOdds_gen_helper(p,q), sep=", ")

rawDescription: I don't know how to strip the end of this line


rawDescription: Convert a binary to an array with each binary number


rawDescription: Convert triplets to matrix/dataframe in python


code:
@login_required
def test(request):
    a = Profile.objects.filter(user=request.user).select_related('user').get()
    return render_to_response('peeks/test.html', {'a':a,})

rawDescription: How to select users based on their profile

description: Select users based on their profile


code:
while True:
    login()

rawDescription: Creating a dictionary to store pass and user


code:
def combine_n(elements, r, cur_index=0, cur_combo=()):
    r-=1
    temp_list = []
    for elem_index in range(cur_index, len(elements)-r):
        i = elements[elem_index]
        if r > 0:
            temp_list = temp_list + combine_n(elements, r, elem_index+1, cur_combo+(i,))
        else:
            temp_list.append(cur_combo+(i,))
    return temp_list

elements = list(range(1,6))
print = combine_n(elements, 3)

rawDescription: Is it possible to write a combination function with recursion technique?


code: df['Rheum'] = df.ICD.str.contains('391.1') + 0

rawDescription: REGEX using Pandas

description: REGEX using Pandas


rawDescription: How do you remove \r and \n using re.py?

description: Remove \r and \n using re.py


code:
from threading import Thread

def my_function():
    while True:
        if player.lives < 5:
            do_stuff()

Thread(my_function).start()

rawDescription: How do you create a new thread in python?

description: Create a new thread in python


code:
class SomeFileType(object):
    _filename = None
    _client = None

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

    @property
    def filename(self):
        if self._filename is None:
            filename = os.path.basename(self.path)
            self._filename = os.path.splitext(filename)[0]
        return self._filename

    @property
    def client(self):
        '''Returns client name associated with file'''
        if self._client is None:
            client = self.filename.split()
            self._client = client[1] # Assuming filename is formatted "date client - docTitle"
        return self._client

rawDescription: Python class __init__ layout?

description: Python class __init__ layout


code:
def __iter__(self):
    for i in self.__a:
        yield i

rawDescription: Why yield returns an iterator?

description: Why yield returns an iterator


code:
def find(abc):
    try:                                                          # first element is list
        return find(abc[0] + abc[1:])                             #  -> flatten
    except:                                                       # first element is value
        if len(abc) <= 1: return abc                              # -> either end recursion
        return sorted(abc[:1] + find(abc[1:]), reverse=True)[-2:] # -> or recurse over tail

rawDescription: Finding the second smallest int in list of list in Python 3 with recursion


rawDescription: Iteratively collect first two elements of each vector of a matrix


code: p1.func == p2.func and p1.args == p2.args and p1.keywords == p2.keywords

rawDescription: How to compare wrapped functions with functools.partial?

description: Compare wrapped functions with functools.partial


code: OrderedDict(dog='dom',tiger='EN',panda='EN')  #doesn't preserve order

rawDescription: pythonic way for FIFO order in Dictionary

description: Pythonic way for FIFO order in Dictionary


code: lines = [line.strip() for line in file.readlines() if len(line.strip()) != 0]

rawDescription: Deleting blank lines with Python

description: Deleting blank lines with Python


code:
rangeList = range(0,21)
lastNumber = rangeList[len(rangeList)-1:][0]

rawDescription: how get last number in range in python

description: How get last number in range in python


rawDescription: Python: Saving parts of str to an array

description: Python: Saving parts of str to an array


code:
df.sort(['mac address', 'datetime'], inplace=True)

df['origin'] = df['node name'].shift(1)
df['departure time'] = df['datetime'].shift(1)

# correct for the places where the mac addresses change
idx = df['mac address'] != df['mac address'].shift(1)
df.loc[idx, 'origin'] = np.nan
df.loc[idx, 'departure time'] = np.nan

rawDescription: How to Efficiently Process Time-Series Data in Pandas


rawDescription: Get attribute of all items in container python


code:
def gen():
     print('In gen')
     yield 1
     yield 2

def func():
     print('In gen')

rawDescription: How python interpret a function as a generator


code:
from ryu.lib.packet import packet, ethernet, arp, ipv4
import array

@set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
def _packet_in_handler(self, ev):

    ### Mike Pennington's logging modifications
    ## Set up to receive the ethernet src / dst addresses
    pkt = packet.Packet(array.array('B', ev.msg.data))
    eth_pkt = pkt.get_protocol(ethernet.ethernet)
    arp_pkt = pkt.get_protocol(arp.arp)
    ip4_pkt = pkt.get_protocol(ipv4.ipv4)
    if arp_pkt:
        pak = arp_pkt
    elif ip4_pkt:
        pak = ip4_pkt
    else:
        pak = eth_pkt
    self.logger.info('  _packet_in_handler: src_mac -> %s' % eth_pkt.src)
    self.logger.info('  _packet_in_handler: dst_mac -> %s' % eth_pkt.dst)
    self.logger.info('  _packet_in_handler: %s' % pak)
    self.logger.info('  ------')
    src = eth_pkt.src  # Set up the src and dst variables so you can use them
    dst = eth_pkt.dst
    ## Mike Pennington's modifications end here

    msg = ev.msg
    datapath = msg.datapath
    ofproto = datapath.ofproto

    dpid = datapath.id
    self.mac_to_port.setdefault(dpid, {})

    # learn a mac address to avoid FLOOD next time.
    self.mac_to_port[dpid][src] = msg.in_port

    if dst in self.mac_to_port[dpid]:
        out_port = self.mac_to_port[dpid][dst]
    else:
        out_port = ofproto.OFPP_FLOOD

    actions = [datapath.ofproto_parser.OFPActionOutput(out_port)]

    # install a flow to avoid packet_in next time
    if out_port != ofproto.OFPP_FLOOD:
        self.add_flow(datapath, msg.in_port, dst, actions)

    out = datapath.ofproto_parser.OFPPacketOut(
        datapath=datapath, buffer_id=msg.buffer_id, in_port=msg.in_port,
        actions=actions)
    datapath.send_msg(out)

rawDescription: python - ryu handling packets using a switch after flow was added to switch

description: Python - ryu handling packets using a switch after flow was added to switch


rawDescription: how to traverse a list in reverse order in python(index style-'in Range' only)

description: Traverse a list in reverse order in python(index style-'in Range' only)


code:
from itertools import izip
print(all(x >= y for x,y  in izip(a,b)))

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


code:
panelOneId = wx.NewId()
panelTwoId = wx.NewId()

rawDescription: wxpython controlling a widget with the id

description: Wxpython controlling a widget with the id


rawDescription: How to change the icon in the pygame window?

description: Change the icon in the pygame window


code:
expl_var = 'Av_Temp'
cname = 'Tot_Precip'
df[expl_var+'_Deciles'] = pandas.qcut(df[expl_var], 2)

# I moved your nan check into the df apply function
grp_df = df.groupby('Av_Temp_Deciles').apply(lambda x: numpy.array(x[cname][~numpy.isnan(x[cname])]))

# boxplot_stats can take a 2D numpy array of data, and a 1D array of labels
# stats is now a list of dictionaries of stats, one dictionary per quantile
stats = cbook.boxplot_stats(grp_df.values, labels=grp_df.index)

# now it's a one-shot plot, no loops
fig, ax = plt.subplots()
ax.bxp(stats)
ax.set_yscale('log')

rawDescription: Overlapping boxplots in python

description: Overlapping boxplots in python


code:
sentences = []
sentence = []

for word, code in data:
    sentence.append((word, code))
    if word in '.?!':
        sentences.append(sentence)
        sentence = []

rawDescription: How to stop a for-loop and make it work further?

description: Stop a for-loop and make it work further


code:
class KeyPressEvent(KeyEvent):
    name = 'keyPress'
    binding = wx.EVT_CHAR
    id = wx.wxEVT_CHAR

rawDescription: PythonCard not getting 'enter' KeyEvent in Windows


code:
import re
import StringIO
import pandas as pd

txt = '''P-X1-6030-07-A01    368963
P-X1-6030-08-A01    368964
P-X1-6030-09-A01    368965
P-A-1-1011-14-G-01  368967
P-A-1-1014-01-G-05  368968
P-A-1-1017-02-D-01  368969'''

fileobj = StringIO.StringIO(txt)

def df_from_file(fileobj):
    '''
    takes a file object, returns DataFrame with columns grouped by
    contiguous runs of either letters or numbers (but not both together)
    '''
    # unfortunately, we must materialize the data before putting it in the DataFrame
    gen_records = [re.findall(r'(\d+|[A-Z]+)', line) for line in fileobj]
    return pd.DataFrame.from_records(gen_records)

df = df_from_file(fileobj)

rawDescription: How do I create a pandas dataframe in python from a csv with additional delimiters?

description: Create a pandas dataframe in python from a csv with additional delimiters


code:
cursor.execute('INSERT OR IGNORE INTO foo (bar,baz) VALUES (?, ?)',(1,3))

cursor.execute('SELECT * from foo')
data=cursor.fetchall()
print(data)
# [(1, 2)]

rawDescription: Basic pySQLite example?

description: Basic pySQLite example


code:
{'author': 'User',
 'contributors': 'None',
 'contributors_enabled': 'False',
 'coordinates': 'None',
 'created_at': 'datetime',
 'default_profile': 'True',
 'default_profile_image': 'False',
 'favorite_count': '0',
 'favorited': 'False',
 'favourites_count': '46',
 'follow_request_sent': 'None',
 'followers_count': '204',
 'following': 'False',
 'friends_count': '274',
 'geo': 'None',
 'geo_enabled': 'True',
 'id': '652242063048724480',
 'in_reply_to_screen_name': 'None',
 'in_reply_to_status_id': 'None',
 'in_reply_to_status_id_str': 'None',
 'in_reply_to_user_id': 'None',
 'in_reply_to_user_id_str': 'None',
 'is_quote_status': 'False',
 'is_translator': 'False',
 'listed_count': '91',
 'location': 'None',
 'notifications': 'None',
 'place': 'None',
 'possibly_sensitive': 'False',
 'profile_background_tile': 'False',
 'profile_use_background_image': 'True',
 'protected': 'False',
 'retweet_count': '0',
 'retweeted': 'False',
 'statuses_count': '9724',
 'truncated': 'False',
 'user': 'User',
 'utc_offset': '7200',
 'verified': 'False'}

rawDescription: Loading `status` objects from File?

description: Loading `status` objects from File


code: return dict(item.split(':', 1) for item in info.split(';'))

rawDescription: Python split and manipulate results

description: Python split and manipulate results


code:
import requests
from bs4 import BeautifulSoup

r = requests.get('http://www.tamswithmark.com/shows/anything-goes-beaumont-1987/')
soup = BeautifulSoup(r.content, 'html.parser')
rows = soup.findAll('tr', {"class": "upcoming_performance"})

rawDescription: Using Python to Automate Web Searches

description: Using Python to Automate Web Searches


code:
i=1
while i<=10:
    print ( "Welcome student #", i ,"your ticket is #" , 1000+i)
    i+=1

rawDescription: how to solve this in python (for and while loops)?

description: Solve this in python (for and while loops)


rawDescription: Read a CSV file and Append to dictionary


code:
inds = np.lexsort((a['time'], np.minimum(a['to'], a['fr'])))
a = a[inds]

rawDescription: Sorting a record array in numpy

description: Sorting a record array in numpy


code:
class YourModel(models.Model):
    _name = 'your.model'
    _inherit = [
        'protected_fields.mixin',
    ]
    _protected_fields = ['field_you_want_to_protect']

    field_you_want_to_protect = fields.Char()
    forbridden_user = fields.Many2one('res.users')
    current_user_forbidden = fields.Boolean(compute="_compute_current_user_forbidden")

    @api.one
    @api.depends('forbridden_user')
    def _compute_current_user_forbidden(self):
        """
        Compute a field indicating whether the current user
        shouldn't be able to edit some fields.
        """
        self.current_user_forbidden = (self.forbridden_user == self.env.user)

    @api.multi
    def _is_permitted(self):
        """
        Allow only authorised users to modify protected fields
        """
        permitted = super(DetailedReport, self)._is_permitted()
        return permitted or not self.current_user_forbidden

rawDescription: Odoo fields access rights/rules

description: Odoo fields access rights/rules


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

def two_lines(x, a, b, c, d):
    one = a*x + b
    two = c*x + d
    return np.maximum(one, two)

rawDescription: Fit a curve for data made up of two distinct regimes


code:
import mysql.connector
from mysql.connector import errorcode

try:
    conn = mysql.connector.connect(user='root', password=password,
                                   database='test') # MySQL 4.1+
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exists")
    else:
        print(err)
else:
    conn.close()

rawDescription: Testing connection to MySQL with Python using subprocess


code:
from operator import itemgetter
print(sorted(final_list.items(),key=itemgetter(1),reverse=True))

rawDescription: How do I create a dictionary where I add points to names form a text file?

description: Create a dictionary where I add points to names form a text file


code:
g.diff()
Out[246]: -sin(x)*cos(cos(x))

rawDescription: How to do function composition in Sympy?

description: Do function composition in Sympy


rawDescription: OpenCV: setting all pixels of specific BGR value to another BGR value


code:
class MyInt(int):
    difference=property(lambda self: self.__sub__)

rawDescription: Setting a lambda function as a property

description: Setting a lambda function as a property


code: circle += 1

rawDescription: save variables on a while loop

description: Save variables on a while loop


code:
def play():
    currentFrame.pack_forget()
    game.pack()

rawDescription: Having trouble with packing and unpacking frames in Tkinter


code:
import numpy as np

a = [range(255) for _ in range(10)]
np_a = np.array(a)
# set all values above 200 to 0
np_a[np_a > 200] = 0
# np_a now contains the data with all values above 200 changed to 0

# if you needed to convert the numpy array back to a python list
a = np_a.tolist()

rawDescription: Filtering a list of lists in a smart way


code:
import numpy as np

def generate_text_file(length=1e6, ncols=20):
    data = np.random.random((length, ncols))
    np.savetxt('large_text_file.csv', data, delimiter=',')

def iter_loadtxt(filename, delimiter=',', skiprows=0, skipcols=None,dtype=float):
    if skipcols is None:
        skipcols = []
    def iter_func():
        with open(filename, 'r') as infile:
            for _ in range(skiprows):
                next(infile)
            for line in infile:
                line = line.rstrip().split(delimiter)
                for i, item in enumerate(line):
                    if i in skipcols:
                        continue
                    yield dtype(item)
        iter_loadtxt.rowlength = len(line) - len(skipcols)

    data = np.fromiter(iter_func(), dtype=dtype)
    data = data.reshape((-1, iter_loadtxt.rowlength))
    return data

#generate_text_file()
data = iter_loadtxt('large_text_file.csv')

rawDescription: numpy.loadtxt - negated usecols?

description: Numpy.loadtxt - negated usecols


code:
for x in somelist:
    something( x )

rawDescription: Cleaning up nested for loops in python

description: Cleaning up nested for loops in python


code: return counter

rawDescription: My 'lowest common multiple' program hangs, and doesn't output an answer


code:
sizes = np.array([[s.stop-s.start for s in object_slice]
                  for object_slice in data_slices])
# array([[1, 1, 1],
#        [1, 1, 1],
#        [1, 1, 1],
#        [1, 1, 1],
# ...

rawDescription: Objects' sizes along dimension?

description: Objects' sizes along dimension


code:
# Group and sort in descending order of scenario
grp = df.sort_values(['master id', 'scenario'], ascending=False).groupby('master id')

# Get only the latest and previous scenarios
df_first = grp.nth(0).reset_index()  # synonymous to .first()
df_first['rev_scen'] = 'current'
df_second = grp.nth(1).reset_index()
df_second['rev_scen'] = 'previous'

df_latest = df_first.append(df_second) # Merge the two

# From here on it's basically the same as the original answer
df_scen = df_latest.groupby(['master id', 'rev_scen']).agg({'price': 'sum'}).unstack('rev_scen')
df_scen['% change'] = 100 * df_scen[('price', 'current')] / df_scen[('price', 'previous')] - 100

rawDescription: How to df.groupby.sum only one column

description: Df.groupby.sum only one column


rawDescription: Python - creating subpackage without exposing internal imports


code:
import re
p = re.compile(r'\*\s*\({2}.*?\){2}\s*')
test_str = "Name Multiple Words Testing With 1234 Numbers and this stuff* ((Bla Bla Bla (Bla Bla) A40 & A41)) Name Multiple Words Testing With 3456 Numbers and this stuff2* ((Bla Bla Bla (Bla Bla) A42 & A43)) Name Multiple Words Testing With 78910 Numbers and this stuff3* ((Bla Bla Bla (Bla Bla) A44 & A45)) Name Multiple Words Testing With 1234 Numbers and this stuff4* ((Bla Bla Bla (Bla Bla) A46 & A47)) Name Multiple Words Testing With 1234 Numbers and this stuff5* ((Bla Bla Bla (Bla Bla) A48 & A49)) Name Multiple Words Testing With 1234 Numbers and this stuff6* ((Bla Bla Bla (Bla Bla) A50 & A51)) Name Multiple Words Testing With 1234 Numbers and this stuff7* ((Bla Bla Bla (Bla Bla) A52 & A53)) Name Multiple Words Testing With 1234 Numbers and this stuff8* ((Bla Bla Bla (Bla Bla) A54 & A55)) Name Multiple Words Testing With 1234 Numbers and this stuff9* ((Bla Bla Bla (Bla Bla) A56 & A57)) Name Multiple Words Testing With 1234 Numbers and this stuff10* ((Bla Bla Bla (Bla Bla) A58 & A59)) Name Multiple Words Testing With 1234 Numbers and this stuff11* ((Bla Bla Bla (Bla Bla) A60 & A61)) Name Multiple Words Testing With 1234 Numbers and this stuff12* ((Bla Bla Bla (Bla Bla) A62 & A63)) Name Multiple Words Testing With 1234 Numbers and this stuff13* ((Bla Bla Bla (Bla Bla) A64 & A65)) Name Multiple Words Testing With 1234 Numbers and this stuff14* ((Bla Bla Bla (Bla Bla) A66 & A67)) Name Multiple Words Testing With 1234 Numbers and this stuff15* ((Bla Bla Bla (Bla Bla) A68 & A69)) Name Multiple Words Testing With 1234 Numbers and this stuff16*"
print(re.split(p, test_str))

rawDescription: Parsing Text with Python RegEx re.findall


code: stats = {'ponyattack': 0, 'health': 100, 'armor': 1, 'strength': 1, 'potion': 0, 'attack': 10, 'stamina': "N/A", 'shield': "lol, what shield?", 'hint': 3}

rawDescription: My game relies heavily on globals, but also gives me syntaxwarning even though the game won't work without them


rawDescription: Python find longest ORF in DNA sequence

description: Python find longest ORF in DNA sequence


code:
flash('category one flash message', 'category1')
flash('category two flash message', 'category2')

rawDescription: Flashing 2 groups of messages in 2 different places using Flask


rawDescription: How to get list of all possible sums of n*m matrix rows

description: Get list of all possible sums of n*m matrix rows


code:
from math import *
try:
    import matplotlib as mpl
    import matplotlib.pyplot
    from mpl_toolkits.mplot3d import Axes3D
    import numpy
    plotting_enabled = True
except ImportError:
    plotting_enabled = False

def main():
    # get base polygon data based on unit sphere
    r = 1.0
    polygon = get_cartesian_polygon_data(r)
    point_count = len(polygon)
    reference = ok_reference_for_polygon(polygon)
    # decompose the polygon into triangles and record each area and 3d centroid
    areas, subcentroids = list(), list()
    for ia, a in enumerate(polygon):
        # build an a-b-c point set
        ib = (ia + 1) % point_count
        b, c = polygon[ib], reference
        if points_are_equivalent(a, b, 0.001):
            continue  # skip nearly identical points
        # store the area and 3d centroid
        areas.append(area_of_spherical_triangle(r, a, b, c))
        tx, ty, tz = zip(a, b, c)
        subcentroids.append((sum(tx)/3.0,
                             sum(ty)/3.0,
                             sum(tz)/3.0))
    # combine all the centroids, weighted by their areas
    total_area = sum(areas)
    subxs, subys, subzs = zip(*subcentroids)
    _3d_centroid = (sum(a*subx for a, subx in zip(areas, subxs))/total_area,
                    sum(a*suby for a, suby in zip(areas, subys))/total_area,
                    sum(a*subz for a, subz in zip(areas, subzs))/total_area)
    # shift the final centroid to the surface
    surface_centroid = scale_v(1.0 / mag(_3d_centroid), _3d_centroid)
    plot(polygon, reference, _3d_centroid, surface_centroid, subcentroids)

def get_cartesian_polygon_data(fixed_radius):
    cartesians = list()
    with open('longitude and latitude.txt') as f:
        for line in f.readlines():
            spherical_point = [float(v) for v in line.split()]
            if len(spherical_point) == 2:
                spherical_point.append(fixed_radius)
            cartesians.append(degree_spherical_to_cartesian(spherical_point))
    return cartesians

def ok_reference_for_polygon(polygon):
    point_count = len(polygon)
    # fix the average of all vectors to minimize float skew
    polyx, polyy, polyz = zip(*polygon)
    # /10 is for visualization. Remove it to maximize accuracy
    return (sum(polyx)/(point_count*10.0),
            sum(polyy)/(point_count*10.0),
            sum(polyz)/(point_count*10.0))

def points_are_equivalent(a, b, vague_tolerance):
    # vague tolerance is something like a percentage tolerance (1% = 0.01)
    (ax, ay, az), (bx, by, bz) = a, b
    return all(((ax-bx)/ax < vague_tolerance,
                (ay-by)/ay < vague_tolerance,
                (az-bz)/az < vague_tolerance))

def degree_spherical_to_cartesian(point):
    rad_lon, rad_lat, r = radians(point[0]), radians(point[1]), point[2]
    x = r * cos(rad_lat) * cos(rad_lon)
    y = r * cos(rad_lat) * sin(rad_lon)
    z = r * sin(rad_lat)
    return x, y, z

def area_of_spherical_triangle(r, a, b, c):
    # points abc
    # build an angle set: A(CAB), B(ABC), C(BCA)
    # http://math.stackexchange.com/a/66731/25581
    A, B, C = surface_points_to_surface_radians(a, b, c)
    E = A + B + C - pi  # E is called the spherical excess
    area = r**2 * E
    # add or subtract area based on clockwise-ness of a-b-c
    # http://stackoverflow.com/a/10032657/377366
    if clockwise_or_counter(a, b, c) == 'counter':
        area *= -1.0
    return area

def surface_points_to_surface_radians(a, b, c):
    """build an angle set: A(cab), B(abc), C(bca)"""
    points = a, b, c
    angles = list()
    for i, mid in enumerate(points):
        start, end = points[(i - 1) % 3], points[(i + 1) % 3]
        x_startmid, x_endmid = xprod(start, mid), xprod(end, mid)
        ratio = (dprod(x_startmid, x_endmid)
                 / ((mag(x_startmid) * mag(x_endmid))))
        angles.append(acos(ratio))
    return angles

def clockwise_or_counter(a, b, c):
    ab = diff_cartesians(b, a)
    bc = diff_cartesians(c, b)
    x = xprod(ab, bc)
    if x < 0:
        return 'clockwise'
    elif x > 0:
        return 'counter'
    else:
        raise RuntimeError('The reference point is in the polygon.')

def diff_cartesians(positive, negative):
    return tuple(p - n for p, n in zip(positive, negative))

def xprod(v1, v2):
    x = v1[1] * v2[2] - v1[2] * v2[1]
    y = v1[2] * v2[0] - v1[0] * v2[2]
    z = v1[0] * v2[1] - v1[1] * v2[0]
    return [x, y, z]

def dprod(v1, v2):
    dot = 0
    for i in range(3):
        dot += v1[i] * v2[i]
    return dot

def mag(v1):
    return sqrt(v1[0]**2 + v1[1]**2 + v1[2]**2)

def scale_v(scalar, v):
    return tuple(scalar * vi for vi in v)

def plot(polygon, reference, _3d_centroid, surface_centroid, subcentroids):
    fig = mpl.pyplot.figure()
    ax = fig.add_subplot(111, projection='3d')
    # plot the unit sphere
    u = numpy.linspace(0, 2 * numpy.pi, 100)
    v = numpy.linspace(-1 * numpy.pi / 2, numpy.pi / 2, 100)
    x = numpy.outer(numpy.cos(u), numpy.sin(v))
    y = numpy.outer(numpy.sin(u), numpy.sin(v))
    z = numpy.outer(numpy.ones(numpy.size(u)), numpy.cos(v))
    ax.plot_surface(x, y, z, rstride=4, cstride=4, color='w', linewidth=0,
                    alpha=0.3)
    # plot 3d and flattened polygon
    x, y, z = zip(*polygon)
    ax.plot(x, y, z, c='b')
    ax.plot(x, y, zs=0, c='g')
    # plot the 3d centroid
    x, y, z = _3d_centroid
    ax.scatter(x, y, z, c='r', s=20)
    # plot the spherical surface centroid and flattened centroid
    x, y, z = surface_centroid
    ax.scatter(x, y, z, c='b', s=20)
    ax.scatter(x, y, 0, c='g', s=20)
    # plot the full set of triangular centroids
    x, y, z = zip(*subcentroids)
    ax.scatter(x, y, z, c='r', s=4)
    # plot the reference vector used to findsub centroids
    x, y, z = reference
    ax.plot((0, x), (0, y), (0, z), c='k')
    ax.scatter(x, y, z, c='k', marker='^')
    # display
    ax.set_xlim3d(-1, 1)
    ax.set_ylim3d(-1, 1)
    ax.set_zlim3d(0, 1)
    mpl.pyplot.show()

# run it in a function so the main code can appear at the top
main()

rawDescription: Locating the centroid (center of mass) of spherical polygons


rawDescription: python module/framework for math formulas?

description: Python module/framework for math formulas


code:
class Handlers():
    def btn_start_clicked(self, button):
        with open("btn.txt", "a") as muhfile:
            text = "click {}\n".format(datetime.datetime.now())
            muhfile.write(text)

    def directory_set(self, button):
        print(button.get_filename())

rawDescription: Get folder path from FileChooserButton in Python


code:
class Abstract1( object ):
    """Some description that tells you it's abstract,
    often listing the methods you're expected to supply."""
    def aMethod( self ):
        raise NotImplementedError( "Should have implemented this" )

rawDescription: Difference between abstract class and interface in Python


code:
set = 'oops'
set
del set
set

rawDescription: How to restore a builtin that I overwrote by accident?

description: Restore a builtin that I overwrote by accident


code: x = d.keys()

rawDescription: custom comparison for built-in containers

description: Custom comparison for built-in containers


code:
from __future__ import print_function

def f1(LoD, idd=20):
    # loop until first one is found then break and return the dict found
    desired_dict = None
    for di in LoD:
        if di['id'] == idd:
            desired_dict = di
            break
    return desired_dict

def f2(LoD, idd=20):
    # The genexp goes through the entire list, then next() returns either the first or None
    return next((di for di in LoD if di['id'] == idd), None)

def f3(LoD, idd=20):
    # NOTE: the 'filter' here is ifilter if Python2
    return next(filter(lambda di: di['id']==idd, LoD), None)

def f4(LoD, idd=20):
    desired_dict=None
    i=0
    while True:
        try:
            if LoD[i]['id']==idd:
                desired_dict=LoD[i]
                break
            else:
                i+=1
        except IndexError:
            break

    return desired_dict

def f5(LoD, idd=20):
    try:
        return [d for d in LoD if d['id']==idd][0]
    except IndexError:
        return None

if __name__ =='__main__':
    import timeit
    import sys
    if sys.version_info.major==2:
        from itertools import ifilter as filter

    x = [
        {'Car': 'Honda', 'id': 12},
        {'Car': 'Mazda', 'id': 45},
        {'Car': 'Toyota', 'id': 20}
        ]  * 10   # the '* 10' makes a list of 30 dics...

    result=[]
    for f in (f1, f2, f3, f4, f5):
        fn=f.__name__
        fs="f(x, idd=20)"
        ft=timeit.timeit(fs, setup="from __main__ import x, f", number=1000000)
        r=eval(fs)
        result.append((ft, fn, r, ))

    result.sort(key=lambda t: t[0])

    for i, t in enumerate(result):
        ft, fn, r = t
        if i==0:
            fr='{}: {:.4f} secs is fastest\n\tf(x)={}\n========'.format(fn, ft, r)
        else:
            t1=result[0][0]
            dp=(ft-t1)/t1
            fr='{}: {:.4f} secs - {} is {:.2%} faster\n\tf(x)={}'.format(fn, ft, result[0][1], dp, r)

        print(fr)

rawDescription: Python: Fetch item in list where dict key is some value using lambda


code: open(filename, 'w').write('\n'.join('{}  {}'.format(key, d[key]) for key in d))

rawDescription: How to read from file, turn into a dictionary and write to the same file

description: Read from file, turn into a dictionary and write to the same file


code:
for line in fileinput.input():

    line, n = re.subn(pattern1, repl1, line)
    if not n:
        line, n = re.sub(pattern2, repl2, line)
    if not n:
        line, n = re.sub(pattern3, repl3, line)

    ...

    print(line, end="")

rawDescription: python regex only apply one replace

description: Python regex only apply one replace


code:
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
figure = Figure()
canvas = FigureCanvas(figure)
axes = figure.add_subplot(1, 1, 1)
axes.plot(x, np.sin(x), 'k-')
canvas.print_figure('sine.png')

rawDescription: Matplotlib can't suppress figure window

description: Matplotlib can't suppress figure window


code:
import random
import operator

opslist= {
    operator.add: "+",    # the operators all on one line
    operator.sub: "-",
    operator.mul: "x"
}

num1 = random.randint(1,10)  # These are two random numbers for my quiz
num2 = random.randint(1,10)
ops = random.choice(list(opslist.keys())) #Random operator from opslist keys

total = (ops(num1,num2)) # Answer for my quiz

print(num1,opslist[ops],num2)

rawDescription: How do I use arithmetic symbols instead of built in functions

description: Use arithmetic symbols instead of built in functions


rawDescription: Python - convert <type 'instance'> to <type 'str'>?


code:
import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

rawDescription: Append single package folder to sys.path


code:
import numpy as np
np.cumsum([1,2,3,4,5])

rawDescription: Elegant pythonic cumsum

description: Elegant pythonic cumsum


code:
lines = ax.plot(x, y)
line = lines[0]

rawDescription: How do I target a list element of a MatPlotLib object that "returns a list"?

description: Target a list element of a MatPlotLib object that "returns a list"


rawDescription: Is there a consistent way to enumerate days/weeks/months between two dates?


code: shape = pi3d.Lines(vertices=pts)

rawDescription: how to use Pi3d to draw an array

description: Use Pi3d to draw an array


code: pd.Series([dic[el] for el in pd.Series(l)])

rawDescription: Index pandas series entries with integers


code:
emails = tuple(
    (u'Subject', u'Message.', u'from@example.com', [address])
    for name, address in recipients
)

rawDescription: Looping through to create a tuple

description: Looping through to create a tuple


rawDescription: in python: difference between two lists

description: In python: difference between two lists


rawDescription: Merge sliced lists

description: Merge sliced lists


code:
a = np.random.randint(0, 100, size=(5, 5))
a

rawDescription: Get max or min n-elements out of numpy array? (preferably not flattened)