code:
from PyQt4 import QtCore, QtGui

class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        widget = QtGui.QWidget(self)
        layout = QtGui.QVBoxLayout(widget)
        self.setCentralWidget(widget)
        self.splitter = QtGui.QSplitter(self)
        self.splitter.addWidget(QtGui.QTextEdit(self))
        self.splitter.addWidget(QtGui.QTextEdit(self))
        self.splitter.addWidget(QtGui.QTextEdit(self))
        self.button = QtGui.QPushButton('Test', self)
        self.button.clicked.connect(lambda: self.printSizes('Test'))
        layout.addWidget(self.splitter)
        layout.addWidget(self.button)
        self.printSizes('Show Before')
        settings = self.settings()
        value = settings.value('splitter')
        if value is not None:
            self.splitter.restoreState(value)
        value = settings.value('layout')
        if value is not None:
            self.restoreState(value)
        value = settings.value('geometry')
        if value is not None:
            self.restoreGeometry(value)
        self.printSizes('Show After')
        QtCore.QTimer.singleShot(
            20, lambda: self.printSizes('Timer'))

    def closeEvent(self, event):
        self.printSizes('Close')
        settings = self.settings()
        settings.setValue("splitter", self.splitter.saveState())
        settings.setValue("geometry", self.saveGeometry())
        settings.setValue("layout", self.saveState())

    def settings(self):
        return QtCore.QSettings(
            QtCore.QSettings.IniFormat,
            QtCore.QSettings.UserScope, 'test', 'test')

    def printSizes(self, message):
        print('%s:' % message)
        print('  window geometry:', (
            self.width(), self.height(), self.x(), self.y()))
        print('  splitter sizes:', self.splitter.sizes())
        print()

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: QSplitter.sizes indicates wrong sizes

description: QSplitter.sizes indicates wrong sizes


code: chargeTypeName = models.CharField(max_length=6, blank=True)

rawDescription: Python Django rest framework Post Get Serializer


code:
import locale
locale.setlocale( locale.LC_ALL, '' )
locale.currency( 188518982.18 )
locale.currency( 188518982.18, grouping=True )

rawDescription: Currency formatting in Python

description: Currency formatting in Python


code:
from django.test.client import RequestFactory
rf = RequestFactory()
get_request = rf.get('/hello/')
post_request = rf.post('/submit/', {'foo': 'bar'})

rawDescription: How to mock users and requests in django

description: Mock users and requests in django


rawDescription: datetime to date format in python

description: Datetime to date format in python


code:
import sys
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://website.aspx")

elem = driver.find_element_by_id("ctl00_ctl00")
elem.send_keys( '15' )
elem.send_keys( Keys.RETURN )

rawDescription: How to scrape a web-site filling out forms and 'clicking' on links with R?

description: Scrape a web-site filling out forms and 'clicking' on links with R


code:
import shlex
shlex.split('play song I\ Want\ To\ Break\ Free')

rawDescription: Python split string with space unless a \ is in front


code:
cipher = {}
for f in open('mapping.txt'):
  org, cip = f.split()
  cipher[ord(org)] = cip

inpt = input('Enter string: ')

inpt = inpt.translate(cipher)
print('Message: ' + inpt)

rawDescription: How to cipher a string with info from a txt file?

description: Cipher a string with info from a txt file


code:
@mock.patch("A.increment")
def test_method(self, mock_increment):
    mock_increment.side_effect = [5,10]
    self.assertEqual(mock_increment(), 5)
    self.assertEqual(mock_increment(), 10)

rawDescription: Python Mock Multiple Calls with Different Results


code:
from gi.repository import Gtk, WebKit
...
win = Gtk.Window()
overlay = Gtk.Overlay()
page = WebKit.WebView()
page.load_uri("http://www.google.com")
overlay.add(page)
image = Gtk.Image()
image.set_from_file("HappyFish.jpg")
image.set_halign(Gtk.Align.START)
image.set_valign(Gtk.Align.START)
overlay.add_overlay(image)
win.add(overlay)
win.show_all()
win.connect('destroy', Gtk.main_quit)
Gtk.main()

rawDescription: how do I overlay an image on webview using python Gtk and webkit

description: Overlay an image on webview using python Gtk and webkit


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set_xticks([0.15, 0.68, 0.97])
ax.set_yticks([0.2, 0.55, 0.76])
plt.show()

rawDescription: How to set ticks on Fixed Position , matplotlib

description: Set ticks on Fixed Position , matplotlib


code: ax1.scatter(x_data, y_data, label= 'Example legend entry.', s=80, marker=r'$\odot$', facecolors='none', edgecolors='black')

rawDescription: Matplotlib; Scatter plot marker, dot within circle


code:
#models.py

class Section(models.Model):
    name = models.CharField(max_length=20)

class TagName(models.Model):
     tag_name = models.CharField(max_length=255, blank=True)

class Tags(models.Model):
    parent = models.ForeignKey(Section)
    name = models.ForeignKey(TagName)

class Article(TimeStampedMode):
    ...
    tag = models.ForeignKey(Tags)

rawDescription: One-To-Many models and Django Admin

description: One-To-Many models and Django Admin


code:
def make_dal(name):
    return {
        'DBDal identifier string': DBDal,
        'WSDal identifier string': WSDal
    }[name]()

rawDescription: Multiple DAL design pattern

description: Multiple DAL design pattern


rawDescription: How can I use a string with the same name of an object in Python to access the object itself?

description: Use a string with the same name of an object in Python to access the object itself


code:
df
pd.pivot_table(df, rows="A", cols="B", values="C")

rawDescription: Pandas: Moving from table to matrix layout


code:
import sys
from Tkinter import *

ABOUT_TEXT = """About

SPIES will search your chosen directory for photographs containing
GPS information. SPIES will then plot the co-ordinates on Google
maps so you can see where each photograph was taken."""

DISCLAIMER = """
Disclaimer

Simon's Portable iPhone Exif-extraction Software (SPIES)
software was made by Simon. This software
comes with no guarantee. Use at your own risk"""

def clickAbout():
    toplevel = Toplevel()
    label1 = Label(toplevel, text=ABOUT_TEXT, height=0, width=100)
    label1.pack()
    label2 = Label(toplevel, text=DISCLAIMER, height=0, width=100)
    label2.pack()

app = Tk()
app.title("SPIES")
app.geometry("500x300+200+200")

label = Label(app, text="Please browse to the directory you wish to scan", height=0, width=100)
b = Button(app, text="Quit", width=20, command=app.destroy)
button1 = Button(app, text="About SPIES", width=20, command=clickAbout)
label.pack()
b.pack(side='bottom',padx=0,pady=0)
button1.pack(side='bottom',padx=5,pady=5)

app.mainloop()

rawDescription: How do I make a pop up in Tkinter when a button is clicked? Python

description: Make a pop up in Tkinter when a button is clicked? Python


code: db.execute("PRAGMA read_uncommitted = true;");

rawDescription: How to set SQLite isolation levels, using Python

description: Set SQLite isolation levels, using Python


code:
some_method(
    that_has,
    very_many,
    arguments=None,
    of_different=None,
    kinds=u'',
    and_importance=None,
    spanning=u'multple lines'
)

rawDescription: Pythonic argument passing

description: Pythonic argument passing


code:
def _RunTestsList(self, lTestsPaths):
    """ Runs all tests in lTestsPaths with the unittest module
    """
    for sTestPath in lTestsPaths:
        testLoader = unittest.TestLoader()
        temp_module = imp.load_source('temp_module', sTestPath)
        tstSuite = testLoader.loadTestsFromModule(temp_module)
        unittest.TextTestRunner (verbosity=1).run(tstSuite)
        del sys.modules['temp_module']

rawDescription: unittest.TestSuite runs previously loaded tests in addition to currently added tests

description: Unittest.TestSuite runs previously loaded tests in addition to currently added tests


code:
from django.db.models import Q, Sum

Category.objects.filter(Q(name='difficulty',key='hard') | Q(name='success',key='yes') | Q(name='alternative',key='yes') | Q(name='processing',key='good') | Q(name='personal_touch',key='yes')).aggregate(Sum('value'))

rawDescription: How to write a query with many ANDs and ORs with sum in Python?

description: Write a query with many ANDs and ORs with sum in Python


code:
# create auth
auth = Auth(db)
# create the country table
db.define_table('country',
                Field('name'),
                Field('desc'),
                format = '%(name)s')
# say you want to add it to auth_user table (not yet created)
auth.settings.extra_fields['auth_user']=[Field('country','reference country')]
# ask auth to make the auth tables, including auth_user
auth.define_tables()

rawDescription: Extending an existing web2py database

description: Extending an existing web2py database


code:
import mechanize
br = mechanize.Browser()
br.open("http://www.gabar.org/membersearchresults.cfm?id=ED162783-9C8E-9913-79DBE86CBE9FB115")
response1 = br.follow_link(text_regex=r"Next", nr=0)
Html = response1.read()

#rest is the same

rawDescription: Using urllib2 and BeautifulSoup not receiving the data I view in browser


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

spectrum_matrix = np.random.rand(200,3)

plt.imshow(spectrum_matrix)
plt.axes().set_aspect('auto')
plt.show()

rawDescription: matplotlib aspect ratio for narrow matrices

description: Matplotlib aspect ratio for narrow matrices


code:
import threading
state = threading.local()

def three():
    # something is defined implicitly
    print(state.something)

def two():
    # ...
    three()

def one(something):
    # somehow define something inside a context
    # for this activation
    def inner():
        state.something = something
        two()
    t = threading.Thread(target=inner)
    t.start()
    t.join()

if __name__=='__main__':
    one(42)
    one(24)

rawDescription: A per-activation "global" variable in Python?


code:
import urllib2
import xml.etree.ElementTree as ET

# Make request to PDFX
pdfdata = open('example.pdf', 'rb').read()
request = urllib2.Request('http://pdfx.cs.man.ac.uk', pdfdata, headers={'Content-Type' : 'application/pdf'})
response = urllib2.urlopen(request).read()

# Parse the response
tree = ET.fromstring(response)
for tbox in tree.findall('.//region[@class="DoCO:TableBox"]'):
    src = ET.tostring(tbox.find('content/table'))
    info = ET.tostring(tbox.find('region[@class="TableInfo"]'))
    caption = ET.tostring(tbox.find('caption'))

rawDescription: pypdf not extracting tables from pdf

description: Pypdf not extracting tables from pdf


code:
from Bio import SeqIO
import glob

class Process(object):
    def __init__(self, fasta_file_name):
        # read entire fasta file into memory as a dictionary indexed by ID
        with open(fasta_file_name, "rU") as fasta_file:
            self.fasta_sequences = SeqIO.to_dict(
                                        SeqIO.parse(fasta_file, 'fasta'))

    def __call__(self, wanted_file_name, results_file_name):
        with open(wanted_file_name, "rU") as wanted, \
             open(results_file_name, "w") as results:
            for seq_id in (line.strip() for line in wanted):
                if seq_id:
                    SeqIO.write(self.fasta_sequences[seq_id], results, "fasta")

process = Process("goodProteins.fasta")  # create process object

# process each wanted file using it
for wanted_file_name in glob.glob(r"My_folder\*.txt"):
    results_file_name = wanted_file_name[:-4] + ".fasta"
    process(wanted_file_name, results_file_name)

rawDescription: Extracting fasta sequences in list files order


code:
import datetime
import os
import shutil

threshold = datetime.datetime.now() + datetime.timedelta(days=-7)
file_time = datetime.datetime.fromtimestamp(os.path.getmtime('/folder_name'))

if file_time < threshold:
    shutil.rmtree('/folder_name')

rawDescription: deleting old folders with datetime function

description: Deleting old folders with datetime function


code:
import numpy as np
import matplotlib.pyplot as plt
from skimage import color
from skimage import data

def colorize(image, hue):
    """Return image tinted by the given hue based on a grayscale image."""
    hsv = color.rgb2hsv(color.gray2rgb(image))
    hsv[:, :, 0] = hue
    hsv[:, :, 1] = 1  # Turn up the saturation; we want the color to pop!
    return color.hsv2rgb(hsv)

