code:
import wx
import wx.lib.agw.foldpanelbar as fpb

class frame(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        self.text_ctrl_1=wx.TextCtrl(self, -1, size=(400, 100),
                                     style=wx.TE_MULTILINE)
        self.fpb = fpb.FoldPanelBar(self, -1,
            style=fpb.FPB_HORIZONTAL|fpb.FPB_DEFAULT_STYLE)
        self.fold_panel = self.fpb.AddFoldPanel("Thing")
        self.thing = wx.TextCtrl(self.fold_panel, -1, size=(400, -1),
                                 style=wx.TE_MULTILINE)
        self.fpb.AddFoldPanelWindow(self.fold_panel, self.thing)
        self.fpb.Bind(fpb.EVT_CAPTIONBAR, self.onCaptionBar)
        self.sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer_1.Add(self.text_ctrl_1, 1, wx.EXPAND)
        self.sizer_1.Add(self.fpb, 0, wx.EXPAND)
        self.SetSizer(self.sizer_1)
        self.ResizeFPB()

    def onCaptionBar(self, event):
        event.Skip()
        wx.CallAfter(self.ResizeFPB)

    def ResizeFPB(self):
        sizeNeeded = self.fpb.GetPanelsLength(0, 0)[2]
        self.fpb.SetMinSize((sizeNeeded, self.fpb.GetSize()[1]))
        self.Fit()

app = wx.App(0)
f = frame(None)
f.Show()
app.MainLoop()

rawDescription: WxPython: FoldPanelBar not really folding


code:
img = QImage("/tmp/example.png")
buffer = QBuffer()
buffer.open(QIODevice.ReadWrite)
img.save(buffer, "PNG")

strio = cStringIO.StringIO()
strio.write(buffer.data())
buffer.close()
strio.seek(0)
pil_im = Image.open(strio)

rawDescription: Convert PyQt to PIL image

description: Convert PyQt to PIL image


code:
arr = np.arange(6).reshape((2, 3))
desired_shape = np.array((5, 8))

pads = tuple((0, i) for i in (desired_shape-arr.shape))
# pads = ((0, add_rows), (0, add_columns), ...)
np.pad(arr, pads, mode="wrap")

rawDescription: numpy.tile a non-integer number of times

description: Numpy.tile a non-integer number of times


code:
import subprocess
subprocess.check_output('ps -ef | grep something | wc -l', shell=True)

rawDescription: Python: how to get the final output of multiple system commands?


code:
def rolldice():
    while True:
        num_sides = input("Enter number of sides for die: ")
        num_rolls = input("Enter number of rolls for die: ")
        try:
            int(num_sides)
            int(num_rolls)
            break
        except ValueError:
            print("Enter an integer")

rawDescription: Python: If...and... not working as expected


code:
def get_initial_input():
    input_list = []
    input_list.append(int(input("How many assignments? ")))
    input_list.append(int(input("How many quizzes? ")))
    input_list.append(int(input("How many labs? ")))
    input_list.append(int(input("How many tests? ")))
    return input_list

def get_scores(s):
    return [ int(input("Give a score: ")) for x in s]
    #use list comprehensions

def main():

    input_list = get_initial_input()
    scores = get_scores(input_list)

    total = sum(scores)
    num = sum(input_list) # I am assuming this

    print("The sum is: "+str(total))
    if total > 0:
        print("The average is: "+str(total/num))

    if (total/num) > 100:
        print("You got extra credit!")

main()

rawDescription: How to pass multiple inputs from the user to a function?

description: Pass multiple inputs from the user to a function


rawDescription: Regular expression where first letter in a word is uppercase, and word is surrounded by _


code:
def myfunc(a, bret=False, cret=False):
   ...
   return (a,) + ((b,) if bret else ()) + ((c,) if cret else ())

rawDescription: return value in Python

description: Return value in Python


code:
import html2text
html = open("textFileWithHtml.txt")
f = html.read()
w = open("out.txt", "w")
w.write(html2text.html2text(f).encode('utf-8'))
html.close()
w.close()

rawDescription: Python - html2text write to file

description: Python - html2text write to file


code:
days = (datetime.strptime(max_date,"%Y-%d-%m")-datetime.strptime(max_date,"%Y-%d-%m")).days

colLastData.aggregate([
    { "$match": {
        "categoryId" : id_categoria,
        "dataDate": { "$lte":max_date, "$gte":min_date }
    }},
    { "$group": {
        "_id": {
            "$subtract": [
                { "$subtract": [ "$dataDate", datetime.datetime.utcfromtimestamp(0) ] },
                { "$mod": [
                    { "$subtract": [ "$dataDate", datetime.datetime.utcfromtimestamp(0) ] },
                    1000 * 60 * 60 * 24
                ]}
            ]
        }
    }},
    { "$group": {
        "_id": None,
        "count": { "$sum": 1 }
    }},
    { "$match": { "count": days } }
])

rawDescription: return true of false if any data exists between two dates in Mongo

description: Return true of false if any data exists between two dates in Mongo


code: from twisted.internet import reactor

rawDescription: How to get the 'reactor' when the twisted application is started by twistd?

description: Get the 'reactor' when the twisted application is started by twistd


code:
thresholds = numpy.linspace(0.7, 0.9, 21)

# freezing the precision of your floating point numbers
stringified_thresholds = [str(i) for i in thresholds]

thresholds_dict = dict.fromkeys(stringified_thresholds)

rawDescription: dict.fromkeys doesn't work as expected for floating point keys

description: Dict.fromkeys doesn't work as expected for floating point keys


code:
import csv
def csvWriter(filename, records):
  header = []
  for i in records:
    if len(i) < 1:
      records.remove(i)
  for i in records:
    for v in i:
      if v not in header:
        header.append(v)
  for i in records:
    if len(i) == 0:
      return '0 records processed.'
  test=open(filename,'w')
  dict_wr = csv.DictWriter(test,header,lineterminator='\n')
  dict_wr.writerow(dict(zip(header,header)))
  for i in records:
  # Adding in the **sorted** built-in fixed it
    dict_wr.writerow(dict(zip(header,sorted(i.values()))))
  test.close()
  return '%d records processed.' % len(records)

rawDescription: Pyschools Topic 13 Q 9 csv.writer

description: Pyschools Topic 13 Q 9 csv.writer


code:
import re
pattern = re.compile(r'\b(\d{1,2})\D(\d{1,2})\D(\d{1,4})\b')
def repl(match):
    return '{:0>2}-{:0>2}-{:0>4}'.format(*match.groups())
pattern.sub(repl, '1|1/2002')
pattern.sub(repl, '5|9-20')

rawDescription: date normalization using regular expressions

description: Date normalization using regular expressions


code:
with open("settings.py", 'r') as file:
    settings = file.readlines()

new_settings = []
for line in settings:
    if "INSTALLED APPS" in line:
        new_settings.append(line.replace("INSTALLED_APPS = (", "INSTALLED_APPS = (\n'%s'," % your_app_name))
    else:
        new_settings.append(line)
with open("settings.py", 'w') as file:
    file.write("".join(new_settings))

rawDescription: Python script to run Django commands

description: Python script to run Django commands


rawDescription: pandas: sorting observations within groupby groups

description: Pandas: sorting observations within groupby groups


code: canvas.itemconfig(J, text=Score)

rawDescription: Display/Update score on python using tkinter


code:
def generate_serial():
    return random.choice(string.ascii_uppercase) + random.choice(string.digits)

class CardFactory(DjangoModelFactory):
    class Meta:
        model = Card
    serial_number = FuzzyAttribute(generate_serial)

rawDescription: Create a mix of string and digit with Factory Boy in django


code:
while 1:
    for event in pygame.event.get():
        pygame.display.flip()
        if event.type == pygame.QUIT:sys.exit()
        pygame.time.wait(100)
        score = score + 1

rawDescription: Python/Pygame, Where do I put my pygame.time.wait loop?


code:
def prod(L):
    p = 1
    for i in range(len(L)):
        p *= L[i]
    return p

print(prod([1,2,3,4]))  # prints 24

rawDescription: Python 3+ - for in range loop, multiply, product, list NOT using mul or lambda or for in loop


rawDescription: Calculating cumulative minimum with numpy arrays


code:
sig = celery_app.signature('myapp.add_numbers', args=(1,2))
sig.delay()

rawDescription: Can a Celery task's definition and implementation be split?


code:
import re

filename = "xxx.txt"
with open(filename, "r") as f:
    content = f.read()
new_content = re.sub(r"(\w+)=Part-(1(_1)?|Default(_1)?)", r"\1=Part-1", content)
with open(filename, "w") as f:
    f.write(new_content)

rawDescription: how to replace a line containing certain string with a new modified line with python?

description: Replace a line containing certain string with a new modified line with python


code:
import json
import requests
from requests.auth import HTTPBasicAuth

posts = []
url = 'https://stream.twitter.com/1.1/statuses/sample.json'
r = requests.get(url, auth=('dhelm', '12345'), stream=True)
for line in r.iter_lines():
    try:
        posts.append(json.loads(line))
    except:
        pass

rawDescription: How to read a file that is continuously being updated by appending lines?

description: Read a file that is continuously being updated by appending lines


code:
def lists_with_sum(length, limit, exact=True):
    if length:
        for l in lists_with_sum(length-1, limit, False):
            gap = limit-sum(l)
            for i in range(gap if exact else 0, gap+1):
                yield l + [i]
    else:
        yield []

rawDescription: Creating an array of numbers that sum to a given number


code: a = something(); print(a)

rawDescription: Assign and print at the same time in Python


code:
import threading
import subprocess
from Queue import LifoQueue

class Job(object):
  def __init__(self, popenArgs, runTime, children):
    self.popenArgs = popenArgs
    self.runTime = runTime
    self.children = children

def run_jobs(queue):
  while True:
    job = queue.get()
    subprocess.Popen(job.popenArgs).wait()
    for child in job.children:
      queue.put(child)
    queue.task_done()

# Parameter 'jobs' contains the jobs that have no parent.
def main(jobs):
  job_queue = LifoQueue()
  num_workers = 4
  jobs.sort(key=lambda job: job.runTime)
  for job in jobs:
    job_queue.put(job)
  for i in range(num_workers):
    t = threading.Thread(target=run_jobs, args=(job_queue,))
    t.daemon = True
    t.start()
  job_queue.join()

rawDescription: Dynamically reordering jobs in a multiprocessing pool in Python


code:
def treeToList(node, order=Order.INORDER):
    if node is None:
        return []

    right = treeToList(node.right, order)
    down = treeToList(node.down, order)
    current = [node.data]

    if order == Order.PREORDER:
        return current + right + down

    if order == Order.INORDER:
        return right + current + down

    if order == Order.POSTORDER:
        return right + down + current

rawDescription: Python: Simplify many if-statements

description: Python: Simplify many if-statements


code: newString = re.sub(r'\boldword\b', r'newword', oldString)

rawDescription: String replace python

description: String replace python


code:
import urllib2
req = urllib2.urlopen("http://example.com/file.zip")
total_size = int(req.info().getheader('last-modified'))

rawDescription: `document.lastModified` in Python

description: `document.lastModified` in Python


code: lst.sort(key=lambda x: x[::-1])

rawDescription: Python Sorting Lists in Lists

description: Python Sorting Lists in Lists


code:
def fn(s):
  order = []
  counts = {}
  for x in s:
    if x in counts:
      counts[x] += 1
    else:
      counts[x] = 1
      order.append(x)
  for x in order:
    if counts[x] == 1:
      return x
  return None

rawDescription: Best way to find first non repeating character in a string

description: Find first non repeating character in a string


code: theta2 = pymc.Beta('theta2', alpha=10, beta=2)

rawDescription: Sequential updating in PyMC

description: Sequential updating in PyMC


code:
class Person(models.Model):
   name = models.CharField(max_length=20)
   lastname = models.CharField(max_length=20)
   job = models.CharField(max_length=20)
   salary = models.IntegerField()

   class Meta:
       abstract = True

class Person1(Person):
    ...

rawDescription: How to create a general class for other class can have the same model as well

description: Create a general class for other class can have the same model as well


code:
from Tkinter import *

master = Tk()

w = Text(master, height=1, borderwidth=0)
w.insert(1.0, "Hello, world!")
w.pack()

w.configure(state="disabled")

# if tkinter is 8.5 or above you'll want the selection background
# to appear like it does when the widget is activated
# comment this out for older versions of Tkinter
w.configure(inactiveselectbackground=w.cget("selectbackground"))

mainloop()

rawDescription: In python's tkinter, how can I make a Label such that you can select the text with the mouse?


code:
btn1 = Button() #Blue Button
btn1.background_color = [0,0,1,0]
btn2 = Button() #Green Button
btn2.background_color = [0,1,0,0]
b.addWidget(btn1)
b.addWidget(btn2)

rawDescription: Python- Kivy- Adding colour to buttons

description: Python- Kivy- Adding colour to buttons


code:
baseHeightList = [(1,3),(3,4)]
volumeList = [13,1,12,9,4,2]

def sqPyramidVolume(baseHeightList,volumeList):
    volume = map(lambda x: int((x[0]**2 * x[1])/3),baseHeightList)
    return filter(lambda x: x in volume, volumeList)

sqPyramidVolume(baseHeightList,volumeList)

rawDescription: Finding similar values in two lists using the filter function


code: {{ data|tojson|safe }}

rawDescription: Passing data for nvd3 chart from Flask as an argument


code:
from sqlalchemy.orm import relationship

...

class Profile(Base):
    __tablename__ = 'profile'

    ...

    answers = relationship("Answer", backref="profile")

    ...

class Question(Base):
    __tablename__ = 'question'

    ...

    answers = relationship("Answer", backref="question")

    ...

rawDescription: SQLAlchemy many-to-many relationship on declarative tables


code:
from random import randint as r
array = [ (r(1,100), r(1,100)) for i in xrange(10)]

rawDescription: How do i get 10 random values in python?

description: Get 10 random values in python


code:
def search(tree, word):
    node = tree
    depth = 0
    count = 0
    while True:
        print(node.value)
        depth += 1
        if node.value == word:
            count = node.count
            break
        elif word < node.value:
            node = node.left
        elif word > node.value:
            node = node.right

    return depth, count

def main():
    print(search(tree, "a"))

rawDescription: Python: search in binary search tree

description: Python: search in binary search tree


code:
from skimage import io, color, img_as_float
from skimage.feature import corner_peaks, plot_matches

import matplotlib.pyplot as plt
import numpy as np

image = img_as_float(io.imread('colordots.jpg'))

black_mask = color.rgb2gray(image) < 0.1
distance_red = color.rgb2gray(1 - np.abs(image - (1, 0, 0)))
distance_blue = color.rgb2gray(1 - np.abs(image - (0, 0, 1)))

distance_red[black_mask] = 0
distance_blue[black_mask] = 0

coords_red = corner_peaks(distance_red, threshold_rel=0.9, min_distance=50)
coords_blue = corner_peaks(distance_blue, threshold_rel=0.9, min_distance=50)

f, ((ax0, ax1), (ax2, ax3)) = plt.subplots(2, 2, figsize=(15, 10))
ax0.imshow(image)
ax0.set_title('Input image')
ax1.imshow(image)
ax1.set_title('Marker locations')
ax1.plot(coords_red[:, 1], coords_red[:, 0], 'ro')
ax1.plot(coords_blue[:, 1], coords_blue[:, 0], 'bo')
ax1.axis('image')
ax2.imshow(distance_red, interpolation='nearest', cmap='gray')
ax2.set_title('Distance to pure red')
ax3.imshow(distance_blue, interpolation='nearest', cmap='gray')
ax3.set_title('Distance to pure blue')
plt.show()

rawDescription: Scikit image color filtering and changing parts of image to array


code:
import re

full_text = my_stc.GetText()
search_string = 'a string to find'

matches = [i.start() for i in re.finditer(search_string, full_text)]

rawDescription: Search that returns array of founds in wxPython?


code: getattr(getattr(myobject, "id", None), "number", None)

rawDescription: Python: How to get attribute of attribute of an object with getattr?


rawDescription: Why does a list slice [:n] allow using a list with fewer than n elements in a loop?


rawDescription: Square brackets applied to "self" in Python


code:
for t in (np.int8, np.int16, np.int32, np.int64,
          np.uint8, np.uint16, np.uint32, np.uint64):
    sqlite3.register_adapter(t, long)

cur.execute("insert into foo(bar) values(?)", np.array([1]))

rawDescription: sqlite3 writes only floating-point numpy arrays not integer ones

description: Sqlite3 writes only floating-point numpy arrays not integer ones


code:
def checkcsv():
        with open("lesspreadsheettest.csv") as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                result=(row['Shop Order'])
                if sonumber.get() == result:
                    descQty=(row['Quantity'])
                    descInfo=(row['Description'])
                    descPN=(row['Part Number'])
                    # I've added the following four lines of code
                    # and commented out some lines, hopefully it is clear
                    # how to add more descDwg, descIss, simply change the range
                    # assuming your csv work that way = DrawingsX, IssueX...
                    for i in xrange(1,4):
                        descDwg=(row['Drawings'+ str(i)])
                        descIss=(row['Issue'+ str(i)])
                        # check, whether the issue is empty if so, skip to the next one
                        if descIss ==  '':
                            continue
                        self.dwgoutputbox.insert(1.0, descDwg, "dwg", "  Issue: ", "", descIss, "", "\n")

                    # descDwg1=(row['Drawings1'])
                    # descIss1=(row['Issue1'])
                    # descDwg2=(row['Drawings2'])
                    # descIss2=(row['Issue2'])
                    # descDwg3=(row['Drawings3'])
                    # descIss3=(row['Issue3'])

                    self.outputQty.insert(1.0, descQty)
                    self.outputDesc.insert(1.0, descPN, "", ": ", "", descInfo)
                    # self.dwgoutputbox.insert(1.0, descDwg3, "dwg", "  Issue: ", "", descIss3, "", "\n")
                    # self.dwgoutputbox.insert(1.0, descDwg2, "dwg", "  Issue: ", "", descIss2, "", "\n")
                    # self.dwgoutputbox.insert(1.0, descDwg1, "dwg", "  Issue: ", "", descIss1, "", "\n")
                    self.outputQty.configure(state="disabled")
                    self.outputDesc.configure(state="disabled")
                    self.dwgoutputbox.configure(state="disabled")

rawDescription: Read and display CSV in text widget using loop


code:
def next(n):
    i = n
    while (i >> 1) < n:
        yield i
        i = (i + 1) | n

rawDescription: How to generate all integers i, n & i == n (keeping bit length)

description: Generate all integers i, n & i == n (keeping bit length)


rawDescription: picking contents out of lists python

description: Picking contents out of lists python


code:
class ICMPSocket():
    def __init__(self):
        self.s = socket.socket(
            socket.AF_INET,
            socket.SOCK_RAW,
            socket.getprotobyname("icmp"))
    def sendto(self, data, host):
        self.s.sendto(data, (host, 1))
    def __getattr__(self, attr):
        return getattr(self.s, attr)

rawDescription: Subclassing and built-in methods in Python


rawDescription: Python list inter-element operation - can this be done with list comprehension?


code:
from operator import attrgetter
from collections import namedtuple

Person = namedtuple('Person', 'name age score')
seq = [Person(name='nick', age=23, score=100),
       Person(name='bob', age=25, score=200)]

# sort list by name
print(sorted(seq, key=attrgetter('name')))
# sort list by age
print(sorted(seq, key=attrgetter('age')))

rawDescription: Pythonic way to sorting list of namedtuples by field name


code:
mainLayout = QtGui.QGridLayout()
mainLayout.setColumnMinimumWidth(0, 100) #set column 0 width to 100 pixels
button = QtGui.QPushButton('OK')
mainLayout.addWidget(button, 0, 0) #adds the button to the widened column

rawDescription: Positioning widgets to QBoxLayout

description: Positioning widgets to QBoxLayout


rawDescription: Call multi-quoted unix command in python's subprocess


code:
def __init__(self, parent=None):
    ...
    ...
    self.current_line_edit = self.line_edit_1
    self.tablewidget.itemDoubleClicked.connect(self.onDoubleClick)
    self.line_edit_1.editingFinished.connect(self.onChangeLineEdit)
    self.line_edit_2.editingFinished.connect(self.onChangeLineEdit)
    self.line_edit_3.editingFinished.connect(self.onChangeLineEdit)
    ...
    ...

def onChange(self):
    self.current_line_edit = self.sender()

def onDoubleClick(self, item):
    self.current_line_edit.setText(item.text())

rawDescription: Selecting text for QLinEdit by double clicking on a item in Tablewidget


code:
Solution
from IPython.core.display import HTML
import binascii
from StringIO import StringIO
import matplotlib.pyplot as plt

# open IO object
sio = StringIO()

# generate random DataFrame
np.random.seed(314)
df = pd.DataFrame(np.random.randn(1000, 2), columns=['x', 'y'])

# initialize figure and axis
fig, ax = plt.subplots(1, 1)

# plot DataFrame
ax.scatter(df.iloc[:, 0], df.iloc[:, 1]);

# print raw canvas data to IO object
fig.canvas.print_png(sio)

# convert raw binary data to base64
# I use this to embed in an img tag
img_data = binascii.b2a_base64(sio.getvalue())

# keep img tag outter html in its own variable
img_html = ''.format(img_data)

HTML("
Hello

"+img_html)

rawDescription: Imbed matplotlib figure into iPython HTML


code:
import re
p = re.compile(r'[abcgr]([a-z])\1[ldc]')
s = "reel reed have that with this they"
print([x.group(0) for x  in p.finditer(s)])

rawDescription: regex backreference findall not working python

description: Regex backreference findall not working python


code:
s = ('select count(*)'
     'from ept_inv e'
     'where e.ept_type = {device_type}'
     'and e.inv_id = {endpoint_id};')

sql_statement = sql_statement_format.format(
                    device_type=in_row[cs.DeviceType],
                    endpoint_id=in_row[cs.EndpointId])

rawDescription: Proper CPython String Concatenation

description: Proper CPython String Concatenation


code: next((i for i, v in enumerate(a) if i == 666), None)

rawDescription: How can I get a Python generator to return None rather than StopIteration?

description: Get a Python generator to return None rather than StopIteration


code:
from sklearn import svm
clt = svm.SVC()
clt.fit( [[1],[2],[3]], ["a","b","a"] )
clt.classes_

rawDescription: Getting the class labels from an sklearn.svm.LinearSVC object


code:
import numpy as np
import pandas as pd
numbers = np.random.randint(0, 1000, 100)
col = numbers % 4 # put your logic here
s = pd.Series(numbers)
cnt = s.groupby(col).cumcount()
pd.pivot(cnt, col, numbers)

rawDescription: Table, with the different length of columns


code:
num_fields = len(cursor.description)
field_names = [i[0] for i in cursor.description]

rawDescription: MySQL: Get column name or alias from query


code:
import gtk
from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas
import matplotlib.animation as animation
from matplotlib import pyplot as plt

class MyProgram():
    def __init__(self):
        #some_gtk_stuff
        self.signals = {
                'on_button_clicked': self.create_plot,
        }
        self.builder.connect_signals(self.signals)

        self.vbox = self.builder.get_object('vbox')

        self.figure = plt.figure()
        self.axis = self.figure.add_subplot(1,1,1)
        self.canvas = None

    def create_plot(self, button):
        self.ani = animation.FuncAnimation(self.figure, self.update_plot, interval = 1000)

    def update_plot(self, i):
        #read SampleData from txt File
        x = []
        y = []
        with open('SampleData.txt') as f:
            x_raw, y_raw = f.readline().strip().split(',')
            x.append(int(x_raw))
            y.append(int(y_raw))

        self.axis.plot(x, y)

        if not self.canvas:
            self.canvas = FigureCanvas(self.figure)
            self.vbox.pack_start(self.canvas)
            self.canvas.show()

        self.canvas.draw()

MyProgram()
gtk.main()

rawDescription: python Matplotlib gtk - animate plot with FuncAnimation

description: Python Matplotlib gtk - animate plot with FuncAnimation


code:
pb['label'] = pb['Progress']

pb['label'] = pb['label'].replace('Approved (Underwritten)', '1')
pb['label'] = pb['label'].replace('Approved (Automatic)', '1')
pb['label'] = pb['label'].replace('E-Sign (Accepted)', '1')
pb['label'] = pb['label'].replace('Initial Payment', '1')

pb['label'] = pb['label'].replace('Choose Product', '0')
pb['label'] = pb['label'].replace('Account Access', '0')
pb['label'] = pb['label'].replace('Credit Profile', '0')
pb['label'] = pb['label'].replace('Ineligible', '0')
pb['label'] = pb['label'].replace('Declined (Credit | Internal)', '0')
pb['label'] = pb['label'].replace('Declined (ID & Bank)', '0')
pb['label'] = pb['label'].replace('Declined (Underwritten)', '0')
pb['label'] = pb['label'].replace('Unauthorised', '0')
pb['label'] = pb['label'].replace('Pre-Declined', '0')
pb['label'] = pb['label'].replace('E-Sign (Referred)', '0')
pb['label'] = pb['label'].replace('Referred (Automatic | Expired)', '0')

rawDescription: How to create group values in classes in pandas?

description: Create group values in classes in pandas


code: x = numpy.transpose(x, (1, 2, 0))

rawDescription: Converting 3x32x32 size numpy image array to 32x32x3 and saving to actual image in Python


code:
def convert(ls):
    last = None
    for x in ls:
        if x == 'prev': x = -1
        if x == 'next': x = +1
        if isinstance(x, int) and isinstance(last, int):
            x += last
        elif last:  # last is not None if you want zeroes
            yield last
        last = x
    yield last

rawDescription: Flatten 'next' and 'prev' links in a linked list


code:
reverse = False
if order.startswith('-'):
    reverse = True
    order = order[1:]
if reverse:
    games_query = games_query.order(-getattr(Game, order))
else:
    games_query = games_query.order(getattr(Game, order))

rawDescription: How to pass in custom properties to an ancestor query using Google App Engine with Python without using eval?

description: Pass in custom properties to an ancestor query using Google App Engine with Python without using eval


code:
from PyQt4 import QtGui, QtWebKit

app = QtGui.QApplication([])
view = QtWebKit.QWebView()

# intercept form submits
class MyWebPage(QtWebKit.QWebPage):
    def acceptNavigationRequest(self, frame, req, nav_type):
        if nav_type == QtWebKit.QWebPage.NavigationTypeFormSubmitted:
            text = "
\n".join(["%s: %s" % pair for pair in req.url().queryItems()])
            view.setHtml(text)
            return False
        else:
            return super(MyWebPage, self).acceptNavigationRequest(frame, req, nav_type)
view.setPage(MyWebPage())

# setup the html form
html = """
<form action="" method="get">
Like it?
<input type="radio" name="like" value="yes"/> Yes
<input type="radio" name="like" value="no" /> No

<input type="text" name="text" value="Hello" />
<input type="submit" name="submit" value="Send"/>
</form>
"""
view.setHtml(html)

# run the application
view.show()
app.exec_()

rawDescription: How do I display a website with html-forms locally using python and collect the user input?

description: Display a website with html-forms locally using python and collect the user input


code:
from  Tkinter import *
import tkMessageBox

root = Tk()

root.title("Simple Bot")
root.geometry("500x80")

def msg(ev=None):
   tkMessageBox.showinfo("Message", v.get() + " Thank you for naming me.")

root.bind('<Return>', msg)

L = Label(root, text="Bot: Hello User, my name is ______ please name me: ", font=("Helvetica", 14))

v = StringVar()
E = Entry(root, textvariable=v, font=("Helvetica", 16))

L.pack()
E.pack(side=BOTTOM, fill=BOTH, expand=1)

root.mainloop()

rawDescription: How to integrate code into application in python

description: Integrate code into application in python


code:
import csv
with open("C:/path/a.txt","r") as f,open("C:/path/a.csv" ,"wb") as w:
    temp = []
    writer = csv.writer(w)
    for line in f:
        temp.append(line.strip())
        if "9F" in line:
            writer.writerow(temp)
            temp = []

rawDescription: How to modify multiple columns and rows in a csv file using python 2.7.9

description: Modify multiple columns and rows in a csv file using python 2.7.9


code:
X
Y
mask = Y!=-1 # Create mask for boolean indexing
X[mask.ravel()]
Y[mask]

rawDescription: Get subset of rows in the numpy matrix based on the values from the column of another matrix


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

with Image(width=32, height=32, background=Color('red')) as ico:
    with Image(width=16, height=16, background=Color('green')) as s16:
        ico.sequence.append(s16)
    ico.save(filename='multisized.ico')

rawDescription: Wand Python multi-size icon

description: Wand Python multi-size icon


code:
a = numpy.array([2, 0, 1.5, -3])
b = numpy.ma.log(a)
b
b.sum()

rawDescription: Ignoring -Inf values in arrays using numpy/scipy in Python


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

import re
#ascii
pat = u"(tes?ts?)"
ttt = re.finditer(pat, u"test and tets")
print(ttt.next().start())
print(ttt.next().start())
# 0, 9

#russian
pat = u"(молоде?цы?)"
ttt = re.finditer(pat, u"молодец и молодцы")
print(ttt.next().start())
print(ttt.next().start())
# 0, 10

rawDescription: Unexpected RegExp work in Python 2.7 on non ascii symbols


code:
ar = input('please input string to be de/encrypted:')
key = input('please input single character key:')

def encrypt1(key,ar):
    i = 0
    while i < len(ar):
        br = chr(ord(ar[i])^ord(key))
        i = i+1
        print(br, end='')

encrypt1(key,ar)

print('\nInput string = ' + ar+'\n'+'key = '+key)

rawDescription: How can I group while outputs into a single string?

description: Group while outputs into a single string


code:
import unicodedata

glob.glob(unicodedata.normalize('NFD', '*/Bärlauch*'))

rawDescription: Python's glob module and unix' find command don't recognize non-ascii


code:
class Universe:
    def __contains__(_,x): return True

rawDescription: How to test whether x is a member of a universal set?

description: Test whether x is a member of a universal set


code:
list_1 = ['1','2','3']
list_2 = ['2','5','7']
list_3 = ['9','9','8']
from itertools import product
["".join(x) for x in product(list_1,list_2,list_3)]

rawDescription: Python combination generation

description: Python combination generation


code:
filteredDayContainers = [tag for tag in soup.find_all('div',
    attrs = {'class': 'dayContainer'})
    if "disabled" not in tag.parent['class']]

rawDescription: BeautifulSoup - findAll not within certain tag


code:
d = {"your": "DATA", "FROM": "above"}
dict((k.lower(), v) for k, v in d.iteritems())
def lower_keys(x):
  if isinstance(x, list):
    return [lower_keys(v) for v in x]
  elif isinstance(x, dict):
    return dict((k.lower(), lower_keys(v)) for k, v in x.iteritems())
  else:
    return x
lower_keys({"NESTED": {"ANSWER": 42}})

rawDescription: How to ensure that a python dict keys are lowercase?

description: Ensure that a python dict keys are lowercase


code:
with open(TEXTFILENAME,'r') as f:
    targets = [line for line in f if FINDSTRING in line]

rawDescription: Efficiently extract lines containing a string in Python


code:
sql = ("SELECT URL, Name AS Category "
       "FROM sitelist sl "
       "INNER JOIN sitecategory sc ON sc.PlacementCategory_id = sl.Category_id")

if limit > 0:
    whatever.execute(sql+" LIMIT %s", (limit,))
else:
    whatever.execute(sql)

rawDescription: Concatenate string with another that contains a variable


code:
from OpenGL.GL import shaders
from OpenGL.arrays import vbo
from OpenGL.GL import *
from OpenGL.raw.GL.ARB.vertex_array_object import glGenVertexArrays, \
                                                  glBindVertexArray

import pygame

import numpy as np

def run():
    pygame.init()
    screen = pygame.display.set_mode((800,600), pygame.OPENGL|pygame.DOUBLEBUF)

    #Create the VBO
    vertices = np.array([[0,1,0],[-1,-1,0],[1,-1,0]], dtype='f')
    vertexPositions = vbo.VBO(vertices)

    #Create the index buffer object
    indices = np.array([[0,1,2]], dtype=np.int32)
    indexPositions = vbo.VBO(indices, target=GL_ELEMENT_ARRAY_BUFFER)

    #Now create the shaders
    VERTEX_SHADER = shaders.compileShader("""
    #version 330
    layout(location = 0) in vec4 position;
    void main()
    {
        gl_Position = position;
    }
    """, GL_VERTEX_SHADER)

    FRAGMENT_SHADER = shaders.compileShader("""
    #version 330
    out vec4 outputColor;
    void main()
    {
        outputColor = vec4(0.0f, 1.0f, 0.0f, 1.0f);
    }
    """, GL_FRAGMENT_SHADER)

    shader = shaders.compileProgram(VERTEX_SHADER, FRAGMENT_SHADER)

    #The draw loop
    while True:
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        glUseProgram(shader)

        indexPositions.bind()

        vertexPositions.bind()
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, False, 0, None)

        #glDrawArrays(GL_TRIANGLES, 0, 3) #This line still works
        glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, None) #This line does work too!

        # Show the screen
        pygame.display.flip()

