code:
def Sierpienski(A,B,C,n):

    if n==0:#On trace le triangle
        line(A[0],A[1],B[0],B[1])#AB
        line(B[0],B[1],C[0],C[1])#BC
        line(C[0],C[1],A[0],A[1])#CA
        return

    MAB=[int((A[0]+B[0])/2),int((A[1]+B[1])/2)]#Milieu de AB
    MBC=[int((B[0]+C[0])/2),int((B[1]+C[1])/2)]#Milieu de BC
    MCA=[int((C[0]+A[0])/2),int((C[1]+A[1])/2)]#Milieu de CA

    Sierpienski(A, MAB, MCA, n-1)
    Sierpienski(MAB, MBC, B, n-1)
    Sierpienski(C, MBC, MCA, n-1)

    return

rawDescription: Infinite loop in recursive program

description: Infinite loop in recursive program


code:
def SSN():
    store = {}
    while True:
        name = input('Enter Name: ')
        if not name:
            for k, v in store.items():
                print(k + ' has SSN ' + v)
            break

        if name in store:
            if input(name + ' has SSN ' + store[name] + '. Update? ') != 'y':
                continue

        store[name] = input('Enter SSN: ')

rawDescription: How can I implement this program using a dictionary rather than a list?

description: Implement this program using a dictionary rather than a list


code:
from wtforms.widgets import Select

class ChoicesSelect(Select):
    def __init__(self, multiple=False, choices=()):
        self.choices = choices
        super(ChoicesSelect, self).__init__(multiple)

    def __call__(self, field, **kwargs):
        field.iter_choices = lambda: ((val, label, val == field.default)
                                      for val, label in self.choices)
        return super(ChoicesSelect, self).__call__(field, **kwargs)

UserEdit = model_form(User, exclude=['password'], field_args={
    'role': {
        'widget': ChoicesSelect(choices=ROLE.items()),
    }
})

rawDescription: How-to customize WTForm model_form field mapping?


rawDescription: python how to access a variable, whose name in another variable

description: Python how to access a variable, whose name in another variable


code:
import time
import contextlib

from tornado.ioloop import IOLoop
import tornado.web
from tornado import gen

@gen.coroutine
def async_sleep(timeout):
    yield gen.Task(IOLoop.instance().add_timeout, time.time() + timeout)

@contextlib.contextmanager
def auto_timeout(self, timeout=2): # Seconds
    handle = IOLoop.instance().add_timeout(time.time() + timeout, self.timed_out)
    try:
        yield handle
    except Exception as e:
        print("Caught %s" % e)
    finally:
        IOLoop.instance().remove_timeout(handle)
        if not self._timed_out:
            self.finish()
        else:
            raise Exception("Request timed out") # Don't continue on passed this point

class TimeoutableHandler(tornado.web.RequestHandler):
    def initialize(self):
        self._timed_out = False

    def timed_out(self):
        self._timed_out = True
        self.write("Request timed out!\n")
        self.finish()  # Connection to client closes here.
        # You might want to do other clean up here.

class MainHandler(TimeoutableHandler):

    @gen.coroutine
    def get(self):
        with auto_timeout(self): # We'll timeout after 2 seconds spent in this block.
            self.sleeper = async_sleep(5)
            yield self.sleeper
        print("writing")  # get will abort before we reach here if we timed out.
        self.write("hey\n")

    def on_connection_close(self):
        # This isn't the greatest way to cancel a future, since it will not actually
        # stop the work being done asynchronously. You'll need to cancel that some
        # other way. Should be pretty straightforward with a DB connection (close
        # the cursor/connection, maybe?)
        self.sleeper.set_exception(Exception("cancelled"))

application = tornado.web.Application([
    (r"/test", MainHandler),
])
application.listen(8888)
IOLoop.instance().start()

rawDescription: Right way to "timeout" a Request in Tornado


rawDescription: tricky folder structure problem

description: Tricky folder structure problem


code:
gtk.gdk.threads_init()

...

def on_button_clicked(button):
    label.set_text("Doing something...")
    threading.Thread(target=do_something).start()

def do_something():
    time.sleep(2)
    glib.idle_add(label.set_text, "Done")

rawDescription: GTK networking app: need design pattern

description: GTK networking app: need design pattern


code:
def figure_it_out(adding_list):
    now = 1
    while now == 1:
        added = int(input("Enter the number for the list: "))
        adding_list.append(added)
        adding_list = list(set(adding_list))

        answer = input("Would you like to add another number? (yes or no): ")

        if answer == 'yes':
            now = 1
        elif answer == 'no':
            return adding_list

def main():
    adding_list = [0]

    cur_list = figure_it_out(adding_list)

    print(cur_list)

main()

rawDescription: Adds input to a list of numbers, if the number isn't already in the list - Python


code:
pdfAttachment = MIMEApplication(pdf, _subtype = "pdf")
pdfAttachment.add_header('content-disposition', 'attachment', filename = ('utf-8', '', 'payment.pdf'))
text = MIMEMultipart('alternative')
text.attach(MIMEText("Some plain text", "plain", _charset="utf-8"))
text.attach(MIMEText("Some HTML text
Some HTML Text
 Another line of text", "html", _charset="utf-8"))
message = MIMEMultipart('mixed')
message.attach(text)
message.attach(pdfAttachment)
message['Subject'] = 'Test multipart message'
f = open("message.msg", "wb")
f.write(bytes(message.as_string(), 'utf-8'))
f.close()

rawDescription: Sending a PDF attachment with a HTML+plain_text email in Python


rawDescription: How to reference numpy matrix as Excel indexes

description: Reference numpy matrix as Excel indexes


code:
import Tkinter as tk
import Queue as queue

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.queue = queue.Queue()

        buttonFrame = tk.Frame(self)
        for i in range(10):
            b = tk.Button(buttonFrame, text=str(i),
                          command=lambda button=i: self.press(button))
            b.pack(side="top", fill="x")
        self.lb = tk.Listbox(self, width=60, height=20)
        self.vsb = tk.Scrollbar(self, command=self.lb.yview)
        self.lb.configure(yscrollcommand=self.vsb.set)

        buttonFrame.pack(side="left", fill="y")
        self.vsb.pack(side="right", fill="y")
        self.lb.pack(side="left", fill="both", expand=True)

        self.manage_queue()

    def press(self, i):
        '''Add a button to the queue'''
        item = "Button %s" % i
        self.queue.put(item)
        self.log("push", item)

    def log(self, action, item):
        '''Display an action in the listbox'''
        message = "pushed to queue" if action == "push" else "popped from queue"
        message += " '%s' (queue size %s)" % (item, self.queue.qsize())
        self.lb.insert("end", message)
        self.lb.see("end")

    def manage_queue(self):
        '''pull an item off the queue and act on it'''
        try:
            item = self.queue.get_nowait()
            self.log("pop", item)
        except queue.Empty:
            pass

        # repeat again in 1 second
        self.after(1000, self.manage_queue)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: Tkinter background while loop

description: Tkinter background while loop


code:
# if someone tried to log something before basicConfig is called, Python creates a default handler that
# goes to the console and will ignore further basicConfig calls. Remove the handler if there is one.
root = logging.getLogger()
if root.handlers:
    for handler in root.handlers:
        root.removeHandler(handler)
logging.basicConfig(format='%(asctime)s %(message)s',level=logging.DEBUG)

rawDescription: Python logging before you run logging.basicConfig?


code:
import pygame
import math

pygame.init()

screen = pygame.display.set_mode((200, 200))
run = True
pos = (100, 100)
clock = pygame.time.Clock()

# speed of your player
speed = 2

# key bindings
move_map = {pygame.K_LEFT: (-1, 0),
            pygame.K_RIGHT: (1, 0),
            pygame.K_UP: (0, -1),
            pygame.K_DOWN: (0, 1)}

while run:
  screen.fill((0, 255, 0))
  # draw player, but convert position to integers first
  pygame.draw.circle(screen, (255, 0, 0), map(int, pos), 10)
  pygame.display.flip()

  # determine movement vector
  pressed = pygame.key.get_pressed()
  move_vector = (0, 0)
  for m in (move_map[key] for key in move_map if pressed[key]):
    move_vector = map(sum, zip(move_vector, m))

  # normalize movement vector if necessary
  if sum(map(abs, move_vector)) == 2:
    move_vector = [p/1.4142 for p in move_vector]

  # apply speed to movement vector
  move_vector = [speed*p for p in move_vector]

  # update position of player
  pos = map(sum, zip(pos, move_vector))

  for e in pygame.event.get():
    if e.type == pygame.QUIT: run = False

  clock.tick(60)

rawDescription: Pygame: key.get_pressed() does not coincide with the event queue


code:
import pygame, pygame.font, pygame.event, pygame.draw, string
from pygame.locals import *

def display_box(screen, message):
    fontobject=pygame.font.SysFont('Arial', 18)
    if len(message) != 0:
        screen.blit(fontobject.render(message, 1, (255, 255, 255)),
                ((screen.get_width() / 2) - 100, (screen.get_height() / 2) - 10))
    pygame.display.flip()

def get_key():
    while True:
        event = pygame.event.poll()
        if event.type == KEYDOWN:
            return event.key

if __name__ == "__main__":
    # Graphics initialization
    full_screen = False
    window_size = (1024, 768)
    pygame.init()
    if full_screen:
        surf = pygame.display.set_mode(window_size, HWSURFACE | FULLSCREEN | DOUBLEBUF)
    else:
        surf = pygame.display.set_mode(window_size)

    # Create a display box
    while True:
        display_box(surf, "hello world")
        inkey = get_key()
        if inkey == K_RETURN or inkey == K_KP_ENTER:
            break
        pygame.display.flip()

rawDescription: How to display text?

description: Display text


code:
def callback_2(request):
    if request.user.is_authenticated():
        code    = request.GET.get('code')
        state   = request.GET.get('state')

        url     = fitbit_url_access_2
        data    = "client_id="      + auth_2_client_id      + "&" +\
                  "grant_type="     + "authorization_code"  + "&" +\
                  "redirect_uri="   + redirect_uri_special  + "&" +\
                  "code="           + code

        headers     = {
            'Authorization': 'Basic ' + base64.b64encode(auth_2_client_id + ':' + consumer_secret),
            'Content-Type': 'application/x-www-form-urlencoded'}

        r = requests.post(url, data=data, headers=headers).json()

rawDescription: OAUTH2 - Fitbit using requests_oauthlib

description: OAUTH2 - Fitbit using requests_oauthlib


code:
from itertools import groupby
[list(g) for k, g in groupby(numbers, delimiters.__contains__) if not k]

rawDescription: Split a list into chunks with multiple integer delimiters


code:
class MyAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        form.save()
        obj.answer = remote_upload(obj.file.path)
        obj.save()

rawDescription: Django admin process file after upload complete


code:
message = mail.EmailMessage(sender="Me <me@gmail.com>",
        subject="Shop Export",
        attachments=[("shops.csv", self.response.body)])

rawDescription: GAE Python - How to attach the results of csv.writer to an email?


code:
#!/usr/bin/env python

# This sample shows how to take advantage of wx.CallAfter when running a
# separate thread and updating the GUI in the main thread

import wx
import threading
import time

class MainFrame(wx.Frame):

    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title='CallAfter example')

        panel = wx.Panel(self)
        self.label = wx.StaticText(panel, label="Ready")
        self.btn = wx.Button(panel, label="Start")
        self.gauge = wx.Gauge(panel)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.label, proportion=1, flag=wx.EXPAND)
        sizer.Add(self.btn, proportion=0, flag=wx.EXPAND)
        sizer.Add(self.gauge, proportion=0, flag=wx.EXPAND)

        panel.SetSizerAndFit(sizer)
        self.Bind(wx.EVT_BUTTON, self.OnButton)

    def OnButton(self, event):
        """ This event handler starts the separate thread. """
        self.btn.Enable(False)
        self.gauge.SetValue(0)
        self.label.SetLabel("Running")

        thread = threading.Thread(target=self.LongRunning)
        thread.start()

    def OnLongRunDone(self):
        self.gauge.SetValue(100)
        self.label.SetLabel("Done")
        self.btn.Enable(True)

    def LongRunning(self):
        """This runs in a different thread.  Sleep is used to
         simulate a long running task."""
        time.sleep(3)
        wx.CallAfter(self.gauge.SetValue, 20)
        time.sleep(5)
        wx.CallAfter(self.gauge.SetValue, 70)
        time.sleep(4)
        wx.CallAfter(self.OnLongRunDone)