image = data.camera()[::2, ::2]

hue_rotations = np.linspace(0, 1, 6)  # 0--1 is equivalent to 0--180
colorful_images = [colorize(image, hue) for hue in hue_rotations]

fig, axes = plt.subplots(nrows=2, ncols=3)

for ax, array in zip(axes.flat, colorful_images):
    ax.imshow(array, vmin=0, vmax=1)
    ax.set_axis_off()

plt.show()

rawDescription: Color rotation in HSV using scikit-image


code:
from collections import namedtuple
result = json.parse(data)
JsonData = namedtuple("JsonData", result.keys())
jsondata = JsonData(**result)

rawDescription: Python: performance of custom JSON decoder


code:
class MainPage(webapp.RequestHandler):
    def get(self):

        ip = self.request.remote_addr
        log = Log()
        log.ip_address = ip
        log.put()
        self.redirect("http://www.appurl.com") # replaced this -> print "Location:http://www.appurl.com"

rawDescription: Redirect user in Python + Google App Engine


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

data=np.random.rand(10,10)

fig=plt.figure()
ax=fig.add_subplot(111)

p=ax.pcolormesh(data,vmin=0.2,vmax=0.8,cmap='gray')

p.cmap.set_over('red')
p.cmap.set_under('blue')

fig.colorbar(p,extend='both')

plt.show()

rawDescription: Distinguishing clipped values in `colorbar`


code:
import matplotlib.pyplot as plt
import matplotlib.transforms as mtrans

fig, ax = plt.subplots(2, 2)
trans = mtrans.blended_transform_factory(fig.transFigure,
                                         mtrans.IdentityTransform())

txt = fig.text(.5, 15, "total label", ha='center')
txt.set_transform(trans)

rawDescription: Adding figure description to the bottom of several subplots in Matplotlib


code:
from VideoCapture import Device
import datetime
def capt():
  a = datetime.datetime.now().strftime("%Y%m%dT%H%M%S%ms")

  b = str(a)
  cam = Device(devnum=0)
  cam.setResolution(1280, 960)

  return cam.getImage(), b

while True:
  im, b = capt()
  if im:
    break
im.save('%s.png' % (b), 'JPEG')

rawDescription: python video capture loop

description: Python video capture loop


code:
class A():
    def __init__(self):
        self.foo = 100
        self.bar = 200
        self.baz = 300
        self.sub_stack = ['foo', 'baz', 'bar']

    def subt(self, amount):
        tmp_stack = self.sub_stack[:]
        while tmp_stack and amount:
            key = tmp_stack.pop(0)
            val = self.__dict__[key]
            if val > amount:
                self.__dict__[key] -= amount
                amount = 0
            else:
                amount -= self.__dict__[key]
                self.__dict__[key]=0
        return amount

rawDescription: Python: recursive way to subtract from class attributes?


code:
from collections import Counter
freq = Counter(x for sublist in data for x in sublist)
data = [[x for x in row if freq[x] > 1] for row in data]  # Remove non-popular item
data = [row for row in data if row]  # Remove empty rows

# data => [['A', 'B', 'C'], ['E', 'F'], ['A', 'B', 'C', 'E', 'F']]

rawDescription: Remove elements from nested list - Python


code: df['col_name'].str.extract('up to a maximum of (.*)%')

rawDescription: python pandas-extracting a portion of a string based on the pattern around it

description: Python pandas-extracting a portion of a string based on the pattern around it


rawDescription: django admin don't show primary key in forms

description: Django admin don't show primary key in forms


code:
#!/usr/bin/env python

try:
    from Tkinter import *
    from tkMessageBox import showinfo
except ImportError:
    from tkinter import *
    from tkinter.messagebox import showinfo

tag_to_handle = ''

def on_click(event, widget_origin='?'):
    global tag_to_handle
    if tag_to_handle:
        showinfo('Click', '"{}" clicked'.format(tag_to_handle))
        tag_to_handle = ''
    else:
        showinfo('Click', '"{}  " clicked'.format(widget_origin))

def on_tag_click(event, tag):
    global tag_to_handle
    tag_to_handle = tag

root = Tk()
text = Text(root)
text.pack()
text.insert(CURRENT, 'Some untagged text...\n')
text.bind('<Button-1>', lambda e, w='textwidget': on_click(e, w))
for i in range(5):
    tag_name = 'tag_{}'.format(i)
    text.tag_config(tag_name)
    text.tag_bind(tag_name, '<Button-1>',
        lambda e, w=tag_name: on_tag_click(e, w))
    text.insert(CURRENT, tag_name + ' ', tag_name)
root.mainloop()

rawDescription: Python tkinter: stopping event propagation in text widgets tags


code:
import os
os.getloadavg()

rawDescription: Python and Server Load

description: Python and Server Load


code:
import django
django

rawDescription: Dude, where is my Django installation?

description: Dude, where is my Django installation


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

SCREENX = 640
SCREENY = 480

class Character(pygame.sprite.Sprite):
    def __init__(self, image_file):
        pygame.sprite.Sprite.__init__(self)
        temp_image = pygame.image.load(image_file)
        # only to the flipping of the image once
        self.image_r = pygame.transform.scale(temp_image, (100, 100))
        self.image_l = pygame.transform.flip(self.image_r, True, False)
        self.image = self.image_l
        self.rect = self.image.get_rect()

    def update(self, pressed_keys):
        move = 0
        if pressed_keys[K_d]: move += 1
        if pressed_keys[K_a]: move -= 1
        self.rect.move_ip(move*5, 0)

        # check which direction we're facing and set the image
        self.image = self.image_l if move < 0 else self.image_r

def main():
    pygame.init()
    surface = pygame.display.set_mode((SCREENX, SCREENY))
    clock = pygame.time.Clock()

    sprites = pygame.sprite.Group()

    girl = Character("assets/girl.png")
    girl.rect.x = SCREENX / 2
    girl.rect.y = SCREENY - girl.rect.height

    sprites.add(girl)

    while True:
        for event in pygame.event.get():
            # since we are in a function, we can simply return.
            # we don't care here what happens after we quit the main loop
            if event.type == QUIT: return pygame.quit()

        # get all pressed keys, and just let all sprites
        # decide what they want to do with it
        keys_pressed = pygame.key.get_pressed()

        # you could wrap this information in a more
        # general container represeting the game state
        # See how the game loop does not care what a
        # Sprite does with this information
        sprites.update(keys_pressed)

        surface.fill((255, 255, 255))
        sprites.draw(surface)
        pygame.display.update()
        clock.tick(60)

if __name__ == '__main__':
    main()

rawDescription: Is there a better way to move a sprite using the keyboard with Pygame?


code:
from Tkinter import *
from random import randint

class Baloons:
   def __init__(self,wdw, dimension):
        self.canvas= Canvas(wdw, width=dimension, height=dimension)
        self.canvas.pack()
        self.update()
        self.canvas.bind("<Button-1>", self.click2)

   def click2(self, event):
       item = self.canvas.find_withtag(CURRENT)
       if item:
           self.canvas.delete(item)

   def update(self):
      for i in range(200):
          x, y = randint(0, 400-1), randint(0, 400-1)
          self.canvas.create_oval(x-5, y-5, x+5, y+5, fill="red")

if __name__ == "__main__":
     root=Tk()
     dimension = 200
     b=Baloons(root,dimension)
     root.mainloop()

rawDescription: Python Classes order of executing things


code:
class Category(Base):
    __tablename__ = 'categories'
    pk   = Column(String(6), primary_key=True)

class Item(Base):
    __tablename__ = 'items'
    pk          = Column(String(6), primary_key=True)
    category_pk = Column(String(6), ForeignKey('categories.pk') )
    size        = Column(Integer(), nullable=False)
    category    = relationship('Category', backref=backref('items'))

class Sizes(Base):
    __tablename__ = 'sizes'
    category_pk = Column(String(6), primary_key=True )
    size        = Column(Integer(), primary_key=True )
    category    = relationship('Category', backref=backref('sizes'))
    items       = relationship('Item')

    __table_args__ = (
        ForeignKeyConstraint(
            ["category_pk", "size"],
            ["items.category_pk", "items.size"]
        ),
    )

rawDescription: SQLAlchemy: can't understand this one2many relationship with composite keys


code: logData = list(logReader)

rawDescription: Reading CSV rows with a tricky file in Python


code:
import pygtk
import gtk
import gtk.glade
import Pango

def __init__(self):
  self.gladefile                  = "XXXXX.glade"
  self.builder                    = gtk.Builder()
  self.builder.add_from_file(self.gladefile)
  self.builder.connect_signals(self)
  self.window                     = self.builder.get_object("window1")
  self.textbuffer                 = self.builder.get_object("textbuffer1")
  self.e_tag = self.textbuffer.create_tag("err", foreground="#FF0000")

def Print(self, text):

  self.textfeld = text + '\n'
  position = self.textbuffer.get_end_iter()
  self.textbuffer.insert_with_tags(position, self.textfeld, self.e_tag)

rawDescription: Glade GTK TextBuffer change or set color


code:
from __future__ import with_statement
from collections import defaultdict
from operator import itemgetter

d = defaultdict(int)

with open('dict-count.txt') as f:
    for line in f:
        k, v = line.split()
        d[k] += int(v)

lst = d.items()

# sort twice: once for alphabetical order, then for frequency (descending).
# Because the Python sort is "stable", we will end up with descending
# frequency, but alphabetical order for any frequency values that are equal.
lst.sort(key=itemgetter(0))
lst.sort(key=itemgetter(1), reverse=True)

for key, value in lst:
    print("%10s| %d" % (key, value))

rawDescription: Building count dictionary from statistics file


code:
el = driver.find_element_by_id('id_of_select')
for option in el.find_elements_by_tag_name('option'):
    if option.text == 'The Option I Am Looking For':
        option.click()

rawDescription: Selecting combo box values

description: Selecting combo box values


code:
return answer in (self.get_canswer(), )

return {self.get_canswer(): 'this is the correct answer'}.get(answer, False)

return [self.get_canswer()].pop() == answer

rawDescription: Python 3: how to compare two things

description: Python 3: how to compare two things


rawDescription: Python sort a list by two values

description: Python sort a list by two values


code:
df = DataFrame({'from': ['2015-08-24','2015-08-24'], 'to': ['2015-08-26','2015-08-31']})
# Convert boundaries to datetime
df['from'] = pd.to_datetime(df['from'], format='%Y-%m-%d')
df['to'] = pd.to_datetime(df['to'], format='%Y-%m-%d')
# Reseting index to create a row id named index
df = df.reset_index(level=0)
# Pivoting data to obtain 'from' as row index and row id ('index') as column,
# each cell cointaining the 'to' date
# In consequence each range (from - to pair) is split into as many columns.
pivoted = df.pivot('from', 'index', 'to')
# Reindexing the table with a range of business dates (i.e. working days)
pivoted = pivoted.reindex(index=pd.bdate_range(start=min(df['from']),
                                               end=max(df['to'])))
# Filling the NA values forward to copy the to date
# now each row of each column contains the corresponding to date
pivoted = pivoted.fillna(method='ffill')
# Computing the basically 'from' - 'to' for each column and each row and converting the result in days
# to obtain the number of days between the date in the index and the 'to' date
# Note: one day is added to include the right side of the interval
pivoted = pivoted.apply(lambda x: (x + Day() - x.index) / np.timedelta64(1, 'D'),
                        axis=0)
# Clipping value lower than 0 (not in the range) to 0
# and values upper than 0 to 1 (only one by day and by id)
pivoted = pivoted.clip_lower(0).clip_upper(1)
# Summing along the columns and that's it
pivoted.sum(axis=1)

rawDescription: Count the number of days in several ranges


rawDescription: ipython notebook "current directory" in wondows

description: Ipython notebook "current directory" in wondows


code:
pattern = re.compile('(?P<group1>AAA|BBB|CCC)|(?P<group2>DDD|EEE|FFF)')
m = pattern.search("AAA")
m.lastgroup
m = pattern.search("DDD")
m.lastgroup

