code:
# here and below assume that strings are byte-oriented strings.
# In Python 3, where strings are char-oriented, `str.encode()` and `str.decode()` might be in use

def msw_nonblocking_raw_input(limit=100):
    collected = ''
    for i in range(1, limit): # don't let a user block the program by pressing a key permanently
         if not msvcrt.kbhit():
             break
         collected += msvcrt.getche()
    logging.debug('user input [%s]' % collected)
    return collected

def socket_nonblocking_input(sock):
    try:
         msg = sock.recv(4096)
    except socket.error as e:
        err = e.args[0]
        if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
            return ''
        else:
            # a "real" error occurred
            raise
    # got the message. If it's empty, EOF occured
    logging.debug('server sent us [%s]' % msg)
    if not msg:
        sys.exit(0) # perhaps a more graceful shutdown is required...
    return msg

def socket_nonblocking_output(sock, msg):
    try:
        res = sock.send(msg)
    except socket.error as e:
        err = e.args[0]
        if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
            return msg
        else:
            # a "real" error occurred
            raise
    # If res is 0, then EOF occured
    if not res:
        sys.exit(0) # perhaps a more graceful shutdown is required...
    logging.debug("we have sent %d bytes out of %d" % (res, len(msg)))
    return msg[res:] # return the unsent tail of the message

# the main cycle
data_read = ''
data_to_write = ''
timeout = 1.000 # 1 second
client_socket.setblocking(0) # put the socket into the non-blocking mode
while True:
    sockets_to_write = (client_socket,) if data_to_write else ()
    (to_read, to_write, exceptional) = select((client_socket,), sockets_to_write, (), timeout)
    if to_read:
        data_read = socket_nonblocking_input(to_read[0])
        # technically sys.stdout could also block (e.g. being piped or simply in a slow terminal) but for the sake of simplicity, don't bother ourselves.
        if data_read:
            sys.stdout.write(data_read)
    if to_write:
        data_to_write = socket_nonblocking_output(to_write[0], data_to_write)

    data_to_write += msw_nonblocking_raw_input()

rawDescription: python chat with sockets using select model

description: Python chat with sockets using select model


code:
from pygit2 import clone_repository
repo_url = 'git://github.com/libgit2/pygit2.git'
repo_path = '/path/to/create/repository'
repo = clone_repository(repo_url, repo_path) # Clones a non-bare repository
repo = clone_repository(repo_url, repo_path, bare=True) # Clones a bare repository

rawDescription: Cloning a private Github repo using a script


code: user = bundle.request.user

rawDescription: Get authenticated user in django-tastypie


code:
from gi.repository import Gtk, GObject, Vte
#GObject is not required. I just import it everywhere just in case.
#Gtk, Vte, and GLib are required.
from gi.repository import GLib
import os
#os.environ['HOME'] helps to keep from hard coding the home string.
#os is not required unless you want that functionality.

class TheWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="inherited cell renderer")
        self.set_default_size(600, 300)
        self.terminal     = Vte.Terminal()
        self.terminal.fork_command_full(
                Vte.PtyFlags.DEFAULT, #default is fine
                os.environ['HOME'], #where to start the command?
                ["/bin/sh"], #where is the emulator?
                [], #it's ok to leave this list empty
                GLib.SpawnFlags.DO_NOT_REAP_CHILD,
                None, #at least None is required
                None,
                )
        #Set up a button to click and run a demo command
        self.button = Gtk.Button("Do The Command")
        #To get the command to automatically run
        #a newline(\n) character is used at the end of the
        #command string.
        self.command = "echo \"Sending this command to a virtual terminal.\"\n"
        command = Gtk.Label("The command: "+self.command)
        self.button.connect("clicked", self.InputToTerm)
        #end demo command code

        #set up the interface
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        box.pack_start(self.button, False, True, 0)
        box.pack_start(command, False, True, 1)
        #a scroll window is required for the terminal
        scroller = Gtk.ScrolledWindow()
        scroller.set_hexpand(True)
        scroller.set_vexpand(True)
        scroller.add(self.terminal)
        box.pack_start(scroller, False, True, 2)
        self.add(box)

    def InputToTerm(self, clicker):
        #get the command when the button is clicked
        length = len(self.command)
        #A length is not required but is the easiest mechanism.
        #Otherwise the command must be null terminated.
        #Feed the command to the terminal.
        self.terminal.feed_child(self.command, length)

win = TheWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

rawDescription: How to send commands to pygobject virtual terminal?

description: Send commands to pygobject virtual terminal


code:
import pdb
pdb.set_trace()

rawDescription: How do I programmatically stop execution of a python script, without closing python and maintaining the variables?

description: Programmatically stop execution of a python script, without closing python and maintaining the variables


code:
A = np.random.random_integers(0,10,(2,4,3))
A
np.all(A < 5, axis=-1)  # I chose a threshold of 5
A[np.all(A < 5, axis=-1)] = 100  # and set the values to 100 to easily show what has changed
A

rawDescription: Flatten image background using OpenCV/Numpy


code:
from lxml import etree
doc = etree.parse('in.html')
names = {'cas':'http:///text/cas.ecore', 'xmi': 'http://blahblah'}
doc.xpath('//cas:Sofa[@xmi:id="63"]', namespaces=names)
doc.xpath('//cas:Sofa[@xmi:id="63"]/@String', namespaces=names)
doc.xpath('//cas:Sofa[@xmi:id="72" and @ID="Third"]/@String', namespaces=names)

rawDescription: Python libxml2: querying xml using xpath


code:
from urllib import quote

op1, op2, operator = '8', '3', '+'
url = 'http://localhost:8184/messenger/webapi/Calculator/{}/{}/{}'.format(
    quote(op1), quote(op2), quote(operator))

rawDescription: Passing input to URL path parameter from variable - Python


code:
# app/util.py

from flask import request # <- added

from functools import wraps
from models import data

# custom decorator to validate symbol

def symbol_valid(func):
    @wraps(func)
    def decorated_function(*args, **kwargs): # <- removed symbol arg
        symbol = request.form['symbol'] # <- paramter is in the request object
        if not data.validate_symbol(symbol):
            return jsonify({'status': 'fail'})
        return func(*args, **kwargs)
    return symbol_valid

rawDescription: Flask pass POST parameters to custom decorator


code:
folders = [name for name in os.listdir(".")
           if os.path.isdir(name) and name[0] != '_' and len(name) <= 6]

rawDescription: In python exclude folders which start with underscore or more than six characters long


code:
position = 1
field = "tags"
# see http://stackoverflow.com/a/15798087/4249707
# for "not_existent_field" explanation
results = conn.find(
  {}, {field:{"$slice": [position,1]}, "_id": 0, "not_existent_field": 1}
)
distinct_results = {d[field][0] for d in results if field in d and d[field]}

rawDescription: Getting a distinct aggregation elements of array by index


code:
def receiving(ser):
    global last_received

    buffer_string = ''
    while True:
        buffer_string = buffer_string + ser.read(ser.inWaiting())
        if '\n' in buffer_string:
            lines = buffer_string.split('\n') # Guaranteed to have at least 2 entries
            last_received = lines[-2]
            #If the Arduino sends lots of empty lines, you'll lose the
            #last filled line, so you could make the above statement conditional
            #like so: if lines[-2]: last_received = lines[-2]
            buffer_string = lines[-1]

rawDescription: pyserial - How to read the last line sent from a serial device

description: Pyserial - How to read the last line sent from a serial device


code:
class Foo(object):
    def __init__(self, value):
        self.value = value
    def _repr_html_(self):
        return "
This is the {0} object!
".format(self.value)

class Wrapper(object):
    def __init__(self, foo1, foo2):
        self.foo1 = foo1
        self.foo2 = foo2

    def _repr_html_(self):
        return """

Foo1

        {0}

Foo2

        {1}
        """.format(self.foo1._repr_html_(), self.foo2._repr_html_())

rawDescription: IPython _repr_html_

description: IPython _repr_html_


code:
import wx

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        self.panel = wx.Panel(self)
        self.button = wx.Button(self.panel, label="New")
        self.button.Bind(wx.EVT_BUTTON, self.OnButton)
        self.buttons = []
        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.button)
        self.panel.SetSizerAndFit(self.sizer)
        self.Show()

    def OnButton(self, e):
        button = wx.Button(self.panel, label=str(len(self.buttons)))
        self.buttons.append(button)
        self.sizer.Insert(len(self.sizer.Children) - 1, button)
        self.sizer.Layout()

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: Calling wxSizer.Insert()  hides item

description: Calling wxSizer.Insert()  hides item


code:
def accumulate(combiner, start, n, term):
    """Return the result of combining the first n terms in a sequence."""
    total = term(start)
    current = start
    while current < n:
        total = combiner(total, term(current))
        current += 1
    return total

rawDescription: Python: Compositions of functions of multiple arguments /without/ functools


code:
"""UWSGI websocket proxy."""
from urllib.parse import urlparse, urlunparse
import logging
import time

import uwsgi
from ws4py import WS_VERSION
from ws4py.client import WebSocketBaseClient

#: HTTP headers we need to proxy to upstream websocket server when the Connect: upgrade is performed
CAPTURE_CONNECT_HEADERS = ["sec-websocket-extensions", "sec-websocket-key", "origin"]

logger = logging.getLogger(__name__)

class ProxyClient(WebSocketBaseClient):
    """Proxy between upstream WebSocket server and downstream UWSGI."""

    @property
    def handshake_headers(self):
        """
        List of headers appropriate for the upgrade
        handshake.
        """
        headers = [
            ('Host', self.host),
            ('Connection', 'Upgrade'),
            ('Upgrade', 'websocket'),
            ('Sec-WebSocket-Key', self.key.decode('utf-8')),
            # Origin is proxyed from the downstream server, don't set it twice
            # ('Origin', self.url),
            ('Sec-WebSocket-Version', str(max(WS_VERSION)))
            ]

        if self.protocols:
            headers.append(('Sec-WebSocket-Protocol', ','.join(self.protocols)))

        if self.extra_headers:
            headers.extend(self.extra_headers)

        logger.info("Handshake headers: %s", headers)
        return headers

    def received_message(self, m):
        """Push upstream messages to downstream."""

        # TODO: No support for binary messages
        m = str(m)
        logger.debug("Incoming upstream WS: %s", m)
        uwsgi.websocket_send(m)
        logger.debug("Send ok")

    def handshake_ok(self):
        """
        Called when the upgrade handshake has completed
        successfully.

        Starts the client's thread.
        """
        self.run()

    def terminate(self):
        raise RuntimeError("NO!")
        super(ProxyClient, self).terminate()

    def run(self):
        """Combine async uwsgi message loop with ws4py message loop.

        TODO: This could do some serious optimizations and behave asynchronously correct instead of just sleep().
        """

        self.sock.setblocking(False)
        try:
            while not self.terminated:
                logger.debug("Doing nothing")
                time.sleep(0.050)

                logger.debug("Asking for downstream msg")
                msg = uwsgi.websocket_recv_nb()
                if msg:
                    logger.debug("Incoming downstream WS: %s", msg)
                    self.send(msg)

                s = self.stream

                self.opened()

                logger.debug("Asking for upstream msg")
                try:
                    bytes = self.sock.recv(self.reading_buffer_size)
                    if bytes:
                        self.process(bytes)
                except BlockingIOError:
                    pass

        except Exception as e:
            logger.exception(e)
        finally:
            logger.info("Terminating WS proxy loop")
            self.terminate()