run()

rawDescription: How to draw with Vertex Array Objects and glDrawElements in PyOpenGL

description: Draw with Vertex Array Objects and glDrawElements in PyOpenGL


code:
mydict = {}

re_list = [re.compile(r"/Main/"+re.escape(i)) for i in mylist]
with open("dataset.nt", "rb") as input:
    for line in input:
        # any match has to contain the "/Main/" part
        # -> check it's there
        # that may help a lot or not at all
        # depending on what's in your file
        if not '/Main/' in line:
            continue

        # do the regex-part
        for i, regex in zip(mylist, re_list):
            total = 0
            if regex.search(line):
                total = total+1
            mydict[i] = total

rawDescription: What is the most efficient way of looping over each line of a file?


code:
def my_cut (x, bins,
            lower_infinite=True, upper_infinite=True,
            **kwargs):
    r"""Wrapper around pandas cut() to create infinite lower/upper bounds with proper labeling.

    Takes all the same arguments as pandas cut(), plus two more.

    Args :
        lower_infinite (bool, optional) : set whether the lower bound is infinite
            Default is True. If true, and your first bin element is something like 20, the
            first bind label will be '<= 20' (depending on other cut() parameters)
        upper_infinite (bool, optional) : set whether the upper bound is infinite
            Default is True. If true, and your last bin element is something like 20, the
            first bind label will be '> 20' (depending on other cut() parameters)
        **kwargs : any standard pandas cut() labeled parameters

    Returns :
        out : same as pandas cut() return value
        bins : same as pandas cut() return value
    """

    # Quick passthru if no infinite bounds
    if not lower_infinite and not upper_infinite:
        return pd.cut(x, bins, **kwargs)

    # Setup
    num_labels      = len(bins) - 1
    include_lowest  = kwargs.get("include_lowest", False)
    right           = kwargs.get("right", True)

    # Prepend/Append infinities where indiciated
    bins_final = bins.copy()
    if upper_infinite:
        bins_final.insert(len(bins),float("inf"))
        num_labels += 1
    if lower_infinite:
        bins_final.insert(0,float("-inf"))
        num_labels += 1

    # Decide all boundary symbols based on traditional cut() parameters
    symbol_lower  = "<=" if include_lowest and right else "<"
    left_bracket  = "(" if right else "["
    right_bracket = "]" if right else ")"
    symbol_upper  = ">" if right else ">="

    # Inner function reused in multiple clauses for labeling
    def make_label(i, lb=left_bracket, rb=right_bracket):
        return "{0}{1}, {2}{3}".format(lb, bins_final[i], bins_final[i+1], rb)

    # Create custom labels
    labels=[]
    for i in range(0,num_labels):
        new_label = None

        if i == 0:
            if lower_infinite:
                new_label = "{0} {1}".format(symbol_lower, bins_final[i+1])
            elif include_lowest:
                new_label = make_label(i, lb="[")
            else:
                new_label = make_label(i)
        elif upper_infinite and i == (num_labels - 1):
            new_label = "{0} {1}".format(symbol_upper, bins_final[i])
        else:
            new_label = make_label(i)

        labels.append(new_label)

    # Pass thru to pandas cut()
    return pd.cut(x, bins_final, labels=labels, **kwargs)