rawDescription: python regex: get name of named group

description: Python regex: get name of named group


code: subsquares = [[sudokuSquare[j][i] for j in range(x, x + w) for i in range(y, y + h)] for x in range(0, 9, 3) for y in range(0, 9, 3)]

rawDescription: sudoku subsquare generation

description: Sudoku subsquare generation


code: dbfilename /my/path/dump.rdb

rawDescription: REDIS in python

description: REDIS in python


code:
cell = CellRendererPixbufXt()
cell.connect('clicked', func)

rawDescription: gtk treeview: place image buttons on rows

description: Gtk treeview: place image buttons on rows


code:
expr = Integral(x,x)
Eq(expr, expr.doit())

rawDescription: Show formatted unevaluated = evaluated in ipython notebook with sympy


code:
import ast

result = ast.literal_eval("{'a': 1, 'b': 2}")
assert type(result) is dict

result = ast.literal_eval("[1, 2, 3]")
assert type(result) is list

rawDescription: How can I convert string to dict or list?

description: Convert string to dict or list


code:
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)

rawDescription: Commenting Regular expressions in python


code:
a=np.arange(6)
ind=[2,3]
cind=(a==a)
cind[ind]=False
a[cind]

rawDescription: better way to use index array to get elements?

description: Better way to use index array to get elements


code:
def _dfs(start_nodes, rules, visited):
    """
    Depth First Search
    start_nodes - Dictionary of Rule with dependencies (as Tuples):

        start_nodes = {'A': ('B','C')}

    rules - Dictionary of Rules with dependencies (as Tuples):
    e.g.
    rules = {'A':('B','C'), 'B':('D','E'), 'C':('E','F'),
             'D':(), 'E':(), 'F':()}
    The above rules describe the following DAG:

                    A
                   / \
                  B   C
                 / \ / \
                D   E   F
    usage:
    >>> rules = {'A':('B','C'), 'B':('D','E'), 'C':('E','F'),
                 'D':(), 'E':(), 'F':()}
    >>> visited = []
    >>> list(_dfs({'A': ('B','C')}, rules, visited))
    [('A', ('B', 'C')), ('B', ('D', 'E')), ('D', ()), ('E', ()),
    ('C', ('E', 'F')), ('F', ())]
    """

    for rule, dep in start_nodes.items():
        if rule not in visited:
            yield rule, dep
            visited.append(rule)
            for ii in dep:
                new_dep={ ii : rules[ii]}
                for dep in _dfs(new_dep, rules, visited):
                    if dep not in visited:
                        yield dep

rawDescription: DFS algorithm in Python with generators

description: DFS algorithm in Python with generators


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

x = np.arange(1,24,1)
y = np.array([400,650,1020,1300,1600,1950,2200,2550,2850,3150,3400,3550,3800,3950,4050,4150,4210,4250,4300,4320,4310,4300,4200])

fig = plt.figure()
ax = plt.subplot(111)

ax.plot(x,y,'o', label='data set 1')
ax.set_title('Data set A-1')

ax.set_xlabel('x', fontsize=14)
ax.set_ylabel('y', fontsize=14)
ax.set_ylim(ymax=5000)

ax.legend(loc='upper center',
          ncol=3, fancybox=True, shadow=True)
#plt.tight_layout()
plt.show()

rawDescription: Python customised title and legend in figure


code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

Builder.load_string("""
<ButtonsApp>:
    orientation: "vertical"
    Button:
        text: "B1"
        Image:
            source: 'kivy.png'
            y: self.parent.y + self.parent.height - 250
            x: self.parent.x
            size: 250, 250
            allow_stretch: True
    Label:
        text: "A label"
""")

class ButtonsApp(App, BoxLayout):
    def build(self):
        return self

if __name__ == "__main__":
    ButtonsApp().run()

rawDescription: Passing image object as a button background in Kivy


code:
import cProfile,random
def scrambled(orig): # scramble list
    dest = orig[:]
    random.shuffle(dest)
    return dest

myList = scrambled(range(0,10000000))

cProfile.run('print myList.index(1)') #3 func, same amount of time
cProfile.run('print myList.index(1)') #3 func, same amount of time

rawDescription: Does list.index() implement caching

description: Does list.index() implement caching


code: values = data.find().sort("ownName",1)

rawDescription: regroup in django-template mongo values

description: Regroup in django-template mongo values


code:
class CustomPlotItem(pg.PlotDataItem):
    def __init__(self, *args, **kargs):
        super().__init__(*args, **kargs)
        # Need to switch off the "has no contents" flag
        self.setFlags(self.flags() & ~self.ItemHasNoContents)

    def mouseDragEvent(self, ev):
        print("drag")
        if ev.button() != QtCore.Qt.LeftButton:
            ev.ignore()
            return

        if ev.isStart():
            print("start")
        elif ev.isFinish():
            print("finish")

    def shape(self):
        # Inherit shape from the curve item
        return self.curve.shape()

    def boundingRect(self):
        # All graphics items require this method (unless they have no contents)
        return self.shape().boundingRect()

    def paint(self, p, *args):
        # All graphics items require this method (unless they have no contents)
        return

    def hoverEvent(self, ev):
        # This is recommended to ensure that the item plays nicely with
        # other draggable items
        print("hover")
        ev.acceptDrags(QtCore.Qt.LeftButton)

rawDescription: PyQtGraph Custom PlotDataItem is not receiving mouseDragEvents


code:
from django.shortcuts import redirect

def my_view(request):
    ...
    return redirect('some-view-name', foo='bar')

rawDescription: Django: dynamically mapping views in urls.py


code:
class MyAdmin(admin.ModelAdmin):
     def has_add_permission(self, request):
        return False

rawDescription: Django Admin - Disable the 'Add' action for a specific model


code:
import os
import wx
import numpy as np
import matplotlib
matplotlib.use('WXAgg')
import matplotlib.figure as figure
import matplotlib.backends.backend_wxagg as wxagg

class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'Title')
        self.create_menu()
        self.create_main_panel()
        self.draw_figure()

    def create_menu(self):
        self.menubar = wx.MenuBar()

        menu_file = wx.Menu()
        m_exit = menu_file.Append(-1, "&Quit\tCtrl-Q", "Quit")
        self.Bind(wx.EVT_MENU, self.on_exit, m_exit)
        self.menubar.Append(menu_file, "&File")
        self.SetMenuBar(self.menubar)

    def create_main_panel(self):
        """ Creates the main panel with all the controls on it:
             * mpl canvas
             * mpl navigation toolbar
             * Control panel for interaction
        """
        self.panel = wx.Panel(self)

        # Create the mpl Figure and FigCanvas objects.
        # 5x4 inches, 100 dots-per-inch
        #
        self.dpi = 100
        self.fig = figure.Figure((5.0, 4.0), dpi=self.dpi)
        self.canvas = wxagg.FigureCanvasWxAgg(self.panel, -1, self.fig)
        self.axes = self.fig.add_subplot(111)

        # Create the navigation toolbar, tied to the canvas
        #
        self.toolbar = wxagg.NavigationToolbar2WxAgg(self.canvas)

        #
        # Layout with box sizers
        #
        self.vbox = wx.BoxSizer(wx.VERTICAL)
        self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.vbox.AddSpacer(25)
        self.vbox.Add(self.toolbar, 0, wx.EXPAND)

        self.panel.SetSizer(self.vbox)
        self.vbox.Fit(self)

    def draw_figure(self):
        """ Redraws the figure
        """
        # clear the axes and redraw the plot anew
        #
        self.axes.clear()
        x, y = np.random.random((10, 2)).T
        self.axes.scatter(x, y)

        self.canvas.draw()

    def on_exit(self, event):
        self.Destroy()

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

rawDescription: drawing a scatter graph in matlibplot in wxpython

description: Drawing a scatter graph in matlibplot in wxpython


code:
foo = csr_matrix(...)
row_names = np.array(...)
col_names = np.array(...)

# index by name:
row_idx, = np.where(row_names == "my row")
col_idx, = np.where(col_names == "my col")
foo[row_idx, col_idx]

rawDescription: How can I give row and column names to Scipy's csr_matrix?

description: Give row and column names to Scipy's csr_matrix


code:
f = open('c:\\filename.txt', 'w')

f.writeline(path)
f.writeline(analysis)

my_list = ['one','two','three']

for item in my_list:
    f.writeline(item)

f.close

rawDescription: Output Spotfire 'print' to text file

description: Output Spotfire 'print' to text file


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

## Your simulation code here ##

# Extract max, min, and mean values for each x coordinate
minimums = np.array(sim.min())
maximums = np.array(sim.max())
means = np.array(sim.mean())

x = np.array(sim.min().index)
y = np.arange(90,111)
X, Y = np.meshgrid(x, y)

# Insert your calculation for "concentration" in the line below
Z = (maximums[X] - minimums[X]) * Y // 100

# set up axes with matplotlib
fig, ax = plt.subplots()

# Plot contour, you'll want to change the levels
# depending on the range of values in your "concentration"
ax.contourf(X, Y, Z, levels=np.arange(0,20,.1), cmap=plt.get_cmap('jet'))

# Plot min, max, and mean
ax.plot(x, minimums, c='k')
ax.plot(x, maximums, c='k')
ax.plot(x, means, c='k', lw=2)

# Fill space outside min and max with white
ax.fill_between(x, maximums, 110, color='w')
ax.fill_between(x, 90, minimums, color='w')

rawDescription: Matplotlib: use a colormap to show concentration of a process around its mean


code:
please_die = threading.Event()

# in handler
please_die.set()

# in main thread
please_die.wait()
httpd.shutdown()

rawDescription: Python BaseHTTPServer: How to get it to stop?


code:
def dq_strip(string):
    return string.replace('""','')

table = [map(dq_strip, row) for row in table]

rawDescription: python3 - csv import - changing a string in a for loop

description: Python3 - csv import - changing a string in a for loop


rawDescription: Pytables vs. CSV for files that are not very large


code:
import os.path
path = os.path.expanduser('~/.myapp/db.sqlite')

rawDescription: How to write a portable program in python that accesses particular directories?

description: Write a portable program in python that accesses particular directories


code:
data_file = [('Div', 'Date', 'HomeTeam', 'AwayTeam', 'FTHG', 'FTAG'),
('E0', '18/08/12', 'Arsenal', 'Sunderland', '0', '0'),
('E0', '18/08/12', 'Arsenal', 'Sunderland', '4', '0'),
('E0', '18/08/12', 'Arsenal', 'Sunderland', '2', '0'),
('E0', '18/08/12', 'Fulham', 'Norwich', '5', '0') ]

def CalcAverageHome(team, column, data_file):
    total = 0
    n=0         # the number of times the team you are looking for is in the data
    for row in data_file:
        if  row[2] == team:
            total += int(row[column])
            n+=1
    try:
        average = float(total) / n  # if u r using python 2.7.Else if 3.2+  just total/n
    except ZeroDivisionError:       # to prevent zerodevisionerror if t team had n games
        average = 'Not played'
    return average

rawDescription: LIst of lists python - referencing particular locations / slicing sublists


code:
import requests

url = 'http://sg.idtdna.com/calc/analyzer/home/analyze'
data = {
    'settings': {
        'Sequence': 'AACCGGTT',
        'NaConc': 50,
        'MgConc': 0,
        'DNTPsConc': 0,
        'OligoConc': 0.25,
        'NucleotideType': 'DNA',
    }
}

s = requests.Session()
s.get('http://sg.idtdna.com/calc/analyzer')  # to set cookies
r = s.post(url, json=data)
print(r.json())

rawDescription: Python: how to set up a requests.post

description: Python: how to set up a requests.post


code:
last_ping = time.time()
threshold = 5 * 60 # five minutes, make this whatever you want
while connected:
    data = irc.recv ( 4096 )
    # If Nick is in use
    if data.find ( 'Nickname is already in use' ) != -1:
        NICK = NICK + str(time.time())
        Connection()
    # Ping Pong so we don't get disconnected
    if data.find ( 'PING' ) != -1:
        irc.send ( 'PONG ' + data.split() [ 1 ] + '\r\n' )
        last_ping = time.time()
    if (time.time() - last_ping) > threshold:
        break