def serve_websocket(request, port):
    """Start UWSGI websocket loop and proxy."""
    env = request.environ

    # Send HTTP response 101 Switch Protocol downstream
    uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))

    # Map the websocket URL to the upstream localhost:4000x Notebook instance
    parts = urlparse(request.url)
    parts = parts._replace(scheme="ws", netloc="localhost:{}".format(port))
    url = urlunparse(parts)

    # Proxy initial connection headers
    headers = [(header, value) for header, value in request.headers.items() if header.lower() in CAPTURE_CONNECT_HEADERS]

    logger.info("Connecting to upstream websockets: %s, headers: %s", url, headers)

    ws = ProxyClient(url, headers=headers)
    ws.connect()

    # Happens only if exceptions fly around
    return ""

rawDescription: WebSockets Proxy for IPython Notebook using Flask and WebSocket-for-Python (ws4py)


code:
from tkinter import *

class App():

    def __init__(self):
        self.root = Tk()

        self.messages = {}

        self.canvas = Canvas(self.root, bd=0, highlightthickness=0)
        self.image = PhotoImage(file='2.gif')
        self.canvas.create_image(0,0, image=self.image, anchor='nw')
        w,h = self.image.width(), self.image.height()
        self.canvas.config(width=w, height=h)
        self.canvas.pack()

        self.balloon = b = Toplevel(self.root)
        b.withdraw()
        b.wm_overrideredirect(1)
        self.msg = Label(b, bg='black', fg='yellow', bd=2, text='')
        self.msg.pack()

        self.set_up_hotspots()

    def set_up_hotspots(self):
        box1 = self.canvas.create_polygon(50,100,100,100,100,150,50,150,
                                               outline='blue', fill='')
        #note: outline can be '' also ;)
        self.messages[box1] = "The machine head consists of a "\
                              "Flynn mechanism,\na Demmel crank, "\
                              "and a heavy-duty frobulator. "

        box2 = self.canvas.create_polygon(150,100,200,100,200,150,150,150,
                                               outline='red', fill='')
        self.messages[box2] = "And now for something completely different"

        for item in [box1, box2]:
            for event, handler in [('<Enter>', self.on_hotspot_enter),
                                   ('<Leave>', self.on_hotspot_leave)]:
                self.canvas.tag_bind(item, event, handler)

    def on_hotspot_enter(self, event):
        if not self.balloon.winfo_ismapped():
            txt = self.messages[event.widget.find_withtag('current')[0]]
            self.msg.config(text=txt)
            x,y = event.x_root, event.y_root
            self.balloon.geometry('+%d+%d' %(x+16,y))
            self.balloon.deiconify()

    def on_hotspot_leave(self, event):
        if self.balloon.winfo_ismapped():
            self.balloon.withdraw()

if __name__ == "__main__":

    app = App()
    app.root.mainloop()

rawDescription: Need help placing buttons on a PhotoImage .gif


code:
actions = ActionChains(self.driver)
actions.send_keys('dummydata')
actions.perform()

rawDescription: Send keys without specifying element in python selenium webdriver


rawDescription: Find ISBN with regex in Python

description: Find ISBN with regex in Python


code:
sys.getsizeof('')
sys.getsizeof('a')
sys.getsizeof('ab')
sys.getsizeof('abc')

rawDescription: Python: size of strings in memory

description: Python: size of strings in memory


code: return iter(List)

rawDescription: How to Pythonically yield all values from a list?


code:
lgd = axarr[k,l].legend(loc=(X,Y)) # X and Y such that outside of plot
plt.savefig("test.pdf", bbox_inches='tight', bbox_extra_artists=(lgd,))

rawDescription: Subplots grid, legend outside, savefig does not work


code: call(["./code", str(variableContainingNumber), "other", "args"])

rawDescription: how to run a C code with argc argv from python?

description: Run a C code with argc argv from python


code:
import os

def open_file():
    # TARGET_DIR and URL are global variables.
    all_lines = []

    # If the file is not there, make it.
    if not os.path.isfile(TARGET_DIR):
        procesed_data = parse_site(URL)
        save_parsed(procesed_data)
        compare_parsed()
        # Here I am assuming the file has been created.

    current_file = codecs.open(TARGET_DIR, 'r', 'utf-8')
    data = csv.reader(current_file, delimiter=';')
    for row in data:
        all_lines.append(row)
    current_file.close()
    return all_lines

rawDescription: create file after positive exception FileNotFoundError

description: Create file after positive exception FileNotFoundError


code:
lst = sorted(fx_elements.keys())
app = QApplication(sys.argv)
listWidget = QListWidget()
listWidget.setSelectionMode(QAbstractItemView.ExtendedSelection)
for k in lst:
    item = QListWidgetItem(k)
    listWidget.addItem(item)

rawDescription: Reading .csv file in qlistWidget in pyQt


rawDescription: program running programs in python

description: Program running programs in python


code:
for line in FILE:
    for word in keyWords:
            if word in line:
                    parseString = line[29:35] #pulling in session ID
                    sessionID.append(parseString) #saving session IDs to a list
                    break # Assuming there will only be one keyword per line, else remove this
    logLine +=1 #for debugging purposes when testing
importFile2.close()
print(sessionID) #for debugging purposes when testing

rawDescription: Python script not iterating through array


code:
import django
django.__file__

rawDescription: Python analog of Unix 'which'

description: Python analog of Unix 'which'


code:
from matplotlib import pyplot as plt
import numpy as np
randn = np.random.randn
from pandas import *

idx = Index(arange(1,11))
df = DataFrame(randn(10, 5), index=idx, columns=['A', 'B', 'C', 'D', 'E'])
vals = np.around(df.values,2)
normal = plt.normalize(vals.min()-1, vals.max()+1)

fig = plt.figure(figsize=(15,8))
ax = fig.add_subplot(111, frameon=True, xticks=[], yticks=[])

the_table=plt.table(cellText=vals, rowLabels=df.index, colLabels=df.columns,
                    colWidths = [0.03]*vals.shape[1], loc='center',
                    cellColours=plt.cm.hot(normal(vals)))

rawDescription: matplotlib: using a colormap to color table-cell background

description: Matplotlib: using a colormap to color table-cell background


code:
null = None
var = [{"title": null, "metric1": 361429, "metric2": 36,},{"title": null, "metric1": 253798, "metric2": 48}]

rawDescription: Nulls, instead of Nones, in JSON Data with Python


code:
def getItems(soup):
    items = []
    appliance = soup.select('a[data-lid="ubr_app"]')[0]
    for appliance_ul in appliance.parent.find_next_siblings('ul'):
        items.append([i.text for i in appliance_ul.find_all('li')])
    return items

rawDescription: How to collect information from multiple siblings using BeautifulSoup?

description: Collect information from multiple siblings using BeautifulSoup


code:
import re
re.sub(r'%(.+?)%', lambda m: rep_dict[m.group(1)], YOUR_TEMPLATE)

rawDescription: How can I replace sub-strings of a large string based on a dictionary in Python?

description: Replace sub-strings of a large string based on a dictionary in Python


code:
class Company(Document):
    name = StringField(max_length=500)
    feedbacks = ListField(ReferenceField(Feedback))

class Feedback(Document):
    text = StringField(max_length=500)
    is_approved = BooleanField(default=False)
    date = DateTimeField(default=datetime.now())

rawDescription: Manytomany field in Django mongoengine Document


code: key=lambda x: (x.count('\\'), x.split('\\'))

rawDescription: python sort list using lambda function

description: Python sort list using lambda function


code:
f.seek(0, 2)
file_size = f.tell()

rawDescription: how many unread bytes left in a file?

description: How many unread bytes left in a file


code: max(lst, key=lambda x:x['score'])

rawDescription: how to get the index of dictionary with the highest value in a list of dictionary

description: Get the index of dictionary with the highest value in a list of dictionary


code:
filelist = []
for inFile in os.listdir('.'):
    if inFile.isdigit():
        if int(inFile) <= int(strftime("%m")):
            year = strftime("%Y")
        else:
            year = int(strftime("%Y"))-1
        filelist.append((year, inFile))
filelist.sort()
for year, inFile in filelist:
    month = months[int(inFile)]
    ...

rawDescription: Generate a list of file names based on month and year arithmetic


code:
ptable = (df.pivot(index='date', columns='product', values='stock')
          .fillna(method='ffill').asfreq('D', method='ffill'))
cond = ptable.apply(lambda x: (x == 0).all(), axis='columns')
print(ptable.index[cond])

DatetimeIndex(['2016-01-10', '2016-01-11', '2016-01-12', '2016-01-13',
               '2016-01-14'],
              dtype='datetime64[ns]', name=u'date', freq='D')

rawDescription: Efficiently finding overlap between many date ranges


code:
from hashlib import md5

input_list = ['a','b','c','d','e']

hashed_list = [int(md5(x).hexdigest(), base=16) for x in input_list]

# Do whatever you wanted to do with the list of hashes....

rawDescription: Converting values in a list to their hashed forms (Python)


code:
def get_coordinates(infile, delimiter):
    new_list = []
    with open(infile, 'r') as f:
        for line in f:
            x, y = [float(i) for i in line.strip().split(delimiter)]

            ## rounding happens here: 4 decimal places for x and y
            new_list.append('%0.4f,%0.4f' % (x, y))

    return new_list

## Extract x,y coordinates from input file given delimiter
LIST1 = get_coordinates('table1.txt', ',')
LIST2 = get_coordinates('table2.txt', ',')

## New list with common coordinates between the two file
NEW_LIST = list(set(LIST1) & set(LIST2))

## print result to output file: "outfile.txt"
with open('outfile.txt', 'w') as outfile:
    for xy in NEW_LIST:
        ## write entries "x,y" -- this the default
        outfile.write('%s\n' % xy)

        ## -----------------------------------------------------
        ## by default it will be CSV, but
        ## if you want to split by tabs then
        ## comment out previous part & uncomment the following:
        ## -----------------------------------------------------

        # outfile.write('%s\n' % '\t'.join(xy.split(',')))

rawDescription: Matching tables in python

description: Matching tables in python


code:
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def post(self):
        self.write("Hello, world")
    get = post # <--------------

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: Tornado POST 405: Method Not Allowed

description: Tornado POST 405: Method Not Allowed


code:
from itertools import groupby
...
for g_z, group in groupby(zip(zip(x, y), z), lambda p: p[1]):
    g_x, g_y = [], []
    for i in group:
        g_x.append(i[0][0])
        g_y.append(i[0][1])
    if g_z:
        plt.plot(g_x, g_y, linestyle='-')
    else:
        plt.plot(g_x, g_y, linestyle='--')
...

rawDescription: Plotting a line in Python with a variable linestyle


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

class MyItem(scrapy.Item):
    name = scrapy.Field()
    position= scrapy.Field()
    detail=scrapy.Field()
class MySpider(scrapy.Spider):

    name = '<name of spider>'
    allowed_domains = ['mywebsite.org']
    start_urls = ['http://mywebsite.org/<path to the page>']

    def parse(self, response):

        rows = response.xpath('//a[contains(@href,"<div id or class>")]')

        #loop over all links to stories
        for row in rows:
            myItem = MyItem() # Create a new item
            myItem['name'] = row.xpath('./text()').extract() # assign name from link
            myItem['position']=row.xpath('./text()').extract() # assign position from link
            detail_url = response.urljoin(row.xpath('./@href').extract()[0]) # extract url from link
            request = scrapy.Request(url = detail_url, callback = self.parse_detail) # create request for detail page with story
            request.meta['myItem'] = myItem # pass the item with the request
            yield request

    def parse_detail(self, response):
        myItem = response.meta['myItem'] # extract the item (with the name) from the response
        text_raw = response.xpath('//font[@size=3]//text()').extract() # extract the detail (text)
        myItem['detail'] = ' '.join(map(unicode.strip, text_raw)) # clean up the text and assign to item
        yield myItem # return the item