rawDescription: pandas cut with infinite upper/lower bounds

description: Pandas cut with infinite upper/lower bounds


code:
import numpy as np
from sklearn.decomposition import PCA
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
pca = PCA(n_components=2)
pca.fit(X)
print(pca.explained_variance_ratio_)

rawDescription: Dimension reduction Using PCA while preserving variance in percentage


code:
def _upload_path(instance,filename):
    return instance.get_upload_path(filename)

class Document(models.Model):
    docfile = models.FileField(upload_to=_upload_path)
    user = models.ForeignKey('auth.User')

    def get_upload_path(self,filename):
        return "static/uploads/"+str(self.user.id)+"/"+filename

rawDescription: Django user specific folders

description: Django user specific folders


code:
words = ['a', 'b', 'c', 'd']
code = ['3' , '2', '4', '9']

while words != code:
    number = raw_input("Enter a number: ")
    letter = raw_input("Enter the letter: ")
    code = list(map(lambda x: str.replace(x, number, letter), code))

print('You finally got it!')

rawDescription: Looping - python

description: Looping - python


code: query = {"event.region": region}

rawDescription: mongo query doesn't return results

description: Mongo query doesn't return results


code: paste

rawDescription: 3D numpy array into block diagonal matrix


code:
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import Normalize
from numpy.random import rand

