code:
class Chef(games.Sprite):
    """
    A chef which moves left and right, dropping pizzas.
    """
    image = games.load_image("chef.bmp")

    def __init__(self, x = games.screen.width / 2, y = 55, speed = 2, odds_change = 200):
        """ Initialize the Chef object. """
        super(Chef, self).__init__(image = Chef.image,
                               x = x,
                               y = y,
                               dx = speed)     # although this will work, you should either rename dx as speed or vice-versa

        self.odds_change = odds_change
        self.time_til_drop = 0

rawDescription: Understanding super() and questions about class constructors


code:
from fuzzywuzzy import fuzz
string1 = 'Green apple'
string2 = 'Apple, green'
string3 = 'Green apples - grow on trees'
fuzz.partial_token_set_ratio(string1,string3)
100
fuzz.partial_token_set_ratio(string1,string2)
100
string4="apple"
fuzz.partial_token_set_ratio(string1,string4)
100
fuzz.partial_token_set_ratio(string4,string1)
100
string4="app"
fuzz.partial_token_set_ratio(string4,string1)
100
string4="appld"
fuzz.partial_token_set_ratio(string4,string1)
80

rawDescription: Matching two string that contain same words from left to right in Python


code:
list1 = [{'tag':'XXX', 'key1':'a'}, {'tag':'YYY', 'key1':'a'}]
list2 = [{'tag':'XXX', 'key1':'c'}, {'tag':'ZZZ', 'key1':'d'}]
tags = set(d['tag'] for d in list1)
list1.extend(d for d in list2 if not d['tag'] in tags)
list1

rawDescription: How to combine data from two sequences of dictionaries

description: Combine data from two sequences of dictionaries


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

from PyQt4 import QtGui, QtCore

class MyWindow(QtGui.QTextEdit):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.setPlainText("Hello!")

        cursor = self.textCursor()
        cursor.movePosition(QtGui.QTextCursor.End, QtGui.QTextCursor.MoveAnchor)

        self.setTextCursor(cursor)

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.show()

    sys.exit(app.exec_())

rawDescription: Issue with QTextEdit cursor, when using eventFilters


code:
import pylab as pl
xs = [0, 1, 2]
ys = [2.5, 4, 3]
pl.plot(xs, ys, "-o")
for x, y in zip(xs, ys):
    pl.text(x, y, str(x), color="red", fontsize=12)
pl.margins(0.1)

rawDescription: Using numbers as matplotlib plot markers


code:
from email.parser import HeaderParser
data = conn.fetch(message, '(BODY[HEADER.FIELDS (SUBJECT FROM)])')
header_data = data[1][0][1]
parser = HeaderParser()
msg = parser.parsestr(header_data)

rawDescription: Get email subject and sender using imaplib?


code:
from matplotlib.pylab import *
from numpy import arange

pcolor(arange(20).reshape(4,5))
cb = colorbar(label='a label')
ax = cb.ax
text = ax.yaxis.label
font = matplotlib.font_manager.FontProperties(family='times new roman', style='italic', size=16)
text.set_font_properties(font)
show()

rawDescription: How to change font properties of a matplotlib colorbar label?

description: Change font properties of a matplotlib colorbar label


code:
class Foo(object):
    pass
obj = Foo()
obj.__class__.__name__ = 'Bar'
obj
obj.__class__

rawDescription: Is it possible to override `__name__` derived from object?


code:
from itertools import takewhile, dropwhile

with open('logfile') as fin:
    start = dropwhile(lambda L: '03.Nov.2012' not in L, fin)
    until = takewhile(lambda L: '12.Oct.2013' not in L, start)
    query = (line for line in until if 'search string' in line)
    for line in query:
        pass # do something

rawDescription: How can I search a range of lines in python?

description: Search a range of lines in python


code:
def eratosthenes2(n):
    multiples = set()
    for i in range(2, n+1):
        if i not in multiples:
            yield i
            multiples.update(range(i*i, n+1, i))

print(list(eratosthenes2(100)))

rawDescription: Efficient method for generating lists of large prime numbers


code: objects = ndb.get_multi([ndb.Key(Model, k) for k in ids])

rawDescription: Getting multiple entities with get_by_id in ndb


code:
import ast
ast.literal_eval("1+1")
ast.literal_eval("\"1+1\"")
ast.literal_eval("{'a': 2, 'b': 3, 3:'xyz'}")

rawDescription: Python convert string object into dictionary


code:
from mpl_toolkits.mplot3d import Axes3D
from scipy.misc import imread
from matplotlib.pyplot import figure, show
from numpy import linspace, meshgrid, sqrt, sin, mean, flipud

clown = imread('clown.png')
fig = figure()
ax = fig.gca(projection='3d')
X = linspace(-5, 5, clown.shape[0])
Y = linspace(-5, 5, clown.shape[1])
X, Y = meshgrid(X, Y)
R = sqrt(X**2 + Y**2)
Z = sin(R)
clown = clown.swapaxes(0,1) / 255. # meshgrid orients axes the other way around, scaling of rgb to [0-1]
ax.plot_surface(X, Y, Z, facecolors=flipud(clown))
ax.view_init(45,-35) # swapped wrt matlab
show()

rawDescription: equivalent from MATLAB to Python

description: Equivalent from MATLAB to Python


code:
from Tkinter import Text, BOTH
import re

class T(Text):

    def __init__(self, *a, **b):

        # Create self as a Text.
        Text.__init__(self, *a, **b)

        #self.bind("<Button-1>", self.click)
        self.bind("<Key>", self.key)
        self.bind("<Control-v>", self.paste)

    def key(self,k):
        if k.char and k.char not in "atgcATGC":
            return "break"

    def paste(self,event):
        clip=self.selection_get(selection='CLIPBOARD')
        clip=clip.replace("\n","").replace("\r","")
        m=re.match("[atgcATGC]*",clip)
        if m and m.group()==clip:
            self.clipboard_clear()
            self.clipboard_append(clip)
        else:
            self.clipboard_clear()
            return

t = T()
t.pack(expand=1, fill=BOTH)
t.mainloop()

rawDescription: Tkinter text field with limited number of availabale character


code:
A = 45
B = 55
C = 65

names = ['A', 'B', 'C'] # list of variable names
res = '\n'.join([varname + ' =' + str(locals()[varname]) for varname in names])

rawDescription: Format string in python

description: Format string in python


code:
import numpy as np
import Image

im = Image.open('fig1.png')
data = np.array(im)

r1, g1, b1 = 0, 0, 0 # Original value
r2, g2, b2 = 255, 255, 255 # Value that we want to replace it with

red, green, blue = data[:,:,0], data[:,:,1], data[:,:,2]
mask = (red == r1) & (green == g1) & (blue == b1)
data[:,:,:3][mask] = [r2, g2, b2]

im = Image.fromarray(data)
im.save('fig1_modified.png')

rawDescription: Change the color of all pixels with another color


code:
from django.utils.importlib import import_module
app_label = "app"
url = import_module("%s.urls" % app_label).HOME_URL

rawDescription: How to access a python module variable using a string [ django ]

description: Access a python module variable using a string [ django ]


code:
import wx