if __name__ == "__main__":
    app = wx.App(0)
    frame = MainFrame(None)
    frame.Show()
    app.MainLoop()

rawDescription: Implementing my own event loop in a wxPython application


code:
class MyModelManager(models.Manager):
    def get_queryset(self):
        return super(MyModelManager, self).get_queryset().filter(active=True)

class MyModel(models.Model):
    timestamp = models.DateTimeField(default=datetime.utcnow)
    active = models.BooleanField(default=True)

    objects = MyModelManager()

    class Meta:
        ordering = ['-timestamp']

rawDescription: Default filter in Django model

description: Default filter in Django model


code:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib
from matplotlib.ticker import MaxNLocator

fig = plt.figure(figsize=(15,15))
gs1 = gridspec.GridSpec(8, 2)

gs1.update(left=0.05, right=0.95, wspace=0.05, hspace=0.05)

ax1 = plt.subplot(gs1[0:4, 0]) # Original
ax2 = plt.subplot(gs1[0:4, 1]) # Model
ax3 = plt.subplot(gs1[4:8, 0]) # Residual+Sky
ax4 = plt.subplot(gs1[4:7, 1]) # SB profile
ax5 = plt.subplot(gs1[7:8, 1])# SB residuals

# Hide tick labels
plt.setp(ax1.get_yticklabels(), visible=False)
plt.setp(ax1.get_xticklabels(), visible=False)
plt.setp(ax2.get_yticklabels(), visible=False)
plt.setp(ax2.get_xticklabels(), visible=False)
plt.setp(ax3.get_yticklabels(), visible=False)
plt.setp(ax3.get_xticklabels(), visible=False)
plt.setp(ax4.get_xticklabels(), visible=False)

ax4.invert_yaxis()
ax4.set_ylabel(r'Surface Brightness, $\mu$ [mag arcsec$^{-2}$]')
ax5.set_ylabel(r'$\Delta\mu$')
ax5.set_xlabel('Semi-major Axis [arcsec]')
ax5.grid(b=True)
ax4.set_xscale('log')
ax5.set_xscale('log')

gs1.tight_layout(fig)

nbins = len(ax5.get_xticklabels())
ax5.yaxis.set_major_locator(MaxNLocator(nbins=nbins, prune='upper'))
ax4.yaxis.set_major_locator(MaxNLocator(nbins=nbins, prune='upper'))

# change axis location of ax5
pos4 = ax4.get_position()
pos5 = ax5.get_position()

points4 = pos4.get_points()
points5 = pos5.get_points()

points5[1][1]=points4[0][1]

pos5.set_points(points5)

ax5.set_position(pos5)
# Show the plot
plt.show()

rawDescription: Shrinking space between individual subplots in Matplotlib Gridspec with tight_layout()


code:
from heapq import nlargest
from operator import itemgetter

largest_15 = nlargest(15, (line.split()[:2] for line in f), itemgetter(1))

rawDescription: Good way to keep a list of lists sorted on second element when appending new elements?


code:
__author__ = 'Dania'
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from Tkinter import *

class mclass:
    def __init__(self,  window):
        self.window = window
        self.box = Entry(window)
        self.button = Button (window, text="check", command=self.plot)
        self.box.pack ()
        self.button.pack()

    def plot (self):
        x=np.array ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
        v= np.array ([16,16.31925,17.6394,16.003,17.2861,17.3131,19.1259,18.9694,22.0003,22.81226])
        p= np.array ([16.23697,     17.31653,     17.22094,     17.68631,     17.73641 ,    18.6368,
            19.32125,     19.31756 ,    21.20247  ,   22.41444   ,  22.11718  ,   22.12453])

        fig = Figure(figsize=(6,6))
        a = fig.add_subplot(111)
        a.scatter(v,x,color='red')
        a.plot(p, range(2 +max(x)),color='blue')
        a.invert_yaxis()

        a.set_title ("Estimation Grid", fontsize=16)
        a.set_ylabel("Y", fontsize=14)
        a.set_xlabel("X", fontsize=14)

        canvas = FigureCanvasTkAgg(fig, master=self.window)
        canvas.get_tk_widget().pack()
        canvas.draw()

window= Tk()
start= mclass (window)
window.mainloop()

rawDescription: Placing plot on Tkinter main window in Python


code:
df_a = pd.DataFrame(randn(3, 2), columns=["x", "y"], index=range(3))
df_b = pd.DataFrame(randn(3, 2), columns=["x", "y"], index=range(3))
pd.concat([df_a, df_b], keys=['a', 'b'])

rawDescription: Building a hierarchically indexed DataFrame from existing DataFrames


code: if w == u"ה.": print (w)

rawDescription: comparing hebrew strings in python

description: Comparing hebrew strings in python


code:
import ast
a, b, c, d = ast.literal_eval(open('file.txt').read())
a
b
c
d

rawDescription: Reading .txt for separate variables in Python 3.3


rawDescription: SQLAlchemy with count, group_by and order_by using the ORM


code: [x for x in myList if len(x) == 5 and x[3] == Status and x[2]>x[4]]

rawDescription: searching through a list within lists

description: Searching through a list within lists


code:
import warnings
from sqlalchemy import exc as sa_exc

with warnings.catch_warnings():
    warnings.simplefilter("ignore", category=sa_exc.SAWarning)
    # code here...

rawDescription: Turn off a warning in sqlalchemy

description: Turn off a warning in sqlalchemy


code:
patterns = [re.compile('\\b'+name[idx]+'\\b') for idx in index]
for i, row in enumerate(data):
    for j, patt in enumerate(patterns):
        x[i, j] = len(patt.findall(row[1]))
        y[i, j] = len(patt.findall(row[2]))

rawDescription: Nested For Loops Numpy Array: Is vectorizing possible?


code:
import re
sequence = 'aaabbbaaacccdddeeefff'
query = 'aaa'
r = re.compile(query)
[[m.start(),m.end()] for m in r.finditer(sequence)]

rawDescription: Regex findall start() and end() ? Python


code: s = s.extra(track_scores=True)

rawDescription: How to enable track_scores in elasticsearch-dsl python

description: Enable track_scores in elasticsearch-dsl python


rawDescription: Select column based on condition on other column, vectorized, pandas


code: ["A" if x == 9 else "B" for x in range(0,10)]

rawDescription: the right expression for ["A" for x in range(0,10) or "B" if x == 9] in python?

description: The right expression for ["A" for x in range(0,10) or "B" if x == 9] in python


code:
#!/usr/bin/env python3

from PIL import Image
from PIL import ImageDraw

im = Image.open("existing.jpg")
logo = Image.open("python-32.png")

back = Image.new('RGBA', im.size)
back.paste(im)
poly = Image.new('RGBA', (512,512))
pdraw = ImageDraw.Draw(poly)
pdraw.polygon([(128,128),(384,384),(128,384),(384,128)],
          fill=(255,255,255,127),outline=(255,255,255,255))

back.paste(poly, (0,0), mask=poly)
back.paste(logo, (im.size[0]-logo.size[0], im.size[1]-logo.size[1]), mask=logo)

back.show()

rawDescription: PIL - Add semi-transparent polygon to JPEG


code:
from tkinter import *

root = Tk()

def showGrid():
    row    = btn.grid_info()['row']      # Row of the button
    column = btn.grid_info()['column']   # grid_info will return dictionary with all grid elements (row, column, ipadx, ipday, sticky, rowspan and columnspan)
    print("Grid position of 'btn': {} {}".format(row, column))

btn = Button(root, text = 'Click me!', command = showGrid)
btn.grid(row = 0, column = 0)

root.mainloop()

rawDescription: How to retrieve the row and column information of a button and use this to alter its settings in python

description: Retrieve the row and column information of a button and use this to alter its settings in python


code:
class MyModelView(ModelView):
    column_labels = dict(last_name='CUSTOM LAST NAME')

    def is_accessible(self):
        return current_user.is_authenticated()

rawDescription: Custom name of field in Flask-Admin

description: Custom name of field in Flask-Admin


code: regex = re.compile(r"^(?!.*(?:€|£|\b(?:Euro?|Pound|GBP|Yen|JPY)\b))", re.UNICODE | re.I)

rawDescription: Insert negative lookahead when joining multiple re.compile


code:
import datetime
import time
import threading

class AddToList(threading.Thread):

    def __init__(self, lock, entryList):
        threading.Thread.__init__(self)
        self.totalAdded = 0
        self.entryList = entryList
        self.lock = lock

    def run(self):
        while True:
            self.lock.acquire()
            entryList.append("AddToList at {}".format(datetime.datetime.now()))
            self.totalAdded += 1
            self.lock.release()
            print("totalAdded: {}".format(self.totalAdded))
            time.sleep(2)

class SaveList(threading.Thread):
    def __init__(self, lock, entryList):
        threading.Thread.__init__(self)
        self.totalSaved = 0
        self.entryList = entryList
        self.lock = lock

    def run(self):
        while True:
            self.lock.acquire()
            self.totalSaved += len(self.entryList)
            del self.entryList[:]
            self.lock.release()
            print("totalSaved: {}".format(self.totalSaved))
            time.sleep(3)

if __name__=="__main__":
    lock=threading.Lock()
    entryList=[]

    addClass = AddToList(lock, entryList)
    addClass.start()

    saveClass = SaveList(lock, entryList)
    saveClass.start()

rawDescription: multi threads modify a global list in python

description: Multi threads modify a global list in python


code:
turtles = [tx, ty, tz, ti, tj]
for turtle in turtles:
    turtle.fd()

rawDescription: How to use one method for various same type objects in python?

description: Use one method for various same type objects in python


rawDescription: Merge two lists,one as keys, one as values, into a dict in Python


code:
def create_subplot(data, ax=None):
    if ax is None:
        ax = plt.gca()
    more_data = do_something_on_data()
    bp = ax.boxplot(more_data)
    return bp

# make figure with subplots
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(10,5))
create_subplot(data, ax1)

rawDescription: IPython/matplotlib: Return subplot from function


code:
indices = np.where(bool_vect)[0]
out1 = M.tocsc()[:,indices]
out2 = M.tocsr()[indices,:]

rawDescription: Slicing Sparse Matrices in Scipy -- Which Types Work Best?


code:
class point(object):
    @classmethod
    def from_coordinates(cls, x, y):
        pt = cls()
        pt.x, pt.y = x, y
        return pt

rawDescription: How to define a method like int.from_bytes() in Python?

description: Define a method like int.from_bytes() in Python


code:
text = nltk.word_tokenize("They refuse to permit us to obtain the refuse permit")
nltk.pos_tag(text)

rawDescription: Does NLTK parts of speech tagger use global information or just the word that is being tagged?


code:
import re
a = 'aaaa bbbb cccc:dd eeee:ff ggg hhhh iiii:jjjj kkkk:llll:mm nnn:ooo pppp qqqq:rrr'
print(re.findall(r'([^:]*:[^ ]*) *', a))

rawDescription: python split string on whitespace following specific character

description: Python split string on whitespace following specific character


