code:
ugly = "[{'ride': 1, 'pickup_time': datetime.datetime(2016, 3, 17, 15, 36, 35, 976202)},{'ride': 2, 'pickup_time': datetime.datetime(2016, 3, 17, 15, 41, 35, 976202)}]"
import datetime
dlist = eval(ugly)
dlist

rawDescription: How to convert a string containing a list of dict into Python object?

description: Convert a string containing a list of dict into Python object


code:
import networkx as nx
G = nx.Graph()
G.add_node(1,color='red')
import math
G.add_node('a',f = math.cos)
G.node['a']['f'](math.pi)

rawDescription: Heuristics in NetworkX-Python

description: Heuristics in NetworkX-Python


rawDescription: How do you dynamically assign aliases in a django aggregate?

description: Dynamically assign aliases in a django aggregate


code:
import itertools
group_func = lambda o: (o.classification, o.type)
map(lambda pair: (pair[0], min(pair[1], key=lambda o: o.last - o.first)),
    itertools.groupby(sorted(l, key=group_func), group_func))

rawDescription: Determining the minimum of a list of n elements


code:
class ScanFolder:
    'Class defining a scan folder'

    def __init__(self, path):
        self.path = path
        self.documents = dict() # key = document label   value = Document reference

        self.event_handler = watchdog.events.PatternMatchingEventHandler(patterns=["*.jpg", "*.jpeg", "*.png", "*.bmp", "*.pdf"],
                                    ignore_patterns=[],
                                    ignore_directories=True)
        self.event_handler.on_any_event = self.on_any_event
        self.observer = Observer()
        self.observer.schedule(self.event_handler, self.path, recursive=False)
        self.observer.start()

    def on_any_event(self, event):
        print(event.src_path, event.event_type)
        print("Complete ScanFolder() access")

    def stop(self):
        self.observer.stop()
        self.observer.join()

rawDescription: How to pass an argument to my Python watchdog.events.PatternMatchingEventHandler

description: Pass an argument to my Python watchdog.events.PatternMatchingEventHandler


rawDescription: Finding objects in lists

description: Finding objects in lists


code:
def search_issues(self, jql_str, startAt=0, maxResults=50, validate_query=True, fields=None, expand=None,
                  json_result=None):
    """
    Get a ResultList of issue Resources matching a JQL search string.

    :param jql_str: the JQL search string to use
    :param startAt: index of the first issue to return
    :param maxResults: maximum number of issues to return. Total number of results
        is available in the ``total`` attribute of the returned ResultList.
        If maxResults evaluates as False, it will try to get all issues in batches of 50.
    :param fields: comma-separated string of issue fields to include in the results
    :param expand: extra information to fetch inside each resource
    """
    # TODO what to do about the expand, which isn't related to the issues?
    infinite = False
    maxi = 50
    idx = 0
    if fields is None:
        fields = []

    # If None is passed as parameter, this fetch all issues from the query
    if not maxResults:
        maxResults = maxi
        infinite = True

    search_params = {
        "jql": jql_str,
        "startAt": startAt,
        "maxResults": maxResults,
        "validateQuery": validate_query,
        "fields": fields,
        "expand": expand
    }
    if json_result:
        return self._get_json('search', params=search_params)

    resource = self._get_json('search', params=search_params)
    issues = [Issue(self._options, self._session, raw_issue_json)
              for raw_issue_json in resource['issues']]
    cnt = len(issues)
    total = resource['total']
    if infinite:
        while cnt == maxi:
            idx += maxi
            search_params["startAt"] = idx
            resource = self._get_json('search', params=search_params)
            issue_batch = [Issue(self._options, self._session, raw_issue_json) for raw_issue_json in
                           resource['issues']]
            issues.extend(issue_batch)
            cnt = len(issue_batch)
    return ResultList(issues, total)

rawDescription: Possibility to read out search filters using jira-python


code:
if libitem.startswith('__MACOSX/'):
  continue

rawDescription: Unzipping a Zip File in Django

description: Unzipping a Zip File in Django


code:
df
df.pivot(index="Customer", columns="Product", values="Quantity")

rawDescription: Python Pandas Indexing Reform

description: Python Pandas Indexing Reform


code:
from selenium import webdriver

fp = webdriver.FirefoxProfile()

fp.set_preference("browser.download.folderList",2)
fp.set_preference("javascript.enabled", False)

browser = webdriver.Firefox(firefox_profile=fp)

rawDescription: How can I disable javascript in firefox with selenium?

description: Disable javascript in firefox with selenium


code:
r = requests.post(conf.email_api_gateway,
                auth=('api',     conf.email_api_key),
                data={'to':      self.email_add,
                      'from':    self.get_email_from(),
                      'subject': self.get_email_subject(),
                      'html':    self.get_email_html(),
                      'text':    self.get_email_text() })

## manually set UTF-8 so we can json the response
r.encoding = 'UTF-8'

if r.status_code == 200:
    mail_id = r.json[u"id"]

rawDescription: urllib2 HTTPPasswordMgrWithDefaultRealm 'loses' password after 5 requests

description: Urllib2 HTTPPasswordMgrWithDefaultRealm 'loses' password after 5 requests


code:
fig = pylab.figure()
ax = fig.add_subplot(111)
ax.plot(freqs,modfreqp,color='black')
ax.plot(freqs1,modfreqp1,color='blue')
ax.plot(freqs2,modfreqp2,color='red')
show()

rawDescription: Can't get 3 plots to overlay in pylab

description: Can't get 3 plots to overlay in pylab


rawDescription: How to extract certain value from collection of text files

description: Extract certain value from collection of text files


code:
from difflib import SequenceMatcher
text1 = open(file1).read()
text2 = open(file2).read()
m = SequenceMatcher(None, text1, text2)
m.ratio()

rawDescription: percentage difference between two text files

description: Percentage difference between two text files


code:
with open('input.txt','r') as f:
    data = f.readlines()

with open('output.txt','w') as f:
    for i, line in enumerate(data):
        if '456' in line:
            fields = data[i+3].split(',')
            fields[-1] = 'PIZZA\n'
            data[i+3] = ','.join(fields)
        f.write(line)

rawDescription: Replace word in text file and writing it to a new file in python


code:
shell = subprocess.Popen("/bin/bash -i".split(), stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)

rawDescription: Reusing subprocess object

description: Reusing subprocess object


code:
main_dict = {"Paul":"mister", "Raj": "mister"}

def form_statement(main_dict, subject, verb, object):
    greetings = main_dict.get(subject, '')
    return "{} {} {} {}".format(subject, verb, object, greetings)

rawDescription: More pythonic way for a conditional variable


code:
import collections
d = collections.defaultdict(list)
d['foo'].append(9)
d
d['foo'].append(90)
d
d['bar'].append(5)
d

rawDescription: Python: Storing a list value associated with a key in dictionary


display_name: Django

rawDescription: django-extensions shell_plus --kernel specify connection file

description: Django-extensions shell_plus --kernel specify connection file


code:
name_query = Institution.objects.filter(name__icontains='term')
aliases_query = Institution.objects.filter(aliases__name__icontains='term')
final_query = list(name_query) + list(aliases_query)

rawDescription: Most efficient Django query to get the objects and their related


code:
import cv2
import numpy as np
cam=cv2.VideoCapture(0)
fgbg = cv2.BackgroundSubtractorMOG()
while(cam.isOpened):
   f,img=cam.read()
   if f==True:
       #img=cv2.flip(img,1)
       #img=cv2.medianBlur(img,3)
       fgmask = fgbg.apply(img)
       cv2.imshow('track',fgmask)
   if(cv2.waitKey(27)!=-1):
       cam.release()
       cv2.destroyAllWindows()
       #break

rawDescription: how to do Background Subtraction in opencv (opencv-master) python

description: Do Background Subtraction in opencv (opencv-master) python


code:
my_patch = patch('somelongmodulename.somelongmodulefunction')

@my_patch
def test_a(patched):
    pass

@my_patch
def test_b(patched):
    pass

rawDescription: Apply a single decorator to multiple functions


code:
if any(x in answer for x in array1):
    print("yes")
else:
    print("fail")

rawDescription: Searching an array for key words -python


code:
import random
monday_diary
random.choice(monday_diary)

rawDescription: Splitting dictionary of lists based on criteria in python


code:
import os
os.system('I:/dosefile.exe')

rawDescription: Call a DOS executable file from Python

description: Call a DOS executable file from Python


code:
#!/usr/bin/env python
import curses
import time

def updater():
    fakedata = [[1, 78], [2, 97], [1, 45], [2, 2], [3, 89]]
    codes_to_linenums_dict = {}
    last_line = 0
    win = curses.initscr()
    for code, data in fakedata:
        try:
            # if we haven't seen this code before, give it the next line
            if code not in codes_to_linenums_dict:
                codes_to_linenums_dict[code] = last_line
                last_line += 1
            # use the line we set for this code.
            line = codes_to_linenums_dict[code]
            win.addstr(line, 0, '{}: {}    '.format(code, data))
            win.refresh()
            # For display only
            time.sleep(2)
        except KeyboardInterrupt:
            # if endwin isn't called the terminal becomes unuseable.
            curses.endwin()
            raise
    curses.endwin()

if __name__ == '__main__':
    updater()

rawDescription: Editable data table display in Python

description: Editable data table display in Python


code:
from datetime import datetime, time

now = datetime.now()
beginning_of_day = datetime.combine(now.date(), time(0))
print (now - beginning_of_day).seconds

rawDescription: Counting passed seconds

description: Counting passed seconds


code:
if item in q.queue:
   print("already there!")

rawDescription: How to check if object exists in queue before pushing new object

description: Check if object exists in queue before pushing new object


code: sorted_sum = sorted([sum(products[i]) for i in range(1, 16)])

rawDescription: compare sum of column values in python

description: Compare sum of column values in python


rawDescription: Grouping django objects using QuerySet API by shared text tags using two models with ForeignKey relationship


code:
import wx
import  wx.lib.scrolledpanel as scrolled

class TestFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, size=(1000, 550))
        panel = wx.Panel(self)

        mainSizer = wx.BoxSizer(wx.VERTICAL)
        pbox0 = wx.BoxSizer(wx.VERTICAL)
        controlback0 = wx.Button(panel, label="Back0")
        controlforward0 = wx.Button(panel, label="Forward0")
        pbox0.Add(controlback0, 0, wx.ALL)
        pbox0.Add(controlforward0, 0, wx.ALL)
        mainSizer.Add(pbox0)

        self.scrolling_window = scrolled.ScrolledPanel( panel )
        self.scrolling_window.SetAutoLayout(1)
        self.scrolling_window.SetupScrolling()
        self.sizer = wx.BoxSizer( wx.VERTICAL )
        self.child_windows = []
        for i in range(0,8):
            wind = self.addBox()
            self.sizer.Add(wind, 0, wx.CENTER|wx.ALL, 5)
        self.scrolling_window.SetSizer(self.sizer)

        mainSizer.Add(self.scrolling_window, 1, wx.EXPAND)
        panel.SetSizer(mainSizer)

    def addBox(self):
        pbox = wx.BoxSizer(wx.VERTICAL)

        controlback = wx.Button(self.scrolling_window, label="Back")
        controlforward = wx.Button(self.scrolling_window, label="Forward")

        pbox.AddMany([(controlback, 0, wx.ALL), (controlforward, 0, wx.ALL)])
        return pbox

    def OnSize(self, event):
        self.scrolling_window.SetSize(self.GetClientSize())

if __name__=='__main__':
    app = wx.App(False)
    f = TestFrame()
    f.Show()
    app.MainLoop()

rawDescription: WxPython: Multiple Widgets in a Child Window