class ExamplePanel(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        self.mainBox = wx.StaticBox(self, id=-1, label="Box Label")
        self.mainSizer = wx.StaticBoxSizer(self.mainBox, wx.VERTICAL)

        labels = ["A: ", "B: ", "C: "]
        for i, label in enumerate(labels):
            itemLabel = wx.StaticText(self, label=label)
            itemTextCtrl = wx.TextCtrl(self, value="placeholder")
            itemTextCtrl.SetForegroundColour(wx.LIGHT_GREY)
            rowSizer = wx.BoxSizer(wx.HORIZONTAL)
            rowSizer.Add(itemLabel, 0, wx.ALL, 0)
            rowSizer.Add(itemTextCtrl, 0, wx.ALL, 0)
            self.mainSizer.Add(rowSizer)

        self.SetSizer(self.mainSizer)
        self.mainSizer.Fit(self)

if __name__ == '__main__':
    app = wx.App(False)
    frame = wx.Frame(None)
    panel = ExamplePanel(frame)
    frame.Show()
    app.MainLoop()

rawDescription: Nesting sizers within a box using wxPython


code:
r.table('f_tab').filter(
  lambda row: r.expr([{'sid': 21, 'et': 5}, ...]).set_difference(row['sk']).is_empty()
).filter(
  lambda row: r.expr([{'wid': 22, 'et': 6}, ...]).set_difference(row['wc']).is_empty()
)['pid']

rawDescription: Filter nested fields in RethinkDB rows based on multiple values


code:
from cStringIO import StringIO
import win32clipboard
from PIL import Image

def send_to_clipboard(clip_type, data):
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardData(clip_type, data)
    win32clipboard.CloseClipboard()

filepath = 'image.jpg'
image = Image.open(filepath)

output = StringIO()
image.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()

send_to_clipboard(win32clipboard.CF_DIB, data)

rawDescription: Write image to Windows clipboard in python with PIL and win32clipboard?


code:
s = 'this is the string that Luci want to parse for a dataset uci at web'
s.split(' ').count('uci')

rawDescription: count word occurances in a string

description: Count word occurances in a string


code:
def say_hi(self):
    print("hi there, everyone!")
    sys.stdout.flush()

rawDescription: Emacs: Inferior-mode python-shell appears "lagged"


code:
df['date'] = map(lambda x: x.date(), df.index)
df['time'] = map(lambda x: x.time(), df.index)

sol = df.pivot('time', 'date', 'Close')

rawDescription: Custom display of time series data using Pandas


code:
""" Guess the number game.
"""
import random

def is_same(targ, num):
    """ Check for correct entry. """
    if targ == num:
        result = "WIN"
    elif targ > num:
        result = "LOW"
    else:
        result = "HIGH"

    return result

def play_game():
    """ Play the game 1 time, returns play_again """
    User_Name = input("What is your name?\n:")
    print("\nWelcome", User_Name, "To the guessing number game")
    print("""\n\n
                GUESSING NUMBER GAME
          ----------------------------------
          ##################################
          #                                #
          #     [E] For Easy 1 - 10        #
          #                                #
          #     [M] For Medium 1 - 50      #
          #                                #
          #     [H] For Hard 1 - 100       #
          #                                #
          ##################################
          """)

    Choose_Level = input("\t\tPlease choose your Level : ")

    while Choose_Level != "E" and Choose_Level != "M" and Choose_Level != "H":
        # this could be simplified to: while choose_level not in 'EMF':
        Choose_Level = input("Sorry. You must type in one of the letters " +
                "'E', 'M', 'H'\n:")

    if Choose_Level == "E":
        print("You have chosen the Easy Level! You are a wimp by nature")
    elif Choose_Level == "M":
        print("You have chosen the Medium Level! Can you defeat the game?")
    else:
        print("You have chosen the Hard Level! " +
                "You are a Guessing Number warrior")

    if Choose_Level == "E":
        computer_number = random.randint(1, 10)
    elif Choose_Level == "M":
        computer_number = random.randint(1, 50)
    else:
        computer_number = random.randint(1, 100)

    counter = 1
    higher_or_lower = ""
    while higher_or_lower != "WIN":
        guess = int(input("Can you guess the number? \n:"))
        higher_or_lower = is_same(computer_number, guess)
        counter += 1

        if higher_or_lower == "LOW":
            print("Guess attempts", counter)
            print("\nSorry, you are to low. Please try again.\n:")
        elif higher_or_lower == "HIGH":
            print("Guess attempts", counter)
            print("\nSorry, To high. Please try again. \n:")
        else:
            print("Correct!\nWell done\n\n")
            break

    print("""
    ##############################
    #                            #
    #    [S] Play again          #
    #                            #
    #    [E] Exit                #
    #                            #
    ##############################
    """)

    start_again = input("\t\t Please choose a option 'S' or 'E' ")

    while start_again != "S" and start_again != "E":
        # can simplify: while start_again not in 'SE':
        start_again = input("You must enter a upper case letter" +
                "'S' or 'E' to continue")

    if start_again == "S":
        return True
    else:
        return False

def main():
    """ Main loop for playing the game. """
    play_again = True
    while play_again:
        play_again = play_game()

    print("Thanks for playing the number game. Goodbye")

if __name__ == '__main__':
    main()

rawDescription: Beginner Python-Looping to the beginning of a programme


code: num_lines = sum(not s.startswith('#') for s in open('/etc/default/nss'))

rawDescription: Is there a Python one-liner to grab the number of lines in a file EXCLUDING comments?


code:
import os

os.system('export http://<your proxy>:<your port>/')
os.system('export https://<your proxy>:<your port>/')

rawDescription: Change browser proxy settings from Python in Ubintu?


code:
import bs4

soup =  bs4BeautifulSoup(html_content);
result = soup.find("div", { "class" : "wikicontent", "id" : "wikicontentid" })

rawDescription: How can I remove everything except a selected tag from a html file with python?

description: Remove everything except a selected tag from a html file with python


code:
def Insert(head, data):

    if (head == None):
        head = Node(data)
    else:
        current = head
        while (current.next != None):
            current = current.next
        current.next = Node(data)
    return head

rawDescription: Insert a Node at the Tail of a Linked List python HackerRank


code:
from ansible.plugins.callback import CallbackBase
import os
import time
import sqlite3

dbname = './test.db'
TIME_FORMAT='%Y-%m-%d %H:%M:%S'

try:
    con = sqlite3.connect(dbname)
    cur = con.cursor()
    cur.execute('CREATE TABLE `test` (`now` TEXT, `host` TEXT UNIQUE)')
    con.commit()
except:
    pass

def log(host, data):

    if type(data) == dict:
        invocation = data.pop('invocation', None)
        if invocation.get('module_name', None) != 'setup':
            return

    facts = data.get('ansible_facts', None)

    now = time.strftime(TIME_FORMAT, time.localtime())

    try:
        # `host` is a unique index
        cur.execute("REPLACE INTO test (now, host) VALUES(?,?);",
        (
            now,
            facts.get('ansible_hostname', None)
        ))
        con.commit()
    except:
        pass

class CallbackModule(CallbackBase):
    def runner_on_ok(self, host, res):
        log(host, res)

rawDescription: Ansible - putting facts in SQLite via Callback


code: MyInt(1) + MyInt(1) is 2

rawDescription: What objects are guaranteed to have different identity?


code:
def login_required(test):
  @wraps(test)
  def wrap(*args, **kwargs):
    if 'logged_in' in session:

      # session is always none
      start_time = session.get('session_time', None)

      #get the current time and set it as start time, this is also your session timer start
      if start_time is None:
        start_time = datetime.datetime.now()
        session['session_time'] = start_time

      # make an end time 1 minute from now
      end_time = start_time + datetime.timedelta(minutes=1)

      #find the current time in a for loop maybe? or just an if will probably work.
      if datetime.datetime.now() > end_time:
        return redirect(url_for('expired', next=request.url))
        session.clear()
        start_time = session.get('session_time', None)

      return test(*args, **kwargs)
    else:

      return redirect(url_for('login', next=request.url))
  return wrap

@app.route('/login', methods=['GET', 'POST'])
def login():
  error = None
  if request.method == 'POST':
    if request.form['username'] != app.config['USERNAME']:
      error = 'Invalid username'
    elif request.form['password'] != app.config['PASSWORD']:
      error = 'Invalid password'
    else:
      session['logged_in'] = True
      return redirect(url_for('media'))
  return render_template('login.html', error=error)

@app.route('/expired')
def expired():
  session.clear()
  return render_template('expired.html')

rawDescription: Basic timeout for HTTP Basic Auth

description: Basic timeout for HTTP Basic Auth


code:
from bs4 import BeautifulSoup
from bs4.element import NavigableString
from copy import copy

def strip_content(in_tag):
    tag = copy(in_tag) # remove this line if you don't care about your input
    if tag.name == 'script':
        # Do no mess with scripts
        return tag
    # strip content from all children
    children = [strip_content(child) for child in tag.children if not isinstance(child, NavigableString)]
    # remove everything from the tag
    tag.clear()
    for child in children:
        # Add back stripped children
        tag.append(child)
    return tag

def test(filename):
    soup = BeautifulSoup(open(filename))
    cleaned_soup = strip_content(soup)
    print(cleaned_soup.prettify())

if __name__ == "__main__":
    test("myfile.html")

rawDescription: Remove text from HTML files but keep the javascript and structure using python


code:
s = "abc"
out.write( struct.pack(">H", len(s) ))
out.write( struct.pack(">%ds" % len(s), s ))

rawDescription: How to read String in java that was written using python's struct.pack method

description: Read String in java that was written using python's struct.pack method


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

X, Y, Z = axes3d.get_test_data(0.05)

plt.subplot(131)
cset = plt.contourf(X, Y, Z, cmap=cm.coolwarm)
plt.subplot(132)
cset = plt.contourf(Y, Z, X, cmap=cm.coolwarm)
plt.subplot(133)
cset = plt.contourf(X, Z, Y, cmap=cm.coolwarm)

plt.show()

rawDescription: Matplotlib separate 2D contour projection plots of 3D data


code:
Properties = JClass('java.util.Properties')
props = Properties()
props.setProperty('foo','bar')

rawDescription: jpype and java.util.Properties

description: Jpype and java.util.Properties


code:
import re

s = re.compile(r'^<div.*?>([^<]+)<br.*?>([^,]+), (\w\w) (\d{5}-\d{4})</div>$')
mo = s.match(thestring)
if mo is None:
  raise ValueError('No match for %r' % thestring)
address, city, state, zip = mo.groups()

rawDescription: Python string split

description: Python string split


code:
a
b = numpy.array([numpy.NaN] * len(a))
b[::8] = a[::8]
b

rawDescription: How can I mask every element except each nth, in an iterator?

description: Mask every element except each nth, in an iterator


code:
import json
...
res = f.responce.read().decode()
data = json.loads(res)

rawDescription: Data request string python

description: Data request string python


code:
#!/usr/bin/python
import subprocess
import threading
import time
import os

bytes_read = 0

def readBOB(pipe):
    global bytes_read
    bytes_read = 0
    while True:
        # Wait for some data to arrive. This must use os.read rather
        # than pipe.read(1024) because file.read would block us if less
        # than 1024 bytes of data arrives. (Reading one byte at a time
        # with pipe.read(1) would work, but would be too slow at
        # consuming large amounts of data.)
        s = os.read(pipe.fileno(), 1024)
        if not s:
            return  # EOF
        # we are the only writer, so GIL serves as the lock
        bytes_read += len(s)

def runBOB(argsList):
    # Start the subprocess of BOB
    BOBsp = subprocess.Popen(argsList, stdout=subprocess.PIPE)

    thr = threading.Thread(target=readBOB, args=(BOBsp.stdout,))
    thr.start()
    old_bytes_read = -1

    while True:
        # See if subprocess has finished
        if BOBsp.poll() is not None:
            return 0

        # if the size of the stdout has increased, BOB.exe is still running
        new_bytes_read = bytes_read

        if new_bytes_read > old_bytes_read:
            old_bytes_read = new_bytes_read
        else: # if not, kill it (readBOB will exit automatically)
            BOBsp.kill()
            return 1

        # Check every 10 seconds
        time.sleep(10)

rawDescription: Python: Reading a subprocess' stdout without printing to a file


code:
try:
    _count = int(open("counter").read())
except IOError:
    _count = 0

def incrcounter(n):
    global _count
    _count = _count + n

def savecounter():
    open("counter", "w").write("%d" % _count)

import atexit
atexit.register(savecounter)

rawDescription: Always execute Code and the end of a python script


code:
import unidecode
unidecode.unidecode(u'BACK RUSHIN\u2019')

rawDescription: Character encoding in python to replace 'u2019' with '


code:
import re
pattern = re.compile(r'^\s*([^\s]+)\s*$', re.UNICODE)

rawDescription: Lookbehind assertion needed?

description: Lookbehind assertion needed


code:
import os
folder1={x for x in os.listdir('some_directory') if os.path.isfile(x)}
folder2={x for x in os.listdir('some_other_directory') if os.path.isfile(x)}
common_files=folder1.intersection(folder2)

rawDescription: Finding matching filenames between directories


rawDescription: Matlab Colon Operator equivalent in Vpython


code: self.timer = Timer(seconds, lambda: None)

rawDescription: is this python Timer usage safe?

description: Is this python Timer usage safe


rawDescription: Link C in llvmlite

description: Link C in llvmlite


rawDescription: Fast conversion from string to numpy.int16 array


rawDescription: using regular expression substitution command to insert leading zeros in front of numbers less than 10 in a string of filenames

description: Using regular expression substitution command to insert leading zeros in front of numbers less than 10 in a string of filenames


code:
from datetime import timedelta

from django.utils import timezone
from user_sessions.models import Session

recent_users = Session.objects.filter(last_activity__gte=(timezone.now()-timedelta(minutes=5))).only('user').distinct('user')

rawDescription: How to fetch users who had at least 1 session within the last 5 mins in my Django app

description: Fetch users who had at least 1 session within the last 5 mins in my Django app


code:
class IngressFlow(models.Model):
    class Meta:
        db_table = 'ingress_flow'

rawDescription: Django - database data not showing in application?


code:
class UserSerializer(serializers.ModelSerializer):
    # <Your other UserSerializer stuff here>

    def create(self, validated_data):
        password = validated_data.pop('password', None)
        instance = self.Meta.model(**validated_data)
        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            if attr == 'password':
                instance.set_password(value)
            else:
                setattr(instance, attr, value)
        instance.save()
        return instance

rawDescription: Why isn't my Django User Model's Password Hashed?


rawDescription: how to use logging inside Gevent?

description: Use logging inside Gevent


code: getattr(cls, 'fields')['key'] = 'value'

rawDescription: Add key to dict with setattr() in Python


code:
class A(object):
  def __init__(self, params = None):
    self.myBs = [B() for _ in range(10)]

  def getB(self):
    return self.myBs[5]

class B(object):
  def foo(self):
    pass

inst = A().getB()
# Auto-complete broken.  PyDev thinks inst is a list.
assert isinstance(inst, B)
# Auto-complete working again.

rawDescription: In PyDev, how can I get autocompletion for an instance returned by a method?


code:
myList = [0.0 , 0.0, 0.0, 2.0, 2.0]
next((i for i, x in enumerate(myList) if x), None) # x!= 0 for strict match

rawDescription: Python find first instance of non zero number in list


code:
from StringIO import StringIO
import numpy as np
f = StringIO()
x = np.array(( -9999, 1.345, -9999, 3.21, 0.13, -9999), dtype=float)
np.savetxt(f, x, fmt='%.3f')
f.seek(0)
fs = f.read().replace('-9999.000', '-9999', -1)
f.close()
f = open('ASCIIout.asc', 'w')
f.write("ncols " + str(ncols) + "\n")
f.write("nrows " + str(nrows) + "\n")
f.write("xllcorner " + str(xllcorner) + "\n")
f.write("yllcorner " + str(yllcorner) + "\n")
f.write("cellsize " + str(cellsize) + "\n")
f.write("NODATA_value " + str(noDATA) + "\n")
f.write(fs)
f.close()

rawDescription: Writing an ASCII file from a 2D numpy array


code: pd.concat([GOOG, AAPL], keys=['GOOG', 'AAPL'], axis=1)

rawDescription: How do I stack two DataFrames next to each other in Pandas?

description: Stack two DataFrames next to each other in Pandas


code:
def format_phone(self):
    # strip non-numeric characters
    phone = re.sub(r'\D', '', self.phone)
    # remove leading 1 (area codes never start with 1)
    phone = phone.lstrip('1')
    return '{}.{}.{}'.format(phone[0:3], phone[3:6], phone[6:])

rawDescription: How to format a phone number in python

description: Format a phone number in python


code: toolz.unique(obj_list, key=lambda x: x.my_attr)

rawDescription: Best way of removing duplicates from a list by object attribute


code:
import os, tempfile, shutil, subprocess

temp_dir = tempfile.mkdtemp()
filename = os.path.join(temp_dir, 'file.txt')
text = '<text>'
os.mkfifo(filename)

try:
    subprocess.Popen(('segment.sh', 'ctf', filename, 'utf-8', '0'))
    with open(filename, 'w') as f:
        f.write(text)
finally:
    shutil.rmtree(temp_dir)

rawDescription: How to provide input to a python subprocess call that expects filename, rather than variable?

description: Provide input to a python subprocess call that expects filename, rather than variable


code:
import importlib

def genecirCall(package_name, module_name, function_name):
    # import module you need
    module = importlib.import_module('%s.%s' % (package_name, module_name))
    getattr(module, function_name)() # make a call

rawDescription: Python get module reference from another package, knowing package and module name


code:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-p", "--parameter", default="latest")
parser.add_argument("-q", "--query")
parser.add_argument("query_string",nargs='?', default=False)

args = parser.parse_args()

if args.parameter:
   print("zoinks a parameter! %s" %args.parameter)
if args.query or args.query_string:
   print("making a query %s" % (args.query or args.query_string))

rawDescription: Set argparse argument as default switch

description: Set argparse argument as default switch


code:
class p1(object):pass
class p2(p1):pass

issubclass(p2, p1)

rawDescription: Checking if A is superclass of B in Python


rawDescription: Python/Regex - How to extract date from filename using regular expression?


code: self.factory.clients[24].transport.write("You are client 24!")

rawDescription: Twisted - sending data to selected clients


rawDescription: x axis is scaled 0.5 in default python

description: X axis is scaled 0.5 in default python


code:
dr = date_range('1/1/2010', periods=3, freq=3 * datetools.bday)
raw = randn(3)
ts = Series(raw, index=dr)
ts
ts.asfreq(datetools.BDay())
ts.resample(datetools.BDay())

rawDescription: Difference between asfreq and resample

description: Difference between asfreq and resample


code: li_sorted = sorted(li, key=lambda x: x['age'])

rawDescription: How to sort list like this?

description: Sort list like this


code:
j = 1;
axes = tuple({0,1,2,3,4} - {j})
fn = WeightedValue.sum(axes, keepdims=True) / Weights.sum(axes, keepdims=True)

rawDescription: How to broadcast a numpy 2D-array to a 6D-array

description: Broadcast a numpy 2D-array to a 6D-array


code:
import unittest

class CustomResult(unittest.TestResult):
    def addFailure(self, test, err):
        critical = ['test4', 'test7']
        if test._testMethodName in critical:
            print("Critical Failure!")
            self.stop()
        unittest.TestResult.addFailure(self, test, err)

class TestSuite1(unittest.TestCase):
    def setUp(self):
        pass

    def test1(self):
        return True

    def test2(self):
        return False

    def test3(self):
        return True

    # This is a critical test
    def test4(self):
        self.fail()
        pass

    def test5(self):
        print("test5")
        return True

    def tearDown(self):
        pass

if __name__ == '__main__':
    runner = unittest.runner.TextTestRunner(resultclass=CustomResult)
    unittest.main(testRunner=runner)

rawDescription: How to force tests to stop running a test suite after a specified test failed?

description: Force tests to stop running a test suite after a specified test failed


code:
import random

...

choice = random.choice(npc_name_male)

rawDescription: How do you Build Random Items with Multiple Variables with Multiple Choices in Python?


rawDescription: How to pop up a minimized wxPython window

description: Pop up a minimized wxPython window


code: somelist[:] = [ x for x in somelist if not somecondition(x) ]

rawDescription: Deleting list elements whilst iterating over it


code:
def combine_files(file1, file2, new_filename):
    with open(new_filename, 'w') as new_file:
        for file in [file1, file2]:
            with open(file, 'r') as original_file:
                new_file.write(original_file.read())

rawDescription: How do I concatenate the content of two files to make a third?

description: Concatenate the content of two files to make a third


code:
import web

urls = (
    "/product/(.*)", "Product"
)

class Product:
    def GET(self, product_id):
        return product_id

app = web.application(urls, globals())

if __name__ == "__main__":
    #app.run()
    assert web.__version__ == "0.37"
    b = app.browser()
    b.open('/product/xy&z')
    assert b.status == 200
    assert "xy&z" in b.data
    assert "xy&z" not in b.data
    b.open('/product/xy&z')
    assert "xy&z" in b.data

rawDescription: Unescaping URL Parameter w/ Web.py

description: Unescaping URL Parameter w/ Web.py


code: np.where(np.any(e>15, axis=1))

rawDescription: numpy get index where value is true

description: Numpy get index where value is true


rawDescription: How to reference to the top-level module in Python inside a package?

description: Reference to the top-level module in Python inside a package


code:
from itertools import product
A = [(X(x), Y(y), Z(z)) for x, y, z in product(range(N), repeat=3)]

rawDescription: Is there a more pythonic way to loop over multiple similar indices using list comprehension?


code:
import csv

d = {}

with open("file1.csv", newline="") as f:
  for row in csv.reader(f):
    d.setdefault(row[0], []).append(row + [""] * 3)

with open("file2.csv", newline="") as f:
  for row in csv.reader(f):
    old_row = d.setdefault(row[0][0], [row[0], "", "", ""])
    old_row[4:] = row[1:]

with open("out.csv", "w", newline="") as f:
  writer = csv.writer(f)
  for rows in d.values():
    writer.writerows(rows)

rawDescription: Merge 2 csv file with one unique column but different header


code:
from account import account_invoice

class account_invoice(osv.osv):
    _inherit="account.invoice"
    def invoice_validate(self, cr, uid, ids, context=None):
        super(account_invoice,self).invoice_validate()

rawDescription: Add a simple process in a account.invoice workflow


code:
# reposition the checkbox
def Reposition(self):
    rect = self.GetFieldRect(1) # the checkbox lives in the 2nd (index 1) slot
    self.cb.SetPosition((rect.x+2, rect.y+2))
    self.cb.SetSize((rect.width-4, rect.height-4))
    self.sizeChanged = False

rawDescription: How to Remove a Field from a wxStatusBar

description: Remove a Field from a wxStatusBar


code:
from time import *

# make a time string
t = strftime('%H%M%S', localtime())

# convert time string to unix time (seconds since epoch)
mktime(localtime()[:3] + strptime(t, '%H%M%S')[3:])

rawDescription: python generate Posix time from time of day

description: Python generate Posix time from time of day


code:
class EmployeeResource(ModelResource):
    def dehydrate(self, bundle):
        t = bundle.request.GET.get('t')
        if t:
            bundle.data['custom_field'] = bundle.obj.custom_field
        return bundle

    class Meta:
        fields = common_fields

rawDescription: Conditionally Showing All or Some Fields from Single TastyPie Resource


code:
class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200)

    def __str__(self):
        return self.title + ": " + self.author

