code:
#!/usr/bin/env python
import rospy
from std_msgs.msg import Float32

def callback(data):
    distance = data.data
    rospy.loginfo(rospy.get_caller_id() + "distance = ", distance )
    #here update your label, I assume the following (maybe not correct)
    v = StringVar()
    v.set(distance)
    self.clock = Label(frame, font=('times', 20, 'bold'), bg='green', textvariable = v)
    self.clock.pack(fill=BOTH, expand=1)

def listener():
    rospy.init_node('listener', anonymous=True)
    rospy.Subscriber("distance", Float32, self.callback)
    # spin() simply keeps python from exiting until this node is stopped
    rospy.spin()

if __name__ == '__main__':
    listener()

rawDescription: How do we dynamically change the text in label widget of Tkinter according to the change of subscribed topic message?


code:
Product.objects.all().order_by(\
        Case(When(price=0, then=Value(MAX_INT)), default=F('price')))

rawDescription: Order a Django queryset in ascending order but with 0-valued items at the end


code:
import random, sys

for i in xrange(500):
   sys.stdout.write(chr(random.randrange(256)))

rawDescription: sending raw bits to the terminal in python

description: Sending raw bits to the terminal in python


code:
class DbQuery(object):
  def __init__(self,query):
        self.query = query

class DbResultSet(object):
  def __init__(self, dbquery):
        self.result = []
        self.dbquery = dbquery
  def __getattr__(self, name):
        return getattr(self.dbquery,name)

rawDescription: python: using attributes as an enum, and then assigning the attributes to another class

description: Python: using attributes as an enum, and then assigning the attributes to another class


code:
#Months
#January=0
#February=31
#March=60
#April=91
#May=121
#June=152
#July=182
#August=213
#September=244
#October=274
#November=305
#December=335

monthvalue = -1

#Title
print("Convert: Date to day and day to date.")

#user inputs a date
month = input("\nPick a Month (Make sure to capitalize the first letter): ")
month = month.lower()
month = month[:1].capitalize() + month[1:]

if(month=="January"):
    monthvalue = 0

if(month=="February"):
    monthvalue = 31

if(month=="March"):
    monthvalue = 60

if(month=="April"):
    monthvalue = 91

if(month=="May"):
    monthvalue = 121

if(month=="June"):
    monthvalue = 152

if(month=="July"):
    monthvalue = 182

if(month=="August"):
    monthvalue = 213

if(month=="September"):
    monthvalue = 244

if(month=="October"):
    monthvalue = 274

if(month=="November"):
    monthvalue = 305

if(month=="December"):
    monthvalue = 335

if(monthvalue<0):
    print("Error, you have not entered a valid month.")
    xwdwa=input("\nPress any key to continue...")
    exit(0)

day=int(input("Pick the day of the date you wish to input: "))
if day<1 or day>31:
    print("Error, no months have greater than 31 days or less than 1 day.")

total = monthvalue + day

print("Your date is ", total, " days into a leap year.")
exitvar = input("Press any key to continue.")

rawDescription: Python: Date to Day conversion

description: Python: Date to Day conversion


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

colors="bgrcmyk"

for i in range(1,len(sys.argv)):
    gen,gen_len=np.genfromtxt(sys.argv[i],usecols=(0,3),unpack=True,comments='#')
    plt.plot(gen,gen_len,c=colors[i])

plt.savefig('result.png')

rawDescription: Different colors for each line in the graph


rawDescription: Sort a pandas datetime index

description: Sort a pandas datetime index


code:
widget = Button(None, text='Mouse Clicks')

def hello(event):
    print("hello -Single Click, Button-l")
    widget.bind('<Button-1>', goodbye)

def goodbye(event):
    print("goodbye -Single Click, Button-1")
    widget.bind('<Button-1>', hello)

# Initial bind
widget.bind('<Button-1>', hello)

rawDescription: I want to toggle between event binds in tkinter python 3.1


code:
import re
str = "This\sis a weird\sstring"
str.split("\s")                    # treated literally
re.split("\s", str)                # regex

rawDescription: why doesn't line.split('\s') do the same as line.split()?

description: Why doesn't line.split('\s') do the same as line.split()


code:
st = 'asdf'
[st[:n+1] for n in range(len(st))]

rawDescription: python: list comprehension tactics

description: Python: list comprehension tactics


rawDescription: How to set a value to elements in a column filtered by another array

description: Set a value to elements in a column filtered by another array


code:
def change_to_yyyymmdd(str_mmddyyyy):
    import re
    try:
        m,d,y = re.findall(r"^(\d{2}).(\d{2}).(\d{4})",str_mmddyyyy)[0]
    except IndexError:
        raise TypeError("Date not in mm/dd/yyyy format.")
    return "-".join([y,m,d])

rawDescription: CSVKit Failing on Non-ISO8601 Format

description: CSVKit Failing on Non-ISO8601 Format


code:
from datetime import datetime
datetime.strptime("2012-11-09-165420", "%Y-%m-%d-%H%M%S")

rawDescription: split string into groups of given size

description: Split string into groups of given size


code:
PinyinToneMark = {
    0: "aoeiuv\u00fc",
    1: "\u0101\u014d\u0113\u012b\u016b\u01d6\u01d6",
    2: "\u00e1\u00f3\u00e9\u00ed\u00fa\u01d8\u01d8",
    3: "\u01ce\u01d2\u011b\u01d0\u01d4\u01da\u01da",
    4: "\u00e0\u00f2\u00e8\u00ec\u00f9\u01dc\u01dc",
}

def decode_pinyin(s):
    s = s.lower()
    r = ""
    t = ""
    for c in s:
        if c >= 'a' and c <= 'z':
            t += c
        elif c == ':':
            assert t[-1] == 'u'
            t = t[:-1] + "\u00fc"
        else:
            if c >= '0' and c <= '5':
                tone = int(c) % 5
                if tone != 0:
                    m = re.search("[aoeiuv\u00fc]+", t)
                    if m is None:
                        t += c
                    elif len(m.group(0)) == 1:
                        t = t[:m.start(0)] + PinyinToneMark[tone][PinyinToneMark[0].index(m.group(0))] + t[m.end(0):]
                    else:
                        if 'a' in t:
                            t = t.replace("a", PinyinToneMark[tone][0])
                        elif 'o' in t:
                            t = t.replace("o", PinyinToneMark[tone][1])
                        elif 'e' in t:
                            t = t.replace("e", PinyinToneMark[tone][2])
                        elif t.endswith("ui"):
                            t = t.replace("i", PinyinToneMark[tone][3])
                        elif t.endswith("iu"):
                            t = t.replace("u", PinyinToneMark[tone][4])
                        else:
                            t += "!"
            r += t
            t = ""
    r += t
    return r

rawDescription: Convert numbered pinyin to pinyin with tone marks


code:
import sys
from PyQt4.QtCore import Qt
from PyQt4.QtGui import QApplication, QWidget, QSlider, QLabel, QVBoxLayout

class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.v_layout = QVBoxLayout()

        self.slider = QSlider()
        self.slider.setOrientation(Qt.Horizontal)
        self.label = QLabel('Slider at position 0')

        self.v_layout.addWidget(self.label)
        self.v_layout.addWidget(self.slider)

        self.setLayout(self.v_layout)

        self.slider.valueChanged.connect(self.slider_moved)

    def keyPressEvent(self, event):
        if event.key()==Qt.Key_Right:
            self.slider.setValue(self.slider.value() + 1)
        elif event.key()==Qt.Key_Left:
            self.slider.setValue(self.slider.value() - 1)
        else:
            QWidget.keyPressEvent(self, event)

    def slider_moved(self, position):
        self.label.setText('Slider at position %d' % position)

if __name__ == '__main__':
  app = QApplication(sys.argv)

  widget = Widget()
  widget.show()

  sys.exit(app.exec_())

rawDescription: QSlider and Key Press Event

description: QSlider and Key Press Event


code:
self.posts = self.driver.find_elements_by_xpath("//div[@class='post']")

for post in self.posts:
    self.image = post.find_element_by_xpath(".//a/img")
    str = self.image.get_attribute("src").replace("b.", ".")

    self.title = post.find_element_by_xpath(".//div/p")
    print(self.title.text)

rawDescription: Losing WebElement context inside for loop ? Why?


rawDescription: How to split list item?

description: Split list item


code:
import cStringIO

class MyWriter(object):

    def __init__(self, stdout):
        self.stdout = stdout
        self.dumps = cStringIO.StringIO()
        self.final = None

    def write(self, text):
        self.stdout.write(smart_unicode(text).encode('cp1251'))
        self.dumps.write(text)

    def close(self):
        self.stdout.close()
        self.final = self.dumps.getvalue()
        self.dumps.close()

    def getvalue(self):
        if self.final is not None:
            return self.final
        return self.dumps.getvalue()

rawDescription: Object for storing strings in Python

description: Object for storing strings in Python


code:
from scripttest import TestFileEnvironment

env = TestFileEnvironment('./scratch')

def test_script():
    env.reset()
    result = env.run('do_awesome_thing testfile --with extra_win --file %s' % filename)
    # or use a list like ['do_awesome_thing', 'testfile', ...]
    assert result.stdout.startswith('Creating awesome file')
    assert filename in result.files_created

rawDescription: testing command line utilities

description: Testing command line utilities


code: do_something() if 2 in [x.get('arm_id') for x in tcp_packet['red']] else None

rawDescription: How to parse a json list?

description: Parse a json list


code:
import Tkinter as tk
import tkFont

the_window = tk.Tk()

def changefont():
    label_font.config(size=12)

b = tk.Button(the_window, text="Reduce label font", command=changefont)
b.pack()

label_font = tkFont.Font(family='Arial', size=25)

for i in range(5):
    lbl = tk.Label(the_window, text='Label ' + str(i), font=label_font,
        borderwidth=1, relief=tk.SOLID)
    lbl.pack()

the_window.mainloop()

rawDescription: Resizing font in tkinter GUI

description: Resizing font in tkinter GUI


code:
MathJax.Hub.Config({
  "HTML-CSS": {
    availableFonts: ["TeX"],
    preferredFont: "TeX",
  }
});

rawDescription: How do I configure mathjax for iPython notebooks?

description: Configure mathjax for iPython notebooks


code:
import numpy
from scipy import interpolate
x = numpy.array([0.0, 0.60, 1.0])
y = numpy.array([0.0, 0.25, 0.80, 1.0])
z = numpy.array([
   [ 1.4 ,  6.5 ,  1.5 ,  1.8 ],
   [ 8.9 ,  7.3 ,  1.1 ,  1.09],
   [ 4.5 ,  9.2 ,  1.8 ,  1.2 ]])
# you have to set kx and ky small for this small example dataset
# 3 is more usual and is the default
# s=0 will ensure this interpolates.  s>0 will smooth the data
# you can also specify a bounding box outside the data limits
# if you want to extrapolate
sp = interpolate.RectBivariateSpline(x, y, z, kx=2, ky=2, s=0)

sp([0.60], [0.25])  # array([[ 7.3]])
sp([0.25], [0.60])  # array([[ 2.66427408]])

description: Python/Scipy Interpolation (map_coordinates)


code:
import ctypes
from ctypes.wintypes import MAX_PATH

dll = ctypes.windll.shell32
buf = ctypes.create_unicode_buffer(MAX_PATH + 1)
if dll.SHGetSpecialFolderPathW(None, buf, 0x0005, False):
    print(buf.value)
else:
    print("Failure!")

rawDescription: How do you get the exact path to "My Documents"?

description: Get the exact path to "My Documents"


code:
r=re.compile('(b+)')
r.search('abbbc')
r.search('abbbc').group(0)
r.sub('z', 'abbbc')

rawDescription: In Python, how do I do a string replacement AND retrive the replaced substring?


code:
import Image
from PIL import ImageChops

im1 = Image.open("splash.png")
im2 = Image.open("splash2.png")

diff = ImageChops.difference(im2, im1)