code:
def pair(a,b):
    c = ''.join(b.split('_processed'))
    return a == c
lst3 = [[x,y] for x in lst1 for y in lst2 if pair(x,y)]

rawDescription: Any faster ways of searching for items from one list in another?


code:
from module import function

def main():
    my_func = functon
    for i in sequence:
        my_func()

rawDescription: Unexpected performance loss when calling Cython function within Python script?


code:
import random
variable1 = lambda: random.randint(13, 19)
print(variable1())
print(variable1())
print(variable1())

rawDescription: In python, is there anyway to have a variable be a different random number everytime?


code:
from flask.ext.script import Shell
from ptpython.ipython import embed

class PtShell(Shell):
    def run(self, **kwargs):
        context = self.get_context()
        embed(user_ns=context)

manager.add_command("shell", PtShell())

rawDescription: How can I use ptiPython with Flask-Script together?

description: Use ptiPython with Flask-Script together


code:
class Place(models.Model):
    name = models.CharField(unique=True)

    class Meta:
        abstract = True

rawDescription: Django: store common fields in a parent model


code:
input = '''1
2
3

4
5
6'''

def parse(string):
    out = []
    groups = string.split('\n\n') # Split by empty line
    for group in groups:
        out.append([item.strip() for item in group.split('\n')])
    return out

print(parse(input))

rawDescription: Split string with double enter in Python


code:
df
df["C"] = (df.A * df.B).groupby((df.A == 0).cumsum()).cummax()
df

rawDescription: Creating max's of sublist in python pandas dataframe based upon other columns


code: USE_TZ = False

rawDescription: Django / DRF - Changing the timezone does not work


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

data = {'A1_mean': [0.457, 1],
         'A2_median': [0.391,1],
         'A3_range': [0.645,1],
         'A4_std': [0.111,1],
         'B1_mean': [0.132,3],
         'B2_median': [0.10,3],
         'B3_range': [0.244,3],
         'B4_std': [0.297,3],
         'C1_mean': [0.286,2],
         'C2_median': [0.231,2],
         'C3_range': [0.554,2],
         'C4_std': [0.147,2]}
df = pd.DataFrame(data).T
color = {1:'red',2:'green',3:'blue'}
labels = ['A','C','B']
fig, ax = plt.subplots()
df[0].plot(ax=ax, kind='bar', color=df[1].map(color))

handles = []
for i, c in color.items():
    handles.append(mpatches.Patch(color=c, label=labels[i-1]))
plt.legend(handles=handles, loc='best')
# auto-rotate xtick labels
fig.autofmt_xdate()
plt.show()

rawDescription: Plotting legend with correct labels python


code: from django.utils.datastructures import SortedDict

rawDescription: How to iterate a multidimensional dict in a pre-specified order in a django template?

description: Iterate a multidimensional dict in a pre-specified order in a django template


code:
import numpy as np
from scipy.signal import argrelextrema

a = np.array([1,2,3,4,5,4,3,2,1,2,3,2,1,2,3,4,5,6,5,4,3,2,1])

# determine the indices of the local maxima
maxInd = argrelextrema(a, np.greater)

# get the actual values using these indices
r = a[maxInd]  # array([5, 3, 6])

rawDescription: Find local maximums in numpy array

description: Find local maximums in numpy array


code:
# Fast O(n) solution using a dictionary
def solution(lst):
    counts = {}

    for item in lst:
        if item in counts:
            counts[item] += 1
        else:
            counts[item] = 1

    for item in lst:
        if counts[item] == 1:
            return item

    return -1

print(solution([1,2,1,3,2,5])) # prints 3
print(solution([1,2,1,3,3,2,5])) # prints 5
print(solution([1,2,1,3,3,2,5,5])) # prints -1
print(solution([7])) # prints 7

rawDescription: Python: first unique number in a list

description: Python: first unique number in a list


code:
import math
int(math.round((((year2 - year1) * 12) + (month2 - month1)) * 30.4375 + (day2 - day1)))

rawDescription: Procedure for explicit type conversion in python from a float to int


code:
from scipy import optimize
f=lambda x, y: (x**3+y**3+y**2+2*x*y*y-0)**2
y_range=linspace(-1, 1, 100)
x_range=[optimize.fmin(f,0,args=(y,), disp=0) for y in y_range]
xr=linspace(-1,1)
yr=linspace(-1,1)
X, Y=meshgrid(xr, yr)
Z=f(X, Y)
plt.plot(x_range, y_range, 'k')
plt.contourf(xr, yr, Z, levels=linspace(0,0.001,51), alpha=0.5)
plt.colorbar()

rawDescription: how to draw a nonlinear function using matplotlib?

description: Draw a nonlinear function using matplotlib


rawDescription: Matplotlib - two different colormaps with different ranges


code:
import re
s = '\n    \n        Last Updated: Friday, March 14, 2014 \n        ", "\n '
re.search('Updated: ([\w, ]+)', s).group(1).strip()

rawDescription: Pick out part of text field in Python with Scrapy


code:
class Obj1(object):
    def __init__(self):
        self.list_of_obj2 = []

rawDescription: Trouble With Lists of Lists in Python

description: Trouble With Lists of Lists in Python


code:
from sklearn.datasets import fetch_20newsgroups_vectorized
from sklearn.feature_selection import chi2
data = fetch_20newsgroups_vectorized()
X, y = data.data, data.target
scores, pvalues = chi2(X, y)
pvalues

rawDescription: Python sklearn - how to calculate p-values


code:
import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as dates

# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(100)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.plot(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()

ax = plt.gca()
# set date ticks to something sensible:
xax = ax.get_xaxis()
xax.set_major_locator(dates.DayLocator())
xax.set_major_formatter(dates.DateFormatter('%d/%b'))

xax.set_minor_locator(dates.HourLocator(byhour=range(0,24,3)))
xax.set_minor_formatter(dates.DateFormatter('%H'))
xax.set_tick_params(which='major', pad=15)

plt.show()

rawDescription: matplotlib: draw major tick labels under minor labels

description: Matplotlib: draw major tick labels under minor labels


code: self.btn.configure(state = "normal", relief="raised", bg = "red")

rawDescription: Tkinter button changes color after having hovered on it


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

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

# Add some extra space for the second axis at the bottom
fig.subplots_adjust(bottom=0.2)

X = np.linspace(0,1,1000)
Y = np.cos(X*20)

ax1.plot(X,Y)
ax1.set_xlabel(r"Original x-axis: $X$")

new_tick_locations = np.array([.2, .5, .9])

def tick_function(X):
    V = 1/(1+X)
    return ["%.3f" % z for z in V]

# Move twinned axis ticks and label from top to bottom
ax2.xaxis.set_ticks_position("bottom")
ax2.xaxis.set_label_position("bottom")

# Offset the twin axis below the host
ax2.spines["bottom"].set_position(("axes", -0.15))

# Turn on the frame for the twin axis, but then hide all
# but the bottom spine
ax2.set_frame_on(True)
ax2.patch.set_visible(False)
for sp in ax2.spines.itervalues():
    sp.set_visible(False)
ax2.spines["bottom"].set_visible(True)

ax2.set_xticks(new_tick_locations)
ax2.set_xticklabels(tick_function(new_tick_locations))
ax2.set_xlabel(r"Modified x-axis: $1/(1+X)$")
plt.show()

rawDescription: How to add second x-axis at the bottom of the first one in matplotlib.?

description: Add second x-axis at the bottom of the first one in matplotlib.


rawDescription: Select batch of rows sqlalchemy mysql

description: Select batch of rows sqlalchemy mysql


code:
with open(filename) as f:
    H = nx.read_adjlist(f, create_using=nx.DiGraph())

rawDescription: How to read Adjacency list into NetworkX to create a directed graph?

description: Read Adjacency list into NetworkX to create a directed graph


code:
def show(close=None):
    """Show all figures as SVG/PNG payloads sent to the IPython clients.
    Parameters
    ----------
    close : bool, optional
      If true, a ``plt.close('all')`` call is automatically issued after
      sending all the figures. If this is set, the figures will entirely
      removed from the internal list of figures.
    """
    if close is None:
        close = InlineBackend.instance().close_figures
    try:
        for figure_manager in Gcf.get_all_fig_managers():
            display(figure_manager.canvas.figure)
    finally:
        show._to_draw = []
        # only call close('all') if any to close
        # close triggers gc.collect, which can be slow
        if close and Gcf.get_all_fig_managers():
            matplotlib.pyplot.close('all')

rawDescription: Why does savefig and plot commands have to be in the same cell in an IPython notebook?


code:
def get_all_of_field(model, field):
  for x in model.all():
    yield getattr(x, field)

names = get_all_of_field(Contact, 'name')

rawDescription: How to write a query like SQL's SELECT x FROM

description: Write a query like SQL's SELECT x FROM


code:
np.random.seed(2016); arr = np.random.randint(10, size=(2,3)); arr
np.argmax(arr)
np.unravel_index(np.argmax(arr), arr.shape)

rawDescription: Using np.argwhere to find the maximum in a matrix


code:
from collections import defaultdict

d = defaultdict(list)
for m, x in main_dict.items():
    for k, v in x.items():
        d[k].append((m, v))

rawDescription: Assist with dict comprehension

description: Assist with dict comprehension


code:
from werkzeug.contrib.cache import SimpleCache, MemcachedCache

class Cache(object):

    cache = SimpleCache(threshold = 1000, default_timeout = 100)
    # cache = MemcachedCache(servers = ['127.0.0.1:11211'], default_timeout = 100, key_prefix = 'my_prefix_')

    @classmethod
    def get(cls, key = None):
        return cls.cache.get(key)

    @classmethod
    def delete(cls, key = None):
        return cls.cache.delete(key)

    @classmethod
    def set(cls, key = None, value = None, timeout = 0):
        if timeout:
            return cls.cache.set(key, value, timeout = timeout)
        else:
            return cls.cache.set(key, value)

    @classmethod
    def clear(cls):
        return cls.cache.clear()

...

@app.route('/path/<user>/<id>', methods=['POST'])
def post_kv(user, id):
    Cache.set(user, id)
    return "Cached {0}".format(id)

@app.route('/path/<user>', methods=['GET'])
def get_kv(user):
    id = Cache.get(user)
    return "From cache {0}".format(id)

rawDescription: flask: How to store and retrieve POST calls?

description: Flask: How to store and retrieve POST calls


code:
if 'month' in node.attrib:
    if node.attrib['month'] in ['05', '06']:
        return nums

rawDescription: Parse floats and return paths except for certain attribute values


code:
from flask_security.utils import encrypt_password
user.password = encrypt_password('Stack Overflow')

rawDescription: Use Flask-Security to change password in code


code:
inside = np.logical_and(np.logical_and(lons >= west,
                                       lons <= east),
                        np.logical_and(lats >= south,
                                       lats <= north))

rawDescription: Filter data, based on Latitude and Longitudes - Numpy


code:
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from yourapplication import app

http_server = HTTPServer(WSGIContainer(app))
http_server.listen(5000)
IOLoop.instance().start()

rawDescription: How to run Flask app with Tornado

description: Run Flask app with Tornado


code:
from __future__ import division
import pyparsing as pyp
import math
import operator