def parse_book(book_name):
    title, author = book_name.split(": ", 1)
    try:
        return Book.objects.get(title=title, author=author)
    except Book.DoesNotExist:
        return None

rawDescription: Finding a model instance by string in Django


code:
with open(loc, 'r') as f:
    for i in range(16):
        f.readline()

    data = []
    while True:
        line = f.readline()
        if not line:
            if data:
                function_call(data)
            break
        if line == "\n":
            if data:
                function_call(data)
                data = []
        else:
            data.append(line)

rawDescription: Parsing newline delimited file

description: Parsing newline delimited file


code:
df
df.dtypes

rawDescription: Are there any good methods to explore Python data type?


code:
df = pd.DataFrame({'size':['big', 'big', 'small', 'small'], 'amount':[1, 9, 3, 1]})
df['pct'] = df.groupby('size')['amount'].apply(lambda x: x.astype(float)/x.sum())

rawDescription: Pandas: Percentage within Category

description: Pandas: Percentage within Category


code:
#!/usr/bin/python

import subprocess

def asrun(ascript):

    osasc = subprocess.Popen(['osascript', '-'],
    stdin = subprocess.PIPE, stdout=subprocess.PIPE)
    return osasc.communicate(ascript)[0]

def asquote(astr):

    ascrpt = astr.replace('"', '" & quote & "')
    return '"{}"'.format(ascrpt)

ascript = '''
tell application "Terminal"
    activate
    set current settings of tabs of windows to settings set "Pro"
end tell
'''

asrun(ascript)

rawDescription: Change mac's terminal theme using python


code:
import numpy as np
import string

y = np.array([[0.2,0.8,0],[0,1,0],[0,0.3,0.7]])

def transform(y,labels):
  f = np.vectorize(lambda i : string.letters[i])
  y = f(y.argmax(axis=1))
  return y

y = transform(y,'abc')

rawDescription: How to fit multidimensional output using scikit-learn?

description: Fit multidimensional output using scikit-learn


code:
z2 = T.tile(x, (3, 1))  # repeat 3x in the first dimension, 1x in the second
bar = theano.function([x], z2)

print(bar(a))
# [[ 1.  2.]
#  [ 3.  4.]
#  [ 1.  2.]
#  [ 3.  4.]
#  [ 1.  2.]
#  [ 3.  4.]]

rawDescription: How to duplicate matrix in theano

description: Duplicate matrix in theano


rawDescription: Python tar generation question

description: Python tar generation question


rawDescription: Split a list element in python by splitting by the '\t'


rawDescription: Matplotlib x-axis formatter showing decimal seconds--won't go away


code:
query[port] = {"$exists" : True}
items = mongo.db.nmaps.find(query)

rawDescription: Python3: Get rid of single quotes automatically added in a dictionary to pass it as a MongoDB query


code:
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1],[1])
ax.tick_params(axis=u'both', which=u'both',length=0)
plt.show()

rawDescription: Python hide ticks but show tick labels

description: Python hide ticks but show tick labels


code: return FooBar(foo_exp)

rawDescription: How does python treat a returned variable in a recursion function?


code:
buf = ''
ser.timeout = 1
while True:
    data = ser.read() # read a single character
    buf += data
    if data == '': # emtpy string indicates a read timeout
        processs_data(buf)
        buf = '' # wipe the buffer

rawDescription: how do I create a string of serial data only when the serial port is high and ends when the line goes low?

description: Create a string of serial data only when the serial port is high and ends when the line goes low


code:
def idDetailIndex(request, user_id):
    user = User.objects.get(id=user_id)
    return redirect('FLSocial', first_name=user.firstName, last_name=user.lastName)

rawDescription: how to rewrite a url and change it from database values in django

description: Rewrite a url and change it from database values in django


code:
def recursive_func_wrapper(arg, option=True):
    def recursive_func(arg):
        if option: recursive_func(new_arg)
        else: recursive_func(new_arg2)
    return recursive_func(arg)

rawDescription: DRYly and consisely write a recursive function


rawDescription: Reading regexes from file, in Python

description: Reading regexes from file, in Python


code:
from itertools import count

class MyClass(object):
    id_counter = count().next
    def __init__(self):
        self.id = self.id_counter()

rawDescription: Best way to generate a consecutive id in Python

description: Generate a consecutive id in Python