rawDescription: How to execute an specific spider from the Pipeline without activating it again

description: Execute an specific spider from the Pipeline without activating it again


code:
def parse_multi_msg(msg):
  is_in_quotation = False
  aObjs = []
  sTemp = ""
  for c in msg:
    sTemp += c;

    if c == '"':
      if not is_in_quotation:
        is_in_quotation = True
      else:
        is_in_quotation= False

    if c == "}" and not is_in_quotation:
      aObjs.append(json.loads(sTemp));
      sTemp = "";

  return aObjs

rawDescription: tornado websocket get multi message when on_message called

description: Tornado websocket get multi message when on_message called


code:
import math
scanner.scan(image)
[a,b,c,d] = x.location   # it returns the four corners of the QR code in an order
w = math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)  # Just distance between two points
h = math.sqrt((b[0]-c[0])**2 + (b[1]-c[1])**2)
Area = w*h

rawDescription: Detect the size of a QR Code in Python using OpenCV and Zbar


code:
class Haha(object): pass
sys.getsizeof(Haha)
sys.getsizeof(Haha())

rawDescription: Why is creating a class in Python so much slower than instantiating a class?


code:
skflow.TensorFlowDNNRegressor.__init__(
     hidden_units,
     n_classes=0,
     tf_master='',
     batch_size=32,
     steps=200,
     optimizer='SGD',
     learning_rate=0.1,
     tf_random_seed=42,
     continue_training=False,
     config_addon=None,
     verbose=1,
     max_to_keep=5,
     keep_checkpoint_every_n_hours=10000)

description: Skflow.TensorFlowDNNRegressor parameters


code:
func = lambda xs: np.any(xs)  # or whatever appropriate
mask = generic_filter(array1, func, footprint=(3, 3))
array2[mask] = 0

rawDescription: Python interaction between two numpy arrays of the same shape involving cell neighbours


code:
@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
    class form(forms.ModelForm):
        adress = forms.BooleanField(widget=MapWidget(),)

rawDescription: Add a map in Django Admin

description: Add a map in Django Admin


rawDescription: What does axes[0,0] semantics mean in Python?


code:
c = compile('raise Exception("spam")', 'eggs', 'exec')
eval(c)

rawDescription: What's the use of the filename parameter of ast.parse?


code:
import boto.ec2
conn = boto.ec2.connect_to_region('us-east-1')  # or whatever region you use
reservations = conn.get_all_instances(instance_ids='i-12345678')
instance = reservations[0].instances[0]
print(instance.public_dns_name)

rawDescription: Get ec2 instance metadata from instance id


code:
def createEngine(metadata, dsn, **args):
    engine  = create_engine(dsn, **args)
    metadata.create_all(engine)
    return engine

def doStuff(engine):
    res = engine.execute('select * from mytable')
    # etc etc

def main():
    engine = createEngine(metadata, 'sqlite:///:memory:')
    doStuff(engine)

if __name__=='__main__':
    main()

rawDescription: SQLAlchamy Database Construction & Reuse


code:
from matplotlib.collections import PatchCollection
import matplotlib
import matplotlib.pyplot as plt
import random

fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
plt.xlim([0, 1001])
plt.ylim([0, 1001])
n=10000
patches = []
for i in range(0,n):
    x = random.uniform(1, 1000)
    y = random.uniform(1, 1000)
    patches.append(matplotlib.patches.Rectangle((x, y),1,1,))
ax.add_collection(PatchCollection(patches))
plt.show()

rawDescription: How to speed up the plot of a large number of rectangles with Matplotlib?

description: Speed up the plot of a large number of rectangles with Matplotlib


code:
from ImageUtilis import ImageUtilis

iu = ImageUtilis()

image_address = "image1.jpg"
mark_address = "watermake.png"  # transparent or whatever

iu.watermark(image_address, mark_address, 'tile', 0.5)
iu.watermark(image_address, mark_address, 'scale', 1.0)
iu.watermark(image_address, mark_address, (100, 100), 0.5) # (100,100) is position x,y

rawDescription: python PIL - how to put transparent image over original image

description: Python PIL - how to put transparent image over original image


code:
from tkinter import *

class Window1:

    def __init__(self, master):

        # keep `root` in `self.master`
        self.master = master

        self.label = Button(self.master, text="Example", command=self.load_new)
        self.label.pack()

    def load_new(self):
        self.label.destroy()

        # use `root` with another class
        self.another = Window2(self.master)

class Window2:

    def __init__(self, master):

        # keep `root` in `self.master`
        self.master = master

        self.label = Label(self.master, text="Example")
        self.label.pack()

root = Tk()
run = Window1(root)
root.mainloop()

rawDescription: Is it possible to keep the same window for every class in python's tkinter?


code:
import pyspark
conf = pyspark.SparkConf()
conf.set('spark.dynamicAllocation.minExecutors', 5)
sc = SparkContext(appName="tmp", conf=conf)

rawDescription: Using external modules when applying custom functions in PySpark


code:
import csv
from collections import defaultdict

subgroups = defaultdict(set)
processed_subgroups = defaultdict(set)

with open('data.csv') as csvfile:
    for group, subgroup, processed in csv.reader(csvfile):
        subgroups[group].add(subgroup)
        if processed == 'y':
            processed_subgroups[group].add(subgroup)

    for group in sorted(processed_subgroups):
        print("Group {} -- {:.2f}%".format(group, (len(processed_subgroups[group]) / float(len(subgroups[group])) * 100)))

rawDescription: Python 2.7, comparing 3 columns of a CSV


code:
usernames = ['john', 'ivan']
emails = User.objects.filter(username__in=usernames) \
                     .values_list('email', flat=True)

rawDescription: query in django

description: Query in django


code:
from app import db

def ClassFactory(name):
    tabledict={'id':db.Column(db.Integer, primary_key = True),
               'trans_id':db.Column(db.Integer),
               'timestamp':db.Column(db.Integer),
               'order_type':db.Column(db.String(25)),
               'price':db.Column(db.Numeric(25,8)),
               'quantity':db.Column(db.Numeric(25,8)),}

    newclass = type(name, (db.Model,), tabledict)
    return newclass

rawDescription: Overriding the table name in Flask-Alchemy


rawDescription: splitting characters of a string by a delimiter in those characters

description: Splitting characters of a string by a delimiter in those characters


code:
s = read_clipboard(header=None)
news = s.rename(columns=lambda x: ['Region', 'data'][x])
news
news_converted = news.convert_objects(convert_numeric=True)
news_converted
news_converted.loc[11, 'Region'] = 'N'
news_converted_with_index = news_converted.set_index('Region')
news_converted_with_index
news_converted_with_index.sort_index()

rawDescription: Pandas Series Sort

description: Pandas Series Sort


code:
import pandas as pd

data = np.random.random(20)
stds = pd.rolling_std(data, window=7, center=True, min_periods=1)  # min_periods to get the edges

rawDescription: Statistics of region of numpy array

description: Statistics of region of numpy array


code:
file = open("rawData", "wb")
...
file.write(data)
...
file.close()

rawDescription: Opening a file in Python: bytes array converted to string?


code:
class Event(object):

    def __init__(self):
        self.msg_idx=0 ## the message from the panel
        self.evt_id=0 ## the event id given by the server
        self.Panel_Number=0 ## the panel number
        self.line=""

    def updateData(self,msg,event,panel,line):
        self.msg_idx =msg
        self.evt_id = event
        self.Panel_Number = panel
        self.line =line

class Events(object):

    def __init__(self):
        self.event =[]

    def addEvent(self, Server_Event):
         self.event.append(Server_Event)

something = Event()
somethings = Events()
somethings.addEvent(something)

rawDescription: add 1 class to another class array

description: Add 1 class to another class array


code:
from urllib import urlencode
artist = 'Tommy James & The Shondells'
api_key = 'KEY_GOES_HERE'
urlencode({'artist': artist, 'api_key': api_key})

rawDescription: html "&" and parameters

description: Html "&" and parameters


code:
d = pd.date_range(start="1/1/2012", end="2/1/2012", freq="B")
v = np.linspace(1,10,len(d))

plt.plot(range(d.size), v)
xticks = plt.xticks()[0]
xticklabels = [(d[0] + x).strftime('%Y-%m-%d') for x in xticks.astype(int)]
plt.xticks(xticks, xticklabels)
plt.autoscale(True, axis='x', tight=True)

rawDescription: matplotlib only business days without weekends on x-axis with plot_date

description: Matplotlib only business days without weekends on x-axis with plot_date


code:
original_list, my_index = [1, 2, 3, 4, 5], 2
original_list[my_index + 1:] + original_list[:my_index + 1]

rawDescription: Python rearrange list starting from a certain element


code:
s = pd.Series([0, np.nan, np.nan, 1, np.nan, np.nan, np.nan, 2])
w = pd.Series([0, 1, 0, 1, 1, 2, 0, 1])
print(s.interpolate())
sb = s.fillna(method='ffill')
se = s.fillna(method='bfill')
cw = w.cumsum()
w2 = pd.Series(None, index=s.index)
w2[~np.isnan(s)] = cw[~np.isnan(s)]
wb = w2.fillna(method='ffill')
we = w2.fillna(method='bfill')
cw = (cw - wb) / (we - wb)
r = sb + cw * (se - sb)
r.update(s)
print(r)

rawDescription: Weighted interpolation in pandas.Series

description: Weighted interpolation in pandas.Series


code:
from django import forms

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file  = forms.FileField()

from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseNotAllowed, HttpResponseServerError

# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file

@csrf_exempt
def upload_file(request):
    if request.method != 'POST':
        return HttpResponseNotAllowed('Only POST here')

    form = UploadFileForm(request.POST, request.FILES)
    if not form.is_valid():
        return HttpResponseServerError("Invalid call")

    handle_uploaded_file(request.FILES['file'])
    return HttpResponse('OK')

rawDescription: Writing a file upload API using Django

description: Writing a file upload API using Django


code:
def build_component_list(base, custom):
    """Compose a component list based on a custom and base dict of components
    (typically middlewares or extensions), unless custom is already a list, in
    which case it's returned.
    """
    if isinstance(custom, (list, tuple)):
        return custom
    compdict = base.copy()
    compdict.update(custom)
    items = (x for x in six.iteritems(compdict) if x[1] is not None)
    return [x[0] for x in sorted(items, key=itemgetter(1))]

rawDescription: Scrapy - Activating an Item Pipeline component - ITEM_PIPELINES setting


code:
img = Image.open('your_wonderful_image.png')
nonwhite_positions = [(x,y) for x in range(img.size[0]) for y in range(img.size[1]) if img.getdata()[x+y*img.size[0]] != (255,255,255)]
rect = (min([x for x,y in nonwhite_positions]), min([y for x,y in nonwhite_positions]), max([x for x,y in nonwhite_positions]), max([y for x,y in nonwhite_positions]))
img.crop(rect).save('out.png')

rawDescription: Crop the border of an image using PIL

description: Crop the border of an image using PIL


code:
from operator import itemgetter
sorted(L, key=itemgetter(1))

rawDescription: Python - sort wrt second argument

description: Python - sort wrt second argument


rawDescription: python: print using carriage return and comma not working

description: Python: print using carriage return and comma not working


code:
grid = [
    [[1, 0], [2, 0], [3, 1]],
    [[3, 1], [1, 0], [2, 0]],
    [[1, 0], [2, 0], [3, 1]]
]

