code:
import wx

# Test context menu that should be displayed at the insertion point position
# in the TextCtrl object
class CustomMenu(wx.Menu):

    def __init__(self):
        wx.Menu.__init__(self)

        # Add some items in the menu
        self.AppendItem(wx.MenuItem(self, wx.NewId(), 'This should be at the'))
        self.AppendItem(wx.MenuItem(self, wx.NewId(), 'insertion point'))
        self.AppendItem(wx.MenuItem(self, wx.NewId(), 'position...'))

# Text area from which to open the custom context menu
class TestTextCtrl(wx.TextCtrl):

    def __init__(self, parent):
        wx.TextCtrl.__init__(self, parent, style=wx.TE_MULTILINE)

        self.parent = parent

        # Set a monospaced font
        font = wx.Font(12, wx.MODERN, wx.NORMAL, wx.NORMAL)
        self.SetFont(font)

        # Get the character size (width and height)
        self.pixelSize = font.GetPixelSize()

        # Display some text
        self.SetValue("[Ctrl] key = custom popup menu \n"
                      "[Menu] key = original context menu \n"
                      "[Ctrl] key = custom popup menu \n"
                      "[Menu] key = original context menu \n"
                      "[Ctrl] key = custom popup menu \n"
                      "[Menu] key = original context menu \n"
                      "[Ctrl] key = custom popup menu \n"
                      "[Menu] key = original context menu \n"
                      "[Menu] key = original context menu \n"
                      "[Ctrl] key = custom popup menu \n"
                      "[Menu] key = original context menu \n"
                      "[Ctrl] key = custom popup menu \n"
                      "[Menu] key = original context menu \n"
                      "[Menu] key = original context menu \n"
                      "[Ctrl] key = custom popup menu \n"
                      "[Menu] key = original context menu \n"
                      "[Ctrl] key = custom popup menu \n"
                      "[Menu] key = original context menu \n"
                      "[Menu] key = original context menu \n"
                      "[Ctrl] key = custom popup menu \n"
                      "[Menu] key = original context menu \n"
                      "[Ctrl] key = custom popup menu \n"
                      "[Menu] key = original context menu \n"
                      "[Menu] key = original context menu \n"
                      "[Ctrl] key = custom popup menu \n"
                      "[Menu] key = original context menu \n"
                      "[Ctrl] key = custom popup menu \n"
                      "[Menu] key = original context menu \n"
                      "[Menu] key = original context menu \n"
                      "[Ctrl] key = custom popup menu \n"
                      "[Menu] key = original context menu \n"
                      "[Ctrl] key = custom popup menu \n"
                      "[Menu] key = original context menu \n"
                      "[Ctrl] key = custom popup menu \n"
                      "[Menu] key = original context menu \n")

        # Activate the [Ctrl] key stroke detection (1/2)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyStroke)

    def OnKeyStroke(self, event):

        # Activate the [Ctrl] key stroke detection (2/2)
        if event.GetUnicodeKey() == wx.WXK_CONTROL:

            #######################################
            ##### Here is the interesting code ####
            #######################################

            # Get the scroll position in pixels
            scrollPosition = [
                self.GetScrollPos(wx.HORIZONTAL),
                self.GetScrollPos(wx.VERTICAL),
                ]

            # Get the text cursor position in the text area (int)
            insertionPointPosition = self.GetInsertionPoint()

            # Convert it into a row/column position (2D tuple)
            insertionPointRowColumnPosition = self.PositionToXY(insertionPointPosition)

            # Calculate the popup menu position in pixels
            insertionPointPositionInPixels = []
            for i in range(2):
                insertionPointPositionInPixels.append(
            #       (  row/column position    +   offset   ) * size of character - position of scroll in pixels)
                    (insertionPointRowColumnPosition[i] + i) * self.pixelSize[i] - scrollPosition[i]
                )

            # Convert the position into a wx.Point object
            popupMenuPoint = wx.Point(
                insertionPointPositionInPixels[0],
                insertionPointPositionInPixels[1]
            )

            # Display the context menu at the given position
            self.PopupMenu(CustomMenu(), popupMenuPoint)

            ### We did it ! :) ###

            #######################################
            #######################################
            #######################################

        else:
            event.Skip()

# Test frame
class TestFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None)

        # Create a text area
        TestTextCtrl(self)

        # Display the window
        self.Show(True)

if __name__ == "__main__":

    # Create an application
    application = wx.App(False)

    # Create a frame
    TestFrame()

    # Launch the application
    application.MainLoop()

rawDescription: Popup menu at the insertion point position in a wx.TextCtrl


code: soup.select("table.search-results-table tr h4 a")

rawDescription: Crawling a specific link on a page with multiple links?


rawDescription: Wtforms: How to generate blank value using select fields with dynamic choice values


code:
import tkinter as tk
from tkinter import ttk

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.button = ttk.Button(text="start", command=self.start)
        self.button.pack()
        self.progress = ttk.Progressbar(self, orient="horizontal",
                                        length=200, mode="determinate")
        self.progress.pack()

        self.bytes = 0
        self.maxbytes = 0

    def start(self):
        self.progress["value"] = 0
        self.maxbytes = 50000
        self.progress["maximum"] = 50000
        self.read_bytes()

    def read_bytes(self):
        '''simulate reading 500 bytes; update progress bar'''
        self.bytes += 500
        self.progress["value"] = self.bytes
        if self.bytes < self.maxbytes:
            # read more bytes after 100 ms
            self.after(100, self.read_bytes)

app = SampleApp()
app.mainloop()

rawDescription: How to create downloading progress bar in ttk?

description: Create downloading progress bar in ttk


code:
import logging
class ListHandler(logging.Handler): # Inherit from logging.Handler
        def __init__(self, log_list):
                # run the regular Handler __init__
                logging.Handler.__init__(self)
                # Our custom argument
                self.log_list = log_list
        def emit(self, record):
                # record.message is the log message
                self.log_list.append(record.msg)

rawDescription: Python logging handler to append to list


code:
import os
path = os.path.join(os.path.expanduser('~'), '.myfolder') # save the value
print(path)                                               # print it

rawDescription: using printed value as input value in Python

description: Using printed value as input value in Python


code:
def config_filter(allConfigs, filterOptions, fieldName):
    return [d for d in allConfigs
              if len([o for o in filterOptions
                        if d[int(o)-1][fieldName] == filterOptions[o]])
                 == len(filterOptions) ]

l = [({"type":1},{"type":2},{"type":3},{"type":4}),
      ({"type":5},{"type":2},{"type":3},{"type":4}),
      ({"type":5},{"type":2},{"type":6},{"type":4}),
      ({"type":5},{"type":3},{"type":6},{"type":4}),
      ({"type":1},{"type":6},{"type":3},{"type":4}),
      ({"type":1},{"type":2},{"type":5},{"type":4}),
      ({"type":1},{"type":2},{"type":6},{"type":4})]
print(config_filter(l, {}, "type"))
print(config_filter(l, {1:5}, "type"))
print(config_filter(l, {1:5, 3:6}, "type"))
print(config_filter(l, {1:5, 3:6, 2:3}, "type"))

rawDescription: python filtering a list of combinations

description: Python filtering a list of combinations


code:
find_words = re.compile(r'\w+').findall

# create *sets* for faster membership tests
wanted1 = set(find_words(open('words1.csv').read().lower()))
wanted2 = set(find_words(open('words2.csv').read().lower()))

csvfile = "summary.csv"
with open(csvfile, "wb") as output:
    writer = csv.writer(output)

    for f in sys.argv[1:]:
        cnt1 = cnt2 = cntWords = 0

        with open(f) as inputfile:
            for line in inputfile:
                for word in find_words(line.lower()):
                    cntWords += 1
                    if word in wanted1:
                        cnt1 += 1
                    if word in wanted2:
                        cnt2 += 1

        writer.writerow([cnt1, cnt2, cntWords])

rawDescription: Python - csv writer write by column, not row


code:
today = currentDate.strftime('%m/%d/%Y').replace("/0", "/")
if today[0] == '0':
    today = today[1:]

rawDescription: Date formatting using python

description: Date formatting using python


rawDescription: Python automatically simplifies floats to ints during set construction


code:
import pexpect
child = pexpect.spawn('student_program')
while child.expect('Enter (\w+)\r\n', pexpect.EOF) == 0:
    if child.match[1] == 'p':
        child.sendline('3.14159')

rawDescription: Python subprocess allow for user interaction


code:
from lxml import etree
q = etree.fromstring('<xml><hello>a</hello><x><hello>b</hello></x></xml>')
q.findall('hello')     # Tag name, first level only.
q.findall('.//hello')  # XPath, recursive.

rawDescription: how to find recursively for a tag of xml using LXML?

description: Find recursively for a tag of xml using LXML


rawDescription: How can I get the exponent of each number in a np.array?

description: Get the exponent of each number in a np.array


rawDescription: Python/Pandas: How to quickly pivot datetimeindex on date and time?


code:
keys = ["id", "count", "animal", "sound"]

lstValues = [1, 2, "cat", "meow"]

data = dict(zip(keys, lstValues))

rawDescription: copy values in a python list to a dictionary

description: Copy values in a python list to a dictionary


code:
db.define_table('followers',
    Field('follower', 'reference auth_user',
          requires=IS_IN_DB(db(db.auth_user.id != request.post_vars.user),
                            'auth_user.id', db.auth_user._format)),
    Field('user', 'reference auth_user'))

rawDescription: web2py : non identical field constraint

description: Web2py : non identical field constraint


code:
model = gtk.ListStore(gtk.gdk.Pixbuf, str)
model.append([gtk.gdk.pixbuf_new_from_file('image.png'), 'Foo'])

cb = gtk.ComboBox(model)

pb_cell = gtk.CellRendererPixbuf()
cb.pack_start(pb_cell, False)
cb.add_attribute(pb_cell, 'pixbuf', 0)

txt_cell = gtk.CellRendererText()
cb.pack_start(txt_cell, True)
cb.add_attribute(txt_cell, 'text', 1)

rawDescription: Python: gtk.ComboBox append box

description: Python: gtk.ComboBox append box


code:
strs='Hello%World'
strs.split("%")

rawDescription: How to filter a string to a list on Python

description: Filter a string to a list on Python


code:
from itertools import cycle
cols = cycle(["red", "green", "blue"])
next(cols)
next(cols)
next(cols)
next(cols)

rawDescription: Cycle through elements in list to assign different colors to plot


rawDescription: Getting only particular columns in every row in a numpy array


code:
k1 = 'k1'
k2 = 'k2'
v1 = 'v1'
v2 = 'v2'
l1 = [ {k1:v1} , {k2:v2}, {v1:k1} ]

kv = [e.items()[0] for e in l1]
print(kv)

vk = [(v, k) for (k, v) in kv]
print(vk)

result = [(k, v) for (k, v) in kv if (k, v) in vk]
print(result)

rawDescription: How can I check if there exist any reverse element in list of dict without looping on it

description: Check if there exist any reverse element in list of dict without looping on it


code:
def admin(handler_method):
  """
  This decorator requires admin, 403 if not.
  """
  def auth_required(self, *args, **kwargs):
    if users.is_current_user_admin():
      handler_method(self, *args, **kwargs)
    else:
      self.error(403)
  return auth_required

...

@admin
def crudmethod_update(self, *args, **kwargs):
  ...

rawDescription: Authentication on App Engine / Python / Django non-rel over JSON


code:
example = ['(string1)-(hello)', '(string2)-(world)']
[x for i in example for x in re.findall(r'\(([^\)]*)\)', i)]

rawDescription: Extracting strings from regular expression Python