code:
# --- initial data
import pandas as pd
from random import random
from datetime import datetime
rng = pd.date_range('1/1/2011', periods=5, freq='H')
Activity = ([True,True,False,True,False])
ts = pd.DataFrame(Activity, index=rng, columns=['activity'])
data = ts.asfreq('45Min', method='pad')

# --- organise the data for plotting
data['colour'] = 'green'
data.colour = data.colour.where(~data.activity, other='red')
data['sz'] = 100
data.sz = data.sz.where(~data.activity, other=50)
data['position'] = data.activity.astype(int)
print(data)

# --- plot the data
import matplotlib.pyplot as plt
from matplotlib.ticker import FixedLocator
fig, ax = plt.subplots(figsize=(8,4))
ax.scatter(data.index, data.position, s=data.sz, c=data.colour)

# - the x axis
ax.set_xlim(['2010-12-31 23:00:00','2011-01-01 04:45:00'])
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')

# - the y axis
ax.set_ylim(-1, 2)
ax.spines['right'].set_color('none')
ax.yaxis.set_ticks_position('left')
labels = ['False', 'True']
tick_locations = [0, 1]
ax.yaxis.set_major_locator(FixedLocator(tick_locations))
ax.set_yticklabels(labels, minor=False)
# - and display
plt.show()

rawDescription: Plotting labed time series data pandas

description: Plotting labed time series data pandas


code:
try:
  import setproctitle
  setproctitle.setproctitle('my-awesome-program')
except:
  pass # Ignore errors, since this is only cosmetic

rawDescription: how to specify the name of my daemon process using pydaemon

description: Specify the name of my daemon process using pydaemon


code:
import httplib
c = httplib.HTTPConnection("www.google.co.uk")
c.request("HEAD", "/index.html")
r = c.getresponse()
r.getheaders()

rawDescription: Abort a request after checking response headers


code:
from google.appengine.ext import deferred
deferred.defer(my_func, arg0, arg1, ...)

rawDescription: Flask in GAE: respond quickly and then do some lengthy work


code:
from System import Uri
from System.Windows.Media.Imaging import BitmapImage

uri = Uri("D:\\test.gif")
self.img.Source = BitmapImage(uri)

rawDescription: IronPython & WPF. How to change Image.Source at runtime in code?


code:
import subprocess
subprocess.call(["git", "pull"])
subprocess.call(["make"])
subprocess.call(["make", "test"])

rawDescription: Use Git commands within Python code

description: Use Git commands within Python code


rawDescription: Django Mongoengine concurrent saves are failing


code:
from Tkinter import *

def save(e,e1,e2):
    open("text.txt","w").close()
    text = e.get() + "\t" + e1.get() + "\t" +  e2.get() + "\t"
    with open("text.txt", "a") as f:
        f.write(text)

def loadme(l,l2,l3):
    f = open('text.txt','r')
    line = f.readline()
    la1,la2,la3 = line.split()
    l.config(text=la1)
    l2.config(text=la2)
    l3.config(text=la3)
    f.close()

def main():
    root = Tk()
    c = Canvas(root,width=600)
    c.pack(side = 'left',expand=1,fill=BOTH)

    c2 = Canvas(c,width=600)
    c2.pack(side = 'left',expand=1,fill=BOTH)
    c3 = Canvas(c,width=600)
    c3.pack(side = 'left',expand=1,fill=BOTH)

    w1 = Label(c2, text="Controller value")
    w1.pack()
    e = Entry(c2)
    e.pack()
    w2 = Label(c2, text="Velocity")
    w2.pack()
    e1 = Entry(c2)
    e1.pack()
    w3 = Label(c2, text="Desired Heading")
    w3.pack()
    e2 = Entry(c2)
    e2.pack()
    toolbar = Frame(c2)
    b = Button(toolbar, text="save", width=9, command=lambda:save(e,e1,e2))
    b.pack(side=LEFT, padx=2, pady=2)
    toolbar.pack(side=TOP, fill=X)

    l = Label(c3,text='',bg='red')
    l.pack(side='left',expand=1,fill='x')
    l2 = Label(c3,text='',bg='yellow')
    l2.pack(side='left',expand=1,fill='x')
    l3 = Label(c3,text='',bg='blue')
    l3.pack(side='left',expand=1,fill='x')

    b2 = Button(c3,text='load',command=lambda:loadme(l,l2,l3))
    b2.pack(fill='x')
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Read Contents of txt file and display in Tkinter GUI Python


code:
import sip
sip.setapi('QString', 2)

from xml.etree import cElementTree as etree
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self, xml):
        QtGui.QWidget.__init__(self)
        self.tree = QtGui.QTreeWidget(self)
        self.tree.header().hide()
        self.importTree(xml)
        self.button = QtGui.QPushButton('Export', self)
        self.button.clicked[()].connect(self.exportTree)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.tree)
        layout.addWidget(self.button)

    def importTree(self, xml):
        def build(item, root):
            for element in root.getchildren():
                child = QtGui.QTreeWidgetItem(
                    item, [element.attrib['text']])
                child.setFlags(
                    child.flags() | QtCore.Qt.ItemIsEditable)
                build(child, element)
            item.setExpanded(True)
        root = etree.fromstring(xml)
        build(self.tree.invisibleRootItem(), root)

    def exportTree(self):
        def build(item, root):
            for row in range(item.childCount()):
                child = item.child(row)
                element = etree.SubElement(
                    root, 'node', text=child.text(0))
                build(child, element)
        root = etree.Element('root')
        build(self.tree.invisibleRootItem(), root)
        from xml.dom import minidom
        print(minidom.parseString(etree.tostring(root)).toprettyxml())

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window("""\
<?xml version="1.0" ?>
<root>
    <node text="Child (0)">
        <node text="Child (0)">
            <node text="Child (0)"/>
            <node text="Child (1)"/>
        </node>
        <node text="Child (1)">
            <node text="Child (0)"/>
            <node text="Child (1)"/>
        </node>
    </node>
    <node text="Child (1)">
        <node text="Child (0)">
            <node text="Child (0)"/>
            <node text="Child (1)"/>
        </node>
        <node text="Child (1)">
            <node text="Child (0)"/>
            <node text="Child (1)"/>
        </node>
    </node>
</root>
        """)
    window.setGeometry(800, 300, 300, 300)
    window.show()
    sys.exit(app.exec_())

rawDescription: How to save PySide tree view model structure

description: Save PySide tree view model structure


code: plt.xticks(range(0, 24), range(8, 24) + range(0, 8))

rawDescription: change Python plot x axis sticker values

description: Change Python plot x axis sticker values


code:
from django.forms import ModelForm

class ArticleForm(ModelForm):
    class Meta:
        model = Article

rawDescription: How to shift the django admin features to front end

description: Shift the django admin features to front end


code:
import imaplib
gmail = imaplib.IMAP4_SSL('imap.gmail.com')
gmail.login('username@gmail.com', 'password')
...

rawDescription: What library should i use to download a copy of Gmail emails through Python script?


code:
def lifecycle(population, i):
    if i == 100:
        return ...
    ...
    return lifecycle(new_population, i + 1)

rawDescription: How to Loop x Times With Functional Style?

description: Loop x Times With Functional Style


code:
{
  title: 'Skill A',
  url: 'http://skilla.com',
  children: [
    {
      title: 'Skill B',
      url: 'http://skillb.com',
      rating: 3,
      children: [
        {
          title: 'Skill D',
          url: 'http://skilld.com',
          rating: 5
        },
        {
          title: 'Skill E',
          url: 'http://skilld.com',
          rating: 10
        }
      ]
    },
    {
      title: 'Skill C',
      url: 'http://skillc.com',
      rating: 1
    }
  ]
}

rawDescription: Drawing rooted trees with KineticJS

description: Drawing rooted trees with KineticJS


code:
import numpy as np
import sys

a = np.array([0]*10000, np.uint8)
len(a)
# 10000
sys.getsizeof(a)
# 10048
sys.getsizeof(a[0])
# 13
a = np.array([0]*1000000, np.uint8)
sys.getsizeof(a)
# 1000048

rawDescription: Storing an integer less than 256 within a byte of memory in Python


rawDescription: Marquee style progressbar in wxPython

description: Marquee style progressbar in wxPython


code:
import platform
platform.version()
platform.system()
platform.release()
platform.win32_ver()
platform.platform()

rawDescription: Python os.name return nt on windows 7

description: Python os.name return nt on windows 7


rawDescription: run an Excel Macro from Python (but an Excel process stays in memory)

description: Run an Excel Macro from Python (but an Excel process stays in memory)


code: item ["imgurl1"] = titles.select("a/img/@src").extract()

rawDescription: Extracting elements in Scrapy to different fields


code:
def simpleSum(a=1,b=2):
    return a + b
simpleSum(**{'a':1,'b':2}) # returns 3

rawDescription: generating tuples using n-lists with itertools.product

description: Generating tuples using n-lists with itertools.product


code:
for report in MyReport.objects.raw('SELECT * FROM reporting_report GROUP by group_id'):
     print(report)

rawDescription: query.group_by in Django 1.9

description: Query.group_by in Django 1.9


code:
def divisors(num, limit):
  if isinstance(num,int) and isinstance(limit,int):
        for i in range(1,limit):
           if num%i==0:
              yield i
  else :
       yield None

list(divisors(12, 5))
list(divisors('12', 5))

rawDescription: return divisor in function of involving more than one arguments?

description: Return divisor in function of involving more than one arguments


code:
def cluster(data, maxgap):
    '''Arrange data into groups where successive elements
       differ by no more than *maxgap*

        >>> cluster([1, 6, 9, 100, 102, 105, 109, 134, 139], maxgap=10)
        [[1, 6, 9], [100, 102, 105, 109], [134, 139]]

        >>> cluster([1, 6, 9, 99, 100, 102, 105, 134, 139, 141], maxgap=10)
        [[1, 6, 9], [99, 100, 102, 105], [134, 139, 141]]

    '''
    data.sort()
    groups = [[data[0]]]
    for x in data[1:]:
        if abs(x - groups[-1][-1]) <= maxgap:
            groups[-1].append(x)
        else:
            groups.append([x])
    return groups

if __name__ == '__main__':
    import doctest
    print(doctest.testmod())

rawDescription: Grouping / clustering numbers in Python

description: Grouping / clustering numbers in Python


code:
s = pd.Series(np.random.choice(list(string.uppercase), 1000))
counts = s.value_counts()
ax = counts.iloc[:10].plot(kind="barh")
ax.invert_yaxis()

rawDescription: Sorted bar charts with pandas/matplotlib or seaborn


code:
if not '<body>Tomcat is running...</body>' in results:
   notify_us()

rawDescription: Python: using a regular expression to match one line of HTML


code:
import functools

from garlicsim.general_misc import decorator_tools

from . import base_profile