fig, ax = plt.subplots(1, 1)
# get a color map
my_cmap = cm.get_cmap('jet')
# get normalize function (takes data in range [vmin, vmax] -> [0, 1])
my_norm = Normalize(vmin=0, vmax=5)
# some boring fake data
my_data = 5*rand(5)
ax.bar(range(5), rand(5), color=my_cmap(my_norm(my_data)))

plt.show()

rawDescription: vary the color of each bar in bargraph using particular value

description: Vary the color of each bar in bargraph using particular value


code:
LIST_STYLE = TableStyle([('LINEABOVE', (0,0), (-1,0), 2, colors.green),
    ('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
    ('LINEBELOW', (0,-1), (-1,-1), 2, colors.green)])

rawDescription: Is it possible to make a table with only horizontal borders in reportlab?


code:
# channels = [255, 0, 0]
if 0 in channels or 255 in channels:
    channels = [255, 255, 255]

rawDescription: Python/Pillow: Filter pixels with max/min RGB values


code:
def logtest2(N):
    T = 40. + 10. * np.random.rand(N)
    return np.sum(-1*np.log(np.random.rand(N)) / T)

rawDescription: Speeding up a big a loop with a logarithm in Python


code:
from suds.xsd.sxbasic import Import

file_url = 'file://<path to xml.xsd>'
Import.bind('http://www.w3.org/XML/1998/namespace', file_url)

rawDescription: How do I prevent suds from fetching xml.xsd over the network?

description: Prevent suds from fetching xml.xsd over the network


code:
import pandas as pd
import numpy as np

# Create some randomised data
N = 20
date_range = pd.date_range('01/01/2015', periods=N, freq='W')
df = pd.DataFrame({'ages':np.arange(N), 'payments':np.arange(N)*10}, index=date_range)

print(df.head())
#             ages  payments
# 2015-01-04     0         0
# 2015-01-11     1        10
# 2015-01-18     2        20
# 2015-01-25     3        30
# 2015-02-01     4        40

# Apply np.mean to the ages column and np.sum to the payments.
agg_funcs = {'ages':np.mean, 'payments':np.sum}

# Groupby each individual month and then apply the funcs in agg_funcs
grouped = df.groupby(df.index.to_period('M')).agg(agg_funcs)

print(grouped)
#          ages  payments
# 2015-01   1.5        60
# 2015-02   5.5       220
# 2015-03  10.0       500
# 2015-04  14.5       580
# 2015-05  18.0       540

rawDescription: Pandas: using multiple functions in a group by


code:
import numpy as np
import matplotlib.pyplot as plt
from itertools import count

def newton_fractal(xmin, xmax, ymin, ymax, xres, yres):
    yarr, xarr = np.meshgrid(np.linspace(xmin, xmax, xres), \
                             np.linspace(ymin, ymax, yres) * 1j)
    arr = yarr + xarr
    ydim, xdim = arr.shape
    arr = arr.flatten()
    f = np.poly1d([1,0,0,-1]) # x^3 - 1
    fp = np.polyder(f)
    counts = np.zeros(shape=arr.shape)
    unconverged = np.ones(shape=arr.shape, dtype=bool)
    indices = np.arange(len(arr))
    for i in count():
        f_g = f(arr[unconverged])
        new_unconverged = np.abs(f_g) > 0.00001
        counts[indices[unconverged][~new_unconverged]] = i
        if not np.any(new_unconverged):
            return counts.reshape((ydim, xdim))
        unconverged[unconverged] = new_unconverged
        arr[unconverged] -= f_g[new_unconverged] / fp(arr[unconverged])

N = 1000
pic = newton_fractal(-10, 10, -10, 10, N, N)

plt.imshow(pic)
plt.show()

rawDescription: How do I speed up fractal generation with numpy arrays?

description: Speed up fractal generation with numpy arrays


code:
import ctypes
pp = ctypes.string_at(msg.payload, msg.payloadlen)

rawDescription: efficiently turning a ctypes LP_c_ubyte into a python 'str'

description: Efficiently turning a ctypes LP_c_ubyte into a python 'str'


code:
class ReviewCreate(FormView):
    template_name = 'food/item_add_review.html'
    form_class = ReviewForm

    @method_decorator(login_required)  # Use a class level mixin instead
    def get_context_data(self, **kwargs):
        return super(
            ReviewCreate,
            self
        ).get_context_data(
            item=self.review_item,
            **kwargs
        )

    def lookup_review_item(self):
        self.item_modelname = self.kwargs.get('model')
        item_model = apps.get_model('food', self.item_modelname)
        self.review_item = get_object_or_404(
            item_model,
            pk=self.kwargs.get('pk')
        )

    def dispatch(self, request, *args, **kwargs):
        # lookup performed here to be set for both GET and POST
        self.lookup_review_item()
        return super(ReviewCreate, self).dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        r = form.save(commit=False)
        r.content_object=self.review_item
        r.save()
        return super(ReviewCreate, self).form_valid(form)

    def get_success_url(self):
        return reverse(
            'pkitem',
            kwargs = {
                'pk': self.review_item.id,
                'model': self.item_modelname
            },
        )

rawDescription: Persist Django FormView Data

description: Persist Django FormView Data


code:
import BeautifulSoup
resp = urllib2.urlopen("http://stackoverflow.com")
rawhtml = resp.read()
#parse through html to get text
soup=BeautifulSoup(rawhtml)

rawDescription: html to text conversion using python language

description: Html to text conversion using python language


code:
pd.factorize(df.CUSIP)
values, labels = pd.factorize(df.CUSIP)
df['NEW_ID'] = values
df

rawDescription: Create columns in a large data frame based on another columns


code: x, y = (fxn() for _ in range(2))

rawDescription: Repeat function a couple times without for loop in python


code:
import time
time.ctime() # 'Mon Oct 18 13:35:29 2010'
time.strftime('%l:%M%p %Z on %b %d, %Y') # ' 1:36PM EDT on Oct 18, 2010'
time.strftime('%l:%M%p %z on %b %d, %Y') # ' 1:36PM EST on Oct 18, 2010'

rawDescription: In Python, how to display current time in readable format


code:
from base64 import b64encode

data = b64encode(request.files['file'].read())
client = pyimgur.Imgur(IMGUR_CLIENT_ID)
r = client._send_request('https://api.imgur.com/3/image', method='POST', params={'image': data})
return r['link']

rawDescription: Upload an uploaded image using PyImgur without saving to a temporary file


code:
class ABCGuard(object):
    def __init__(self, obj, *abcs):
        if any(not isinstance(obj, abc) for abc in abcs):
            raise ValueError("{0} must implement {1}"
                             .format(obj.__class__.__name__,
                                     ', '.join(abc.__name__ for abc in abcs
                                               if not isinstance(obj, abc))))
        self.__obj = obj
        self.__abcs = abcs
        classname = '{0}{{{1}}}'.format(obj.__class__.__name__,
                                        ', '.join(abc.__name__ for abc in abcs))
        self.__class__ = type(classname, (ABCGuard, ) + abcs, {})

    def __getattribute__(self, name):
        if name.startswith('_ABCGuard__') or (name.startswith('__') and
                                              name.endswith('__')):
            return super(ABCGuard, self).__getattribute__(name)
        elif any(name in abc.__abstractmethods__ for abc in self.__abcs):
            return getattr(self.__obj, name)
        else:
            raise AttributeError("%r object has no attribute %r" %
                                 (self.__class__.__name__, name))

    def __dir__(self):
        return [x for abc in self.__abcs for x in abc.__abstractmethods__]

rawDescription: Constrain method access to an interface?

description: Constrain method access to an interface


code:
from collections import Sequence    # collections.abc in Python 3.3
isinstance(arg, Sequence) and not isinstance(arg, basestring)    # str in Python 3

rawDescription: Python reference for hasattr() choices to identify types


code:
last_name = 'Walsh'

first_name_re = "".join('(%s|%s)' % (re.escape(c.upper()),re.escape(c.lower())) for c in first_name)
last_name_re = "".join('(%s|%s)' % (re.escape(c.upper()),re.escape(c.lower())) for c in last_name)

# now that they are safe -we can simply put them in the middle of the regex
middle_name_regex_str = "\b?((%s (?P<middle_name1>[A-Z][^ ]?[a-z]* )?%s)|(%s (?P<middle_name2>[A-Z][^ ]?[a-z]* )?%s))" % (first_name_re, last_name_re, first_name_re, last_name_re)

rawDescription: re.escape modifying behavior

description: Re.escape modifying behavior


code:
class MyUserManager(BaseUserManager):
    def create_user(self, email, date_of_birth, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
            date_of_birth=date_of_birth,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

rawDescription: django authenticate returning Nonetype with valid credentials

description: Django authenticate returning Nonetype with valid credentials


code:
criterion = df['year_week'].map(lambda x: len(x)< 6)
df[criterion].index.values

rawDescription: Subsetting data in pandas with complex operations


code:
all = range(1, 539) # numbers from 1 to 538
random.shuffle(all) # shuffle them randomly
test = all[:239] # first half in test
train = all[239:] # second half in train

rawDescription: extracting two random sample sets in python

description: Extracting two random sample sets in python


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

def line_picker(line, me):
    if me.xdata is None: return False, dict()
    x, y = me.x, me.y
    xdata, ydata = line.axes.transData.transform(np.array(line.get_data()).T).T
    index = np.arange(len(xdata))
    index2 = np.linspace(0, index[-1], 2000)
    xdata2 = np.interp(index2, index, xdata)
    ydata2 = np.interp(index2, index, ydata)
    d = np.sqrt((xdata2-x)**2. + (ydata2-y)**2.)
    if np.min(d) < 5:
        return True, {}
    else:
        return False, {}

mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
line1 = ax.plot(x, y, z, label='parametric curve', picker=line_picker)[0]

t = np.linspace(-1, 1, 100)
x = 4*np.sin(10*t)
y = 4*np.cos(10*t)
z = t**2*5-3

line2 = ax.plot(x, y, z, label="second", picker=line_picker)[0]

ax.legend()

def onpick(event):
    print [line1, line2].index(event.artist)

fig.canvas.mpl_connect('pick_event', onpick)

plt.show()

rawDescription: wxPython matplotlib - detecting which line was clicked on 3D line plot

description: WxPython matplotlib - detecting which line was clicked on 3D line plot


code:
current = ['it1', 'test', 'blah', 10]
results = []
while current:
    remaining = []
    for item in current:
        (results if meets_conditional(item) else remaining).append(item)
    current = remaining

rawDescription: loop and process items in list, reloop until all items have been processed

description: Loop and process items in list, reloop until all items have been processed


code:
import subprocess
ret = subprocess.call(["ssh", "user@host", "program"]);

# or, with stderr:
prog = subprocess.Popen(["ssh", "user@host", "program"], stderr=subprocess.PIPE)
errdata = prog.communicate()[1]

rawDescription: How to execute a process remotely using python

description: Execute a process remotely using python


rawDescription: Python Matrix (list of lists) to dictionary


code:
home = os.path.expanduser('~')
f = tkFileDialog.askopenfile(initialdir = home)

rawDescription: tkinter home directory

description: Tkinter home directory


code:
import matplotlib.pyplot as plt

data_dic={1:'1:Text 1',2:'2:Text 2',3:'3:Text 3',4:'4:Text 4'}
ax1 = plt.subplot(111)
xval = [1,2,3,4]
yval = [ 22.,  13.,  21.,   6.]
for j in range(len(xval)):
    ax1.bar(xval[j], yval[j], width=0.8, bottom=0.0, align='center', color='k')
    ax1.plot(1,1,label = data_dic[xval[j]],marker = '',ls ='') #plot with not marker or line
ax1.set_xticks(xval)
ax1.legend(frameon = False)
plt.show()

rawDescription: Bar Graph with Legend without Colors

description: Bar Graph with Legend without Colors


code:
def prettify(elem):
    """Return a pretty-printed XML string for the Element.
    """
    rough_string = ElementTree.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="\t")

rawDescription: use xml.etree.elementtree to write out nicely formatted xml files

description: Use xml.etree.elementtree to write out nicely formatted xml files


code:
train_samples = {}

with file('pos.txt', 'rt') as f:
    for line in f.readlines():
        train_samples[line] = 'pos'

rawDescription: how to label sentiment polarity in big text file?

description: Label sentiment polarity in big text file


rawDescription: Python unicode list join

description: Python unicode list join


code:
class StateManager(threading.Thread):
    def __init__(self, lock, state):
        threading.Thread.__init__(self)
        self.lock = lock
        self.state = state

    def run(self):
        lock = self.lock
        state = self.state
        while True:
            lock.acquire()
            self.updateState(state)
            lock.release()
            time.sleep(60)

rawDescription: Python: what is the proper way to pass arguments to threading.Thread instance


code:
import sys
from optparse import OptionParser as OP
cmdLine = sys.argv
i = cmdLine.index('-u')
if (i+1) == len(cmdLine) or cmdLine[i+1] not in users:
    cmdLine.insert(i+1,userName)
p = OP()
p.add_option('-u',action='append')
p.parse_args(cmdLine[1:])

rawDescription: Commandline options with optional arguments using optparse


rawDescription: Get first N key pairs from an Ordered Dictionary to another one in python


code:
def distance(len_my_list, idx_1, idx_2):
    i = (idx_1 - idx_2) % len_my_list
    j = (idx_2 - idx_1) % len_my_list
    return min(i, j)

rawDescription: Minimum distance between two elements of a circular list?


rawDescription: Django filter objects based on related field


code:
while not q.empty():
    sleep(1)

rawDescription: How to make sure queue is empty before exiting main thread

description: Make sure queue is empty before exiting main thread


code:
from lxml import objectify

xml = "01"
a = objectify.fromstring(xml)
print(a.b)
print(a.b.text)

rawDescription: Change int element to str element in lxml objectify python


code:
from maya import cmds as mc

sel = mc.ls(sl=True)#here you get the selected vertex
mc.polyMergeVertex(sel)#Merge those vertex

mc.select(sel)#if you run this you will see that the selected vertex are diferent from the ones you made the merge.

rawDescription: Maya: Show merged vertices

description: Maya: Show merged vertices


code:
import pandas as pd
df = pd.merge(  left=firstDataFrame, right=secondDataFrame, on='NameOfColumnContainingBakery...')

rawDescription: matching indexes in python to categorize a column

description: Matching indexes in python to categorize a column


code:
import matplotlib.pyplot as plt
import networkx as nx
import random

G = nx.gnp_random_graph(10,0.3)
for u,v,d in G.edges(data=True):
    d['weight'] = random.random()

edges,weights = zip(*nx.get_edge_attributes(G,'weight').items())

pos = nx.spring_layout(G)
nx.draw(G, pos, node_color='b', edgelist=edges, edge_color=weights, width=10.0, edge_cmap=plt.cm.Blues)
plt.savefig('edges.png')

rawDescription: Colouring edges by weight in networkx

description: Colouring edges by weight in networkx


code:
f = self.wopener("mydata", "w", atomictemp=True)
f.write(somedata)
f.close()

rawDescription: How should one manage hook specific files in the '.hg/' state directory?


code:
def run_safely(f, *args):
    try:
        f(*args)
    except SpecificException:
        # handle appropriately here
        pass

with open(sys.argv[1]) as f:
   for line in f:
       run_safely(do_1, line)
       run_safely(do_2, line)
       run_safely(do_3, line)

rawDescription: writing multiple try and except in python

description: Writing multiple try and except in python


code: sum(isinstance(fruit, Orange) for fruit in basket)

rawDescription: Count number of instances of object type in OrderedSet


code:
from itertools import groupby
from operator import itemgetter
from multiprocessing import pool

def func(lines):
    groups = []
    for key, group in groupby(lines, key=itemgetter(0)):
        groups.append( list(group) )

    pool = Pool(processes=len(groups))

    results_lst = pool.map( my_cpu_intensive_function, groups )

    # send results to stdout for further processing
    print(results)

def main():
    # a generator holding lists of data
    lines = (line.strip().split('\t') for line in sys.stdin)
    func(lines)

rawDescription: Modify CPU-intensive function to parallel function


code:
import os

fileobj.flush()  # clear buffers
fileobj.seek(-256, os.SEEK_END)  # 256 bytes from the end
fileobj.truncate()

rawDescription: remove the last 256 byte for a output file

description: Remove the last 256 byte for a output file


code:
user = User.objects.get(id=1)
group = Group.objects.get(id=5)

user.groups.add(group)

rawDescription: How to insert the group_id of a user to 'auth_user_groups' table

description: Insert the group_id of a user to 'auth_user_groups' table


code:
def func_want(func, n):
    def wrapper(*args):
        args = list(args)
        args[n] += 1
        return func(*args)
    return wrapper

def f(w, x, y, z):
    return w, x, y, z

func_want(f, 2)(0, 0, 0, 0)

rawDescription: Function that takes a function with varying arguement lengths


code:
lst = ['2    19   2839475239874 hda']

# Extracting the device part
dev = filter(lambda s: s[0] is 'h', lst[0].split())[0]

# Inserting it
cmd = 'dd if=/dev/zero of=/dev/{0} bs=512 count=1'.format(dev)

rawDescription: Extracting a changeable string from a list and insertion in Python


code:
#!/usr/bin/env python

import mapnik
import cairo

m = mapnik.Map(15000, 15000, "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs") # end result: OpenStreetMap projection
m.background = mapnik.Color(0, 0, 0, 0)

bbox = mapnik.Envelope(-10000000, 2000000, -4000000, -19000000) # must be adjusted
m.zoom_to_box(bbox)

s = mapnik.Style()
r = mapnik.Rule()

polygonSymbolizer = mapnik.PolygonSymbolizer()
polygonSymbolizer.fill_opacity = 0.0
r.symbols.append(polygonSymbolizer)

lineSymbolizer = mapnik.LineSymbolizer(mapnik.Color('red'), 1.0)
r.symbols.append(lineSymbolizer)

s.rules.append(r)
m.append_style('My Style',s)

lyr = mapnik.Layer('path', '+init=epsg:4326')
lyr.datasource = mapnik.Ogr(file = './path.kml', layer = 'path')
lyr.styles.append('My Style')
m.layers.append(lyr)

# mapnik.render_to_file(m,'./path.png', 'png')

file = open('./path.pdf', 'wb')
surface = cairo.PDFSurface(file.name, m.width, m.height)
mapnik.render(m, surface)
surface.finish()

rawDescription: programmatically converting kml to image

description: Programmatically converting kml to image


code:
def index(request):
  context_dict = {}

  category_list = Category.objects.order_by('-likes')[:5]
  category_list = remove_spaces(category_list)
  context_dict['categories'] = category_list

  page_list = Page.objects.order_by('-views')[:5]
  context_dict['pages'] = page_list

  # Deal with cookies
  if request.session.get('last_visit'):
    last_visit_time = request.session.get('last_visit')
    visits = request.session.get('visits', 0)

    # Use seconds instead of days for testing
    if (datetime.now() - datetime.strptime(last_visit_time[:-7]), "%Y-%m-%d %H:%M:%S").seconds > 5:
      request.session['visits'] = visits + 1
      request.session['last_visit'] = str(datetime.now())
  else:
    # this code was never reached, so the session was not being set
    request.session['last_visit'] = str(datetime.now())
    request.session['visits'] = 1

  return render(request, 'rango/index.html', context_dict)

rawDescription: Problems using session based cookies in Django


code:
from glob import glob
from pylab import *

for fname in glob("xydata*.txt"):
    x, y = loadtxt(fname, unpack=True, usecols=[1, 0])
    mask_inf = gradient(y) < 0
    mask_sup = gradient(y) >= 0

    plot(x[mask_inf], y[mask_inf], 'r')
    plot(x[mask_sup], y[mask_sup], 'g')

    legend(("grad(y) < 0", "grad(y) >= 0"))
    title(fname)

    savefig(fname.replace("xydata", "data").replace(".txt", ".svg"))
    clf()

rawDescription: Loop plot for mulitiple data files - Python


rawDescription: How to slice a pandas dataframe by columns using a mix of array of labels and slice of objects?

description: Slice a pandas dataframe by columns using a mix of array of labels and slice of objects


code: memcacheService.put(userKey + "userBalance", userBalance);

rawDescription: Google appengine memcache scope

description: Google appengine memcache scope


code:
import subprocess, os

subprocess.Popen('cmd.exe')

os.system("cmd.exe")

rawDescription: build cmd into Tkinter window

description: Build cmd into Tkinter window


code:
f = open('filename', 'r')
lines = f.readlines()

rawDescription: How to read text file line by line and do something for a particular line?

description: Read text file line by line and do something for a particular line


code: any(item in input_string for item in my_list)

rawDescription: Loop through each element of the list

description: Loop through each element of the list


rawDescription: Trying to turn inner and out tuples into inner and outer lists


rawDescription: Django data retrieval performance

description: Django data retrieval performance


rawDescription: What is more efficient in python new array creation or in place array manipulation?


code: next((i for i,x in enumerate(a) if 'node4' in x), None)

rawDescription: Finding index of a dictionary in a list by key value


code:
for file_chunk in uploaded_file.chunks():
    saved_file.write(file_chunk)

rawDescription: Image upload: iPhone Client - Django - S3


rawDescription: GitPython equivalent command

description: GitPython equivalent command


code:
# Sample Projects Container
db.define_table('it_projects',
                db.Field('project_name', 'string', length=255, required=True),
                db.Field('description', 'text', required=False, default=''),
                db.Field('is_active', 'boolean', required=False, default=True),
                db.Field('created_on', 'datetime', required=True),
                db.Field('created_by', db.auth_users),
                db.Field('anonymous_read', 'boolean', required=True),
                migrate='it_projects.table')

rawDescription: how to create, insert and update database table using web2py?

description: Create, insert and update database table using web2py


code:
t = datetime.datetime.now()
t
time.mktime(t.timetuple()) + t.microsecond / 1E6

rawDescription: Python: Converting from `datetime.datetime` to `time.time`


code:
query:sky
board:123
res_opt:eqeq
res:0x0
aspect:0
nsfw_sfw:1
nsfw_sketchy:0
nsfw_nsfw:0
thpp:32
orderby:relevance
orderby_opt:desc

rawDescription: How do I parse through an infinite scrolling page (ex. Wallbase.cc/search/sky) with Python?

description: Parse through an infinite scrolling page (ex. Wallbase.cc/search/sky) with Python


code:
import wx

class PanelWithText(wx.Panel):
    def __init__(self, parent):
        super(PanelWithText, self).__init__(parent)

        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        st1 = wx.StaticText(self, label='Some Text')
        hbox1.Add(st1)

class Example(wx.Frame):

    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title,
            size=(390, 350))

        panel = wx.Panel(self)

        vbox = wx.BoxSizer(wx.VERTICAL)

        #hbox1 = wx.BoxSizer(wx.HORIZONTAL)                  # comment out from here
        #panel1 = wx.Panel(panel)                            #
        #st1 = wx.StaticText(panel1, label='Some Text')      #
        #hbox1.Add(st1)                                      # to here
        panel1 = PanelWithText(panel)
        vbox.Add(panel1)

        panel.SetSizer(vbox)

        self.Centre()
        self.Show()