rawDescription: Python : Check if IRC connection is lost (PING PONG?)


code:
left_len = len(leftcell)
for i in xrange(left_len-1,0,-1):
    if B[leftcell[i]].length  % 140 != 0:
        leftcell.insert(i, 2)

rawDescription: Insert Element in list during iteration

description: Insert Element in list during iteration


code:
import subprocess

var = 'foo server'
cmd = ['/etc/openvpn/easy-rsa/pkitool', '--server', var]
output = subprocess.check_output(cmd)

rawDescription: String interpolation to bash inside python code


code:
target_dir = os.path.expanduser('~/a/long/long/path')
os.makedirs(target_dir)
shutil.copy('resources/foo.bar', os.path.join(target_dir, 'foo_bar'))

rawDescription: Copying a file to a path, with Python

description: Copying a file to a path, with Python


code:
import datetime
import resource
import os
from mpi4py import MPI

mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
rank = MPI.COMM_WORLD.Get_rank()
fname = 'r{}.log'.format(rank)
with open(fname, 'a') as f:
    # Dump timestamp, PID and amount of RAM.
    f.write('{} {} {}\n'.format(datetime.datetime.now(), os.getpid(), mem))

rawDescription: How can I measure the memory occupancy of Python MPI or multiprocessing program?

description: Measure the memory occupancy of Python MPI or multiprocessing program


rawDescription: Appending specific integers to nested lists - Python


code:
from django.http import HttpResponse

# use custom response class to override HttpResponse.close()
class HttpResponseAndMail(HttpResponse):
    def __init__(self, article="", people=[], *args, **kwargs):
        super(HttpResponseAndMail, self).__init__(*args, **kwargs)
        self.article = article
        self.people = people

    def close(self):
        super(HttpResponseAndMail, self).close()
        # do whatever you want, this is the last codepoint in request handling
        if self.status_code == 200:
            send_mail(subject="", from_email="", message=self.article, recipient_list=self.people)

rawDescription: In Django, how can I run a function in background


code:
regex_title = ['I went to the store', 'Itlt's a nice day today',
               'I went home for a rest']
regex_title = [s.replace("lt'", "'") for s in regex_title]
regex_title

rawDescription: Replacing parts of strings in a list in Python


code: "%.2f" % myNum

rawDescription: Save list to csv with two decimal digits in python?


code:
class LoginFormWithoutNickname(LoginForm):
    def __init__(self, *args, **kwargs):
        super(LoginFormWithoutNickname, self).__init__(*args, **kwargs)
        self.fields.pop('nickname')

rawDescription: Django: Remove a field from a Form subclass


code:
def only_filename(instance, filename):
    return filename

class MyModel(models.Model):
    file = models.FileField(upload_to=only_filename)

rawDescription: Django models.FileField - store only the file name not any paths or folder references


code:
mls_search = driver.find_element_by_id('txtMlsNumber')
mls_search.send_keys('number that you scraped')

search = driver.find_element_by_id('lnkMlsSearch')
search.click()

rawDescription: Trying to use Python Mechanize to fill in search box contained in <td> tags


code:
class Obj(object):
    pass

obj = Obj()
for key, value in {'var1':5, 'var2':6}.iteritems():
    setattr(obj, key, value)

obj.var1
obj.var2

rawDescription: Looping through dictionary to insert value to an object


code:
def encrypt(message, shift):
    new = ''
    for i in (ord(x) for x in message): #gets the ascii value of each letter in message
        if 64 < i < 91: #uppercase
            new += chr(65 + (i+shift-65)%26)
        elif 96 < i < 123: #lowercase
            new += chr(97 + (i+shift-97)%26)
    return new

def decrypt(message, shift):
    return encrypt(message, 26-shift)

rawDescription: my output goes into non alphabetic values python 3.4 caesar cipher

description: My output goes into non alphabetic values python 3.4 caesar cipher


code:
import networkx as nx
G = nx.Graph()
G.add_edge(1,2,weight=7)
G.add_edge(1,3,weight=42)
G.degree(weight='weight')
G.degree(weight='weight').items()

rawDescription: NetworkX Get Degree of Node with Weights Applied


code:
from matplotlib.ticker import FormatStrFormatter

fig, ax = plt.subplots()

ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))

rawDescription: Matplotlib: Specify format of floats for tick lables


rawDescription: Type-casting of session object in python, django


code:
from piston.emitters import Emitter, XMLEmitter

class ProductXMLEmitter(XMLEmitter):
    def _to_xml(self, xml, data):
        if isinstance(data, (list, tuple)):
            for item in data:
                attrs = {}
                # if item contains id value, use it as an attribute instead
                if isinstance(item, dict):
                    attrs["id"] = unicode(item.pop("id"))
                xml.startElement("product", attrs)
                self._to_xml(xml, item)
                xml.endElement("product")
        else:
            super(BetterXMLEmitter, self)._to_xml(xml, data)

# replace default XMLEmitter with ours
Emitter.register('xml', ProductXMLEmitter, 'text/xml; charset=utf-8')

rawDescription: how to change xml element name in django-piston?

description: Change xml element name in django-piston


code:
def SumPrice():
    price = 0
    TotalPrice = 0
    if cup_cone=="cup":
        price=(price+(mass/10)*0.59)*TotalSet
    else:
        if cone_size=="small":
            price=(price+2)*TotalSet
        else:
            if cone_size=="medium":
                price=(price+3)*TotalSet
            else:
                price=(price+4)*TotalSet

    if Member_Ans=="yes":
        TotalPrice=TotalPrice+price*0.90

    return price, TotalPrice

def PrintDetails():
    price, TotalPrice = SumPrice()
    if Member_Ans=="yes":
        print("Member ID: ", loginID, " (" , Username, ")")

    for element in range (len(UserFlavor)):
        print (UserFlavor[element], "--- ", UserFlavorPercentage[element], "%")

    print ("Total set = ", TotalSet)
    print ("Total price = RM %.2f" % (price))
    if Member_Ans=="yes":
        print ("Price after 10%% discount = RM %.2f" %  (TotalPrice))

    while True:
        Payment=int(input("Please enter your payment: "))
        if Payment<TotalPrice:
            print("Not enough payment.")
        if Payment >= TotalPrice:
            break

    Balance=Balance+(Payment-TotalPrice)
    print(Balance)

PrintDetails()

rawDescription: Return value doesn't work in Python 3

description: Return value doesn't work in Python 3


code:
email = EmailMessage(
            subject='Registration Successful',
            body=msg,
            from_email='My Name <me@gmail.com>',
            to='recipient@gmail.com',
            headers={'Reply-To': 'another@gmail.com'})
email.send()

rawDescription: Let receivers of an email reply to a different address


code:
import os
import sys
import ImageFont
import Image
import ImageDraw

img = Image.open("two.jpg")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("/usr/share/fonts/truetype/msttcorefonts/Times_New_Roman.ttf",27)
draw.text((100, 100), "test test test", font=font, fill = 'blue')
img.save("out.jpg")

rawDescription: PIL Draw.text and Lower Resolution

description: PIL Draw.text and Lower Resolution


code:
class BaseObject(StructuredNode):
    __index__ = 'MyBaseIndex'
    uid = StringProperty(unique_index=True)
    ...

class Type1Object(BaseObject):
    __index__ = 'MyBaseIndex'
    ...
    def assign_uid(self, guid):
        # I may need tweaking of uid generator
        # on subclass level
        self.uid = guid

class Type2Object(BaseObject):
    __index__ = 'MyBaseIndex'
    ...
    def assign_uid(self, guid):
        self.uid = guid

rawDescription: neomodel: how to share index across StructuredNode Objects

description: Neomodel: how to share index across StructuredNode Objects


code:
def removeComments(string):
    string = re.sub(re.compile("/\*.*?\*/",re.DOTALL ) ,"" ,string) # remove all occurance streamed comments (/*COMMENT */) from string
    string = re.sub(re.compile("//.*?\n" ) ,"" ,string) # remove all occurance singleline comments (//COMMENT\n ) from string
    return string

rawDescription: Using regex to remove comments from source files


code:
import tokenize
import io

class _CHAIN(object):

    def __init__(self, execution_context=None):
        self.execution_context = execution_context

    def eat(self, toktype, tokval, rowcol, line, logical_line):
        #some code and error checking
        print(toktype, tokval, rowcol, line, logical_line)

operations = _CHAIN(None)

readline = io.StringIO('aaaa').readline

#Python 2 way:
#tokenize.tokenize(readline, operations.eat)

#Python 3 way:
for token in tokenize.generate_tokens(readline):
    operations.eat(token[0], token[1], token[2], token[3], token[4])

rawDescription: tokenize in python3.x

description: Tokenize in python3.x


code:
import time
# record when person was first hit.
previousHit = time.time()

if time.time() - previousHit > 10:
    # The rest of your logic for getting hit.
    previousHit = time.time() # Reset the timer to get the hit again.

rawDescription: How to make a slower timer? (Python)

description: Make a slower timer? (Python)


code:
from csv import DictReader, DictWriter

with open('file1.csv') as fin1,\
     open('file2.csv') as fin2,\
     open('file3.csv', 'wb') as fout:

    reader1 = DictReader(fin1)
    reader2 = DictReader(fin2)

    writer = DictWriter(fout, fieldnames=reader2.fieldnames)
    writer.writeheader()

    for line2 in reader2:
        outline = dict(line2)
        fin1.seek(0) # resets the reader1 iterator
        for line1 in reader1:
            if line1['Search Value'] in line2['Name']:
                outline['Geo Location'] = line1['Location']
        writer.writerow(outline)

rawDescription: Writing a value in a csv column based on another value in another csv


code:
wait = WebDriverWait(driver, 10)

for x in range(len(self._data)):
    try:
        wait.until(expected_conditions.visibility_of(_inputs[x]))
        _inputs[x].send_keys(self._data[x])
    except Exception:
        continue
    finally:
        _all_inputs[0].send_keys(Keys.RETURN)

rawDescription: Filling out create form with values from a list/dict using webdriver


code:
from django.core.cache.utils import make_template_fragment_key

def clear_cache_block(obj, lang):
    key = make_template_fragment_key('object_detail', (obj.id, lang))
    cache.delete_pattern(key)

rawDescription: Django clear cache for only detail view

description: Django clear cache for only detail view


code:
import pygame
import math
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()

# some helpful vector math functions
def normalize(v):
    vmag = magnitude(v)
    return [v[i]/vmag  for i in range(len(v))]
def magnitude(v):
    return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))
def add(u, v):
    return [ u[i]+v[i] for i in range(len(u)) ]

class Paddle(pygame.sprite.Sprite):
    def __init__(self, start_pos, up_key, down_key):
        pygame.sprite.Sprite.__init__(self)
        # the image is just a white rect
        self.image = pygame.surface.Surface((20, 100))
        self.image.fill(pygame.color.Color('White'))
        self.image.set_colorkey(pygame.color.Color('Black'))
        self.rect = self.image.get_rect(topleft=start_pos)
        # using a mask so we can use pixel perfect collision
        self.mask = pygame.mask.from_surface(self.image)
        self.up_key, self.down_key = up_key, down_key
    def update(self, pressed):
        if pressed[self.up_key]:   self.rect.move_ip(0, -3)
        if pressed[self.down_key]: self.rect.move_ip(0,  3)
        # keep the paddle inside the screen
        self.rect.clamp_ip(pygame.display.get_surface().get_rect())