code:
process = subprocess.Popen(your_cmd, shell=true, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

count=0
while True:
    buff = process.stdout.readline()

    if buff == '':
        count += 1

    if buff == '' and process.poll() != None:
        break

    sys.stdout.write(buff)

process.wait()

rawDescription: Retrieving stdout from subprocess in Windows


code:
import numpy as np

x = np.array([0,1,2,3,4,5])
y = np.array([2.1, 2.9, 4.15, 4.98, 5.5, 6])

z = np.polyfit(x, y, 1)
p = np.poly1d(z)

#plotting
import matplotlib.pyplot as plt
xp = np.linspace(-1, 6, 100)
plt.plot(x, y, '.', xp, p(xp))
plt.show()

rawDescription: Least square method in python

description: Least square method in python


code:
import datetime
import numpy as np
n = np.array([5,7,3])
d = np.array([datetime.datetime(2013, 1, 1, 12, 0), datetime.datetime(2013, 9, 1, 12, 0), datetime.datetime(2013, 5, 1, 12, 0)])
n[np.argsort(d)]

rawDescription: Sort numpy array by datetime objects

description: Sort numpy array by datetime objects


code:
# Find contours at a constant value of 0.8
contours = measure.find_contours(r_grey, 0.8)

# Display the image and plot all contours found
plt.imshow(r, interpolation='nearest')

for n, contour in enumerate(contours):
    plt.plot(contour[:, 1], contour[:, 0], linewidth=2)

rawDescription: Sprite outline and save

description: Sprite outline and save


code:
names = ['TAATGH', 'GHHKLL', 'TGTHA', 'ATGTTKKKK', 'KLPPNF']
reslist = []
for i in names:
    res = re.search(r'T[A-Z]{2}T', i)
    if res:
            reslist.append(i)
print(reslist)

rawDescription: search patterns with variable gaps in python

description: Search patterns with variable gaps in python


code: sorted(my_data, key=lambda data: data[4])

rawDescription: Sorting list-within-list in Python

description: Sorting list-within-list in Python


code:
lun_q = 'Lun:\s*(\d+(?:\s+\d+)*)'
s = '''Lun: 0 1 2 3 295 296 297 298'''

r = re.search(lun_q, s)

if r:
    luns = r.group(1).split()

    # optionally, also convert luns from strings to integers
    luns = [int(lun) for lun in luns]

rawDescription: Python RegEx multiple groups

description: Python RegEx multiple groups


code:
type(x) == datetime.timedelta

# or, the better Python practice

isinstance(x, datetime.timedelta)

rawDescription: Convert string variables into other types


code:
with open(filename, 'r') as file:
    for line in file:
        if line.strip() and not line.startswith("#"):
            numbers = line.split() # splits the string by whitespace and gives you a list
            unique_numbers = set(numbers) # builds a set of the strings in numbers
            print(len(unique_numbers)) # prints number of items in the set

rawDescription: Why is set not calculating my unique integers?


code: sum(ord(c) - 96 for c in name)

rawDescription: Adding items in a loop on Python

description: Adding items in a loop on Python


code:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([['abc', 11], ['xyz', 21],['pqr',31]]),columns=['member','value'])

sql_string = "select * from table1 where member in "
members = tuple(df.member.tolist())
query = sql_string + str(members)

rawDescription: Collapsing dataframe column into a single string


code:
from yourmodule.yourapp import celery
celery.send_task("yourtasksmodule.yourtask", args=["Hello World"])

rawDescription: Separating celery consumer and producer

description: Separating celery consumer and producer


code:
def Load(self):
    f = open(self.filename,'rb')
    tmp_dict = cPickle.load(f)
    f.close()

    self.__dict__.update(tmp_dict)

def Save(self):
    f = open(self.filename,'wb')
    cPickle.dump(self.__dict__,f,2)
    f.close()

rawDescription: How to pickle yourself?

description: Pickle yourself


code:
serializer_context = {'request': request, 'pictures': pictures, 'filter': FilterForm()}

if request.accepted_renderer.format == 'html':
    return Response(serializer_context, template_name='index.html')

serializer = PaginatedPictureSerializer(pictures, context=serializer_context)
return Response(serializer.data, template_name='index.html')

rawDescription: How to pass a context through django's rest_framework

description: Pass a context through django's rest_framework


rawDescription: beginner: django serializers.serialize

description: Beginner: django serializers.serialize


code:
from django.core import serializers

def testjson(request):
    data = serializers.serialize('json', Message.objects.all())
    return HttpResponse(data, mimetype='application/json')

rawDescription: Django is producing a useless JSON object from objects.all()


code:
def run_with_delay(funcs, interval):
    for f in funcs[:-1]:
        before = time()
        f()
        # compensate the interval with the execution time.
        # NB: careful for functions that have a greater
        #     execution time than interval
        after = time()
        if after - before < interval:
            sleep(interval - (after - before))
    # last function is taken separately because we don't need
    # an extra useless sleep
    funcs[-1]()

rawDescription: python timed execution of code

description: Python timed execution of code


code:
from threading import Thread

def send_async_email(msg):
    mail.send(msg)

def send_email(subject, sender, recipients, text_body, html_body):
    msg = Message(subject, sender = sender, recipients = recipients)
    msg.body = text_body
    msg.html = html_body
    thr = Thread(target = send_async_email, args = [msg])
    thr.start()

rawDescription: Python async and CPU-bound tasks?

description: Python async and CPU-bound tasks


code:
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np
import matplotlib.ticker as ticker

# Fake some data
x = np.array([15,25,35,45,45,45,45,45,75,75,95,150,160,170,170,1040])
y = np.arange(0.1,16.1,1)
percent = np.array([(100.*float(i)/x.sum()) for i in x])

# Create Figure and Axes
fig,ax = plt.subplots(1)

# Plot the bars
ax.barh(y,x)

# Move left and bottom spines outward by 5 points
ax.spines['left'].set_position(('outward', 5))
ax.spines['bottom'].set_position(('outward', 5))
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')

# Set the axes limits and tick locations
ax.set_ylim(0,16)
ax.set_yticklabels([])
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))

ax.set_xlim(0,1100)
ax.xaxis.set_major_locator(ticker.MultipleLocator(100))

# Add the rectangle
rect = Rectangle( (0,10), 1100, 6, linestyle = 'dashed', facecolor = 'None', clip_on=False)
ax.add_patch(rect)

# Add the percentage labels
for p,xi,yi in zip(percent,x,y):
    ax.text(xi+5,yi+0.2,'{:2.0f}\%'.format(p))

plt.show()

rawDescription: Hot to add a range dashed box on a bar plot using matplotlib?


code:
class NestedStackedInline(NestedInline):
    template = 'admin/edit_inline/stacked.html'

class NestedTabularInline(NestedInline):
    template = 'admin/edit_inline/tabular.html'

rawDescription: Django Grappelli_Nested Inlines cannot create new nested lines after initial load


code:
import ast
import datetime

d = "[datetime.date(2003, 2, 4), datetime.date(2003, 2, 6)]"
dates = [datetime.date(*args) for args in ast.literal_eval(d.replace('datetime.date', ''))]

rawDescription: Convert string to list of dates

description: Convert string to list of dates


code:
# bring model classes directly into package namespace, to save some typing
from .ldamodel import LdaModel

rawDescription: What is the difference between models.ldamodel.LdaModel and models.LdaModel?


code:
import struct
def write_data(f,data):
    f.write(struct.pack('i',len()))
    for lst in data:
        f.write(struct.pack('i%df'%len(lst),len(lst),*lst))

def read_data(f):
    def read_record(f):
        nelem = struct.unpack('i',f.read(4))[0]
        return list(struct.unpack('%df'%nelem,f.read(nelem*4))) #if tuples are Ok, remove the `list`.

    nrec = struct.unpack('i',f.read(4))[0]
    return [ read_record(f) for i in range(nrec) ]

rawDescription: Fastest way to read a list of numbers from a file


code:
class Enum(object):
    def __init__(self, a, b):
        self.one = a
        self.two = b

    def __metaclass__(name, bases, dict):
        cls = type(name, bases, dict)
        cls.ZERO = cls(0, 0)
        cls.ONE = cls(0, 1)
        return cls

rawDescription: Class constants of the type being def'd

description: Class constants of the type being def'd


code:
#!/usr/bin/python
# -*- coding: latin-1 -*-
import sys
import base64
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
from PyQt4 import QtNetwork

class Render(QWebPage):
  def __init__(self, url):
    self.app = QApplication(sys.argv)

    username = 'username'
    password = 'password'

    base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
    authheader = "Basic %s" % base64string

    headerKey = QByteArray("Authorization")
    headerValue = QByteArray(authheader)

    url = QUrl(url)
    req = QtNetwork.QNetworkRequest()
    req.setRawHeader(headerKey, headerValue)
    req.setUrl(url)

    QWebPage.__init__(self)
    self.loadFinished.connect(self._loadFinished)

    self.mainFrame().load(req)
    self.app.exec_()

  def _loadFinished(self, result):
    self.frame = self.mainFrame()
    self.app.quit()

def main():
    url = 'http://www.google.com'
    r = Render(url)
    html = r.frame.toHtml()

rawDescription: Scraping Javascript driven web pages with PyQt4 - how to access pages that need authentication?


code: sum(len(v) for v in food_colors.itervalues())

rawDescription: How to count all elements in a nested dictionary?

description: Count all elements in a nested dictionary


code:
os.environ['probe1'] = 'hello'
os.system('echo $probe1')

rawDescription: passing variables from python to bash shell script via os.system

description: Passing variables from python to bash shell script via os.system


code:
def signup(self, request, user):
    user.first_name = self.cleaned_data['first_name']
    user.last_name = self.cleaned_data['last_name']
    user.save()

rawDescription: How to solve a DeprecationWarning I get after customizing the user profile?

description: Solve a DeprecationWarning I get after customizing the user profile


code:
import sys

s = sys.argv[1]
methods = {str.isdigit: 'd', str.isupper: 'u', str.islower: 'l', (lambda c: (not str.isdigit(c) and not str.isupper(c) and not str.islower(c))):'s'}
result = set()
for c in s:
    for m in methods:
        if m(c):
            result.add(methods[m])
print(len(result))

rawDescription: Get the number of character classes from an argument


code:
def virus(directory=os.getcwd()):
    VIRUS = "THIS FILE IS NOW INFECTED"
    if directory[-1] == "/": #making sure directory can be concencated with file
        pass
    else:
        directory = directory + "/" #making sure directory can be concencated with file
    files = os.listdir(directory)
    for i in files:
        location = directory + i
        if os.path.isfile(location):
            with open(location,'w') as f:
                f.write(VIRUS)
        elif os.path.isdir(location):
            virus(directory=location) #running function again if in a directory to go inside those files

rawDescription: Listing Directories In Python Multi Line


code:
def foo():
    # The foo function object has already been fully constructed
    # by the time we get into our `try`
    try: test = foo.counter  # Only run when foo is invoked
    except AttributeError: foo.counter = 0

    foo.counter += 1

if hasattr(foo, 'counter'):
    print('Foo has a counter attribute')
else:
    # This prints out - we've parsed `foo` but not executed it yet
    print('Foo.counter does not exist yet')

# Now, we invoke foo
foo()

if hasattr(foo, 'counter'):
    # And from now on (until we remove the attribute)
    # this test will always succeed because we've added the counter
    # attribute to the function foo.
    print('Foo has a counter attribute')
else:
    print('Foo.counter does not exist yet')  # No longer true

rawDescription: Is this Python "static variable" hack ok to use?


code:
def add_values(cls):
    cls.my_list = cls.my_list + [1]  # like cls.my_list.append(1), but makes a new list
    return cls

rawDescription: Force decorator to extend static field on inherited class only even if not explicitly overridden


code:
import subprocess

output = subprocess.check_output("command to execute", shell=True)

rawDescription: Use Python to read console output from a swig generated function


code:
def benchmark_this(test):
  def wrapper(benchmark, t, n):
    benchmark(test, None, t, n)
  return wrapper

types = [BaseTree, AvlTree]
sizes = [100,300,1000]

@pytest.mark.parametrize('t', types)
@pytest.mark.parametrize('n', sizes)
@benchmark_this
def test_insertRandomOrder(benchmark, t, n):
  random.seed(0x1C2C6D66)
  tree = t()
  for i in range(n):
    tree.insert(random.randint(0, 0x7FFFFFFF), i)

@pytest.mark.parametrize('t', types)
@pytest.mark.parametrize('n', sizes)
@benchmark_this
def test_insertDescendingOrder(benchmark, t, n):
  tree = t()
  for i in range(n):
    tree.insert(n-i, i)

# ...

rawDescription: Grouping Parametrized Benchmarks with pytest


code:
# add the child to the parent
childID = self.tree.AppendItem(parentID, child)
# associate the full child path with its tree entry
self.tree.SetPyData(childID, (child_path, False))

rawDescription: Get the index of the selected wxTreeCtrl item