class NumericStringParser(object):
    '''
    Most of this code comes from the fourFn.py pyparsing example
    http://pyparsing.wikispaces.com/file/view/fourFn.py
    http://pyparsing.wikispaces.com/message/view/home/15549426
    __author__='Paul McGuire'

    All I've done is rewrap Paul McGuire's fourFn.py as a class, so I can use it
    more easily in other places.
    '''
    def pushFirst(self, strg, loc, toks ):
        self.exprStack.append( toks[0] )
    def pushUMinus(self, strg, loc, toks ):
        if toks and toks[0] == '-':
            self.exprStack.append( 'unary -' )
    def __init__(self):
        """
        expop   :: '^'
        multop  :: '*' | '/'
        addop   :: '+' | '-'
        integer :: ['+' | '-'] '0'..'9'+
        atom    :: PI | E | real | fn '(' expr ')' | '(' expr ')'
        factor  :: atom [ expop factor ]*
        term    :: factor [ multop factor ]*
        expr    :: term [ addop term ]*
        """
        point = pyp.Literal( "." )
        e     = pyp.CaselessLiteral( "E" )
        fnumber = pyp.Combine( pyp.Word( "+-"+pyp.nums, pyp.nums ) +
                           pyp.Optional( point + pyp.Optional( pyp.Word( pyp.nums ) ) ) +
                           pyp.Optional( e + pyp.Word( "+-"+pyp.nums, pyp.nums ) ) )
        ident = pyp.Word(pyp.alphas, pyp.alphas+pyp.nums+"_$")
        plus  = pyp.Literal( "+" )
        minus = pyp.Literal( "-" )
        mult  = pyp.Literal( "*" )
        div   = pyp.Literal( "/" )
        lpar  = pyp.Literal( "(" ).suppress()
        rpar  = pyp.Literal( ")" ).suppress()
        addop  = plus | minus
        multop = mult | div
        expop = pyp.Literal( "^" )
        pi    = pyp.CaselessLiteral( "PI" )
        expr = pyp.Forward()
        atom = ((pyp.Optional(pyp.oneOf("- +")) +
                 (pi|e|fnumber|ident+lpar+expr+rpar).setParseAction(self.pushFirst))
                | pyp.Optional(pyp.oneOf("- +")) + pyp.Group(lpar+expr+rpar)
                ).setParseAction(self.pushUMinus)
        # by defining exponentiation as "atom [ ^ factor ]..." instead of
        # "atom [ ^ atom ]...", we get right-to-left exponents, instead of left-to-right
        # that is, 2^3^2 = 2^(3^2), not (2^3)^2.
        factor = pyp.Forward()
        factor << atom + pyp.ZeroOrMore( ( expop + factor ).setParseAction(
            self.pushFirst ) )
        term = factor + pyp.ZeroOrMore( ( multop + factor ).setParseAction(
            self.pushFirst ) )
        expr << term + pyp.ZeroOrMore( ( addop + term ).setParseAction( self.pushFirst ) )
        self.bnf = expr
        # map operator symbols to corresponding arithmetic operations
        epsilon = 1e-12
        self.opn = { "+" : operator.add,
                "-" : operator.sub,
                "*" : operator.mul,
                "/" : operator.truediv,
                "^" : operator.pow }
        self.fn  = { "sin" : math.sin,
                "cos" : math.cos,
                "tan" : math.tan,
                "abs" : abs,
                "trunc" : lambda a: int(a),
                "round" : round,
                "sgn" : lambda a: abs(a)>epsilon and cmp(a, 0) or 0}
        self.exprStack = []
    def evaluateStack(self, s ):
        op = s.pop()
        if op == 'unary -':
            return -self.evaluateStack( s )
        if op in "+-*/^":
            op2 = self.evaluateStack( s )
            op1 = self.evaluateStack( s )
            return self.opn[op]( op1, op2 )
        elif op == "PI":
            return math.pi # 3.1415926535
        elif op == "E":
            return math.e  # 2.718281828
        elif op in self.fn:
            return self.fn[op]( self.evaluateStack( s ) )
        elif op[0].isalpha():
            return 0
        else:
            return float( op )
    def eval(self, num_string, parseAll = True):
        self.exprStack = []
        results = self.bnf.parseString(num_string, parseAll)
        val = self.evaluateStack( self.exprStack[:] )
        return val

nsp = NumericStringParser()
print(nsp.eval('1+2'))
# 3.0

print(nsp.eval('2*3-5'))
# 1.0

rawDescription: Safe way to parse user-supplied mathematical formula in Python


code:
sql = 'select * from tablename where ' + ' and '.join(k + ' = %s' for k in data)
cursor.execute(sql, tuple(data.values()))

rawDescription: How do I use prepared statements for "select from xxx where xxx" using python

description: Use prepared statements for "select from xxx where xxx" using python


code:
import os

path = "/home/b2blogin/webapps/mongodb/rawdata/segment_slideproof_testing"
processed_files_file = os.path.join(path,"processed_files.txt")
processed_files = set(line.strip() for line in open(processed_files_file))

with open(processed_files_file, "a") as pff:
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith(".gz"):
                if file not in processed_files:
                    pff.write("%s\n" % file)

rawDescription: How to process only new (unprocessed) files in linux

description: Process only new (unprocessed) files in linux


rawDescription: Simple Window using TkInter

description: Simple Window using TkInter


code:
import webbrowser
url = "https://www.google.com.tr/search?q={}".format("Raspberry Pi")
b = webbrowser.get('lynx')
b.open(url)

rawDescription: Script for opening up a Google search in a specific browser


code:
an = gca().annotate('TEST', xy=(.1, .1), xytext=(.1 + 15,.1), arrowprops=dict(facecolor='#404040'))
gca().set_xlim([0, 30])
draw()
plt.pause(5)
an.set_visible(False)
draw()
plt.pause(5)
an.set_visible(True)
draw()

rawDescription: Remove and Re-Add Object in matplotlib | Toggle Object appearance matplotlib


code: df.replace(r'[\s\-,\.]+', r'', regex=True, inplace=True)

rawDescription: Remove unwanted parts from strings in a range of columns


code: sys.stdin = open("/dev/stdin")

rawDescription: Hide stdin data from user running script?


code:
# Set up stimuli
from psychopy import visual
win = visual.Window(units='norm')
stim = visual.ElementArrayStim(win, sizes=0.05)

BORDER_RIGHT = 1  # for 'norm' units, this is the coordinate of the right border

# Animation
for frame in range(360):
    # Determine location of elements on next frame
    stim.xys += (0.01, 0)  # move all to the right
    exceeded = stim.xys[:,0] > BORDER_RIGHT  # index of elements whose x-value exceeds the border
    stim.xys[exceeded] *= (-1, 1)  # for these indicies, mirror the x-coordinate but keep the y-coordinate

    # Show it
    stim.draw()
    win.flip()

rawDescription: How to create a continuous visual.Window background/wrapping of background?

description: Create a continuous visual.Window background/wrapping of background


code:
pivot = initiatTdElement
for i in range(22):
    pivot = pivot.nextSibling

#at this point you've done calling `nextSibling` 22x
#and store the result in pivot variable

rawDescription: is there a way to use multiple of identical attributes like nextSibling?

description: Is there a way to use multiple of identical attributes like nextSibling


code:
nextD = []
def next_move(posr, posc, board):
    global nextD

    if nextD == []:
        nextD = next_d(posr,posc,board)

    if (nextD[0] == posr) and (nextD[1] == posc):
        print("CLEAN")
        board[posr][posc] = "-"
        nextD = []
    elif posc < nextD[1]:
        print("RIGHT")
    elif posc > nextD[1]:
        print("LEFT")
    elif posr < nextD[0]:
        print("DOWN")
    elif posr > nextD[0]:
        print("UP")

#find closest d
def next_d(posr, posc, board):
    val = len(board) * 2
    nextD = []
    for i in range(len(board)):
        for j in range(len(board[i])):
            if board[i][j] == 'd' and abs(i - posr) + abs(j - posc) < val:
                val = abs(i - posr) + abs(j - posc)
                nextD = [i, j]

    return nextD

# Tail starts here
if __name__ == "__main__":
    pos = [int(i) for i in input().strip().split()]
    board = [[j for j in input().strip()] for i in range(5)]
    next_move(pos[0], pos[1], board)

rawDescription: Optimizing a robot vacuum's path

description: Optimizing a robot vacuum's path


code:
data = dict(a=1,b=2,c=3,d=4)
from argparse import Namespace
v = Namespace(**data)
v.a
v.d

rawDescription: Python: include entries of a dictionary in the local namespace of a function


code:
import schedule
import time

def job():
    print("I'm working on job one...")

def job2():
    print("I'm working on job two..")

schedule.every().day.at("10:30").do(job)
schedule.every().day.at("10:35").do(job2)

while True:
    schedule.run_pending()
    time.sleep(1)

rawDescription: rSimple python schedule two timed events

description: RSimple python schedule two timed events


code:
import os
import psutil
current_process = psutil.Process(os.getpid())
mem = current_process.memory_percent()
for child in current_process.children(recursive=True):
    mem += child.memory_percent()

rawDescription: Find total memory used by Python process and all its children


code:
lines = lines.split('\n')
for i, line in enumerate(lines):
    line = line.strip().lstrip()
    if line.startswith('...') and i != 0:
        lines[i - 1] = lines[i - 1].strip().lstrip() + line.replace('...', '')
        del lines[i]

rawDescription: How to join continue line seperated with ellipses (...) in python

description: Join continue line seperated with ellipses (...) in python


rawDescription: set column of pandas.DataFrame object

description: Set column of pandas.DataFrame object


rawDescription: Python: Remove duplicates and indicate index


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

N = 9

x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x,y)
plt.show()

rawDescription: Python: displaying random dots in coordinate system


code:
from itertools import chain

main_query = Resource.objects.all().annotate(rating=Avg('resourcerating__rating'),rate_count=Count('resourcerating'))

data_top_query = main_query.exclude(rate_count__lt=settings.ORB_RESOURCE_MIN_RATINGS).order_by(order_by)
data_bottom_query = main_query.exclude(rate_count__gte=settings.ORB_RESOURCE_MIN_RATINGS).order_by(order_by)

data = list(chain(data_top_query, data_bottom_query))

rawDescription: Ordering objects by rating accounting for the number or ratings


rawDescription: How to split a string (using regex?) depending on digit/ not digit

description: Split a string (using regex?) depending on digit/ not digit


code:
f = Foo()
type(f.__class__.__dict__['bari'])
type(f.__class__.__dict__['barc'])
type(f.__class__.__dict__['bars'])

rawDescription: How to distinguish an instance method, a class method, a static method or a function in Python 3?

description: Distinguish an instance method, a class method, a static method or a function in Python 3


code: df

rawDescription: Pandas - Python 2.7: How convert timeseries index to seconds of the day?


code:
db_cursor.execute("""SELECT player.player_id, player.player_name,
                       COUNT(match.winner_id)::int as wins, COUNT(match.loser_id + match.winner_id)::int as total_matches
                       FROM player LEFT JOIN match ON player.player_id = match.winner_id
                       GROUP BY player.player_id
                       ORDER BY wins ASC""")

rawDescription: psycopg2 PSQL SELECT statement returning 0L instead of 0

description: Psycopg2 PSQL SELECT statement returning 0L instead of 0


code:
c = collections.Counter(item for sublist in data for item in sublist)
c
c.most_common(1)[0]

rawDescription: Python: return value with higher percentage of appearance in nested list


code:
with open('Path/to/file', 'r') as content_file:
    content = content_file.read()
    print(content.count("Methadone"))

rawDescription: Counting the occurence of a specific string in a csv file


code:
buttons = {}
for x in range(gridx):
    buttons[x] = GridBtn(self,x,y,btn_id)

rawDescription: How can I have increasing named variables?

description: Have increasing named variables


code:
##############################################################
# Searches for the "endorse skills" buttons and iteratively clicks them...
##############################################################

list_of_skills = browser.find_by_id("profile-skills")[0].find_by_css("li")