def find(g, length):
    # Top left -> bottom right, top right -> bottom left
    # and left -> right lengths are stored here
    prev = [[0] * 3 for _ in xrange(len(g[0]))]
    # 'Line' length is stored here for efficiency
    prev_line = {}
    for row in grid:
        cur = []
        cur_line = {}
        for i in xrange(len(row)):
            tl = line = tr = left = 0
            if row[i][1] == 1:
                # Up left
                tl = 1 + (prev[i-1][0] if i else 0)
                # Line
                line = 1 + prev_line.get(row[i][0], 0)
                # Up right
                tr = 1 + (prev[i+1][1] if i < len(row) - 1 else 0)
                # Straight Left
                left = 1 + (cur[i-1][2] if i else 0)

            if any(x == length for x in (tl, line, tr, left)):
                return True
            cur.append([tl, tr, left])
            cur_line[row[i][0]] = line

        prev = cur
        prev_line = cur_line

    return False

find(grid, 3) # True

rawDescription: Checking a series of binary states

description: Checking a series of binary states


code:
import sys
import time
import os
def typer(x):
    for i in x:
        print(i, end='')
        time.sleep(0.020)

def register():

    name = input('Create username: ')+'.txt'
    file = open(name, 'a')
    i = input("Create password: ")
    file.write(i+'\n')
    typer("Creating account...")

def login():
    user = input("Insert username: ")
    try:
        file = open((user+'.txt'), "r")  # line altered
    except FileNotFoundError:
        print("Username\Password incorrect")
        sys.exit()
    pas = input("Enter password: ")
    pas += '\n'  # line altered
    try:
        file = open((user+'.txt'), 'r')
        if (user+'.txt') == file.name:  # line altered
            pasmatch = file.read() # line altered, removed '1'
            if pas == pasmatch:
                typer("Logging into your account...")
    except:
        print("Username\Password i incorrect")
        sys.exit()

menu = True

while menu == True:
    menu = True
    print("What do you want to do?")
    print("1. Register")
    print("2. Login")
    ii = input("")
    if ii == "1":
        register()
    if ii == "2":
        login()
        menu = False

rawDescription: Open, help! Account don't work. Python

description: Open, help! Account don't work. Python


code:
import struct
print(list(struct.pack('d', 3.14)))

rawDescription: How to print out the memory contents of object in python?

description: Print out the memory contents of object in python


rawDescription: Aggregate Numpy Array By Summing

description: Aggregate Numpy Array By Summing


code:
def pkcs7_pad(data, blocksize=16):
    padlen = blocksize - len(data) % blocksize
    return data + bytes([padlen]) * padlen

def pkcs7_unpad(data, blocksize=16):
    if data:
        padlen = data[-1]
        if 0 < padlen < blocksize:
            if data.endswith(bytes([padlen]) * padlen):
                return data[:-padlen]

    raise ValueError('incorrect padding')

rawDescription: How to make M2Crypto work with aes128-cbc-pkcs7?

description: Make M2Crypto work with aes128-cbc-pkcs7


code:
from PIL import Image

im = Image.open(my_image_file)
a4im = Image.new('RGB',
                 (595, 842),   # A4 at 72dpi
                 (255, 255, 255))  # White
a4im.paste(im, im.getbbox())  # Not centered, top-left corner
a4im.save(outputfile, 'PDF', quality=100)

rawDescription: Python PIL/Pillow - Pad image to desired size (eg. A4)


code:
my_string = "blah, lots  ,  of ,  spaces, here "
[x.strip() for x in my_string.split(',')]

rawDescription: Split by comma and strip whitespace in Python


code: Worksheets("Sheet1").Range("A1:A5").Value = [1, 2, 3, 4, 5]

rawDescription: Writing csv reader to excel using python


code:
import sys; reload(sys)
'urlfetch' in sys.modules

rawDescription: Check which module imported

description: Check which module imported


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

location_uid, count = np.unique(np.random.randint(0, 20, 1000), return_counts=True)
location_uid = np.require(location_uid, dtype=np.int)
n_wifi_locs = len(location_uid)

fig, ax = plt.subplots(figsize = (15, 8))
idx = np.argsort(count)[::-1][:10]

dummy = ax.bar(np.arange(10), count[idx], align='center',alpha=0.4)
dummy = ax.set_xticks(np.arange(10))
dummy = ax.set_xticklabels(location_uid[idx])

rawDescription: Bar Chart Python

description: Bar Chart Python


code:
from Queue import PriorityQueue
priority_queue = PriorityQueue()
priority_queue.put((1, 2))
priority_queue.put((1, 1))
priority_queue.get()
priority_queue.get()

rawDescription: Priority queue with two priority values

description: Priority queue with two priority values


rawDescription: numpy matrix multiplication

description: Numpy matrix multiplication


rawDescription: row items against each bars in matplotlib

description: Row items against each bars in matplotlib


code:
import matplotlib.pyplot as plt
from collections import OrderedDict

def chartmak (dic) :
    plt.barh(range(len(dic)), dic.values(), 0.95, align='center', color="lightskyblue")
    plt.yticks(range(len(dic)), ["{} GB".format(v) for v in dic.values()])
    for index, label in enumerate(dic.keys()):
        plt.text(10, index, label, ha='left',va='center')
    plt.gca().invert_yaxis()
    plt.show()

Dic = OrderedDict([('PROFESSIONAL_SERVICES', 621), ('WEB_SEARCH', 381), ('REMOTE_ACCESS', 160), ('Microsoft Category', 141), ('INTERNET_SERVICES', 62)])
chartmak(Dic)

rawDescription: How to use Python and matplotlib to customize a bar chart

description: Use Python and matplotlib to customize a bar chart


code:
import mechanize

url = 'http://www.cpsc.gov/cpscpub/prerel/prhtml03/03059.html'
br = mechanize.Browser()
br.set_handle_refresh(False)
br.open(url)

rawDescription: Python Mechanize won't open these sites

description: Python Mechanize won't open these sites


code:
import imp
imp.load_source(path)

rawDescription: Importing Python script with nonstandard name


rawDescription: How to set ETAGS on Google App Engine for Python?

description: Set ETAGS on Google App Engine for Python


code:
orig_type = sa.dtype
descr = orig_type.descr
descr[1] = (descr[1][0], "|S10")
new_type = numpy.dtype(descr)

rawDescription: NumPy: programmatically modify dtype of a structured array


code:
def unflatten(dictionary):
    resultDict = dict()
    for key, value in dictionary.iteritems():
        parts = key.split(".")
        d = resultDict
        for part in parts[:-1]:
            if part not in d:
                d[part] = dict()
            d = d[part]
        d[parts[-1]] = value
    return resultDict

rawDescription: Python - Unflatten dict

description: Python - Unflatten dict


rawDescription: Pywin32 SendKeys: "Windows button" keypress


code:
import itertools

bases = ['a','c','t','g']
for subset in itertools.permutations(bases, 3):
  print(subset)

rawDescription: Why is my program returning the same permutations multiple times?


code:
def features_to_dict(self):
    members = inspect.getmembers(self, inspect.ismethod)
    return {name: method() for name, method in members if name.startswith('get')}

rawDescription: Load All Method Results in Python Class to Dictionary


code:
rank=Rank()
for att in attributes:
     setattr(rank, att, somevalue)

rawDescription: python: send value of a variable instead of its name to function

description: Python: send value of a variable instead of its name to function


code:
full_name = input("Please enter in a full name: ")
len(full_name) - full_name.count(' ')
len(full_name)

rawDescription: Using len in texts but discluding spaces in the count


code: from B_file_1 import B_file_1

rawDescription: Python module organization to make import statement cleaner


code: print("%s %s" % (lines[a].rstrip(), answer))

rawDescription: I want to print a line from a text file along with a variable


code:
import re
a = "to be removed blah blah \r\nrow 2 blah blah\r\nrow 3 more blah blah \r\nto be removed more blah blah \r\nrow 5 final blah blah"
a = re.sub(r'to be removed.*?\r\n', '', a)
a

rawDescription: remove substring until end of the line

description: Remove substring until end of the line


code:
from tkinter import *
#from threading import Thread #no longer needed

class Note(Toplevel):
    nid = 0
    #title = "" #this would block the method to override the current title
    message = ""

    def __init__(self, master, nid, title, message):
      Toplevel.__init__(self,master)
      self.nid = nid
      self.title(title) #since toplevel widgets define a method called title you can't store it as an attribute
      self.message = message
      self.display_note_gui() #maybe just leave that code part of the __init__?

    def display_note_gui(self):
      '''Tkinter to create a note gui window with parameters '''
      #no window, just self
      self.geometry("200x200")
      self.configure(background="#BAD0EF")
      #pass self as the parent to all the child widgets instead of window
      title = Entry(self,relief=FLAT, bg="#BAD0EF", bd=0)
      title.pack(side=TOP)
      scrollBar = Scrollbar(self, takefocus=0, width=20)
      textArea = Text(self, height=4, width=1000, bg="#BAD0EF", font=("Times", "14"))
      scrollBar.pack(side=RIGHT, fill=Y)
      textArea.pack(side=LEFT, fill=Y)
      scrollBar.config(command=textArea.yview)
      textArea.config(yscrollcommand=scrollBar.set)
      textArea.insert(END, self.message)
      #self.mainloop() #leave this to the root window

    def run(self):
      self.display_note_gui()

root = Tk()
root.withdraw() #hide the root so that only the notes will be visible

new_note1 = Note(root, 0, "Hello", "Hi, how are you?")
#new_note1.start()
#new_note1.join()

new_note2 = Note(root, 1, "2", "How's everyone else?")
#new_note2.start()
#new_note2.join()

root.mainloop() #still call mainloop on the root

rawDescription: How do I run multiple tkinter windows simultaneously in Python?

description: Run multiple tkinter windows simultaneously in Python


code:
def main():
    ROWS = get_input()
    draw_pattern(ROWS)

def get_input():
    return int(input("Enter the number of rows (or -1 or -99 to quit): "))

def draw_pattern(ROWS):
    if ROWS == -1 or ROWS == -99:
        return

    else:
        for x in range(1, ROWS, 2):
            print(' ' * int(ROWS / 2.0 - x / 2.0) + ("*" * x))

        for x in range(ROWS, 1, -2):
            print(' ' * int(ROWS / 2.0 - x / 2.0) + ("*" * x))

        if x != 1:
            print(' ' * int(ROWS / 2.0 - 1 / 2.0) + ("*" * 1))

main()

rawDescription: Python 3.4: creating an asterisk diamond


rawDescription: Python Selenium find element by link text contains a string with wildcard or regex


code: self.assertContains(result, "abcd")

rawDescription: Python/Django: how to assert that unit test result contains a certain string?


rawDescription: python relative import

description: Python relative import


code:
import re
if re.search(r'\btest\b', theString):
    pass

rawDescription: Properly check if word is in string?

description: Properly check if word is in string