def profile_ready(condition=None, off_after=True, sort=2):
    '''
    Decorator for setting a function to be ready for profiling.

    For example:

        @profile_ready()
        def f(x, y):
            do_something_long_and_complicated()

    The advantages of this over regular `cProfile` are:

     1. It doesn't interfere with the function's return value.

     2. You can set the function to be profiled *when* you want, on the fly.

    How can you set the function to be profiled? There are a few ways:

    You can set `f.profiling_on=True` for the function to be profiled on the
    next call. It will only be profiled once, unless you set
    `f.off_after=False`, and then it will be profiled every time until you set
    `f.profiling_on=False`.

    You can also set `f.condition`. You set it to a condition function taking
    as arguments the decorated function and any arguments (positional and
    keyword) that were given to the decorated function. If the condition
    function returns `True`, profiling will be on for this function call,
    `f.condition` will be reset to `None` afterwards, and profiling will be
    turned off afterwards as well. (Unless, again, `f.off_after` is set to
    `False`.)

    `sort` is an `int` specifying which column the results will be sorted by.
    '''

    def decorator(function):

        def inner(function_, *args, **kwargs):

            if decorated_function.condition is not None:

                if decorated_function.condition is True or \
                   decorated_function.condition(
                       decorated_function.original_function,
                       *args,
                       **kwargs
                       ):

                    decorated_function.profiling_on = True

            if decorated_function.profiling_on:

                if decorated_function.off_after:
                    decorated_function.profiling_on = False
                    decorated_function.condition = None

                # This line puts it in locals, weird:
                decorated_function.original_function

                base_profile.runctx(
                    'result = '
                    'decorated_function.original_function(*args, **kwargs)',
                    globals(), locals(), sort=decorated_function.sort
                )
                return locals()['result']

            else: # decorated_function.profiling_on is False

                return decorated_function.original_function(*args, **kwargs)

        decorated_function = decorator_tools.decorator(inner, function)

        decorated_function.original_function = function
        decorated_function.profiling_on = None
        decorated_function.condition = condition
        decorated_function.off_after = off_after
        decorated_function.sort = sort

        return decorated_function

    return decorator

rawDescription: Is there a high-level profiling module for Python?


rawDescription: Writing a python function to loop out the values of each id


code:
import time

while True:
    if int(time.strftime("%H")) > 12:
        check = True

rawDescription: How to run a command in python after a certain time?

description: Run a command in python after a certain time


code:
from django.db import models

class MyModel(models.Model):
    whatever = models.Manager()

rawDescription: Understanding Django's database API and models - Poll.objects


code:
new_foo = {}
for key, (old_key, value) in enumerate( sorted( foo.items() ) ):
    key = key+1  # adjust for 1-based
    new_foo[key] = value

rawDescription: How can I populate a dictionary with an enumerated list?

description: Populate a dictionary with an enumerated list