for skill in list_of_skills:

    if skill.has_class("endorse-item has-endorsements endorsable"):

        # ...this skill can be endorsed

        button_and_other = skill.find_by_css("div")[0].find_by_css("a") # there are two elements that match "a": [0] list of endorsers, [1] the endorse button

        for css in button_and_other:

            if css.has_class("endorse-button"): # ..if the element has the class: "endorse-button" we click it

                css.click()
    else:

        # ...this skill is already endorsed

        pass

rawDescription: In python: splinter, how can I .click() on un-endorsed linkedin skills?


code:
class MyTextBox(TextInput):

    def insert_text(self, substring, from_undo=False):

        line_length = 50

        # Remove all whitespace in string.
        seq = ''.join(substring.split())

        # For every line_length characters, insert a newline character.
        if len(seq) > line_length:

            # Splits seq by every Nth character and creates a list.
            # Example: [abc,def,ghi]
            # Then join the list items together using a newline character
            # as the separator.
            seq = '\n'.join([seq[i:i+line_length] for i in range(0, len(seq), line_length)])

        return super(MyTextBox, self).insert_text(seq, from_undo=from_undo)

rawDescription: Kivy Textinput Wrap

description: Kivy Textinput Wrap


code:
class Recipe(object):

    def __init__(self, buildout, name, options):
        self.buildout, self.name, self.options = buildout, name, options
        directory = buildout['buildout']['directory']
        download_cache = buildout['buildout'].get('download-cache')

rawDescription: Python & buildout : get path to the egg in the recipe API


code:
tuple = ('one', 'two', 'one', 'two', 'one')
['<strong>%s</strong>' % tuple[i] if i%2 else tuple[i] for i in range(len(tuple))]

rawDescription: Easily Alternate Delimiters in a Join

description: Easily Alternate Delimiters in a Join


code:
from bisect import bisect

def find_closest(v, options):
   i = bisect(options, v)
   if i == len(options):
       return options[-1]
   elif i == 0:
       return options[0]
   else:
       low, high = options[i-1:i+1]
       return low if (high-v) > (v-low) else high

standard_values = [100, 150, 275, 340, 420, 550]
answer = 176
print(find_closest(answer, standard_values))

rawDescription: Python 3 - Electronics Analysis Script

description: Python 3 - Electronics Analysis Script


code: textContent = findMatch.sub(answers[i], textContent, count=1)

rawDescription: Building a mad libs program in Python using regular expressions


code:
import sys

A = "Random sentence"
for x in A:
    time.sleep(random.randint(1,4))
    print(x, end='')
    sys.stdout.flush()

rawDescription: How to make it look like the computer is typing?

description: Make it look like the computer is typing


code:
human = 'ACCGTGAAAAACGTGAGTATA'
mouse = 'ACCAAAAGTGTAT'
import re
def format_dna(s):
    return re.sub(r'(.{5})(?!$)', r'\g<1>\n', s)
print(format_dna(human))
print(format_dna(mouse))

rawDescription: Splitting string into groups of "x" length


code:
from itertools import groupby

d = {
    k: sum(item[1] for item in g)
    for k, g in groupby(sorted(codes.items()), key=lambda item: item[0][:2])
}

d
{'11': 8, '32': 1, '31': 1, '21': 4, '23': 7}

rawDescription: Sum Values by Key First X Characters (Python)


code:
cell = {
    "cell_type": "markdown",
    "metadata": {'collapsed': False, 'name': 'test'},
    "source": [
        "## Header line\n\n",
        "Second line, not a header...hopefully"
    ],
}

rawDescription: Include carriage return correctly in iPython notebooks when writing using json.dump


code:
from itertools import islice

def number_difference(iterable):
    return float(iterable[-1].strip('\n')) - float(iterable[0].strip('\n'))

def file_crop(big_fname, chunk_fname, no_lines):
    with open(big_fname, 'r') as big_file:
        ifile = 0
        while True:
            data = list(islice(big_file, no_lines))
            if not data:
                break
            with open('{}_{}.txt'.format(chunk_fname, ifile), 'w') as small_file:
                small_file.write('{} {} Sam\n'.format(len(data), number_difference(data)))
                small_file.write(''.join(data))
            ifile += 1

rawDescription: Need help cropping a large text file to multiple small text files with a header


code:
values = []
for row in woof_1.findAll("tr", { "class" : "row_b" }):
  for col in row.findAll(re.compile('td')):
    if col.string:
      values.append(col.string)
result = ''.join(values)

rawDescription: How to I make the result of this a variable?

description: I make the result of this a variable


code:
from tkinter import *
import random
import time

#==================================================================================================
root=Tk()
#==================================================================================================

class GridGame(Toplevel):
    def __init__(self,master):
        self.fr=Toplevel(master)
        self.TotalFrame=Frame(self.fr,bg="black")
        self.ButtonColor="red"
        self.GameFrame=Frame(self.TotalFrame,bg="white")
        self.AllButtons=[]
        self.MineGrid=[]
        self.SizeGrid=17
        self.Mines=50
        self.MarkedMineColour="blue"
        self.Counter="Start"
        for x in range(self.SizeGrid):
            Column=[]
            MineColumn=[]
            for y in range(self.SizeGrid):
                item=Button(self.GameFrame,bg=self.ButtonColor,text="",height=2, width=6)
                item.bind("<Button-3>",self.ChoiceChange)
                Column.append(item)
                MineColumn.append("")
            self.AllButtons.append(Column)
            self.MineGrid.append(MineColumn)
        self.GameFrame.grid(row=0,column=0,pady=15,padx=20,columnspan=2)
        self.Quit=Button(self.TotalFrame, text="Destroy This Game", bg="orange",command=self.fr.destroy)
        self.Restart=Button(self.TotalFrame, text="Reset This Game", bg="light blue",command=self.Reset)
        self.Quit.grid(row=1,column=0,pady=5,padx=10)
        self.Restart.grid(row=1,column=1,pady=5,padx=10)
        self.TotalFrame.pack()

        for x in range(self.SizeGrid):
            for y in range(self.SizeGrid):
                    self.AllButtons[x][y].configure(command=lambda a=self.AllButtons[x][y],c=x,d=y:self.ColorFlip(a,c,d))
                    self.AllButtons[x][y].grid(row=x,column=y,padx=5,pady=5)
##        w = self.fr.winfo_screenwidth()
##        h = self.fr.winfo_screenheight()
        self.fr.geometry('%dx%d+%d+%d' % (1100, 950, 300, 10))
#==================================================================================================
    def MineGridMaker(self,a="a",b="a"):
        for x in range(0,self.Mines):
            CarryOn=False
            while CarryOn==False:
                choice1,choice2=random.choice(range(0,len(self.AllButtons))),random.choice(range(0,len(self.AllButtons)))
                if self.MineGrid[choice1][choice2]=="":
                    if a!=choice1 or b!=choice2:
                        self.MineGrid[choice1][choice2]="M"
                        CarryOn=True

        for x in range(0,len(self.AllButtons)):
            for y in range(0,len(self.AllButtons)):
                if self.MineGrid[x][y]=="M":
                    for xx in range(x-1,x+2):
                        for yy in range(y-1,y+2):
                            if xx in range(0,self.SizeGrid) and yy in range(0,self.SizeGrid):
                                if self.MineGrid[xx][yy]!="M" and self.MineGrid[xx][yy]=="":
                                    self.MineGrid[xx][yy]="1"
                                elif self.MineGrid[xx][yy]!="M" and int(self.MineGrid[xx][yy])>=1:
                                    self.MineGrid[xx][yy]=str(int(self.MineGrid[xx][yy])+1)
#==================================================================================================
    def ColorFlip(self,Object,x,y):
        if self.Counter=="Start":
            self.Counter=(self.SizeGrid**2)-self.Mines
            self.MineGridMaker(x,y)
        if Object["bg"]==self.ButtonColor:
            if self.MineGrid[x][y]=="M":
                for Item in range(0,len(self.AllButtons)):
                    for item in range(0,len(self.AllButtons)):
                        self.AllButtons[Item][item].configure(bg="grey",text=self.MineGrid[Item][item])
                Object.configure(bg="red",text=self.MineGrid[x][y])
                for a in range(x-1,x+2):
                    for b in range(y-1,y+2):
                        if a in range(0,self.SizeGrid) and b in range(0,self.SizeGrid):
                            root.after(200,self.BlowUp,a,b)
            else:
                self.Counter-=1
                if self.MineGrid[x][y]=="":
                    for a in range(x-1,x+2):
                        for b in range(y-1,y+2):
                            if a in range(0,self.SizeGrid) and b in range(0,self.SizeGrid):
                                if self.AllButtons[a][b]["bg"]==self.ButtonColor:
                                    Object.configure(bg="white",text=self.MineGrid[x][y])
                                    self.ColorFlip(self.AllButtons[a][b],a,b)
                else:
                    Object.configure(bg="white",text=self.MineGrid[x][y])
        if self.Counter<=0:
            for a in range(0,(self.SizeGrid)):
                for b in range(0,(self.SizeGrid)):
                    if self.MineGrid[a][b]=="M":
                        self.AllButtons[a][b].configure(text=self.MineGrid[a][b],bg="orange")
                    else:
                        self.AllButtons[a][b].configure(bg="light green")
#==================================================================================================
    def BlowUp(self,x,y):
        for a in range(1,21):
            root.after((75*a)-25,self.Flash1,x,y)
            root.after(75*a,self.Flash2,x,y)
        root.after(1800,self.Fade,x,y)

    def Flash1(self,x,y):
        try:
            if self.AllButtons[x][y]["bg"]!=self.ButtonColor:
                self.AllButtons[x][y].configure(bg="orange")
        except:
            pass

    def Flash2(self,x,y):
        try:
            if self.AllButtons[x][y]["bg"]!=self.ButtonColor:
                self.AllButtons[x][y].configure(bg="yellow")
        except:
            pass

    def Fade(self,x,y):
        try:
            if self.AllButtons[x][y]["bg"]!=self.ButtonColor or self.AllButtons[x][y]["text"]!="":
                self.AllButtons[x][y].configure(bg="white")
        except:
            pass

    def Reset(self):
        for x in self.AllButtons:
            for y in x:
                y.configure(bg=self.ButtonColor,text="")
        self.Counter=(self.SizeGrid**2)-self.Mines

    def ChoiceChange(self,event):
        if event.widget["bg"]==self.ButtonColor:
            event.widget["bg"]=self.MarkedMineColour
        elif event.widget["bg"]==self.MarkedMineColour:
            event.widget["bg"]=self.ButtonColor

rawDescription: How to avoid a mine being hit first in a tkinter version of minesweeper?

description: Avoid a mine being hit first in a tkinter version of minesweeper


code: mr.execute(inputdata, mapper, reducer)

rawDescription: Understanding flow of execution of Python code


code:
def filter_nested_dict(node, search_term):
    if isinstance(node, list):
        if node[0] == search_term:
            return node
        else:
            return None
    else:
        dupe_node = {}
        for key, val in node.iteritems():
            cur_node = filter_nested_dict(val, search_term)
            if cur_node:
                dupe_node[key] = cur_node
        return dupe_node or None

rawDescription: Python: How can I filter a n-nested dict of dicts by leaf value?


code:
for src in universe:
   for dst in universe:
      if src == dst:
         continue
      ...

rawDescription: Ugly combination of generator expression with for loop


code:
import subprocess
subprocess.call(['Rscript.exe', 'script.r', 'filename'])

rawDescription: Simple way to pass directory to r script using python


code:
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Favorite(models.Model):
    user = models.ForeignKey(User)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

rawDescription: Beginner: Trying to understand how apps interact in Django


code:
import win32com.client as win32
import os

excel = win32.gencache.EnsureDispatch('Excel.Application')