code:
args = ["perl", "myscript.perl", "--in", "/dev/stdin", "other_args", other_vals]
pipe1 = subprocess.Popen(["echo", mytext], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
pipe2 = subprocess.Popen(args, stdin=pipe1.stdout, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
pipe1.stdout.close()
result = pipe2.communicate()[0]

rawDescription: Using stdin instead of a file in a python call to a perl script


code:
for dct in dictionary_list:
    if 'gene_name' in dct:
        dct['gene_name'] = str(dct['gene_name'])

rawDescription: DictVectorizer Recognize Feature as String


code:
keyboard = pygame.transform.scale(keyboard, size)
my_little_copy = keyboard.subsurface(Rect(500, 300, 32, 32)).copy()
screen.blit(keyboard, (0, 0))
screen.blit(my_little_copy, (500, 350))

rawDescription: Need to move a small area of the screen

description: Need to move a small area of the screen


rawDescription: Invert slice in python

description: Invert slice in python


code:
if user not in data:
    data[user] = []
data[user].append({'item': row[0], 'time': row[1]})

rawDescription: Appending associative arrays in Python

description: Appending associative arrays in Python


rawDescription: How to get the last number from list in python

description: Get the last number from list in python


code:
import pandas as pd
df = pd.DataFrame([])
df.instrument_name = 'Binky'

rawDescription: Adding meta-information/metadata to pandas DataFrame


code:
import itertools
lol = [[1,2,3],[4,5,6],[7,8,9]]
result = list()
while lol:
    l=lol.pop(0)
    o=itertools.chain(*lol)
    result += itertools.product( l,o )

rawDescription: recursively create tuples from lists

description: Recursively create tuples from lists


code:
from flask import Flask

app = Flask(__name__)

@app.before_first_request
def do_heavy_work():
    print("work, work!")

@app.route('/')
def index():
    return 'Hello, world.'

@app.route('/next')
def next():
    return 'yoo'

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

rawDescription: Running a single .py file once before main app.py in Flask


rawDescription: Clustering data with given cluster centers in Python


code:
root = Tk.Tk()
root.wm_title("Pie Chart")

labels = [r'Rayos X (88.4 %)', r'RMN en solucion (10.6 %)', r'Microscopia electronica (0.7 %)', r'Otros (0.3 %)']
sizes = [88.4, 10.6, 0.7, 0.3]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']

fig = plt.figure()
piechart = fig.add_subplot(1, 1, 1)
patches, texts = piechart.pie(sizes, colors=colors, startangle=90, pctdistance=1)
piechart.legend(patches, labels, loc="best")
piechart.axis('equal')

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
Tk.mainloop()

rawDescription: Figure of piechart empty

description: Figure of piechart empty


code: model = RandomForestRegressor(n_estimators=100, verbose=2, n_jobs=2).fit(X_train, y_train)

rawDescription: scikit-learn fit remaining time

description: Scikit-learn fit remaining time


rawDescription: Extracting first n columns of a numpy matrix


code:
import subprocess
import os

devnull = open(os.devnull,"w")
subprocess.call(['play', 'flap.wav'], stdout=devnull)
devnull.close()

rawDescription: How do I stop play function from printing?

description: Stop play function from printing


code:
if self.folderactive.isChecked():
    ...
else:
    ...

rawDescription: How to check if a checkbox is checked in pyqt

description: Check if a checkbox is checked in pyqt


code:
import sys
from os.path import dirname, abspath
sys.path.insert(0, dirname(dirname(abspath(__file__))))
from package_a import some_a_file

rawDescription: How to load python module from a neighbouring package?

description: Load python module from a neighbouring package


code: i = re.sub(r"\b" + re.escape(word.rstrip("\n")) + r"\b", "", i)

rawDescription: What is an easy way of removing a list of words from a list of sentences?


code:
def gen_alphaLabels(donotInclude):
    for i in range(65,91):
        char = chr(i)
        if char not in donotInclude:
            yield char

rawDescription: Skipping over values in a generator function


code:
from scipy.spatial import cKDTree as KDTree
import numpy as np

#a is the big data as numpy array N rows by 3 cols
a = np.random.randn(10**8, 3).astype('float32')

# This will create the index, prepare to wait...
# NOTE: took 7 minutes on my mac laptop with 10^8 rand 3-d numbers
#  there are some parameters that could be tweaked for faster indexing,
#  and there are implementations (not in scipy) that can construct
#  the kd-tree using parallel computing strategies (GPUs, e.g.)
k = KDTree(a)

#ask for the 2-nearest neighbors by querying the index with the
# same points
(dists, idxs) = k.query(a, 2)
# (dists, idxs) = k.query(a, 2, n_jobs=4)  # to use more CPUs on query...

#Note: 9 minutes for query on my laptop, 2 minutes with n_jobs=6
# So less than 10 minutes total for 10^8 points.

# If the second NN is > thresh distance, then there is no other point
# in the data set closer.
thresh_d = 0.1   #some threshold, equiv to 'd' in O.P.'s code
d_slice = dists[:, 1]  #distances to second NN for each point
res = np.flatnonzero( d_slice >= thresh_d )

rawDescription: Speeding up distance between all possible pairs in an array


code:
from tkinter import *

class Cell():
    FILLED_COLOR_BG = "green"
    EMPTY_COLOR_BG = "white"
    FILLED_COLOR_BORDER = "green"
    EMPTY_COLOR_BORDER = "black"

    def __init__(self, master, x, y, size):
        """ Constructor of the object called by Cell(...) """
        self.master = master
        self.abs = x
        self.ord = y
        self.size= size
        self.fill= False

    def _switch(self):
        """ Switch if the cell is filled or not. """
        self.fill= not self.fill

    def draw(self):
        """ order to the cell to draw its representation on the canvas """
        if self.master != None :
            fill = Cell.FILLED_COLOR_BG
            outline = Cell.FILLED_COLOR_BORDER

            if not self.fill:
                fill = Cell.EMPTY_COLOR_BG
                outline = Cell.EMPTY_COLOR_BORDER

            xmin = self.abs * self.size
            xmax = xmin + self.size
            ymin = self.ord * self.size
            ymax = ymin + self.size

            self.master.create_rectangle(xmin, ymin, xmax, ymax, fill = fill, outline = outline)

class CellGrid(Canvas):
    def __init__(self,master, rowNumber, columnNumber, cellSize, *args, **kwargs):
        Canvas.__init__(self, master, width = cellSize * columnNumber , height = cellSize * rowNumber, *args, **kwargs)

        self.cellSize = cellSize

        self.grid = []
        for row in range(rowNumber):

            line = []
            for column in range(columnNumber):
                line.append(Cell(self, column, row, cellSize))

            self.grid.append(line)

        #memorize the cells that have been modified to avoid many switching of state during mouse motion.
        self.switched = []

        #bind click action
        self.bind("<Button-1>", self.handleMouseClick)
        #bind moving while clicking
        self.bind("<B1-Motion>", self.handleMouseMotion)
        #bind release button action - clear the memory of midified cells.
        self.bind("<ButtonRelease-1>", lambda event: self.switched.clear())

        self.draw()

    def draw(self):
        for row in self.grid:
            for cell in row:
                cell.draw()

    def _eventCoords(self, event):
        row = int(event.y / self.cellSize)
        column = int(event.x / self.cellSize)
        return row, column

    def handleMouseClick(self, event):
        row, column = self._eventCoords(event)
        cell = self.grid[row][column]
        cell._switch()
        cell.draw()
        #add the cell to the list of cell switched during the click
        self.switched.append(cell)

    def handleMouseMotion(self, event):
        row, column = self._eventCoords(event)
        cell = self.grid[row][column]

        if cell not in self.switched:
            cell._switch()
            cell.draw()
            self.switched.append(cell)

if __name__ == "__main__" :
    app = Tk()

    grid = CellGrid(app, 50, 50, 10)
    grid.pack()

    app.mainloop()

rawDescription: How to make an interactive 2D grid in a window in python?

description: Make an interactive 2D grid in a window in python


code: tracker_thread = threading.Thread(target=MyClass, args=(x,y,z))

rawDescription: Create a thread using a class constructor as function


code:
def check_victory(board):
    combinations = [
        # horizontal
        ((0,0), (1,0), (2,0)),
        ((0,1), (1,1), (2,1)),
        ((0,2), (1,2), (2,2)),
        # vertical
        ((0,0), (0,1), (0,2)),
        ((1,0), (1,1), (1,2)),
        ((2,0), (2,1), (2,2)),
        # crossed
        ((0,0), (1,1), (2,2)),
        ((2,0), (1,1), (0,2))
    ]

    for coordinates in combinations:
        letters = [board[y][x] for x,y in coordinates]
        if len(set(letters)) == 1:
            return letters[0] # returns corresponding letter for winner (X/O)

    return False

rawDescription: How to improve a code for Tic Tac Toe-Check Victory in Python

description: Improve a code for Tic Tac Toe-Check Victory in Python


rawDescription: Generate all possible variable values in Python


rawDescription: Apply function on Pandas dataframe

description: Apply function on Pandas dataframe


rawDescription: Novice to code: Converting individual numbers from an input into seperate values in binary


code:
def f_a(s): pass
def f_b(s): pass

consumers = [f_a, f_b]

while True:
    chunk = process.stdout.read(100)
    if chunk == '': break # or something like that
    for c in consumers: c(chunk)

rawDescription: Python communicate with a subprocess

description: Python communicate with a subprocess


code:
with open(filename, 'wb') as fd:
    total = ftpclient.size(filename)

    with tqdm(total=total) as pbar:
        def cb(data):
            l = len(data)
            pbar.update(l)
            fd.write(data)

    ftpclient.retrbinary('RETR {}'.format(filename), cb)

rawDescription: Python's ftplib with tdqm

description: Python's ftplib with tdqm


code:
def testF(self):
    for tuple1, tuple2 in zip(f(range(1,3)), [(1.0, 2), (0.5, 4)]):
        for val1, val2 in zip(tuple1, tuple2):
            if type(val2) is float:
                self.assertAlmostEquals(val1, val2, 5)
            else:
                self.assertEquals(val1, val2)

rawDescription: Test assertions for tuples with floats

description: Test assertions for tuples with floats


rawDescription: Gnomonic projection into 2-dim ndarray with healpy


code:
if img and img.meta_type == 'Image':
    pilImg = PIL.Image.open( StringIO(str(img.data)) )
elif imgData:
    pilImg = PIL.Image.open( StringIO(imgData) )

try:
    pilImg.load()
except IOError:
    pass # You can always log it to logger

pilImg.thumbnail((width, height), PIL.Image.ANTIALIAS)

rawDescription: Python PIL "IOError: image file truncated" with big images


code:
import urlparse
url = 'http://www.youtube.com/watch?v=cUjfXWuZySE&list=cUjfXWuZySE'
parts = urlparse.urlparse(url)
urlparse.parse_qs(parts.query)
{name:values[0] for name, values in urlparse.parse_qs(parts.query).iteritems()}

rawDescription: How to parse url parameters in key:value format?

description: Parse url parameters in key:value format


code:
y_speed = 0
x_speed = -10
gravity = -3 # Depending on how fast you want gravity to be
while True:
    x += x_speed
    y += y_speed
    y_speed += gravity
    gameDisplay.fill(white)
    pygame.draw.rect(gameDisplay, black, (x, y, 50,50))
    pygame.display.update()
    clock.tick(FPS)

rawDescription: How to move a rectangle in a curved path in pygames?

description: Move a rectangle in a curved path in pygames


code:
def polysemy(word):
    return wn.synsets(word)

rawDescription: Polysemy count: return senses rather than # of senses. (Wordnet NLTK)


code:
def check_in(self, barcode):
    item = barcode

    # get the relationship
    for rel in graph.match(start_node=self, rel_type="CHECKED_OUT", end_node=item):
        # set property
        rel.properties["status"] = False
        rel.push()

rawDescription: Modify or change relationship properties in py2neo


code:
data_files = []
directories = glob.glob('data/subfolder?/subfolder??/')
for directory in directories:
    files = glob.glob(directory+'*')
    data_files.append((directory, files))
# then pass data_files to setup()

rawDescription: How to add package data recursively in Python setup.py?

description: Add package data recursively in Python setup.py


code:
from matplotlib import pylab as pl

pl.subplot(211)
pl.plot(date, series1, color='black')
pl.plot(date, series2, color='blue')
pl.subplot(212)
pl.plot(date, series3, color='red')
pl.show()

rawDescription: Python: Using Pandas to plot more than one series in each subplot


rawDescription: How to access list of dicts

description: Access list of dicts


rawDescription: How to properly test for valid characters in pattern, possibly using character arrays or some other method(regex)

description: Properly test for valid characters in pattern, possibly using character arrays or some other method(regex)


code:
aggr = lambda df, key, col: df.groupby(key)[col].transform('sum')
df['B as % of A'] = aggr(df, ('A', 'B'), 'Area') / aggr(df, 'A', 'Area')
df

rawDescription: How to perform operations on groups in pandas

description: Perform operations on groups in pandas


code:
import turtle as t
t.tracer(2,1) # pour accelerer le dessin
def arbre(branche,t):
    if branche > 5:
        t.forward(branche)
        t.right(20)
        arbre(branche-15,t)
        t.left(40)
        arbre(branche-15,t)
        t.right(20)
        t.backward(branche)

def main( n ):
    for k in range( n ):
        t.left(10)
        arbre(90,t)

t.color("green")
main(17)

t.right(80)
t.backward(50)
t.penup()
t.forward(25)
t.pendown()
t.right(60)

main(10)

rawDescription: How do I make this python turtle code smaller so it becomes a class?

description: Make this python turtle code smaller so it becomes a class


code:
import System
f = file('abc.txt', 'w+')
f.GetType().GetField('_stream', System.Reflection.BindingFlags.Instance |
                                System.Reflection.BindingFlags.NonPublic).GetValue(f)

rawDescription: Converting IronPython file object to .NET Stream object


code: next((i for i,x in enumerate(li) if 'amp' in x), None)

rawDescription: In Python, how do I find the index of an sub-item given a list?


code:
with open('MySourceFile', 'r') as sourcefile:
    source = sourcefile.read().splitlines()

with open('MyKeyFile', 'r') as keyfile:
    keys = keyfile.read().split()

with open('MyOutFile', 'w') as outfile:
    for line in source:
        if line.split():
            if line.split()[0] in keys:
                outfile.write(line + "\n")
outfile.close()

rawDescription: Python: Extracting lines from a file using another file as key


code:
import wx
import wx.wizard

class WizardPage(wx.wizard.PyWizardPage):
    def __init__(self, parent, title):
        wx.wizard.PyWizardPage.__init__(self, parent)
        self.next = None
        self.prev = None
        self.initializeUI(title)

    def initializeUI(self, title):
        # create grid layout manager
        self.sizer = wx.GridBagSizer()
        self.SetSizerAndFit(self.sizer)

    def addWidget(self, widget, pos, span):
        self.sizer.Add(widget, pos, span, wx.EXPAND)

    # getters and setters
    def SetPrev(self, prev):
        self.prev = prev

    def SetNext(self, next):
        self.next = next

    def GetPrev(self):
        return self.prev

    def GetNext(self):
        return self.next

########################################################################
class MyWizard(wx.wizard.Wizard):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.wizard.Wizard.__init__(self, None, -1, "Some Title")
        self.SetPageSize((500, 350))

        mypage1 = self.create_page1()

        forward_btn = self.FindWindowById(wx.ID_FORWARD)
        forward_btn.Disable()

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.onUpdate, self.timer)
        self.timer.Start(1)

        self.RunWizard(mypage1)

    #----------------------------------------------------------------------
    def create_page1(self):
        page1 = WizardPage(self, "Page 1")
        d = wx.StaticText(page1, label="test")
        page1.addWidget(d, (2, 1), (1,5))

        self.text1 = wx.TextCtrl(page1)
        page1.addWidget(self.text1, (3,1), (1,5))

        self.text2 = wx.TextCtrl(page1)
        page1.addWidget(self.text2, (4,1), (1,5))

        page2 = WizardPage(self, "Page 2")
        page2.SetName("page2")
        self.text3 = wx.TextCtrl(page2)
        self.Bind(wx.wizard.EVT_WIZARD_PAGE_CHANGED, self.onPageChanged)
        page3 = WizardPage(self, "Page 3")

        # Set links
        page2.SetPrev(page1)
        page1.SetNext(page2)
        page3.SetPrev(page2)
        page2.SetNext(page3)

        return page1

    #----------------------------------------------------------------------
    def onPageChanged(self, event):
        """"""
        page = event.GetPage()
        print
        if page.GetName() == "page2":
            self.text3.SetValue(self.text2.GetValue())

    #----------------------------------------------------------------------
    def onUpdate(self, event):
        """
        Enables the Next button if both text controls have values
        """
        value_one = self.text1.GetValue()
        value_two = self.text2.GetValue()
        if value_one and value_two:
            forward_btn = self.FindWindowById(wx.ID_FORWARD)
            forward_btn.Enable()
            self.timer.Stop()

#----------------------------------------------------------------------
def main():
    """"""
    wizard = MyWizard()

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

rawDescription: How do I pass information between pages of a wxPython PyWizardPage wizard?

description: Pass information between pages of a wxPython PyWizardPage wizard


code:
proxy = urllib2.ProxyHandler({'http': '127.0.0.1'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')

rawDescription: Proxy with urllib2

description: Proxy with urllib2


code:
def getwrap(my_dict, my_key, default=None):
    if default is None:
        return my_dict[my_key]
    else:
        return my_dict.get(my_key, default)

rawDescription: Idiomatic way of specifying default arguments whose presence/non-presence matter


rawDescription: How can I replace elements of a list with values of corresponding indices of another list?

description: Replace elements of a list with values of corresponding indices of another list


code:
import numpy as np

def radial_profile(data, center):
    y, x = np.indices((data.shape))
    r = np.sqrt((x - center[0])**2 + (y - center[1])**2)
    r = r.astype(np.int)

    tbin = np.bincount(r.ravel(), data.ravel())
    nr = np.bincount(r.ravel())
    radialprofile = tbin / nr
    return radialprofile

rawDescription: Most efficient way to calculate radial profile


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

np.random.seed(101)
zvals = np.random.rand(100, 100) * 10

# make a color map of fixed colors
cmap = colors.ListedColormap(['white', 'red'])
bounds=[0,5,10]
norm = colors.BoundaryNorm(bounds, cmap.N)

# tell imshow about color map so that only set colors are used
img = plt.imshow(zvals, interpolation='nearest', origin='lower',
                    cmap=cmap, norm=norm)

# make a color bar
plt.colorbar(img, cmap=cmap, norm=norm, boundaries=bounds, ticks=[0, 5, 10])

plt.savefig('redwhite.png')
plt.show()

rawDescription: Defining a discrete colormap for imshow in matplotlib


code:
cwd = os.path.join(os.getcwd(), "<scriptname>.py")
...
os.system('{} {}'.format('python', cmd))

rawDescription: When attempting run a python script from within another python script, I get 'permission denied'!


code:
def outcome(surveys,voters):
    out = np.random.random((surveys,voters))
    rep = [0]*surveys
    for i in range(0,surveys):
        rep[i] = sum(out[i,out[i,:]<0.49])
    return rep

rawDescription: How do I sum only certain elements from an array?

description: Sum only certain elements from an array


code:
def is_valid(template):
    return re.search(r'\{(?!(?:one|two|three)\}).*\}', template) is None

rawDescription: Using regex to reject a format string containing unrecognised parameters


rawDescription: Python floating point number comparison

description: Python floating point number comparison


code:
import asyncio

class SubprocessProtocol(asyncio.SubprocessProtocol):
    def pipe_data_received(self, fd, data):
        if fd == 1:
            text = data.decode()
            if len(text.strip()) > 16:
                print(text.strip())

    def process_exited(self):
        loop.stop()

loop = asyncio.get_event_loop()

ls = loop.run_until_complete(loop.subprocess_exec(
    SubprocessProtocol, 'watch', 'ls', '/proc'))
loop.run_forever()

rawDescription: Why is the output of my subprocess not being printed?


code:
units = []

# Your Unit constructor handles the creation of a new unit:
# No need to create a special function for that.
units.append(Unit(1,1))
units.append(Unit(1,2))

# etc...

print(units)

rawDescription: Automating creation of class instances in python for an undetermined amount of instances


code:
nw_to_se = [your_list[i][i] for i in range(3)]
ne_to_sw = [your_list[i][2-i] for i in range(3)]
diags = (nw_to_se, ne_to_sw)

rawDescription: Diagonal of a nested list in Python 3

description: Diagonal of a nested list in Python 3


code:
class spaceObj(object):
    storage = None

    def __init__(self):  # this is for testing only
        self.storage = {'total':100,'used':88,'free':1}

    def __getattr__(self, item):
        if item[:7] == 'getSize':  # check if an undefined attribute starts with this
            return self.getSize(item[7:])

    def getSize(self, what='total'):
        return self.storage[what.lower()]

print (spaceObj().getSizeTotal)  # 100

rawDescription: Python: dynamically generate method from string?


code:
class SingleNeedFormWithDescription(ModelForm):

    need = forms.ModelChoiceField(
        queryset=Need.objects.all(),
        widget=forms.TextInput)

rawDescription: I need display ModelChoiceField like CharField


code:
class MainFrame(QWidget):
    def __init__(self):
        self.popup_windows = [] # to store the pops

def display_popup_window(self, item):
    # item is the reference item that it's internal value reached 0
    popup_window = PopupFrame(self, item)
    popup_window.show()
    popup_window._raise()
    self.popup_windows.append(popup_window)

class PopupFrame(QWidget):
    def __init__(self, parent, item):
        self.parent = parent
        self.item = item
        # set up other things, like buttons, layout...
        self.options_button_completed.clicked.connect(self.set_completed)
        self.options_button_missed.clicked.connect(self.set_missed)
        self.options_button_delayed.clicked.connect(self.set_delayed)

    def set_completed(self):
        # do something with self.item
        pass

rawDescription: Proper way to deal with options in a pop up window


code:
class Foo(object):
  def __init__(bippity, colour):
    bippity.colour = colour
  def get_colour(_):
    return _.colour

f = Foo('Blue')
f.get_colour()

rawDescription: What is the difference between self and object parameters in __repr__ method?


code:
def ranmob():
    #randint(1,2)
    roll=Dice.die(2)
    if roll ==1:
        return Goblin(Goblin.name,Goblin.hp,Goblin.thaco,Goblin.ac,Goblin.inventory)
    if roll ==2:
        return Orc(Orc.name,Orc.hp,Orc.thaco,Orc.ac,Orc.inventory)

while True:
    #pick a new random monster
    mob = ranmob()
    #print the name of the random monster
    print(mob.name)

rawDescription: How to make this code pick a random number each call Python?

description: Make this code pick a random number each call Python


rawDescription: JSON serialization Error in Python 3.2

description: JSON serialization Error in Python 3.2


code: np.column_stack((b, a))

rawDescription: Insert 1-d numpy array as column in existing 2-d array


code:
min_idx = min(x, key=funct)
min_val = funct(min_idx)

rawDescription: Find global minimum for discrete function


code: np.concatenate([a[a==i][:2] for i in np.unique(a)])

rawDescription: numpy select fixed amount of values among duplicate values in array

description: Numpy select fixed amount of values among duplicate values in array


code:
import Folder1.facebook as pyfacebook
import Folder2.facebook as facebooksdk

rawDescription: Install two python modules with same name


code:
import json
parsed = json.loads(response.content)

rawDescription: Request returns bytes and I'm failing to decode them


rawDescription: Python Tkinter File Menu Options

description: Python Tkinter File Menu Options


code:
import win32gui
import win32con
taskbar = win32gui.FindWindow("Shell_TrayWnd", None)
trayArea = win32gui.FindWindowEx(taskbar, None, "TrayNotifyWnd", None)
win32gui.SetForegroundWindow(taskbar)
win32gui.SendMessage(trayArea, win32con.WM_SETFOCUS, 0, 0)

rawDescription: Putting the focus on the tray icons in Windows XP using Python


code:
import smtplib
server = smtplib.SMTP('localhost:2525')
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

rawDescription: SMTP and XMPP deployment/workflow

description: SMTP and XMPP deployment/workflow


code:
def _get_version():
    import hglib
    with hglib.open() as repo:
        [p] = repo.parents()
    return p[1]

version = _get_version()

rawDescription: How do I stop hg child process when using hglib

description: Stop hg child process when using hglib


code:
cursor = connection.cursor()
cursor.execute("""select to_char(allmonths.yeardate::date, 'YYYY/MM/DD') as monthdate,
                    COUNT("day") as bookings
                    from (
                    select distinct date_trunc('month', (date %s - offs)) as yeardate
                    from generate_series(0,365,28) as offs
                    ) as allmonths
                    left join bookings_bookedassetday
                    on EXTRACT(MONTH from "day")=EXTRACT(MONTH from yeardate)
                    and asset_id=%s and EXTRACT(YEAR from "day") = %s
                    group by allmonths.yeardate
                    order by allmonths.yeardate asc""", [year+'-12-31', id, year])

query = cursor.fetchall()

rawDescription: Django aggregation on a date range

description: Django aggregation on a date range


code:
import math
math.cos(90)
old_cos = math.cos
def new_cos(degrees):
    return old_cos(math.radians(degrees))
math.cos = new_cos
math.cos(90)

rawDescription: Override python package util method

description: Override python package util method


rawDescription: How do I plot a step function with Matplotlib in Python?

description: Plot a step function with Matplotlib in Python


code:
import jinja2
import os
# more imports

jinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class MainPage(webapp2.RequestHandler):
    def get(self):
         template = jinja_environment.get_template('index.html')
         self.response.out.write(template.render(template_values))

class NotFound(webapp.RequestHandler):
    def get(self):
         # you need to create the not_found.html file
         # check Using Templates from Getting Started for more
         template = jinja_environment.get_template('not_found.html')
         self.response.out.write(template.render(template_values))

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/.*', NotFound)], # <-- This line is important
                                      debug=True)

rawDescription: Catch All Script in App Engine Python (APP.YAML) does not work in Static Files


rawDescription: Converting to Precomposed Unicode String using Python-AppKit-ObjectiveC


code:
import numpy as np
import seaborn as sns
iris = sns.load_dataset("iris")
g = sns.pairplot(iris)
for i, j in zip(*np.triu_indices_from(g.axes, 1)):
    g.axes[i, j].set_visible(False)

rawDescription: Plot lower triangle in a seaborn Pairgrid


code:
filelist = ['D.txt','A.txt','S.txt']
wordbank = {}
for file in filelist:
    f = open(file, 'r')
    lines = f.readlines()
    for l in lines:
        line = l.split('\t')
        word = line[0]

        if word not in wordbank:
            wordbank[word] = 1
        else:
            wordbank[word] += 1
    f.close()

# Gather unique words
unique_words = []
for word in wordbank.keys():
    if wordbank[word] == 1:
        unique_words.append(word)

rawDescription: How do I only use one column of imported text file?

description: Only use one column of imported text file


code:
from BeautifulSoup import BeautifulSoup
import urllib2
import sys
lPreviewLinkList = []
bCapture = False
lLink = "http://www.afl.com.au/fixture?roundId=CD_R201401410#tround"
header = {'User-Agent': 'Mozilla/5.0'}
req_for_players = urllib2.Request(lLink,headers=header)
page_for_players = urllib2.urlopen(req_for_players)
soup_for_players = BeautifulSoup(page_for_players)

table_for_players = soup_for_players.find("table", { "class" : "fancy-zebra fixture" })
for row in table_for_players.findAll("tr"):
    for dateRow in row.findAll("th", {"colspan" : "4"}):
        bCapture = True if dateRow.text == "Saturday, May 24" else False
    if bCapture:
        for infoRow in row.findAll("td", {"class": "info"}):
            for link in infoRow.findAll("a", {"class" : "preview"}):
                lPreviewLinkList.append("http://www.afl.com.au/" + link.get('href'))

rawDescription: Unable to fetch certain data using beautifulsoup


code:
while True:
    start = time.time()
    some_long_process()
    end = time.time()
    remain = start + 10*60 - end
    if remain > 0:
        time.sleep(remain)

rawDescription: Rate Limit an Infinite While Loop in Python


code:
from sqlalchemy.orm import column_property

class Demo(...):
    data_uncompressed = column_property(func.uncompress(data))

rawDescription: SELECT UNCOMPRESS(text) FROM with sqlalchemy


code:
import requests
proxies = {
    "http": "http://username:password@proxyserver:port/",
    # "https": "https://username:password@proxyserver:port/",
}
url = 'http://google.com'
data = requests.get(url, proxies=proxies)

rawDescription: python httplib: connect through proxy with authentification

description: Python httplib: connect through proxy with authentification


code:
@route("/")
@route("/<url:re:.+>")
def hello(url):
   return template('page_template', url=url)

rawDescription: bottlepy route match any url with exceptions

description: Bottlepy route match any url with exceptions


code:
p = RespuestaPreguntaSeleccionMultiple.objects.all().values('respuesta').annotate(Count('respuesta'))

for item in p:
    item['respuesta__count']  # This will return 2
    item['respuesta']  # This will return 'Una vez'

rawDescription: How to access to a key of a result of .value() queryset

description: Access to a key of a result of .value() queryset


code:
import threading
import weakref

class A(object):
    instances = []
    lock = threading.RLock()

    @classmethod
    def _cleanup_ref(cls, ref):
        print('cleanup') # debug
        with cls.lock:
            try:
                cls.instances.remove(ref)
            except ValueError:
                pass

    def __init__(self):
        with self.lock:
            self.instances.append(weakref.ref(self, self._cleanup_ref))

# test
test = [A() for _ in range(3)]
for i in range(3,-1,-1):
    assert len(A.instances) == i
    if test:
        test.pop()

print("see if 3 are removed at exit")
test = [A() for _ in range(3)]

rawDescription: In Python: How to remove an object from a list if it is only referenced in that list?


code:
def plot(self):
    ultra_beam_point = np.array(self.Beam_points)
    for z,y in ultra_beam_point[:,:,1:]:
        plt.plot(z, y, color = "Blue")
    plt.title('Beam Path')
    plt.xlabel('z')
    plt.ylabel('y')
    plt.show()

rawDescription: Creating coordinates out of elements in arrays in lists in a bigger list


code:
def mouseMotion(self, buttons, pos, rel):

    if self.pressing == True:
        diffx = self.start[0] - pos[0]
        diffy = self.start[1] - pos[1]
        width = abs(self.start[0] - pos[0])
        height = abs(self.start[1] - pos[1])
        if diffx > 0 and diffy > 0:
            width = (width - (width * 2))
            height = (height - (height * 2))
        elif diffx > 0 and diffy <= 0:
            width = (width - (width * 2))
        elif diffx <= 0 and diffy > 0:
            height = (height - (height * 2))
        elif diffx < 0 and diffy < 0:
            pass

        dimensions = (width, height)
        self.box = pygame.Rect(self.start, dimensions)

        pygame.draw.rect(self.screen, (0,0,0), self.box, 1)

rawDescription: How to get the right values for mouse hold-and-drag boxing

description: Get the right values for mouse hold-and-drag boxing


code:
class AnimalBaseClass:
    def __init__(self):
        self._limbs = None

    @property
    def limbs(self):
        return self._limbs

    @limbs.setter
    def limbs(self, value):
        self.paws = value
        self._limbs = value

class BipedalMixIn:
    @property
    def limbs(self):
        return super().limbs

    @limbs.setter
    def limbs(self, value):
        self.bipedal = (value == 2)
        # works!
        super(BipedalMixIn, self.__class__).limbs.__set__(self, value)

class Bird(BipedalMixIn, AnimalBaseClass):
    pass

bird = Bird()
bird.limbs = 2
print(bird.bipedal)    # True
print(bird.paws)        # 2

rawDescription: Calling the setter of a super class in a mixin


code:
response = opener.open(self.__url, data)
if response.info().get('Content-Encoding') == 'gzip':
    buf = StringIO.StringIO( response.read())
    gzip_f = gzip.GzipFile(fileobj=buf)
    content = gzip_f.read()
else:
    content = response.read()

rawDescription: urllib2 opener providing wrong charset

description: Urllib2 opener providing wrong charset


code:
session.sendline(cmd)  # program started
# put here user interaction
# ... expect('(?i)password:'); sendline(passwd) ...
session.prompt()       # program ended (the shell prompt is shown)

rawDescription: Running sudo commands through pxssh

description: Running sudo commands through pxssh


code:
import io
import PIL
from hubarcode.datamatrix import DataMatrixEncoder

dm = DataMatrixEncoder("M103")
dm_in_bytes = io.BytesIO(dm.get_imagedata())
img = PIL.Image.open(dm_in_bytes)

img.show()

rawDescription: how to convert datamatrix code from hubarcode to PILimage

description: Convert datamatrix code from hubarcode to PILimage


code:
fileToWrite = open("somefile", "wb")
ftp.retrbinary("RETR somefile", lambda block: handleDownload(block, fileToWrite))

rawDescription: Pass a value to the ftp.retrbinary callback


code:
class GpsPoint(object):
    """A class for representing gps coordinates"""
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
    def __add__(self, other):
        try:
            return GpsPoint(self.x + other.x, self.y + other.y, self.z + other.z)
        except AttributeError:
            return GpsPoint(self.x + other, self.y + other, self.z + other)
    def __radd__(self, other):
        try:
            return GpsPoint(self.x + other.x, self.y + other.y, self.z + other.z)
        except AttributeError:
            return GpsPoint(self.x + other, self.y + other, self.z + other)
    def __str__(self):
        return "%d, %d, %d" % (self.x, self.y, self.z)

rawDescription: How do I implement polymorphic arithmetic operators pythonicly?

description: Implement polymorphic arithmetic operators pythonicly


code:
df = pd.Series(data= np.random.random(size=400), index=pd.date_range(start=datetime(2015,1,1,9,0,0), freq='1Min', periods=400)).cumsum()
df.loc[datetime(2015, 1, 1, 11, 30, 0): datetime(2015, 1, 1, 13, 0, 0)] = np.nan
df.index = df.index.to_series().apply(lambda x: x.strftime('%H:%M'))
df.dropna().plot.line()

rawDescription: how to draw the dataframe without the breaktime

description: Draw the dataframe without the breaktime


code:
numservers = 15 # put anything you want here
for i in range(1,numservers+1):
    print('server{}'.format(i))
    if i%5 == 0:
        print('*'*22)

rawDescription: Increment server number in double loop with separator every 5 servers


code: matcher = re.compile(myExpression, re.IGNORECASE)

rawDescription: Case insensitivity in Python strings

description: Case insensitivity in Python strings


code:
size = os.stat(fn).st_size
f = open(fn)
data = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)

m = re.search(r"867-?5309", data)

rawDescription: Python: find regexp in a file

description: Python: find regexp in a file


code:
def startServer(host):
    host.cmd( 'python server.py an_argument_to_server &' )

rawDescription: call function with arguments via instance.cmd()

description: Call function with arguments via instance.cmd()


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

fig,ax = plt.subplots(1)

# create some x data and some integers for the y axis
x = np.array([3,5,2,4])
y = np.arange(4)

# plot the data
ax.plot(x,y)

# tell matplotlib which yticks to plot
ax.set_yticks([0,1,2,3])

# labelling the yticks according to your list
ax.set_yticklabels(['A','B','C','D'])

rawDescription: Matplotlib line plot of x values against y


code:
import wx
class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'test frame',size=(790, 524))
        self.Bind(wx.EVT_LEFT_DOWN, self.OnClick)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.clip = wx.Clipboard()
        self.x = wx.BitmapDataObject()
        self.bmp = None

    def OnClick(self, evt):
        self.clip.Open()
        self.clip.GetData(self.x)
        self.clip.Close()
        self.bmp = self.x.GetBitmap()
        self.Refresh()

    def OnPaint(self, evt):
        if self.bmp:
            dc = wx.PaintDC(self)
            dc.DrawBitmap(self.bmp, 20, 20, True)