class Ball(pygame.sprite.Sprite):
    def __init__(self, start_pos):
        pygame.sprite.Sprite.__init__(self)
        # the image is just a white ball
        self.image = pygame.surface.Surface((20, 20))
        self.rect = self.image.get_rect(center=start_pos)
        pygame.draw.circle(self.image, pygame.color.Color('White'), self.image.get_rect().center, 10)
        self.image.set_colorkey(pygame.color.Color('Black'))
        # using a mask so we can use pixel perfect collision
        self.mask = pygame.mask.from_surface(self.image)
        # the vector we use to move the ball
        self.move_v = (1, 0.7)
        # store the absolute position in self.pos
        # because a rect can only use integers
        self.pos = self.rect.center
    def update(self, pressed):
        # check if the ball collides with any other sprite
        collide = [s for s in pygame.sprite.spritecollide(self, self.groups()[0], False, pygame.sprite.collide_mask) if s != self]
        if collide:
            # warning: this does not handle the case of the ball hits
            # the top or bottom of the paddle, only the sides.
            self.move_v = [-self.move_v[0], self.move_v[1]]

        # check if the ball would go out of screen
        display = pygame.display.get_surface().get_rect()
        if self.rect.top < display.top and self.move_v[1] < 0 or \
           self.rect.bottom > display.bottom and self.move_v[1] > 0:
            self.move_v = [self.move_v[0], -self.move_v[1]]

        # apply a constant speed and update the position
        move_vector = [c * 4 for c in normalize(self.move_v)]
        self.pos = add(self.rect.center, move_vector)
        self.rect.center = map(int, self.pos)

player1 = Paddle((30,  190), pygame.K_w , pygame.K_s)
player2 = Paddle((590, 190), pygame.K_UP, pygame.K_DOWN)
ball = Ball(screen.get_rect().center)
sprites = pygame.sprite.Group(player1, player2, ball)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: break
    else:
        pressed = pygame.key.get_pressed()
        sprites.update(pressed)
        screen.fill(pygame.color.Color('black'))
        sprites.draw(screen)
        pygame.display.flip()
        clock.tick(60)
        continue
    break
pygame.quit()

rawDescription: Ping pong clone collision detection

description: Ping pong clone collision detection


code:
def check_id(tag):
    valid_ids = ['priceblock_ourprice','priceblock_saleprice','priceblock_dealprice']
    if tag.has_attr('id'):
        return tag['id'] in valid_ids
    else:
        return False

m = soup1.find_all(check_id)

rawDescription: Python - Beautiful Soup OR condition in soup.find_all(....)


code:
import ctypes
b = ctypes.c_buffer("abc\0def", 16)
b.value
b.raw

rawDescription: Receiving non Null-Terminated data in Python Ctypes callback


code:
librc.rohc_alloc_compressor.restype = c_void_p
librc.rohc_activate_profile.argtypes = [c_void_p, c_int]

rawDescription: ctypes - call library function passing a struct resulted from an other library call

description: Ctypes - call library function passing a struct resulted from an other library call


code:
from docx import Document

doc = Document()
table = doc.add_table(6,6)
header_row = table.rows[0]
header_row.merge_cells()

# args can also be passed to merge_cells(mergeStart, mergeStop) in order to
# implement any kind of merge on the same row, such as:
table.rows[1].merge_cells(0,3)  # This will merge the cells indexed from 0 to 2.

rawDescription: Cell spanning multiple columns in table using python-docx


code:
from ctypes import windll

WM_LBUTTONDBLCLK = 0x0203
MK_LBUTTON = 0x0001

if __name__=='__main__':
    hProgman = windll.User32.FindWindowW( "Progman", 0 )
    if hProgman != 0:
        hFolder = windll.User32.FindWindowExW( hProgman, 0, "SHELLDLL_DefView", 0 )
        if hFolder != 0:
            hListView = windll.User32.FindWindowExW( hFolder, 0, "SysListView32", 0 )
            if hListView != 0:
                windll.User32.PostMessageW( hListView, WM_LBUTTONDBLCLK, MK_LBUTTON,
                                            110 + (65536*32) )

rawDescription: How to simulate desktop click at (x,y) position with python?

description: Simulate desktop click at (x,y) position with python


code: SQLstring = curs.mogrify('select name, age from people where name = %s;', ('ann',) )

rawDescription: psycopg - Get formatted sql instead of executing

description: Psycopg - Get formatted sql instead of executing


code:
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt
import numpy as np

fig,host = plt.subplots()
fig.subplots_adjust(right=0.75)

par1 = host.twinx()
par2 = host.twinx()

par2.spines["right"].set_position(("axes", 1.2))
par2.spines["right"].set_visible(True)

host.set_xlabel("Depth")
host.set_ylabel("Temperature")
par1.set_ylabel("Salinity")
par2.set_ylabel("Velocity")

x  = np.array([0,5,10,15,20,25,30,35])
y1 = np.array([30.340,30.080,29.116,28.395,28.093,28.040,27.975,27.872])
y2 = np.array([33.130,34.046,35.119,34.933,34.764,34.824,34.860,34.852])
y3 = np.array([1544.296, 1544.787, 1543.452,1542.280,1541.522,1544.548,1541.523,1541.368])

p1, = host.plot(x, y1, 'b', label="Temperature")
p2, = par1.plot(x, y2, 'r', label="Salinity")
p3, = par2.plot(x, y3/10, 'g', label="Velocity/00")

host.yaxis.label.set_color(p1.get_color())
par1.yaxis.label.set_color(p2.get_color())
par2.yaxis.label.set_color(p3.get_color())

tkw = dict(size=4, width=1.5)
host.tick_params(axis='y', colors=p1.get_color(), **tkw)
par1.tick_params(axis='y', colors=p2.get_color(), **tkw)
par2.tick_params(axis='y', colors=p3.get_color(), **tkw)
host.tick_params(axis='x', **tkw)

host.legend()
plt.show()

rawDescription: Multiple y axis using matplotlib not working


code:
import pylab
from pylab import *
import numpy as np

manXnames = np.array(range(0,120))
Ynames = (8.3333333333333331e-05)*manXnames + 0.01
Vt_X = manXnames
Vt_Y = (12.0/1000.0)*np.exp(-0.01*(120-manXnames))
Vterror = Ynames + randn(size(Ynames))

fig_base = pylab.figure()
fig1 = fig_base.add_subplot(111)
lns1 = fig1.plot(manXnames, Ynames, marker='s', color='g',label='Plain Line')
lns2 = fig1.plot(Vt_X, Vt_Y, marker='^', color='r',label='V_t')

# yticks on left
locs,labels = yticks()
pylab.yticks(locs, map(lambda x: "%g" % x, locs*1e3))

#axis labels
pylab.xlabel('Temperature (C)')
pylab.ylabel('Emitter Voltage (mV)', labelpad=20)
pylab.xticks(rotation=45)

fig2 = fig1.twinx()
lns3 = fig2.plot(manXnames, Vterror, marker='o', linestyle='-',label='V_terror')

# xticks
locs,labels = xticks()
pylab.xticks(locs, map(lambda x: "%g" % x, locs))

# yticks on right
locs,labels = yticks()
pylab.yticks(locs, map(lambda x: "%g" % x, locs))

#2nd axis labels
pylab.ylabel('Percentage Error %', labelpad=20)

pylab.legend((lns1, lns2, lns3), ('Plain Line', 'V_t', 'V_t Error'))
pylab.show()

rawDescription: matplotlib - Secondary Y axis with different base exponents and a legend

description: Matplotlib - Secondary Y axis with different base exponents and a legend


code: data.resample('D', how='count')

rawDescription: Plotting grouped data by date

description: Plotting grouped data by date


code:
def __new__(cls, pattern):
    new_selection = super().__new__(cls, *pattern)
    new_selection.xflipped = False
    new_selection.yflipped = False
    new_selection.rotation = 0
    return new_selection

rawDescription: Extending NamedTuple with Methods and Mutable Fields


code:
fp = webdriver.FirefoxProfile()

fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir",getcwd())
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","text/csv")

browser = webdriver.Firefox(firefox_profile=fp)

rawDescription: Python Selenium, how to save http response content?


code:
from collections import defaultdict

tmp = defaultdict(lambda: {'value': 0})
for d in data:
    tmp[d["nid"], d["cid"]]['count'] = d["count"]
    tmp[d["nid"], d["cid"]]['value'] += d["value"]

new_data = [{'nid': nid, 'cid': cid, 'count': v['count'], 'value': v['value']}
            for (nid, cid), v in tmp.iteritems()]

rawDescription: Intelligently merging dicts

description: Intelligently merging dicts


rawDescription: Adding BOM (unicode signature) while saving file in python


code:
time.sleep(2)
clickme = browser.find_elements_by_xpath('//*[@id="annotations"]')
data = []
for tr in clickme:
    tds=tr.find_elements_by_tag_name('td')
    if tds:
        data.append([td.text for td in tds])

def chunks(l, n):
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

with open('out.csv', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile)

    for a_chunk in chunks(data[0], 6):
        csvwriter.writerow(a_chunk)

browser.close()

rawDescription: Input contents of csv column by column into a website Python


rawDescription: pandas: return column values that begin with certain number(s)

description: Pandas: return column values that begin with certain number(s)


code:
band = Band.objects.get(id=target_band_id)
song_list = Song.objects.filter(bandname=band)
album_list = Album.objects.filter(song__in=song_list).distinct()

rawDescription: Filter based on mutually related models

description: Filter based on mutually related models


code:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setsockopt(socket.IPPROTO_IP, 24,1)
s.bind((serverip, serverport))
s.listen(1)
port = reactor.adoptStreamPort(
       s.fileno(), AF_INET, YourFactory())

rawDescription: setsockopt before connect for reactor.connectTCP

description: Setsockopt before connect for reactor.connectTCP


code:
df
neworder = [1, 0, 2]
newindex = sorted(df.index, key=lambda x: neworder.index(x[0]))
newindex
df.reindex(newindex)

rawDescription: Pandas shuffle rows at a certain level

description: Pandas shuffle rows at a certain level


rawDescription: Sympy expression as ratio of polynomials


code:
class SetPasswordMixin(forms.Form):
    ...

class MessageFormBase(forms.ModelForm):
    class Meta:
        model = Message

class MessageForm(MessageFormBase, SetPasswordMixin):
    pass

rawDescription: Reuse form fields in Django

description: Reuse form fields in Django


code:
import sys
sys.path.append("/path/to/numpy")
import numpy

rawDescription: Workaround Way To Install Numpy?

description: Workaround Way To Install Numpy


code:
def func1(a=1, b=2, c=3):
    func2(**locals())

rawDescription: Passing all arguments of a function to another function


code:
reader = DictReader(open('name_of_file.csv'))
reader.fieldnames

rawDescription: Automatize input_fields declaration from a csv file using python


code:
import struct

def int32(some_bytes):
    return struct.unpack("i", some_bytes)[0]

def int16(some_bytes):
    return struct.unpack("h", some_bytes)[0]

rawDescription: Interpreting binary string as integer in python


code:
from ftplib import FTP
ftp = FTP('ftp.debian.org')     # connect to host, default port
ftp.login()                     # user anonymous, passwd anonymous@
ftp.cwd('debian')               # change into "debian" directory
ftp.retrlines('LIST')           # list directory contents
ftp.retrbinary('RETR README', open('README', 'wb').write)
ftp.quit()

rawDescription: Ways to transfer PDF documents using python


code:
import numpy as np

arr = np.empty(shape=(2, 100, 100))

arr[0,:,:] = array_2d_1
arr[1,:,:] = array_2d_2

rawDescription: Creating a 3d numpy array matrix using append method


code:
def CurSelect(self, a):
    indexes = self.root.listbox.curselection()
    items = [self.root.listbox.get(index) for index in indexes]
    print("indexes:", indexes)
    print("items:", items)

rawDescription: Python Tkinter - Listbox custom class to return index, but there is no index


code:
def foo(self, blah=None):
    if blah is None: # faster than blah == None - thanks to kcwu
        blah = self.instance_var

rawDescription: python instance variables as optional arguments

description: Python instance variables as optional arguments


code:
wrapped = [1, 2, 3]
getattr(wrapped, 'append')
getattr(wrapped, 'append')(4)
wrapped

rawDescription: After calling __getattr__ method

description: After calling __getattr__ method


code:
ip_string = ",".join(IPsToPING)
subprocess.call('Fping.exe -H %s ...' % ip_string)

rawDescription: How to strip an individual list item (string)?

description: Strip an individual list item (string)


code: print("... you guessed {}, and ... was {}!".format(math_guess, math_score))

rawDescription: Extra spaces when printing