src_filename = r"c:\my_folder\my_file.csv"
name, ext = os.path.splitext(src_filename)
target_filename = name + '.xls'

wb = excel.Workbooks.Open(src_filename)
excel.DisplayAlerts = False
wb.DoNotPromptForConvert = True
wb.CheckCompatibility = False
wb.SaveAs(target_filename, FileFormat=56, ConflictResolution=2)

excel.Application.Quit()

rawDescription: Tablib export corrupting files

description: Tablib export corrupting files


code:
start_indx = stop1.searchsorted(start2, "left")
end_indx = start1.searchsorted(stop2, "right")
result = [data1[start_indx[i]:end_indx[i]]for i in range(len(start_indx))]

rawDescription: Speed up array interval comparison using NumPy


code:
re.findall("'(?P<content>.*?)'","'
something, \n something else
'", re.DOTALL)

rawDescription: Regular expression: how to match a string containing "\n" (newline)?


code:
import functools
import os

class cd:
    def __init__(self, path):
        self.path = path
    def __enter__(self):
        self.old = os.getcwd()
        os.chdir(self.path)
        return self
    def __exit__(self, exc_type, exc_value, tb):
        os.chdir(self.old)
    def __call__(self, func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            with self:
                return func(*args, **kwargs)
        return wrapper

rawDescription: What is the most Pythonic way to change dir with a function that is both decorator and context manager?


code:
import numpy as np
from scipy import stats
data = np.array([[1, 4, 3], [2, .6, 1.2], [2, 1, 1.2],
         [2, 0.5, 1.4], [5, .5, 0], [0, 0, 0],
         [1, 4, 3], [5, .5, 0], [2, .5, 1.2]])

data = data.T #The KDE takes N vectors of length K for K data points
              #rather than K vectors of length N

kde = stats.gaussian_kde(data)

# You now have your kde!!  Interpreting it / visualising it can be difficult with 3D data
# You might like to try 2D data first - then you can plot the resulting estimated pdf
# as the height in the third dimension, making visualisation easier.

# Here is the basic way to evaluate the estimated pdf on a regular n-dimensional mesh
# Create a regular N-dimensional grid with (arbitrary) 20 points in each dimension
minima = data.T.min(axis=0)
maxima = data.T.max(axis=0)
space = [np.linspace(mini,maxi,20) for mini, maxi in zip(minima,maxima)]
grid = np.meshgrid(*space)

#Turn the grid into N-dimensional coordinates for each point
#Note - coords will get very large as N increases...
coords = np.vstack(map(np.ravel, grid))

#Evaluate the KD estimated pdf at each coordinate
density = kde(coords)

#Do what you like with the density values here..
#plot them, output them, use them elsewhere...

rawDescription: How to implement Kernel density estimation in multivariate/3D

description: Implement Kernel density estimation in multivariate/3D


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

# input
xv = np.array([1, 3, 5])
yv = np.array([0.1, 0.4, 0.5, 0.7])
x,y = np.meshgrid(xv,yv)
M = np.random.rand(4,3)

xqv = np.arange(1,6)
yqv = np.arange(0.1,1.1,0.1)
xq,yq = np.meshgrid(xqv,yqv)
zqfun = interp.interp2d(x,y,M)
zq = zqfun(xqv,yqv)

plt.figure()
#h = plt.pcolor(xq,yq,zq)
h = plt.pcolormesh(xq,yq,zq)   # <-- same thing but faster

rawDescription: Python: is it possible to interpolate a matrix in a MATLAB style?


code:
class Terminal(Vte.Terminal):
    """Defines a simple terminal"""
    def __init__(self, CONF):
        super(Vte.Terminal, self).__init__()

        self.pty = self.pty_new_sync(Vte.PtyFlags.DEFAULT, None)
        self.set_pty(self.pty)
        self.connect("key_press_event", self.copy_or_paste)

        self.set_scrollback_lines(-1)
        self.set_audible_bell(0)

    def copy_or_paste(self, widget, event):
        """Decides if the Ctrl+Shift is pressed, in which case returns True.
        If Ctrl+Shift+C or Ctrl+Shift+V are pressed, copies or pastes,
        acordingly. Return necesary so it doesn't perform other action,
        like killing the process, on Ctrl+C.
        """

        control_key = Gdk.ModifierType.CONTROL_MASK
        shift_key = Gdk.ModifierType.SHIFT_MASK
        if event.type == Gdk.EventType.KEY_PRESS:
            if event.state == shift_key | control_key: #both shift  and control
                if event.keyval == 67: # that's the C key
                    self.copy_clipboard()
                elif event.keyval == 86: # and that's the V key
                    self.paste_clipboard()
                return True

rawDescription: GTK+: Add custom accelerator to VTE

description: GTK+: Add custom accelerator to VTE


code:
def kbin(l, k, ordered=True):
    """
    Return sequence ``l`` partitioned into ``k`` bins.

    Examples
    ========

    The default is to give the items in the same order, but grouped
    into k partitions:

    >>> for p in kbin(range(5), 2):
    ...     print p
    ...
    [[0], [1, 2, 3, 4]]
    [[0, 1], [2, 3, 4]]
    [[0, 1, 2], [3, 4]]
    [[0, 1, 2, 3], [4]]

    Setting ``ordered`` to None means that the order of the elements in
    the bins is irrelevant and the order of the bins is irrelevant. Though
    they are returned in a canonical order as lists of lists, all lists
    can be thought of as sets.

    >>> for p in kbin(range(3), 2, ordered=None):
    ...     print p
    ...
    [[0, 1], [2]]
    [[0], [1, 2]]
    [[0, 2], [1]]

    """
    from sympy.utilities.iterables import (
        permutations, multiset_partitions, partitions)

    def partition(lista, bins):
        #  EnricoGiampieri's partition generator from
        #  http://stackoverflow.com/questions/13131491/
        #  partition-n-items-into-k-bins-in-python-lazily
        if len(lista) == 1 or bins == 1:
            yield [lista]
        elif len(lista) > 1 and bins > 1:
            for i in range(1, len(lista)):
                for part in partition(lista[i:], bins - 1):
                    if len([lista[:i]] + part) == bins:
                        yield [lista[:i]] + part
    if ordered:
        for p in partition(l, k):
            yield p
    else:
        for p in multiset_partitions(l, k):
            yield p

rawDescription: Partition N items into K bins in Python lazily


code:
with open(file1) as fsock1, open(file2, 'a') as fsock2:
    fstring1 = fsock1.read()
    fstring2 = fsock2.read()

rawDescription: Nesting 'WITH' statements in Python

description: Nesting 'WITH' statements in Python


code:
article['title'] = response.css("p.title ::text").extract() + \
                   response.css("span.newstitle ::text").extract()

rawDescription: Using multiple CSS selectors for the same ArticleItem in Scrapy


code:
import codecs

def opener(filename):
    try:
        f = codecs.open(filename, encoding='utf-8')
    except UnicodeError:
        f = open(filename)
    return f

rawDescription: Python Check for unicode files

description: Python Check for unicode files


code:
with open(off_path_name) as shadowed_module_file:
  shadow_getpass = imp.load_module(
      'shadowed.getpass',    # the name reported by the module, rather arbitrary
      shadowed_module_file,  # where we are reading it from
      '', # we don't plan to reload this module normally, no suffix
      ('', 'r', imp.PY_COMPILED) # Assuming it's getpass.pyc, use PY_COMPILED
  )

rawDescription: Import shadowed module into shadowing module which is in sys.path


code:
melted = reshape.melt(df, id_vars=['DateTime', 'ColumnName'])
melted.set_index(['DateTime', 'ColumnName', 'variable']).value.unstack([1, 2])

rawDescription: Reshape Long Format Multivalue Dataframes with Pandas


code:
#!/usr/bin/python2
temp_stage = tempfile.NamedTemporaryFile(delete = True)
temp_prod = tempfile.NamedTemporaryFile(delete = True)
temp_stage.write(stage_notes)
temp_prod.write(prod_notes)

temp_stage.flush()
temp_prod.flush()

subprocess.Popen(["diff", temp_stage.name, temp_prod.name])

rawDescription: Need to run a diff command on 2 NamedTemporaryFiles using subprocess module


code:
class CatZoo(object):
    def __init__(self, name, age, gender, location):
        self._names = name
        self._ages = age
        self._genders = gender
        self._location = location

    @classmethod
    def make_zoo_cat(cls, name, ages, genders, location):
        return cls.mak_zoo_cats([name], age, gender, location)

    @classmethod
    def make_zoo_cats(cls, names, ages, genders, location):
        return CatZoo(names, age, gender, location)

    @property
    def location(self):
        return self._location

    @property
    def names(self):
        return self._names

    def age(self, name):
        if name in self._names:
            return self._ages[self._names.index(name)]
        else:
            return None

    def gender(self, name):
        if name in self._names:
            return self._genders[self._names.index(name)]
        else:
            return None

    @property
    def meow(self):
        return "meow!"

rawDescription: create python factory method

description: Create python factory method


code:
import sys
sys.path.insert(0, u'/…/…/…/python2.7/site-packages')

rawDescription: ImportError: No module named serial in windows 7 python 2.7 and python 3.3


code:
for mod in net.modules:
    print("Module:", mod.name)
    if mod.paramdim > 0:
        print("--parameters:", mod.params)
    for conn in net.connections[mod]:
        print("-connection to", conn.outmod.name)
        if conn.paramdim > 0:
             print("- parameters", conn.params)
    if hasattr(net, "recurrentConns"):
        print("Recurrent connections")
        for conn in net.recurrentConns:
            print("-", conn.inmod.name, " to", conn.outmod.name)
            if conn.paramdim > 0:
                print("- parameters", conn.params)

rawDescription: pybrain: how to print a network (nodes and weights)

description: Pybrain: how to print a network (nodes and weights)


code:
import numpy as np
from itertools import groupby
np.array([list(g) for k,g in groupby(a, lambda i: i // 10)])

rawDescription: Separating list of years into decades

description: Separating list of years into decades


code:
dc = DesiredCapabilities.CHROME
dc['loggingPrefs'] = {'browser': 'ALL'}

chrome_profile = webdriver.ChromeOptions()
profile = {"download.default_directory": "C:\\SeleniumTests\\PDF",
           "download.prompt_for_download": False,
           "download.directory_upgrade": True,
           "plugins.plugins_disabled": ["Chrome PDF Viewer"]}
chrome_profile.add_experimental_option("prefs", profile)

#Helpful command line switches
# http://peter.sh/experiments/chromium-command-line-switches/
chrome_profile.add_argument("--disable-extensions")

self.driver = webdriver.Chrome(executable_path="C:\\SeleniumTests\\chromedriver.exe",
                               chrome_options=chrome_profile,
                               service_args=["--log-path=C:\\SeleniumTests\\chromedriver.log"],
                               desired_capabilities=dc)

rawDescription: Chromedriver, Selenium - Automate downloads


code:
from datetime import datetime

def getdate(text):
    formats = ('%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d', '%b%d/%Y')
    for format in formats:
        try:
            return datetime.strptime(text, format)
        except:
            pass

rawDescription: Elegant way of parsing dates in python

description: Elegant way of parsing dates in python


code:
print(path1.resolve() == path2.resolve())
# True

import os
print(os.path.samefile(str(path1), str(path2)))
# True

rawDescription: In Python 3.4, what is best/easiest way to compare paths?


rawDescription: How to parse a formatted string using Python(re)

description: Parse a formatted string using Python(re)


code:
class IndexList(collections.MutableSequence):
    def __init__(self, int_list):
        self._list = []
        for el in int_list:
            self.append(Index(el))

    def __len__(self): return len(self._list)
    def __getitem__(self, item): return self._list[item]
    def __delitem__(self, item): del self._list[item]

    def __setitem__(self, index, value):
        self._list.key[index] = Index(value)

    def insert(self, index, value):
        self._list.insert(index, Index(value))

rawDescription: single class python list

description: Single class python list


code:
A.argsort()
idx=np.array([5, 2, 3, 9])
indices = A.argsort()[:,::-1]

idx[indices]

rawDescription: Sort rows of numpy matrix efficiently

description: Sort rows of numpy matrix efficiently


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

x = np.random.rand(50)
y = np.random.rand(50)

c = np.array([1, 1, 0])  # base color, set for each point (here, yellow)
z = x/max(x)   # the darkness for each point (here, scale along x-axis)

plt.scatter(x,y, s=300, c=c[np.newaxis,:]*z[:, np.newaxis], marker=">")
plt.show()

rawDescription: How to plot points in different color?

description: Plot points in different color


code:
import urllib
urllib.urlretrieve(url, destination_path) # First and short way

with open(destination_path, 'wb') as f:   # Equivalent to the first, but longer
    f.write(urllib.urlopen(url).read())

rawDescription: Python download file without external library


code:
class ExampleAdmin(admin.ModelAdmin):
    def queryset(self, request):
        qs = super(ExampleAdmin, self).queryset(request)
        return qs.exclude(status='Resolved')

rawDescription: Django Admin - Don't show results where a status tables shows "resolved"


code:
machines = [object() for i in range(TOTAL_MACHINES)]
working, spares = machines[:TOTAL_WORKING], machines[TOTAL_WORKING:]
spares_inventory = Store(env, capacity=TOTAL_MACHINES)
spares_inventory.items = spares
working = [Working(env, i, machine) for i, machine in enumerate(working)]

rawDescription: Need help for SimPy Simulation on Availability


code:
def any_even(foo):
    for i in foo:
        if i % 2 == 0:
            return True
    return False

rawDescription: Input with tuple and choosing odd or even


code:
return pd.DataFrame([{'address_ property': place.cssselect("li a")[0].text,
                      'house_type': place.cssselect("li")[1].text,
                      'house_sell_price': place.cssselect("li")[2].text,
                      'house_sell_date': place.cssselect("li")[3].text}
                          for place in address],
                    index=address)

rawDescription: How can I use Pandas column to parse textfrom the web?

description: Use Pandas column to parse textfrom the web


code:
class MyClass(object):
    def __init__(self):
        self._means = np.zeros(5)

    @property
    def means(self):
        return self._means  # Note the underscore

    @means.setter
    def means(self, value):
        # Convert to np array before setting
        self._means = np.array(value)

rawDescription: implementing python set logic (as in get and set)

description: Implementing python set logic (as in get and set)


code: hint = random.choice(list({a, b, c, d, e, f} - {killer, previous_guess}))

rawDescription: Giving Exceptions to a Random Choice

description: Giving Exceptions to a Random Choice


code:
import wx
import textwrap

class MultilineRadioButton(wx.RadioButton):
        def __init__(self, parent, id=-1, label=wx.EmptyString, wrap=10, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, validator=wx.DefaultValidator, name=wx.RadioButtonNameStr):
            wx.RadioButton.__init__(self,parent,id,'',pos,size,style,validator,name)
            self._label = label
            self._wrap = wrap
            lines = self._label.split('\n')
            self._wrappedLabel = []
            for line in lines:
                self._wrappedLabel.extend(textwrap.wrap(line,self._wrap))

            self._textHOffset = 20
            dc = wx.ClientDC(self)
            font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
            dc.SetFont(font)
            maxWidth = 0
            totalHeight = 0
            lineHeight = 0
            for line in self._wrappedLabel:
                width, height = dc.GetTextExtent(line)
                maxWidth = max(maxWidth,width)
                lineHeight = height
                totalHeight += lineHeight

            self._textHeight = totalHeight

            self.SetInitialSize(wx.Size(self._textHOffset + maxWidth,totalHeight))
            self.Bind(wx.EVT_PAINT, self.OnPaint)

        def OnPaint(self, event):
            dc = wx.PaintDC(self)
            self.Draw(dc)
            self.RefreshRect(wx.Rect(0,0,self._textHOffset,self.GetSize().height))
            event.Skip()

        def Draw(self, dc):
            dc.Clear()
            font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
            dc.SetFont(font)
            height = self.GetSize().height
            if height > self._textHeight:
                offset = height / 2 - self._textHeight / 2
            else:
                offset = 0
            for line in self._wrappedLabel:
                width, height = dc.GetTextExtent(line)
                dc.DrawText(line,self._textHOffset,offset)
                offset += height

class HFrame(wx.Frame):
   def __init__(self,pos=wx.DefaultPosition):
       wx.Frame.__init__(self,None,title="Hello World",size=wx.Size(600,400),pos=pos)

       self.panel = wx.Panel(self,-1)
       sizer = wx.BoxSizer(wx.HORIZONTAL)

       cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10)
       sizer.Add(cb,1)

       cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10)
       sizer.Add(cb,1)

       cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10)
       sizer.Add(cb,1)

       self.panel.SetSizer(sizer)
       sizer.Layout()

class VFrame(wx.Frame):
   def __init__(self,pos=wx.DefaultPosition):
       wx.Frame.__init__(self,None,title="Hello World",size=wx.Size(600,400),pos=pos)

       self.panel = wx.Panel(self,-1)
       sizer = wx.BoxSizer(wx.VERTICAL)

       cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10)
       sizer.Add(cb,1)

       cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10)
       sizer.Add(cb,1)

       cb = RadioButton(self.panel,-1,label="This is a very very long label for the control!",wrap=10)
       sizer.Add(cb,1)

       self.panel.SetSizer(sizer)
       sizer.Layout()