if __name__ == '__main__':
    app = wx.App()
    frame = MyFrame()
    frame.Show()
    app.MainLoop()

rawDescription: Reading an image from the clipboard with wxPython


code: z = np.random.binomial(500, 0.5, size=499)

rawDescription: Replace for loops by list comprehension

description: Replace for loops by list comprehension


code:
from multiprocessing import Pool
from multiprocessing import cpu_count

def handle_tiff(some_file):
    data_open = gdal.Open(some_file)
    data_array = data_open.ReadAsArray().astype(np.float32)
    return data_array

tiff_files = glob.glob('*.tif')
p = Pool(cpu_count()- an_integer)
all_data = p.map(handle_tiff, tiff_files)

rawDescription: Any solution for accelerating the reading of data from disk and converting them into numpy array for further processing?


code:
@app.route('/download/<int:id>')
def download_id(id):
    '''This downloads a certain image specified by *id*'''
    return ...

rawDescription: What tools are available to auto-produce documentation for a REST API written in Flask?


code:
b = Element("Batch")
b.append(Attribute("OnError","Continue")).append(Attribute("ListVersion","3"))
bm= Element("Method")
bm.append(Attribute("ID","1")).append(Attribute("Cmd","Update"))
bm.append(Element("Field").append(Attribute("Name","ID")).setText(''))
bm.append(Element('Field').append(Attribute('Name','FileRef')).setText('http://.....'))
bm.append(Element('Field').append(Attribute('Name','Jurisdiction')).setText('UK'))
bm.append(Element('Field').append(Attribute('Name','Desk')).setText('Structured Equity Derivatives'))
bm.append(Element('Field').append(Attribute('Name','Business Area')).setText('Back Office'))
bm.append(Element('Field').append(Attribute('Name','Title')).setText('whatever'))
b.append(bm)
u = Element("ns1:updates")
u.append(b)
c.service.UpdateListItems("Reports",u)