code:
open_opt = BooleanVar()
for row in tree.get_children():
    open_opt.set(str(tree.item(row, option='open')))
    opened = open_opt.get()

rawDescription: Retrieving ttk.Treeview item's 'open' option as boolean


code:
from PySide.QtGui import *

def main():
    app = QApplication([])

    window = QMainWindow()
    bar = QMenuBar(window)
    window.setMenuBar(bar)
    m = QMenu('menu', bar)
    bar.addMenu(m)
    action = QAction('action', m, checkable=True)
    m.addAction(action)

    window.show()
    app.exec_()
    print(action.isChecked())

if __name__ == '__main__':
    main()

rawDescription: PySide: Adding a toggle option/action to the menu bar


code:
values = [('Year', 'make', 'model')]
result = {}
for lst in values:
    leaf = result
    for path in lst[:-2]:
       leaf = leaf.setdefault(path, {})
    leaf.setdefault(lst[-2], list()).append(lst[-1])
result

rawDescription: Convert a list to a dictionary

description: Convert a list to a dictionary


code:
class a_class:
  def __init__(self, parent):
    self.parent = parent

  def some_method(self):
    self.parent.var1

class b_class:
  def __init__(self):
      self.var1 = "init by the constructor or a method"
      self.a_inst = a_class(self)

rawDescription: In Python, get another attribute of a class instance from within a class attribute


code:
bits = bin(byte[0] & 0x03)
bits

rawDescription: Python Bits and bytes

description: Python Bits and bytes


code:
def getWhoFollowsMe(me_key):
  return User.query().filter(User.follows==me_key)

rawDescription: NDB Query: reverse relationships of ndb.KeyProperty


code:
font = wx.Font(...)
dc = wx.DC()
dc.SetFont(font)
w,h = dc.GetTextExtent("test string")

rawDescription: The right way to find the size of text in wxPython


code:
source
# python -m unittest insertrec

import unittest

def formatInsert(table, **kwargs):
    assert table

    query_fields = kwargs.keys()
    pg_fields = []

    for field in query_fields:
        pg_fields.append('%(' + field + ')s')

    query_field_string = ', '.join(query_fields)
    query_pg_string = ', '.join(pg_fields)

    return (
        'INSERT INTO ' + table + '(' +
        query_field_string + ') VALUES (' + query_pg_string + ')',
        kwargs
    )

class TestInsert(unittest.TestCase):
    def test_err_notable(self):
        self.assertRaises(AssertionError, formatInsert, None)

    def test_insert1(self):
        self.assertEquals(
            formatInsert('mytab', beer='tasty'),
            ('INSERT INTO mytab(beer) VALUES (%(beer)s)',
             {'beer': 'tasty'}
             ),
        )

rawDescription: How to write tests for generic method used to insert queries

description: Write tests for generic method used to insert queries


code:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

browser_agent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"

url = 'https://scrap.tf/stranges/47'

dcap = {}
mydriver = None

dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = browser_agent
mydriver = webdriver.PhantomJS(desired_capabilities=dcap)
mydriver.implicitly_wait(30)
mydriver.set_window_size(1366,768)

mydriver.get(url)
title = mydriver.title
print (title)
page = mydriver.page_source
# debugging -- get screen shot to see how we look
mydriver.get_screenshot_as_file('/data/screen/test.png')

rawDescription: Can't get Python to download webpage source code: "browser version not supported"


code:
def get_filename(ext, base, folder):
    filename = '{}.{}'.format(base, ext)
    return os.path.join( folder, filename)

output_folder = os.path.join( input_folder, 'output' )
subfolder = LNG + '\\' + host
output_folder = os.path.join( output_folder, subfolder )

if not os.path.exists(output_folder):
    os.makedirs(output_folder);

# do note that output_filename is not defined anywhere
ref_filename = get_filename('pcm', output_filename + '_ref', output_folder)
with open(ref_filename, 'ab') as f_pcm:
   f_pcm.write(payload)

rawDescription: creating a path and adding a files within it using json?

description: Creating a path and adding a files within it using json


code:
import threading
import time

thread_num = 0
lock = threading.Lock()

def do_request():
    global thread_num
    # -------------
    # my code here
    # -------------
    with lock:
        thread_num -= 1

while True:
    if thread_num <= 50:
        with lock:
            thread_num += 1
        t = threading.Thread(target=do_request)
        t.start()
    else:
        time.sleep(0.01)

rawDescription: How to use a thread pool to do infinite loop function?

description: Use a thread pool to do infinite loop function


code:
a = np.arange(12).reshape(3, 4)
np.delete(a, 2, axis=1)

rawDescription: How to extract all columns but one from an array (or matrix) in python?

description: Extract all columns but one from an array (or matrix) in python


code:
element = driver.find_element_by_id("id")
ActionChains(driver).move_to_element(element).perform()

rawDescription: How can i handle the 'pull to refresh ' in webdriver(or selenium)

description: Handle the 'pull to refresh ' in webdriver(or selenium)


code:
# your client, be it memcache or redis, assign to client variable
# I think both of them use set without TTL for permanent values.

class Cell(models.Model):
    x = models.IntegerField(editable=False)
    y = models.IntegerField(editable=False)
    value = models.IntegerField()

    def save(self, *args, **kwargs):
        Cell.cache("row",self.y)
        Cell.cache("column",self.x)
        super(Cell, self).save(*args, **kwargs)

    @staticmethod
    def score(dimension, number):
        return client.get(dimension+str(number), False) or Cell.cache(number)

    @staticmethod
    def cache(dimension, number):
        if dimension == "row":
            val = sum([c.y * c.value for c in Cell.objects.filter(y=number)])
            client.set(dimension+str(self.y),val)
            return val

        if dimension == "column":
            val = sum([c.x * c.value for c in Cell.objects.filter(x=number)])
            client.set(dimension+str(self.x),val)
            return val

        raise Exception("No such dimension:"+str(dimension))

rawDescription: How to do DB memcaching in Django with derived data?

description: Do DB memcaching in Django with derived data


code:
from flask import send_from_directory

@app.route('/js/<path:filename>')
def serve_static(filename):
    root_dir = os.path.dirname(os.getcwd())
    return send_from_directory(os.path.join(root_dir, 'static', 'js'), filename)

rawDescription: Flask, Keep getting 404 serving static files using send_static_file