app = wx.App(redirect=False)
htop = HFrame(pos=wx.Point(0,50))
htop.Show()
vtop = VFrame(pos=wx.Point(650,50))
vtop.Show()
app.MainLoop()

rawDescription: multiline checkbox in wxpython

description: Multiline checkbox in wxpython


code:
tot = 0.

for i in xrange(data.shape[0]-1):
    tot += ((((data[i+1:]-data[i])**2).sum(1))**.5).sum()

avg = tot/((data.shape[0]-1)*(data.shape[0])/2.)

rawDescription: Using Numpy to find the average distance in a set of points


code:
import subprocess
retcode = subprocess.call(["at", "x", "y", "z"])

rawDescription: How to execute a shell command through Python

description: Execute a shell command through Python


code:
params = {
    'param1': 'val1',
    'param2': 'val2',
    'param3': 'val3'
}

foo(**params) # Even ubener magic

rawDescription: Use string or dict to build Python function parameters


code:
re.compile(r"(?<!Profile Pictures)
(\d+) photos
")

rawDescription: regular expression excludes specific strings

description: Regular expression excludes specific strings


code: b_id = [v.strip() for v in line.split(',')][1]

rawDescription: No output when merge two data frame by loop


code:
def example(fname):
    f = open(fname, 'r+b')
    f.seek(100)
    f.write('foobar')
    f.close()

rawDescription: Python Replace one line in >20GB text file


code: list([ "{%s , %s}" % tup[1:] for tup in df.replace(np.nan,0).astype(int).replace(0,'').itertuples() ])

rawDescription: Single quote replacement, handling of null integers in pandas/python2.7


code:
accum = list()
data = [(0.0, 0.9811758192941256), (1.00422, 0.9998252466431066), (0.0, 0.9024831978342827), (2.00425, 0.9951777494430947)]

EPSILON = 0.05

newdata = {d: True for d in data}
for k, v in data:
    if not newdata[(k,v)]: continue
    newdata[(k,v)] = False
    # use each piece of data only once
    keys,values = [k*v],[v]
    for kk, vv in [d for d in data if newdata[d]]:
        if abs(k-kk) < EPSILON:
            keys.append(kk*vv)
            values.append(vv)
            newdata[(kk,vv)] = False
    accum.append((sum(keys)/sum(values),sum(values)))

rawDescription: Merging python lists based on a 'similar' float value


code:
from timeit import timeit
timeit("import re; list(re.finditer('.*a', 'foo' * 10000))", number=1)
timeit("import re; list(re.finditer('.*a', 'foo' * 50000))", number=1)

rawDescription: PyCharm 3.1 hangs forever during indexing and unusable


code:
class Scenario(object):
  def __init__(self, w, x, y, z):
    self.val = {}
    self.val['w'] = self.value(w,10,50)
    self.val['x'] = self.value(x,5,15)
    self.val['y'] = self.value(y,25,75)
    self.val['z'] = self.value(z,3,7)
  def value(self, v, l, u):
    if (v < l):
      return "low"
    if (u > v >= l ):
      return "med"
    if (v >= u):
      return "high"
  def __str__(self):
    return "scenario = w: " + self.val['w'] + " x: " + self.val['x'] + " y: " + self.val['y'] + " z: " + self.val['z']

rawDescription: Python Scenario Building Through Input Classification


code: writer.writerow([some_float1, some_float2] + alist)

rawDescription: Python: writing int and list in a csv row


code:
def gen_wrapper(cmp):
    class Wrapper(object):
        def __init__(self, value): self.value = value
        def __cmp__(self, obj): return cmp(self.value, obj.value)
    return Wrapper

rawDescription: min heap in python

description: Min heap in python


code:
df['C'] = df['A'] + df['B']
df['C'] = df['C'].apply(lambda x: ''.join(sorted(x)))
df = df.drop_duplicates(subset='C')[['A', 'B']]

rawDescription: Pandas:drop_duplicates() based on condition in python


rawDescription: PyTables Column to normal python list

description: PyTables Column to normal python list


code:
lines = ['fooevent\tfoo_info1\tfoo_info2',
     'barevent\tbar_info2\tbar_info4',
     'basevent\tbas_info2\tbas_info5'
     ]

mapper = {
    'fooevent':(1,2),
    'barevent':(2,4),
    'basevent':(2,5)
}

output_length = max([max(v) for v in mapper.values()]) + 1

a = lambda x,m: fields[1:][m.index(x)] if x in m else ''

for line in lines:

    fields = line.split('\t')
    data = [a(x,mapper[fields[0]]) for x in range(1,output_length)]
    data.insert(0,fields[0])
    print(','.join(data))

rawDescription: Elegant conversion of tab separated log lines into a CSV matrix


code:
i = 0
numbers = []
while i < 6:
    print ("Secret Exponent (Uncompressed) : {}".format(private_key))
    print ("Private Key     : {} ".format(privateKeyToWif(private_key)))
    print ("Address         : {} ".format(keyToAddr(private_key)))
    i+=1

rawDescription: Script error please correct it

description: Script error please correct it


code:
def application(environ, start_response):
    start_response('200 OK', [('Content-type','text/plain')])
    yield 'body starts. You should see this in browser already'
    # do something
    yield 'some more of body'

rawDescription: In Pylons, how do I perform actions after writing the response?


code:
a = ['John 2', 'Jack 1']

print(sorted(a, key=lambda x:int(x.split(' ')[-1])))
# ['Jack 1', 'John 2']

rawDescription: Python - sorting a list

description: Python - sorting a list


code: numpy.zeros((2, 20))

rawDescription: ipython: how to set terminal width

description: Ipython: how to set terminal width


code: isRunningInPyCharm = "PYCHARM_HOSTED" in os.environ

rawDescription: How to check if python unit test started in PyCharm or not?

description: Check if python unit test started in PyCharm or not


code: os.popen("ps -p %d -oppid=" % os.getppid()).read().strip()

rawDescription: How to get process's grandparent id

description: Get process's grandparent id


code:
x = 34
y = 32

def f():
    global x,y
    x = 1
    y = 2

rawDescription: Python - Functions access to global variables


code: data = " ".join(bin(ord(b))[2:].rjust(8, "0") for b in data)

rawDescription: Display a string of 1's and 0's in binary format Python


code:
type(abs(-2))
type(abs(-2.0))
type(abs(3+4j))
type(math.fabs(-2))
type(math.fabs(-2.0))
type(math.fabs(3+4j))

rawDescription: Python - abs vs fabs

description: Python - abs vs fabs


rawDescription: Python - Opening Multible Tabs in Internet Explorer


code:
#!/usr/bin/env python

from flask import Flask
import time
import eventlet

eventlet.monkey_patch()

app = Flask(__name__)
app.debug = True

def background():
    """ do something in the background """
    print('[background] working in the background...')
    time.sleep(2)
    print('[background] done.')
    return 42

def callback(gt, *args, **kwargs):
    """ this function is called when results are available """
    result = gt.wait()
    print("[cb] %s" % result)

@app.route('/')
def index():
    greenth = eventlet.spawn(background)
    greenth.link(callback)
    return "Hello World"

if __name__ == '__main__':
    app.run()

rawDescription: `eventlet.spawn` doesn't work as expected


code:
import unittest
import carfactory
from mock import Mock

def constructorMock(name):
    """Create fake constructor that returns Mock object when invoked"""
    instance = Mock()
    instance._name_of_parent_class = name
    constructor = Mock(return_value=instance)
    return constructor

class CarFactoryTest(unittest.TestCase):

    def setUp():
        """Replace classes Wheel, Engine and Car with mock objects"""

        carfactory.Wheel = constructorMock("Wheel")
        carfactory.Engine = constructorMock("Engine")
        carfactory.Car = constructorMock("Car")

    def test_factory_creates_car():
        """Create car and check it has correct properties"""

        factory = carfactory.CarFactory()
        car_created = factory.create_car()

        # Check the wheels are created with correct radii
        carfactory.Wheel.assert_called_with(radius=50)
        carfactory.Wheel.assert_called_with(radius=50)
        carfactory.Wheel.assert_called_with(radius=60)
        carfactory.Wheel.assert_called_with(radius=60)

        # Check the engine is created with correct power
        carfactory.Engine.assert_called_once_with(power=500)

        # Check the car is created with correct engine and wheels
        wheel = carfactory.Wheel.return_value
        engine = carfactory.Engine.return_value
        carfactory.Car.assert_called_once_with(engine, [wheel, wheel, wheel, wheel])

        # Check the returned value is the car created
        self.assertEqual(car_created._name_of_parent_class, "Car")

rawDescription: How to unit test factory in python?

description: Unit test factory in python


code:
import numpy as np
stats = [100, 98, 102, 100, 108, 23, 120]
mean = np.mean(stats)
std = np.std(stats)
stats_z = [(s - mean)/std for s in stats]
np.abs(stats_z) > 2

rawDescription: Finding unusual value in an array, list

description: Finding unusual value in an array, list


code:
@click.command(name='list')
def list_command():
    pass

rawDescription: Python Click command names

description: Python Click command names


code:
import some_module

def my_method(self):
   pass

some_module.SomeClass.a_method = my_method

rawDescription: Override Django module class method

description: Override Django module class method


code:
import wx
from wx.combo import OwnerDrawnComboBox as ComboBox
from wx.lib.scrolledpanel import ScrolledPanel

class Choice(wx.Panel):
    def __init__(self, parent, allow_delete=True):
        wx.Panel.__init__(self, parent)

        self.colChoice = ComboBox(self, choices=['a','b','c'], style=wx.CB_READONLY)
        self.colChoice.Select(0)
        if allow_delete:
            self.minus_button = wx.Button(self, label='-', size=(30,-1))
            self.minus_button.Bind(wx.EVT_BUTTON, lambda event: self.Parent.on_remove_choice(event,self))
        self.plus_button = wx.Button(self, label='+', size=(30,-1))
        self.plus_button.Bind(wx.EVT_BUTTON, lambda event: self.Parent.on_add_choice(event,self))

        colSizer = wx.BoxSizer(wx.HORIZONTAL)
        colSizer.Add(self.colChoice, 1, wx.EXPAND|wx.ALL,1)
        colSizer.AddSpacer((5,-1))
        colSizer.Add(self.plus_button, 0, wx.EXPAND|wx.ALL,1)
        if allow_delete:
            colSizer.AddSpacer((5,-1))
            colSizer.Add(self.minus_button, 0, wx.EXPAND)
        else:
            colSizer.AddSpacer((5,-1))
            colSizer.Add(wx.StaticText(self), 0,wx.EXPAND)
        self.SetSizerAndFit(colSizer)

class ChoicePanel(ScrolledPanel):
    def __init__(self,parent):
        ScrolledPanel.__init__(self, parent, -1)

        self.panel_sizer = wx.BoxSizer( wx.VERTICAL )
        self.choices = []
        c = Choice(self, False)
        self.panel_sizer.Add(c, 0, wx.EXPAND)
        self.choices.append(c)

        self.SetSizer(self.panel_sizer)
        self.SetAutoLayout(1)
        self.SetupScrolling(False,True)

    def on_add_choice(self,event,selected_filter):
        self.choices.append(Choice(self, True))
        self.panel_sizer.Add(self.choices[-1], 0, wx.EXPAND|wx.BOTTOM|wx.LEFT|wx.RIGHT, 5)
        self.panel_sizer.Layout()
        self.Fit()
        self.GetParent().Layout()

    def on_remove_choice(self,event,selected_filter):
        i = self.choices.index(selected_filter)
        self.choices.remove(selected_filter)
        self.panel_sizer.Remove(selected_filter)
        selected_filter.Destroy()
        self.panel_sizer.Layout()
        self.Fit()
        self.GetParent().Layout()

class TestFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1)
        self.sizer = wx.BoxSizer(wx.HORIZONTAL)
        panel = wx.Panel(self, -1)
        self.test_panel = ChoicePanel(panel)
        self.sizer.Add(wx.StaticText(panel, -1, "Some text here:"), 1, wx.EXPAND|wx.CENTER|wx.ALL, 4)
        self.sizer.AddSpacer((4,-1))
        self.sizer.Add(self.test_panel, 1, wx.EXPAND|wx.CENTER|wx.ALL, 4)
        panel.SetSizer(self.sizer)
        panel.Layout()