description: Extra spaces when printing


code:
#!/usr/bin/env python
from subprocess import check_output

tag = check_output('dicom_hinfo -tag aaaa,bbbb filename.dcm output:fgre'.split(),
                   universal_newlines=True).strip()

rawDescription: How to call command line command (AFNI command)?

description: Call command line command (AFNI command)


code:
# create a sinusoid
F=4 ## select the frequency -- use an even integer to minimize spectral "leakage"
new_image = np.ones([X,Y])
for y in xrange(Y):
   for x in xrange(X):
      new_image[y][x] = sin(x/float(X)*pi*F)*sin(y/float(Y)*pi*F)

rawDescription: Taking fourier transform after phase shift


rawDescription: Get list of attributes in class

description: Get list of attributes in class


code:
import os
import pandas as pd

# Get the home directory (not recommended, work somewhere else)
directory = os.environ["HOME"]
# Read all files in directory, filter out non-csv
files = [os.path.join(directory, f)
         for f in os.listdir(directory) if f.endswith(".csv")]
# Make list of tuples [(filename, sum)]
sums =  [(filename, pd.read_csv(filename)["Value"].sum())
         for filename in files ]
# Make a dataframe
df = pd.DataFrame(sums, columns=["filename", "sum"])
df.to_csv(os.path.join(directory, "files_with_sum.csv"))

rawDescription: Iterate a simple calculation in Pandas across multiple files


code:
import random

while True:

    Which_Dice= input("What dice do you want? 4,6 or 12")

    if input(Which_Dice)!=("4","6","12"):
        print("Please input the number 4,6 or 12")

    elif int(Which_Dice)== 4:
        print(int(Which_Dice), "sided dice thrown", "score",random.randint(0,5))

    elif int(Which_Dice)== 6:
        print(int(Which_Dice), "sided dice thrown", "score",random.randint(0,7))

    elif int(Which_Dice)==12:
        print(int(Which_Dice), "sided dice thrown", "score",random.randint(0,13))

rawDescription: How Do I return to the top of the loop Python


code: re.search(r'(?<!function) Foo\(', line)

rawDescription: Regular expression: find function calls

description: Regular expression: find function calls


code:
import mock
from boto.s3.key import Key

def mock_s3_key(func):
    def _mock_s3_key(*args, **kwargs):
        with mock.patch.object(Key, 'set_contents_from_filename', return_value=None):
            return func(*args, **kwargs)
    return _mock_s3_key

class YourTest(TestCase):

    @mock_s3_key
    def test_save_file_to_s3(self):
        # test code here
        pass

rawDescription: mocking set_contents_from_filename of boto in python

description: Mocking set_contents_from_filename of boto in python


code:
def parse(data):
    items = [i.strip() for i in data.split('|')]
    newitems = []
    nest = [False]
    for item in items:
        if item.startswith('{{'):
            if item.startswith('{{Ulist'):
                nest.append(True)
            else:
                nest.append(False)
            newitems.append(item)
        else:
            if item.startswith('item') and nest[-1]:
                newitems.append('U' + item)
            else:
                newitems.append(item)
        if item.endswith('}}'):
            nest.pop()
    return ' | '.join(newitems)

rawDescription: Regex to match special list items II

description: Regex to match special list items II


code:
from __future__ import print_function, division

import math

def LinearSineSweep(f, fStart, fEnd, samplingTime, samplesPerSecond,
                    t0=0, phi0=0):
    nValues = int(samplesPerSecond * samplingTime)
    actualSamplingTime = nValues / samplesPerSecond
    for i in range(0, nValues):
        delta = float(i) / nValues
        t = actualSamplingTime * delta
        phase = 2 * math.pi * t * (fStart + (fEnd - fStart) * delta / 2)
        value = math.sin(phase + phi0)
        # Write the time and sample value to the output...
        print(t0 + t, value, file=f)
    phase = 2 * math.pi * actualSamplingTime * (fStart + (fEnd - fStart) / 2)
    return t0 + actualSamplingTime, phi0 + phase

if __name__ == "__main__":
    with open('out.csv', 'w') as f:
        t, phi = LinearSineSweep(f, 0, 1700, 0.001, 44100)
        t, phi = LinearSineSweep(f, 1700, 1700, 0.001, 44100, t, phi)
        t, phi = LinearSineSweep(f, 1700, 100, 0.001, 44100, t, phi)

    import numpy as np
    import matplotlib.pyplot as plt

    tvals, v = np.loadtxt('out.csv', unpack=True)
    plt.figure(figsize=(10, 4))
    plt.plot(tvals, v)
    plt.grid()
    plt.show()

rawDescription: calculate multiple sine sweeps one after another

description: Calculate multiple sine sweeps one after another


code:
{
    "copy" : {{ dumps(self.copy()) | safe }},
    "title" : {{ dumps(self.title()) | safe }}
}

rawDescription: Rendering jinja2 blocks as json

description: Rendering jinja2 blocks as json


code:
import re

s = 'abccba'
ss = 'facebookgooglemsmsgooglefacebook'
p = 'xyzzyx'

def match(s, p):
    nr = {}
    regex = []
    for c in p:
        if c not in nr:
            regex.append('(.+)')
            nr[c] = len(nr) + 1
        else:
            regex.append('\\%d' % nr[c])
    return bool(re.match(''.join(regex) + '$', s))

print(match(s, p))
print(match(ss, p))

rawDescription: Python: Find pattern in a string

description: Python: Find pattern in a string


code:
import tkinter as tk

class NumberBox():
    def __init__(self, root,  display_number):
        self.number_label = tk.Label(root, text=display_number)
        self.number_label.pack()

    def changeNumber(self, display_number):
        self.number_label.config(text=display_number)

class NumberBoxesList():
    def __init__(self, root,  start_number = 5):
        self.number = start_number
        self.root = root
        self.boxes = []
        tk.Button(root, text="Add Class", command= self.addBox).pack()
        tk.Button(root, text="Number UP", command=lambda: self.change_number("add")).pack()
        tk.Button(root, text="Number DOWN", command=lambda: self.change_number("subtract")).pack()

    def addBox(self):
        self.boxes.append(NumberBox(self.root,  self.number))

    def change_number(self,  operation):
        if operation == "add":
            self.number += 1
        if operation == "subtract":
            self.number -= 1
        for box in self.boxes:
            box.changeNumber(self.number)

root = tk.Tk()
boxList = NumberBoxesList(root)

for _ in range(5):
    boxList.addBox()

root.mainloop()

rawDescription: Python Tkinter: How do I avoid global variables in a changing class?


code:
SUBS = [
  ('[. ]', '_'),
  ('__+', '_'),
  ('[][)(}{]',  ''),
  ('[-_]([^-_]+)$',  r'.\1'),
]

def normalize(name):
    name = name.lower()
    for pattern, replacement in SUBS:
        name = re.sub(pattern, replacement, name)
    return name

rawDescription: Multiple regex substitutions

description: Multiple regex substitutions


code:
import sqlite3
class MyConnect(sqlite3.Connection):
    def cursor(self):
        return super(MyConnect, self).cursor(MyCursor)

class MyCursor(sqlite3.Cursor):
    def mymethod1(self, argv):
        print('Got here')

conn = sqlite3.connect(':memory:', factory=MyConnect)
print(conn)
# <__main__.MyConnect object at 0x90db66c>

cursor = conn.cursor()
print(cursor)
# <__main__.MyCursor object at 0x90d19dc>

cursor.mymethod1('foo')
# Got here

rawDescription: Python: How to successfully inherit Sqlite3.Cursor and add my customized method


code:
def FindProjectSubfolders(masterPath, projectSubfolders):
    for currRoot, dirnames, filenames in os.walk(masterPath):
        # check if have a project subfolder
        foundMatch = False
        for dirname in dirnames:
            for projectSubfolder in projectSubfolders:
                if (dirname == projectSubfolder):
                    foundMatch = True;
                    break
        if (foundMatch == True):
            # what goes here to stop traversing "currRoot"
            # and iterate to the next one?
            dirnames[:] = []  # replace all indices in `dirnames` with the empty list

rawDescription: How to stop traversing current root and iterate to the next one

description: Stop traversing current root and iterate to the next one


code:
from django.db.models import Count

Author.objects.annotate(article_count=Count('articles'))

rawDescription: Correct way to count for a foreign key model in Django template


code:
import copy

def step(G,V1,V2):
    tempcut=sys.maxint
    for k in range(min(len(V1),len(V2))):
        V1, V2, C=Switch(G,V1,V2,k)
        print(C)
        if C<tempcut:
           tempcut=C
           best1=copy.copy(V1) #or : best1= V1[:] as Serge suggested
           best2=copy.copy(V2) #or : best2= V2[:] as Serge suggested
           print('enter')
           print(tempcut)
           print(best1)
           print(best2)
    return best1, best2, tempcut,

rawDescription: Problems with wrong values "return"-ed in Python ( a deep-copy issue )


code:
interp_data = interpolate.interp1d(data[:,0], data[:,1:], axis=0, kind='cubic')
data_int = np.zeros((len(new_x),len(data[0])))
data_int[:,0] = new_x
data_int[:,1:] = interp_data(new_x)
data_int

rawDescription: How can I use scipy.interpolate.interp1d to interpolate multi Y arrays using the same X array?

description: Use scipy.interpolate.interp1d to interpolate multi Y arrays using the same X array


code:
class Code(db.Model):
    __searchable__ = ['scramble']

    id = db.Column(db.Integer, primary_key = True)
    scramble = db.Column(db.String(64))
    country_id = db.Column(db.Integer, db.ForeignKey('country.id'))

    def __repr__(self):
        return '<%r>' % (self.scramble)

rawDescription: Flask-SQLAlchemy db.commit() changes value of field


code:
class A(object):
    pass
class B(A):
    pass
import inspect
inspect.getmro(B)

rawDescription: Python: List all base classes in a hierarchy of given class


code:
a = """<record>
    <player_birthday>1979-09-23</player_birthday>
    <player_name>Orene Ai'i</player_name>
    <player_team>Blues</player_team>
    <player_id>453</player_id>
    <player_height>170</player_height>
    <player_position>F&W</player_position>   <---- a '&' here.
    <player_weight>75</player_weight>
</record>"""

from xml.etree import ElementTree as ET
x = ET.fromstring(a)

rawDescription: How to validate xml using python without third-party libs?

description: Validate xml using python without third-party libs


code:
a = numpy.zeros( (5, 5) )
a[0,0] = numpy.NaN
a[3,3:5] = numpy.NaN
a
labels, num_labels = scipy.ndimage.measurements.label ( numpy.isnan( a ) )
labels
num_labels

rawDescription: How to count the number of holes in a numpy 2D grid?

description: Count the number of holes in a numpy 2D grid


code:
import colorsys

class Level(object):

    def __init__(self, minv, maxv, gamma):
        self.minv= minv/255.0
        self.maxv= maxv/255.0
        self._interval= self.maxv - self.minv
        self._invgamma= 1.0/gamma

    def new_level(self, value):
        if value <= self.minv: return 0.0
        if value >= self.maxv: return 1.0
        return ((value - self.minv)/self._interval)**self._invgamma

    def convert_and_level(self, band_values):
        h, s, v= colorsys.rgb_to_hsv(*(i/255.0 for i in band_values))
        new_v= self.new_level(v)
        return tuple(int(255*i)
                for i
                in colorsys.hsv_to_rgb(h, s, new_v))

def level_image(image, minv=0, maxv=255, gamma=1.0):
    """Level the brightness of image (a PIL.Image instance)
    All values ≤ minv will become 0
    All values ≥ maxv will become 255
    gamma controls the curve for all values between minv and maxv"""

    if image.mode != "RGB":
        raise ValueError("this works with RGB images only")

    new_image= image.copy()

    leveller= Level(minv, maxv, gamma)
    levelled_data= [
        leveller.convert_and_level(data)
        for data in image.getdata()]
    new_image.putdata(levelled_data)
    return new_image

rawDescription: Doing the same as ImageMagick's "-level" in python / PIL?