if __name__ == '__main__':
    import wx.lib.mixins.inspection
    app = wx.App()
    Example(None, title='Example')
    wx.lib.inspection.InspectionTool().Show()
    app.MainLoop()

rawDescription: Derived panel classes in wxpython

description: Derived panel classes in wxpython


code:
values = ["Regression", "Regression Test"]

selected_row = driver.find_element_by_class_name('selectedRow')
tds = [td.text for td in selected_row.find_elements_by_tag_name('td')]

self.assertTrue(all(value in tds for value in values))

rawDescription: Python selenium bindings, picking out <td> elements


code:
supported = ['.mp3','.ogg','.wma'] #put all known here

for root, dirs, files in os.walk("."):
    for filename in files:
        if filename.lower() in supported: #test if filename ext is in supported
            fullname = os.path.join(root, filename)

rawDescription: Mutagen All File Types

description: Mutagen All File Types


code:
for i in range(1,9):
    with open(inputgui, 'r') as input1:
        junkinfo = [next(input1) for dummy in range(22)]

        newOutput = output[:-4] + str(i) + output[-4:]

        with open(newOutput, 'w') as output1:
            for line in input1:
                columns = line.strip().split()
                output1.write('{:8}{:8}\n'.format(columns[1], columns[i+1]))

rawDescription: Iteration with a variable in Python 2.7