if __name__=='__main__':
    app = wx.App(False)
    f = TestFrame()
    f.Show()
    app.MainLoop()

rawDescription: Problems sizing a ScrolledPanel when adding/removing child widgets


code: choice = int(input("please call the function you want to execute: "))

rawDescription: Python IDLE : how to run the whole script as it is always stopping at some point


code:
"""
Start $compass watch, command when you do $python manage.py runserver

file: main/management/commands/runserver.py

Add ´main´ app to the last of the installed apps
"""

from optparse import make_option
import os
import subprocess

from django.core.management.base import BaseCommand, CommandError
from django.core.management.commands.runserver import BaseRunserverCommand
from django.conf import settings

class Command(BaseRunserverCommand):
    option_list = BaseRunserverCommand.option_list + (
        make_option('--adminmedia', dest='admin_media_path', default='',
            help='Specifies the directory from which to serve admin media.'),
        make_option('--watch', dest='compass_project_path', default=settings.MEDIA_ROOT,
            help='Specifies the project directory for compass.'),
    )

    def inner_run(self, *args, **options):
        self.compass_project_path = options.get('compass_project_path', settings.MEDIA_ROOT)

        self.stdout.write("Starting the compass watch command for %r\n" % self.compass_project_path)
        self.compass_pid = subprocess.Popen(["compass watch %s" % self.compass_project_path],
            shell=True,
            stdin=subprocess.PIPE,
            stdout=self.stdout,
            stderr=self.stderr)
        self.stdout.write("Compas watch process on %r\n" % self.compass_pid.pid)

        super(Command, self).inner_run(*args, **options)

rawDescription: There is a way to add features to an existing django command?


code:
import sys
sys.path.insert(0, './toplevel')

rawDescription: top-level package handling with setuptools (or another python egg builder)

description: Top-level package handling with setuptools (or another python egg builder)


code:
import psycopg2

conn = psycopg2.connect(database='yourdb', user='dbuser', password='abcd1234', host='server', port='5432', sslmode='require')

rawDescription: How to connect to a remote PostgreSQL database with Python

description: Connect to a remote PostgreSQL database with Python


rawDescription: How to add feature names to output of decision tree in scikit learn

description: Add feature names to output of decision tree in scikit learn


code:
def make_form(exclude_user=True):
    class Form(forms.ModelForm):
        class Meta:
            model = Folder
            exclude = ['user'] if exclude_user else None
    return Form

form_cls = make_form(request.user != folder.owner)

rawDescription: Modifying a Django ModelForms fields

description: Modifying a Django ModelForms fields


code:
from PyQt4 import QtCore, QtGui

class Window(QtGui.QScrollArea):
    def __init__(self):
        super(Window, self).__init__()
        self.setWidgetResizable(True)
        widget = QtGui.QWidget(self)
        layout = QtGui.QVBoxLayout(widget)
        for text in 'One Two Three Four Five Six Seven'.split():
            button = QtGui.QPushButton(text)
            layout.addWidget(button)
        layout.addStretch()
        self.setWidget(widget)

if __name__ == '__main__':

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

rawDescription: How can I replicate this tkinter scroll behavior with pyQT?

description: Replicate this tkinter scroll behavior with pyQT


code:
import json
yield Request( url, method='POST',
               body=json.dumps(payload),
               headers={'Content-Type':'application/json'} )

rawDescription: python/scrapy for dynamic content

description: Python/scrapy for dynamic content


code:
# Demo to add rotated text to an image using PIL

import Image
import ImageFont, ImageDraw, ImageOps

im=Image.open("stormy100.jpg")

f = ImageFont.load_default()
txt=Image.new('L', (500,50))
d = ImageDraw.Draw(txt)
d.text( (0, 0), "Someplace Near Boulder",  font=f, fill=255)
w=txt.rotate(17.5,  expand=1)

im.paste( ImageOps.colorize(w, (0,0,0), (255,255,84)), (242,60),  w)

rawDescription: How do I draw text at an angle using python's PIL?

description: Draw text at an angle using python's PIL


code:
from encodings.aliases import aliases
def find(q):
    return [(k,v) for k, v in aliases.items() if q in k or q in v]
find('1252') # multiple aliases
find('856') # no codepage 856 in aliases
find('koi8') # no koi8_u in aliases
'x'.decode('cp856') # but cp856 is a valid codec
'x'.decode('koi8_u') # but koi8_u is a valid codec

rawDescription: Get a list of all the encodings Python can encode to


code:
df["Occ_Number"] = df.groupby("Name").cumcount()+1
df

rawDescription: Pandas: Incrementally count occurrences in a column


code:
class UploadImageForm(forms.ModelForm):
    class Meta:
        model = GallryImage
...
# Sample view
def upload_file(request):
    if request.method == 'POST':
        form = UploadImageForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadImageForm()
    return render_to_response('upload.html', {'form': form})

rawDescription: Django: how to use upload_to property of an ImageField


code:
from Bio import SeqIO
from collections import defaultdict

mapping = defaultdict(list)

for stool_record in SeqIO.parse('stool.fasta', 'fasta'):
    stool_seq = str(stool_record.seq)

    for lib_record in SeqIO.parse('libs.fasta', 'fasta'):
        lib_seq = str(lib_record.seq)

        if stool_seq.startswith(lib_seq):
            mapping[lib_record.id.split(';')[0]].append(stool_record.id)