rawDescription: importing python modules - ImageChops

description: Importing python modules - ImageChops


code:
def fix_imports(top_dir, not_ui_keys):
    """Walk through the directory and substitute the wrong imports """
    from itertools import imap,ifilter
    gen = ifilter(None,imap(extract_dotted, not_ui_keys))
    repl = dict((dotted,add_model(dotted)) for dotted in gen)

    py_files = (path.join(root, x)
                for root, dirs, files in walk(top_dir)
                for x in files if x[-3:]=='.py')
    for py in py_files:
        with open(py) as opf:
            res = replace_text(opf.read(), repl)

rawDescription: Replace recursively from a replacement map


rawDescription: Cast types on the fly while creating dataframe


code:
def maxafter(l):
    max = 1
    for elt in l:
        if elt > max: max = elt
        yield max
[[x for x in maxafter(l[::-1])][::-1] for l in L]

rawDescription: Assign elements of 2d list before integer > 1 (python)


code:
client = app.test_client()
response = client.get('/your/url/',
                      environ_base={'HTTP_USER_AGENT': 'Chrome, etc'})

rawDescription: Setting (mocking) request headers for Flask app unit test


code:
gray = (.5,.5,.5)
orange = (1.0, 0.647, 0.0)
red = (1.0, 0.0, 0.0)

clrs = [gray for xx in bins]

idxs = pdf.argsort()
idxs = idxs[::-1]
oranges = idxs[(cumsum(pdf[idxs])*binwidth < 0.8).nonzero()]
reds = idxs[(cumsum(pdf[idxs])*binwidth < 0.6).nonzero()]

for idx in oranges:
    clrs[idx] = orange

for idx in reds:
    clrs[idx] = red

bar(left=bins,height=pdf,width=binwidth,color=clrs)

rawDescription: Python/matplotlib Show confidence levels in a histogram


code:
class Article(models.Model):
    ...

    def save(self, *args, **kwargs):
        if not self.url:
            self.url = self.title.lower()

        super(Article, self).save(*args, **kwargs)

rawDescription: Change form exclude value in django after validation


code: c.execute("UPDATE table1 SET waiting=%s where dept='billing'", (data.strip(),))

rawDescription: read value from file then pass value in sql UPDATE command(python script)

description: Read value from file then pass value in sql UPDATE command(python script)


code:
import json
data = json.loads("[1, 2, 3]")

rawDescription: Does converting json to dict with eval a good choice?


code:
mylastrow ='$A$70006'
...
myrange = xlwings.Range('Sheet1', 'A2:{0}'.format(mylastrow)).value

rawDescription: Python: Passing Variable to Range()

description: Python: Passing Variable to Range()


code:
TINYMCE_DEFAULT_CONFIG = {
    # your other configuration
    'theme_advanced_buttons3_add': 'code',
}

rawDescription: Editing the raw HTML inside a TinyMCE control


code:
import openpyxl

wb = openpyxl.load_workbook(filename = r'test108.xlsx')
ws = wb.worksheets[0]

wb_out = openpyxl.Workbook()
ws_out = wb_out.worksheets[0]

n = 1

for x in range (0, 1000):
    if ws.cell(row=x, column=27).value == '7.image2.jpg':
        ws_out.cell(row=n, column=1).value = ws.cell(row=x, column=26).value #x changed
        ws_out.cell(row=n, column=2).value = ws.cell(row=x, column=10).value #x changed
        ws_out.cell(row=n, column=3).value = ws.cell(row=x, column=17).value #x changed
        n += 1

wb_out.save('output108.xlsx')

rawDescription: Conditional parsing and output of xlsx files with Openpyxl


rawDescription: matplotlib set_label_position no effect in 3d?

description: Matplotlib set_label_position no effect in 3d


code:
# provided that your hashtable is in this file
# and its size is 4 GiB
with open("hashtable", "r+b") as f:
    # memory-map the file, size 0 means whole file
    mm = mmap.mmap(f.fileno(), 0)

    # here mm behaves like 4 billion element bytearray
    # that you can read from and write to. changes
    # are flushed to the underlying file.

    # set 1 byte in the file
    mm[123456789] = 42

    # ensure that changes are written to disk
    mm.flush()

    # close the mapping
    mm.close()

rawDescription: How many bytes are typically loaded into memory when using file.seek() in python?


code: birthdays.sort(key = lambda d: (d.month, d.day))

rawDescription: Sorting datetime objects while ignoring the year?


code:
def singleton(cls):
    class C(cls):
        _instance = None
        def __new__(c, *args, **kwargs):
            if type(c._instance) != c:
                c._instance = cls.__new__(c, *args, **kwargs)
            return c._instance
    C.__name__ = cls.__name__
    return C

rawDescription: Decorated classes inheritance and classmethods


code:
class Calculator:
    def __init__(self):
        # ... this is where you'd set up the rest of the GUI ..
        self.buttons = {}  # Store the calculator buttons in a dictioanry
        for num in [str(x) for x in range(10)]:
            self.buttons[num] = Tkinter.Button(self.keyFrame, text=num, command=self.callbackCreator(num))
        self.currentNumber = ""

    def callbackCreator(self, num):
        return lambda event:self.buttonCallback(num)

    def buttonCallback(key):
        if key in "0123456789":        # Check if the button is a digit or not
            self.currentNumber += key  # add new digit

rawDescription: Python - Continous Button Inputing (Sort of like BCD)


code:
import sys, shutil
if 'clean' in sys.argv:
    shutil.rmtree('cxxextension/build')

rawDescription: clean C++ extension build directory in setup.py

description: Clean C++ extension build directory in setup.py


code:
import imp
import sys
import os

module_path = sys.argv[1]
module_name = os.path.splitext(module_path)[0]

mymodule = imp.load_source(module_name, module_path)

result = mymodule.take_turn()

print("The result is: {}".format(result))

rawDescription: Importing a file given in the command line


code:
from pydub import AudioSegment

def detect_leading_silence(sound, silence_threshold=-50.0, chunk_size=10):
    '''
    sound is a pydub.AudioSegment
    silence_threshold in dB
    chunk_size in ms

    iterate over chunks until you find the first one with sound
    '''
    trim_ms = 0 # ms
    while sound[trim_ms:trim_ms+chunk_size].dBFS < silence_threshold:
        trim_ms += chunk_size

    return trim_ms

sound = AudioSegment.from_file("/path/to/file.wav", format="wav")

start_trim = detect_leading_silence(sound)
end_trim = detect_leading_silence(sound.reverse())

duration = len(sound)
trimmed_sound = sound[start_trim:duration-end_trim]

rawDescription: remove silence at the beginning and at the end of wave files with PyDub

description: Remove silence at the beginning and at the end of wave files with PyDub


code:
radiogroup = Frame(master)
# self.mit = Radiobutton(radiogroup, ...)
# ...
self.mit.grid(row=0, column=0)
self.gpl2.grid(row=0, column=1)
self.gpl3.grid(row=0, column=2)
radiogroup.grid(row=4, column=0)

rawDescription: Radiobutton horizontal center alignment Tkinter


code:
df
header = [1, 1, 2, 2, 3, 3]
df.columns = pd.MultiIndex.from_tuples(list(zip(header, df.columns)))
df

rawDescription: Pandas: multiindexing column headers

description: Pandas: multiindexing column headers


code:
import clr
clr.AddReference('YourAssemblyName')

from YourAssemblyName.WhateverNamespace import MyClass, MyEnum

# Now these should work, since the objects have been properly imported
mc = MyClass()
me = MyEnum.One

rawDescription: Access host class from IronPython script


code:
from tkinter import *

def show_entry_fields(v1, v2):
   print("Username: %s\nPassword: %s" % (v1.get(), v2.get()))

if __name__ == "__main__":
  master = Tk()
  Label(master, text="Username").grid(row=0)
  Label(master, text="Password").grid(row=1)

  v1 = StringVar()
  v2 = StringVar()

  e1 = Entry(master, textvariable=v1)
  e2 = Entry(master, textvariable=v2)

  e1.grid(row=0, column=1)
  e2.grid(row=1, column=1)

  Button(master, text='Quit', command=master.quit).grid(row=3, column=0, sticky=W, pady=4)
  Button(master, text='Submit', command=(lambda : show_entry_fields(v1, v2))).grid(row=3, column=1, sticky=W, pady=4)

  master.mainloop()

rawDescription: Python console output to variable

description: Python console output to variable


code:
import matplotlib.pyplot as plt

hf, ha = plt.subplots(3,2)
ha[-1, -1].axis('off')

plt.show()

rawDescription: How can I make a blank subplot in matplotlib?

description: Make a blank subplot in matplotlib


code:
cast_unique = {}
for person in cast:
    if person.people not in cast_unique:
        cast_unique[person.people] = person
    else:
        cast_unique[person.people].role_title = '{0} / {1}'.format(cast_unique[person.people].role_title, person.role_title)

rawDescription: Django, filter and group query results by a field


code:
text_file = 'C:\AA\aa.txt'
lines = open(text_file).read().splitlines()
numbers = []
Vector = []
section = ''
for line in lines:
    line = line.strip()
    if line.startswith('Some_numbers'):
        section = 'numbers'
        continue
    elif line.startswith('some_vector'):
        section = 'vectors'
        continue
    elif section == 'numbers':
        numbers.append(line) # or numbers.append(int(line)) , whichever you want
    elif section == 'vectors':
        Vector.append(line)

rawDescription: Reading input data to array(s) with multiple delimiters and headings


code:
import numpy as np
arr = np.array(test)
arr[1:3] += 1

rawDescription: Python increment part of an array

description: Python increment part of an array


code:
with open(file, "r") as f:
    line = f.readline(max_chars)
    while line:
        print(line, end='')
        line = f.readline(max_chars)

rawDescription: 10+ gig file reading problems Python

description: 10+ gig file reading problems Python


rawDescription: Pandas data frame from dictionary

description: Pandas data frame from dictionary


code:
fig, ax = make_example_plot()
tform = blended_transform_factory(ax.transData, ax.transAxes)
ax.annotate(label, xy=(r, 0), xycoords=tform,
            xytext=(r, 0.9), textcoords=tform, fontsize='xx-large',
            ha='center', va='center', color='r', arrowprops=arrowprops)

rawDescription: Is it possible to anchor a matplotlib annotation to a data coordinate in the x-axis, but to a relative location in the y-axis?


code:
import time, sys

for letter in "Stack Overflow":
    sys.stdout.write(letter)
    sys.stdout.flush()
    time.sleep(1) # that's in seconds, adjust at will

sys.stdout.write('\n')

rawDescription: How Can I Print Running Text? For Example to Print "Stack" Python Will Print S then t then a then c and then k?


code:
a = [1, 2, 3, 4, 5]
b = set([9, 7, 6, 5, 1, 0])
[i for i, item in enumerate(a) if item in b]

rawDescription: compare two lists in python and return indices of matched values

description: Compare two lists in python and return indices of matched values


code:
previous_pixel = None
for y in xrange(image_test.size[1]):
    for x in xrange(image_test.size[0]):
        currentPixel_2 = image_test.getpixel((x,y))
        if currentPixel_2 == (0,0,0) and previous_pixel:
            image_test.putpixel((x,y), previous_pixel)
        else:
            previous_pixel = currentPixel_2

rawDescription: Python Imaging Library- Changing a colour for the last one encountered


rawDescription: flask-sqlalchemy - PostgreSQL - Define specific schema for table?

description: Flask-sqlalchemy - PostgreSQL - Define specific schema for table


code:
# ... import 're' and pull username from DB
normalized_username = re.sub('[,.]', '', real_username)
# query using the normalized username

rawDescription: Django: How to query terms with punctuation (ie: !.;’) insensitivity?


code:
class BookPrioInline(admin.TabularInline):
    model = BookPrio