description: Iteration with a variable in Python 2.7


code:
import bisect

def f(x):
    funcs = [do_something_1, do_something_2, do_something_3, do_something_4]
    funcs[bisect.bisect_left([.1, 1, 10], x)]()

rawDescription: Python - switch alternative for non-discrete comparisons


code: replaceArray = 'Replace the string|(?:in|inside|within) the string|with the string'

rawDescription: How to split a string in Python without redundant output

description: Split a string in Python without redundant output


code:
from PySide.QtCore import *
from PySide.QtGui import *

class MainWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.layout=QVBoxLayout()
        self.setLayout(self.layout)

        self.checkbox=QCheckBox("Layouts")
        self.layout.addWidget(self.checkbox)

        self.widget1=QWidget()
        self.layout.addWidget(self.widget1)

        self.layout1=QVBoxLayout()
        self.widget1.setLayout(self.layout1)

        self.layout1.addWidget(QLabel("First layout"))

        self.layout1.addWidget(QTextEdit())

        self.widget2=QWidget()
        self.layout.addWidget(self.widget2)

        self.layout2=QHBoxLayout()
        self.widget2.setLayout(self.layout2)

        self.layout2.addWidget(QTextEdit("Second layout"))

        self.layout2.addWidget(QTextEdit())

        self.checkbox.toggled.connect(self.checkbox_toggled)
        self.checkbox.toggle()

        self.show()

    def checkbox_toggled(self, state):
        self.widget1.setVisible(state)
        self.widget2.setVisible(not state)

app=QApplication([])
mw=MainWindow()
app.exec_()

rawDescription: pyside show / hide layouts

description: Pyside show / hide layouts


code:
from datetime import date
from dateutil.relativedelta import relativedelta

six_months = date.today() - relativedelta(months=+6)

rawDescription: How to find all the dates within last 6 months using Python ?

description: Find all the dates within last 6 months using Python


code:
# monitor.py
import subprocess

TIMEOUT = 10
while True:
  # start a new process to monitor
  # you could also run sys.argv[1:] for a more generic monitor
  child = subprocess.Popen(['python','other.py','arg'], stdout=subprocess.PIPE)
  while True:
    rlist,_,_ = select([child.stdout], [], [], TIMEOUT)
    if rlist:
      child.stdout.read() # do you need to save the output?
    else:
      # timeout occurred, did the process finish?
      if child.poll() is not None:
        # child process completed (or was killed, but didn't hang), we are done
        sys.exit()
      else:
        # otherwise, kill the child and start a new one
        child.kill()
        break

rawDescription: Detect hanging python shell in OS X

description: Detect hanging python shell in OS X


code:
from django.db.models.signals import pre_save
from django.contrib.auth import User

# method for updating
def update_primary_user(sender, instance, **kwargs):
     if instance.pk:
          return
     if instance.is_superuser and not instance.userprofile.is_primary_user:
          instance.userprofile.is_primary_user = True
          instance.userprofile.save()

# register the signal
pre_save.connect(update_primary_user, sender=User)

rawDescription: Django .is_superuser field permission

description: Django .is_superuser field permission


code:
#!/usr/bin/python

from distutils.core import setup

setup (name = 'Initech Package 3',
          description = "Services and libraries ABC, DEF",
          author = "That Guy, Initech Ltd",
          author_email = "that.guy@initech.com",
          version = '1.0.5',
          package_dir = {'Package3' : 'site-packages/Package3'},
          packages = ['Package3', 'Package3.Queries'],
          data_files = [
                       ('/etc/Package3', ['etc/Package3/ExternalResources.conf'])
          ])

rawDescription: Python distutils - does anyone know how to use it?


code:
def due_date_key(t):
  return (t.due_date is None, t.due_date)

tasks.sort(key=due_date_key)

rawDescription: Changing a comparison function to use keys for sorting


code:
class Employee(models.Model):
     name = models.CharField(max_length = 100)
     dob = models.DateField('date of birth')
     doj = models.DateField()
     mobile=models.IntegerField(max_length = 12)
     email = models.EmailField(max_length=50)
     bill = models.BooleanField(db_index=True,default=False)
     proj = models.ForeignKey(Project, verbose_name='project')

rawDescription: change colum name in django admin

description: Change colum name in django admin


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

S0 = np.ones([20,20], int)
S = np.copy(S0)
Mx = np.shape(S)[0]
My = np.shape(S)[1]

for x in range(Mx):
    for y in range(My):
            S[x,y]=2*random.randint(2)-1

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

ax.matshow(S,alpha=0.75, cmap="summer", interpolation="none")

ax.set_xticks([i+0.5 for i in range(Mx)])
ax.set_yticks([i+0.5 for i in range(My)])

ax.set_xticklabels(range(Mx))
ax.set_yticklabels(range(My))

#plt.grid(which = 'minor', ls = '-')
plt.grid(which = 'major', ls = '-')

plt.minorticks_on()
plt.show()

rawDescription: How to change the number of minorticks?

description: Change the number of minorticks


code:
import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()

# These are in unitless percentages of the figure size. (0,0 is bottom left)
left, bottom, width, height = [0.25, 0.6, 0.2, 0.2]
ax2 = fig.add_axes([left, bottom, width, height])

ax1.plot(range(10), color='red')
ax2.plot(range(6)[::-1], color='green')

plt.show()

rawDescription: How to add different graphs (as an inset) in another python graph

description: Add different graphs (as an inset) in another python graph


code: subprocess.Popen('ulimit -v 1024; ls', shell=True)

rawDescription: Check memory usage of subprocess in Python


code:
my_var = (#some_variable +
         some_other_var)

rawDescription: How can I create inline comments (without using backslash to continue on another line)?

description: Create inline comments (without using backslash to continue on another line)


code:
d = decimal.Decimal('56.4325')
d.as_tuple().exponent
d = decimal.Decimal('56.43256436')
d.as_tuple().exponent

rawDescription: Easy way of finding decimal places

description: Easy way of finding decimal places


code:
style = xlwt.easyxf('font: bold off, color black;\
                     borders: top_color red, bottom_color red, right_color red, left_color red,\
                              left thin, right thin, top thin, bottom thin;\
                     pattern: pattern solid, fore_color white;')

rawDescription: Excel write, borders colour

description: Excel write, borders colour


code:
def mount(f):
    op = gio.MountOperation()
    op.connect('ask-password', ask_password_cb)
    f.mount_enclosing_volume(op, mount_done_cb)

def ask_password_cb(op, message, default_user, default_domain, flags):
    op.set_username(USERNAME)
    op.set_domain(DOMAIN)
    op.set_password(PASSWORD)
    op.reply(gio.MOUNT_OPERATION_HANDLED)

def mount_done_cb(obj, res):
    obj.mount_enclosing_volume_finish(res)

rawDescription: Accessing samba shares with gio in python


code:
from my_module import fn
with patch('__main__.fn', return_value='hello') as patch_context:
    x = fn()

rawDescription: Using patch to to mock a function (as opposed to a method)


code:
def search (self, element):
    current=self.head
    index=1
    while current != None:
        if current.data == element:
            return index
        current = current.next_node
        index += 1
    return -1

rawDescription: search function for doubly linked list

description: Search function for doubly linked list


code:
url_header_list = [
    (url1, headers1),
    (url2, headers2),
    (url3, headers3),
    ...
]

items = []
# You can change your headers and url in any way you want, not just like that
for url, headers in url_header_list:
    # And this you need to do for each pair of url and headers
    response = requests.get(url, headers=headers).json()
    items.extend(response['items'])

rawDescription: Merging two API calls together with JSON


code:
from Tkinter import *
import ttk

def inputToFloat(input):
    if isinstance(input, float):
        return input
    elif isinstance(input, basestring):
        input = input.strip()
        return 0.0 if not input else float(input)
    else:
        raise Exception("unsupported type")

def plus(*args):
    value = inputToFloat(a.get())
    value1 = inputToFloat(b.get())
    if c:
        value2 = inputToFloat(c.get())
    else:
        value2 == inputToFloat(0.0)
    if d:
        value3 = inputToFloat(d.get())
    else:
        value3 == inputToFloat(0.0)

    result.set(value + value1 + value2 + value3)

root = Tk()
root.title("Plus them")

mainframe = ttk.Frame(root, padding="10 10 10 10")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

a = StringVar()
b = StringVar()
c = StringVar()
d = StringVar()
result = StringVar()

feet_entry = ttk.Entry(mainframe, width=5, textvariable=a)
feet_entry.grid(column=2, row=1, sticky=(W, E))

feet_entry1 = ttk.Entry(mainframe, width=5, textvariable=b)
feet_entry1.grid(column=5, row=1, sticky=(W, E))