code:
new_string = re.sub(r'\.(\d+\. )', '

\\1', old_string)

rawDescription: PYTHON REGEXP to replace recognized pattern with the pattern itself and the replacement?


code:
from PySide import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.edit = QtGui.QTextEdit(self)
        self.edit.installEventFilter(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.edit)

    def eventFilter(self, widget, event):
        if (event.type() == QtCore.QEvent.KeyPress and
            widget is self.edit):
            key = event.key()
            if key == QtCore.Qt.Key_Escape:
                print('escape')
            else:
                if key == QtCore.Qt.Key_Return:
                    self.edit.setText('return')
                elif key == QtCore.Qt.Key_Enter:
                    self.edit.setText('enter')
                return True
        return QtGui.QWidget.eventFilter(self, widget, event)

if __name__ == '__main__':

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

rawDescription: PySide keyPressEvent catching enter or return


rawDescription: How to inherit from SQLAlchemy classes and own classes

description: Inherit from SQLAlchemy classes and own classes


rawDescription: Python inserting lists into a list with given length of the list


code:
tags = Tag.objects.filter(field_name='string_or_field')
posts = Post.objects.filter(tags__in=tags)

rawDescription: How to convert a list in to queryset django

description: Convert a list in to queryset django


code:
def mock_requests_post(self, url, data=None):
    ''' Mock method for post method from responses library.
        It replaces the responses.post calls in Api class.
    '''
    url = self.encode_url(url, data)

    class classWithAttributes(object):
        content = json.dumps(self.fixtures[url])

    if url:
        return classWithAttributes()

rawDescription: Mock patch method and an attribute

description: Mock patch method and an attribute


code:
import Tkinter

root = Tkinter.Tk()
menubar = Tkinter.Menu(root)
root.config(menu=menubar)

fileMenu = Tkinter.Menu(menubar, tearoff=False)
editMenu = Tkinter.Menu(menubar, tearoff=False)

menubar.add_cascade(label="File",underline=0, menu=fileMenu)
menubar.add_cascade(label="Edit",underline=0, menu=editMenu)

fileMenu.add_command(label="Open...", underline=0)
fileMenu.add_command(label="Save", underline=0)
fileMenu.add_separator()
fileMenu.add_command(label="Exit", underline=1)

editMenu.add_command(label="Cut", underline=2)
editMenu.add_command(label="Copy", underline=0)
editMenu.add_command(label="Paste", underline=0)

root.mainloop()

rawDescription: Auto-adjusting size for Tkinter frame

description: Auto-adjusting size for Tkinter frame


code:
original_text = '<title>Kramer vs. Kramer</title>'
replacement_text = "Kramer V Kramer"
re.sub(r'(?<=<title>).+?(?=</title>)', replacement_text, original_text)

rawDescription: re.sub between two tags

description: Re.sub between two tags


code:
class PyLogger:

  def __init__(self, source):
    self.file_handle = open('Python_Log.txt', 'a')
    self.source=source
    self.buf = []

  def write(self, data):
    self.buf.append(data)
    if data.endswith('\n'):
      self.file_handle = open('Python_Log.txt', 'a')
      self.file_handle.write('\t' * indent_level)
      self.file_handle.write(self.source + "::" + ''.join(self.buf))
      self.file_handle.close()
      self.buf = []

  def __del__(self):
    if self.buf != []:
      self.file_handle = open('Python_Log.txt', 'a')
      self.file_handle.write('\t' * indent_level)
      self.file_handle.write(self.source + "::" + ''.join(self.buf) + '\n')
      self.file_handle.close()
    self.file_handle.close()

import sys
sys.stdout = PyLogger('stdout')
sys.stderr = PyLogger('stderr')

rawDescription: Python - Print on stdout on a "terminal"


code:
parser = argparse.ArgumentParser()
parser.add_argument("--foo", action='store_true', help="Foos something. Must use --bar if --foo is used.")
parser.add_argument("--bar", action='store_true', help="Bars something.")

parsed_args = parser.parse_args()

if parsed_args.foo and not parsed_args.bar:
    sys.stderr.write("ERROR: Must use --bar if using --foo\n")
    parser.print_help()
    sys.exit(1)

rawDescription: Python2.7 argparse require none or both options


code:
import cStringIO
import sys

def getPrint(thefun, *a, **k):
  savstdout = sys.stdout
  sys.stdout = cStringIO.StringIO()
  try:
    thefun(*a, **k)
  finally:
    v = sys.stdout.getvalue()
    sys.stdout = savstdout
  return v

rawDescription: Python Encapsulate a function to Print to a variable


code:
button1 = '''
BoxLayout:
    Button:
        text: 'Check In'
        size_hint: None, None
        pos_hint: {'center_x': .5, 'center_y': .5}
        canvas.before:
            PushMatrix
            Rotate:
                angle: 0
                origin: self.center
        canvas.after:
            PopMatrix
    Button:
            text: 'SOS'
            size_hint: None, None
            pos_hint: {'center_x': 1.5, 'center_y': 1.5}
            canvas.before:
                PushMatrix
                Rotate:
                    angle: 45
                    origin: self.center
            canvas.after:
                PopMatrix

'''

rawDescription: Kivy Not showing two buttons

description: Kivy Not showing two buttons


code:
class UserObjectsOnlyAuthorization(Authorization):

    def read_list(self, object_list, bundle):
        # This assumes a ``QuerySet`` from ``ModelResource``.
        return object_list.filter(user=bundle.request.user)

    def read_detail(self, object_list, bundle):
        # Is the requested object owned by the user?
        return bundle.obj.user == bundle.request.user

    # DON'T FORGET TO IMPLEMENT METHODS FOR CREATE/UPDATE/DELETE as shown in the docs.

rawDescription: In Tastypie, what is the right way to override Resource.is_authorized() to implement row-level permissions


code:
import re

with open("temp.html") as html_file:
    html = html_file.read()

tags = re.findall(r"<MYTAG>.*</MYTAG>\n*", html)

html = re.sub(r"<MYTAG>.*</MYTAG>\n*", "", html)

footer = re.split(r"<footer>", html)

tags.insert(0, "<footer>\n")
tags.insert(0, footer[0])
tags.append(footer[1])

with open("temp.html", "w") as html_file:
    html_file.write("".join(tags))

rawDescription: NPP + Python: Move Text between search strings to Another Position (Footer)


code:
t = plt.text(0.5, 0.5, 'text', transform=ax.transAxes, fontsize=30)
t.set_bbox(dict(color='red', alpha=0.5, edgecolor='red'))

rawDescription: Adjusting Text background transparency

description: Adjusting Text background transparency


code:
df = DataFrame(Y)
df[1] = df[0].diff() > 600000000000.0 #nanoseconds in ten minutes
df[1] = df[1].apply(lambda x: 1 if x else 0).cumsum()
df.groupby(1)

rawDescription: Split a series on time gaps in pandas?

description: Split a series on time gaps in pandas


code:
class LoginManager(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        user = users.get_current_user()
        if user is not None:
            marker = Session.get(user.user_id())
            if marker is None:
                login_action()
                Session.set(user.user_id(), "true")

rawDescription: Google Apps Engine / Django, calling action upon user login?


code:
import httplib2

from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

# Email of the Service Account.
SERVICE_ACCOUNT_EMAIL = '<some-id>@developer.gserviceaccount.com'

# Path to the Service Account's Private Key file.
SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/to/<public_key_fingerprint>-privatekey.p12'

def createAnalyticsService():
  f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
  key = f.read()
  f.close()

  credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,
      scope='https://www.googleapis.com/auth/analytics.readonly')
  http = httplib2.Http()
  http = credentials.authorize(http)

  return build('analytics', 'v3', http=http)

rawDescription: How to get a list of most popular pages from Google Analytics in Python (Django)?

description: Get a list of most popular pages from Google Analytics in Python (Django)


code:
numero = str(input("Digite um numero de quatro digitos"));

y = len(numero)

for i in range (y):
    ai = numero [y]

rawDescription: Broken "String" into a variable in Python


rawDescription: Python & Matplot: How can I draw a simple shape by points?


code:
cache = tempfile.NamedTemporaryFile()
...

cache.seek(0)
cache.writelines(bytes(line, 'UTF-8') for line in content)

cache.seek(0)
webbrowser.open_new_tab('file://' + cache.name)

rawDescription: How to implement the 'tempfile' module to this code

description: Implement the 'tempfile' module to this code


code:
def my_min(d1,d2,d3,d4):
    lst = [d1,d2,d3,d4]
    return min([x for x in lst if x !=0])

rawDescription: Rejecting zero values when creating a list of minimum values. (Python Field Calc)


code:
import math

def distance_matrix(pattern):
    # to get the side length, solve for n where len(pattern) = n*(n + 1)/2 (triangular number formula)
    side_length = (int(math.sqrt(1 + 8 * len(pattern))) - 1) / 2 + 1
    assert (side_length * (side_length - 1)) // 2 == len(pattern), "Pattern length must be a triangular number."

    # create the grid
    grid = [[0] * side_length for i in range(side_length)]

    # fill in the grid
    position = 0
    for i in range(0, side_length - 1):
        for j in range(0, side_length - 1 - i):
            element = pattern[position]; position += 1
            grid[i][i + j + 1] = element # fill in the upper triangle
            grid[i + j + 1][i] = element # fill in the lower triangle

    return grid

def matrix_to_string(matrix): return "\n".join("\t".join(str(x) for x in row) for row in distance_matrix([1, 2, 4, 3, 5, 6]))

if __name__ == "__main__":
    print(matrix_to_string(distance_matrix([1, 2, 4, 3, 5, 6])))

rawDescription: Python: How to create a complete distance matrix from a row of values?


rawDescription: Parsing Information from redirect URL

description: Parsing Information from redirect URL


code:
import random

ref = []

for image in images:
    n = random.randint(0, 3), random.randint(0, 3)
    while n not in ref:
        n = random.randint(0, 3), random.randint(0, 3)
    ref.append(n)
    image.grid(row=n[0], column=n[1])

rawDescription: How to arrange pictures randomly in a table with tkinter?

description: Arrange pictures randomly in a table with tkinter


code:
from math import floor

def build_rfc3339_phrase(datetime_obj):
    datetime_phrase = datetime_obj.strftime('%Y-%m-%dT%H:%M:%S')
    us = datetime_obj.strftime('%f')

    seconds = datetime_obj.utcoffset().total_seconds()

    if seconds is None:
        datetime_phrase += 'Z'
    else:
        # Append: decimal, 6-digit uS, -/+, hours, minutes
        datetime_phrase += ('.%.6s%s%02d:%02d' % (
                            us,
                            ('-' if seconds < 0 else '+'),
                            abs(int(floor(seconds / 3600))),
                            abs(seconds % 3600)
                            ))

    return datetime_phrase

rawDescription: Python and RFC 3339 timestamps

description: Python and RFC 3339 timestamps


code:
import sys

def stdout(message):
    sys.stdout.write(message)
    sys.stdout.write('\b' * len(message))   # \b: non-deleting backspace

def demo():
    stdout('Right'.rjust(50))
    stdout('Left')
    sys.stdout.flush()
    print()

demo()

rawDescription: Allign left and right in python?

description: Allign left and right in python


code:
from django.test.runner import DiscoverRunner
from djcelery.contrib.test_runner import _set_eager

class CeleryDiscoverRunner(DiscoverRunner):
    def setup_test_environment(self, **kwargs):
        _set_eager()
        super(CeleryDiscoverRunner, self).setup_test_environment(**kwargs)

rawDescription: Django Celery test runner doing very strange things


code:
import Tkinter as tk

class App(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        go_button = tk.Button(text="Go!", command=self.go)
        go_button.pack()

    def go(self):
        self.dialog = ProgressWindow(self)
        self.do_real_work(0)

    def do_real_work(self, count):
        # simulate doing work; update the status window periodically
        self.dialog.set(count)
        self.after(500, lambda count=count+10: self.do_real_work(count))

class ProgressWindow(tk.Toplevel):
    def __init__(self, *args, **kwargs):
        tk.Toplevel.__init__(self, *args, **kwargs)
        self.label = tk.Label(self, text="0%")
        self.label.pack(side="top", fill="both", expand=True)
        self.wm_geometry("200x200")

    def set(self, value):
        if value > 100:
            self.destroy()
        else:
            self.label.configure(text="%s %%" % value)

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

rawDescription: How to create a self-destroying child window to monitor an activity?

description: Create a self-destroying child window to monitor an activity


code:
res = []
conversion = {}
i = 0
for x in l:
    if x not in conversion:
        value = conversion[x] = i
        i += 1
    else:
        value = conversion[x]
    res.append(value)

rawDescription: Indexing a list with an unique index

description: Indexing a list with an unique index


code:
import sys
current_module = sys.modules[__name__]

rawDescription: Python: How do I get a reference to a module inside the module itself?


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

nonnans = -np.isnan(f1)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(t[nonnans], f1[nonnans])

rawDescription: Pandas: Pivoting and plotting workflow

description: Pandas: Pivoting and plotting workflow


code:
class MySpider(Spider):
    mapping = [(1, 'my_url1'), (2, 'my_url2')]

    ...

    def start_requests(self):
        for id, url in self.mapping:
            yield Request(url, callback=self.parse_page, meta={'id': id})

    def parse_page(self, response):
        id = response.meta['id']

rawDescription: Pass extra values along with urls to scrapy spider


code:
def clickButton():
    widget = root.focus_get()
    if widget != root:
        widget.invoke()

root = Tkinter.Tk()
root.bind("<Return>", clickButton)
root.mainloop()

rawDescription: How do I bind '<Return>' to focused (tabbed) button in tkinter?

description: Bind '<Return>' to focused (tabbed) button in tkinter


code:
list1 = ["they" , "are" ,"really" , "angry"]
list2 = ["they" , "are" ,"seriously" , "angry"]
list3 = zip(list1, list2)
list3

rawDescription: Joining 2 lists ,Python

description: Joining 2 lists ,Python


code:
from scrapy.selector import HtmlXPathSelector
from scrapy.spider import BaseSpider
from scrapy.http import Request
from myproject.items import MyItem

class StackOverflow(BaseSpider):
    name = 'stackoverflow.com'
    allowed_domains = ['stackoverflow.com']
    start_urls = ['http://stackoverflow.com/questions']

    def parse(self, response):
        hxs = HtmlXPathSelector(response)

        for question in hxs.select('//question-xpath'):
            question_url = question.select('./question-url')
            answer_count = question.select('./answer-count-xpath')
            # you'll have to write the xpaths and db logic yourself
            if get_db_answer_count(question_url) != answer_count[0]:
                yield Request(question_url, callback = self.parse_question)

    def parse_question(self, response):
        insert_question_and_answers_into_db
        pass

rawDescription: how to crawl webpages base on the info on the index page

description: Crawl webpages base on the info on the index page


code:
from wand.image import Image
from wand.drawing import Drawing
from wand.color import Color

with Drawing() as draw:
    draw.fill_color = Color('#00ff00')
    draw.color(x,y,'replace')
    with Image(filename='image.jpg') as img:
        draw(img)
        img.save(filename='new_image.jpg')

rawDescription: Change color of specific pixels [Wand]

description: Change color of specific pixels [Wand]


rawDescription: Python regex url grab

description: Python regex url grab


code: table_lens = [len(table.xpath('tr')) for table in tables]

rawDescription: How can I grab the rows from a specific table using an XPATH expression - mine seems to grab all the rows in the document

description: Grab the rows from a specific table using an XPATH expression - mine seems to grab all the rows in the document


code:
class FooV2(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    # c and d and stuff

def retrieve_data():
    conn = sqlite3.connect('/foodata')
    cursor = conn.cursor()
    cursor.execute('SELECT a, b FROM foos')
    for row in cursor.fetchall():
        foo = FooV2(*row)
        print(foo.a, foo.b)

rawDescription: Subclassing namedtuple with properties

description: Subclassing namedtuple with properties


rawDescription: format string python

description: Format string python


code:
import wx

class Frame1(wx.Frame):
    def __init__(self, *args, **kwds):
        wx.Frame.__init__(self, *args, **kwds)
        self.panel1 = wx.Panel(self, wx.ID_ANY)
        img = wx.EmptyImage(100, 100)
        self.imgctrl = wx.StaticBitmap(self.panel1, wx.ID_ANY, wx.BitmapFromImage(img))
        self.st = wx.StaticLine(self.panel1, wx.ID_ANY, style=wx.LI_VERTICAL)
        self.but = wx.Button(self.panel1, wx.ID_ANY, 'OK')
        self.hbox = wx.BoxSizer(wx.HORIZONTAL)
        self.hbox.Add(self.imgctrl, 0, wx.ALL, 5)
        self.hbox.Add(self.st, 0, wx.ALL | wx.EXPAND, 5)
        self.hbox.Add(self.but, 1, wx.ALL, 5)
        self.panel1.SetSizer(self.hbox)
        self.hbox.Fit(self.panel1)

if __name__ == '__main__':
    app = wx.App(False)
    frame_1 = Frame1(None)
    frame_1.Show()
    app.MainLoop()

rawDescription: WxPython StaticLine after Image in BoxSizer


code:
# setup a figure
fig, (ax1, ax2) = plt.subplots(2)

# generate some random data
data = np.random.rand(100)

# plot undesired way
ax1.plot(data)

# change the tick positions and labels ...
ax2.plot(data)

# ... to one label every 12th value
xticks = np.arange(0,100,12)

# ... start counting in the year 2000
xlabels = range(2000, 2000+len(xticks))

ax2.set_xticks(xticks)
ax2.set_xticklabels(xlabels)

plt.show()

rawDescription: X labels matplotlib

description: X labels matplotlib


code:
class IndexView(generic.ListView):
   template_name = 'items/index.html'
   context_object_name = 'popular_items_list'

   def get_queryset(self):
     return Item.objects.order_by('-rating')[:5]

   def get_context_data(self, *args, **kwargs):
       context = super(IndexView, self).get_context_data(*args, **kwargs)
       context['moreItems'] = Item.objects.order_by('pub_date')[:5]
       return context

rawDescription: How to display multiple views in a Django template?

description: Display multiple views in a Django template


code:
def main():
    global Output
    Output = rgb_to_s(red, green, blue)

def rgb_to_s(r, g, b):
    # if you have 0-255 rgb values:
    r = float(r)/255
    g = float(g)/255
    b = float(b)/255

    cmax = max(r, g, b)
    cmin = min(r, g, b)
    l = (cmax + cmin)/2
    d = cmax - cmin

    return d/(1-abs(2*l - 1))

rawDescription: Simplest way of converting RGB to Saturation


code:
from tkinter import *

class Game:
    def __init__(self):
        #creating the static canvas background
        self.window = Tk()
        self.window.title('Shoot your friends')
        self.canvas = Canvas(width= 900,
                          height= 700,
                          cursor= 'circle')
        self.canvas.pack()

        self.canvas.create_line(450, 900,
                           450, 0,
                           dash = (10))

        self.p1_ship = PhotoImage(file = "rd.gif")
        self.p2_ship = PhotoImage(file = "rd.gif")
        self.p1_laser = PhotoImage(file = "rd.gif")
        self.p2_laser = PhotoImage(file = "rd.gif")

        #Buttons at the bottom
        self.frame = Frame(self.window)
        self.frame.pack()

        #Determining the state of edge teleporting and toggling it
        self.etb = True
        def et():
            if self.etb == True:
                self.etb = False
                Et["text"] = "Turn On Edge Teleporting"
            else:
                self.etb = True
                Et["text"] = "Turn Off Edge Teleporting"

            print ("Edge Telepoting Toggled")

        Et = Button(self.frame, text="Turn Off Edge Teleporting", command = et, cursor= 'double_arrow')
        Et.grid(row=0,column=0)

        self.Rfb = False
        def rf():
            if self.Rfb == True:
                self.Rfb = False
                Rf["text"] = "Turn On Rapid Fire "
            else:
                self.Rfb = True
                Rf["text"] = "Turn Off Rapid Fire"

            print ("Rapid Fire Toggled")

        Rf = Button(self.frame, text="Turn On Rapid Fire", command = rf, cursor= 'cross')
        Rf.grid(row=0,column=1)

        def restart():
            print ('restart')
        restart_b = Button(self.frame, text="Restart Game", command = restart, fg='Blue', bg= 'red', cursor='exchange' )
        restart_b.grid(row=0,column=2)

        self.y_p1 = 400
        self.y_p2 = 400

        self.ship_p1 = self.canvas.create_image(40, 450, image=self.p1_ship)
        self.ship_p2 = self.canvas.create_image(860, 450, image=self.p2_ship)

        self.canvas.move(self.ship_p1,0,0)
        self.canvas.move(self.ship_p2,0,0)

        #For example If edge teleporting is ON the ship will teleport to the top of the screen if it is at the bottom and the down key is pressed and vice versa
        #My implementation of this may not be the most efficient but I like the options it gives me for adding future features and it looks cool.
        def p1_up(event):
            if self.etb == True and self.y_p1 >= 100:
                self.canvas.move(self.ship_p1,0,-100)
                self.y_p1 += -100
            elif self.etb == True:
                self.canvas.move(self.ship_p1,0,+800)
                self.y_p1 += +800
            elif self.y_p1 >= 100:
                self.canvas.move(self.ship_p1,0,-100)
                self.y_p1 += -100

        def p1_down(event):
            if self.etb == True and self.y_p1 <= 799:
                self.canvas.move(self.ship_p1,0,+100)
                self.y_p1 += 100
            elif self.etb == True:
                self.canvas.move(self.ship_p1,0,-800)
                self.y_p1 += -800
            elif self.y_p1 <= 799:
                self.canvas.move(self.ship_p1,0,+100)
                self.y_p1 += 100

        def p2_up(event):
            if self.etb == True and self.y_p2 >= 100:
                self.canvas.move(self.ship_p2,0,-100)
                self.y_p2 += -100
            elif self.etb == True:
                self.canvas.move(self.ship_p2,0,+800)
                self.y_p2 += +800
            elif self.y_p2 >= 100:
                self.canvas.move(self.ship_p2,0,-100)
                self.y_p2 += -100

        def p2_down(event):
            if self.etb == True and self.y_p2 <= 799:
                self.canvas.move(self.ship_p2,0,+100)
                self.y_p2 += 100
            elif self.etb == True:
                self.canvas.move(self.ship_p2,0,-800)
                self.y_p2 += -800
            elif self.y_p2 <= 799:
                self.canvas.move(self.ship_p2,0,+100)
                self.y_p2 += 100

        # Functions for shooting

        self.p1_shot_out = False
        self.p2_shot_out = False

        def p1_shoot(event):

            if self.p1_shot_out == True:
                self.canvas.delete(self.laser_p1)
            #draws the laser
            self.laser_p1 = self.canvas.create_image(50, self.y_p1 +50, image=self.p1_laser)
            self.x_p1_laser = 50
            self.p1_shot_out = True

            self.window.after(1, p1_shoot_move)

        def p1_shoot_move():
            #moves the laser until its outside the canvas
            if self.x_p1_laser >= 930:
                pass
            else:
                self.canvas.move(self.laser_p1,5,0)
                self.x_p1_laser += 5
                self.canvas.update()
                self.window.after(1, p1_shoot_move)

        def p2_shoot(event):
            if self.p2_shot_out == True:
                self.canvas.delete(self.laser_p2)
            #draws the laser
            self.laser_p2 = self.canvas.create_image(750, self.y_p2 +50, image=self.p2_laser)
            self.x_p2_laser = 750
            self.p2_shot_out = True

            self.window.after(1, p2_shoot_move)

        def p2_shoot_move():
            #moves the laser until its outside the canvas
            if self.x_p2_laser <= -110:
                pass
            else:
                self.canvas.move(self.laser_p2,-5,0)
                self.x_p2_laser += -5
                self.canvas.update()
                self.window.after(1, p2_shoot_move)

        # Key bindings that trigger their respective functions
        self.canvas.bind('w', p1_up)
        self.canvas.bind('s', p1_down)
        self.canvas.bind('<Up>', p2_up)
        self.canvas.bind('<Down>', p2_down)
        self.canvas.bind('<space>', p1_shoot)
        self.canvas.bind('<Control_R>', p2_shoot)

        self.canvas.focus_set()

Game()

rawDescription: Moving two objects on a canvas in separate loops


code:
import re

if re.search("who\s.*are\s.*you","who the heck are you"):
    print("I AM JOE")

rawDescription: Test for multiple strings in a certain order


code:
y = [lambda : x for x in range(3)]
y[0]()
x = 88
y[0]()
x = [lambda : x for x in range(3)]
y = x
y[0]()
x = 88
y[0]()

rawDescription: Why do these two 'x' refer to different variable?


code:
class Product(models.Model):
    name    = models.CharField(max_length = 100)
    base_price = models.DecimalField(max_digits = 5, decimal_places = 2)

    def __unicode__(self):
        return self.name

class Country(models.Model):
    name = models.CharField(max_length = 2)
    base_price = models.DecimalField(max_digits = 5, decimal_places = 2)
    products = models.ManyToManyField(Product, through = 'CountryProduct')

    def __unicode__(self):
        return self.name

class CountryProduct(models.Model):
    country = models.ForeignKey(Country)
    product = models.ForeignKey(Product)
    overriden_price = models.DecimalField(max_digits = 5, decimal_places = 2)

    class Meta:
        unique_together = (("country", "product"),)

class CountryProductInline(admin.TabularInline):
    model = CountryProduct

class CountryAdmin(admin.ModelAdmin):
    inlines = [CountryProductInline]

class ProductAdmin(admin.ModelAdmin):
    inlines = [CountryProductInline]

rawDescription: Better way to represent Many to many relationship in django admin


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

Base = declarative_base()

class Person(Base):
    __tablename__ = 'person'
    id      = Column(Integer, primary_key=True)
    name    = Column(String(50))

class SexyParty(Base):
    __tablename__ = 'sexy_party'
    id      = Column(Integer, primary_key=True)
    guests  = relationship('Person', secondary='guest_association',
                        lazy='dynamic', backref='parties')

guest_association = Table(
    'guest_association', Base.metadata,
    Column('user_id',       Integer(), ForeignKey('person.id'), primary_key=True),
    Column('sexyparty_id',  Integer(), ForeignKey('sexy_party.id'), primary_key=True)
)

e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)

sess = Session(e)

p1 = Person(id=1, name='p1')
p2 = Person(id=2, name='p2')
p3 = Person(id=3, name='p3')
p4 = Person(id=4, name='p4')

sp1 = SexyParty(id=1)

sess.add_all([sp1, p1, p2, p3, p4])
sess.commit()

# method one.  use insert()
sess.execute(guest_association.insert().values([(1, 1), (2, 1)]))

# method two.  map, optional association proxy
from sqlalchemy.ext.associationproxy import association_proxy

class GuestAssociation(Base):
    __table__ = guest_association
    party = relationship("SexyParty", backref="association_recs")

SexyParty.association_ids = association_proxy(
                    "association_recs", "user_id",
                    creator=lambda uid: GuestAssociation(user_id=uid))

sp1.association_ids.extend([3, 4])
sess.commit()

rawDescription: Populating a SQLAlchemy many-to-many relationship using ID's instead of objects


code:
import urllib2
import MultipartPostHandler

params = {'file':open( "FILENAME.JPG" , 'rb')}
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
urllib2.install_opener(opener)
req = urllib2.Request( "PROCESS.PHP" , params)
text_response = urllib2.urlopen(req).read().strip()

rawDescription: How to upload photos to a image hosting server programmatically?

description: Upload photos to a image hosting server programmatically


code:
response = FileResponse('/some/path/to/a/file.txt')
response.headers['Content-Disposition'] = ...

rawDescription: How can I serve temporary files from Python Pyramid

description: Serve temporary files from Python Pyramid


code: """ssh -t kity@{0} 'sudo nohup bash -c "./tcp_sender > /dev/null 2>&1 &"'""".format(ip_address)

rawDescription: single quotes and double quotes in python strings

description: Single quotes and double quotes in python strings


code: pd.date_range((Timestamp('20141231') +pd.DateOffset(months=-11)), periods=12, freq='MS')

rawDescription: Pandas generate date range of Beginning Month


code:
a = 'ZENOVW'
''.join(sorted(a))

rawDescription: How to sort the letters in a string alphabetically in Python

description: Sort the letters in a string alphabetically in Python


code:
d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
genexp = ((k, d[k]) for k in sorted(d, key=d.get, reverse=True))
for k, v in genexp:
    k, v

rawDescription: Python 3 sort a dict by its values

description: Python 3 sort a dict by its values


code:
class Mixin(object):

    def f1(self):
        return self._Z.f1()

    def f2(self):
        return self._Z.f2()

class A2(A, Mixin):

    def __init__(self):
        A.__init__(self)
        self._Z = Z('high')

class B2(B, Mixin):
    def __init__(self):
        B.__init__(self)
        self._Z = Z('low')

rawDescription: python - refactoring - generalizing derived classes

description: Python - refactoring - generalizing derived classes


rawDescription: Is there a limit in Gensim's Doc2Vec most_similar documents result set?


code:
days = days_hours//100

hours = days_hours % 100

rawDescription: How to slice a pandas.Series of type int by length

description: Slice a pandas.Series of type int by length


code:
try:
    return self.model.objects.create_user(
        mobile=mobile,
        password=password,
    )
except IntegrityError:
    return self.model.objects.get(mobile=mobile)

rawDescription: How to stop Celery creating duplicated users in this task?

description: Stop Celery creating duplicated users in this task


code:
import pandas as pd
prediction = pd.read_csv('/Users/username/Documents/fichieretudebis.csv', delimiter= ';')

rawDescription: How to convert a .csv file into a numpy array of different type

description: Convert a .csv file into a numpy array of different type


code:
def my_func(pattern=None):
    query = session.query(Foo)

    if pattern is not None:
        query = query.filter(Foo.Bar.like(pattern))

    return query

rawDescription: Like Operator in SQLAlchemy default to wildcard


code: max(a_list, key=operator.itemgetter(1))

rawDescription: Pythonic way to get the largest item in a list


code:
from PyQt4 import QtCore, QtGui
import sys

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):
        self.fname_graph_file = ''
        file_btn = QtGui.QPushButton('Select File', self)
        file_btn.setGeometry(100, 100, 150, 30)
        file_btn.clicked.connect(self.get_graph_file)

        graphing_btn = QtGui.QPushButton('Plot Graph', self)

        plot = Plotting_Graph()
        graphing_btn.clicked.connect(lambda: plot.PlottingGraph(self.fname_graph_file))

        self.show()

    def get_graph_file(self):

        self.fname_graph_file = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '/home', 'excel files (*.xlsx)')