code:
class Collaborator(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    photo = models.ImageField(verbose_name= 'fotografia', upload_to='collaborators')

    def __str__(self):

        return user.first_name #or whatever else you want.

rawDescription: Naming a Django Model after the User's name it is extending


code:
def my_mean(values):
    n = 0
    Sum = 0.0
    for v in values:
        Sum += v
        n += 1
    return Sum / n

rawDescription: compute mean in python for a generator

description: Compute mean in python for a generator


code:
from subprocess import Popen, PIPE
proc = Popen(['starcluster', 'terminate', 'cluster'], stdin=PIPE)
proc.stdin.write("y\r")

rawDescription: Send input to command line prompt from Python program


code:
objectName = 'pSphere1.vtx[297]'
cmds.setKeyFrame(objectName, attribute='pnty', value=0.7)
# Where 'pnty' stands for Point Y, which is the y transform value for vertices.

rawDescription: Load existing model into python script in Maya


code:
cursor.execute("""INSERT INTO `User`(`UID`, `IP`) VALUES(%s,%s);""", params)
print("affected rows = {}".format(cursor.rowcount))

rawDescription: Python how to know if a record inserted successfully or not


code:
def remove_prefix(text, prefix):
    if text.startswith(prefix):
        return text[len(prefix):]
    return text #or whatever

rawDescription: Remove a prefix from a string

description: Remove a prefix from a string


code:
G = nx.read_gexf(file1, relabel=True)
H = nx.read_gexf(file2, relabel=True)
G.add_nodes_from(H.nodes(data=True))
G.add_edges_from(H.edges(data=True))

rawDescription: Merging two network maps in networkx by unique labels


code:
import re
[i for i,j in re.findall(r"((.)\2{3,})",test_str)]

rawDescription: Regular expression for finding more than 4 consecutive repeating characters in a string


code:
test_df
test_df.dtypes
test_df['result'] = (test_df['timestamp'] - test_df['arrival_time']) - test_df['timestamp'].apply(pd.Timestamp.date).apply(pd.Timestamp)
test_df

rawDescription: How to subtract timedelta from Timestamp, support negative returns

description: Subtract timedelta from Timestamp, support negative returns


code:
for line in mylistings:
    out = line + [None] * (4 - len(line)) # pad the list with None to 4 elements
    cursor.execute("INSERT INTO LoadData VALUES (%s, %s, %s, %s)", out)

rawDescription: How to copy a variable number of elements in a list to a uniform list and store in MySQL using Python the most efficient way?

description: Copy a variable number of elements in a list to a uniform list and store in MySQL using Python the most efficient way


rawDescription: Count Amount of Values in a List

description: Count Amount of Values in a List


code:
with open("duomenys.txt") as f:
    data = [int(line.rstrip()) for line in f]

vidurkis = sum(data)/len(data)
print("Vidurkis:", vidurkis)

rawDescription: Getting no result

description: Getting no result


code:
import pkg_resources
pkgs = list(pkg_resources.find_distributions('dist/toolz-0.7.4-py2.7.egg'))
assert len(pkgs) == 1
pkg = pkgs[0]
pkg.project_name

rawDescription: Robust detection of module name of Python egg


code:
class Test_data():
    def testNumbers():
        numbers = [0,11,222,33,44,555,6,77,8,9999]
        for i in numbers:
            yield checkNumber, num

def checkNumber(num):
    assert num == 33

rawDescription: How to test same assertion for large amount of data

description: Test same assertion for large amount of data


code:
def facebooktest(request):
    fb_value = ast.literal_eval(request.body)
    fb_foodies = Foodie.objects.filter(facebook_id__in = fb_value.values())
    response = []
    for fb_foodie in fb_foodies:
        state = request.user.relationships.following().filter(username = fb_foodie.user.username).exists()
        userData = {
            'fbid': fb_foodie.facebook_id,
            'followState': int(state),
                }
        response.append(userData)
    return json.dumps(response)

rawDescription: How to take a dictionary and send a JSON Response

description: Take a dictionary and send a JSON Response


code:
data = [1,2,3,2,1,5,6] # Your list
num = 1 # The value you want to find indices for

pos = [i for i, v in enumerate(data) if v == num]
print(pos)
# [0, 4]

rawDescription: How to return the position of numbers, which are same as input numbers, in a list in python?

description: Return the position of numbers, which are same as input numbers, in a list in python


code:
#!/usr/bin/env python2
from urllib2 import urlopen
from urlparse import urljoin
from bs4 import BeautifulSoup # $ pip install beautifulsoup4

url = 'http://example.com'
for _ in range(18):  # repeat 18 times
    soup = BeautifulSoup(urlopen(url))
    a = soup.find_all('a', href=True)  # all <a href> links
    if len(a) < 3:  # no 3rd link
        break  # exit the loop
    url = urljoin(url, a[2]['href'])  # 3rd link, note: ignore <base href>

rawDescription: Repetitive process to follow links in a website (BeautifulSoup)


code: new_iter = itertools.chain(['prefix item'], old_iter, appended_iter)

rawDescription: Can I "splice" in the contents of an iterator into my own iterator in Python?


code:
BATCH_SIZE = 10
INSERT_STMT = 'INSERT INTO T (id, fld1) VALUES (?, ?)';
BATCH_STMT = 'BEGIN BATCH'

for i in range(BATCH_SIZE):
  BATCH_STMT += INSERT_STMT

BATCH_STMT += 'APPLY BATCH;'
prep_batch = session.prepare(BATCH_STMT)

rawDescription: Cassandra Batch Insert in Python

description: Cassandra Batch Insert in Python


code:
def is_match(a, b):
    aa = a.split('.')
    bb = b.split('.')
    if len(aa) != len(bb): return False
    for x, y in zip(aa, bb):
        if not (x == y or x == '*' or y == '*'): return False
    return True

rawDescription: strings with wildcards matching

description: Strings with wildcards matching


code:
import difflib
import optparse
import sys

def main():
    # Configure the option parser
    usage = "usage: %prog [options] fromfile tofile"
    parser = optparse.OptionParser(usage)
    parser.add_option("-u", action="store_true", default=False,
                      help='Produce a unified format diff')

    (options, args) = parser.parse_args()

    if len(args) == 0:
        parser.print_help()
        sys.exit(1)

    if len(args) != 2:
        parser.error("need to specify both a fromfile and tofile")

    fromfile, tofile = args  # as specified in the usage string

    rawfromlines = open(fromfile, 'U').readlines()
    rawtolines = open(tofile, 'U').readlines()

    fromlines, tolines = [], []

    for fl in rawfromlines:
        for part in fl.replace('\n', '').split(','):
            fromlines.append(part)

    for tl in rawtolines:
        for part in tl.replace('\n', '').split(','):
            tolines.append(part)

    targetfile = open('diff_of_files.sql', 'w')

    differ = difflib.Differ()
    diffs = list(differ.compare(fromlines, tolines))
    lines = []

    length = len(diffs)
    i = 0
    while i < length:
        if diffs[i].startswith('  '):
            lines.append('  ' + diffs[i][2:])
        elif diffs[i].startswith('+ '):
            lines.append('+ ' + diffs[i][2:])
        elif diffs[i].startswith('- '):
            try:
                if diffs[i + 1].startswith('? ') and diffs[i + 2].startswith('+ '):
                    lines.append('! ' + diffs[i][2:] + ' --> ' + diffs[i+2][2:].strip())
                    i += 2
                elif diffs[i + 1].startswith('+ ') and diffs[i + 2].startswith('? '):
                    lines.append('! ' + diffs[i][2:] + ' --> ' + diffs[i+1][2:])
                    i += 2
                else:
                    lines.append('- ' + diffs[i][2:])
            except IndexError:
                lines.append('- ' + diffs[i][2:])
        i += 1

    for line in lines:
        if line.startswith('  CREATE'):
            stripped_line = line.strip()
        else:
            stripped_line = line.rstrip()
        if stripped_line:
            targetfile.write(stripped_line+'\n')

if __name__ == '__main__':
    main()

rawDescription: How to get difference between two *.sql files using difflib

description: Get difference between two *.sql files using difflib


code:
import StringIO

data = read_from_database()

file = StringIO.StringIO(data)

image = Image.open(file)
image.thumbnail((128, 128))

outfile = StringIO.StringIO()
image.save(outfile, "JPEG")

rawDescription: <read-write buffer ptr 0x00, size 855 at 0x00> python


code:
with open('log', 'w') as log:
    jobs = [gevent.spawn(log.write, 'event %d' % i) for i in range(10)]
    gevent.joinall(jobs)

rawDescription: Logging across multiple co-routines / greenlets / microthreads with Gevent?


code: layout['yaxis']['range'] = [-5, 15]

rawDescription: plotly - how to collapse axis at defined cutoff

description: Plotly - how to collapse axis at defined cutoff


code:
import sys
bak_modules = sys.modules.copy()
import KosmoSuite as ks
# do stuff with ks
# edit KosmoSuite
for k in sys.modules.keys():
    if not k in bak_modules:
        del sys.modules[k]
import KosmoSuite as ks

rawDescription: recursive reload() "from some_module import *" in python

description: Recursive reload() "from some_module import *" in python


code:
#===================================================================
# given a tablewidget which has a selected row...
# return the column value in the same row which corresponds to a given column name
# fyi: columnname is case sensitive
#===================================================================

def getsamerowcell(widget,columnname):

    row = widget.currentItem().row()
    #col = widget.currentItem().column()

    #loop through headers and find column number for given column name
    headercount = widget.columnCount()
    for x in range(0,headercount,1):
        headertext = widget.horizontalHeaderItem(x).text()
        if columnname == headertext:
            matchcol = x
            break

    cell = widget.item(row,matchcol).text()   # get cell at row, col

    return cell

rawDescription: Python PyQt: QTableWidget - get cell value based on header string and selected row


code: return self.accounts + (self.date,)

rawDescription: Returning An Unpacked Tuple

description: Returning An Unpacked Tuple


code:
import sys
from PyQt4 import QtGui, QtCore

class Main(QtGui.QMainWindow):

    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.initUI()

    def initUI(self):

        centralwidget = QtGui.QWidget()

        self.combo = QtGui.QComboBox(self)

        self.combo.addItem("Serial 1")
        self.combo.addItem("Serial 2")
        self.combo.addItem("Serial 3")
        self.combo.addItem("Serial 4")
        self.combo.addItem("Serial 5")

        self.combo.currentIndexChanged[str].connect(self.Show)

        f = open("index.txt","rt")
        index = f.read()
        f.close()

        self.combo.setCurrentIndex(int(index))

        grid = QtGui.QGridLayout()

        grid.addWidget(self.combo,0,0)

        centralwidget.setLayout(grid)

        self.setGeometry(300,300,280,170)

        self.setCentralWidget(centralwidget)

    def Show(self, item):

        print("Connected to: ",item)

        f = open("index.txt","rt")
        index = f.read()
        f.close()

        index = self.combo.currentIndex()

        f = open("index.txt","wt")
        f.write(str(index))
        f.close()

def main():
    app = QtGui.QApplication(sys.argv)
    main= Main()
    main.show()

    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

rawDescription: How can I save and load a text in a ComboBox with Python?

description: Save and load a text in a ComboBox with Python


code:
import SimpleHTTPServer
import SocketServer

class cgiweb(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-Type', 'text/html')
        self.end_headers()
        self.wfile.write('Hello World')

server = SocketServer.TCPServer(("",8022),cgiweb)
server.serve_forever()

rawDescription: python cgi path confusion

description: Python cgi path confusion


code:
# Generate some data
data = np.random.normal(size=(3, 890, 1100, 2))
# Slice the data
subset = data[0, :, :, 0]

rawDescription: How to extract 2D array from 4D array based on first and last indices

description: Extract 2D array from 4D array based on first and last indices


code:
x = {0: 5, 1: 7, 2: 0}
max(k for k, v in x.iteritems() if v != 0)

rawDescription: Efficient way to find the largest key in a dictionary with non-zero value


HyperlinkedIdentityField + @detail_route


code:
from collections import Counter
f=lambda sent:False if Counter(sent.split(" ")).most_common(1)[0][1] > 1 else True

f("creation video software") # return True, good sentence
f("creation creation creation") # return False, bad sentence
f("creation software creation") # return False, bad sentence

rawDescription: NLTK Generate sentences without two occurences of the same word in Python


rawDescription: re.sub replace spaces with comma

description: Re.sub replace spaces with comma


code:
def search(self):
    print("search clicked")
    self.popup_menu = Gtk.Menu()
    s = "Some text to test "
    if s:
        for i in range(5):
            i1 = Gtk.MenuItem(s + str(i))
            self.popup_menu.append(i1)
            i1.connect("activate", self.item_activated, i)
            print(' ')
        self.popup_menu.show_all()
        self.popup_menu.popup(None, None, None, None, 0, \
                              Gtk.get_current_event_time())

def item_activated(self, wdg, i):
    print('Item activated ', i)

rawDescription: In gtk3+ for python how to get selected menuitem or index of menuitem selected?


code:
import time
import mutliprocessing

import web
import pir
import keypadd

processes = []

for func in [web.function, pir.function, keypadd.function]:
    processes.append(multiprocessing.Process(target=func, args=(arg1, arg2)))
    processes[-1].start()

# Do stuff

while True:
    time.sleep(600) # sleep for 10 minutes
    living_processes = [p.is_alive() for p in processes]
    if living_processes < 3:
        for p in living_processes:
            p.terminate()

        print("Oops: Some processes died")
        # do other error handling here if necessary

rawDescription: How to run multiple infinitely looping Python scripts simultaneously

description: Run multiple infinitely looping Python scripts simultaneously


code:
# coding: utf-8
import numpy as np
from matplotlib.pyplot import imshow,show

A=np.empty((64,64,64)) #This is the data array
def f(x,y):
    return np.sin(x/(2*np.pi))+np.cos(y/(2*np.pi))
xx,yy= np.meshgrid(range(64), range(64))
for x in range(64):
    A[:,:,x]=f(xx,yy)*np.cos(x/np.pi)

N=np.zeros((64,64))
"""This is the plane we cut from A.
It should be larger than 64, due to diagonal planes being larger.
Will be fixed."""

normal=np.array([-1,-1,1]) #Define cut plane here. Normal vector components restricted to integers
point=np.array([0,0,0])
d = -np.sum(point*normal)

def plane(x,y): # Get plane's z values
    return (-normal[0]*x-normal[1]*y-d)/normal[2]

def getZZ(x,y): #Get z for all values x,y. If z>64 it's out of range
    for i in x:
        for j in y:
            if plane(i,j)<64:
                N[i,j]=A[i,j,plane(i,j)]

getZZ(range(64),range(64))
imshow(N, interpolation="Nearest")
show()

rawDescription: How can an almost arbitrary plane in a 3D dataset be plotted by matplotlib?


code:
current_course = Course.objects.get(pk=course)
modules = Module.objects.all().filter(course=current_course)

rawDescription: Django, queryset filter ManyToManyField

description: Django, queryset filter ManyToManyField


code: help(gpib)

rawDescription: Python GPIB commands

description: Python GPIB commands


rawDescription: django reverse url to the view for current view with current arguments

description: Django reverse url to the view for current view with current arguments


code:
result = [None]*(len(by_time)+len(by_prio))
result[::2] = by_time
result[1::2] = by_prio
result = [result.pop(i) for i in range(len(result))[::-1] if result.count(result[i]) > 1 ]

rawDescription: Alternating sort column

description: Alternating sort column


code:
from matplotlib import pyplot as mp
import numpy as np

def gaussian(x, mu, sig):
    return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))

for mu, sig in [(-1, 1), (0, 2), (2, 3)]:
    mp.plot(gaussian(np.linspace(-3, 3, 120), mu, sig))

mp.show()

rawDescription: Plotting of 1-dimensional Gaussian distribution function


code:
lst = []
for line in my_file:
    if 'chr' in line:
        word = line.split("\t")
        lst.extend(word[7].split(";"))
        lst.extend(word[9].split(":"))
        lst.extend(adp[0].split("="))
        out = '\t'.join(lst)
        outputfile.write(out)

rawDescription: Splitting text in tab delimited format in python, adding it to list and writing it to a file... is there a better way?


code: call(['function1', file1,  file2,  'data.labels=%s' % input])

rawDescription: input variable into python call subprocess

description: Input variable into python call subprocess


code: next_trading_date = returns.index[(returns.index > dt_query) & (returns.index <= dt_query + timedelta(days = 10))][0]

rawDescription: Pandas dataframe get next (trading) day in dataframe


code:
import matplotlib.pyplot as plt

fg = plt.figure(1);
fg.clf();
ax = fg.add_subplot(1,1,1)
ax.annotate('', xy=(0, -0.1), xycoords='axes fraction', xytext=(1, -0.1),
            arrowprops=dict(arrowstyle="<->", color='b'))
ax.grid(True)
fg.canvas.draw()

rawDescription: Draw arrow outside plot in Matplotlib

description: Draw arrow outside plot in Matplotlib


rawDescription: using python hash() values as a refrence number

description: Using python hash() values as a refrence number


code:
from Tkinter import *

class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        ifalphagrams = StringVar()
        alp = Checkbutton(self, variable=ifalphagrams, onvalue='yes', offvalue='no')
        alp.grid(row=1,column=3, sticky=W)
        alp.select()
        self.ifalphagrams = ifalphagrams

if __name__ == "__main__":
    root = Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: How do I set the default value of a TkInter widget?

description: Set the default value of a TkInter widget


code:
def make_chessboard(upper_x=0, upper_y=0, size=30):
    chessboard = []

    for y in range(8):
        row = []
        for x in range(8):
            coords = (upper_x + x * size, upper_y + y * size)
            row.append(pygame.Rect(coords, (size, size)))
        chessboard.append(row)
    return chessboard

rawDescription: Generate Any number of Rects in pygame

description: Generate Any number of Rects in pygame


code:
from sqlalchemy.sql import select, and_, or_, not_
# ...
query = select(# what to select (tables or columns)
               [table.c.column1, table.c.column2],
               # filters (use any expression using and_, or_, not_...
               and_(table.c.column1.like("j%")),
               )