rawDescription: How to update document's metadata in Sharepoint? (Linux -> WebServices -> Sharepoint)

description: Update document's metadata in Sharepoint? (Linux -> WebServices -> Sharepoint)


code:
import select
...
scan_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
poll_obj = select.poll()
poll_obj.register(scan_process.stdout, select.POLLIN)
while(some_criterium and not time_limit):
    poll_result = poll_obj.poll(0)
    if poll_result:
        line = scan_process.stdout.readline()
        some_criterium = do_something(line)
    update(time_limit)

rawDescription: timeout on subprocess readline in python

description: Timeout on subprocess readline in python


code:
class HelloWorld(object):

    @cherrypy.expose
    def index(self):

        plt.plot([1,2,3,4])

        img = StringIO.StringIO()

        plt.savefig(img,format='png') # step 1.

        imagedata = img.getvalue() # step 2.

        encoded = base64.b64encode(imagedata) # step 3.

        page =  """

        """
        return page.format(encoded) # step 4.

cherrypy.quickstart(HelloWorld())

rawDescription: Cherrypy image in HTML

description: Cherrypy image in HTML


code:
def writebuffered(self, zinfo_or_arcname, file_pointer, file_size, compress_type=None):
    if not isinstance(zinfo_or_arcname, ZipInfo):
        zinfo = ZipInfo(filename=zinfo_or_arcname,
                        date_time=time.localtime(time.time())[:6])

        zinfo.compress_type = self.compression
        if zinfo.filename[-1] == '/':
            zinfo.external_attr = 0o40775 << 16   # drwxrwxr-x
            zinfo.external_attr |= 0x10           # MS-DOS directory flag
        else:
            zinfo.external_attr = 0o600 << 16     # ?rw-------
    else:
        zinfo = zinfo_or_arcname

    zinfo.file_size = file_size            # Uncompressed size
    zinfo.header_offset = self.fp.tell()    # Start of header bytes
    self._writecheck(zinfo)
    self._didModify = True

    fp = file_pointer
    # Must overwrite CRC and sizes with correct data later
    zinfo.CRC = CRC = 0
    zinfo.compress_size = compress_size = 0
    # Compressed size can be larger than uncompressed size
    zip64 = self._allowZip64 and \
            zinfo.file_size * 1.05 > ZIP64_LIMIT
    self.fp.write(zinfo.FileHeader(zip64))
    if zinfo.compress_type == ZIP_DEFLATED:
        cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
             zlib.DEFLATED, -15)
    else:
        cmpr = None
    file_size = 0
    while 1:
        buf = fp.read(1024 * 8)
        if not buf:
            break
        file_size = file_size + len(buf)
        CRC = crc32(buf, CRC) & 0xffffffff
        if cmpr:
            buf = cmpr.compress(buf)
            compress_size = compress_size + len(buf)
        self.fp.write(buf)

    if cmpr:
        buf = cmpr.flush()
        compress_size = compress_size + len(buf)
        self.fp.write(buf)
        zinfo.compress_size = compress_size
    else:
        zinfo.compress_size = file_size
    zinfo.CRC = CRC
    zinfo.file_size = file_size
    if not zip64 and self._allowZip64:
        if file_size > ZIP64_LIMIT:
            raise RuntimeError('File size has increased during compressing')
        if compress_size > ZIP64_LIMIT:
            raise RuntimeError('Compressed size larger than uncompressed size')
    # Seek backwards and write file header (which will now include
    # correct CRC and file sizes)
    position = self.fp.tell()       # Preserve current position in file
    self.fp.flush()
    self.filelist.append(zinfo)
    self.NameToInfo[zinfo.filename] = zinfo