class AuthorAdmin(admin.ModelAdmin):
    inlines = (BookPrioInline,)

    def change_view(self, request, object_id, extra_context=None):
          def formfield_for_foreignkey(self, db_field, request, **kwargs):
              if db_field.name == 'book':
                  kwargs['queryset'] = Book.objects.filter(author__id=object_id)
              return super(ItemInline, self).formfield_for_foreignkey(db_field, request, **kwargs)

          ItemInline.formfield_for_foreignkey = formfield_for_foreignkey

          self.inline_instances = [ItemInline(self.model, self.admin_site)]

          return super(AuthorAdmin, self).change_view(request, object_id,
              extra_context=extra_context)

admin.site.register(Author, AuthorAdmin)

rawDescription: Filter Foreignkey within Inlineform

description: Filter Foreignkey within Inlineform


rawDescription: Sorting sets (not a single set)

description: Sorting sets (not a single set)


code: set(range(1, n + 1)).difference(lst)

rawDescription: A better solution for a card game

description: A better solution for a card game


code:
def search(d, baz):
    if baz in d:
        return d[baz]
    for value in d.values():
        if isinstance(value, dict):
            ret = search(value, baz)
            if ret:
                return ret
foo = {"foo" : {"bar": {"baz": "some value"}}}
search(foo, 'baz')
search(foo, 'spam')

rawDescription: is it possible to get a grandchild dict key's value without iterating

description: Is it possible to get a grandchild dict key's value without iterating


code:
global_iterator = 0

def numerate(table, tree):
    global global_iterator
    for item in tree:
        global_iterator += 1

        if type(item) == type(1):
            table.append(node(item, global_iterator))
            index = len(table)
        else:
            table.append(node(item[0], global_iterator))
            index = len(table)

            if len(item) > 1:
                table.append(numerate(table, item[1]))

        global_iterator += 1

        table[index-1].add_right(global_iterator)

    return table

table = numerate([], tree)

rawDescription: python - mptt for nested lists

description: Python - mptt for nested lists


code:
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker

fig,ax=plt.subplots()

#Spacing between each line
intervals = float(sys.argv[1])

loc = plticker.MultipleLocator(base=intervals)
ax.xaxis.set_major_locator(loc)
ax.yaxis.set_major_locator(loc)

# Add the grid
ax.grid(which='major', axis='both', linestyle='-')

rawDescription: PyPlot - Setting grid line spacing for plot


code: k, v = [x.strip() for x in line.lower().split(':')]

rawDescription: `strip`ing the results of a split in python


code:
ax1.set_ylim( -.1, 1.1 )
ax1.set_yticks( np.linspace(0, 1, 10) )

ax1.set_xscale('log')

rawDescription: graphing scatter for ranges in python's matplotlib

description: Graphing scatter for ranges in python's matplotlib


code:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class Window(QtWidgets.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        widget = QtWidgets.QWidget(self)
        layout = QtWidgets.QHBoxLayout(widget)
        self.mdi = QtWidgets.QMdiArea(self)
        self.leftScroll = Pane(
            QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft, self)
        self.rightScroll = Pane(
            QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft, self)
        layout.addWidget(self.leftScroll)
        layout.addWidget(self.mdi)
        layout.addWidget(self.rightScroll)
        self.setCentralWidget(widget)
        for scroll in self.leftScroll, self.rightScroll:
            for index in range(4):
                widget = QtWidgets.QTextEdit()
                widget.setText('one two three four five')
                scroll.addWidget(widget)

class Pane(QtWidgets.QScrollArea):
    MinWidth = 186

    def __init__(self, alignment=0, parent=None):
        super().__init__(parent)
        self.mainWidget = QtWidgets.QWidget(self)
        self.mainLayout = QtWidgets.QVBoxLayout(self.mainWidget)
        self.mainLayout.setAlignment(alignment)
        self.mainLayout.setContentsMargins(0, 0, 0, 0)
        self.mainLayout.setSpacing(0)
        self.setContentsMargins(0, 0, 0, 0)
        self.setFrameStyle(QtWidgets.QFrame.NoFrame)
        self.setFixedWidth(Pane.MinWidth)
        self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
        self.setSizePolicy(QtWidgets.QSizePolicy.Maximum,
                           QtWidgets.QSizePolicy.Ignored)
        self.setWidgetResizable(True)
        self.setWidget(self.mainWidget)
        self.verticalScrollBar().installEventFilter(self)

    def addWidget(self, widget):
        self.mainLayout.addWidget(widget)

    def removeWidget(self, widget):
        self.mainLayout.removeWidget(widget)

    def eventFilter(self, source, event):
        if isinstance(source, QtWidgets.QScrollBar):
            if event.type() == QtCore.QEvent.Show:
                self.setFixedWidth(Pane.MinWidth + source.width())
            elif event.type() == QtCore.QEvent.Hide:
                self.setFixedWidth(Pane.MinWidth)
        return super(Pane, self).eventFilter(source, event)

if __name__ == '__main__':

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

rawDescription: Qt.ScrollBarAsNeeded not showing scrollbar when it's actually needed


code: min_tuple = min(l, key=lambda x:x[1])

rawDescription: Get min int in a list of tuples of (int, string) in Python


code:
sentence = 'hello world cat dog'
words = ['cat', 'bear', 'dog']
[w*(sentence.find(w)>=0) for w in words]

rawDescription: regex or statement in any order

description: Regex or statement in any order


code: [x for x in li if 'ar' in x[2]]

rawDescription: python how to search an item in a nested list

description: Python how to search an item in a nested list


code: return 1 - (-value%1) if value > 0 else value%1

rawDescription: Is there a better way to write this addition function?


code:
class LongHandler(tornado.web.RequestHandler):
    @thread_pool.in_thread_pool
    def long_time_function(self, callback):
        time.sleep(5)
        callback("foo")

rawDescription: Tornado non-blocking request

description: Tornado non-blocking request


code:
def insert(item, tree):
    if (item < tree.entry):
        if (tree.left != None):
            insert(item, tree.left)
        else:
            tree.left = Tree(item)
    else:
        if (tree.right != None):
            insert(item, tree.right)
        else:
            tree.right = Tree(item)

rawDescription: Inserting a value into a Binary Search Tree in Python


code:
counter = 0
nextMillion = 1000000
if counter > nextMillion:
    nextMillion += 1000000
    # Print your message about the counter here.

rawDescription: Python: Detect when a variable exceeds an interval of thresholds


code:
#!/usr/bin/env python

import wx
import wx.grid

app = wx.App(False)

class InfoPane(wx.grid.Grid):
    def __init__(self, parent):
        wx.grid.Grid.__init__(self, parent)

        # Set up the presentation
        self.SetRowLabelSize(0)
        self.CreateGrid(1, 6)

        self.SetColLabelAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTRE)
        self.SetColLabelValue(0, "Name")
        self.SetColLabelValue(1, "Status")
        self.SetColLabelValue(2, "")
        self.SetColLabelValue(3, "File")
        self.SetColLabelValue(4, "Last Action")
        self.SetColLabelValue(5, "Other Info")

frame = wx.Frame(None)
panel = wx.Panel(frame)
info_pane = InfoPane(panel)

note_sizer = wx.BoxSizer()
note_sizer.Add(info_pane, 1, wx.EXPAND)

panel.SetSizer(note_sizer)
frame_sizer = wx.BoxSizer(wx.VERTICAL)
frame_sizer.Add(panel, 1, wx.EXPAND)
frame.SetSizerAndFit(frame_sizer)
frame.Show()

app.MainLoop()

rawDescription: How to size a panel to fit a grid

description: Size a panel to fit a grid


code:
import pandas as pd
s = pd.Series({'a':1, 'b':2, 'c':3})
s.values # a numpy array

rawDescription: Pythonic way to convert a dictionary to a numpy array


code:
while True:
    try:
        data = ser.readline().decode("utf-8")     # Read the data
        if data == '': continue                   # skip empty data

        print(data)                               # Display what was read
        time.sleep(1)

        if "sound" in data:
           print('Found "sound"!')

    except ser.SerialTimeoutException:
        print('Data could not be read')
        time.sleep(1)

rawDescription: Finding string Python Arduino

description: Finding string Python Arduino


code: pd.read_fwf('test.fwf', header=None, converters={0:str, 1:str})

rawDescription: Pandas how to read 0-padded number with read_fwf?


rawDescription: python regex split on repeating character

description: Python regex split on repeating character


code:
lines = data.split('\n')
a = re.search('regex', lines[3])

rawDescription: Can I search on a specific line with regex in Python?

description: Search on a specific line with regex in Python


code:
class AddressInline(admin.StackedInline):
    model = Address
    fk_name = "address"
    max_num = 1

class BillingAddressInline(admin.StackedInline):
    model = Address
    fk_name = "billing_address"
    max_num = 1

class CompanyAdmin(admin.ModelAdmin):
    # ...
    inlines = [AddressInline, BillingAddressInline]

rawDescription: How to not display foreign key as list in Django admin object page?

description: Not display foreign key as list in Django admin object page


code: _proc_status = '/proc/%d/status' % os.getpid()

rawDescription: How to get memory usage of an external program - python

description: Get memory usage of an external program - python


rawDescription: Using genfromtxt to read in data with different column lengths


code: xticks(arange(len(AlphaNum)),AlphaNum)

rawDescription: Pylab Histogram show all bins on x axis

description: Pylab Histogram show all bins on x axis


code:
import datetime
intstring = int( ('1433140740000+0200').split('+')[0])

print(
datetime.datetime.fromtimestamp(intstring/1000).strftime('%Y-%m-%d %H:%M:%S')
)

rawDescription: Python - Convert timestamp including timezone (+0200) to humanly readable


code:
import csv
employees = [
    'name1-surname1-place1',
    'name2-surname2-place2',
    'name3-surname3-place3',
    'name4-surname4-place4',
]
with open('out.csv', 'w') as out:
    writer = csv.writer(out)
    for e in employees:
        writer.writerow(e.split("-"))

rawDescription: How to write data into a CSV file using python?

description: Write data into a CSV file using python


rawDescription: Renaming columns in pandas

description: Renaming columns in pandas


rawDescription: Clear the window in tkinter

description: Clear the window in tkinter


code: Extract(7, 0, BitVecVal(0x87654, 32))

rawDescription: Z3: how to Extract() from a constant number?


code:
from django.http import HttpResponse
from django.views.generic import View
from django.shortcuts import render, render_to_response

import random
import json

def hello(request):
    rand_arr = [random.randint(0, 100) for x in range(10)]
    return HttpResponse(json.dumps(rand_arr), content_type="application/json")

rawDescription: Sending Python array to django template by AJAX


code:
COLS=0,1,5  # the columns you want. The first is numbered zero.
            # NB its a tuple: COLS=0, for one column, mandatory trailing comma

SEP = ', '  # the string you want to separate the columns in the output

INFILE='t.txt'      # file to read from
OUTFILE='out.txt'   # file to write to

f = open( INFILE, 'r')
g = open( OUTFILE, 'w')

for line in f.readlines():
   x = line.split()
   if x != []:  # ignore blank lines

       y = [ x[i] for i in COLS ]
       outline = SEP.join( '{}'.format(q) for q in y )
       g.write( outline+'\n')

rawDescription: Extracting selected columns from a datafile using python


code:
class A(object):
    foobar = 42
    def __init__(self):
        self.foo = 'baz'
        self.bar = 3
    def method(self, arg):
        return True
a = A()
a.__dict__
vars(a)

rawDescription: How list all fields of an class in Python (and no methods)?


code:
List1 = ['a', 'a', 'b', 'c', 'd', 'e']
List2 = ['a', 'b', 'c', 'd']
import collections
counter = collections.Counter(List1)
counter.subtract(List2)
list(counter.elements())

rawDescription: How do you compare 2 lists and return the difference? (difference function in python does not return what I need)

description: Compare 2 lists and return the difference? (difference function in python does not return what I need)


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