class Plotting_Graph(Example):

    def __init__(self):
        pass

    def PlottingGraph(self, fname_graphfile):

        print(fname_graphfile)
        # xl = ef(fname_graphfile[0])

app =  QtGui.QApplication([])
a = Example()
app.exec_()

rawDescription: Python QtGui: inheritance of variables between classes


code:
from datetime import datetime
datetime.strptime('30DEC05', '%d%b%y')

rawDescription: Python: Parse string "30DEC05" to datetime


rawDescription: Python: adding two dicts together

description: Python: adding two dicts together


code:
N['dog']
N['dog'].getSenses()

rawDescription: How can I match words regardless of tense or form?

description: Match words regardless of tense or form


code:
from selenium import webdriver

browser = webdriver.Firefox()
browser.get('https://jobs.theguardian.com/searchjobs/?LocationId=1500&keywords=personal+assistant&radialtown=London+(Central)%2c+London+(Greater)&countrycode=GB')

elem = browser.find_elements_by_class_name('lister__header')

with open('C:\\Users\\sk\\PycharmProjects\\test\\test_email.txt', "a") as f:
    for el in elem:
       f.write(el.text+"\n")

rawDescription: Python: Pack variable result as text to append it to a text file


code:
def closeEvent(self, event):

    quit_msg = "Are you sure you want to exit the program?"
    reply = QtGui.QMessageBox.question(self, 'Message',
                     quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)

    if reply == QtGui.QMessageBox.Yes:
        event.accept()
    else:
        event.ignore()

rawDescription: Prompt on exit in PyQt application

description: Prompt on exit in PyQt application


code:
class Foo: pass
dir(Foo)
class Bar(object): pass
dir(Bar)

rawDescription: What does the object declaration mean in a python class, and should I use it?


code:
def split_by_lines(text_generator):
    last_line = ""
    try:
        while True:
             chunk = "".join(last_line, next(text_generator))
             chunk_by_line = chunk.split('\n')
             last_line = chunk_by_line.pop()
             for line in chunk_by_line:
                 yield line
    except StopIteration: # the other end of the pipe is empty
        yield last_line
        raise StopIteration

rawDescription: Is there a generator that will turn a stream of text into a stream of lines?


code:
with open("myfile.csv") as input_file:
   with open("output.csv", "wt") as output:
      output.write(input_file.readline())
      for line in input_file:
           parts = line.split('""')
           id = parts.split('"')[-1]
           output.write(parts[0] + id + parts[2])