feet_entry2 = ttk.Entry(mainframe, width=5, textvariable=c)
feet_entry2.grid(column=2, row=2, sticky=(W, E), pady = 5)

feet_entry3 = ttk.Entry(mainframe, width=5, textvariable=d)
feet_entry3.grid(column=5, row=2, sticky=(W, E), pady = 5)

ttk.Label(mainframe, text="the result is").grid(column=3, row=3, sticky=W)
ttk.Label(mainframe, textvariable = result).grid(column=5, row=3, sticky=(W, E))

ttk.Button(mainframe, text="Plus", command=plus).grid(column=3, row=4, sticky=W)

feet_entry.focus()
root.bind('<Return>', plus)
root.mainloop()

rawDescription: Simple GUI, only consider values when available


code:
cols = list(df.columns.values) #Make a list of all of the columns in the df
cols.pop(cols.index('b')) #Remove b from list
cols.pop(cols.index('x')) #Remove x from list
df = df[cols+['b','x']] #Create new dataframe with columns in the order you want

rawDescription: move column in pandas dataframe

description: Move column in pandas dataframe


code:
choices = [["small", "medium", "large"],
           ["vanilla", "ultra chocolate", "lychee", "rum raisin", "ginger"],
           ["cone", "cup"]]
from itertools import product
print("\n".join(" ".join(item) for item in product(*choices)))

rawDescription: generating all combinations of nested tuples in python

description: Generating all combinations of nested tuples in python


code:
id = request.args.get('id', type=int)
if id is not None:
    cur.execute("SELECT * FROM data WHERE id = %s", (id,))
else:
    # No (valid) id given, give everything
    cur.execute("SELECT * FROM data")

rawDescription: Python Flask and Psycopg -- Query string request.get in WHERE


code:
from google.appengine.api import memcache

class MainHandler(webapp2.RequestHandler):
  def get (self, q):
    if q is None:
      q = 'index.html'

    rendered = memcache.get('static_%s' % q)
    if rendered is None:
        path = os.path.join (os.path.dirname (__file__), q)
        rendered = template.render (path, {})
    self.response.headers['Content-Type'] = 'text/html'
    self.response.write(rendered)

rawDescription: memcache a static front page in GAE

description: Memcache a static front page in GAE


rawDescription: How to use multiple options with the .format() function in Python

description: Use multiple options with the .format() function in Python


code:
import pyglet
from pyglet.gl import *

# Zooming constants
ZOOM_IN_FACTOR = 1.2
ZOOM_OUT_FACTOR = 1/ZOOM_IN_FACTOR

class App(pyglet.window.Window):

    def __init__(self, width, height, *args, **kwargs):
        conf = Config(sample_buffers=1,
                      samples=4,
                      depth_size=16,
                      double_buffer=True)
        super().__init__(width, height, config=conf, *args, **kwargs)

        #Initialize camera values
        self.left   = 0
        self.right  = width
        self.bottom = 0
        self.top    = height
        self.zoom_level = 1
        self.zoomed_width  = width
        self.zoomed_height = height

    def init_gl(self, width, height):
        # Set clear color
        glClearColor(0/255, 0/255, 0/255, 0/255)

        # Set antialiasing
        glEnable( GL_LINE_SMOOTH )
        glEnable( GL_POLYGON_SMOOTH )
        glHint( GL_LINE_SMOOTH_HINT, GL_NICEST )

        # Set alpha blending
        glEnable( GL_BLEND )
        glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA )

        # Set viewport
        glViewport( 0, 0, width, height )

    def on_resize(self, width, height):
        # Set window values
        self.width  = width
        self.height = height
        # Initialize OpenGL context
        self.init_gl(width, height)

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        # Move camera
        self.left   -= dx*self.zoom_level
        self.right  -= dx*self.zoom_level
        self.bottom -= dy*self.zoom_level
        self.top    -= dy*self.zoom_level

    def on_mouse_scroll(self, x, y, dx, dy):
        # Get scale factor
        f = ZOOM_IN_FACTOR if dy > 0 else ZOOM_OUT_FACTOR if dy < 0 else 1
        # If zoom_level is in the proper range
        if .2 < self.zoom_level*f < 5:

            self.zoom_level *= f

            mouse_x = x/self.width
            mouse_y = y/self.height

            mouse_x_in_world = self.left   + mouse_x*self.zoomed_width
            mouse_y_in_world = self.bottom + mouse_y*self.zoomed_height

            self.zoomed_width  *= f
            self.zoomed_height *= f

            self.left   = mouse_x_in_world - mouse_x*self.zoomed_width
            self.right  = mouse_x_in_world + (1 - mouse_x)*self.zoomed_width
            self.bottom = mouse_y_in_world - mouse_y*self.zoomed_height
            self.top    = mouse_y_in_world + (1 - mouse_y)*self.zoomed_height

    def on_draw(self):
        # Initialize Projection matrix
        glMatrixMode( GL_PROJECTION )
        glLoadIdentity()

        # Initialize Modelview matrix
        glMatrixMode( GL_MODELVIEW )
        glLoadIdentity()
        # Save the default modelview matrix
        glPushMatrix()

        # Clear window with ClearColor
        glClear( GL_COLOR_BUFFER_BIT )

        # Set orthographic projection matrix
        glOrtho( self.left, self.right, self.bottom, self.top, 1, -1 )

        # Draw quad
        glBegin( GL_QUADS )
        glColor3ub( 0xFF, 0, 0 )
        glVertex2i( 10, 10 )

        glColor3ub( 0xFF, 0xFF, 0 )
        glVertex2i( 110, 10 )

        glColor3ub( 0, 0xFF, 0 )
        glVertex2i( 110, 110 )

        glColor3ub( 0, 0, 0xFF )
        glVertex2i( 10, 110 )
        glEnd()

        # Remove default modelview matrix
        glPopMatrix()

    def run(self):
        pyglet.app.run()

App(500, 500).run()

rawDescription: How to pan and zoom properly in 2D?

description: Pan and zoom properly in 2D


code:
from dateutil.parser import parse

tests = [int, float, parse]

def smartcast(value):
     for test in tests:
         try:
             return test(value)
         except ValueError:
             continue
     # No match
     return value

rawDescription: Smart type casting in python

description: Smart type casting in python


code:
s3 = boto3.resource('s3')
bucket = s3.Bucket('test-bucket')
# Iterates through all the objects, doing the pagination for you. Each obj
# is an ObjectSummary, so it doesn't contain the body. You'll need to call
# get to get the whole body.
for obj in bucket.objects.all():
    key = obj.key
    body = obj.get()['Body'].read()

rawDescription: Read file content from S3 bucket with boto3


code:
from email.header import Header

myheader = {'name': str(Header(u'Some unicode value', 'utf-8'))}

rawDescription: Can the header field of requests.post be a unicode object?


code:
player = raw_input("Enter player name")
wb = load_workbook("LeaguePlayers.xlsx")
ws = wb.active
for cell in ws.columns[0]: # get first column
    if cell.value == player:
        cost = cell.offset(column=4).value
        print("{0} costs {1}".format(player, cost))
        break

rawDescription: Using OPENPYXL to extract data from an EXCEL file


code:
def orde(i, s):
    t = sorted(s)
    return t[:t.index(i)]

s = ['A','B','C']
orde("B", s)

rawDescription: Total Order in Python

description: Total Order in Python


code:
def writeProfile(profileName, profileData):
    """ pickle user profile data """

    os.chdir(PROFILE_DIR)

    fileName = profileName + ".dat"
    f = open(fileName, "wb")
    pickle.dump(profileData, f)
    f.close()

    os.chdir("..")

rawDescription: Python game - creating a save file?

description: Python game - creating a save file


code:
import numpy as np
from matplotlib import pylab as pl

dataOne = get_data_one()
dataTwo = get_data_two()

hN = pl.hist(dataTwo, orientation='horizontal', normed=0, rwidth=0.8, label='ONE')
hS = pl.hist(dataOne, bins=hN[1], orientation='horizontal', normed=0,
    rwidth=0.8, label='TWO')

for p in hS[2]:
    p.set_width( - p.get_width())

xmin = min([ min(w.get_width() for w in hS[2]),
                min([w.get_width() for w in hN[2]]) ])
xmin = np.floor(xmin)
xmax = max([ max(w.get_width() for w in hS[2]),
                max([w.get_width() for w in hN[2]]) ])
xmax = np.ceil(xmax)
range = xmax - xmin
delta = 0.0 * range
pl.xlim([xmin - delta, xmax + delta])
xt = pl.xticks()
n = xt[0]
s = ['%.1f'%abs(i) for i in n]
pl.xticks(n, s)
pl.legend(loc='best')
pl.axvline(0.0)
pl.show()

rawDescription: back-to-back histograms in matplotlib

description: Back-to-back histograms in matplotlib


code:
from django.contrib.auth import login as django_login
from django.contrib.auth import authenticate

def login(request):
    ...
    req_dict = request.POST.copy()
    user = authenticate(
        username=req_dict['username'], password=req_dict['password'])

    if user:
        django_login(request, user)
    ...

rawDescription: login_required django decorator

description: Login_required django decorator


code:
class Cdr():

    def __iter__(self):
        return iter([self.name, self.my_value, self.my_datetime])

#from another class
with open(self.file_name, 'wb') as csv_file:
    wr = csv.writer(csv_file, delimiter=',')
    for cdr in cdr_list:
        wr.writerow(list(cdr))  # @Shankar suggestion

rawDescription: convert list of data object to csv

description: Convert list of data object to csv


code:
self.operators = ['+', '/', 'C',
                  '-', '%', 'M',
                  '*', '^', 'M+']

for index in range(9):
    Button(...).grid(padx=2,pady=2,row=index/3,column=index%3)

rawDescription: Need explanation for use of '%' and '/' to grid buttons with Tkinter


code:
# Assume this retrieves the dataset from a GeoTIFF file.
dataset = getDataSet(tiffFileLocation)

saveOptions = []
saveOptions.append("QUALITY=75")

# Obtains a JPEG GDAL driver
jpegDriver = gdal.GetDriverByName("JPEG")

# Create the .JPG file
jpegDriver.CreateCopy("imageFile.jpg", dataset, 0, saveOptions)

rawDescription: Convert GeoTIFF to JPEG and Extract GeoTIFF Headers in Python


code:
userquery = db.GqlQuery("SELECT * FROM User WHERE googleaccount = :1", users.get_current_user())
user = userquery.get() # Gets the first User instance from the query, or None
form = forms.AccountForm(data=request.POST or None, instance=user)

rawDescription: Datastore query outputting for Django form instance


code:
s = 'abbb'
[i[::-1] for i in reversed(re.findall(r'(?=(b*a))', s[::-1]))]

rawDescription: REGEX - using finditer()

description: REGEX - using finditer()


code:
# For the simple case
for value in np.nditer(a):
    do_something_with(value)

# This is similar to above
for value in a.ravel():
    do_somting_with(value)

# Or if you need the index
for idx in np.ndindex(a.shape):
    a[idx] = do_something_with(a[idx])

rawDescription: Dealing with multi-dimensional arrays when ndims not known in advance


code:
test = lambda f: f(lambda x: x + 1)(0)
z = lambda f: lambda x: x
test(z)
succ = lambda n: lambda f: lambda x: f(n(f)(x))
_1 = succ(z)
test(_1)
_2 = succ(_1)
test(_2)
plus = lambda m: lambda n: lambda f: lambda x: m(f)(n(f)(x))
_3 = plus(_1)(_2)
test(_3)
mult = lambda m: lambda n: lambda f: lambda x: m(n(f))(x)
_6 = mult(_2)(_3)
test(_6)
_5 = plus(_2)(_3)
_25 = mult(_5)(_5)
_4 = plus(_2)(_2)
_100 = mult(_25)(_4)
test(_100)

rawDescription: Python: nested lambdas -- `s_push: parser stack overflow Memory Error`


code:
import matplotlib.pyplot as plt
x = [37, 45]; y = [-0.67778, -0.67778]