df = pd.DataFrame({
            'indx':[20141015,20141016,20141017,20141020,20141021,20141022,20141023,20141024,20141027,20141028,20141029],
            'Volume':[5540100,2044700,1818000,798900,2981500,2997900,458900,90000,562900,684300,339300]
            }).astype(float)

fig,ax = plt.subplots(1)

days = pd.to_datetime(df['indx'].astype(str), format='%Y%m%d')
volume = df['Volume']

# Plot all bars with green facecolor
bars = ax.bar(np.array(days),volume,facecolor='g')

# Loop over bars
for i, bar in enumerate(bars):
    if i == 0:
        continue

    # Find bar heights
    h = bar.get_height()
    h0 = bars[i-1].get_height()

    # Change bar color to red if height less than previous bar
    if h < h0: bar.set_facecolor('r')

fig.autofmt_xdate()

plt.show()

rawDescription: How to populate volume bar chart below line chart in green when it increases and red when it decreases from previous value

description: Populate volume bar chart below line chart in green when it increases and red when it decreases from previous value


rawDescription: Python & biology: using python to intersect datasets


code: "".join(str(int(x) + int(y))[-1] for x, y in zip(_id, uid[4:]))

rawDescription: a better version of the following code (python)

description: A better version of the following code (python)


code:
client = MongoClient(w=0)
collection = client.database.collection
w1_collection = collection.with_options(write_concern=WriteConcern(w=1))
w1_collection.update_one({'_id': 1}, {'$inc': {'x': 3}})

rawDescription: How to specify a unsafe/safe write with pymongo's collection.update_one or update_many

description: Specify a unsafe/safe write with pymongo's collection.update_one or update_many


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

def main():
    x = np.linspace(0, 10, 100)
    axes = AxesSequence()
    for i, ax in zip(range(3), axes):
        ax.plot(x, np.sin(i * x))
        ax.set_title('Line {}'.format(i))
    for i, ax in zip(range(5), axes):
        ax.imshow(np.random.random((10,10)))
        ax.set_title('Image {}'.format(i))
    axes.show()

class AxesSequence(object):
    """Creates a series of axes in a figure where only one is displayed at any
    given time. Which plot is displayed is controlled by the arrow keys."""
    def __init__(self):
        self.fig = plt.figure()
        self.axes = []
        self._i = 0 # Currently displayed axes index
        self._n = 0 # Last created axes index
        self.fig.canvas.mpl_connect('key_press_event', self.on_keypress)

    def __iter__(self):
        while True:
            yield self.new()

    def new(self):
        # The label needs to be specified so that a new axes will be created
        # instead of "add_axes" just returning the original one.
        ax = self.fig.add_axes([0.15, 0.1, 0.8, 0.8],
                               visible=False, label=self._n)
        self._n += 1
        self.axes.append(ax)
        return ax

    def on_keypress(self, event):
        if event.key == 'right':
            self.next_plot()
        elif event.key == 'left':
            self.prev_plot()
        else:
            return
        self.fig.canvas.draw()

    def next_plot(self):
        if self._i < len(self.axes):
            self.axes[self._i].set_visible(False)
            self.axes[self._i+1].set_visible(True)
            self._i += 1

    def prev_plot(self):
        if self._i > 0:
            self.axes[self._i].set_visible(False)
            self.axes[self._i-1].set_visible(True)
            self._i -= 1

    def show(self):
        self.axes[0].set_visible(True)
        plt.show()

if __name__ == '__main__':
    main()

rawDescription: matplotlib sequence of figures in the same window

description: Matplotlib sequence of figures in the same window


code:
a = 'foo'

def my_func(a = 'bar'):
    globals()['a'] = a

rawDescription: Modifying global variable with same name as local variable


rawDescription: how to add an empty list to a tuple

description: Add an empty list to a tuple


code:
from subprocess import Popen, PIPE

proc = Popen(['/var/www/scripts/resolveId.py', 'arg1', 'arg2'], stdout=PIPE, stderr=PIPE)
stdout, stderr = proc.communicate()

rawDescription: mod_python equivalent to php exec() command

description: Mod_python equivalent to php exec() command


code:
x = datetime.datetime(2015, 10, 29, 10, 40, 50, tzinfo=GMT2())
x.isoformat()

rawDescription: Python - datetime keep timezone name as of like +02:00


code: re.findall(r'^PY (\d\d\d\d)', wosrecords, flags=re.MULTILINE)

rawDescription: Using ^ to match beginning of line in Python regex


code:
from threading import Thread
...
def on_button_clicked(widget):
    Thread(target=func1).start()

rawDescription: How can i unlock Gtk button event

description: Unlock Gtk button event


code:
#! /usr/bin/env python
"""Read digits from the user in various ways..."""
from twisted.internet import reactor, defer
from starpy import fastagi, error
import logging, time

log = logging.getLogger( 'hellofastagi' )

class DialPlan( object ):
    """Stupid little application to report how many times it's been accessed"""
    def __init__( self,application, agi ):
        self.application = application
        self.agi = agi
    def start( self ):
        """Begin the dial-plan-like operations"""
        return self.agi.answer().addCallbacks( self.onAnswered, self.answerFailure )
    def answerFailure( self, reason ):
        """Deal with a failure to answer"""
        log.warn(
            """Unable to answer channel %r: %s""",
            self.agi.variables['agi_channel'], reason.getTraceback(),
        )
        self.agi.finish()
    def onAnswered( self, resultLine ):
        """We've managed to answer the channel, yay!"""
        return self.agi.wait( 2.0 ).addCallback( self.onWaited )
    def onWaited( self, result ):
        """We've finished waiting, tell the user the number"""
        return self.agi.sayNumber( self.application.count, '*' ).addErrback(
            self.onNumberFailed,
        ).addCallbacks(
            self.onFinished, self.onFinished,
        )
    def onFinished( self, resultLine ):
        """We said the number correctly, hang up on the user"""
        return self.agi.finish()
    def onNumberFailed( self, reason ):
        """We were unable to read the number to the user"""
        log.warn(
            """Unable to read number to user on channel %r: %s""",
            self.agi.variables['agi_channel'], reason.getTraceback(),
        )

    def onHangupFailure( self, reason ):
        """Failed trying to hang up"""
        log.warn(
            """Unable to hang up channel %r: %s""",
            self.agi.variables['agi_channel'], reason.getTraceback(),
        )

class CallCounterApplication(object):
    def __init__( self ):
        self.count = 0

    def __call__(self,agi):
        self.count = self.count+1
        dp = Dialplan(self,agi)
        return dp.start()

if __name__ == "__main__":
    logging.basicConfig()
    fastagi.log.setLevel( logging.DEBUG )
    f = fastagi.FastAGIFactory(CallCounterApplication())
    reactor.listenTCP(4573, f, 50, '10.0.0.167') # only binding on local interface
    reactor.run()

rawDescription: Twisted / Starpy FastAgi app only handling one call properly


code:
class MyClass(ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyClass, self).__init__(*args, **kwargs)

        chain_value = self.fields['name_of_the_field'].chain
        self.fields['name_of_the_field'].widget = CustomWidget(chain=chain_value)

rawDescription: Automatically passing extra attributes to Widget


code:
for key, value in Terrain.__dict__.items():
    if not key.startswith("__"):
        print(...)

rawDescription: Are there any other ways to iterate through the attributes of a custom class, excluding the in-built ones?


code:
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg
from matplotlib.figure import Figure
from PyQt4 import QtGui

class Graph(FigureCanvasQTAgg):
    """
    Matplot Widget
    """
    def __init__(self, figure, parent=None):
        super().__init__(figure)
        self.setParent(parent)
        self.axes = figure.add_subplot(111)
        self.axes.hold(False)
        self.axes.plot(range(10), range(10), 'b')
        self.draw()
        self.updateGeometry()

class ImageView(QtGui.QLabel):
    def __init__(self, some_image, parent=None):
        super().__init__(parent)
        self.setPixmap(QtGui.QPixmap.fromImage(QtGui.QImage(some_image)))

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    figure = Figure(figsize=(4, 2), dpi=100)
    # Uncomment one of the following to test it
    # window = Graph(figure)
    # window = ImageView('my_image.jpg')  # don't forget to give a valid image path
    try:
        window.show()
    except NameError:
        raise NameError("Don't forget to uncomment one of the window versions")
    app.exec_()

rawDescription: How to implement a Graph into a PyQT widget

description: Implement a Graph into a PyQT widget


code:
import curses
import time

stdscr = curses.initscr()

stdscr.addstr("line 1\n")
stdscr.addstr("line 2\n")
stdscr.refresh()
time.sleep(3)

stdscr.erase()
stdscr.addstr("edited line 1\n")
stdscr.addstr("edited line 2\n")
stdscr.refresh()
time.sleep(3)

curses.endwin()

rawDescription: How to edit console output

description: Edit console output


code:
import io
import csv
import argparse

def main():
    # Create the parser
    parser = argparse.ArgumentParser()
    parser.add_argument('filename', help='Name of the file you want to load')
    args = parser.parse_args()

    result = []
    with io.open(args.filename, 'r', encoding='utf-8') as f:
        reader = csv.reader(f)
        for row in reader:
            result.append([row[0], row[1]])

    for item in result:
        print('{0}, {1}'.format(*item))

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print('Something went wrong {0}'.format(e))

rawDescription: User-specified csv reading and printing in Python 3


code:
class FooPlugin(GObject.Object, Gedit.WindowActivatable):

    __gtype_name__ = 'Foo'
    ...

    def do_activate(self):
        self._add_ui()
        self.window.connect('tab-added', self.on_tab_added)
        ...
        return

    def on_tab_added(self, window, tab, data=None):
        doc = tab.get_document()
        doc.connect('saved', self.on_document_saved)
        doc.connect('loaded', self.on_document_loaded)
        return

    def on_document_loaded(self, document, data=None):
        # do something here...
        return

    def on_document_saved(self, document, data=None):
        # do something here...
        return

rawDescription: Can Gedit plugins bind to the OnSave event?


code:
def decor(func):
    def wrapper(*args, **kwargs):
            print('args - ',args)
            print('kwargs - ',kwargs)
            return func(*args, **kwargs)
    return wrapper
@decor
def a(*a, **b):
    print("In a")
    print(a)
    print(b)
a(1,2,x=10,y=20)

rawDescription: access function arguments from function decorator

description: Access function arguments from function decorator


code:
from numpy.random import rand
import matplotlib
matplotlib.use('gtkagg')
import matplotlib.pyplot as plt

# create all axes we need
ax0 = plt.subplot(211)
ax1 = ax0.twinx()
ax2 = plt.subplot(212)
ax3 = ax2.twinx()

# share the secondary axes
ax1.get_shared_y_axes().join(ax1, ax3)

ax0.plot(rand(1) * rand(10),'r')
ax1.plot(10*rand(1) * rand(10),'b')
ax2.plot(3*rand(1) * rand(10),'g')
ax3.plot(10*rand(1) * rand(10),'y')
plt.show()

rawDescription: How to share secondary y-axis between subplots in matplotlib

description: Share secondary y-axis between subplots in matplotlib


code:
plist = ('burleson both', 'the largemouth', 'the largemouth', 'a 19inch', 'his first')
plist = [(x, plist.count(x)) for x in set(plist)]
plist.sort(key=lambda x: x[1], reverse=True)

rawDescription: Using Python to count unique list elements of two strings separated by a space


code:
s = '/path/to/my/handler/?action=query&id=112&type=vca&info=ch%3D0%26type%3Devent%26ev46[sts%3Dbegin'
import urllib
urllib.unquote(s)

rawDescription: De-encode URL parameters

description: De-encode URL parameters


code:
text = 'Aardvark (n.) Definition of Aardvark'
re.split(r'\s*\([^)]*\)\s*', text)

rawDescription: How did I split a string using re module with '()' as a delimiter?


rawDescription: Scipy - optimize. Find ratio between two variables


code:
startrow, startcol = view.rowcol(r.a)
endrow, endcol = view.rowcol(r.b)