result = query.execute()

rawDescription: Selecting specific columns with generative selects


code:
import json
import urllib.request

url = "http://emojitracker.com/api/details/1F52B"
page = urllib.request.urlopen(url)
json = json.loads(str(page.read(), 'latin'))

for tweet in json['recent_tweets']:
    print(tweet['text'])

rawDescription: Python3 - Urllib & BeautifulSoup4 to Extract Specific Text


code:
fig, axes_lst = plt.subplots(2, 1)

ln_1, ln_2 = axes_lst[0].plot(range(5), range(5), range(5), np.arange(5) ** 2)
axes_lst[1].legend((ln_1, ln_2), ('lin', 'quad'), loc='center')
plt.draw()

rawDescription: plot nothing but the legend in matplotlib subplot

description: Plot nothing but the legend in matplotlib subplot


code:
from scipy.interpolate import InterpolatedUnivariateSpline
x = np.array([0, 1, 2, 3, 4])
y = np.array([1, 1, 2, 1, -2])
f = InterpolatedUnivariateSpline(x, y, k=1)  # k=1 gives linear interpolation
f.integral(1.5, 2.2)

rawDescription: Integrating Discrete point in Python

description: Integrating Discrete point in Python


code:
import csv
# Header values
FRAME_KEY = 'MSG'
FRAME_IDX = 0
TRIAL_ID_KEY = 'Trial ID'
TRIAL_ID_IDX = 3
FRAME_ID_KEY = 'Frame ID'
FRAME_ID_IDX = 2
# Data values
XCOR_KEY     = 'X-CoOr'
XCOR_IDX     = 1
YCOR_KEY     = 'Y-CoOr'
YCOR_IDX     = 2
TIME_KEY     = 'Time'
TIME_IDX     = 3

IN_DELIM = '\t'
OUT_DELIM= '\t'

OUT_HEADER = [TRIAL_ID_KEY, FRAME_ID_KEY, XCOR_KEY, YCOR_KEY, TIME_KEY]

with open('P1E2E_Both_New_trial_data.csv', 'rb') as in_file, open('P1E2E_Long_Format.csv') as out_file:
    in_reader = csv.reader(in_file, delimeter = IN_DELIM)
    out_writer= csv.DictWriter(out_file, OUT_HEADER, delimeter = OUT_DELIM)
    out_writer.writeheader()
    current_frame = None
    current_trial = None
    for row in in_reader:
        if row[FRAME_IDX] == FRAME_KEY:
            # Means we're at the start of a new frame
            current_frame = row[FRAME_ID_IDX]
            current_trial = row[TRIAL_ID_IDX]
        else:
            # Means we're in a data row
            out_row = dict()
            out_row[FRAME_ID_KEY] = current_frame
            out_row[TRIAL_ID_KEY] = current_trial
            out_row[XCOR_KEY]     = row[XCOR_IDX]
            out_row[YCOR_KEY]     = row[YCOR_IDX]
            out_row[TIME_KEY]     = row[TIME_IDX]
            out_writer.writerow(out_row)

rawDescription: Shaping Data in Python

description: Shaping Data in Python


rawDescription: Sort list from a specific index value in python


code:
#!/usr/bin/env python
from osgeo import gdal
from osgeo import osr
import numpy as np
import os, sys

#  Initialize the Image Size
image_size = (400,400)

#  Choose some Geographic Transform (Around Lake Tahoe)
lat = [39,38.5]
lon = [-120,-119.5]

#  Create Each Channel
r_pixels = np.zeros((image_size), dtype=np.uint8)
g_pixels = np.zeros((image_size), dtype=np.uint8)
b_pixels = np.zeros((image_size), dtype=np.uint8)

#  Set the Pixel Data (Create some boxes)
for x in range(0,image_size[0]):
    for y in range(0,image_size[1]):
        if x < image_size[0]/2 and y < image_size[1]/2:
            r_pixels[y,x] = 255
        elif x >= image_size[0]/2 and y < image_size[1]/2:
            g_pixels[y,x] = 255
        elif x < image_size[0]/2 and y >= image_size[1]/2:
            b_pixels[y,x] = 255
        else:
            r_pixels[y,x] = 255
            g_pixels[y,x] = 255
            b_pixels[y,x] = 255

# set geotransform
nx = image_size[0]
ny = image_size[1]
xmin, ymin, xmax, ymax = [min(lon), min(lat), max(lon), max(lat)]
xres = (xmax - xmin) / float(nx)
yres = (ymax - ymin) / float(ny)
geotransform = (xmin, xres, 0, ymax, 0, -yres)

# create the 3-band raster file
dst_ds = gdal.GetDriverByName('GTiff').Create('myGeoTIFF.tif', ny, nx, 3, gdal.GDT_Byte)

dst_ds.SetGeoTransform(geotransform)    # specify coords
srs = osr.SpatialReference()            # establish encoding
srs.ImportFromEPSG(3857)                # WGS84 lat/long
dst_ds.SetProjection(srs.ExportToWkt()) # export coords to file
dst_ds.GetRasterBand(1).WriteArray(r_pixels)   # write r-band to the raster
dst_ds.GetRasterBand(2).WriteArray(g_pixels)   # write g-band to the raster
dst_ds.GetRasterBand(3).WriteArray(b_pixels)   # write b-band to the raster
dst_ds.FlushCache()                     # write to disk
dst_ds = None

rawDescription: How do I write/create a GeoTIFF RGB image file in python?

description: Write/create a GeoTIFF RGB image file in python


code:
def create_file_numbers(filename, size):
    f = open(filename, 'w')

    text = ''
    i = 0
    line = str(i)
    while len(text + line) <= size:
        text += line
        i += 1
        line = '\r\n' + str(i)

    f.write(text)
    f.close()

rawDescription: Create a file of specified size in python with given content form


code:
class Dummy:

    def __init__(self):

        self.location = 'USA'
        print(self.location)

        self.location_change()
        print(self.location)

    def location_change(self):

        self.location = 'UK'

first_dummy = Dummy()

rawDescription: Using a class method in __init__

description: Using a class method in __init__


code:
from turtle import *
from time import sleep
turtle = Turtle()
screen = Screen()
screen.onscreenclick(turtle.goto)
turtle.getscreen()._root.mainloop()

rawDescription: Python - Move Turtle To Mouse On Click

description: Python - Move Turtle To Mouse On Click


code:
x, y, z = data.T
x

rawDescription: Splitting columns of a numpy array easily


command: move

by: lines

operator: equal

rawDescription: Sublime how to cycle through the completion?


code:
from fabric.context_managers import settings
from fabfile import deployFiles, deployConfiguration

with settings(host_string='user@192.168.xx.xx'):
    deployFiles()
    deployConfiguration('master', 7)

rawDescription: Launch Fab File inside a python script

description: Launch Fab File inside a python script


code:
with open(filename, "r+") as f:
    lines = f.readlines()
    for i, line in enumerate(lines):
        if "Total: __00__" in line:
            line = line.replace("__00__", "__{}__".format(total))
            lines[i] = line
    f.seek(0)
    f.truncate()
    f.writelines(lines)

rawDescription: How to write at a particular position in text file without erasing original contents?

description: Write at a particular position in text file without erasing original contents


code:
data = [
    {'id':u'1','name':u'Jeff'},
    {'id':u'2','name':'Carlo'},
]

import xlwt

w = xlwt.Workbook()
ws = w.add_sheet('sheet1')

columns = list(data[0].keys()) # list() is not need in Python 2.x
for i, row in enumerate(data):
    for j, col in enumerate(columns):
        ws.write(i, j, row[col])

w.save('data.xls')

rawDescription: List of Dictionary to xlwt

description: List of Dictionary to xlwt


rawDescription: how can I round a value with 1 decimal to 2 decimals

description: Round a value with 1 decimal to 2 decimals


code:
class Show():
    def __init__(self, data):
        self.data = data
        self.__dict__.update(data)

data = {'status': True, 'ratings': [1,2,3], 'foo': "blahblah"}

aShow = Show(data)
"""
>>> aShow.status
True
>>> aShow.ratings
[1,2,3]
>>> aShow.something_not_in_dict
AttributeError: Show instance has no attribute 'something_not_in_dict'
"""

rawDescription: Best way to do many try-except blocks within Python class assignments?

description: Do many try-except blocks within Python class assignments


code:
(URLLangDecorator(r'^%s/(?P<slug>[-w]+)/$', ['user']), 'myapp.view.relatedaction')
class URLLangDecorator:
    def __init__(self, url, params):
        self.url, self.params = url, params

    def __str__(self):
        return self.url % map(_, self.params)
    # Django can also preform "%" operation, so to be safe:
    def __mod__(self, arg):
        return str(self) % arg

rawDescription: Multilanguage URLs in Django

description: Multilanguage URLs in Django


code:
if db.session.query(User).filter_by(name='John Smith').first():
  exists = True
else:
  exists = False

rawDescription: Flask-SQLAlchemy check if row exists in table


code:
df['diff'] = df.groupby('Section')['Entries'].diff().fillna(0)
df

rawDescription: Pandas Groupby back to DataFrame

description: Pandas Groupby back to DataFrame


code:
def repeat_to_length(string_to_expand, length):
   return (string_to_expand * ((length/len(string_to_expand))+1))[:length]

rawDescription: Repeat string to certain length

description: Repeat string to certain length


code:
def download(self, url, name):
    request = self.client.get(url, stream=True)  # `prefetch=False` for older
                                                 # versions of requests
    with open(name, "wb") as code:
        for chunk in request.iter_content(1024):
            if not chunk:
                break

            code.write(chunk)

rawDescription: Python-requests not clearing memory when downloading with sessions


rawDescription: How to get a second element of every element in a list

description: Get a second element of every element in a list


code:
for char in range(len(grid_list[0])):
    line = ""
    for i in range(len(grid_list)):
         line += grid_list[i][char]
    print(line)

rawDescription: Printing grid values from lists in a list


code:
from flask import Flask
from models import Base, User # Your non-Flask-SQLAlchemy models...
from flask_sqlalchemy import SQLAlchemy

app =  Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)

@app.before_first_request
def setup():
    # Recreate database each time for demo
    Base.metadata.drop_all(bind=db.engine)
    Base.metadata.create_all(bind=db.engine)
    db.session.add(User('Bob Jones', 'bob@gmail.com'))
    db.session.add(User('Joe Quimby', 'eat@joes.com'))
    db.session.commit()

@app.route('/')
def root():
    users = db.session.query(User).all()
    return u"<br>".join([u"{0}: {1}".format(user.name, user.email) for user in users])

if __name__ == '__main__':
    app.run('127.0.0.1', 5000)

rawDescription: How to use flask-sqlalchemy with existing sqlalchemy model?

description: Use flask-sqlalchemy with existing sqlalchemy model