code:
def writeToChatTest(CHAT_URL):
    mydriver.get(CHAT_URL)

    message = "Some message to test"
    xpaths = {
        'textArea': "//*[@id='ipsTabs_elChatTabs_chatroom_panel']/div[1]/div[1]/div/div/div[1]/textarea",
        'submitMessage': "//*[@id='ipsTabs_elChatTabs_chatroom_panel']/div[1]/div[1]/div/div/div[3]/button"
    }

    parsed_messages = []
    keepRunning = True
    while keepRunning:
        time.sleep(5)
        lis = mydriver.find_elements_by_xpath('//ul[@class="ipsList_reset cChatContainer"]/li')

        rst_messages_list = []

        for li in lis:
            if li.id() not in parsed_messages:
                '''this will end nicely your test if the message 'end selenium test' is being sent in chat'''
                if li.text == 'end selenium test':
                    keepRunning = False
                rst_messages_list.append(li.text)
                parsed_messages.append(li.id())

        for unique_message in rst_messages_list:
            if "word" in unique_message:
                mydriver.find_element_by_xpath(xpaths['textArea']).clear()
                mydriver.find_element_by_xpath(xpaths['textArea']).send_keys(unique_message[0] + ": " + message)

                mydriver.find_element_by_xpath(xpaths['submitMessage']).click()

rawDescription: It's possible to skip tags if they have been already parsed and coninue with the newer ones in python?


code:
ts = Series(13,date_range('20140714 14:47:57',periods=10,freq='s'))
ts
x = ts.index.to_series()
x-x.iloc[0]

rawDescription: calculate time elapsed timedelta from pandas datetime index

description: Calculate time elapsed timedelta from pandas datetime index


code:
x='command ". / * or any other char like this" some_param="string param" some_param2=50'
re.findall('\w+\=\d+|\w+\="[^"]+"|"[^"]+"|\w+',x)

rawDescription: Tokenize a command string

description: Tokenize a command string


code:
f_n = 100.
np.random.seed(seed=101);
# ??? you want uniform random variable? or is this just a typo and you want normal random variable?
foo = np.random.rand(f_n,3)
foo = DataFrame(foo)
f_filter = np.arange(f_n,.0,-1)

# here is the problem, uneven weight makes a artificial trend, causing non-stationary. covariance only works for stationary data.
# =============================================
f_filter = 1.0 / (f_filter**(f_filter/f_n))

fig, ax = plt.subplots()
ax.plot(f_filter)

rawDescription: Weighted data problems, mean is fine, but Covar and std look wrong, how do I adjust?


code:
class Point3d(tuple):
    @property
    def x(self):
        return self[0]

    @property
    def y(self):
        return self[1]

    @property
    def z(self):
        return self[2]

rawDescription: Optimizing 3d point hash function

description: Optimizing 3d point hash function


code:
chars = ['s','m','n']

query = query.filter(or_(*map(
                              lambda x: model.city.like('%{}%'.format(x)),
                              chars
)))

rawDescription: Query processsing in SQL Alchemy - Python


code:
from flask.globals import _app_ctx_stack, _request_ctx_stack
from werkzeug.urls import url_parse

def route_from(url, method = None):
    appctx = _app_ctx_stack.top
    reqctx = _request_ctx_stack.top
    if appctx is None:
        raise RuntimeError('Attempted to match a URL without the '
                           'application context being pushed. This has to be '
                           'executed when application context is available.')

    if reqctx is not None:
        url_adapter = reqctx.url_adapter
    else:
        url_adapter = appctx.url_adapter
        if url_adapter is None:
            raise RuntimeError('Application was not able to create a URL '
                               'adapter for request independent URL matching. '
                               'You might be able to fix this by setting '
                               'the SERVER_NAME config variable.')
    parsed_url = url_parse(url)
    if parsed_url.netloc is not "" and parsed_url.netloc != url_adapter.server_name:
        raise NotFound()
    return url_adapter.match(parsed_url.path, method)

rawDescription: Reverting a URL in Flask to the endpoint + arguments


code:
class RootFoo(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

class Foo(models.Model):
    rootfoo = models.ForeignKey(RootFoo)
    spam = models.ForeignKey(Spam)

    def __str__(self):
        return self.rootfoo.__str__()

class SpecificFoo(models.Model):
    name = models.CharField(max_length=80)
    foo = models.ForeignKey(Foo)
    bar = models.ForeignKey(Bar)
    property = models.IntegerField()

    def __str__(self):
        return self.name

rawDescription: Profiling Django: very slow performance

description: Profiling Django: very slow performance


code:
import glob
import sys
import TestBase
sys.path.append("tests")
for path in glob.iglob("tests/*.py"):
    module = __import__(os.path.basename(path)[:-3])
    for name in dir(module):
        obj = getattr(module, name)
        if isinstance(obj, type) and issubclass(obj, TestBase.TestBase):
            test = obj()
            test.TestFunction()

rawDescription: Calling a method from an imported python file


code: df = df.reset_index().pivot('Year', 'Month', 'Count')

rawDescription: Transpose multilevel index pandas

description: Transpose multilevel index pandas


rawDescription: how to extract specific info from Soap response in Python (pysimplesoap)

description: Extract specific info from Soap response in Python (pysimplesoap)


rawDescription: Django how to add an instance to reversed ForeignKey


code:
import pyspark
conf = pyspark.SparkConf()
conf.setMaster('yarn-client')
conf.setAppName('My Jupyter Notebook')

# 'spark.hadoop.foo.bar' sets key 'foo.bar' in the Hadoop Configuaration.
conf.set('spark.hadoop.yarn.resourcemanager.address', '<spark-master-hostname>')
conf.set('spark.hadoop.fs.default.name', 'hdfs://<spark-master-hostname>/')

sc = pyspark.SparkContext(conf=conf)

rawDescription: Connecting IPython notebook to spark master running in different machines


rawDescription: Correlation between two dataframes

description: Correlation between two dataframes


code:
from datetime import date
date(day=30, month=11, year=2014).strftime('%A %d %B %Y')

rawDescription: Python how to return date as words?

description: Python how to return date as words


code:
builder = gtk.Builder()
builder.add_from_file(glade_path)
builder.connect_signals(self)

main_window = builder.get_object("main_window")
main_window.show()

text_box1 = builder.get_object("textbox1")
text_box1.set_text("enter your name")

rawDescription: Modifying a GUI started with Glade

description: Modifying a GUI started with Glade


code:
from functools import partial
S=partial(SET, Family='ethernet-switching', PortMode='trunk')
S(Interface='ge-0/0/6.0', Vlan=['v100', 'v101', 'v102'])
S(Interface='ge-0/0/7.0', Vlan=['v100', 'v101', 'v102'])
S(Interface='ge-0/0/8.0', Vlan=['v100', 'v101', 'v102'])

rawDescription: Anonymous class inheritance

description: Anonymous class inheritance


code:
class UserTest(Base):
    ...

    @orm.reconstructor
    def init_on_load(self):
        self.foo = "bar"

rawDescription: Iterating a SQLAlchemy query is reseting newly assigned variables


code:
df = DataFrame(randn(10,10),columns=[ 'c_%s' % i for i in range(3)] + ['d_%s' % i for i in range(3) ] + ['e_%s' % i for i in range(4)])
df.filter(regex='d_|e_')

rawDescription: Python pandas dataframe: filter columns using a list?


code:
#!C:\Python26\python.exe

import MySQLdb

rawDescription: Python 2.7.1 import MySQLdb working via cmd but no in a .py file


code:
import struct
payloadLenMSB_h = struct.unpack('B', packetHeader[offsetPayloadLenMSB])[0]
payloadLenLSB_h = struct.unpack('B', packetHeader[offsetPayloadLenLSB])[0]
payloadLen = payloadLenMSB_h << 8 + payloadLenLSB_h

rawDescription: Convert element list to integer and shift to right


code:
import operator
import functools

nums = [1, 2, 3]
funcs = iter([operator.add, operator.sub])

def special_foldl(nums, funcs):
    return functools.reduce(lambda x,y: next(funcs)(x,y), nums)

print(special_foldl(nums, funcs))
# 0

rawDescription: Looking for a fold-like idiom

description: Looking for a fold-like idiom


code:
# create a sandbox globals dict
sandbox = {}

# create a new version of test() that uses the sandbox for its globals
newtest = type(test)(test.func_code, sandbox, test.func_name, test.func_defaults,
                     test.func_closure)

# add the sandboxed version of test() to the sandbox
sandbox["test"] = newtest

rawDescription: Python eval(compile(...), sandbox), globals go in sandbox unless in def, why?


code:
words = s.split(' ')
results = []
for word in words:
    if len(word) > 4:
       results.append(word[::-1])
    else:
       results.append(word)

print(' '.join(results))

rawDescription: How to replace single word in string not replacing other with same chars

description: Replace single word in string not replacing other with same chars


code: SOME_CMD = '{0} -p %s | tail -n +4 | awk \'{{print \$4}}\''.format(SOMETOOL)

rawDescription: String format python

description: String format python


code:
for letter in name:
    number = (ord(letter) - 97)%9 + 1
    output.append(number)

rawDescription: converting a number to set range of numbers?

description: Converting a number to set range of numbers


code:
from django.core import serializers

# assuming obj is a model instance
serialized_obj = serializers.serialize('json', [ obj, ])

rawDescription: How do you serialize a model instance in Django?

description: Serialize a model instance in Django


code:
Project.objects(code="CL1-002").update_one(set_on_insert__created=Project().created,
                                           set__name="Test Project Two",
                                           set__client="Client One",
                                           upsert=True)

rawDescription: Mongoengine update_one+upsert vs. deprecated get_or_create


code:
def addItem(item, name, offset):
          if isinstance(item, dict):
                lines.append(offset + u"<%s>" % name)
                addDict(item, offset + u" " * 4)
                lines.append(offset + u"</%s>" % name)
          else:
                lines.append(offset + u"<%s>%s</%s>" % (name, escape(unicodify(item)), name))

def addList(value,name, offset):
        for item in value:
            addItem(item, name, offset)

def addDict(node, offset):
        for name, value in node.iteritems():
            if isinstance(value, list):
                addList(value, name, offset)
            else:
                addItem(value, name, offset)

rawDescription: refactor this dictionary-to-xml converter in python

description: Refactor this dictionary-to-xml converter in python


code:
headers = {'User-Agent': user_agent}

data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)

rawDescription: Testing a RESTful API with POSTs from Python


code:
inTopic = urllib2.urlopen('http://stackoverflow.com/questions/4951331/how-do-i-insert-an-attribute-using-beautifulsoup')
content = BeautifulSoup.BeautifulSoup(inTopic)
tlist = content.findAll('table')
for tbl in tlist:
    tbl.attrs.append(('border', 1))

rawDescription: How do I insert an attribute using BeautifulSoup?

description: Insert an attribute using BeautifulSoup


code:
# Assumes a blocking socket.
while True:
    data = sock.recv(4096)
    if not data:
        break
    # Do something with `data` here.

rawDescription: How do I dump the TCP client's buffer in order to accept more data?

description: Dump the TCP client's buffer in order to accept more data


code:
def add_data (new_data, old_data, n): # keep n points
    return (old_data + new_data)[-n:]

rawDescription: How can I plot online data coming from two different sources in python?

description: Plot online data coming from two different sources in python


code:
from math import radians, cos, sin, asin, sqrt