{
    'start': {'line': startrow, 'col': startcol},
    'end': {'line': endrow, 'col': endcol}
}

rawDescription: Sublime Text plugin, get line and column from selection


rawDescription: SQLAlchemy session and connection relationship


code:
C = {}
dist_km=[]
returned_values=[]

for row in product(zip(latA, longA), zip(latB, longB)):
    e=(list(chain(*row)))
    distance= distance_function(e[0],e[1],e[2],e[3])
    dist_kilo=(distance*6373)
    dist_km.append(dist_kilo)

    if dist_kilo<1.01:
        C  ={
            "clat":row[0][0],
            "clong": row[0][1],
            "tlat":row[1][0],
            "tlong": row[1][1],
            "distance_km": dist_kilo
        }
        returned_values.append(C)

rawDescription: Python: how to create dictionary from lists with only certain values using a for loop?


code:
def do_things(verbose=False):
    """Do some things.
    :param verbose: Be verbose (give additional messages).
    """
    raise NotImplementedError

rawDescription: Function and class documentation best practices for Python


code:
def donuts(count):
  if count < 10:
    numberofdonuts = count
  else:
    numberofdonuts = 'many'
  return 'Number of donuts: ' + str(numberofdonuts)

rawDescription: Why can't I get Google's Python test to work?


code: print_tables(int(user_input) if user_input.isdigit() else user_input)

rawDescription: Correct approach for calling a function regardless of parameter type


code: [list(x) for x in output.split('\n')]

rawDescription: Python Convert String to List of Lists of Strings


code:
import redis
db = redis.StrictRedis()     # This connecteds to the standard redis port on the local machine

isLocked = db.sadd("mylocks", "mykey")
if not isLocked:
   data = db.hget("mydata", "mykey")
   try:
       # do something with data
       # ...
       # Saving the data
       db.hset("mydata", "mykey", data)
   except:
       pass

   # Now to the unlocking part
   db.srem("mylocks", "mykey")

rawDescription: Python multiple workers altering the same data


code:
from argparse import Namespace

n = Namespace(foo='Foo', bar='Bar')

n
Out[3]: Namespace(bar='Bar', foo='Foo')

n.bar
Out[4]: 'Bar'

n.hey = 'Hey'

n
Out[6]: Namespace(bar='Bar', foo='Foo', hey='Hey')

rawDescription: Concise flexible struct definition

description: Concise flexible struct definition


code: x = collections.deque(5*[0], 5)

rawDescription: Python Datatype for a fixed-length FIFO

description: Python Datatype for a fixed-length FIFO


code:
with open('file1.js', 'r') as f1, open("file2.js", "w+") as f2:
    f2.write("//blobs\n" + f1.read().strip().replace("\t", "").replace("\n", ""))

rawDescription: trimming whitespace from js file not working in python

description: Trimming whitespace from js file not working in python


code: [x[0] for x in list].index('a')

rawDescription: Index of item in list when only part of the item is known


code:
path = 'D:/my path/' + str(ran) + '.wav'
wave_obj = sa.WaveObject.from_wave_file(path)

rawDescription: How get random number value and attach it to file name


code: [(k, len(v)) for k, v in G['a'].items()]

rawDescription: Python 3, NetworkX - Graph node key list is not displaying repeated edges


code: Rating.objects.extra(select={'total': "upvotes - downvotes"}).order_by('-total')

rawDescription: django order_by value not stored in database

description: Django order_by value not stored in database


rawDescription: Removing Zeroes From a List

description: Removing Zeroes From a List


code:
import os

with open(os.path.join(os.path.dirname(__file__), 'package.txt'), 'w'):
    pass

rawDescription: Python get module to save to its own folder rather than folder of the file accessing it


code:
import os
os.environ['LINES'] = "25"
os.environ['COLUMNS'] = "80"
# run pexpect stuff as before

rawDescription: How to set explicitly the terminal size when using pexpect

description: Set explicitly the terminal size when using pexpect


code:
import scipy.misc
img_rescaled = scipy.misc.imresize(img, size=[400,400], interp='bilinear')

rawDescription: how to read in png into n x n-array with predefined value of "n" in matplotlib using imread

description: Read in png into n x n-array with predefined value of "n" in matplotlib using imread


code:
import requests

def binary_search_urls(urls, lo=0, hi=None):
    if hi is None:
        hi = len(urls)
    while lo < hi:
        mid = (lo+hi)//2
        status = requests.head(urls[mid]).status_code
        if status != 302:
            lo = mid+1
        else:
            hi = mid
    return lo - 1

rawDescription: how to find the last available url which does not return 302 (Redirect) status code in a url list quickly

description: Find the last available url which does not return 302 (Redirect) status code in a url list quickly


code:
#!/usr/bin/env python3
import multiprocessing
import selectors
import os
import array
import fcntl
import termios
import subprocess
import decorator
import locale
import io
import codecs
import re
import collections

def strace(function):
    StraceReturn = collections.namedtuple("StraceReturn", ["return_data", "pid", "strace_data"])
    def strace_filter(stracefile, pid, exclude_system=False):
        system = ( "/bin"
                 , "/boot"
                 , "/dev"
                 , "/etc"
                 , "/lib"
                 , "/proc"
                 , "/root"
                 , "/run"
                 , "/sbin"
                 , "/srv"
                 , "/sys"
                 , "/tmp"
                 , "/usr"
                 , "/var"
                 )
        encoding = locale.getpreferredencoding(False)
        for line in stracefile:
            match = re.search(r'^(?:\[pid\s+(\d+)\]\s+)?open\(\"((?:\\x[0-9a-f]{2})+)\",', line, re.IGNORECASE)
            if match:
                p, f = match.groups(pid)
                f = codecs.escape_decode(f.encode("ascii"))[0].decode(encoding)
                if exclude_system and f.startswith(system):
                    continue
                yield (p, f)
    def strace_reader(conn_parent, conn_child, barrier, pid):
        conn_parent.close()
        encoding = locale.getpreferredencoding(False)
        strace_args = ["strace", "-e", "open", "-f", "-s", "512", "-xx", "-p", str(pid)]
        process_data = io.StringIO()
        process = subprocess.Popen\
            ( strace_args
            , stdout = subprocess.DEVNULL
            , stderr = subprocess.PIPE
            , universal_newlines = True
            )
        selector = selectors.DefaultSelector()
        selector.register(process.stderr, selectors.EVENT_READ)
        selector.select()
        barrier.wait()
        selector.register(conn_child, selectors.EVENT_READ)
        while len(selector.get_map()):
            events = selector.select()
            for key, mask in events:
                if key.fd == conn_child.fileno():
                    conn_child.recv()
                    selector.unregister(key.fd)
                    process.terminate()
                    try:
                        process.wait(5)
                    except TimeoutError:
                        process.kill()
                    process.wait()
                else:
                    ioctl_buffer = array.array("i", [0])
                    try:
                        fcntl.ioctl(key.fd, termios.FIONREAD, ioctl_buffer)
                    except OSError:
                        read_bytes = 1024
                    else:
                        read_bytes = max(1024, ioctl_buffer[0])
                    data = os.read(key.fd, read_bytes)
                    if data:
                        # store all data, simpler but not as memory-efficient
                        # as:
                        #   result, leftover_line = strace_filter\
                        #         ( leftover_line + data.decode(encoding)
                        #         , pid
                        #         )
                        #   process_data.append(result)
                        # with, after this loop, a final:
                        #   result = strace_filter(leftover_line + "\n", pid)
                        #   process_data.append(result)
                        process_data.write(data.decode(encoding))
                    else:
                        selector.unregister(key.fd)
        selector.close()
        process_data.seek(0, io.SEEK_SET)
        for pidfile in strace_filter(process_data, pid):
            conn_child.send(pidfile)
        conn_child.close()
    def strace_wrapper(function, *args, **kw):
        strace_data = list()
        barrier = multiprocessing.Barrier(2)
        conn_parent, conn_child = multiprocessing.Pipe(duplex = True)
        process = multiprocessing.Process\
            ( target=strace_reader
            , args=(conn_parent, conn_child, barrier, os.getpid())
            )
        process.start()
        conn_child.close()
        barrier.wait()
        function_return = function()
        conn_parent.send(None)
        while True:
            try:
                strace_data.append(conn_parent.recv())
            except EOFError:
                break
        process.join(5)
        if process.is_alive():
            process.terminate()
        process.join(5)
        if process.is_alive():
            os.kill(process.pid, signal.SIGKILL)
        process.join()
        conn_parent.close()
        return StraceReturn(function_return, os.getpid(), strace_data)
    return decorator.decorator(strace_wrapper, function)

@strace
def test():
    print("Entering test()")
    process = subprocess.Popen("cat +μυρτιὲς.txt", shell=True)
    f = open("test\"test", "r")
    f.close()
    process.wait()
    print("Exiting test()")
    return 5

print(test())

rawDescription: strace a python function

description: Strace a python function


code:
import time

import wx
from threading import Thread
from wx.lib.pubsub import Publisher

class WorkerThread(Thread):
    def __init__(self):
        Thread.__init__(self)

        #A flag that can be set
        #to tell the thread to end
        self.stop_flag = False

        #This calls the run() to start the new thread
        self.start()

    def run(self):
        """ Over-rides the super-classes run()"""
        #Put everything in here that
        #you want to run in your new thread

        #e.g...
        for x in range(20):
            if self.stop_flag:
                break
            time.sleep(1)
            #Broadcast a message to who ever's listening
            Publisher.sendMessage("your_topic_name", x)
        Publisher.sendMessage("your_topic_name", "finished")

    def stop(self):
        """
        Call this method to tell the thread to stop
        """
        self.stop_flag = True

class GUI(wx.Frame):
    def __init__(self, parent, id=-1,title=""):
        wx.Frame.__init__(self, parent, id, title, size=(140,180))
        self.SetMinSize((140,180))
        panel = wx.Panel(id=wx.ID_ANY, name=u'mainPanel', parent=self)

        #Subscribe to messages from the workerThread
        Publisher().subscribe(self.your_message_handler, "your_topic_name")

        #A button to start the workerThread
        self.startButton = wx.Button(panel, wx.ID_ANY, 'Start thread')
        self.Bind(wx.EVT_BUTTON,  self.onStart, self.startButton)

        #A button to stop the workerThread
        self.stopButton = wx.Button(panel, wx.ID_ANY, 'Stop thread')
        self.Bind(wx.EVT_BUTTON,  self.onStop, self.stopButton)

        #A text control to display messages from the worker thread
        self.threadMessage = wx.TextCtrl(panel, wx.ID_ANY, '', size=(75, 20))

        #Do the layout
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.startButton, 0, wx.ALL, 10)
        sizer.Add(self.stopButton, 0, wx.ALL, 10)
        sizer.Add(self.threadMessage, 0, wx.ALL, 10)
        panel.SetSizerAndFit(sizer)

    def onStart(self, event):
        #Start the worker thread
        self.worker = WorkerThread()

        #Disable any widgets which could affect your thread
        self.startButton.Disable()

    def onStop(self, message):
        self.worker.stop()

    def your_message_handler(self, message):
        message_data = message.data
        if message_data == 'finished':
            self.startButton.Enable()
            self.threadMessage.SetLabel(str(message_data))
        else:
            self.threadMessage.SetLabel(str(message_data))

if __name__ == "__main__":

    app = wx.PySimpleApp()
    frame = GUI(None, wx.ID_ANY, 'Threading Example')
    frame.Show()
    app.MainLoop()

rawDescription: How to control/call another python script within one python script? (Communicate between scripts)

description: Control/call another python script within one python script? (Communicate between scripts)


code:
def score(i):
    return sum([int(j) for j in str(i) if j.isdigit()])

max(x, key=score)

rawDescription: What is the pythonic way to calculate argmax?


code:
# 2.
import operator
def sorted_histogram(a_dict):
  return [
    x[1] # the value
    for x in sorted(a_dict.items(), key=operator.itemgetter(1))
    # of each dict item, sorted by value (i.e. the [1] element of each item).
  ]