code:
item.delete()
items = table.objects.order_by('order')
count =0
for element in items:
  element.order = count
  element.save()
  count=count+1

rawDescription: Auto Increment Field in Django/Python

description: Auto Increment Field in Django/Python


code:
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

gen = np.random.RandomState(0)
n_samples = 1500
n_features = 3
n_clusters = 5

# original data
X, t = make_blobs(n_samples, n_features, n_clusters, random_state=gen)

# with 30% missing values
Xm = np.where(gen.rand(*X.shape) > 0.3, X, np.nan)

# initially set missing values to column mean
valid = np.isfinite(Xm)
mu = np.nanmean(Xm, 0, keepdims=1)
X_hat = np.where(valid, Xm, mu)

for ii in range(10):

    # perform clustering on filled-in data
    cls = KMeans(n_clusters, n_jobs=-1)
    labels_hat = cls.fit_predict(X_hat)

    # update missing values based on cluster centroids
    X_hat[~valid] = cls.cluster_centers_[labels_hat][~valid]

# clustering on original data (without missing values)
cls = KMeans(n_clusters, n_jobs=-1)
labels = cls.fit_predict(X)

# plot results
fig, ax = plt.subplots(1, 2, subplot_kw={'projection':'3d', 'aspect':'equal'})

ax[0].scatter3D(X[:, 0], X[:, 1], X[:, 2], c=labels, cmap='gist_rainbow')
ax[1].scatter3D(X_hat[:, 0], X_hat[:, 1], X_hat[:, 2], c=labels,
                cmap='gist_rainbow')

ax[0].set_title('Original data')
ax[1].set_title('Imputed (30% missing values)')

fig.tight_layout()

rawDescription: python scikit-learn clustering with missing data

description: Python scikit-learn clustering with missing data


code:
from itertools import takewhile, dropwhile

test = ['3 Silver', '3 Oct', '4AD', '99 Reese', '1991', 'alpha', 'beta']

items = dict()
for word in test:
    ordlist  = []
    ## prenumber will be zero if there are no numerical characters
    prenumber = int(''.join(list(takewhile(lambda i: i.isdigit() , word))) or 0)
    ## setting words that start with alpha characters to have infinity as
    ## first item. This puts them at the end of the list for sorting.
    ordlist.append(prenumber or float("inf"))
    ordlist.extend((ord(ch) for ch in dropwhile(lambda i: i.isdigit(), word)))
    items[word] = ordlist

### sort dictionary by value
s = sorted(zip(items.values(), items.keys()))
print(s)
## [([3, 32, 79, 99, 116], '3 Oct'),
##    ([3, 32, 83, 105, 108, 118, 101, 114], '3 Silver'),
##    ([4, 65, 68], '4AD'),
##    ([99, 32, 82, 101, 101, 115, 101], '99 Reese'),
##    ([1991], '1991'),
##    ([inf, 97, 108, 112, 104, 97], 'alpha'),
##    ([inf, 98, 101, 116, 97], 'beta')]

test_sorted = [e[1] for e in s]
## ['3 Oct', '3 Silver', '4AD', '99 Reese', '1991', 'alpha', 'beta']

rawDescription: Sorting alphanumeric sequences is not correct. How can I improve it?


rawDescription: Should pandas dataframes be nested?

description: Should pandas dataframes be nested


code:
def remove_accent(n):
    n_unicode=unicode(n,"UTF-8")
    listn = list(n_unicode)
    for i in range(len(listn)):
        if listn[i] == u'ó':
            listn[i] = 'o'.encode('utf-8')
        else:
            listn[i]=listn[i].encode('utf-8')
    return listn

rawDescription: Is there any way to force ipython to interpret utf-8 symbols?


code:
from re import search as other, match
match  # The name match refers to re.match
other  # The name other refers to re.search
search  # The name search is not defined because it was imported as other

rawDescription: Import with a comma after the as

description: Import with a comma after the as


code:
shifted = df.groupby(level="grp").shift(-1)
df.join(shifted.rename(columns=lambda x: x+"_lag"))

rawDescription: Groupby and lag all columns of a dataframe?


code:
a=u"""\\u003cdiv class=\\"pas status fcg\\">Loading...\\u003c\\/div>
\\u003c\\/div>\\u003cdiv class=\\"uiTypeaheadView fbChatBuddyListTypeaheadView dark hidden_elem\\" id=\\"u971289_14\\">\\u003c\\/div>
\\u003c\\/div>\\u003c\\/div>\\u003cdiv class=\\"fbNubFlyoutFooter\\">
\\u003cdiv class=\\"uiTypeahead uiClearableTypeahead fbChatTypeahead\\" id=\\"u971289_15\\">
\\u003cdiv class=\\"wrap\\">\\u003clabel class=\\"clear uiCloseButton\\" for=\\"u971291_21\\">
"""
print(a.decode('unicode_escape')).replace('\\/', '/')

rawDescription: How to translate/convert unicode escaped < and > in a read HTML doc?

description: Translate/convert unicode escaped < and > in a read HTML doc


code: ratings_5K = LL_features_SCD_min[['id_column_name']].join(ratings_33K, on='id_column_name', how='left')

rawDescription: Find particular rows in Graphlab or Python


code:
def get_object_votes(self, obj, all=False):
    """
    Get a dictionary mapping vote to votecount
    """
    object_id = obj._get_pk_val()
    ctype = ContentType.objects.get_for_model(obj)
    queryset = self.filter(content_type=ctype, object_id=object_id)

    if not all:
        queryset = queryset.filter(is_archived=False) # only pick active votes

    queryset = queryset.values('vote')
    queryset = queryset.annotate(vcount=Count("vote")).order_by()

    votes = {}

    for count in queryset:
        votes[count['vote']] = count['vcount']

    return votes

rawDescription: map raw sql to django orm

description: Map raw sql to django orm


code: data = [randint(50, 99) for i in range(100)]

rawDescription: Trying to create a random list

description: Trying to create a random list


code:
from sqlalchemy import create_engine, Column, String, Integer
from sqlalchemy.orm import sessionmaker, configure_mappers
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.declarative import AbstractConcreteBase

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

class ClientGroupBase(AbstractConcreteBase, Base):
    pass

class ClientGroup1(ClientGroupBase):
    __tablename__ = 'client_group1'
    # __table_args__ = {'schema': 'clients'}
    __mapper_args__ = {
        'polymorphic_identity': 'client_group1',
        'concrete': True,
    }

    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    email = Column(String(32))

class ClientGroup2(ClientGroupBase):
    __tablename__ = 'client_group2'
    # __table_args__ = {'schema': 'clients'}
    __mapper_args__ = {
        'polymorphic_identity': 'client_group2',
        'concrete': True,
    }

    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    email = Column(String(32))

def _test_model():
    # generate classes for all tables
    Base.metadata.create_all()
    print('-'*80)

    # configure mappers (see documentation)
    configure_mappers()
    print('-'*80)

    # add some test data
    session.add(ClientGroup1(name="name1"))
    session.add(ClientGroup1(name="name1"))
    session.add(ClientGroup2(name="name1"))
    session.add(ClientGroup2(name="name1"))
    session.commit()
    print('-'*80)

    # perform a query
    q = session.query(ClientGroupBase).all()
    for r in q:
        print(r)

if __name__ == '__main__':
    _test_model()

rawDescription: SQLAlchemy mapping a table union to a class


code:
from random import choice
choice([-1, 1])
choice([-1, 1])
choice([-1, 1])
choice([-1, 1])
choice([-1, 1])
choice([-1, 1])

rawDescription: generate random -1 or 1 values in a single line of code

description: Generate random -1 or 1 values in a single line of code


code: np.multiply(a, b[:, np.newaxis])

rawDescription: numpy: multiply arrays rowwise

description: Numpy: multiply arrays rowwise


code:
import numpy as np
from numpy import loadtxt
from operator import itemgetter

s = loadtxt("second.txt", delimiter=" ", unpack=False)
ni = loadtxt("newindex1.txt", delimiter=" ", unpack=False)

index = {}

for m,n,v in s:
    index [(m,n)] = v

for i,l in ni:
    key = (i,l)

    if key in index.keys ():
        print (i, l, index [key])

rawDescription: Sorting one array by another in Python

description: Sorting one array by another in Python


code:
ts1
ts2
ts1.corr(ts2)

rawDescription: Correlation of Two Variables in a Time Series in Python?


code:
import inspect
inspect.getargspec(func)

rawDescription: Print out list of function parameters in Python


code:
from tkinter import *
from tkinter.ttk import *