def haversine(lon1, lat1, lon2, lat2):
    """
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a))
    r = 6371 # Radius of earth in kilometers. Use 3956 for miles
    return c * r

rawDescription: Haversine Formula in Python (Bearing and Distance between two GPS points)


code:
from django.http import HttpResponseRedirect

def delete(request, upload_id):
    p = ClientUpload.objects.get(pk=upload_id)
    p.delete()
    return HttpResponseRedirect('your-dashboard-url')

rawDescription: Django Adding a delete action to a template


code:
import pandas as pd

l = [3.0,7.0,10.0,20.0,200.0]
s = pd.Series(np.ones_like(l), index=l)
y = s.reindex(range(1000), fill_value=0)
pd.ewma(y, 199).plot()

rawDescription: Plot using pandas

description: Plot using pandas


code:
a = np.ndarray(shape=(2,3,4), dtype=object)
for (x_index, y_index, z_index), temp in np.ndenumerate(a):
    a[x_index][y_index][z_index] = {'position':(x_index, y_index, z_index)}

a

rawDescription: How to assign values to ndarray variable using loops in python

description: Assign values to ndarray variable using loops in python


code:
try:
  from lxml import etree
except ImportError:
  try:
    # Python 2.5
    import xml.etree.cElementTree as etree
  except ImportError:
    try:
      # Python 2.5
      import xml.etree.ElementTree as etree
    except ImportError:
      try:
        # normal cElementTree install
        import cElementTree as etree
      except ImportError:
        try:
          # normal ElementTree install
          import elementtree.ElementTree as etree
        except ImportError:
          print("Failed to import ElementTree from any known place")

rawDescription: How to install modules for Python 2.7 on Ubuntu 10.10?

description: Install modules for Python 2.7 on Ubuntu 10.10


code:
from Tkinter import *
from time import strftime

class App(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.label_var = StringVar()
        self.label = Label(self, textvariable=self.label_var)
        self.label.pack()
        # Start the loop
        self.go()

    def go(self):
        self.label_var.set(strftime("%H:%M:%S"))
        # The callback is only called once, so call it every time
        self.after(1000, self.go)

app = App()
mainloop()

rawDescription: Python Threading

description: Python Threading


code:
int_data = np.array([[0xC45B36F3, ...],...], dtype=np.uint32)
floats = int_data.view(np.float32)

rawDescription: hard code exact float values in python

description: Hard code exact float values in python


code:
import networkx as nx
G = nx.MultiDiGraph()
G.add_edge(1,1,headport='sw',tailport='nw')
G.add_edge(1,1,headport='se',tailport='ne')
nx.write_dot(G,'sl.dot')
# run dot -Tpng sl.dot >sl.png

rawDescription: Networkx; move edges in nx.MultiDiGraph plot


code:
root = ...
pattern = '*/subdir/subdir2/t*.txt'  # note leading wildcard character

if not os.path.dirname(pattern):  # no subdirectories in pattern
    # no need to compare full paths
    for path, subdirs, files in os.walk(root):
        for fn in fnmatch.filter(files, pattern):
            print('found match - path: "{}", fn: "{}"'.format(path, fn))
else:
    for path, subdirs, files in os.walk(root):
        # must compare full file paths to pattern when it contains directories
        filepaths = (os.path.join(path, file) for file in files)  # generator
        for fp in fnmatch.filter(filepaths, pattern):
            fn = os.path.basename(fp)
            print('match found - path: "{}", fn: "{}"'.format(path, fn))

rawDescription: Python fnmatch filter for patterns that include subdirectory


code:
from pywinauto import application
from pywinauto import clipboard

app = application.Application()
app.start(r'C:\Program Files (x86)\sda 1.06\Steam Desktop Authenticator.exe',
          timeout=5)
sda = app.window_(title_re="Steam Desktop Authenticator")
time.sleep(2)
sda.Copy.Click()
code = clipboard.GetData()
sda.Close()

rawDescription: How to export data from a GUI executable using python

description: Export data from a GUI executable using python


code:
import requests
import json
def make_request(method, url, token ,data=None, params=None, headers=None, timeout=60):
    headers = {'x-li-format': 'json', 'Content-Type': 'application/json'}
    params = {}
    kw = dict(data=data, params=params, headers=headers, timeout=timeout)
    params.update({'oauth2_access_token': token})
    return requests.request(method.upper(), url, **kw)

def submit_share(comment, title, description, submitted_url, submitted_image_url, token):
    post = {
        'comment': comment,
        'content': {
            'title': title,
            'submitted-url': submitted_url,
            'submitted-image-url': submitted_image_url,
            'description': description
        },
        'visibility': {
            'code': 'anyone'
        }
    }
    url = 'https://api.linkedin.com/v1/people/~/shares'
    try:
        response = make_request('POST', url, token,data=json.dumps(post))
        response = response.json()
        return response
    except Exception:
        return False

rawDescription: Python Linkedin API OAuth2 HTTP Error 401: Unauthorized


code:
events = Event.objects.extra(
    select={'attendees': 'SELECT COUNT(*) from event_registration' + \
        ' where attended=1 and event_id=event_event.id'}
).order_by('attendees')

rawDescription: Django Sort By ForeignKey Boolean Field

description: Django Sort By ForeignKey Boolean Field


rawDescription: Scapy arp poisoning not working for me

description: Scapy arp poisoning not working for me


code:
class MyConfigParser(ConfigParser):
    my_defaults = {
            'Section 1': 'spam',
            'Section 2': 'eggs',
    }

    def get(self, section, key):
        try:
            return ConfigParser.get(self, section, key)
        except ConfigParser.NoSectionError:
            if section in self.my_defaults:
                self.add_section(section)
                self.set(section, key, self.my_defaults[section])
                return self.my_defaults[section]
            else:
                raise
        except ConfigParser.NoOptionError:
            if section in self.my_defaults:
                self.set(section, key, self.my_defaults[section])
                return self.my_defaults[section]
            else:
                raise

rawDescription: Can you have defaults for section instead of instance on Python's ConfigParser?

description: Have defaults for section instead of instance on Python's ConfigParser


code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator
import matplotlib.pyplot as plt
import numpy as np

N=10        # matrix size

c1=np.random.randint(2,size=(N,N))  # your mask of 0 and 1
c2=1-c1                             # inverted mask
char1 = np.chararray((N, N))
char1[:] = 'r'                      # color1
char2=np.chararray((N, N))
char2[:]='b'                        # color2

colors=c1*char1+c2*char2            # color mask for plotting

data=np.random.rand(N,N)*5          # data you are plotting

X=linspace(-3,3,N)
Y=linspace(0,4,N)
X,Y=meshgrid(X,Y)
Z=data

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=colors,linewidth=0, antialiased=False)

plt.show()

rawDescription: 3D plot of Meshgrid vs. Labeling Matrix

description: 3D plot of Meshgrid vs. Labeling Matrix


rawDescription: plotting graphs in numpy, scipy

description: Plotting graphs in numpy, scipy


code:
class Message(object):
    """
    Base class representing a message.
    """

    DEFAULT_PRIORITY = 5

    def __init__(self):
        """
        Constructor.
        """
        self.priority = Message.DEFAULT_PRIORITY

    def set_priority(self, priority):
        """
        Set the message priority.

        :param int priority: The new message priority.
        :return: The old message priority.
        :rtype: int
        :raise TypeError: The given priority is not an int.
        """
        if not isinstance(priority, int):
            raise TypeError
        old_priority = priority
        self.priority = priority
        return old_priority

rawDescription: Is py:method needed for docstring info field lists?


code:
try:
    from collections import OrderedDict
except ImportError:
    print("Python 2.7+ is needed for this script.")
    sys.exit(1)

rawDescription: What to reference in the shebang python26 or python2.6


code: proc1.split()[0] == proc2.split()[0]

rawDescription: How to remove a substring separated by a space in Python?

description: Remove a substring separated by a space in Python


code:
def get(*args, **kwargs):
    if kwargs:
        return query.filter_by(**kwargs)
    else:
        return query.filter(*args)

rawDescription: Wrap sqlalchemy's filter and filter_by functions in a single function


code:
class Foo(object):
    def __init__(self, val):
        self.prop = val # The value to compare
    def __lt__(self, other):
        return self.prop < other.prop
    def __repr__(self):
        return 'Foo({})'.format(self.prop)
sorted_foos = sorted([Foo(7), Foo(1), Foo(3), Foo(9)])
sorted_foos
bisect.insort_left(sorted_foos, Foo(2))
sorted_foos

rawDescription: Insert a custom object in a sorted list

description: Insert a custom object in a sorted list


rawDescription: Convert string to list by special symbol including this symbol, miss double symbols (as escaped character)


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

fig = plt.figure()

cols = np.linspace(60,200,4)
rows = np.linspace(60,78,4)

ax = fig.add_subplot(1,1,1)
Z  = np.random.random( (4,4) )

m = Basemap(width=6500000, height=3000000,
        resolution='l', projection='stere',\
        lat_0=72, lon_0=130.,ax=ax)

### draw parallels and meridians.
m.drawparallels(rows, linewidth=0.7)
m.drawmeridians(cols, linewidth=0.7)
m.drawmapboundary()

### set up new cols, rows and z that are on high-res grid
cols2 = np.linspace(cols[0],cols[-1],100)
rows2 = np.linspace(rows[0],rows[-1],100)
Z2    = np.zeros((100,100))

for i in range(0,cols.shape[0]-1):
   for j in range(0,rows.shape[0]-1):
      ### find corresponding cols, rows on high-res grid
      i0 = np.where(np.abs(cols2-cols[i]) == np.min(np.abs(cols2-cols[i])))[0]
      i1 = np.where(np.abs(cols2-cols[i+1]) == np.min(np.abs(cols2-cols[i+1])))[0]
      j0 = np.where(np.abs(rows2-rows[j]) == np.min(np.abs(rows2-rows[j])))[0]
      j1 = np.where(np.abs(rows2-rows[j+1]) == np.min(np.abs(rows2-rows[j+1])))[0]
      ### put Z value in new Z2 array
      Z2[j0:j1+1,i0:i1+1] = Z[j,i]

x,y = m(*np.meshgrid(cols2,rows2))
m.pcolormesh(x,y,Z2,vmin=0,vmax=1)

plt.tight_layout()
plt.savefig('sof_example.png')

plt.show()

rawDescription: Python: Plotting blocks on a polar grid (Basemap.pcolormesh)


code:
_output_all_children = None

@property
def output_all_children(self):
    if self._output_all_children is None:
        lh = ListHolder()
        traverse_directories(self.start_directory, lh)
        self._output_all_children = lh.internal_list
    return self._output_all_children

rawDescription: Does the @properties decorator cache results?


code:
#0  0x00007fffebe9b407 in cv::ThresholdRunner::operator()(cv::Range const&) const () from /usr/local/lib/libopencv_imgproc.so.3.0
#1  0x00007fffecfe44a0 in tbb::interface6::internal::start_for<tbb::blocked_range<int>, (anonymous namespace)::ProxyLoopBody, tbb::auto_partitioner const>::execute() () from /usr/local/lib/libopencv_core.so.3.0
#2  0x00007fffe967496a in tbb::internal::custom_scheduler<tbb::internal::IntelSchedulerTraits>::local_wait_for_all(tbb::task&, tbb::task*) () from /lib64/libtbb.so.2
#3  0x00007fffe96705a6 in tbb::internal::arena::process(tbb::internal::generic_scheduler&) () from /lib64/libtbb.so.2
#4  0x00007fffe966fc6b in tbb::internal::market::process(rml::job&) () from /lib64/libtbb.so.2
#5  0x00007fffe966d65f in tbb::internal::rml::private_worker::run() () from /lib64/libtbb.so.2
#6  0x00007fffe966d859 in tbb::internal::rml::private_worker::thread_routine(void*) () from /lib64/libtbb.so.2
#7  0x00007ffff76e9df5 in start_thread () from /lib64/libpthread.so.0
#8  0x00007ffff6d0e1ad in clone () from /lib64/libc.so.6

rawDescription: Python / OpenCV application lockup issue


rawDescription: Trying to do a strange tranpose with Python pandas


code:
import BeautifulSoup
from urllib import urlopen
html = urlopen('http://www.gutenberg.org/files/82/82-h/82-h.htm').read()
soup = BeautifulSoup.BeautifulSoup(html)
len(soup('h2'))

rawDescription: Beautiful Soup has stopped working since Linux Mint Upgrade Python 2.7.4


code:
def makefunc(val):
  def somephase():
    return '%dd' % (val,)
  return somephase

Phase2 = makefunc(2)
Phase3 = makefunc(3)

rawDescription: Python : creating dynamic functions

description: Python : creating dynamic functions


code:
class TagsSerializer(serializers.HyperlinkedModelSerializer):
    entries = EntriesSerializer(many=True, read_only=True)
    class Meta:
        model = Tags
        fields = ('url', 'tag', 'entries')

rawDescription: How to set Many to Many field blank=True on both sides in django

description: Set Many to Many field blank=True on both sides in django


code:
import copy
l = [[1, 2], (3, 4)]
l2 = copy.deepcopy(l)
l2[0] is l[0]
l2[1] is l[1]

rawDescription: Does Python's copy.deepcopy really copy everything?


code:
from typing import Generator

def yieldMoreIfA(text: str) -> Generator[str, None, None]:
    if text == "A":
        yield text
        yield text
        return
    else:
        yield text
        return

rawDescription: What type signature do generators have in Python?


code:
clock = pygame.time.Clock()
while True:
    # limit the framerate and get the delta time
    dt = clock.tick(60)

    # convert the delta to seconds (for easier calculation)
    speed = 1 / float(dt)

    # do all your stuff, calculate your heroes vector movement
    # if heroes position is "px, py" and movement is "mx, my"
    # then multiply with speed
    px *= mx * speed
    py *= my * speed

rawDescription: How do I make sprites move evenly on all computers in Pygame & Python

description: Make sprites move evenly on all computers in Pygame & Python


code:
import wx

class TextObjectValidator(wx.PyValidator):
     """ This validator is used to ensure that the user has entered something
         into the text object editor dialog's text field.
     """
     def __init__(self):
         """ Standard constructor.
         """
         wx.PyValidator.__init__(self)

     def Clone(self):
         """ Standard cloner.

             Note that every validator must implement the Clone() method.
         """
         return TextObjectValidator()

     def Validate(self, win):
         """ Validate the contents of the given text control.
         """
         textCtrl = self.GetWindow()
         text = textCtrl.GetValue()

         if len(text) == 0:
             wx.MessageBox("A text object must contain some text!", "Error")
             textCtrl.SetBackgroundColour("pink")
             textCtrl.SetFocus()
             textCtrl.Refresh()
             return False
         else:
             textCtrl.SetBackgroundColour(
                 wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
             textCtrl.Refresh()
             return True

     def TransferToWindow(self):
         """ Transfer data from validator to window.

             The default implementation returns False, indicating that an error
             occurred.  We simply return True, as we don't do any data transfer.
         """
         return True # Prevent wxDialog from complaining.

     def TransferFromWindow(self):
         """ Transfer data from window to validator.

             The default implementation returns False, indicating that an error
             occurred.  We simply return True, as we don't do any data transfer.
         """
         return True # Prevent wxDialog from complaining.

#----------------------------------------------------------------------

class TestValidateDialog(wx.Dialog):
    def __init__(self, parent):
        wx.Dialog.__init__(self, parent, -1, "Validated Dialog")

        self.SetAutoLayout(True)
        VSPACE = 10

        fgs = wx.FlexGridSizer(0, 2)

        fgs.Add((1,1));
        fgs.Add(wx.StaticText(self, -1,
                             "These controls must have text entered into them.  Each\n"
                             "one has a validator that is checked when the Okay\n"
                             "button is clicked."))

        fgs.Add((1,VSPACE)); fgs.Add((1,VSPACE))

        label = wx.StaticText(self, -1, "First: ")
        fgs.Add(label, 0, wx.ALIGN_RIGHT|wx.CENTER)

        fgs.Add(wx.TextCtrl(self, -1, "", validator = TextObjectValidator()))

        fgs.Add((1,VSPACE)); fgs.Add((1,VSPACE))

        label = wx.StaticText(self, -1, "Second: ")
        fgs.Add(label, 0, wx.ALIGN_RIGHT|wx.CENTER)
        fgs.Add(wx.TextCtrl(self, -1, "", validator = TextObjectValidator()))

        buttons = wx.StdDialogButtonSizer() #wx.BoxSizer(wx.HORIZONTAL)
        b = wx.Button(self, wx.ID_OK, "OK")
        b.SetDefault()
        buttons.AddButton(b)
        buttons.AddButton(wx.Button(self, wx.ID_CANCEL, "Cancel"))
        buttons.Realize()

        border = wx.BoxSizer(wx.VERTICAL)
        border.Add(fgs, 1, wx.GROW|wx.ALL, 25)
        border.Add(buttons)
        self.SetSizer(border)
        border.Fit(self)
        self.Layout()

app = wx.App(redirect=False)
f = wx.Frame(parent=None)
f.Show()
dlg = TestValidateDialog(f)
dlg.ShowModal()
dlg.Destroy()

app.MainLoop()

rawDescription: wx.TextCtrl and wx.Validator

description: Wx.TextCtrl and wx.Validator


code:
df.index = pd.MultiIndex.from_arrays([df.index.date, df.index.time], names=['Date','Time'])
df

rawDescription: Split DatetimeIndex into date and time MultiIndex conveniently in Pandas


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

scroll_bottom = """$('html, body').animate({scrollTop:$(document).height()},'fast');"""

def scroll_wait(driver):
    # See if your element is present
    # Use the plural 'elements' to prevent throwing an exception
    # if the element is not yet present
    elem = driver.find_elements_by_id("STOP_HERE")

    # Now use a conditional to control the Wait
    if elem and elem[0].is_enabled and elem[0].is_displayed:
        # Returning True (or something that is truthy, like a non-empty list)
        # will cause the selenium Wait to exit
        return elem[0]
    else:
        # Scroll down more
        driver.execute_script(scroll_bottom)

        # Returning False will cause the Wait to wait and then retry
        return False

# Now use your custom expected condition with a Wait
TIMEOUT = 30  # 30 second timeout
WebDriverWait(driver, TIMEOUT, poll_frequency=0.25).until(scroll_wait)

rawDescription: Using while statement with WebDriverWait and expected_conditions


code:
import pandas as pd
from scipy import stats

data = [
7707.443,
 9595.481,
 5923.493,
 4813.446,
 5384.159,
 4108.496,
 6370.271,
 8829.357,
 7495.700,
13709.940,
 6148.129,
 7249.951,
 6546.819,
 7290.730,
 5056.485
 ]

period_index = pd.period_range(start='2012-03', periods=len(data), freq='M')

df = pd.DataFrame(data=data,
              index=period_index,
              columns=['PointProduction'])

# these ordinals are months since the start of the Unix epoch
df['ords'] = [tstamp.ordinal for tstamp in df.index]
m,c,r,x,y = stats.linregress(list(df.ords),
                             list(df['PointProduction']))

rawDescription: Obtain Gradient of values against time stamp python


code:
import win32file # Ensure you import the module.

file_handle = win32file.CreateFile('filename.txt', win32file.GENERIC_READ, win32file.FILE_SHARE_DELETE | win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None)

rawDescription: Python: Opening a file without creating a lock


code:
from enthought.traits.api import HasTraits, Tuple, Delegate, Trait, Float,Dict,List

class Foo(HasTraits):
    def __init__(self):
        super(Foo,self).__init__()
        self.add_trait('node',List)
    def _node_changed(self,name,old,new):
        print("_node_changed: %s %s %s" % (name, str(old), str(new)))
    def _node_items_changed(self,name,old,new):
        print("_node_items_changed: %s %s %s" % (name, str(old), str(new)))

f = Foo()

# change the List membership with append:
f.node.append(0)
# _node_items_changed: node_items <undefined> <traits.trait_handlers.TraitListEvent object at 0x10128af50>

# change the List itself:
f.node = [1,2,3]
# _node_changed: node [0] [1, 2, 3]

# change a member (same result as append):
f.node[1] = 4
# _node_items_changed: node_items <undefined> <traits.trait_handlers.TraitListEvent object at 0x10128af50>

rawDescription: Traits List not reporting items added or removed


code:
import imp

foo = imp.load_source('module.name', '/home/morbo/document/python/python_script/morbo_function_lib.py')

rawDescription: How to import a function I wrote in python

description: Import a function I wrote in python


code:
p = argparse.ArgumentParser()
p.add_argument("--keyvalue", action='append',
               type=lambda kv: kv.split("="), dest='keyvalues')

args = p.parse_args("--keyvalue foo=6 --keyvalue bar=baz".split())
d = dict(args.keyvalues)

rawDescription: Python argparse dict arg

description: Python argparse dict arg


code:
pos = nx.random_layout(g)
nx.draw(g,pos=pos, nodelist = guardians, node_color='b')
nx.draw(g,pos=pos, nodelist = avengers, node_color='y')

rawDescription: How to change the color of a set of nodes?

description: Change the color of a set of nodes


code:
http_server = tornado.httpserver.HTTPServer(applicaton, ssl_options={
    "certfile": os.path.join(data_dir, "mydomain.crt"),
    "keyfile": os.path.join(data_dir, "mydomain.key"),
})

http_server.listen(443)

rawDescription: How to handle a request with HTTPS protocol in Tornado?

description: Handle a request with HTTPS protocol in Tornado


code: return datetime.utcfromtimestamp(int64_unpack(byts) / 1000.0)

rawDescription: How do you return the timestamp from Cassandra when using Python and CQL?

description: Return the timestamp from Cassandra when using Python and CQL


code:
if request.method == 'POST':
    filename=request.FILES['file']
    form = SomeForm(request.POST, request.FILES)
    if form.is_valid():
        dest_file = open('C:/system/upload/'+ str(filename), 'wb+')
        path = 'C:/system/upload/upload/'+ str(filename)
        for chunk in  request.FILES['file'].chunks():
            dest_file.write(chunk)
        dest_file.close()

rawDescription: How to upload file in django server using phonegap?

description: Upload file in django server using phonegap


code:
A = your_input
for i in A.split('MS1'):
    i.count('MS2')

rawDescription: Python - Count character in a text file between a specific character


code:
from scrapy.selector import Selector

self.browser.implicitly_wait(30)

for i in range(0,200):
    time.sleep(20)  # TODO: a delay like this doesn't look good

    button = self.browser.find_element_by_xpath("/html/body/div[4]/div[6]/div[1]/div[2]/div[2]/div[1]/div[2]/button[1]/div[2]/div/div")
    button.click()

    sel = Selector(text=self.browser.page_source)
    sites = sel.xpath('//div[@class="single-review"]/div[@class="review-header"]')

    for site in sites:
        item = Product()

        item['title'] = site.xpath('.//div[@class="review-info"]/span[@class="author-name"]/a/text()').extract()
        yield item

rawDescription: How to update the new page source everytime in scrapy xpath while using selenium?

description: Update the new page source everytime in scrapy xpath while using selenium


code:
socket_data = threading.local()
socket_data = bind_ip = None

true_socket = socket.socket

def bound_socket(*a, **k):
    sock = true_socket(*a, **k)
    if socket_data.bind_ip is not None:
        sock.bind((socket_data.bind_ip, 0))
    return sock

socket.socket = bound_socket

def thread_target(bind_ip):
    socket_data.bind_ip = bind_ip
    # the rest code

for bind_ip in [...]:
    thread = Thread(target=thread_target, args=(bind_ip,))
    # ...

rawDescription: Bind different ip addresses to urllib2 object in seperate threads


rawDescription: Tornado Create a Secure Cookie with expiry time less than 1 day


code:
from scrapy.http import FormRequest

for href in hxs.select('//div[@class="paging pag-num pag-arrows"]//a/@href'):
    target = href.split("'")[1]

    yield FormRequest.from_response(
        response=response,
        formnumber=0,
        formdata={'__EVENTTARGET': target}
    )

rawDescription: Using scrapy to get second page of results that uses Javascript


code:
# original part (left)
import numpy as np
import matplotlib.pyplot as plt
f,ax = plt.subplots(1,2)
ax[0].set_aspect('equal')
data=np.abs(np.random.randn(7))
wedges, texts = ax[0].pie(data)

# redraw plot using patches (right)
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection
ax[1].set_aspect('equal')
ax[1].axis('off')

groups=[[0,1,2],[3,4],[5,6]]
radfraction = 0.1
patches = []
for i in groups:
  ang = np.deg2rad((wedges[i[-1]].theta2 + wedges[i[0]].theta1)/2,)
  for j in i:
    we = wedges[j]
    center = (radfraction*we.r*np.cos(ang), radfraction*we.r*np.sin(ang))
    patches.append(mpatches.Wedge(center, we.r, we.theta1, we.theta2))

colors = np.linspace(0, 1, len(patches))
collection = PatchCollection(patches, cmap=plt.cm.hsv)
collection.set_array(np.array(colors))
ax[1].add_collection(collection)
ax[1].autoscale(True)

rawDescription: Explode multiple slices of pie together in matplotlib


code:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

association_table = Table('edges', Base.metadata,
    Column('predecessor', Integer,
           ForeignKey('nodes.id'), primary_key=True),
    Column('successor', Integer,
           ForeignKey('nodes.id'), primary_key=True))

path_table = Table('paths', Base.metadata,
    Column('predecessor', Integer,
           ForeignKey('nodes.id'), primary_key=True),
    Column('successor', Integer,
           ForeignKey('nodes.id'), primary_key=True))

class Node(Base):
    __tablename__ = 'nodes'
    id = Column(Integer, primary_key=True)
    # extra columns

    def __repr__(self):
        return '<Node #%r>' % (self.id,)

    successors = relationship('Node', backref='predecessors',
        secondary=association_table,
        primaryjoin=id == association_table.c.predecessor,
        secondaryjoin=id == association_table.c.successor)

    before = relationship('Node', backref='after',
        secondary=path_table,
        primaryjoin=id == path_table.c.predecessor,
        secondaryjoin=id == path_table.c.successor)

    def __lt__(self, other):
        return other in self.before

    def add_successor(self, other):
        if other in self.successors:
            return
        self.successors.append(other)
        self.before.append(other)
        for descendent in other.before:
            if descendent not in self.before:
                self.before.append(descendent)
        for ancestor in self.after:
            if ancestor not in other.after:
                other.after.append(ancestor)

    def del_successor(self, other):
        if not self < other:
            # nodes are not connected, do nothing!
            return
        if not other in self.successors:
            # nodes aren't adjacent, but this *could*
            # be a warning...
            return

        self.successors.remove(other)

        # we buld up a set of nodes that will be affected by the removal
        # we just did.
        ancestors = set(other.after)
        descendents = set(self.before)

        # we also need to build up a list of nodes that will determine
        # where the paths may be.  basically, we're looking for every
        # node that is both before some node in the descendents and
        # ALSO after the ancestors.  Such nodes might not be comparable
        # to self or other, but may still be part of a path between
        # the nodes in ancestors and the nodes in descendents.
        ancestors_descendents = set()
        for ancestor in ancestors:
            ancestors_descendents.add(ancestor)
            for descendent in ancestor.before:
                ancestors_descendents.add(descendent)

        descendents_ancestors = set()
        for descendent in descendents:
            descendents_ancestors.add(descendent)
            for ancestor in descendent.after:
                descendents_ancestors.add(ancestor)
        search_set = ancestors_descendents & descendents_ancestors

        known_good = set() # This is the 'paths' from the
                           # original algorithm.

        # as before, we need to initialize it with the paths we
        # know are good.  this is just the successor edges in
        # the search set.
        for predecessor in search_set:
            for successor in search_set:
                if successor in predecessor.successors:
                    known_good.add((predecessor, successor))

        # We now can work our way through floyd_warshall to resolve
        # all adjacencies:
        for ancestor in ancestors:
            for descendent in descendents:
                if (ancestor, descendent) in known_good:
                    # already got this one, so we don't need to look for an
                    # intermediate.
                    continue
                for intermediate in search_set:
                    if (ancestor, intermediate) in known_good \
                            and (intermediate, descendent) in known_good:
                        known_good.add((ancestor, descendent))
                        break # don't need to look any further for an
                              # intermediate, we can move on to the next
                              # descendent.

        # sift through the bad nodes and update the links
        for ancestor in ancestors:
            for descendent in descendents:
                if descendent in ancestor.before \
                        and (ancestor, descendent) not in known_good:
                    ancestor.before.remove(descendent)

rawDescription: Efficient incremental implementation of poset


code:
def rock(x,y):
    result = x * y
    return result

print(rock(440,400))

rawDescription: Python app cannot print result

description: Python app cannot print result


code:
import numpy as np

def split_into_quadrants(points, idx=0):
    if idx < points.shape[-1]:
        positive = points[points[:, idx] >= 0]
        negative = points[points[:, idx] < 0]
        return (split_into_quadrants(positive, idx+1) +
                split_into_quadrants(negative, idx+1))
    else:
        return [points]

b = np.round(np.random.random((30,3))*20)
b = b - b.mean(axis=0)
print(split_into_quadrants(b))

rawDescription: Dividing point clouds into quadrants in python


code:
#Hangman

from tkinter import *
import random, functools, string

root = Tk()

word_list = ["APPLE", "PEAR", "BANNANA"]

word = word_list [random.randrange(0,2)]

#Functions
def click_1 (text):
    if text in word:
        print ("yay")
    else:
        print ("Boo")

#Frames
hangman_frame = Frame(root).grid(row=0, column=0)
letter_frame = Frame(root).grid(row=1, column=0)

#Buttons
r = c = 0
for letter in string.ascii_uppercase:
    Button(letter_frame, text=letter, command=functools.partial(click_1, letter)).grid(row=r, column=c, sticky=W)
    c += 1
    if c > 12:
        c = 0
        r += 1

rawDescription: Trying to find a character in a string, Python using Tkinter


code:
def xlsxHasEntity(filename):
   input_zip = ZipFile(filename)
   xml_files = [name for name in input_zip.namelist() if name.endswith("xml")]
   raw_files = {name: input_zip.read(name) for name in xml_files}
   for raw_filename in raw_files:
      if "<!ENTITY" in raw_files[raw_filename]:
         return True
   return False

rawDescription: Python: Search .xlsx file for certain XML tags


code:
report_tuples = [
    ('http://www.myreport.com/report1', report1_date_object_or_string),
    ('http://www.myreport.com/report2', report2_date_object_or_string),
    ('http://www.myreport.com/report3', report3_date_object_or_string),
]
sorted(report_tuples, key=lambda reports: reports[1])   # sort by date
html = '' #add anything else in here or even better
                      #use a template that you read and complement
lastDate = None
for r in report_tuples:
    if not lastDate or not lastDate == r[1]:
        html += '
%s
' % (str(r[1]))
    html += 'Your Report Title' % (r[0])

return html #or even better, write it to the disk.

rawDescription: Python/html- Combine multiple html's into one


code:
while 1:
    math = input("What Is 8 x 4: ")
    if not math.isdigit():
        print("It's not number")

    elif math == "32":
        print("You Got The Question Correct")
        break

    else:
        print("Sorry You Got The Question Wrong Try Again")

rawDescription: How do I repeat the program?

description: Repeat the program


code:
import json
with open("sample.cfg", "r") as config_file:
  config = json.load(config_file)

changestring = 'clients,0,bar,bar_1:1,2,3'
keyval = changestring.split(':')
keys = keyval[0].split(',')
vals = keyval[1].split(',')

# Move our "pointer"
obj = config
for key in keys[:-1]:
  try: obj = obj[key]
  except TypeError:
    # Probably want a more general solution
    obj = obj[int(key)]

# Update value
obj[keys[-1]] = vals

with open("modified.cfg", "w") as config_file:
  config_file.write(json.dumps(config))

rawDescription: Python modify JSON file based on input

description: Python modify JSON file based on input


code:
# assuming you're using numpy arrays
w = exp(-2*pi*1j*f0*arange(len(signal))/fs)
peak = abs(sum(signal*w))

rawDescription: How to extract the peak at a specific frequency in python

description: Extract the peak at a specific frequency in python


rawDescription: How can I repeat this array of 2d pairs using Numpy?

description: Repeat this array of 2d pairs using Numpy


code:
class CustomButton(tk.Canvas):
    def __init__(self, parent, width, height, color, command=None):
        tk.Canvas.__init__(self, parent, borderwidth=1,
            relief="raised", highlightthickness=0)
        self.command = command

        padding = 4
        id = self.create_oval((padding,padding,
            width+padding, height+padding), outline=color, fill=color)
        (x0,y0,x1,y1)  = self.bbox("all")
        width = (x1-x0) + padding
        height = (y1-y0) + padding
        self.configure(width=width, height=height)
        self.bind("<ButtonPress-1>", self._on_press)
        self.bind("<ButtonRelease-1>", self._on_release)

    def _on_press(self, event):
        self.configure(relief="sunken")

    def _on_release(self, event):
        self.configure(relief="raised")
        if self.command is not None:
            self.command()

rawDescription: How to make a Button using the tkinter Canvas widget?

description: Make a Button using the tkinter Canvas widget


code:
from PIL import Image
gif = Image.open('path.gif')
try:
    gif.seek(1)
except EOFError:
    isanimated = False
else:
    isanimated = True

rawDescription: How do I programmatically check whether a GIF image is animated?

description: Programmatically check whether a GIF image is animated


code:
class MyTabularInline(admin.TabularInline):
    model = MyModel
    readonly_fields = ['decrypt_first_field', 'decrypt_second_field']

    def decrypt_first_field(self, obj):
        if obj.first_field:
            return decrypt(obj.first_field)
        else:
            return 'Nothing here ...'

    def decrypt_first_field(self, obj):
        ...

rawDescription: Override admin.TabularInline fields

description: Override admin.TabularInline fields


rawDescription: Splitting string by '],[', but keeping the brackets


rawDescription: Formatting the output from Pandas .groupby.size()


code:
import random
import numpy as np
import matplotlib.pyplot as plt
r= np.sort(np.array([ random.random()*5 for i in np.arange(100) ]))
len(r)
theta = [t for t in np.linspace(0,2*np.pi,100)]
ax = plt.subplot(111, polar=True)
ax.plot(theta, r, 'o',color='r', linewidth=3)
ax.set_rmax(2.0)
ax.grid(True)

[ax.plot(theta, rcirc*np.ones(100)) for rcirc in r.max()*np.random.rand(5)]

plt.show()

rawDescription: Plotting Circular contour lines in matplotlib


code:
import pyudev
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
observer = pyudev.pygtk.GUDevMonitorObserver(monitor)
observer.connect('device-added', device_added_callback)
observer.connect('device-changed', device_changed_callback)
monitor.enable_receiving()
mainloop = gobject.MainLoop()
mainloop.run()

rawDescription: USB devices UDev and D-BUS

description: USB devices UDev and D-BUS


code:
d = dict()
execfile('test.py', d)
from some_module import f
f
f.func_globals is d

rawDescription: Do references created by exec become invalid when no globals dict is passed?


code:
import sys, random, pygame
from pygame.locals import *

pygame.init()

w = 640
h = 480

screen = pygame.display.set_mode((w,h))
morphingShape = pygame.Surface((20,20))
morphingShape.fill((255, 137, 0)) #random colour for testing
morphingRect = morphingShape.get_rect()

# clock object that will be used to make the animation
# have the same speed on all machines regardless
# of the actual machine speed.
clock = pygame.time.Clock()

def ShapeSizeChange(shape, screen):
    x = random.randint(-21, 20)
    w = shape.get_width()
    h = shape.get_height()
    if w + x > 0 and h + x > 0:
        shape = pygame.transform.smoothscale(shape, (w + x, h + x))
    else:
        shape = pygame.transform.smoothscale(shape, (w - x, h - x))
    shape.fill((255, 137, 0))
    rect = shape.get_rect()
    screen.blit(shape, rect)
    return shape

while True:
    # limit the demo to 50 frames per second
    clock.tick( 50 );

    # clear screen with black color
    # THIS IS WHAT WAS REALLY MISSING...
    screen.fill( (0,0,0) )

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    morphingShape = ShapeSizeChange(morphingShape, screen)
    pygame.display.update()

rawDescription: Pygame, how to draw a shape to the screen and delete the previous surface?


rawDescription: scrape specific table element with scrapy

description: Scrape specific table element with scrapy


code:
import cv2
import numpy as np
im = cv2.imread('/home/zawlin/test.png')

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
contours,h = cv2.findContours(gray,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

final = np.zeros(im.shape,np.uint8)
mask = np.zeros(gray.shape,np.uint8)

for i in xrange(0,len(contours)):
    mask[...]=0
    cv2.drawContours(mask,contours,i,255,-1)
    cv2.drawContours(final,contours,i,cv2.mean(im,mask),-1)

cv2.imshow('im',im)
cv2.imshow('final',final)
cv2.waitKey(0)

rawDescription: OpenCV: How can I find the color inside a contour/polygon?


code: {{ item["directory_name"] }}

rawDescription: Ansible global vars.yml loop Task in Template


code:
import ctypes

def is_aero_enabled():
    try:
        b = ctypes.c_bool()
        retcode = ctypes.windll.dwmapi.DwmIsCompositionEnabled(ctypes.byref(b))
        return (retcode == 0 and b.value)
    except AttributeError:
        # No windll, no dwmapi or no DwmIsCompositionEnabled function.
        return False

rawDescription: Python/PyQT check if Aero enabled

description: Python/PyQT check if Aero enabled


code:
allowed_classes = {
    'A': ClassA,
    'B': ClassB
}

def load_class(class_name, *args, **kwdargs):
    return allowed_classes[class_name](*args, **kwdargs)

new_class_obj = load_class('B', 'Jan 1st')

rawDescription: Taking user input to load a class

description: Taking user input to load a class


rawDescription: Combining columns based on group

description: Combining columns based on group


code:
lib_interests = ["Science", "Arts", "BusinessEconomy", "ComputersTechnology"]
interests = [True, False, True, True]
data = dict(zip(lib_interests, interests))
data.update(user_id = auth.user_id)
db.user_interests.insert(**data)

rawDescription: Web2Py insert record from list

description: Web2Py insert record from list


code:
from psycopg2.extras import NumericRange
from sqlalchemy import create_engine, Column, Integer
from sqlalchemy.dialects.postgresql import INT4RANGE
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

engine = create_engine('postgresql:///example', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base(bind=engine)

class Example(Base):
    __tablename__ = 'example'

    id = Column(Integer, primary_key=True)
    window = Column(INT4RANGE, nullable=False)

Base.metadata.create_all()

session.add(Example(window=NumericRange(2, 6)))
session.add(Example(window=NumericRange(4, 8)))
session.commit()

rawDescription: How to use postgres numeric range with SQLAlchemy

description: Use postgres numeric range with SQLAlchemy


code:
queue = eventlet.queue.Queue(10000)
wait = eventlet.semaphore.CappedSemaphore(1000)

def fetch(url):
  # httplib2.Http().request
  # or requests.get
  # or urllib.urlopen
  # or whatever API you like
  return response

def crawl(url):
  with wait:
    response = fetch(url)
    links = parse(response)
    for url in link:
      queue.put(url)

def spawn_crawl_next():
  try:
    url = queue.get(block=False)
  except eventlet.queue.Empty:
    return False
  # use another CappedSemaphore here to limit number of outstanding connections
  eventlet.spawn(crawl, url)
  return True

def crawler():
  while True:
    if spawn_crawl_next():
      continue

    while wait.balance != 0:
      eventlet.sleep(1)

    # if last spawned `crawl` enqueued more links -- process them
    if not spawn_crawl_next():
      break

def main():
  queue.put('http://initial-url')
  crawler()

rawDescription: How do I feed an infinite generator to eventlet (or gevent)?

description: Feed an infinite generator to eventlet (or gevent)


code:
q = db.Query(Channel)
q.filter("name =", name)
entities = q.fetch(100) # The number of entities you want to be returned
if entries:
    db.delete(entries)

rawDescription: GAE - get() entity by property?

description: GAE - get() entity by property


code:
first_time = None
while first_time is None:
  first_line = file.readline()
  if first_line.find('Chain') != -1:
     first_time = int(searchforfirsttime.group(2))

rawDescription: Skip a blank line when reading a file in python using readline


code:
from models import Student
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin

admin.site.register(Student)

admin.site.unregister(User)

class MyUserAdmin(UserAdmin):
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'email', 'first_name', 'last_name', 'password1', 'password2')}
        ),
    )

admin.site.register(User, MyUserAdmin)

rawDescription: Auth User model in admin page

description: Auth User model in admin page


code:
import wx
import sys
from wx import glcanvas
from OpenGL.GL import *
from OpenGL.GLUT import *

from numpy import arange, sin, pi
import matplotlib
matplotlib.use('WXAgg')

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
from matplotlib.figure import Figure

class CanvasPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

    def draw(self):
        t = arange(0.0, 3.0, 0.01)
        s = sin(2 * pi * t)
        self.axes.plot(t, s)

class MyCanvasBase(glcanvas.GLCanvas):
    def __init__(self, parent):
        glcanvas.GLCanvas.__init__(self, parent, -1)
        self.init = False
        self.context = glcanvas.GLContext(self)

        # initial mouse position
        self.lastx = self.x = 30
        self.lasty = self.y = 30
        self.size = None
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)
        self.Bind(wx.EVT_MOTION, self.OnMouseMotion)

    def OnEraseBackground(self, event):
        pass # Do nothing, to avoid flashing on MSW.

    def OnSize(self, event):
        wx.CallAfter(self.DoSetViewport)
        event.Skip()

    def DoSetViewport(self):
        size = self.size = self.GetClientSize()
        self.SetCurrent(self.context)
        glViewport(0, 0, size.width, size.height)

    def OnPaint(self, event):
        dc = wx.PaintDC(self)
        self.SetCurrent(self.context)
        if not self.init:
            self.InitGL()
            self.init = True
        self.OnDraw()

    def OnMouseDown(self, evt):
        self.CaptureMouse()
        self.x, self.y = self.lastx, self.lasty = evt.GetPosition()

    def OnMouseUp(self, evt):
        self.ReleaseMouse()

    def OnMouseMotion(self, evt):
        if evt.Dragging() and evt.LeftIsDown():
            self.lastx, self.lasty = self.x, self.y
            self.x, self.y = evt.GetPosition()
            self.Refresh(False)

class CubeCanvas(MyCanvasBase):
    def InitGL(self):
        # set viewing projection
        glMatrixMode(GL_PROJECTION)
        glFrustum(-0.5, 0.5, -0.5, 0.5, 1.0, 3.0)

        # position viewer
        glMatrixMode(GL_MODELVIEW)
        glTranslatef(0.0, 0.0, -2.0)

        # position object
        glRotatef(self.y, 1.0, 0.0, 0.0)
        glRotatef(self.x, 0.0, 1.0, 0.0)

        glEnable(GL_DEPTH_TEST)
        glEnable(GL_LIGHTING)
        glEnable(GL_LIGHT0)

    def OnDraw(self):
        # clear color and depth buffers
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # draw six faces of a cube
        glBegin(GL_QUADS)
        glNormal3f( 0.0, 0.0, 1.0)
        glVertex3f( 0.5, 0.5, 0.5)
        glVertex3f(-0.5, 0.5, 0.5)
        glVertex3f(-0.5,-0.5, 0.5)
        glVertex3f( 0.5,-0.5, 0.5)

        glNormal3f( 0.0, 0.0,-1.0)
        glVertex3f(-0.5,-0.5,-0.5)
        glVertex3f(-0.5, 0.5,-0.5)
        glVertex3f( 0.5, 0.5,-0.5)
        glVertex3f( 0.5,-0.5,-0.5)

        glNormal3f( 0.0, 1.0, 0.0)
        glVertex3f( 0.5, 0.5, 0.5)
        glVertex3f( 0.5, 0.5,-0.5)
        glVertex3f(-0.5, 0.5,-0.5)
        glVertex3f(-0.5, 0.5, 0.5)

        glNormal3f( 0.0,-1.0, 0.0)
        glVertex3f(-0.5,-0.5,-0.5)
        glVertex3f( 0.5,-0.5,-0.5)
        glVertex3f( 0.5,-0.5, 0.5)
        glVertex3f(-0.5,-0.5, 0.5)

        glNormal3f( 1.0, 0.0, 0.0)
        glVertex3f( 0.5, 0.5, 0.5)
        glVertex3f( 0.5,-0.5, 0.5)
        glVertex3f( 0.5,-0.5,-0.5)
        glVertex3f( 0.5, 0.5,-0.5)

        glNormal3f(-1.0, 0.0, 0.0)
        glVertex3f(-0.5,-0.5,-0.5)
        glVertex3f(-0.5,-0.5, 0.5)
        glVertex3f(-0.5, 0.5, 0.5)
        glVertex3f(-0.5, 0.5,-0.5)
        glEnd()

        if self.size is None:
            self.size = self.GetClientSize()
        w, h = self.size
        w = max(w, 1.0)
        h = max(h, 1.0)
        xScale = 180.0 / w
        yScale = 180.0 / h
        glRotatef((self.y - self.lasty) * yScale, 1.0, 0.0, 0.0);
        glRotatef((self.x - self.lastx) * xScale, 0.0, 1.0, 0.0);

        self.SwapBuffers()

#----------------------------------------------------------------------
class RunDemoApp(wx.App):
    def __init__(self):
        wx.App.__init__(self, redirect=False)

    def OnInit(self):
        canvasClass = eval('CubeCanvas')

        cx = 0

        frame = wx.Frame(None, -1, 'CubeCanvas', size=(400,400), pos=(cx,400))

        # adding panel with sizer for both canvas
        panel = wx.Panel(frame, -1)

        self.sizer = wx.BoxSizer(wx.HORIZONTAL)

        # adding first canvas
        canvas1 = canvasClass(panel) # CubeCanvas(frame) or ConeCanvas(frame); frame passed to         MyCanvasBase
        self.sizer.Add(canvas1, 1, wx.LEFT | wx.TOP | wx.GROW)

        # adding second canvas
        self.canvas = CanvasPanel(panel)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)

        panel.SetSizer(self.sizer)
        panel.Fit()

        frame.Show(True)

        self.frame = frame
        return True

    def OnExitApp(self, evt):
        self.frame.Close(True)

    def OnCloseFrame(self, evt):
        if hasattr(self, "window") and hasattr(self.window, "ShutdownDemo"):
            self.window.ShutdownDemo()
        evt.Skip()

app = RunDemoApp()
app.MainLoop()

rawDescription: how to combine wxPython, matplotlib and Pyopengl

description: Combine wxPython, matplotlib and Pyopengl


code:
from itertools import groupby
from functools import partial

key = partial(re.match, r'Clutch\d\d\d')

with open('foo.txt') as f:
    groups = (', '.join(map(str.strip, g)) for k, g in groupby(f, key=key))
    pprint(dict(zip(*[iter(groups)]*2)))

{'Clutch001': 'Albino X Pastel, Bumble Bee X Albino Lesser',
 'Clutch002': 'Bee X Fire Bee, Albino Cinnamon X Albino, Mojave X Bumble Bee',
 'Clutch003': 'Black Pastel X Banana Ghost Lesser'}

rawDescription: Parsing file into a dictionary in python


rawDescription: Pythonic way of converting dict of lists to list of dicts


code:
from pdfminer.pdfinterp import PDFResourceManager, process_pdf
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from cStringIO import StringIO

def convert_pdf(path):

    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)

    fp = file(path, 'rb')
    process_pdf(rsrcmgr, device, fp)
    fp.close()
    device.close()

    str = retstr.getvalue()
    retstr.close()
    return str

rawDescription: How do I use pdfminer as a library

description: Use pdfminer as a library


code:
for src in sources:
    self.feedback.append('Copying: %s' % src)
    QtGui.qApp.processEvents()
    shutil.copy(src, dst)

rawDescription: PyQt. Show OS process as I go?

description: PyQt. Show OS process as I go


code:
import cPickle
import zlib

# Compress:
compressed = zlib.compress(cPickle.dumps(obj))

# Get it back:
obj = cPickle.loads(zlib.decompress(compressed))

rawDescription: Compress Python Object in Memory

description: Compress Python Object in Memory


rawDescription: Comparing two numpy arrays and removing elements


code:
from collections import Sequence, Mapping, Set
import numpy as np

def nested_equal(a, b):
    """
    Compare two objects recursively by element, handling numpy objects.

    Assumes hashable items are not mutable in a way that affects equality.
    """
    # Use __class__ instead of type() to be compatible with instances of
    # old-style classes.
    if a.__class__ != b.__class__:
        return False

    # for types that implement their own custom strict equality checking
    seq = getattr(a, "seq", None)
    if seq and callable(seq):
        return seq(b)

    # Check equality according to type type [sic].
    if isinstance(a, basestring):
        return a == b
    if isinstance(a, np.ndarray):
        return np.all(a == b)
    if isinstance(a, Sequence):
        return all(nested_equal(x, y) for x, y in zip(a, b))
    if isinstance(a, Mapping):
        if set(a.keys()) != set(b.keys()):
            return False
        return all(nested_equal(a[k], b[k]) for k in a.keys())
    if isinstance(a, Set):
        return a == b
    return a == b

rawDescription: Best Practice for Equality in Python

description: Best Practice for Equality in Python


code:
from matplotlib.figure import Figure as F
from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FC
from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NT

import gtk

fig = F()
ax = fig.add_subplot(111)
ax.plot(range(10),range(10))

main = gtk.Window()
main.set_default_size(800,600)
main.connect("destroy", gtk.main_quit)
box = gtk.VBox()
main.add(box)

fc = FC(fig)
box.pack_start(fc)
nt = NT(fc, main)
box.pack_start(nt, expand=False, fill=False)
main.show_all()
gtk.main()

rawDescription: matplotlib figure in GTK with tools

description: Matplotlib figure in GTK with tools


code:
import numpy
from matplotlib import pyplot
pyplot.imshow(numpy.random.random( (100,100) ), extent = [0,50, 100, 0] )
cax = pyplot.axes([0.80, 0.1, 0.04, 0.8])
pyplot.colorbar(cax=cax)
pyplot.show()

rawDescription: Matplotlib: Using a colorbar in conjunction with the extent keyword produces off-center images in figure window


code:
def mark_code_ranges(node, source):
    """
    Node is an AST, source is corresponding source as string.
    Function adds recursively attributes end_lineno and end_col_offset to each node
    which has attributes lineno and col_offset.
    """

    NON_VALUE_KEYWORDS = set(keyword.kwlist) - {'False', 'True', 'None'}

    def _get_ordered_child_nodes(node):
        if isinstance(node, ast.Dict):
            children = []
            for i in range(len(node.keys)):
                children.append(node.keys[i])
                children.append(node.values[i])
            return children
        elif isinstance(node, ast.Call):
            children = [node.func] + node.args

            for kw in node.keywords:
                children.append(kw.value)

            if node.starargs != None:
                children.append(node.starargs)
            if node.kwargs != None:
                children.append(node.kwargs)

            children.sort(key=lambda x: (x.lineno, x.col_offset))
            return children
        else:
            return ast.iter_child_nodes(node)

    def _fix_triple_quote_positions(root, all_tokens):
        """
        http://bugs.python.org/issue18370
        """
        string_tokens = list(filter(lambda tok: tok.type == token.STRING, all_tokens))

        def _fix_str_nodes(node):
            if isinstance(node, ast.Str):
                tok = string_tokens.pop(0)
                node.lineno, node.col_offset = tok.start

            for child in _get_ordered_child_nodes(node):
                _fix_str_nodes(child)

        _fix_str_nodes(root)

        # fix their erroneous Expr parents
        for node in ast.walk(root):
            if ((isinstance(node, ast.Expr) or isinstance(node, ast.Attribute))
                and isinstance(node.value, ast.Str)):
                node.lineno, node.col_offset = node.value.lineno, node.value.col_offset

    def _fix_binop_positions(node):
        """
        http://bugs.python.org/issue18374
        """
        for child in ast.iter_child_nodes(node):
            _fix_binop_positions(child)

        if isinstance(node, ast.BinOp):
            node.lineno = node.left.lineno
            node.col_offset = node.left.col_offset

    def _extract_tokens(tokens, lineno, col_offset, end_lineno, end_col_offset):
        return list(filter((lambda tok: tok.start[0] >= lineno
                                   and (tok.start[1] >= col_offset or tok.start[0] > lineno)
                                   and tok.end[0] <= end_lineno
                                   and (tok.end[1] <= end_col_offset or tok.end[0] < end_lineno)
                                   and tok.string != ''),
                           tokens))

    def _mark_code_ranges_rec(node, tokens, prelim_end_lineno, prelim_end_col_offset):
        """
        Returns the earliest starting position found in given tree,
        this is convenient for internal handling of the siblings
        """

        # set end markers to this node
        if "lineno" in node._attributes and "col_offset" in node._attributes:
            tokens = _extract_tokens(tokens, node.lineno, node.col_offset, prelim_end_lineno, prelim_end_col_offset)
            #tokens =
            _set_real_end(node, tokens, prelim_end_lineno, prelim_end_col_offset)

        # mark its children, starting from last one
        # NB! need to sort children because eg. in dict literal all keys come first and then all values
        children = list(_get_ordered_child_nodes(node))
        for child in reversed(children):
            (prelim_end_lineno, prelim_end_col_offset) = \
                _mark_code_ranges_rec(child, tokens, prelim_end_lineno, prelim_end_col_offset)

        if "lineno" in node._attributes and "col_offset" in node._attributes:
            # new "front" is beginning of this node
            prelim_end_lineno = node.lineno
            prelim_end_col_offset = node.col_offset

        return (prelim_end_lineno, prelim_end_col_offset)

    def _strip_trailing_junk_from_expressions(tokens):
        while (tokens[-1].type not in (token.RBRACE, token.RPAR, token.RSQB,
                                      token.NAME, token.NUMBER, token.STRING,
                                      token.ELLIPSIS)
                    and tokens[-1].string not in ")}]"
                    or tokens[-1].string in NON_VALUE_KEYWORDS):
            del tokens[-1]

    def _strip_trailing_extra_closers(tokens, remove_naked_comma):
        level = 0
        for i in range(len(tokens)):
            if tokens[i].string in "({[":
                level += 1
            elif tokens[i].string in ")}]":
                level -= 1

            if level == 0 and tokens[i].string == "," and remove_naked_comma:
                tokens[:] = tokens[0:i]
                return

            if level < 0:
                tokens[:] = tokens[0:i]
                return

    def _set_real_end(node, tokens, prelim_end_lineno, prelim_end_col_offset):
        # prelim_end_lineno and prelim_end_col_offset are the start of
        # next positioned node or end of source, ie. the suffix of given
        # range may contain keywords, commas and other stuff not belonging to current node

        # Function returns the list of tokens which cover all its children

        if isinstance(node, _ast.stmt):
            # remove empty trailing lines
            while (tokens[-1].type in (tokenize.NL, tokenize.COMMENT, token.NEWLINE, token.INDENT)
                   or tokens[-1].string in (":", "else", "elif", "finally", "except")):
                del tokens[-1]

        else:
            _strip_trailing_extra_closers(tokens, not isinstance(node, ast.Tuple))
            _strip_trailing_junk_from_expressions(tokens)

        # set the end markers of this node
        node.end_lineno = tokens[-1].end[0]
        node.end_col_offset = tokens[-1].end[1]

        # Try to peel off more tokens to give better estimate for children
        # Empty parens would confuse the children of no argument Call
        if ((isinstance(node, ast.Call))
            and not (node.args or node.keywords or node.starargs or node.kwargs)):
            assert tokens[-1].string == ')'
            del tokens[-1]
            _strip_trailing_junk_from_expressions(tokens)
        # attribute name would confuse the "value" of Attribute
        elif isinstance(node, ast.Attribute):
            if tokens[-1].type == token.NAME:
                del tokens[-1]
                _strip_trailing_junk_from_expressions(tokens)
            else:
                raise AssertionError("Expected token.NAME, got " + str(tokens[-1]))
                #import sys
                #print("Expected token.NAME, got " + str(tokens[-1]), file=sys.stderr)

        return tokens

    all_tokens = list(tokenize.tokenize(io.BytesIO(source.encode('utf-8')).readline))
    _fix_triple_quote_positions(node, all_tokens)
    _fix_binop_positions(node)
    source_lines = source.split("\n")
    prelim_end_lineno = len(source_lines)
    prelim_end_col_offset = len(source_lines[len(source_lines)-1])
    _mark_code_ranges_rec(node, all_tokens, prelim_end_lineno, prelim_end_col_offset)

rawDescription: How to get source corresponding to a Python AST node?

description: Get source corresponding to a Python AST node


code:
from flask import Flask
from os.path import join

app = Flask(__name__)

def url_for_static(filename):
    root = app.config.get('STATIC_ROOT', '')
    return join(root, filename)

rawDescription: Flask: Static files in subdirectories

description: Flask: Static files in subdirectories


code:
class Spheres(object):

    def __init__(self):
       self._dict = dict()

    def volumes(self, radii=None):
        if radii is None:
            radii = self._dict['radii']
        return (4/3) * math.pi *radii**3

rawDescription: What is the right way to handle "key or value" arguments to a dict?


code:
GZIP_CONTENT_TYPES = (
    'text/css',
    'application/javascript',
    'application/x-javascript',
    'text/javascript'
)

rawDescription: Django compressor using gzip to serve javascript


code:
response = HttpResponse(content_type = mimetype, status=206)
response['Content-Disposition'] = "attachment; filename=%s" % \
                                         (fileModel.FileName)
response['Accept-Ranges'] = 'bytes'
response['X-Accel-Redirect'] = settings.MEDIA_URL + '/' + fileModel.FileData.MD5
response['X-Accel-Buffering'] = 'no'
return response

rawDescription: Stream music with byte range requests with Django + nginx


code:
@app.route('/files/<filename>/download')
def download_file(filename):
    file_path = derive_filepath_from_filename(filename)
    file_handle = open(file_path, 'r')
    @after_this_request
    def remove_file(response):
        os.remove(file_path)
        return response
    return send_file(file_handle)

rawDescription: Flask- Deleting uploads after they have been downloaded


code:
mode = lambda ts: ts.value_counts(sort=True).index[0]
cols = df['X'].value_counts().index
df.groupby('X')[['Y', 'Z']].agg(mode).T.reindex(columns=cols)

rawDescription: Formatting a Pivot Table in Python

description: Formatting a Pivot Table in Python


code:
suite = unittest.TestSuite()

def test_main(self):
    self.assertEquals(self.result, self.expected_output)

def test_method(self):
    """
    """
    # -- code to get tests objects to have all .tests content
    for index, fname in tests.items():
        # get result and expected_output value
        obj = type('Test', (unittest.TestCase,), {'test_main': test_main,
                  'result':result, 'expected_output':expected_output})

        suite.addTest(obj('test_main'))

unittest.TextTestRunner(verbosity=2).run(suite)

rawDescription: Running all test files in python from one function using "assert" without exiting "for loop" on test failure


rawDescription: Generating JSON dynamically with Beautiful Soup


code:
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2),
                      np.arange(-0.8, 1, 0.2),
                      np.arange(-0.8, 1, 0.8))

u = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z)
v = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z)
w = (np.sqrt(2.0 / 3.0) * np.cos(np.pi * x) * np.cos(np.pi * y) *
     np.sin(np.pi * z))

q = ax.quiver(x, y, z, u, v, w, length=0.1, cmap='Reds', lw=2)
q.set_array(np.random.rand(np.prod(x.shape)))

plt.show()

rawDescription: Adding colors to a 3d quiver plot in matplotlib


code:
def convert(self, saType):
    type = "Unknown"
    if isinstance(saType,sqlalchemy.types.INTEGER):
        type = "Integer"
    elif isinstance(saType,sqlalchemy.types.VARCHAR):
        type = "String"
    elif isinstance(saType,sqlalchemy.types.DATE):
        type = "Date"
    elif isinstance(saType,sqlalchemy.dialects.mysql.base._FloatType):
        type = "Double"
    return type

rawDescription: Easy convert betwen SQLAlchemy columns and data types?


code:
def pit(p, q, r):
    return min(A[p] - A[q], A[r] - A[q])

rawDescription: How to simplify lambda to general python

description: Simplify lambda to general python


code:
pd.Series(conditions)
(df == pd.Series(conditions))
(df == pd.Series(conditions)).all(axis=1)
df[(df == pd.Series(conditions)).all(axis=1)]

rawDescription: get subsection of df based on multiple conditions

description: Get subsection of df based on multiple conditions


code:
text = 'abcdefa'
pattern = re.compile('a|c')
[(m.group(), m.start()) for m in pattern.finditer(text)]

rawDescription: How to get a list of character positions in Python?

description: Get a list of character positions in Python


code:
from rpy2.robjects.packages import importr

MASS = importr('MASS')

# the function is now at MASS.fitdistr

rawDescription: fitdistr in rpy2

description: Fitdistr in rpy2


code:
import re
from bs4 import BeautifulSoup

svg = open("/path/to/file.svg", "r").read()
soup = BeautifulSoup(svg)
paths = soup.findAll("path")

raphael = []

for p in paths:
    splitData = p['d'].split(",")
    for line in splitData:
        # Remove ".000000" part
        line = re.sub("\.\d*", "", line)
        line = line.replace(" ", "")
        raphael.append(line)

d = ",\n".join(raphael)

rawDescription: Python- Remove characters then join into string


code:
import gevent
from gevent import socket
urls = ['www.google.com', 'www.example.com', 'www.python.org']
jobs = [gevent.spawn(socket.gethostbyname, url) for url in urls]
gevent.joinall(jobs, timeout=2)
[job.value for job in jobs]

rawDescription: Concurrently hit URLS and process results


code:
import os
path = 'THE PATH OF THE DIRECTORY YOU WANT TO FETCH'
os.statvfs(path)

rawDescription: Disk usage of a directory in Python

description: Disk usage of a directory in Python


code:
class MySub1(MySuper):
    pass

MySub1._meta.get_field('some_attr').help_text = 'sub1 help text'

class MySub2(MySuper):
    pass

MySub2._meta.get_field('some_attr').help_text = 'sub2 help text'

rawDescription: Adding help_text in a superclass attribute


code:
title = u'%s.html' % t.name.decode('utf8')  # decode from UTF8, use a unicode literal
with file(title, 'wb') as fpo:
    fpo.write('<meta charset="utf-8">\n')
    message = 'שלום לך %s' % t.name
    fpo.write('%s\n' % message)

rawDescription: How to create a file with a hebrew name using python 2.7?

description: Create a file with a hebrew name using python 2.7


rawDescription: Loop in a REGEX search

description: Loop in a REGEX search


code:
from eve.methods.get import get_internal

payload = get_internal(endpoint)

rawDescription: Querying my Eve API from my Flask code

description: Querying my Eve API from my Flask code


code:
from threading import Thread
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/plain")
        self.end_headers()
        self.wfile.write("Hello World!")

class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
    pass

def serve_on_port(port):
    server = ThreadingHTTPServer(("localhost",port), Handler)
    server.serve_forever()

Thread(target=serve_on_port, args=[1111]).start()
serve_on_port(2222)

rawDescription: How do I write a python HTTP server to listen on multiple ports?

description: Write a python HTTP server to listen on multiple ports


code:
def l2_norm(sparse_csc_matrix):
    # first, I convert the csc_matrix to csr_matrix which is done in linear time
    norm = sparse_csc_matrix.tocsr(copy=True)

    # compute the inverse of l2 norm of non-zero elements
    norm.data **= 2
    norm = norm.sum(axis=1)
    n_nzeros = np.where(norm > 0)
    norm[n_nzeros] = 1.0 / np.sqrt(norm[n_nzeros])
    norm = np.array(norm).T[0]

    # modify sparse_csc_matrix in place
    sp.sparsetools.csr_scale_rows(sparse_csc_matrix.shape[0],
                                  sparse_csc_matrix.shape[1],
                                  sparse_csc_matrix.indptr,
                                  sparse_csc_matrix.indices,
                                  sparse_csc_matrix.data, norm)

rawDescription: L2 normalization of rows in scipy sparse matrix


code:
from feedfinder2 import find_feeds
import feedparser

feeds = find_feeds('http://timbroder.com')

feeds
#[u'http://feeds.feedburner.com/timbroder']

d = feedparser.parse(feeds[0])
d['feed']['title']
#u'timbroder.com'

rawDescription: Get autodiscovery links with Universal feed parser (feedparser)


code:
from scipy.fftpack import dct
import numpy as np

a = np.random.rand(512, 512, 3)

b = a.reshape(64, 8, 64, 8, 3)

res = dct(dct(b, axis=1), axis=3)

rawDescription: How to apply functions to numpy 8 * 8 blocks?

description: Apply functions to numpy 8 * 8 blocks


code: {{ some_list|slice:":2" }}

rawDescription: Control in for loop in Django template

description: Control in for loop in Django template


code: q1 = [x + 1800 for x in q]

rawDescription: How to keep a list static in Python?

description: Keep a list static in Python


code:
_NUMERALS = '0123456789abcdefABCDEF'
_HEXDEC = {v: int(v, 16) for v in (x+y for x in _NUMERALS for y in _NUMERALS)}
LOWERCASE, UPPERCASE = 'x', 'X'

def rgb(triplet):
    return _HEXDEC[triplet[0:2]], _HEXDEC[triplet[2:4]], _HEXDEC[triplet[4:6]]

def triplet(rgb, lettercase=LOWERCASE):
    return format(rgb[0]<<16 | rgb[1]<<8 | rgb[2], '06'+lettercase)

if __name__ == '__main__':
    print('{}, {}'.format(rgb('aabbcc'), rgb('AABBCC')))
    # -> (170, 187, 204), (170, 187, 204)

    print('{}, {}'.format(triplet((170, 187, 204)),
                          triplet((170, 187, 204), UPPERCASE)))
    # -> aabbcc, AABBCC

    print('{}, {}'.format(rgb('aa0200'), rgb('AA0200')))
    # -> (170, 2, 0), (170, 2, 0)

    print('{}, {}'.format(triplet((170, 2, 0)),
                          triplet((170, 2, 0), UPPERCASE)))
    # -> aa0200, AA0200

rawDescription: How do I convert a hex triplet to an RGB tuple and back?

description: Convert a hex triplet to an RGB tuple and back


code:
sub_process=subprocess.Popen(["ssh", "hostname", "df -h"], stdout=subprocess.PIPE)
stdout_file=sub_process.stdout
first_line=stdout_file.readline()

rawDescription: ssh for df -h using python to display selected information only

description: Ssh for df -h using python to display selected information only


code:
def ewma(l, queries, a=0.01):
  def decay(t0, x, t1, a):
    from math import pow
    return pow((1-a), (t1-t0))*x

  assert l == sorted(l)
  assert queries == sorted(queries)

  samples = []
  try:
    t0, x0 = (0.0, 0.0)
    it = iter(queries)
    q = it.next()-1.0

    for t1 in l:
      # new value is decayed previous value, plus a
      x1 = decay(t0, x0, t1, a) + a
      # take care of all queries between t0 and t1
      while q < t1:
        samples.append(decay(t0, x0, q, a))
        q = it.next()-1.0
      # take care of all queries equal to t1
      while q == t1:
        samples.append(x1)
        q = it.next()-1.0
      # update t0, x0
      t0, x0 = t1, x1

    # take care of any remaining queries
    while True:
      samples.append(decay(t0, x0, q, a))
      q = it.next()-1.0
  except StopIteration:
    return samples

rawDescription: Query long lists

description: Query long lists


code:
def remove_module_docstring(app, what, name, obj, options, lines):
    if what == "module" and name == "yourmodule":
        del lines[:]

def setup(app):
    app.connect("autodoc-process-docstring", remove_module_docstring)

rawDescription: Exclude module docstring in autodoc

description: Exclude module docstring in autodoc


code:
lower_limit = 0
higher_limit = 200
step_size = 5
i = 0

while lower_limit <= i < higher_limit:
    # do something

    i = i + step_size

    higher_limit = higher_limit + randint(0, 5)

rawDescription: Change Python for loop range (higher limit) at runtime


code:
import subprocess
import sys

params = dict()
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
params['startupinfo'] = startupinfo

p = subprocess.Popen("cmd.exe", **params)

rawDescription: Module subprocess has no attribute 'STARTF_USESHOWWINDOW'


rawDescription: SQLalchemy issue recovering binary data from MSSQL Column


code:
def find_pit(seq):
    first = 0
    last = len(seq) - 1
    origlast = last
    mid = 0
    if len(seq) == 1 :
        return 0
    else:
        #change next line to use logical and
        while first <= last and mid < last :
            mid = (first + last) // 2
            #change next line to use logical and
            if seq[mid] <= seq[mid - 1] and seq[mid] <= seq[mid + 1]:
                return mid
            else:
                if seq[mid] > seq[mid - 1]:
                    last = mid
                else:
                    first = mid
    if seq[0] <= seq[1]:
        return 0
    elif seq[origlast] <= seq[origlast-1]:
        return (len(seq) - 1)

print(find_pit([0,1]))
print(find_pit([5, 4, 3, 6, 7]))

rawDescription: Binary Searching in Python

description: Binary Searching in Python


code:
import sys
sys.stdout.write("Status: 200 OK\n")
sys.stdout.write("Content-Type: text/plain\n")
sys.stdout.write("\n")
sys.stdout.write("This is the text that will be in responseText")

rawDescription: How Do I Send a Response to a POST Request with Python?


code: setup_http_proxy("THE_ADRESS", THE_PORT_NUMBER) # address of the Proxy, port the Proxy is listening on

rawDescription: python tcp over http emulation

description: Python tcp over http emulation


code: track_converted = win32com.client.CastTo(tracks[1], "IITFileOrCDTrack")

rawDescription: iTunes COM - How to acess Lyrics

description: ITunes COM - How to acess Lyrics


code: df.columns = [str(col) + '_x' for col in df.columns]

rawDescription: How to add a suffix to each column name?

description: Add a suffix to each column name