# 3.
english_histogram = sorted_histogram(english_dict)
cipher_histogram = sorted_histogram(cipher_dict)

# 4.
# Make the lowercase version
mapping = dict(zip(english_histogram, cipher_histogram))
# Make the uppercase version, and merge it in at the same time.
mapping.update(dict(
  (k.upper(), v.upper()) for (k, v) in zip(english_histogram, cipher_histogram)
))

# 5.
translated = ''.join( # make this list of characters, and string them together:
  mapping.get(c, c) # the mapped result, if possible; otherwise the original
  for c in cipher
)

# 6. Do whatever you want with 'translated' - write to file, etc.

rawDescription: Cipher text Letter Freq Substitution: Comparing 2 dictionaries' dict keys by value and altering a text


code:
def add2(x, y):
    return x + y
    # equivalently: add2 = lambda x,y: x+y

def curry(func, num):
    def wrapped(*args):
        if len(args) == 0:
            return num
        elif len(args) > 1:
            raise TypeError('{} takes 1 positional argument but '
                            '{} were given'.format(
                                func.__name__, len(args)))
        arg = args[0]
        return curry(func, func(num, arg))
    return wrapped

rawDescription: Professor used "The binary version of a function". Does that even exist?


code:
#!/usr/bin/env python
import subprocess
with open("output.txt", "w+") as output:
    subprocess.call(["python", "./script.py"], stdout=output);

rawDescription: How to execute a python script and write output to txt file?

description: Execute a python script and write output to txt file


code: milliseconds = (c.days * 24 * 60 * 60 + c.seconds) * 1000 + c.microseconds / 1000.0

rawDescription: python time(milli seconds) calculation

description: Python time(milli seconds) calculation


code:
class Something(object):
    UNINITIALIZED = object()
    LAZY_ATTRS = ('x','y','z')
    def __init__(self):
        for attr in self.LAZY_ATTRS:
            setattr(self, '_'+attr, self.UNINITIALIZED)
    def _get_x(self):
        if self._x is self.UNINITIALIZED:
            self._x = self.doExpensiveInitStuff('x')
        return self._x

rawDescription: Python: Using getter or "private" attribute inside setter?


code:
dictionary = {}
with open('filename') as f:
    for line in f:
        dictionary[line[0]] = line[1]

rawDescription: Python text into dictionary

description: Python text into dictionary


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

# I don't have your data but let's assume that this function
# replicates the data distribution you want to work with.
def curve(x):
    return 2. * x + 5.

N = 100
x = np.linspace(0,1,100)
y_fit = curve(x)

# margin controls how "noisy" you want your fit to be.
margin = 0.5

noise = margin*(np.random.random(N)-0.5)
y_ran = y_fit + noise

plt.plot(x, y_fit) # Plot the fitted distribution.
plt.plot(x, y_ran, 'rx') # Plot the noisy data.

plt.show()

rawDescription: Generating smoothed randoms that follow a distribution


code:
import numpy as np
from scipy import spatial
import networkx as nx
import matplotlib.pyplot as plt
nnodes = 100
r = 0.15
positions =  np.random.rand(nnodes,2)
kdtree = spatial.KDTree(positions)
pairs = kdtree.query_pairs(r)
G = nx.Graph()
G.add_nodes_from(range(nnodes))
G.add_edges_from(list(pairs))
pos = dict(zip(range(nnodes),positions))
nx.draw(G,pos)
plt.show()

rawDescription: NetworkX Random Geometric Graph Implementation using K-D Trees


code:
a = range(15)
b = range(5)

a = set(a).difference(b)

rawDescription: remove every item of listA from listB

description: Remove every item of listA from listB


code:
km1 = soup.select('#milage .c2')
kml = kml[0].text.strip() if kml else None

rawDescription: handling .find() failures in beautiful soup 4

description: Handling .find() failures in beautiful soup 4


code:
# if you want 100 users...
for n in range(100):
    # you should consider moving these to a separate object that represents the page
    # AKA Page Object Design
    username_field = driver.find_element_by_css_selector("input.ss-med.small")
    password_field = driver.find_element_by_xpath("(//input[@value=''])[2]")
    submit_button = driver.find_element_by_css_selector("input.btn.btn-primary")

    username_field.clear()
    username_field.send_keys('tester{}'.format(n))
    password_field.clear()
    password_field.send_keys('password')
    submit_button.click()

rawDescription: Python Selenium More Efficient Way of Adding Several Users


code:
root = Tk()
info = Label(root, ...)
you = Button(root, ...)

rawDescription: How to tell a widget to stay in one GUI

description: Tell a widget to stay in one GUI


code:
class MyView(TemplateView):
    model = Mymodel
    template_name = "home.html"

    def get_context_data(self, *args, **kwargs):
        context = super(MyView, self).get_context_data(*args, **kwargs)
        context['ngapp'] = "Myapp"
        context['query_results'] = self.get_data()
        return context

    def get_data(self):
        query_results = self.model.objects.all()
        return query_results

rawDescription: How to get all the data from the database and display in a table

description: Get all the data from the database and display in a table


code:
from rpy2.robjects.packages import importr
my_lib = importr("MyLib")

rtn_val = my_lib.fn(param1 = "str_param1",
                    a_b_param2 = None,
                    param3 = 7,
                    param4 = False)

rawDescription: passing function parameters in rpy2

description: Passing function parameters in rpy2


code:
def generate_expense_type(rec):
    def _tx():
      expense_type = type.get(name)
      if not expense_type:
        expense_type = type(key_name=name)
      expense_type.total += rec.amount
      expense_type.put()
    db.run_in_transaction(expense_type)

rawDescription: How to summarise data in Google AppEngine

description: Summarise data in Google AppEngine


code:
from appscript import *

folder = '/path/to/folder'

ps = app('Adobe Photoshop CS4')

for f in app('Finder').items[mactypes.Alias(folder)].files.get(resulttype=k.alias):
    ps.open(f)
    # do stuff here...

rawDescription: How does one feed a list of files into an app with appscript and Python?

description: Feed a list of files into an app with appscript and Python


code:
cache = {}
def lcs(s1, s2):
  global cache
  if len(s1) == 0 or len(s2) == 0:
      return 0
  if (s1, s2) in cache:
      return cache[(s1, s2)]
  else:
      if s1[-1] == s2[-1]:
          cache[(s1, s2)] = 1 + lcs(s1[:-1], s2[:-1])
      else:
          cache[(s1, s2)] = max(lcs(s1[:-1], s2), lcs(s1, s2[:-1]))
  return cache[(s1, s2)]

rawDescription: Memoization using dictionary in Python

description: Memoization using dictionary in Python


rawDescription: How to compare corresponding positions in a list?

description: Compare corresponding positions in a list


rawDescription: Include list in Python request data

description: Include list in Python request data


code:
#!/usr/bin/env
# Removes the shadow from MacOS-Generated screen shots.

import Image,os

if __name__=="__main__":
    image = Image.open(os.sys.argv[1])
    image = image.convert('RGBA')

    (width,height) = image.size
    def find_first_non_alpha_x():
        for i in range(width):
            if image.getpixel((i,height/2))[3]==255:
                return i
        raise RuntimeError("No non-alpha pixels on midline")

    def find_last_non_alpha_x():
        for i in range(width-1,0,-1):
            if image.getpixel((i,height/2))[3]==255:
                return i
        raise RuntimeError("No non-alpha pixels on midline")

    def find_first_non_alpha_y():
        for i in range(height):
            if image.getpixel((width/2,i))[3]==255:
                return i
        raise RuntimeError("No non-alpha pixels on midline")

    def find_last_non_alpha_y():
        for i in range(height-1,0,-1):
            if image.getpixel((width/2,i))[3]==255:
                return i
        raise RuntimeError("No non-alpha pixels on midline")

    x1 = find_first_non_alpha_x()
    y1 = find_first_non_alpha_y()
    x2  = find_last_non_alpha_x()
    y2  = find_last_non_alpha_y()

    y = image.crop((x1-1,y1-1,x2+1,y2+1))
    y.save(os.sys.argv[1]+"-cropped.png")

rawDescription: Programmatically remove Apple Screen Capture Shadow borders


code:
import datetime as dt

now = dt.datetime.now()
then = dt.datetime.combine(now, dt.datetime.strptime("6:02PM", "%I:%M%p").time())
print(then)
# 2012-08-26 18:02:00

tdelta = now - then
print(tdelta)
# -1 day, 20:53:25.190721

rawDescription: Convert a time-only string such as "6:02PM" to a datetime object?


code: graph[v1][v2] = weight

rawDescription: Python dict() and the variable as an argument


code:
for i in range(1,len(DF)):
    DF.iloc[i]['b'] = DF.iloc[i-1]['b']+DF.iloc['i']['c']

rawDescription: python for loop with updated values

description: Python for loop with updated values


code:
diff = repo.git.diff('HEAD~1..HEAD', name_only=True)
print(diff)

rawDescription: gitpython list changed files since last commit

description: Gitpython list changed files since last commit


code:
def print_menu():
    print('1. Print Phone Numbers')
    print('2. Add a Phone Number')
    print('3. Remove a Phone Number')
    print('4. Lookup a Phone Number')
    print('5. Quit')
    print()

numbers = {}
menu_choice = 0
print_menu()
while menu_choice != 5:
    menu_choice = int(input("Type in a number (1-5): "))
    if menu_choice == 1:
        print("Telephone Numbers:")
        for x in numbers.keys():
            print("Name: ", x, "\tNumber:", numbers[x])
        print()
    elif menu_choice == 2:
        print("Add Name and Number")
        name = input("Name: ")
        phone = input("Number: ")
        numbers[name] = phone
    elif menu_choice == 3:
        print("Remove Name and Number")
        name = input("Name: ")
        if name in numbers:
            del numbers[name]
        else:
            print(name, "was not found")
    elif menu_choice == 4:
        print("Lookup Number")
        name = input("Name: ")
        if name in numbers:
            print("The number is", numbers[name])
        else:
            print(name, "was not found")
    elif menu_choice != 5:
        print_menu()

rawDescription: Python assignment for a phonebook

description: Python assignment for a phonebook


code:
followed_ids = db.session.query(Follow.followed_id).filter(Follow.follower_id == current_user.id).subquery()
followed_posts = Post.query.filter(Post.author.in_(followed_ids)).order_by(Post.timestamp.desc()).all()

rawDescription: Get all posts by a group of users ordered by timestamp


code:
lines = [next(fo) for fo in fileobjs]
process(lines)

rawDescription: Reading 1 line at a time from multiple files


code:
a = """=====\nhello\n=====\n\n - one\n - two\n"""
import docutils
docutils.core.publish_parts(a, writer_name='html')['html_body']

rawDescription: parsing rST to HTML on the fly using Docutils

description: Parsing rST to HTML on the fly using Docutils


code:
import csv

with open('yourfile.csv') as f:
    reader = csv.reader(f, delimiter=';')
    for row in reader:
        print(";".join([row[1], row[5], row[2], row[3]]))

rawDescription: How to reorder the columns of a CSV?

description: Reorder the columns of a CSV


code:
def are_equal(string1, string2):
    return all(x == y or '*' in x + y for x, y in zip(string1, string2))

rawDescription: python string compare - any char inside string

description: Python string compare - any char inside string


code:
graph = facebook.GraphAPI(oauth_access_token)
groups = graph.get_object("me/groups")
group_id = groups['data'][0]['id'] # we take the ID of the first group
graph.put_object(group_id, "feed", message="from terminal")

rawDescription: Posting to Facebook Group using the Graph API and Python


code:
dictdict = { 'key1': {'subkey1': 4, 'subkey2': 7}, 'key2': {'subkey1': 6, 'subkey2': 8} }
dictdict["key1"]["subkey1"]
for v1 in dictdict.values():
    v1.update((k,[v]) for k,v in v1.iteritems())