rawDescription: Replacing the content of a column in python


code:
import pandas as pd
data_xls = pd.read_excel('export.csv', 'Sheet1', index_col=None)
data_xls.to_csv('exceltocsv.csv', encoding='utf-8')

rawDescription: How to open file and save as csv

description: Open file and save as csv


code:
import os, time, sys

class SingleInstance:
    def __init__(self, filename):
        self.lockfile = filename

        try:
            # file already exists, we try to remove (in case previous execution was interrupted)
            if os.path.exists(self.lockfile):
                os.unlink(self.lockfile)

            self.fd =  os.open(self.lockfile, os.O_CREAT|os.O_EXCL|os.O_RDWR)

        except OSError as e:
            if e.errno == 13:
                print("Another instance is already running, quitting.")
                #sys.exit(-1)

            print(e.errno)
            raise

        except Exception as x:
            print(x)

    def __del__(self):
        import sys

        if hasattr(self, 'fd'):
            os.close(self.fd)
            os.unlink(self.lockfile)

rawDescription: Python check if another python application is running


code:
if all(i == 0 for i in seq[1:4]):  # for elements with indices between 1 and 4
    pass  # do something

if any(s.startswith('a') for a in str_list[1:2:35]):  # for elements with indices 1, 3, 5 etc. up to 35
    pass  # do something
# etc...

rawDescription: Is it possible to specify a range of array elements in Python to check against a criteria?


code:
def is_power(a,b):
    if(a%b != 0):
        return False
    elif(a/b == 1):
        return True
    else:
        return is_power(a/b,b)

rawDescription: Python Recursion Exercise

description: Python Recursion Exercise


code: LEN(REPLACE(the_string, CHAR(13), ''))

rawDescription: Why is the length of a string returned by SQL different from that returned by other languages?


code:
def noop(x): pass

[noop(i) for i in range(5)]

rawDescription: python list comprehension VS for behaviour

description: Python list comprehension VS for behaviour


code:
url = "http://www.so.com"
if url[-1]!='/':
 url+='/'

url

rawDescription: Ensure a trailing character is included as a string in Python


code: fb(method='stream_publish', args={'session_key': settings.FACEBOOK_SESSION, 'uid':PAGE_ID, 'target_id': 'NULL', 'message':'MESSAGE_HERE'})

rawDescription: PyFacebook: Facebook() instance has no stream methods


code:
from threading import Event,Thread

class FakeClass(object):
    def __init__(self):
        self.progress = Gtk.ProgressBar()
        self.progress.set_show_text(True)
        self.buttonOk = Gtk.Button("Start Count")
        self.buttonOk.connect("clicked", self.clickOk)
        self.buttonCancel = Gtk.Button("Cancel Count")
        self.buttonCancel.connect("clicked", self.clickCancel)

        #create an event to trigger in your thread
        self.trigger = Event()
        self.t = None

        #Other GTK stuff here...

    def tread_function(self):
        progress_fraction = 0.0

        #keep looping while the trigger is not set and the
        #progress is not > 1.0
        while not self.trigger.is_set() and progress <= 1.0:
            progress.set_fraction(progress_fraction)
            time.sleep(1)
            progress_fraction += 0.1

    def clickOk(self, *args):
        # reset the trigger
        self.trigger.clear()
        #launch the thread
        self.t = threading.Thread(target=self.tread_function)
        self.t.start()

    def clickCancel(self, *args):
        # set the trigger (interrupting the thread)
        self.trigger.set()
        # join the thread so it is not left hanging
        if not self.t is None:
            self.t.join()

    # More other GTK stuff here...

rawDescription: How to implement the abolition of actions?

description: Implement the abolition of actions


code:
from scrapy.item import Item, Field
class MyItem(Item):
    attr1 = Field()
    attr2 = Field()
    # ...
    attrN = Field()

    def __repr__(self):
        """only print out attr1 after exiting the Pipeline"""
        return repr({"attr1": self.attr1})

rawDescription: suppress Scrapy Item printed in logs after pipeline

description: Suppress Scrapy Item printed in logs after pipeline


code:
import glob
for fn in glob.glob('pid*'):
    with open(fn) as f:
        if 'done' in f.read():
            ...

rawDescription: How execute cat filename* in python

description: How execute cat filename* in python


code:
class DeletionMixin(object):
    """
    A mixin providing the ability to delete objects
    """
    success_url = None

    def delete(self, request, *args, **kwargs):
        """
        Calls the delete() method on the fetched object and then
        redirects to the success URL.
        """
        self.object = self.get_object()
        self.object.delete()
        return HttpResponseRedirect(self.get_success_url())

    # Add support for browsers which only accept GET and POST for now.
    def post(self, *args, **kwargs):
        return self.delete(*args, **kwargs)

    def get_success_url(self):
        if self.success_url:
            return self.success_url
        else:
            raise ImproperlyConfigured(
                "No URL to redirect to. Provide a success_url.")

rawDescription: How does Django delete the object from a view?


code:
from operator import itemgetter
sorted(tuples, key=itemgetter(2,0))

rawDescription: Sorting a Python list by third element, then by first element, etc?


code:
doc_child = getChildOfDocument() # pseudo
rect = doc_child.geometry()

mappedPoint = doc_child.mapToParent(rect.topleft())
# alternative #
# mappedPoint = doc_child.mapTo(mydocumentwidget, rect.topleft())

mappedRect = QtCore.QRect(mappedPoint, rect.size())
intersection = rubberband.geometry().intersected(mappedRect)

rawDescription: How to get the intersection of geometry of two QWidgets with different parents?

description: Get the intersection of geometry of two QWidgets with different parents


code:
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from scipy.signal import convolve2d

def Gaussian_filter(gamma, N):
    Amp = 1 / (2*np.pi*gamma**2)
    x = np.arange(-N,N,0.5)
    y = np.arange(-N,N,0.5)
    [x,y] = np.meshgrid(x,y)
    g = Amp * np.exp(-(x**2 + y **2)/(2*gamma**2))
    return g

if __name__ == "__main__":
    im = Image.open(r"C:\Users\eladj\Desktop\lena.jpg")
    arr = np.array(im, dtype=np.float32)

    sigma = 1
    N = 5

    gaus = Gaussian_filter(sigma,5)
    im_blurred = convolve2d(arr, gaus, mode='same')
    im_DoG = arr - im_blurred

    plt.figure(1)
    plt.subplot(1,4,1)
    plt.imshow(arr, cmap='gray')
    plt.colorbar(fraction=0.046)
    plt.xticks([]), plt.yticks([])
    plt.subplot(1,4,2)
    plt.imshow(gaus, cmap='gray')
    plt.colorbar(fraction=0.046)
    plt.xticks([]), plt.yticks([])
    plt.subplot(1,4,3)
    plt.imshow(im_blurred, cmap='gray')
    plt.colorbar(fraction=0.046)
    plt.xticks([]), plt.yticks([])
    plt.subplot(1,4,4)
    plt.imshow(im_DoG, cmap='gray')
    plt.colorbar(fraction=0.046)
    plt.xticks([]), plt.yticks([])

rawDescription: Guassian image filtering plots with low stdev. values


code:
def __configureMenuBar(self):
    self.menuBar = self.menuBar()
    self.menuBar.setLayoutDirection(Qt.LeftToRight)
    filemenu = QMenu('File', self)
    self.menuBar.addMenu(filemenu)
    filemenu.addAction('Open')
    filemenu.addAction('Quit', self.close)

rawDescription: QMenuBar missing from QMainWindow on Windows 8.1


code:
a = [7,6,5,4,3,2,1]
b = []
c = []

dd = {'a':a, 'b':b, 'c':c}

def guess2(frompeg, topeg):
    if dd[frompeg] != []:
       temp = dd[frompeg].pop()
    else:
        print('Error Popping', frompeg)
        return

    if dd[topeg] == []:
        dd[topeg].append(temp)
    elif temp < dd[topeg][-1]:
        dd[topeg].append(temp)
    else:
        dd[frompeg].append(temp) # put it back
        print('Error')

rawDescription: Towers of Hanoi, how can I refine my function?


code:
import web
import serial

urls = ("/(.*)", "test"
       )

web.config.debug = True

if(web.config.debug):
    #in debug mode, make sure that global serial instance is only created at start up
    if not hasattr(serObj, "_email"):
        serObj = serial.Serial(0, 9600, parity=serial.PARITY_NONE)
        web._serObj = serObj
    else:
        serObj = web._serObj

class test:
    def GET(self):
        return "Test"

    def POST(self):
        pass

if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()

rawDescription: web.py: avoid global instances?

description: Web.py: avoid global instances


code:
from collections import OrderedDict

from bokeh._legacy_charts import Step, show, output_file

xyvalues = OrderedDict(
    python=[2, 3, 7, 5, 26, 81, 44, 93, 94, 105, 66, 67, 90, 83],
    pypy=[12, 20, 47, 15, 126, 121, 144, 333, 354, 225, 276, 287, 270, 230],
    jython=[22, 43, 70, 75, 76, 101, 114, 123, 194, 215, 201, 227, 139, 160],
)

output_file("steps.html", title="line.py example")

chart = Step(xyvalues, title="Steps", ylabel='measures', legend='top_left')

show(chart)

rawDescription: How do I plot a step function with Bokeh?

description: Plot a step function with Bokeh


code: ''.join(c for c in S if c.isdigit())

rawDescription: Replace non-numeric characters

description: Replace non-numeric characters


code:
list_of_files = {}
for (dirpath, dirnames, filenames) in os.walk(path):
    for filename in filenames:
        if filename.endswith('.html'):
            list_of_files[filename] = os.sep.join([dirpath, filename])

rawDescription: How do you walk through the directories using python?

description: Walk through the directories using python


code:
with open ("lines.txt", "r") as myfile:
    for i, line in enumerate(myfile):
        flag = True
        words = line.split()
        for j, word in enumerate(words):
            if j == len(words) - 1:
                break
            elif word >= words[j+1]:
                flag = False
                break
        if flag:
            print('Line {} is ascending'.format(i+1))

rawDescription: Making the amount of strings checked change based on the amount of strings in a line


code: d = dict(itertools.izip_longest(*[iter(l)] * 2, fillvalue=""))

rawDescription: python convert list to dictionary

description: Python convert list to dictionary


code:
from django.http import HttpResponse

def HelloMonkey(request):
    """Respond to incoming calls with a simple text message."""

    resp = twilio.twiml.Response()
    resp.sms("Hello, Mobile Monkey")
    return HttpResponse(str(resp))

rawDescription: How to respond to text message with Django/Twilio

description: Respond to text message with Django/Twilio


code:
from prettytable import PrettyTable
x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
x.align["City name"] = "l" # Left align city names
x.padding_width = 1 # One space between column edges and contents (default)
x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])
with open('file', 'w') as w:
    w.write(str(x))

rawDescription: Python Pretty Table output to text file

description: Python Pretty Table output to text file


rawDescription: SQLAlchemy - How to select cerain rows?

description: SQLAlchemy - How to select cerain rows


code:
s = '   abdcde   '
s.strip()
'abcde'

rawDescription: Remove leading and trailing spaces?

description: Remove leading and trailing spaces


code:
from django.db.models import Max
entries = (UserRating.objects.filter(for_user = for_user, by_user = by_user)
           .values('rating_category')
           .annotate(last_created = Max('created'))
           .order_by('-last_created'))[:5]

rawDescription: Pick 5 Latest DISTINCT rows

description: Pick 5 Latest DISTINCT rows


code:
while(raw_input('Press "1" to exit.') != '1'):
    pass

rawDescription: How can I tell if a certain key was pressed in Python?

description: Tell if a certain key was pressed in Python