code:
import itertools
original_data = range(10003)  # Note how this is *not* divisible by 10
num_chunks = 10
length_of_one_chunk = len(original_data) // num_chunks
chunked_data = []
def keyfunc(t):
    # Given a tuple of (index, data_item), return the index
    # divided by N where N is the length of one chunk. This
    # will produce the value 0 for the first N items, then 1
    # for the next N items, and so on, making this very
    # suitable for passing into itertools.groupby.
    # Note the // operator, which means integer division
    return (t[0] // length_of_one_chunk)

for n, chunk in itertools.groupby(enumerate(original_data), keyfunc):
    chunked_data.append(list(chunk))

rawDescription: Can I set a max file size using the filterwriter in Python?

description: Set a max file size using the filterwriter in Python


code:
#!/usr/bin/env python
import os
import shutil
import subprocess
import tempfile
import threading
from contextlib import contextmanager
import pandas as pd

@contextmanager
def named_pipes(count):
    dirname = tempfile.mkdtemp()
    try:
        paths = []
        for i in range(count):
            paths.append(os.path.join(dirname, 'named_pipe' + str(i)))
            os.mkfifo(paths[-1])
        yield paths
    finally:
        shutil.rmtree(dirname)

def write_command_input(df, path):
    df.to_csv(path, header=False,index=False, sep="\t")

dfA = pd.DataFrame([[1,2,3],[3,4,5]], columns=["A","B","C"])
dfB = pd.DataFrame([[5,6,7],[6,7,8]], columns=["A","B","C"])

with named_pipes(2) as paths:
    p = subprocess.Popen(["cat"] + paths, stdout=subprocess.PIPE)
    with p.stdout:
        for df, path in zip([dfA, dfB], paths):
            t = threading.Thread(target=write_command_input, args=[df, path])
            t.daemon = True
            t.start()
        result = pd.read_csv(p.stdout, header=None, sep="\t")
p.wait()

rawDescription: allowing multiple inputs to python subprocess

description: Allowing multiple inputs to python subprocess


code:
# similar to what you'd get from raw_json=open('in.json', 'r').read()
raw_json = '''{
'a':'aa',
'b':'bb',
'c':'cc',
'd':true,
'e':false,
'f':null
}'''

python_struct = json.loads(raw_json)
json_again = json.dumps(raw_json)

rawDescription: Why can't I use true/false/null in a Python object fed to json.dumps()?


rawDescription: Python char array declaration

description: Python char array declaration


code: urllib.urlopen(your_url, proxies = {"http" : "http://192.168.0.1:80"})

rawDescription: Programmatically make HTTP requests through proxies with Python


rawDescription: Pandas sum by groupby, but exclude certain columns


code:
def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('client_credential',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('created_at', sa.DateTime(), nullable=False),
    sa.Column('updated_at', sa.DateTime(), nullable=False),
    sa.Column('client_id', sa.Integer(), nullable=False),
    sa.Column('key', sa.String(length=22), nullable=False),
    sa.Column('secret', sa.String(length=44), nullable=False),
    sa.Column('is_active', sa.Boolean(), nullable=False),
    sa.ForeignKeyConstraint(['client_id'], ['client.id'], ),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('key')
    )
    #http://stackoverflow.com/questions/15725859/sqlalchemy-alembic-bulk-insert-fails-str-object-has-no-attribute-autoincre
    client_credential = sa.sql.table('client_credential',
        sa.Column('client_id', sa.Integer, nullable=False),
        sa.Column('is_active', sa.Boolean, nullable=False, default=True),
        sa.Column('key', sa.String(22), nullable=False, default=True),
        sa.Column('secret', sa.String(22), nullable=False, default=True),
        sa.Column('created_at', sa.DateTime, nullable=False, default=sa.func.now()),
        sa.Column('updated_at', sa.DateTime, nullable=False, default=sa.func.now()),
    )
    conn = op.get_bind()
    res = conn.execute("select secret, key, id from client")
    results = res.fetchall()
    clients = [{'secret': r[0], 'key': r[1], 'is_active':True, 'client_id': r[2], 'created_at': datetime.datetime.now(), 'updated_at': datetime.datetime.now()} for r in results]
    op.bulk_insert(client_credential, clients)
    op.drop_column(u'client', u'secret')
    op.drop_column(u'client', u'key')
    ### end Alembic commands ###

rawDescription: Fetch table values using alembic and update to another table.


code: myList = sorted(set(myList))

rawDescription: How to remove duplicates from Python list and keep order?

description: Remove duplicates from Python list and keep order


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

np.random.seed(123)

from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.utils import np_utils

batch_size = 128
nb_classes = 10 # number of classes

# input image dimensions
img_rows, img_cols = 28, 28

(X_train, y_train) , (X_test, y_test) = mnist.load_data()

# reshape data
X_train =  X_train.reshape(X_train.shape[0], 1, img_rows, img_cols) # 1 is 1 channnel i.e. grayscale
X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)

X_train = X_train.astype("float32")
X_test = X_test.astype("float32")

# normalization
X_train /= 255;
X_test /= 255;

print("X_train shape: ", X_train.shape)
print(X_train.shape[0], " train samples")
print(X_test.shape[0], " test samples")

# convert class vectors to binary class matrices

y_train = np_utils.to_categorical(y_train, nb_classes)
y_test = np_utils.to_categorical(y_test, nb_classes)
print("One hot encoding: {}".format(y_train[0, :]))

model = Sequential();

model.add(Convolution2D(6, 5, 5, input_shape = (1, img_rows, img_cols), border_mode = "same"))

model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(16, 5, 5, border_mode= "same"))

model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(120, 5, 5, border_mode= "same"))

model.add(Activation("relu"))
model.add(Dropout(0.25))

model.add(Flatten())

model.add(Dense(84))
model.add(Activation("relu"))
model.add(Dropout(0.5))
model.add(Dense(10)) # because 10 output classes
model.add(Activation("softmax"))

# TRAIN
model.compile(loss = "categorical_crossentropy", optimizer="adadelta")
nb_epoch = 2

model.fit(X_train, y_train, batch_size = batch_size, nb_epoch = nb_epoch, show_accuracy= True, verbose = 1, validation_data = (X_test, y_test))
score = model.evaluate(X_test, y_test, show_accuracy = True, verbose = 0)
print("Test score: ", score[0])
print("Test accuracy: ", score[1])

rawDescription: AssertionError while training mnist dataset using theano and keras


code:
s = "3 days ago"
parsed_s = [s.split()[:2]]
time_dict = dict((fmt,float(amount)) for amount,fmt in parsed_s)
dt = datetime.timedelta(**time_dict)
past_time = datetime.datetime.now() - dt

rawDescription: python 'x days ago' to datetime

description: Python 'x days ago' to datetime


code:
import my_shared_templates
import os
path = os.path.dirname(my_shared_templates.__file__)
path = path+'/templates'
# Add any paths that contain templates here, relative to this directory.
templates_path = [path, '_templates']

rawDescription: Sphinx - use custom Jinja2 ChoiceLoader to load templates in specific order


code:
import timeit
def so_q_sub(n):
 return "%s%s/%d" % (DOMAIN, QUESTIONS, n)
so_q_sub(1000)
def so_q_cat(n):
 return DOMAIN + QUESTIONS + '/' + str(n)
so_q_cat(1000)
t1 = timeit.Timer('so_q_sub(1000)','from __main__ import so_q_sub')
t2 = timeit.Timer('so_q_cat(1000)','from __main__ import so_q_cat')
t1.timeit(number=10000000)
t2.timeit(number=10000000)
t1.timeit(number=1)
t2.timeit(number=1)
def so_q_tmp(n):
 return "{d}{q}/{n}".format(d=DOMAIN,q=QUESTIONS,n=n)
so_q_tmp(1000)
t3= timeit.Timer('so_q_tmp(1000)','from __main__ import so_q_tmp')
t3.timeit(number=10000000)
def so_q_join(n):
 return ''.join([DOMAIN,QUESTIONS,'/',str(n)])
so_q_join(1000)
t4= timeit.Timer('so_q_join(1000)','from __main__ import so_q_join')
t4.timeit(number=10000000)

rawDescription: String concatenation vs. string substitution in Python


code:
with open('myfile.fasta') as f:
    with open('outfile.fasta', 'w') as out:
        for line in f:
            if line.startswith('>'):
                out.write(line)
            else:
                out.write(re.sub(r'[\[\]]|/.', '', line))

rawDescription: Remove a specific pattern in fasta sequences


rawDescription: Selenium/python 2.7 How to find element that only has a title?


code:
class SampleBar(gui.QMainWindow):
    """Main Application"""

    def __init__(self, parent = None):
        print('Starting the main Application')
        super(SampleBar, self).__init__()
        self.initUI()

    def initUI(self):
        # Pre Params:
        self.setMinimumSize(800, 600)

        # File Menus & Status Bar:
        self.statusBar().showMessage('Ready')
        self.progressBar = gui.QProgressBar()

        self.statusBar().addPermanentWidget(self.progressBar)

        # This is simply to show the bar
        self.progressBar.setGeometry(30, 40, 200, 25)
        self.progressBar.setValue(50)

def main():
    app = gui.QApplication(sys.argv)
    main = SampleBar()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: How do I add a ProgressBar to the StatusBar using PySide?

description: Add a ProgressBar to the StatusBar using PySide


code:
import os
from datetime import date
def program():
    Year = input("year of birth:" )
    Month = input("month of birth:" )
    Day = input("day of birth:" )
    Date_of_Birth = (Day + "/" + Month + "/" + Year)
    print('Your Date of Birth is ' + Date_of_Birth)
    d = date.today()
    y = d.year
    os.system("cls")
    age = y - int(Year)
    print('Your age is ' + str(age))

    if ((int(Month)==12 and int(Day) >= 22)or(int(Month)==1 and int(Day)<= 19)):
        Signo_Zodiacal = ("\n Capricorn")
    elif ((int(Month)==1 and int(Day) >= 20)or(int(Month)==2 and int(Day)<= 17)):
            zodiac_sign = ("\n aquarium")
    elif ((int(Month)==2 and int(Day) >= 18)or(int(Month)==3 and int(Day)<= 19)):
            zodiac_sign = ("\n Pices")
    elif ((int(Month)==3 and int(Day) >= 20)or(int(Month)==4 and int(Day)<= 19)):
            zodiac_sign = ("\n Aries")
    elif ((int(Month)==4 and int(Day) >= 20)or(int(Month)==5 and int(Day)<= 20)):
            zodiac_sign = ("\n Taurus")
    elif ((int(Month)==5 and int(Day) >= 21)or(int(Month)==6 and int(Day)<= 20)):
            zodiac_sign = ("\n Gemini")
    elif ((int(Month)==6 and int(Day) >= 21)or(int(Month)==7 and int(Day)<= 22)):
            zodiac_sign = ("\n Cancer")
    elif ((int(Month)==7 and int(Day) >= 23)or(int(Month)==8 and int(Day)<= 22)):
            zodiac_sign = ("\n Leo")
    elif ((int(Month)==8 and int(Day) >= 23)or(int(Month)==9 and int(Day)<= 22)):
            Signo_Zodiacal = ("\n Virgo")
    elif ((int(Month)==9 and int(Day) >= 23)or(int(Month)==10 and int(Day)<= 22)):
            zodiac_sign = ("\n Libra")
    elif ((int(Month)==10 and int(Day) >= 23)or(int(Month)==11 and int(Day)<= 21)):
            zodiac_sign = ("\n Scorpio")
    elif ((int(Month)==11 and int(Day) >= 22)or(int(Month)==12 and int(Day)<= 21)):
            zodiac_sign = ("\n Sagittarius")

    print(zodiac_sign)

program()

rawDescription: Zodiacal sign python

description: Zodiacal sign python


code:
import compileall

compileall.compile_dir('D:/FAS/config', force=True)

rawDescription: How to compile all py file to pyc file in a folder by writing a python script?

description: Compile all py file to pyc file in a folder by writing a python script


code:
from itertools import product
from string import ascii_lowercase, digits

possible_chars = ascii_lowercase + digits

for password_length in range(1, 9):  # up to 8 characters
    for chars in product(possible_chars, repeat=password_length):
        guess = "".join(chars)
        # test guess

rawDescription: My Own Brute Force

description: My Own Brute Force


code:
end_time = datetime.now()
start_time = datetime(end_time.year,end_time.month,end_time.day)

rawDescription: All posts from same day only django

description: All posts from same day only django


code:
if s in ('a', 'b'):
    return 1
elif s in ('c', 'd'):
    return 2
else:
    return 3

rawDescription: how to check variable against 2 possible values python

description: Check variable against 2 possible values python


code:
#!/usr/bin/python
# Circuit:
# * A Piezo is connected to pin 12 on header P8.        - GPIO1_12
# * A LED is connected to pin 14 on header P8.          - GPIO0_26
# * A button is connected to pin 45 on header P8.       - GPIO2_6
#   Use a pull-down resistor (around 10K ohms) between pin 45 and ground.
#       3.3v for the other side of the button can be taken from pins 3 or 4
#       on header P9. Warning: Do not allow 5V to go into the GPIO pins.
# * GND - pin 1 or 2, header P9.

def setup(): # this function will run once, on startup
    pinMode(PIEZO, OUTPUT) # set up pin 12 on header P8 as an output - Piezo
    pinMode(LED, OUTPUT) # set up pin 14 on header P8 as an output - LED
    pinMode(BUTTON, INPUT) # set up pin 45 on header P8 as an input - Button