dictdict["key1"]["subkey1"] += ['a1', 'a2']
dictdict["key1"]["subkey1"]

rawDescription: Python convert dictionary values to list and append items


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

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
fig = plt.figure(figsize=(8, 6))
gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1])
ax0 = plt.subplot(gs[0])
ax0.plot(x, y)
ax1 = plt.subplot(gs[1])
ax1.plot(y, x)

plt.tight_layout()
plt.savefig('grid_figure.pdf')

rawDescription: Matplotlib different size subplots

description: Matplotlib different size subplots


code:
class MomentResource(BaseResource):
    """
    Moment resource
    """
    sender = fields.ForeignKey(StudentResource, 'sender', full=True, readonly=True)
    comments = fields.ToManyField('myapp.api.CommentResource', 'comments', null=True, full=True)

    class Meta:
        """
        Metadata for class
        """
        queryset = Moment.objects.all()
        resource_name = 'moment'
        always_return_data = True
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()
        filtering = {
            'zone': ALL,
        }

class CommentResource(BaseResource):
    """
    Comment resource
    """
    moment = fields.ToOneField(MomentResource, 'content_object')

    class Meta:
        queryset = Comment.objects.all()
        resource_name = 'comments'

rawDescription: Accessing comments on an object via reverse relationship with Tastypie


code:
import config_parser_details as p
import sys
import warnings
import os
import argparse

commandLineArgumentParser = argparse.ArgumentParser()
commandLineArgumentParser.add_argument("-c", "--compname", help="Company name", default=p.company)
commandLineArguments = commandLineArgumentParser.parse_args()

company = commandLineArguments.compname

name = p.name
date = p.joindate

print("%s\n" %company)
print("%s\n" %name)

rawDescription: how to create dynamic configuration file using python

description: Create dynamic configuration file using python


code:
n = 5
groups = [files_arguments[i:i + n] for i in range(0, len(files_arguments), n)]

rawDescription: How to make groups of five elements from the list?

description: Make groups of five elements from the list


code: list(ordered((g(x),f(x))))

rawDescription: How to canonicalize list of expressions in SymPy?

description: Canonicalize list of expressions in SymPy


code:
import zipfile, lxml.etree

# open zipfile
zf = zipfile.ZipFile('my_doc.docx')
# use lxml to parse the xml file we are interested in
doc = lxml.etree.fromstring(zf.read('docProps/core.xml'))
# retrieve creator
ns={'dc': 'http://purl.org/dc/elements/1.1/'}
creator = doc.xpath('//dc:creator', namespaces=ns)[0].text

rawDescription: How to retrieve author of a office file in python?

description: Retrieve author of a office file in python


code:
def genInt():
    i = 0
    while True:
        i+=1
        yield i
        yield -i

gennr = genInt()

rawDescription: How to generate ints with varying signs?

description: Generate ints with varying signs


code:
s
df.lookup(s.values, s.keys())
pd.DataFrame(dict(zip(s.keys(), df.lookup(s.values, s.keys()))), index=[0])

rawDescription: parallel indexing in pandas dataframe using a pandas series?

description: Parallel indexing in pandas dataframe using a pandas series


code:
from re import findall
findall(r"[^\s?!,;]+", "Holy moly, feferoni!")

rawDescription: Python - regex, blank element at the end of the list?


code:
def remove_last(x):
    return x[...,:-1]

rawDescription: Remove last column of 2D matrix, or last element of 1D vector


code:
#!/usr/bin/env python
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

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

im = plt.imshow(Z, interpolation='bilinear', cmap=cm.gray,
                origin='lower', extent=[-3,3,-3,3])

plt.show()

rawDescription: Overlaying a scatter plot on background image and changing axes ranges


rawDescription: Python mechanize to fill form with variables or extracted text


code:
from PIL import Image

iname = 'test.bmp'
oname = 'test.pdf'

img = Image.open(iname)
newimg = img.convert(mode='P', colors=16)
newimg.save(oname)

rawDescription: How to convert a 24 color bmp image to 16 color bmp in python

description: Convert a 24 color bmp image to 16 color bmp in python


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

class Ladder(pygame.sprite.Sprite):
    image = pygame.Surface((60, 300))
    image.fill(pygame.Color('blue'))

    def __init__(self, location):
        pygame.sprite.Sprite.__init__(self)
        self.rect = self.image.get_rect(bottomleft=location)

class Mario(pygame.sprite.Sprite):
    image = pygame.Surface((30, 50))
    image.fill(pygame.Color('red'))

    def __init__(self, location):
        pygame.sprite.Sprite.__init__(self)
        self.rect = self.image.get_rect(bottomleft=location)

class Game:

    def __init__(self):
        self.fps = 30
        self.dispwidth = 600
        self.dispheight = 800
        self.screen = pygame.display.set_mode((self.dispwidth, self.dispheight))
        pygame.display.set_caption('Donkey Kong')
        self.fpstime = pygame.time.Clock()
        self.white = (255, 255, 255)
        self.black = (0, 0, 0)
        self.mario = Mario([0, 600])
        self.ladder = Ladder([400, 600])
        self.all_sprites = pygame.sprite.OrderedUpdates(self.ladder, self.mario)
        self.game_over = False

    def run(self):
        while not self.game_over:
            self.handle_events()
            self.run_logic()
            self.draw()
            self.fpstime.tick(self.fps)

    def run_logic(self):
        self.all_sprites.update()

    def handle_events(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                self.game_over = True
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[K_LEFT]:
            self.mario.rect.x -= 6
        if keys_pressed[K_RIGHT]:
            self.mario.rect.x += 6
        if keys_pressed[K_UP]:
            if pygame.sprite.collide_rect(self.mario, self.ladder):
                self.mario.rect.y -= 6
        if keys_pressed[K_DOWN]:
            if pygame.sprite.collide_rect(self.mario, self.ladder):
                self.mario.rect.y += 6

    def draw(self):
        self.screen.fill(self.white)
        self.all_sprites.draw(self.screen)
        pygame.display.update()

if __name__ == '__main__':
    pygame.init()
    Game().run()
    pygame.quit()
    sys.exit()

rawDescription: climb ladder in pygame

description: Climb ladder in pygame


code:
import pycurl

fields = [('field1', 'this is a test using httppost & stuff'),
    ('field2', (pycurl.FORM_FILE, 'file1.txt', pycurl.FORM_FILE, 'file2.txt')),
    ('field3', (pycurl.FORM_CONTENTS, 'this is wei\000rd, but null-bytes are okay'))
]

c = pycurl.Curl()
c.setopt(c.URL, 'http://www.example.com')
c.setopt(c.HTTPPOST, fields)
c.perform()
c.close()

rawDescription: with curl, how do I post a form with a file and stream that file?

description: With curl, how do I post a form with a file and stream that file


code: matrix = np.insert(matrix,0,flist,0)

rawDescription: Python - How to add column headers from the generated List


code:
class C(object):

    def __init__(self, Type='generic', X=None, Y=None):
        X = X or 5
        Y = Y or 500
        self.X, self.Y = {
            "generic": (X, Y),
            "short": (1, Y),
            "long": (10, Y),
            "large": (X, 2000),
            "small": (X, 100),
        }[Type]

    def __str__(self):
        return "X={0} Y={1}".format(self.X, self.Y)

print(C())
print(C('short'))
print(C('long'))
print(C('large'))
print(C('small'))
print(C('small', 10))
print(C('small', 20, 20))

rawDescription: defaults of method python

description: Defaults of method python


rawDescription: How to remove a part of a url in python?

description: Remove a part of a url in python


code:
class Bar:
    ...

class BarAction(argparse.Action):
    def __call__(self,parser,namespace,values,option_string=None):
        try:  #Catch the runtime error if it occures.
           l=[Bar(v) for v in values] #Create Bars, raise RuntimeError if bad arg passed.
        except RuntimeError as E:
           #Optional:  Print some other error here.  for example: `print E; exit(1)`
           parser.error()

        setattr(namespace,self.dest,l) #add the list to the namespace

...
parser.add_argument('-b', '--bar', nargs='*',
                    choices=VALID_BAR_NAMES,
                    action=BarAction,  # SELECTED TYPE -- The action does all the type conversion instead of the type keyword.
                    help=('Specify one or many valid bar(s)'))

...

rawDescription: Normal argument error when using a custom type with argparse


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

fig, ax = plt.subplots()

# the x coords of this transformation are data, and the
# y coord are axes
trans = transforms.blended_transform_factory( ax.transData, ax.transAxes)

# data points on the axes
x = np.random.rand(5)*100. + 200.
y = [0]*5
ax.plot(x, y, 'kx', transform=trans, markersize=10, markeredgewidth=2,
        clip_on=False)

# regular data
x = np.random.rand(5)*100. + 200.
y = np.random.rand(5)*100. + 200.
ax.plot(x, y, 'ro')

plt.show()

rawDescription: how can I plot on the axes

description: Plot on the axes


code:
class Foo:
    def __init__(self, a):
        self.a = a

    def sayHello(self):
        print("Hello!")

class Bar(Foo):
    def __init__(self, a, b):
        super().__init__(self, a)  # calls overridden __init__ method from Foo
        self.b = b

    def doSomething(self):
        self.sayHello()            # calls a method defined in Foo
        return self.a + self.b     # accesses variable "a" that was set in Foo

rawDescription: How to get the name of the instance of the parent class from the derived class in Python?

description: Get the name of the instance of the parent class from the derived class in Python


code:
def calc_pump_height(self):
    for subkind_indices in self.get_1_4_subkinds():
        self.calc_pump_spec_height(subkind_indices)

rawDescription: Python Style: nested vs extra function

description: Python Style: nested vs extra function


code:
delta_t = t1 - t0
a_t = (t1 - t) / delta_t * a_0 + (t - t0) / delta_t * a_1

rawDescription: Temporal interpolation in NumPy/matplotlib


code:
import sys

while True:
    line = sys.stdin.readline()
    if not line:
        break
    sys.stdout.write(line)
    sys.stdout.flush()

rawDescription: Filtering output of tail in with Python

description: Filtering output of tail in with Python


rawDescription: Find the second closest index to value

description: Find the second closest index to value


code:
import cv2
import numpy as np

img = cv2.imread('zen.jpg')
rows, cols, ch = img.shape
pts1 = np.float32(
    [[cols*.25, rows*.95],
     [cols*.90, rows*.95],
     [cols*.10, 0],
     [cols,     0]]
)
pts2 = np.float32(
    [[cols*0.1, rows],
     [cols,     rows],
     [0,        0],
     [cols,     0]]
)
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img, M, (cols, rows))
cv2.imshow('My Zen Garden', dst)
cv2.imwrite('zen.jpg', dst)
cv2.waitKey()

rawDescription: how to adjust photo with skew angle?

description: Adjust photo with skew angle


code:
from my_package import create_app

app = create_app(my_environment)
ctx = app.app_context()
ctx.push()

# your code here

ctx.pop()

rawDescription: creating a database outside the application context

description: Creating a database outside the application context


code:
from Foundation import *
s = NSAppleScript.alloc().initWithSource_("tell app \"Finder\" to activate")
s.executeAndReturnError_(None)

rawDescription: Calling AppleScript from Python without using osascript or appscript?


code:
content = hxs.select("//div[@id='content']").extract()[0]
infobox = hxs.select("//div[@id='content']//div[@class='infobox']").extract()[0]

item['article_html'] = content.replace(infobox, "")

rawDescription: Exclude div from Scrapy

description: Exclude div from Scrapy


code:
import re

s = "track._Event('product', 'test');Product.lisen(1234, 21, 4343); return false;"

pattern = re.compile(r'.*lisen\((?P<pid>\d+),\s*(?P<p1>\d+),\s*(?P<p2>\d+)\).*')

pid, p1, p2 =  map(int, pattern.match(s).groups())

rawDescription: Regex find numbers in specific position

description: Regex find numbers in specific position


code:
serial_f = serial.Serial(port=dev, baudrate=BAUDRATE, timeout=2)