rawDescription: How to zip a very large file in python

description: Zip a very large file in python


code:
b.write_i2c_block_data(0x31, 5, [0, 8]) # write number 8 to digit 0
b.write_i2c_block_data(0x31, 5, [4, 5]) # write number 5 to digit 4 etc etc

rawDescription: Python i2c write_bus_data usage

description: Python i2c write_bus_data usage


rawDescription: Matrix inversion without Numpy

description: Matrix inversion without Numpy


code:
class Cache:
     myvar = 1

def foo():
    Cache.myvar = 2

rawDescription: An alternative to global in Python

description: An alternative to global in Python


code:
from skimage import data
from skimage import filter
from skimage import img_as_float
import matplotlib.pyplot as plt

unsharp_strength = 0.8
blur_size = 8  # Standard deviation in pixels.

# Convert to float so that negatives don't cause problems
image = img_as_float(data.camera())
blurred = filter.gaussian_filter(image, blur_size)
highpass = image - unsharp_strength * blurred
sharp = image + highpass

fig, axes = plt.subplots(ncols=2)
axes[0].imshow(image, vmin=0, vmax=1)
axes[1].imshow(sharp, vmin=0, vmax=1)
plt.show()

rawDescription: Image filtering with scikit-image?

description: Image filtering with scikit-image


code:
str1="ABCD"
str2="ABCD is ABCD"
str2.count(str1)

rawDescription: to count the occurrence of one string in other string in python

description: To count the occurrence of one string in other string in python


rawDescription: python equivalent of this short java code

description: Python equivalent of this short java code


code:
for (key, value) in set(data1.items()) ^ set(data2.items()):
        print(key, value)

rawDescription: Get non-matching data when comparing python dicts and store them


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

x = np.linspace(0,1,20)
z1 = x[:,np.newaxis] * x
y = np.linspace(0,1,32)
z2 = y[:,np.newaxis] * y

fig = plt.figure(figsize=(2,1))
plt.figimage(z1, 25, 25, cmap='gray') # X, Y offsets are in pixels
plt.figimage(z2, 75, 25, cmap='gray')

plt.show()

rawDescription: How to set imshow scale

description: Set imshow scale


code:
if "\n" in data:
    data = data.replace("\r", "")
else:
    data = data.replace("\r", "\n")

rawDescription: Split double new lines in platform independent manner


code:
from tkinter import *

class window_design:

    def __init__(self):
        root=Tk()
        root.title("Bag Weight")
        #root.geometry("500x700")
        root.wm_iconbitmap('favicon.ico')

        image=PhotoImage(file="Weight Program.png")
        imagelabel=Label(root,image=image)
        imagelabel.pack()

        weightentrylabel=Label(root,text="Enter Weight!")
        weightentrylabel.pack()

        self.string=StringVar()
        weightentry=Entry(root,textvariable=self.string)
        weightentry.pack()

        menutext=Label(root,text="What coin are you using?")
        #menutext.pack(side=LEFT)
        menutext.pack()

        values=['1p','2p','5p','10p','20p','50p','£1','£2','Exit']

        button1=Button(root,text="1p",command=self.btn1)
        #button1.pack(side=LEFT)
        button1.pack()

        #--------------------------------------------------
        self.result=StringVar()
        resultlabel=Label(root, textvariable = self.result)
        resultlabel.pack()
        #--------------------------------------------------

        root.mainloop()
    #-------------------------------------
    def btn1(self):
        p1=3.56
        p1should=356
        if not self.string.get(): return

        value = int(self.string.get())
        if value > p1should:
            weightdif = value - p1should
            coins=weightdif/p1

        elif value < p1should:
            weightdif=p1should - value
            coins=weightdif/p1

        self.result.set(coins)
    #-----------------------------------

window_design()

rawDescription: How Do I assign a function to a button in Python/TKinter?


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

matplotlib.rcParams['xtick.direction'] = 'out'
matplotlib.rcParams['ytick.direction'] = 'out'

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
# difference of Gaussians
Z = 10.0 * (Z2 - Z1)

Z[X<-1] = None
Z[X>2] = None

plt.figure()
CS = plt.contour(X, Y, Z, levels=np.arange(-.5, 2, .5))
plt.clabel(CS, inline=1, fontsize=10)
plt.title('Simplest default with labels')

plt.show()

rawDescription: Non-closed contours in matplotlib?

description: Non-closed contours in matplotlib


code:
from django.db import models

class PersonManager(models.Manager):
    def get_by_natural_key(self, first_name, last_name):
        return self.get(name=first_name)

class Person(models.Model):
    objects = PersonManager()

    name = models.CharField(max_length=100)

    birthdate = models.DateField()

class Meta:
    unique_together = (('name'),)

rawDescription: Changing String Representation of JSON Serialized Foreign Key


code:
a = create_object()
b = create_object()
c = create_object()

rawDescription: Initialise several variables at once to the same object but different instances


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

pivoted_table = df.pivot(index='x_specie', columns='y_species', values='r_value')
pivoted_table.fillna(0, inplace=True)
plt.pcolor(pivoted_table.values, cmap=plt.cm.Reds)
plt.show()

rawDescription: How to transform a pandas dataframe into a heatmap compatible dataframe?

description: Transform a pandas dataframe into a heatmap compatible dataframe


code: array.reshape((8,1)) > lower_bounds

rawDescription: Numpy vectorized less than/greater than comparisons