rawDescription: Merge two large text files by common row to one mapping file


rawDescription: repeat elements of an array according to other array with the same length? like repelem for numpy

description: Repeat elements of an array according to other array with the same length? like repelem for numpy


code:
from celery.task.schedules import crontab
from celery.decorators import periodic_task

@periodic_task(run_every=crontab(hour=7, minute=30, day_of_week="mon"))
def every_monday_morning():
    print("This runs every Monday morning at 7:30a.m.")

rawDescription: How can I schedule a Task to execute at a specific time using celery?

description: Schedule a Task to execute at a specific time using celery


code: Shell("cmd.exe /c " & compiler & " """ & fileName & " "" > ""C:\output.txt"" ", vbNormalFocus)

rawDescription: Python not outputing to file when script is run in vb program


code:
FILE = open(filename,"rb")
FILE.read(numBytes)

rawDescription: Convert binary files into ascii in Python


code:
import subprocess

return_value = subprocess.call(['ffmpeg', '-loop',
    '1', '-i', video_file, '-i', sound_file, '-c:v', 'libx264', '-tune',
    'stillimage', '-c:a', 'aac', '-strict', 'experimental', '-b:a', '192k',
    '-pix_fmt', 'yuv420p', '-shortest', output_name])

if return_value:
    print("Failure")
else:
    print("Sucess!")

rawDescription: Can I run ffmpeg from my Python code and return a signal when it's done compressing?

description: Run ffmpeg from my Python code and return a signal when it's done compressing


code:
def vencedor_linha(t):
    tl1=(t[0],t[1],t[2])
    tl2=(t[3],t[4],t[5])
    tl3=(t[6],t[7],t[8])
    tl=(tl1,tl2,tl3)
    for row in tl:
        if all(x == 'X' for x in row) or all(x == 'O' for x in row):
            return True
    return False

rawDescription: I want to call the element inside a tuple of tuples for my function


code:
tempFile = open("/tmp/myAppName.file.txt","w")
p2 = Popen(cmd, stdin=p1.stdout, stdout=PIPE, stderr=tempFile)
p2out = ""
#when you need the output, just do this:
with open("/tmp/myAppName.file.txt","r") as f:
     p2out = f.read()

rawDescription: In Python, how can I chain multiple processes together with popen, while redirecting intermediate partial results into a string


code:
import win32evtlog
x = win32evtlog.EvtOpenChannelEnum()
win32evtlog.EvtNextChannelPath(x)
win32evtlog.EvtNextChannelPath(x)
win32evtlog.EvtNextChannelPath(x)

rawDescription: Python equivalent of PowerShell Get-EventLog


code:
while True:
    line = pandas.read_csv()
    if line[0] != '2004': continue
    # whatever else you need here

rawDescription: read and concatenate 3,000 files into a pandas data frame starting at a specific value, python

description: Read and concatenate 3,000 files into a pandas data frame starting at a specific value, python


code:
num_entry = int(input('Please enter an odd number: '))

def number():
    return num_entry % 2 == 0

def main():

    if number() == True:
        print('Sorry, please try again.')

    else:
        print('Nice! You know your numbers!')

number()

main()

rawDescription: Boolean return value?

description: Boolean return value


code:
def bar(self):
    assert isinstance(self, Foo)
    return self

rawDescription: Only let function be called as a method in Python


code:
for i in range(n):
       if i < 0:
           return 'negative'

rawDescription: Python why is 'int' object is not iterable in a simple if, else loop function


code:
def make_C(parent):
    class C(parent):
        def bar(self):
            ...
    return C

myClass1 = make_C(A)
myClass2 = make_C(B)

rawDescription: Is there generic inheritance in python?

description: Is there generic inheritance in python


code:
import string
def unique_words2(filename):
    words = {}
    strip = string.whitespace + string.punctuation + string.digits + "\"'"
    translation = {ord(bad):None for bad in strip}
    for line in open(filename):
        for word in line.lower().split():
             word = word.translate(translation)
             if word:
                 words[word] = words.get(word, 0) + 1
    for word in sorted(words):
        print("{0} {1}".format(word, words[word]))

unique_words2("alice.txt")

rawDescription: I am trying to count the number of time a word appears in a .txt file using Python3


rawDescription: How to reverse a list of lists in python?

description: Reverse a list of lists in python


code:
from PIL import Image, ImageDraw
BLACK, DARKGRAY, GRAY = ((0,0,0), (63,63,63), (127,127,127))
LIGHTGRAY, WHITE = ((191,191,191), (255,255,255))
BLUE, GREEN, RED = ((0, 0, 255), (0, 255, 0), (255, 0, 0))

class Point(object):
    def __init__(self, x, y):
        self.x, self.y = x, y

    @staticmethod
    def from_point(other):
        return Point(other.x, other.y)

class Rect(object):
    def __init__(self, x1, y1, x2, y2):
        minx, maxx = (x1,x2) if x1 < x2 else (x2,x1)
        miny, maxy = (y1,y2) if y1 < y2 else (y2,y1)
        self.min = Point(minx, miny)
        self.max = Point(maxx, maxy)

    @staticmethod
    def from_points(p1, p2):
        return Rect(p1.x, p1.y, p2.x, p2.y)

    def __str__(self):
        return 'Rect({:d}, {:d}, {:d}, {:d})'.format(self.min.x, self.min.y,
                                                     self.max.x, self.max.x)
    width  = property(lambda self: self.max.x - self.min.x)
    height = property(lambda self: self.max.y - self.min.y)

def interpolate_color(minval, maxval, val, color_palette):
    """ Computes intermediate RGB color of a value in the range of minval-maxval
        based on color_palette representing the range. """
    max_index = len(color_palette)-1
    v = float(val-minval) / float(maxval-minval) * max_index
    i1, i2 = int(v), min(int(v)+1, max_index)
    (r1, g1, b1), (r2, g2, b2) = color_palette[i1], color_palette[i2]
    f = v - i1
    return int(r1 + f*(r2-r1)), int(g1 + f*(g2-g1)), int(b1 + f*(b2-b1))

def draw_hz_gradient(rect, color_func, color_palette):
    minval, maxval = 1, len(color_palette)
    delta = maxval - minval
    for x in xrange(rect.min.x, rect.max.x+1):
        f = (x - rect.min.x) / float(rect.width)
        val = minval + f * delta
        color = color_func(minval, maxval, val, color_palette)
        draw.line([(x, rect.min.y), (x, rect.max.y)], fill=color)

def draw_vt_gradient(rect, color_func, color_palette):
    minval, maxval = 1, len(color_palette)
    delta = maxval - minval
    for y in xrange(rect.min.y, rect.max.y+1):
        f = (y - rect.min.y) / float(rect.height)
        val = minval + f * delta
        color = color_func(minval, maxval, val, color_palette)
        draw.line([(rect.min.x, y), (rect.max.x, y)], fill=color)

color_palette = [BLUE, GREEN, RED]
region = Rect(0, 0, 730, 350)
imgx, imgy = region.max.x+1, region.max.y+1
image = Image.new("RGB", (imgx, imgy), WHITE)
draw = ImageDraw.Draw(image)
draw_vt_gradient(region, interpolate_color, color_palette)
image.show()
#image.save("vt_gradient.png", "PNG")
#print 'image saved'

rawDescription: Python PIL Generating Vertical Gradient Image


code:
def accumulate_vector(start, scalars, vecs):
    prev = start
    yield start
    for k, vec in zip(scalars, vecs):
        prev = add_vector(prev, k, vec)
        yield prev

rawDescription: Cumulative sum of vectors from a point

description: Cumulative sum of vectors from a point


code:
driver = webdriver.Firefox()
driver.get('http://example.com')
add = driver.find_element_by_id("ajax_button")
add.click()
source = driver.page_source

def compare_source(driver):
    try:
        return source != driver.page_source
    except WebDriverException:
        pass

WebDriverWait(driver, 5).until(compare_source)
# and now do some assertions

rawDescription: selenium.wait_for_condition equivalent in Python bindings for WebDriver

description: Selenium.wait_for_condition equivalent in Python bindings for WebDriver


code:
from Tkinter import *
#Entry
def printkey(event):
    print('press:' + event.keysym)
#
root = Tk()
#input
entry = Entry(root)
#
entry.bind('<Key>', printkey)
#
entry.pack()
root.mainloop()

rawDescription: Cannot print out "event.char" using Tkinter


code:
class DrargDropListWidget(QtGui.QListWidget):
    def __init__(self, type, parent=None):
        super(DrargDropListWidget, self).__init__(parent)
        self.setDefaultDropAction(QtCore.Qt.MoveAction)
        self.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
        self.setAcceptDrops(True)

rawDescription: pyqt dropEvent will not fire

description: Pyqt dropEvent will not fire


code:
import socks, ssl
s = socks.socksocket()
s.setproxy(socks.PROXY_TYPE_SOCKS5,"127.0.0.1", 9050)
s.connect(('127.0.0.1', 443))
ssl_sock = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1)

rawDescription: Proxy not working over SSL connection

description: Proxy not working over SSL connection


code:
import random
import time
counter=0
score=0
count=0

function=['+','x','÷','-']

print('Welcome To The Arithmetic Quiz!')
name=input('Please enter you name.')
print('Thanks' , name , 'Lets Get Started!')

while counter <10:
    firstnumber=random.randint(0,12)
    secondnumber=random.randint(0,6)
    operator=random.choice(function)

    question=print(firstnumber, operator, secondnumber, '=')
    userAnswer = input('Answer:')

    if operator== '+':
                    count=firstnumber+secondnumber
                    if count == int (userAnswer):
                        print ('Correct!')
                        score= score+1
                    else:
                        print ('Incorrect')
    elif operator== 'x':
                    count=firstnumber*secondnumber
                    if count == int (userAnswer):
                        print ('Correct!')
                        score= score+1
                    else:
                        print ('Incorrect')
    elif operator== '-':
                    count=firstnumber-secondnumber
                    if count == int (userAnswer):
                        print ('Correct!')
                        score= score+1
                    else:
                        print ('Incorrect')
    elif operator== '÷':
                    count=firstnumber/secondnumber
                    if count == int (userAnswer):
                        print ('Correct!')
                        score= score+1
                    else:
                        print ('Incorrect')
    counter += 1

print ("Your quiz is over!")

rawDescription: Python Maths Quiz- Outputting Correct or Incorrect


code:
from django.contrib import admin
from .forms import SuperuserForm, OtherForm

class MyAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        if request.user.is_superuser():
            kwargs['form'] = SuperUserForm
        else:
            kwargs['form'] = OtherUserForm

        return super(MyAdmin, self).get_form(request,obj=obj,**kwargs)

rawDescription: How can I display form in django admin depending on user, Django

description: Display form in django admin depending on user, Django


code:
opener = urllib.FancyURLopener({})
f = opener.open("http://london.mycompany/mydir/")
f.read()

rawDescription: What is causing urllib2.urlopen() to connect via proxy?


code:
import operator
from functools import reduce

def getSearchQuery(search, list, columns=None):
    """
    Breaks up the search string and makes a query list
    Filters the given list based on the query list
    """
    if not columns:
        return list
    search = search.strip('\'"').split(" ")
    queries = []
    for col in columns:
        queries.extend([Q((col+'__icontains', value)) for value in search])

    return list.filter(reduce(operator.or_, queries))

rawDescription: Django querying using array for column value


code:
class Student(object):
    """A class to model students"""

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

    def get_all_information(self):
        """Get all information about the student"""
        return (self.age, self.grade, self.name)

james = Student(15, 9, 'James Herbert')
print(james.get_all_information())

rawDescription: Trying to learn python classes

description: Trying to learn python classes