def loop(): # this function will run repeatedly, until user hits CTRL+C
    if (digitalRead(BUTTON) == HIGH):
        # was the button pressed? (is 3.3v making it HIGH?) then do:
            buzz()
    delay(10) # don't "peg" the processor checking pin

def delay(j):  #need to overwrite delay() otherwise, it's too slow
    for k in range(1,j):
            pass

def buzz():    #this is what makes the piezo buzz - a series of pulses
               # the shorter the delay between HIGH and LOW, the higher the pitch
    limit = 500     # change this value as needed;
                    # consider using a potentiometer to set the value
    for j in range(1, limit):
            digitalWrite(PIEZO, HIGH)
            delay(j)
            digitalWrite(PIEZO, LOW)
            delay(j)
            if j==limit/2:
                    digitalWrite(LED, HIGH)
    digitalWrite(LED, LOW) # turn it off

run(setup, loop)

rawDescription: How to generate sound signal through a GPIO pin on BeagleBone

description: Generate sound signal through a GPIO pin on BeagleBone


rawDescription: how to get around a websocket call blocking other websocket calls

description: Get around a websocket call blocking other websocket calls


code:
import numpy as np
np.dstack((a,b,c)).swapaxes(1,2)

rawDescription: combining 2D arrays to 3D arrays

description: Combining 2D arrays to 3D arrays


rawDescription: How does one specify the input file for a runner from Python?

description: Specify the input file for a runner from Python


code:
class get_db:
    def __init__(self, dbpath):
        con = sqlite3.connect(dbpath, isolation_level=None)
        self.tups = con.cursor()

        self.dict = con.cursor()
        self.dict.row_factory = sqlite3.Row

rawDescription: Tuples AND row_factory functionality via Python classes


code:
class Defender(object):

    def spy_on_attacker(self, attacker):
        guns = attacker.guns
        weight = attacker.weight

rawDescription: getting variables from one class into another

description: Getting variables from one class into another


code: x1, xy, x2, y2 = wsol.T

rawDescription: How to set a numpy array in loop and plot

description: Set a numpy array in loop and plot


code:
import struct
plc_real = "1234"
struct.unpack("f", plc_real)[0]

rawDescription: Interpret list of integers as a float in Python


code: res = dict((v,k) for k,v in a.iteritems())

rawDescription: Python: Best Way to Exchange Keys with Values in a Dictionary?


rawDescription: Pandas stack columns in dataframe an make a histogram


code:
L=[1,2,2,3,4,5,5,5,6,7,8,8,9]
from collections import Counter
[[k]*v for k,v in Counter(L).items()]

rawDescription: Unique lists from a list

description: Unique lists from a list


rawDescription: Python, How to round up to maximum precision


code:
import subprocess

def dl(lk, fl):
    opts = ['-o', fl + '/%(title)s-%(id)s.%(ext)s', '--playlist-end', '20',
            '--extract-audio', '--audio-   format', 'mp3', '--audio-quality',
            '9', '--write-thumbnail', lk]

    args = ['python', '-m', 'youtube_dl']
    args.extend(opts)

    p = subprocess.Popen(args) # You can use subprocess.PIPE to redirect stdout & stderr. Read the doc for more info.
    p.communicate() # Wait for process to terminate.

    if p.returncode == 0: # You might wanna check for correct successful return code.
        return 'Successful download'
    else:
        return 'Download Failed'

rawDescription: Python Youtube-dl - keep terminal / tkinter window open after executing


code: ' '.join(s.split())

rawDescription: Python/Django: How to remove extra white spaces & tabs from a string?


code:
import pyproj
from shapely.geometry import Polygon, Point
from shapely.ops import transform
from functools import partial

project = partial(
    pyproj.transform,
    pyproj.Proj(init='epsg:4326'),
    pyproj.Proj('+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs'))

poly = Polygon(([-80.190262, 25.774252], [-66.118292, 18.466465], [-64.75737, 32.321384]))
p1 = Point(-76.728515625, 27.254629577800088)

# Old answer, using long/lat coordinates
poly.contains(p1)  # False
poly.distance(p1)  # 0.01085626429747994 degrees

# Translate to spherical Mercator or Google projection
poly_g = transform(project, poly)
p1_g = transform(project, p1)

poly_g.contains(p1_g)  # True
poly_g.distance(p1_g)  # 0.0 meters

rawDescription: shapely and matplotlib point-in-polygon not accurate with geolocation

description: Shapely and matplotlib point-in-polygon not accurate with geolocation


code:
import mako.runtime

# Scan for scripts and styles to include.
include_scripts = []
include_styles = []

# Start at the first descendant template.
ns = next
while isinstance(ns, mako.runtime.Namespace):
    if hasattr(ns.attr, 'include_scripts'):
        include_scripts.extend(ns.attr.include_scripts)
    if hasattr(ns.attr, 'include_styles'):
        include_styles.extend(ns.attr.include_styles)

    # NOTE: If the template namespace does not have *next* set, the built
    # in python function *next()* gets returned.
    ns = ns.context.get('next')

rawDescription: Scan descendant template namespaces for particular attributes


code:
from inspect import getsourcefile, getfile, getlineno, stack
from sys import exc_info

...

def add_error(self, error):
    """
    Adds an error to the test.

    :type error: Exception
    """
    error.file = None
    error.line = None

    # Try to guess the file and line number where the error occurred.
    exc_tb = exc_info()[2]

    try:
        if exc_tb:
            # If we have traceback info (i.e., from a caught exception), add it to the error.
            error.file = (getsourcefile(exc_tb.tb_frame) or getfile(exc_tb.tb_frame))
            error.line = getlineno(exc_tb.tb_frame)
        else:
            #
            # Otherwise, find the caller in the current stack.
            #
            # stack()[1] = (<frame object>, filename, line_number, caller, context_line, pos_in_context_line)
            # Note that we pass 0 to `stack()` so that it doesn't return any context lines,
            #  since we're not interested in that.
            #
            (error.file, error.line) = stack(0)[1][1:3]
    except Exception as e:
        # Well, we tried.
        error.file = '(unable to determine due to %s %r)' % (e.__class__.__name__, e.message,)
    finally:
        #
        # Very important to make sure `exc_tb` gets deleted to prevent a circular reference.  Although Python's GC
        #   is smart enough to catch this and free the memory anyway, it's better not to create the circular
        #   reference in the first place.
        #
        # :see: https://docs.python.org/2/library/sys.html#sys.exc_info
        #
        del exc_tb

    self.errors.append(error)

rawDescription: Capture file and line number for an exception that wasn't raised


code:
def gcd(a, b):
    rem = a % b
    while rem != 0:
        a = b
        b = rem
        rem = a % b
    return b

def primegen():
    yield 2
    yield 3
    yield 5
    yield 7
    yield 11
    accum = 2*3*5*7
    out = file('tmp_primes.txt', 'w')
    inp = file('tmp_primes.txt', 'r+')
    out.write('0x2\n0x3\n0x5\n0x7\n0xb\n')
    inp.read(20)
    inpos = inp.tell()
    next_accum = 11
    next_square = 121
    testprime = 13
    while True:
        if gcd(accum, testprime) == 1:
            accum *= testprime # It's actually prime!
            out.writelines((hex(testprime), '\n'))
            yield testprime
        testprime += 2
        if testprime >= next_square:
            accum *= next_accum
            nextline = inp.readline()
            if (len(nextline) < 1) or (nextline[-1] != '\n'):
                out.flush()
                inp.seek(inpos)
                nextline = inp.readline()
            inpos = inp.tell()
            next_accum = int(nextline, 16)
            next_square = next_accum * next_accum

def next_n(iterator, n):
    """Returns the next n elements from an iterator.

    >>> list(next_n(iter([1,2,3,4,5,6]), 3))
    [1, 2, 3]
    >>> list(next_n(primegen(), 10))
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
    """
    while n > 0:
        yield iterator.next()
        n -= 1

rawDescription: How to solve this memory error - python

description: Solve this memory error - python


code:
from IPython.nbformat import current as nbf

nb = nbf.new_notebook()

cells = []

for var in my_list:
    # Assume make_image() saves an image to file and returns the filename
    image_file = make_image(var)
    text = "Variable: %s\n![image](%s)" % (var, image_file)
    cell = nbf.new_text_cell('markdown', text)
    cells.append(cell)

nb['worksheets'].append(nbf.new_worksheet(cells=cells))

with open('my_notebook.ipynb', 'w') as f:
        nbf.write(nb, f, 'ipynb')

rawDescription: programatically add cells to an ipython notebook for report generation

description: Programatically add cells to an ipython notebook for report generation


code:
count = 0
for c in data['comments']:
  count += c['count']

rawDescription: Parsing Json (list within dictionaries) in Python


code:
import wx

from time import *

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, (550, 350))
        self.second_zones = []
        zone_list = ['CET', 'GMT', 'MSK', 'EST', 'PST', 'EDT']

        panel = wx.Panel(self, -1)
        self.time_zones = wx.ListBox(panel, -1, (10,100), (170, 130), zone_list, wx.LB_SINGLE)
        self.time_zones.SetSelection(0)

        self.time_zones2 = wx.ListBox(panel, -1, (10,200), (170, 400), '',wx.LB_SINGLE)

        self.Bind(wx.EVT_LISTBOX, self.OnSelectFirst, self.time_zones)
        self.Bind(wx.EVT_LISTBOX, self.OnSelectSecond, self.time_zones2)

    def OnSelectFirst(self, event):
        index = event.GetSelection()
        time_zone = str(self.time_zones.GetString(index))
        self.second_zones.append(time_zone)
        self.time_zones2.Set(self.second_zones)

    def OnSelectSecond(self, event):
        index = event.GetSelection()
        time_zone = str(self.time_zones2.GetString(index))
        self.second_zones.remove(time_zone)
        self.time_zones2.Set(self.second_zones)

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'listbox.py')
        frame.Centre()
        frame.Show(True)
        return True

app = MyApp(0)
app.MainLoop()

rawDescription: wxpython:Insert multiple strings from one listbox to an other listbox

description: Wxpython:Insert multiple strings from one listbox to an other listbox


code:
data = urllib.urlretrieve(url, targetPath)
msg = data[1]
print(msg.getheader("content-length"))

rawDescription: In Python: how to verify if file has been downloaded correctly before opening it


rawDescription: Simple way of stacking arrays with index offset


code:
import pandas as pd
# generating data set (N: number, S: resulting string)
df = pd.DataFrame({'N': np.arange(1,N+1), 'S': np.arange(1,N+1) },columns=['N','S'])
# convert col. S to string
df['S']=df['S'].apply(str)
# set empty string if x mod 3 == 0 or x mod 5 == 0
df['S'][(df['N'].mod(3)==0) | (df['N'].mod(5)==0)] = ""
# set mod 3 == 0 condition
df['S'][(df['N'].mod(3)==0)] = "inf"
# mod 5 == 0
df['S'][(df['N'].mod(5)==0)] = df['S']+"luans"

rawDescription: how to vectorize this?

description: Vectorize this


code: total = sum(x+y for x in (0,1,2,3) for y in (0,1,2,3) if x < y)

rawDescription: List comprehension for loops Python

description: List comprehension for loops Python


code:
bar = foo.get('bar')
if bar:
   ...
del bar

rawDescription: If expression variables inside if block

description: If expression variables inside if block


code:
dispatch = {
  'check': do_check,
  'search': do_search,
}
cmd, _, arg = input.partition(' ')
if cmd in dispatch:
    dispatch[cmd](arg)
else:
    do_default(cmd, arg)

rawDescription: "Pythonic" equivalent for handling switch and multiple string compares


code:
DOC = """<root>
  <link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=gfyKPbic&feature=youtube_gdata'/>
  <link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/gf7zhyKPbic/responses'/>
</root>"""
from xml.dom.minidom import parseString, parse
dom = parseString(DOC)
hreflist= [elt.getAttribute("href") for elt in dom.getElementsByTagName('link')  if elt.getAttribute("rel")=="alternate"]
for href in hreflist:
    print(href)

rawDescription: In Python, retrieving Xml attribute value