class ButtonApp(Frame):
    """Container for the buttons."""

    def __init__(self, master=None):
        """Initialize the frame and its children."""

        super().__init__(master)
        self.createWidgets()

        # configure the frame's resize behaviour
        master.columnconfigure(0, weight=1)
        master.rowconfigure(0, weight=1)
        self.grid(sticky=(N,S,E,W))

        # configure resize behaviour for the frame's children
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        # bind to window resize events
        self.bind('<Configure>', self.resize)

    def createWidgets(self):
        """Make the widgets."""

        # this button mutates
        self.mutantButton = Button(self, text='Press Me',
                                   style='10.TButton')
        self.mutantButton.grid(column=0, row=0, sticky=(N,S,E,W))
        self.mutantButton['command'] = self.mutate

        # an ordinary quit button for comparison
        self.quitButton = Button(self, text='Quit', style='TButton')
        self.quitButton.grid(column=0, row=1, sticky=(N,S,E,W))
        self.quitButton['command'] = self.quit

    def mutate(self):
        """Rotate through the styles by hitting the button."""

        style = int(self.mutantButton['style'].split('.')[0])
        newStyle = style + 5
        if newStyle > 50: newStyle = 10
        print('Choosing font '+str(newStyle))
        self.mutantButton['style'] = fontStyle[newStyle]

        # resize the frame

        # get the current geometries
        currentGeometry = self._root().geometry()
        w, h, x, y = self.parseGeometry(currentGeometry)
        reqWidth = self.mutantButton.winfo_reqwidth()
        reqHeight = self.mutantButton.winfo_reqheight()

        # note assume height of quit button is constant at 20.
        w = max([w, reqWidth])
        h = 20 + reqHeight
        self._root().geometry('%dx%d+%d+%d' % (w, h, x, y))

    def parseGeometry(self, geometry):
        """Geometry parser.
        Returns the geometry as a (w, h, x, y) tuple."""

        # get w
        xsplit = geometry.split('x')
        w = int(xsplit[0])
        rest = xsplit[1]

        # get h, x, y
        plussplit = rest.split('+')
        h = int(plussplit[0])
        x = int(plussplit[1])
        y = int(plussplit[2])

        return w, h, x, y

    def resize(self, event):
        """Method bound to the <Configure> event for resizing."""

        # get geometry info from the root window.
        wm, hm = self._root().winfo_width(), self._root().winfo_height()

        # choose a font height to match
        # note subtract 30 for the button we are NOT scaling.
        # note we assume optimal font height is 1/2 widget height.
        fontHeight = (hm - 20) // 2
        print('Resizing to font '+str(fontHeight))

        # calculate the best font to use (use int rounding)
        bestStyle = fontStyle[10] # use min size as the fallback
        if fontHeight < 10: pass # the min size
        elif fontHeight >= 50: # the max size
            bestStyle = fontStyle[50]
        else: # everything in between
            bestFitFont = (fontHeight // 5) * 5
            bestStyle = fontStyle[bestFitFont]

        # set the style on the button
        self.mutantButton['style'] = bestStyle

root = Tk()
root.title('Alice in Pythonland')

# make a dictionary of sized font styles in the range of interest.
fontStyle = {}
for font in range(10, 51, 5):
    styleName = str(font)+'.TButton'
    fontName = ' '.join(['helvetica', str(font), 'bold'])
    fontStyle[font] = styleName
    Style().configure(styleName, font=fontName)

# run the app
app = ButtonApp(master=root)
app.mainloop()
root.destroy()

rawDescription: Python3: How to dynamically resize button text in tkinter/ttk?


code:
# write the header to the file only
pd.DataFrame(data=[df.columns]).to_csv("outfile.csv", header=False, index=False)

# now replace header
types_header_for_insert = list(df.columns.values)
for idx, val in enumerate(df.columns.values):
    if df[val].dtype == 'float64':
        types_header_for_insert[idx] = 'REAL'

    elif self.grouped[val].dtype == 'int64':
        types_header_for_insert[idx] = 'INTEGER'

    else:
        types_header_for_insert[idx] = 'STRING'

df.columns = types_header_for_insert

# append the whole df with new header
df.to_csv("outfile.csv", mode="a", float_format='%.3f', index=False)

rawDescription: How to insert a second header row in pandas df for csv write

description: Insert a second header row in pandas df for csv write


code:
while True:
    name1 = input("A male name (protagonist): ")
    if name1.endswith(('ly', 's')):
        print("Sorry mate, this doesn't seem to be a proper noun. Try it again.")
        continue
    break

print("Input name is:", name1)

rawDescription: How to loop on Python 3.4.2?

description: Loop on Python 3.4.2


code:
from itertools import count
from collections import defaultdict

def create_lookup_list(data, domains):
    domain_keys = defaultdict(lambda:defaultdict(count().next))
    out = []
    for row in data:
        out.append(tuple(domain_keys[dom][val] for val, dom in zip(row, domains)))
    lookup_table = dict((k, sorted(d, key=d.get)) for k, d in domain_keys.items())
    return out, lookup_table

rawDescription: Convert list of objects to a list of integers and a lookup table


code:
pattern = r"(([0-9]+ ?)(%|percent|per cent))"
print(re.sub(pattern, r"<b>\1</b>", myInput))

rawDescription: Add tag around matches in Python

description: Add tag around matches in Python


code:
import urlparse
import scrapy

from scrapy.http import Request

class pwc_tax(scrapy.Spider):
    name = "pwc_tax"

    allowed_domains = ["www.pwc.com"]
    start_urls = ["http://www.pwc.com/us/en/tax-services/publications/research-and-insights.html"]

    def parse(self, response):
        for href in response.css('div#all_results h3 a::attr(href)').extract():
            yield Request(
                url=response.urljoin(href),
                callback=self.parse_article
            )

    def parse_article(self, response):
        for href in response.css('div.download_wrapper a[href$=".pdf"]::attr(href)').extract():
            yield Request(
                url=response.urljoin(href),
                callback=self.save_pdf
            )

    def save_pdf(self, response):
        path = response.url.split('/')[-1]
        self.logger.info('Saving PDF %s', path)
        with open(path, 'wb') as f:
            f.write(response.body)

rawDescription: Using Scrapy to to find and download pdf files from a website


code:
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [10,20,30,40]
Temp = [100,200,300,400]

plt.scatter(x,y,c=Temp)
plt.colorbar()
plt.show()

rawDescription: Making a simple colorbar

description: Making a simple colorbar


rawDescription: Display floating point number in decimal form in Python?


code:
pid = os.fork()
if pid == 0:
     s = Popen('cat', stdin=PIPE, stdout=DEVNULL, stderr=DEVNULL)
     s.stdin.write(b'helloworld')
     s.stdin.close()
     s.wait()
     sys.exit()
time.sleep(1000)

rawDescription: Backgrounding a process after writing to its stdin


code: arr = [line.split(',') for line in open('./urls-eu.csv')]

rawDescription: How to read lines from a file into a multidimensional array (or an array of lists) in python

description: Read lines from a file into a multidimensional array (or an array of lists) in python


rawDescription: python reg exp: how to delete a field delimited by [ and ] from a string

description: Python reg exp: how to delete a field delimited by [ and ] from a string


code:
import urllib2
import string
import itertools
import os

chars, filenames = string.lowercase, []
for r in itertools.product(chars, chars, chars):
    filenames.append(r[0] + r[1] + r[2])

# filenames will now contain an array like
# [aaa, aab, aac, aad, aae, ... , zzx, zzy, zzz]

print("Number of filenames: " + str(len(filenames)))

# Uncomment the line below for testing before you run it for all filenames
# filenames = ['eng']

# Change your directory relative to current directory here
save_to = os.path.abspath("pdfs/")

for f in filenames:
    url = 'http://www.ohchr.org/EN/UDHR/Documents/UDHR_Translations/' + f + '.pdf'
    print('Requesting: ' + url)

    # Setup urllib2 Request
    req = urllib2.Request(url)
    req.add_header('User-Agent', 'some fake agent string')
    req.add_header('Referer', 'fake referrer')

    # Get status code first and if status is 200 get response
    try:
        response = urllib2.urlopen(req, timeout=4)
        status = response.getcode()
        # If 200 status found
        if status == 200:
            print('PDF File found at: ' + f + ' ' + url)
            print('Saving..')
            # Write in Binary mode as files are PDF
            f = open(save_to + '/' + f + '.pdf', 'wb')
            f.write(response.read())
            f.close() # Dont forget to close the file
            print('Saved.')
        else:
            print('Status was not 200 OK: ' + f + ' ' + url)
    except urllib2.HTTPError: # 404 error
        print('No file found: ' + f + ' ' + url)

rawDescription: How do I retrieve every file with a HTTP 200 response code in a certain directory with Python

description: Retrieve every file with a HTTP 200 response code in a certain directory with Python


code:
import re

from django import template
from django.core.urlresolvers import get_resolver, get_urlconf

register = template.Library()

@register.simple_tag
def data_url(urlname):

    urlconf = get_urlconf()
    resolver = get_resolver(urlconf)

    if urlname not in resolver.reverse_dict:
        return ""

    url = resolver.reverse_dict[urlname][0][-1][0]
    url = re.sub(r'%\((.*?)\)s', '{{ \g<1> }}', url)

    return "/%s" % url

rawDescription: Is there a generic way to create an URL template in Django?


code:
m1 = M1.objects.filter(title__istartswith=q)
m2 = M2.objects.filter(title__istartswith=q)
results = [x.title for x in m1] + [x.title for x in m2]

rawDescription: Searching from multiple models (jquery autocomplete)


code:
import os
files = os.listdir("path/to/files")
for src in files:
    dst = src.replace('S1', 'S2')
    os.rename(src, dst)

rawDescription: PYTHON - How to change one character in many file names within a directory


code:
def delete():
    if request.args(0) == 'templates':
        if db.templates[request.args(1)].id == auth.user_id:
            db(db.templates.id ==  request.args(1)).delete()
            return dict(form=redirect(URL('templates')))
    return dict(form=redirect(URL('index')))

rawDescription: web2py delete query

description: Web2py delete query


code: typ, data = imap_server.search(None, '(SUBJECT "Whatever you are searching for")')

rawDescription: python imaplib parsing gmail

description: Python imaplib parsing gmail


rawDescription: How to check if a numeric value is an integer?

description: Check if a numeric value is an integer


code:
def find_int(xml, text):
    found = xml.findtext(text)
    return int(found) if found else None

row['discoveryyear'] = find_int(planet, "./discoveryyear")

rawDescription: Cast value if it is not None in python

description: Cast value if it is not None in python


code:
import matplotlib.pylab as plt
import random
import matplotlib.gridspec as gridspec

random.seed(20)

#create x-axis of my data
x1 = range(0,10) #different range than the next one
x2 = range(1,9)

#create data (just random data corresponding the x1,x2)
data1 = [random.random() for i in x1]
data2 = [random.random()*1000 for i in x2]

gs = gridspec.GridSpec(2,1)
fig = plt.figure()

#first plot
ax = fig.add_subplot(gs[0])
ax.plot(x1,data1)
ax.set_ylabel(r'Label One', size =16)
ax.get_yaxis().set_label_coords(-0.1,0.5)
plt.tick_params(
    axis='x',          # changes apply to the x-axis
    labelbottom='off') # labels along the bottom edge are off

#second plot
ax = fig.add_subplot(gs[1], sharex=ax)
ax.plot(x2,data2)
ax.set_ylabel(r'Label Two', size =16)
ax.get_yaxis().set_label_coords(-0.1,0.5)

plt.show()

rawDescription: Python: Matplotlib: Vertically aligned plots in matplotlib


code:
from __future__ import print_function
with open('filename', 'w') as f:
    print('some text', file=f)

rawDescription: how to print directly to a text file in both python 2.x and 3.x?

description: Print directly to a text file in both python 2.x and 3.x


code:
edits = [(search0, replace0), (search1, replace1), (search2, replace2)] # etc.
for search, replace in edits:
    s = s.replace(search, replace)

rawDescription: similar function to php's str_replace in python?

description: Similar function to php's str_replace in python


code: [a for a in SearchList if a[:-7] in BaseList]

rawDescription: Searching a lists items against a another lists subset items


code:
class http_connection(httplib.HTTPConnection):
    def __init__(self, dns_server, *args, **kwargs):
        httplib.HTTPConnection.__init__(self, *args, **kwargs)
        self.resolv = resolver(dns_server, self.source_address)
    def connect(self):
        self.sock = socket.create_connection((self.resolv(self.host), self.port), self.timeout, self.source_address)
...
x = http_connection(args.dns_server, '%s:%d' % (args.host, args.port), source_address = (args.source_address, 0))

rawDescription: avoid RDNS lookup for an HTTP request

description: Avoid RDNS lookup for an HTTP request


code:
sqlite3.execute("CREATE TEMPORARY TABLE items(x)")
sqlite3.executemany("INSERT INTO items VALUES (?)", items);
sqlite3.execute("SELECT ... WHERE item in items")
...
sqlite3.execute("DROP TABLE items")

rawDescription: sqlite + python using a WHERE ... IN as a parameter > 999 --- or just escape

description: Sqlite + python using a WHERE ... IN as a parameter > 999 --- or just escape


code:
import re
strs="{foo} spam eggs {bar}"
re.findall(r"{(\w+)}",strs)

rawDescription: How can I find all placeholders for str.format in a python string using a regex?

description: Find all placeholders for str.format in a python string using a regex


code:
class State:
    instance_count = 0  # as an example, this is now a static variable counting instances.

    def __init__(self, name):
        self.name = name      # name is now a member variable
        self.transitions = {} # transitions is now a member variable
        State.instance_count += 1

    def addTransition(self, symbol, transition):
        self.transitions[symbol] = transition

    def __del__(self):
        State.instance_count -= 1

rawDescription: Value updating to multiple dictionaries

description: Value updating to multiple dictionaries


code:
import re
re.findall(r'(\?(.+?))\b', 'some text ?var etc')

rawDescription: Regex not working normally in python

description: Regex not working normally in python


code:
def asarray(a, dtype=None, order=None):
    return array(a, dtype, copy=False, order=order)

rawDescription: Numpy - array vs asarray

description: Numpy - array vs asarray


code:
class EmployeeAdmin(admin.ModelAdmin):
        search_fields = ['name']
        list_display = ('name','id','dob','bill','mobile','email')
        list_filter = ('bill','proj')
      # readonly_fields=('id',)

        def get_readonly_fields(self, request, obj=None):
            if obj: # editing an existing object
                return self.readonly_fields + ('id',)
            return self.readonly_fields

rawDescription: primary key should be read only in django admin. But during new entry insert it should be visible

description: Primary key should be read only in django admin. But during new entry insert it should be visible


code:
for event in pygame.event.get():
    if event.type == MOUSEBUTTONDOWN :
        x, y = event.pos
        for button in buttons:
            if button.rect.collidepoint(x, y):
                print("play sound here.")

                # or, if button handles on clicking, by a defined function:
                button.click()

description: Pygame.MOUSEBUTTONDOWN


code:
data = defaultdict(set)
data['a'].add(1)
data['b'].add(2)
data['b'].add(3)
min(data.items(), key=lambda x: min(x[1]))
min(data.items(), key=lambda x: max(len(x[1])))

rawDescription: Returning Key matching Value -- Adding Constraint


code:
def view1(request):

    if request.POST:
        request.session['li'] = [form_value1,form_value2]
        return HttpResponse()

    return render(request,'form.html',{})

def view2(request):

    li = request.session['li']

    ...

rawDescription: how to use one variable second time in different view function in django

description: Use one variable second time in different view function in django