# as an example for where to place the text we can use the mean
xmean = sum(i for i in x) / float(len(x))
ymean = sum(i for i in y) / float(len(y))

plt.plot(x, y, '--k', lw=1.2)
plt.annotate('some text', xy=(xmean,ymean), xycoords='data')
plt.show() # or plt.savefig('filename.png')

rawDescription: matplotlib plot Label along plot line

description: Matplotlib plot Label along plot line


code:
import re
with open("filename","r+") as f:
    text = f.read()
    modified_text, modified = re.subn(r'(?:^|(?<=\n))path\s\=.*',CurrentFilePath, text)
    if  modified:
        print ("Success!!!!")
    else:
        print ("Failure :(")
    f.seek(0)
    f.write(modified_text)
    f.truncate()

rawDescription: Replace entire line in a text file based on search using Python


code:
G = nx.erdos_renyi_graph(20,0.1)
color_map = []
for node in G:
    if node <10:
        color_map.append('blue')
    else: color_map.append('green')
nx.draw(G,node_color = color_map,with_labels = True)
plt.show()

rawDescription: How to set colors for nodes in networkx python?

description: Set colors for nodes in networkx python


code: call(["command", "argument", raw_input("enter file name:  ")])

rawDescription: How do I incorporate a raw_input as an argument in a function

description: Incorporate a raw_input as an argument in a function


code:
import unittest
import mock

class TestCaseName(unittest.TestCase):

    @mock.patch('path_to_module.AdWordsClient', autospec=True)
    @mock.patch('path_to_module.GoogleRefreshTokenClient', autospec=True)
    @mock.patch('path_to_module.tz', autospec=True)
    def test_get_account_timezone(self, tz_mock, adwords_client_mock, grefresh_token_client_mock):
        adwards_client_instance = mock.Mock()
        adwords_client_mock.return_value = test_get_account_timezone
        instance = AdWords(...)
        instance.get_account_timezone()
        adwards_client_instance.GetService.assert_called_with(...)

rawDescription: Mocking Googleads for Unit Tests

description: Mocking Googleads for Unit Tests


code:
def modify_duplicates_ordered(original):
    result = []
    for val in original:
        while val in result:
                val += 0.0001
        result.append(val)

rawDescription: How can I modify (not remove!) duplicated elements in a Python list, while preserving their order?

description: Modify (not remove!) duplicated elements in a Python list, while preserving their order


code:
for email, name, entry in feed:
    photo_link = e.GetPhotoLink()
    if photo_link:
        request = http.request(
            'GET',
            photo_link.href,
            headers={
                'Authorization':'OAuth %s' % client.current_token.access_token
            }
        )

        if request.status == 200:
            photo = str(request.read())
            fname = str(uuid.uuid4()) + '.jpg'
            image_file = open(dname + '/' + fname, 'wb')
            image_file.write(photo)
            image_file.close()
            result[email] = '/media/import/%s/%s' % (tid, fname) #str(photo.href) #

rawDescription: Google contacts. GetPhoto

description: Google contacts. GetPhoto


code:
import pygtk
pygtk.require('2.0')
import gtk
import gobject
import time

class MainWin(object):
    def destroy(self, widget, data=None):
        gtk.main_quit()
    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.connect("destroy", self.destroy)
        self.window.set_border_width(10)
        self.button = gtk.Button("Reset")
        self.button.connect("clicked", self.onclick)
        self.window.add(self.button)
        self.button.show()
        self.window.show()
        self.reset_timer = False
        self.count = 0
        self.duration = 1000
        self.timer = gobject.timeout_add(self.duration, self.update)
    def reset(self):
        print('Resetting timer')
        gobject.source_remove(self.timer)
        # start a new period call to update
        self.count = 0
        self.timer = gobject.timeout_add(self.duration, self.update)
    def onclick(self, widget):
        # Every action which resets the timer should call self.reset_timer().
        self.reset()
    def update(self):
        print('{t:.1f}: count = {i}'.format(t=time.time() % 100, i=self.count))
        self.count += 1
        return True
    def main(self):
        gtk.main()

if __name__=='__main__':
    MainWin().main()

rawDescription: nonblocking timer in python

description: Nonblocking timer in python


code:
#!/usr/bin/env python
from multiprocessing.dummy import Pool # thread pool
from tqdm import tqdm # $ pip install tqdm # simple progress report

def mp_process_image(filename):
    try:
       return filename, process_image(filename), None
    except Exception as e:
       return filename, None, str(e)

def main():
    # consider every non-blank line in the input file to be an image path
    image_paths = (line.strip()
                   for line in open('image_paths.txt') if line.strip())
    pool = Pool() # number of threads equal to number of CPUs
    it = pool.imap_unordered(mp_process_image, image_paths, chunksize=100)
    for filename, result, error in tqdm(it):
        if error is not None:
           print(filename, error)

if __name__=="__main__":
    main()

rawDescription: Multiprocessing in Python, each process handles part of a file


code:
def download(url, local_file):
    def progress(blocks_read, block_size, total_size):
        percent = min(int(blocks_read * block_size * 100 / total_size), 100)
        sys.stdout.write("\rdownloading {}: {:2}%".format(local_file, percent))
        if percent == 100:
            sys.stdout.write('\n')
        sys.stdout.flush()

    urllib.urlretrieve(url, local_file, reporthook=progress)

# call download function
download("http://ww1.microchip.com/downloads/en/DeviceDoc/pk2cmdv1-20Linux2-6.tar.gz",
         "pickit.tar.gz")

rawDescription: How do I read the size of an archive on web

description: Read the size of an archive on web


rawDescription: Two Flask Applications at same time

description: Two Flask Applications at same time


code:
def status_view_directive(config, view, **view_config_kwargs):
    config.add_view(
        view=view,
        route_name='status',
        **view_config_kwargs
        )

rawDescription: Adding views using directives and actions in pyramid


rawDescription: How to create an empty zip file?

description: Create an empty zip file


code:
children_rate = [3, 3, 5, 7, 10]
bucket = 100

lo, hi = 0, bucket * max (children_rate)
while lo < hi:
    me = (lo + hi) // 2
    if sum (me // i for i in children_rate) < bucket:
        lo = me + 1
    else:
        hi = me

print (lo)

rawDescription: Optimization in a time based algorithm

description: Optimization in a time based algorithm


rawDescription: How to create open ChainShape in pybox2d

description: Create open ChainShape in pybox2d


code:
import tarfile

with tarfile.open("TarName.tar.gz") as tar:
    tar.extractall()

rawDescription: How can I read a compressed folder file using python?

description: Read a compressed folder file using python


code:
# Definitions of xs, ys and zs
nx, ny = 20, 30
x = np.linspace(0, np.pi, nx)
y = np.linspace(0, 2*np.pi, ny)

X,Y = np.meshgrid(x, y)

xs = X.reshape((nx*ny, 1))
ys = Y.reshape((nx*ny, 1))

## Arbitrary definition of zs
zs = np.cos(3*xs/2.)+np.sin(5*ys/3.)**2

## new points where I want the interpolations
points = np.random.rand(1000, 2)

import scipy.interpolate
zs2 = scipy.interpolate.griddata(np.hstack((xs, ys)), zs, points)

rawDescription: Given a set of points defined in (X, Y, Z) coordinates, interpolate Z-value at arbitrary (X, Y)


code:
np.fromiter('3300', dtype=np.float64)
np.fromiter('3300', dtype=np.float64, count=4)  # count=len(..)

rawDescription: numpy fromstring empty string separator

description: Numpy fromstring empty string separator


code:
if x and y: # logical operation
   ...
z = z & 0xFF # bitwise operation

rawDescription: Logical vs bitwise

description: Logical vs bitwise


code:
def facebook_login(request):
    """
    Facebook login page
    """
    if request.REQUEST.get("device"):
        device = request.REQUEST.get("device")
    else:
        device = "user-agent"

    params = {}
    params["client_id"] = FACEBOOK_APP_ID
    params["redirect_uri"] = request.build_absolute_uri(reverse("socialauth_facebook_login_done"))

    url = "https://graph.facebook.com/oauth/authorize?"+urllib.urlencode(params)

    return HttpResponseRedirect(url)

def facebook_login_done(request):
    user = authenticate(request=request)

    if not user:
        request.COOKIES.pop(FACEBOOK_API_KEY + '_session_key', None)
        request.COOKIES.pop(FACEBOOK_API_KEY + '_user', None)

        # TODO: maybe the project has its own login page?
        logging.debug("SOCIALAUTH: Couldn't authenticate user with Django, redirecting to Login page")
        return HttpResponseRedirect(reverse('socialauth_login_page'))

    login(request, user)

    logging.debug("SOCIALAUTH: Successfully logged in with Facebook!")

    if request.GET.get('next'):
        return HttpResponseRedirect(request.GET.get('next'))
    else:
        return HttpResponseRedirect(LOGIN_REDIRECT_URL)

rawDescription: Facebook login for Django and url redirection?


code:
options = [('python','hello.py'), ('python','hello2.py')]
for option in options:
    process = subprocess.Popen(option)
    #do something here

rawDescription: Python - Convert string to command

description: Python - Convert string to command


code:
import Image
import ImageOps

x = Image.open('test.png')
y = ImageOps.expand(x,border=5,fill='red')
y.save('test2.png')

rawDescription: applying image decoration (border) in Python (programatically)

description: Applying image decoration (border) in Python (programatically)


code:
import matplotlib.animation as animation
import numpy as np
from pylab import *

dpi = 100

def ani_frame():
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_aspect('equal')
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)

    im = ax.imshow(rand(300,300),cmap='gray',interpolation='nearest')
    im.set_clim([0,1])
    fig.set_size_inches([5,5])

    tight_layout()

    def update_img(n):
        tmp = rand(300,300)
        im.set_data(tmp)
        return im

    #legend(loc=0)
    ani = animation.FuncAnimation(fig,update_img,300,interval=30)
    writer = animation.writers['ffmpeg'](fps=30)

    ani.save('demo.mp4',writer=writer,dpi=dpi)
    return ani

rawDescription: Generating movie from python without saving individual frames to files


code:
for i in d:
    doSomethingWith(i)

rawDescription: Iterate over deque in python

description: Iterate over deque in python


rawDescription: Python logging: How to set time to GMT

description: Python logging: How to set time to GMT


code:
from ipaddress import IPv4Network

network = IPv4Network('10.220.1.0/24')
reserved = {'10.220.1.1', '10.220.1.2', '10.220.1.3', '10.220.1.5'}

hosts_iterator = (host for host in network.hosts() if str(host) not in reserved)

# Using hosts_iterator:
print(next(hosts_iterator))  # prints 10.220.1.4
print(next(hosts_iterator))  # prints 10.220.1.6
print(next(hosts_iterator))  # prints 10.220.1.7

# Or you can iterate over hosts_iterator:
for host in hosts_iterator:
    print(host)

rawDescription: Find next available IP address in python


code:
position = {
    (x, y): {
        shapeid: {'meandiff': curim[shape].mean() - curim[contour].mean(),
                  'maxmin': int(curim[shape].min()) - int(curim[contour].max())}
        for shapeid,(shape,contour) in enumerate(zip(shapes,contours))
    }
    for (x,y,curim) in ((x, y, im[x:x+shapesize, y:y+shapesize])
            for x in range(imdim[0]-shapesize+1)
            for y in range(imdim[1]-shapesize+1)
    )
}

rawDescription: Any way to dict comprehension in dict comprehension in dict comprehension this?


code:
class DeudaForm(forms.ModelForm):

    class Meta:
        model = Deuda
        exclude = ('propietario',)

    def __init__(self, propietario):
        forms.ModelForm.__init__(self)
        self.fields['adeudado'].queryset = User.objects.exclude(pk=d.propietario.pk)

rawDescription: Delimiting choices in ModelChoiceField

description: Delimiting choices in ModelChoiceField