def write_serial():
    status = serial_f.read(1)
    serial_f.write(buffer)

loop = asyncio.get_event_loop()
loop.add_reader(serial_f.fileno(), write_serial)

rawDescription: Using asyncio to read the output of a serial port


code:
def cod(n):
    if n == "":
        return ""
    else:
        a = str(ord(n[0])) + str(cod(n[1:]))
        return int(a)

rawDescription: Python: convert str to int inside a recursive function


code:
import numpy as np
from numpy.lib.format import open_memmap
import pandas as pd

# make some test data
data = np.random.randn(100000, 2)
np.savetxt('/tmp/data.csv', data, delimiter=',', header='foo,bar')

# we need to specify the shape and dtype in advance, but it would be cheap to
# allocate an array with more rows than required since memmap files are sparse.
mmap = open_memmap('/tmp/arr.npy', mode='w+', dtype=np.double, shape=(100000, 2))

# parse at most 10000 rows at a time, write them to the memmaped array
n = 0
for chunk in pd.read_csv('/tmp/data.csv', chunksize=10000):
    mmap[n:n+chunk.shape[0]] = chunk.values
    n += chunk.shape[0]

print(np.allclose(data, mmap))
# True

rawDescription: loading csv column into numpy memmap (fast)

description: Loading csv column into numpy memmap (fast)


code:
env.Command ('document.tex', '', 'python table_generator.py')
env.PDF ('document.pdf', 'document.tex')

rawDescription: How to I get scons to invoke an external script?


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

image = data.chelsea()

shift_y, shift_x = np.array(image.shape[:2]) / 2.
tf_rotate = transform.SimilarityTransform(rotation=np.deg2rad(30))
tf_shift = transform.SimilarityTransform(translation=[-shift_x, -shift_y])
tf_shift_inv = transform.SimilarityTransform(translation=[shift_x, shift_y])

image_rotated = transform.warp(image, (tf_shift + (tf_rotate + tf_shift_inv)).inverse)

plt.imshow(image_rotated)
plt.show()

rawDescription: python: skimage.transform.AffineTransform rotation center

description: Python: skimage.transform.AffineTransform rotation center


code:
from idlelib.PyShell import main
if __name__ == '__main__':
  main()

rawDescription: How to launch python Idle from a virtual environment (virtualenv)

description: Launch python Idle from a virtual environment (virtualenv)


code:
a_found = b_found = c_found = False

while not (a_found and b_found and c_found):
    return_value = myfunction(type)
    if A in return_value[3] and not a_found:
        a_found = True
        print("found A")

    [...]

print("Done")

rawDescription: Cycle through a resource until all the parameters are satisfied


code:
import pandas as pd
df = pd.DataFrame({"A":["foo", "foo", "foo", "bar"], "B":[0,1,1,1], "C":["A","A","B","A"]})
df.groupby(["A", "C"]).filter(lambda df:df.shape[0] == 1)

rawDescription: Drop all duplicate rows in Python Pandas


code: exec(some_code, globals())

rawDescription: Python 3.2.1: exec('x = y()') sets a value in a toy example, but not in the full code


code:
import turtle

turtle.forward(100)
turtle.left(90)
turtle.forward(100)
# etc.

turtle.getscreen()._root.mainloop()  # <-- run the Tkinter main loop

rawDescription: Python Turtle graphics - how do I control when the window closes?


rawDescription: Regular expression content generator

description: Regular expression content generator


code:
a = ['house', 'bikeCT', 'car', 'bike', 'houseCT']
b = [x for x in a if 'CT' not in x]

rawDescription: Python: How to create a new list based on existing list without certain objects


code:
def redraw(self, *args):
    '''redraw line numbers'''
    self.delete("all")

    # Build dict to convert line index to line number
    linenums = {}
    num = 1
    contents = self.textwidget.get("1.0", tk.END)
    for i, line in enumerate(contents.splitlines(), 1):
        i = str(i) + '.0'
        # Only increment line number if the line's not blank
        linetext = self.textwidget.get(i, "%s+1line" % i)
        if linetext.strip():
            linenums[i] = str(num)
            #print num, linetext,
            num += 1

    i = self.textwidget.index("@0,0")
    while True :
        dline = self.textwidget.dlineinfo(i)
        if dline is None:
            break

        linenum = linenums.get(i)
        if linenum is not None:
            y = dline[1]
            self.create_text(2,y,anchor="nw", text=linenum)

        i = self.textwidget.index("%s+1line" % i)

rawDescription: line number spacing in text widget Tkinter

description: Line number spacing in text widget Tkinter


code:
class AdminUserView(AdminView):

    column_list = ['first_name', 'last_name', 'email', 'roles', 'active']

    form_columns = ['first_name', 'last_name', 'email', 'active', 'roles']

    # Other common functionality here

class UserView(AdminUserView):

    # Just redefine the columns that can be seen/edited

    column_list = ['first_name', 'last_name', 'email', 'roles']

    form_columns = ['first_name', 'last_name', 'email', 'roles']

# register your views and remember to set a unique endpoint as we are using the same model in multiple views

admin.add_view(AdminUserView(model=User, session=db.session, category="Accounts", name="Users", endpoint="users_admin", roles_accepted=["admin"]))
admin.add_view(UserView(model=User, session=db.session, category="Accounts", name="Users", endpoint="users_user", roles_accepted=["user"]))

rawDescription: Hiding fields in Flask-Admin depending on logged in user?


code:
from Tkinter import *
root = Tk()
def f1():
    print('f1')
def f2():
    print('f2')
def f3():
    print('f3')

MODES = [("Option1", f1, '1'), ("Option2", f2, '2'), ("Option3", f3, '3')]

v = StringVar()
v.set("L") # initialize

for text, function, mode in MODES:
    b = Radiobutton(root, text=text, indicatoron=0, variable=v, command=function, value=mode)
    b.pack(anchor=W)
root.mainloop()

rawDescription: How do I make a button console using Tkinter?

description: Make a button console using Tkinter


code:
with open('/tmp/bigfile.new', 'w') as output:
    with open('/tmp/bigfile', 'r') as input:
        while True:
            line = input.readline().strip()
            if not line:
                break
            line += ' Look ma, no hands!'
            print(line, file=output)

rawDescription: Add text to end of line without loading file


code:
x = np.array([1,2,3,4])
AA = scipy.sparse.csr_matrix(x, (1,4))

rawDescription: In Python, how to assign the values of a sparse matrix from the values of another matrix without looping?


rawDescription: Permanently define environment variable (for Python gdal undefined symbol)


code:
grid_sizer_1 = wx.GridSizer(3, 3, 0, 0)
grid_sizer_1.AddMany( [
  (self.button_last_page, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL),
  (self.button_up, 0, wx.ALIGN_BOTTOM|wx.ALIGN_CENTER_HORIZONTAL),
  (self.button_next_page, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL),
  (self.button_left, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL),
  (self.button_select, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL),
  (self.button_right, 0, wx.ALIGN_CENTER_VERTICAL),
  (wx.StaticText(self, -1, ''), 0, wx.EXPAND),
  (self.button_down, 0, wx.ALIGN_CENTER_HORIZONTAL) ] )

rawDescription: wxPython GridSizer - dealing with empty cells

description: WxPython GridSizer - dealing with empty cells


code:
def rec(lista, goal):
    if not lista:
        return False
    return (goal==lista.pop() or rec(lista, goal))

rawDescription: Recursively finding if an element belongs to a list


code:
def user_create(request):
    if request.method == 'POST':
        list_form = forms.ListForm(request.POST)
        if list_form.is_valid():
            list_create = list_form.save()
            messages.success(request, 'List {0} created'.format(list_create.list_id))
            up, _ = UserProfile.objects.get_or_create(user=request.user, list_id=list_create)
            return redirect(reverse('user_dashboard', args=(2,))) # 2 is just an example

    #rest of the code

rawDescription: Django -- Only Displaying Objects A User Created


code:
from django.conf import settings

class CheckStatus(object):

    def process_request(self, request):
        if request.user.is_authenticated():
           if not request.path.startswith(settings.MEDIA_URL):
                s = request.session.get('visible')
                if str(s) is not 'yes':
                    return HttpResponseRedirect(reverse("myapp.myview.views.test"))

rawDescription: django middleware redirect infinite loop

description: Django middleware redirect infinite loop


code:
import random

f1_dict = {}
f2_dict = {}
match_dict = {}
match_threshold = .05
matches_to_return = 2
skip_unmatched = True

isfirstline = True
for line in open("file1"):
    if isfirstline:
            isfirstline = False
            continue
    f1_dict[line.split()[0]] = line.split()[1]

isfirstline = True
for line in open("file2"):
    if isfirstline:
            isfirstline = False
            continue
    f2_dict[line.split()[0]] = line.split()[3]

for i in f1_dict:
    compare_rsID = i
    compare_val = f1_dict[i]
    temp_list = []
    for j in f2_dict:
        if abs(float(f2_dict[j]) - float(compare_val)) <= match_threshold:
            temp_list.append(j)
    match_dict[i] = temp_list

fo = open("output.txt", "wb")
for k in match_dict:
    if skip_unmatched and len(match_dict[k]) == 0:
        continue
    else:
        random.shuffle(match_dict[k])
        fo.write(k),
        for l in match_dict[k][:matches_to_return]:
            fo.write(" ")
            fo.write(l),
        fo.write("\n")

rawDescription: Matching files based on one column

description: Matching files based on one column


code:
mymodule = __import__('mymodule')
reload(mymodule)

rawDescription: is there an equivalent __reload__ function as to __import__?

description: Is there an equivalent __reload__ function as to __import__


code:
result = serve_fileobj(RETURN_FILE,disposition='attachment',
                         content_type='.txt',name=filename)
os.unlink(filename)
return result

rawDescription: How to serve file with cherrypy and delete the file from server?

description: Serve file with cherrypy and delete the file from server


code:
import os
import zipfile

path = raw_input('Enter the directory: ')
path = os.path.abspath(os.path.normpath(os.path.expanduser(path)))
for folder in os.listdir(path):
    zipf = zipfile.ZipFile('{0}.zip'.format(os.path.join(path, folder)), 'w', zipfile.ZIP_DEFLATED)
    for root, dirs, files in os.walk(os.path.join(path, folder)):
        for filename in files:
            zipf.write(os.path.abspath(os.path.join(root, filename)), arcname=filename)
    zipf.close()

rawDescription: Python: zip all folders in directory

description: Python: zip all folders in directory


code:
if person.id in downline_cache:
      team.append(downline_cache[person.id])
else:
      downline_cache[person.id] = results
      team.append(results)

rawDescription: Can this recursion be written more efficiently?


code:
# in student.py
class Student:
    Id=""

    def __init__(self, Id):
        self.Id = Id

# in main.py, assume main.py and student.py are in the same folder.
def main():
    from student import Student
    print("is workign")
    temp =  Student("50")  ## I want to create the object of class Student and send an attribute

if __name__ == '__main__':
    main()

rawDescription: Create an object of another class python


code:
results = []
for language in categories.language.all():
    results.append(Movie.objects.filter(title__istartswith=q, language=language)[:10])

rawDescription: Combine query result

description: Combine query result


code:
def sleep_in(weekday, vacation):
    return (not weekday or vacation)

rawDescription: Python function prints None

description: Python function prints None


code:
import datetime
import croniter
import crontab
import time

c = croniter.croniter("0 9,10,11 * * TUE")
next_due_date = c.get_next(datetime.datetime)

while True:
    now = datetime.datetime.now()
    if now > next_due_date:
        do_something(line.py) # Edit: fixed tabbing; just in case it wasn't tabbed in
                              #       your script
        # Use os.system to run the exe
        os.system("myexecutable.exe")
        time.sleep(60 * 60 * 36)
    else:
        time.sleep(60) # Edit: I always find that it's better to have a smaller
                       #       sleep time

rawDescription: Launching a .exe Upon a Timer's Due_Date