code: node = api.item_lookup('B001OXUIIG', ResponseGroup='Medium')

rawDescription: Using Amazon's API to find a product's UPC (Python)


code:
string = 'domain.com'
answer = ''
for x in string.split('.'):
    answer += '(' + str(len(x)) + ')' + x
print(answer)

rawDescription: Python: count word lenth in site name

description: Python: count word lenth in site name


code: re.sub(' \$?::(?=.*\])', ' ', '\n#{ [matchclass [HTTP::uri] starts_with $::XYZ] or [matchclass [HTTP::host] equals $::ABC]}\n#{[class match $HOST starts_with ::qaz]\n')

rawDescription: Python RegEx Sub, Greedy Issue?

description: Python RegEx Sub, Greedy Issue


code:
#!/usr/bin/env python
from __future__ import print_function
import os
import subprocess
import tempfile

with tempfile.NamedTemporaryFile('w', suffix='.bat', delete=False) as bat_file:
    print(precommand, file=bat_file)
    print(command, file=bat_file)
rc = subprocess.call(bat_file.name)
os.remove(bat_file.name)
if rc != 0:
    raise subprocess.CalledProcessError(rc, bat_file.name)

rawDescription: Python create shell for several processes


code:
import inspect, sys

class WrapStdout(object):
    _stdout = sys.stdout
    def write(self, buf):
        frame = sys._getframe(1)
        try:
            f = inspect.getsourcefile(frame)
        except TypeError:
            f = 'unknown'
        l = frame.f_lineno
        self._stdout.write('{}:{}:{}'.format(f, l, buf))
    def flush(self):
        self._stdout.flush()

sys.stdout = WrapStdout()

rawDescription: Deciphering large program flow in Python


code:
class X(object):
    def __init__(self, val):
        self.val = val

    def __add__(self, other):
        if isinstance(other, X):
            return X(self.val + other.val)
        else:
            return X(self.val + other)

    def __radd__(self, other):
        return self.__add__(other)

X(3) + 4 # calls `__add__`
4 + X(3) # calls `__radd__`

rawDescription: TypeError: unsupported operand type(s) for +: 'int' and 'IntervalMap'


rawDescription: Python / Pandas - Turning a list with inner dictionaries into a DataFrame


code:
import _socket
from _socket import *

rawDescription: What are the '_modname' built-in modules in Python? What are they used for?


code:
def is_env_shell_func(name):
    return os.environ[name].startswith('() {')

rawDescription: Is there a way in Python to check whether an entry to os.environ is a variable or a shell function?


code:
coins = 0

def f():
    global coins  # <--
    coins += 100  # notice also that we're not returning anything

f()

coins

rawDescription: Python: Changing a pre-defined variable inside if a function


code:
ax = df.plot()

years = [2005, 2007, 2008, 2009, 2011, 2012]
# you can get years from you dataframe (but without seeing the dataframe I can't say exactly how)
# legend also accepts a Series or numpy array
ax.legend(years, loc='best')
plt.show()

rawDescription: reconstruction figure legend in pandas

description: Reconstruction figure legend in pandas


rawDescription: Regressive python counter

description: Regressive python counter


code:
from pyspark.sql import SQLContext
from pyspark import SparkContext

sqlContext = SQLContext.getOrCreate(SparkContext.getOrCreate())

sqlContext.clearCache()

rawDescription: Un-persisting all dataframes in (py)spark


code:
s = "Je vais bien, merci!"
"".join(c for c in s if c.isalpha() or c in " '")

rawDescription: Removing all non-alphabet characters from a list


code:
from geopy import Point
from geopy.distance import distance, VincentyDistance

# given: lat1, lon1, bearing, distMiles
lat2, lon2 = VincentyDistance(miles=distMiles).destination(Point(lat1, lon1), bearing)

rawDescription: calculating a gps coordinate given a point, bearing and distance

description: Calculating a gps coordinate given a point, bearing and distance


rawDescription: Is it possible to write a script which will make Windows 7 open a non-xls file with Excel?


code:
class Y(X):
    def __init__(self, stuff):
        new_stuff = self.call_another_method(stuff)
        # super(Y, self) is implicit here:
        super().__init__(new_stuff)

rawDescription: When to call Python's super().__init__()?


code:
from collections import defaultdict

class_col = 3
data_col = 11

# Read in the data
with open('path/to/your/file.csv', 'r') as f:
    # if you have a header on the file
    # header = f.readline().strip().split(',')
    data = [line.strip().split(',') for line in f]

# Sum the data for each unique class.
# assuming integers, replace int with float if needed
count = defaultdict(int)
for row in data:
    count[row[class_col]] += int(row[data_col])

# Append the relevant sum to the end of each row
for row in xrange(len(data)):
    data[row].append(str(count[data[row][class_col]]))

# Write the results to a new csv file
with open('path/to/your/new_file.csv', 'w') as nf:
    nf.write('\n'.join(','.join(row) for row in data))

rawDescription: calculation then and insert results into a csv in python

description: Calculation then and insert results into a csv in python


rawDescription: Python unserialize PHP session

description: Python unserialize PHP session


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

x = np.linspace(0, 1, num=11)
y = np.linspace(1, .42, num=11)

fig, (ax1, ax2) = plt.subplots(1,2, figsize=(8,3), gridspec_kw={'wspace':.2})
ax1.plot(x,y)
ax2.plot(x,y)

locator=MaxNLocator(prune='both', nbins=5)
ax1.yaxis.set_major_locator(locator)

# You don't need to use tight_layout and using it might give an error
# plt.tight_layout()

fig.show()

rawDescription: matplotlib - How can I use MaxNLocator and specify a number which has to be in an axis?

description: Matplotlib - How can I use MaxNLocator and specify a number which has to be in an axis


code:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)

class ImageCategoryToImageAssociation(db.Model):
    __tablename__ = 'image_categories_to_image_association'
    image_category_id = db.Column(db.Integer, db.ForeignKey('image_categories.id'), primary_key=True)
    image_id = db.Column(db.Integer, db.ForeignKey('images.id'), primary_key=True)
    order = db.Column(db.Integer, default=0)
    image = db.relationship("Image", back_populates="categories")
    category = db.relationship("ImageCategory", back_populates="images")

class ImageCategory(db.Model):
    __tablename__ = 'image_categories'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), unique=True)
    images = db.relationship(ImageCategoryToImageAssociation, back_populates="category", order_by="ImageCategoryToImageAssociation.order")

class Image(db.Model):
    __tablename__ = 'images'
    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.String(255), default='')
    categories = db.relationship(ImageCategoryToImageAssociation, back_populates="image")

@app.route('/')
def index():

    _html = ""
    categories = ImageCategory.query.all()
    for category in categories:
        _html += "
Category : {category}
".format(category=category.name)
        _html += "
"
        for assoc in category.images:
            _html += "
Image : {url}; Order: {order}
".format(url=assoc.image.url, order=assoc.order)

        _html += "
"

    return _html

def build_db():

    db.drop_all()
    db.create_all()

    # Add Categories
    category_1 = ImageCategory(name="First Category")
    db.session.add(category_1)
    category_2 = ImageCategory(name="Second Category")
    db.session.add(category_2)

    # Add Images
    image_1 = Image(url="First Image")
    db.session.add(image_1)
    image_2 = Image(url="Second Image")
    db.session.add(image_2)

    image_3 = Image(url="Third Image")
    db.session.add(image_3)

    # Associate images with category 1
    a_1 = ImageCategoryToImageAssociation(order=0)
    a_1.image = image_1
    category_1.images.append(a_1)

    a_2 = ImageCategoryToImageAssociation(order=2)
    a_2.image = image_2
    category_1.images.append(a_2)

    a_3 = ImageCategoryToImageAssociation(order=1)
    a_3.image = image_3
    category_1.images.append(a_3)

    # Associate images with category 2 in reverse order
    a_1 = ImageCategoryToImageAssociation(order=2)
    a_1.image = image_1
    category_2.images.append(a_1)

    a_2 = ImageCategoryToImageAssociation(order=1)
    a_2.image = image_2
    category_2.images.append(a_2)

    a_3 = ImageCategoryToImageAssociation(order=0)
    a_3.image = image_3
    category_2.images.append(a_3)

    db.session.commit()

@app.before_first_request
def before_first_request():
    build_db()

if __name__ == '__main__':
    app.run()

rawDescription: Flask-SQLAlchemy,How to sort results in Many-to-Many Relationship?


code:
import sys
from PyQt4.QtGui import *

class TableWidgetDragRows(QTableWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.setDragEnabled(True)
        self.setAcceptDrops(True)
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.setDragDropOverwriteMode(False)
        # self.setSelectionMode(QAbstractItemView.SingleSelection)

        self.last_drop_row = None

    # Override this method to get the correct row index for insertion
    def dropMimeData(self, row, col, mimeData, action):
        self.last_drop_row = row
        return True

    def dropEvent(self, event):
        # The QTableWidget from which selected rows will be moved
        sender = event.source()

        # Default dropEvent method fires dropMimeData with appropriate parameters (we're interested in the row index).
        super().dropEvent(event)
        # Now we know where to insert selected row(s)
        dropRow = self.last_drop_row

        selectedRows = sender.getselectedRowsFast()

        # Allocate space for transfer
        for _ in selectedRows:
            self.insertRow(dropRow)

        # if sender == receiver (self), after creating new empty rows selected rows might change their locations
        sel_rows_offsets = [0 if self != sender or srow < dropRow else len(selectedRows) for srow in selectedRows]
        selectedRows = [row + offset for row, offset in zip(selectedRows, sel_rows_offsets)]

        # copy content of selected rows into empty ones
        for i, srow in enumerate(selectedRows):
            for j in range(self.columnCount()):
                item = sender.item(srow, j)
                if item:
                    source = QTableWidgetItem(item)
                    self.setItem(dropRow + i, j, source)

        # delete selected rows
        for srow in reversed(selectedRows):
            sender.removeRow(srow)

        event.accept()

    def getselectedRowsFast(self):
        selectedRows = []
        for item in self.selectedItems():
            if item.row() not in selectedRows:
                selectedRows.append(item.row())
        selectedRows.sort()
        return selectedRows

class Window(QWidget):
    def __init__(self):
        super().__init__()

        layout = QHBoxLayout()
        self.setLayout(layout)

        self.table_widgets = []
        for _ in range(3):
            tw = TableWidgetDragRows()
            tw.setColumnCount(2)
            tw.setHorizontalHeaderLabels(['Colour', 'Model'])

            self.table_widgets.append(tw)
            layout.addWidget(tw)

        filled_widget = self.table_widgets[0]
        items = [('Red', 'Toyota'), ('Blue', 'RV'), ('Green', 'Beetle')]
        for i, (colour, model) in enumerate(items):
            c = QTableWidgetItem(colour)
            m = QTableWidgetItem(model)

            filled_widget.insertRow(filled_widget.rowCount())
            filled_widget.setItem(i, 0, c)
            filled_widget.setItem(i, 1, m)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: Drag and Dropping Rows between two separate QTableWidgets


rawDescription: Does Tornado AsyncHTTPClient support persistance connection?


code:
def get_node(container, path):
    for node in path:
        container = container[node]
    return container

def set_node(container, path, value):
    container = get_node(container, path[:-1])
    container[path[-1]] = value

DISCLAIMER_PATH = ("template_data_array", 0, "template_section", "section_fields_data",
                   0, "disclaimer_text")

set_node(plist, DISCLAIMER_PATH, new_text)

rawDescription: known dictionary structure, but very nested - alternative to ugly code

description: Known dictionary structure, but very nested - alternative to ugly code


code:
self.setStyleSheet("""QToolTip {
                           background-color: black;
                           color: white;
                           border: black solid 1px
                           }""")

rawDescription: Setting the text colour of a tooltip in PyQt


rawDescription: Pandas - Efficient way for this?

description: Pandas - Efficient way for this


code:
from shapely.geometry import Polygon

lists = [[(1,1),(2,2),(3,3),(4,4)], [(6,6),(7,7),(8,8),(9,9)], [(1,1),(2,2),(3,3),(4,4)]]
polys = [Polygon(item) for item in lists] ##This is given condition
uniqpolies = []
for poly in polys:

    if not any(p.intersects(poly) for p in uniqpolies):
        uniqpolies.append(poly)

rawDescription: Removing Duplicate Geometries

description: Removing Duplicate Geometries


code:
d = datetime.datetime.strptime("23:23:23","%H:%M:%S")
d.time()

rawDescription: python - datetime output time only

description: Python - datetime output time only


code:
import sqlalchemy as sqa

def DuplicateObject(oldObj):
    # SQLAlchemy related data class?
    if not isinstance(oldObj, _Base):
        raise TypeError('The given parameter with type {} is not ' \
            'mapped by SQLAlchemy.'.format(type(oldObj)))

    mapper = sa.inspect(type(oldObj))
    newObj = type(oldObj)()

    for name, col in mapper.columns.items():
        # no PrimaryKey not Unique
        if not col.primary_key and not col.unique:
            setattr(newObj, name, getattr(oldObj, name))

    return newObj

rawDescription: How to duplicate an SQLAlchemy-mapped object the correct way?

description: Duplicate an SQLAlchemy-mapped object the correct way


code:
import re
s = 'blah blah link'
re.sub('<[^>]*>', '', s)

rawDescription: Python HTML removal

description: Python HTML removal


code:
placeholders = []
for plugin in project.projectplugin_set.all():
    placeholders.append(plugin.placeholder_id)
NewsEntry.objects.filter(content__in=placeholders).distinct()

rawDescription: django-cms placeholder outside cms - how to get related model using the placeholder from the one model that is connected?

description: Django-cms placeholder outside cms - how to get related model using the placeholder from the one model that is connected


code:
# Bind mouse motion events in the canvas
self.figure.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)

# ...

def on_mouse_move(self, evt):
    #
    # LAAAME SAUCE -- Crosshair cursor is all black on Windows making it
    #    virtually invisible on dark images. Use custom cursor instead.
    #
    if (sys.platform.lower().startswith('win') and
        evt.inaxes and
        self.navtoolbar.mode == 'Zoom to rect mode'):  # NOTE: There are no constants for the navbar modes
        #
        # Build the crosshair cursor image as a numpy array.
        # Sadly I can't figure out how to make a white outline since every
        # value above 127 is apparently transparent.
        # Soooo the outline is yellow.
        #
        # Best docs I could find: http://wxruby.rubyforge.org/doc/cursor.html
        #
        buf = np.ones((16,16,3), dtype='uint8') * 255
        buf[:,:,2] = 1
        buf[7,1:-1,:] = buf[1:-1,7,:] = 0
        buf[:6,:6,:] = buf[9:,:6,:] = buf[9:,9:,:] = buf[:6,9:,:] = 255
        #
        # NOTE: I tried making an alpha channel and doing
        #  wx.ImageFromBuffer(16, 16, buf.tostring(), alpha_buffer.to_string())
        # ...no good. wx just ignores the channel.
        #
        im = wx.ImageFromBuffer(16, 16, buf.tostring())
        im.SetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_X, 7)
        im.SetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_Y, 7)
        cursor = wx.CursorFromImage(im)
        self.figure.canvas.SetCursor(cursor)

rawDescription: Fix for all-black wx cursors on windows

description: Fix for all-black wx cursors on windows


rawDescription: Python - Expression generator to build list with 'and' before last item?


rawDescription: Split text on paragraphs where paragraph delimiters are non-standard


code: newArgs = re.sub(argVariable+r'=\S*', item, newArgs)

rawDescription: How to replace non-character surrounded string in python

description: Replace non-character surrounded string in python


code:
article = page.summary()   # Extract article using readability
article.findAll("a")       # Return a list of all links in the article

rawDescription: Is there a way to use readability (text extraction algorithm) and a custom algorithm in python to extract links from text?


code:
class Model2(QAbstractTableModel):
    def __init__(self, model, parent=None):
        self.model = model
        QAbstractTableModel.__init__(self, parent)

    def rowCount(self):
        return self.model.columnCount()

    def columnCount(self):
        return self.model.rowCount()

    def data(self, a, b):
        return self.model.data(b, a)

rawDescription: How to change QTableView items Orientation from Vertical to Horizontal?

description: Change QTableView items Orientation from Vertical to Horizontal


code:
class Activity(EmbeddedDocument):
    user = ReferenceField('Profile')
    user_unrelated = ReferenceField('Profile')
    created_date = DateTimeField(default=datetime.datetime.now, required=True)

rawDescription: ReferenceField in EmbeddedDocument to master Document


code: sharedModule.agr = aggregator

rawDescription: Why can't I change variables from cached modules in IronPython?


rawDescription: How do I create unicode characters with variable numbers?

description: Create unicode characters with variable numbers


code:
from cvxopt import matrix, spmatrix
from cvxopt.blas import gemv
from cvxopt.solvers import qp

def append_matrix_at_bottom(A, B):
    l = []
    for x in xrange(A.size[1]):
        for i in xrange(A.size[0]):
            l.append(A[i+x*A.size[0]])
        for i in xrange(B.size[0]):
            l.append(B[i+x*B.size[0]])
    return matrix(l,(A.size[0]+B.size[0],A.size[1]))

M = matrix([[ 4.0,  6, -4,    1.0 ],
            [ 6,  1,  1.0,     2.0 ],
            [-4,  1.0,   2.5,  -2.0 ],
            [ 1.0,   2.0,   -2.0,     1.0 ]])
q = matrix([12, -10, -7.0, 3])

I = spmatrix(1.0, range(M.size[0]), range(M.size[1]))
G = append_matrix_at_bottom(-M, -I)   # inequality constraint G z <= h
h = matrix([x for x in q] + [0.0 for _x in range(M.size[0])])

sol = qp(2.0 * M, q, G, h)      # find z, w, so that w = M z + q
if sol['status'] == 'optimal':
    z = sol['x']
    w = matrix(q)
    gemv(M, z, w, alpha=1.0, beta=1.0)   # w = M z + q
    print(z)
    print(w)
else:
    print('failed')

rawDescription: How to solve an LCP (linear complementarity problem) in python?

description: Solve an LCP (linear complementarity problem) in python


code:
from django.db.models import Q
result = SomeModel.objects.filter(Q(somefield='foo') | Q(somefield='bar'))

rawDescription: django objects.filter with 2 conditions for the same keyword where either of them match

description: Django objects.filter with 2 conditions for the same keyword where either of them match


code:
import sys, subprocess
sys.exit(subprocess.call(['php', sys.argv[0].replace('.py', '.php')] + sys.argv[1:]))

rawDescription: 1:1 call PHP from Python

description: 1:1 call PHP from Python


code:
import re
s = "first token, <second token part 1, second token part 2>, third token"
regex = re.compile(",(?![^<>]*>)")
regex.split(s)
[item.strip(" <>") for item in _]

rawDescription: Split string by delimiter only if not wrapped in certain pattern


code:
now = timezone.now()
items_within_date_range = Q(start_date__lte=today, end_date__gte=today)
curr_store_items = Q(store=store_id)

result = SaleItems.objects.filter(items_within_date_range|curr_store_items).distinct()

rawDescription: How to filter queryset not equal to in Django?

description: Filter queryset not equal to in Django


code:
# prints the length of name if user desires, if not it goes onto ask age

answer = input('Would you like to know the length of your name?')
# Rather than printing, input can take the string to print (helps with figuring out what the input is used for)
affirmative = ['yes', 'Yes', 'yeah', 'Yeah', 'yup', 'Yup', 'y', 'Y', 'yea',
'Yea']
negative = ['No', 'no', 'Nope', 'nope', 'N', 'n', 'Nah', 'nah']
if answer in affirmative:
    print('The length of your name is ' + str(int(len(myName))))
elif answer in negative:
    print('Ok! Thats fine! I didn\'t want to tell you anyway!')
else:
    print('Ok then.....next question')

rawDescription: Using lists to define multiple answers in if, elif, else statements


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

# creates two lists with the same length
x = range(20)
y = [0] * 20
for i in x:
  y.insert(i, np.random.random())
  plt.plot(x, y)
  plt.savefig('plot_%d.png' % i)

rawDescription: matplotlib: Continuously overwriting

description: Matplotlib: Continuously overwriting


code:
def sc1(self, *argv):
        self.a = float(argv[0])
        # rather than re-request the value resulting in more function calls
        # i'm using the value that is passed in during the callback
        if not hasattr(self, "a_prev"): # this is a hacky method to
            self.a_prev = 1             # remember the previous value

        b_diff = self.scale_2.get() - self.a_prev
        c_diff = self.scale_3.get() - self.a_prev
        # calculate the differences to the previous value

        self.scale_2.set(self.a+b_diff) # set the scales
        self.scale_3.set(self.a+c_diff)
        self.a_prev = self.a # remember current value as the new previous

rawDescription: one scale controls other scale values in tkinter python3

description: One scale controls other scale values in tkinter python3


code:
import Image
import math

def ScaleRotateTranslate(image, angle, center = None, new_center = None, scale = None, resample=Image.NEAREST):
    if (scale is None) and (center is None):
        return image.rotate(angle=angle, resample=resample)
    nx,ny = x,y = center
    sx=sy=1.0
    if new_center:
        (nx,ny) = new_center
    if scale:
        (sx,sy) = (scale, scale)
    cosine = math.cos(angle)
    sine = math.sin(angle)
    a = cosine/sx
    b = sine/sx
    c = x-nx*a-ny*b
    d = -sine/sy
    e = cosine/sy
    f = y-nx*d-ny*e
    return image.transform(image.size, Image.AFFINE, (a,b,c,d,e,f), resample=resample)

def Distance(p1,p2):
    dx = p2[0] - p1[0]
    dy = p2[1] - p1[1]
    return math.sqrt(dx*dx+dy*dy)

pilIm = Image.open('/Users/carlos/Downloads/image.jpg').convert('RGB');
eye_left = (10,10)
eye_right = (40,30)
rotation = 0.3;

image_center = ((eye_left[0]+eye_right[0])/2,(eye_left[1]+eye_right[1])/2)
rotatedImg = ScaleRotateTranslate(pilIm,center=image_center,angle=rotation)
rotatedImg.save('out.jpg')

rawDescription: Why the image color is changed after affine transform using PIL?


code:
class RegistrationForm(forms.Form):
     user_type = forms.ChoiceField(choices=Person.USER_TYPE_CHOICES)

rawDescription: Database choices with modelchoiceform connection


code:
# original queryset - where author is an FK
queryset = MyModel.objects.values('id', 'author')

# loop through the original queryset, and replace FK
author_map = {a['id']: a for a in Author.objects.values('id', 'name')}
for obj in queryset:
    obj['author'] = author_map[obj['author']]

rawDescription: How to combine select_related() and value()? (2016)

description: Combine select_related() and value()? (2016)


code:
import csv

diseases = {}

# Load the disease file in memory
with csv.reader(open('table1.csv', 'rb')) as dfile:
    # Skip the header
    dfile.next()
    for disease, gene, pvalue in dfile:
        diseases[gene] = (disease, pvalue)

with csv.reader(open('table2.csv', 'rb')) as idfile, csv.writer(open('output.csv', 'wb')) as output:
    # Skip the header
    idfile.next()
    for ident, homologue, symbol in idfile:
        if symbol in diseases:
            output.writerow((ident, homologue, symbol) + diseases[symbol])

rawDescription: Matching and merging two text tables?

description: Matching and merging two text tables


rawDescription: Get the word from a WordNet synset

description: Get the word from a WordNet synset


code:
def getFiles(files):
    for file in files:
        file_start, file_number, file_end = file.split('-')
        num = file_number.split().zfill(4)  # num is 4 characters long with leading 0

        new_file = "{}- {} -{}".format(file_start, num, file_end)
        # rename or store the new file name for later rename

rawDescription: Python - Add leading 0 to file numbers

description: Python - Add leading 0 to file numbers


code:
import csv
import datetime
import sys
import os.path

def key(date):
    date = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
    date = datetime.date(date.year,
                         date.month,
                         1 if date.day < 16 else 16)
    date = date.strftime('%Y-%m-%d')
    return date

old_key = None
for filename in sys.argv[1:]:
    with open(filename) as file_in:
        base, ext = os.path.splitext(filename)
        rows_in = csv.reader(file_in)
        for row in rows_in:
            new_key = key(row[3])
            if new_key != old_key:
                old_key = new_key
                filename_out = '%s-%s%s'%(base, new_key, ext)
                file_out = open(filename_out, 'w')
                rows_out = csv.writer(file_out)
            rows_out.writerow(row)

rawDescription: Split CSV data in biweekly partitions

description: Split CSV data in biweekly partitions


code:
def game(n):
    for i in range(n):
        dig1 = random.randrange(0,10)
        dig2 = random.randrange(0,10)
        print (dig1, '+', dig2, '=')
        answer = eval(input('Enter Answer: '))
        if answer == dig1 + dig2:
            print ('Correct.')
        else:
            print ('Incorrect.')

rawDescription: single digit addition questions

description: Single digit addition questions


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('bbb</html')
soup.find('a')

rawDescription: Extracting HTML data fields with Python

description: Extracting HTML data fields with Python


code:
# Use cStringIO to create the file on the fly
cebd_xml_file = StringIO.StringIO()

# Create the file name ...
base_file_name = "cebd"

# Get the XML String
xml_string = get_xml_cebd(cebds)

# Create the Gzip file handler, with the StringIO in the fileobj
gzip_handler = gzip.GzipFile(
    fileobj=cebd_xml_file,
    filename=base_file_name + '.xml',
    mode='wb'
)

# Write the XML data into the gziped file
gzip_handler.write(xml_string)

# Flush the data
gzip_handler.flush()

# Close the Gzip handler, the close method will add the CRC32 and the size
gzip_handler.close()

# Generate the response using the file warpper, content type: x-gzip
# Since this file can be big, best to use the StreamingHTTPResponse
# that way we can garantee that the file will be sent entirely
response = StreamingHttpResponse(
    cebd_xml_file.getvalue(),
    content_type='application/x-gzip'
)

# Add content disposition so the browser will download the file, don't use mime type !
response['Content-Disposition'] = ('attachment; filename=' +
    base_file_name + '.xml.gz')

# Content size
cebd_xml_file.seek(0, os.SEEK_END)
response['Content-Length'] = cebd_xml_file.tell()

# Send back the response to the request, don't close the StringIO handler !
return response

rawDescription: Django - HTTPStream of gzip file creaed on the fly


code:
re.search(r'\d{10}$', n).group()
re.search(r'\d{10}$', m).group()

rawDescription: How to ignore characters with Python Regex

description: Ignore characters with Python Regex


code:
class Asignaturas(models.Model):
    ...
    #your fields
    ...
    nombre = models.CharField(max_length=255)

    def __unicode__(self):
        return self.nombre

rawDescription: ModelChoiceForm not showing any values

description: ModelChoiceForm not showing any values


code:
import Tkinter as tk

class Window():

    def __init__(self, root):

        self.frame = tk.Frame(root)
        self.frame.grid()

        self.i = 0
        self.labelVar = tk.StringVar()
        self.labelVar.set("This is the first text: %d" %self.i)

        self.label = tk.Label(self.frame, text = self.labelVar.get(), textvariable = self.labelVar)
        self.label.grid(column = 0, row = 0)

        self.button = tk.Button(self.frame, text = "Update", command = self.updateLabel)
        self.button.grid(column = 1, row = 0)

        self.enableButton = tk.Button(self.frame, text = "Enable Update Button", state = 'disabled', command = self.enable)
        self.enableButton.grid(column = 2, row = 0)

    def updateLabel(self):

        self.i += 1
        self.labelVar.set("This is the new text: %d" %self.i)
        self.button.config(state = 'disabled')
        self.enableButton.config(state = 'active')

    def enable(self):

        self.button.config(state = 'active')
        self.enableButton.config(state = 'disabled')

root = tk.Tk()
window = Window(root)
root.mainloop()

rawDescription: Tkinter button disable not working

description: Tkinter button disable not working


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

from PyQt4 import QtCore, QtGui

class Settings(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Settings, self).__init__(parent)

        self.parent = parent

        self.setWindowTitle(u'Préférences')

        self.list_pathes = QtGui.QListWidget(self)

        self.label_directories = QtGui.QLabel(self)
        self.label_directories.setText(u"Dossiers surveillés :")

        self.rm_directory_button = QtGui.QPushButton(self)
        self.rm_directory_button.setText(u"Enlever")
        self.rm_directory_button.clicked.connect(self.removePath)

        self.add_directory_button = QtGui.QPushButton(self)
        self.add_directory_button.setText(u"Ajouter")
        self.add_directory_button.clicked.connect(self.addPath)

        self.gridLayout = QtGui.QGridLayout(self)
        self.gridLayout.addWidget(self.label_directories, 0, 0, 1, 1)
        self.gridLayout.addWidget(self.list_pathes, 2, 0, 2, 2)
        self.gridLayout.addWidget(self.rm_directory_button, 3, 2, 1, 1)
        self.gridLayout.addWidget(self.add_directory_button, 2, 2, 1, 1)

        self.show()
    #    self.connexion()

    def connexion(self):
        self.parent.options.beginGroup("Watching")
        pathes = self.parent.options.allKeys()
        if pathes:
            for each_key in pathes:
                self.list_pathes.addItem(self.parent.options.value(each_key))

        self.parent.options.endGroup()

    def removePath(self):
        try:
            path = self.list_pathes.selectedItems()[0].text()
            item = self.list_pathes.takeItem(self.list_pathes.currentRow())
            del item

        except IndexError:
            print(u"Aucun path sélectionné")

    def addPath(self):
        path = QtGui.QFileDialog.getExistingDirectory(self, 'Open file', '/home')
        self.list_pathes.addItem(path)

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.settingsAction = QtGui.QAction(u'Préférences', self)
        self.settingsAction.triggered.connect(lambda: Settings(self))

        self.toolBar = QtGui.QToolBar(self)
        self.toolBar.addAction(self.settingsAction)

        self.addToolBar(QtCore.Qt.ToolBarArea(QtCore.Qt.TopToolBarArea), self.toolBar)

if __name__ == "__main__":
    import  sys

    app  = QtGui.QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())

rawDescription: Secondary window without slot

description: Secondary window without slot


code:
s = pd.Series([4,3,1,5,2], index=range(10,15))
a = s.nsmallest(2)
a
s = pd.Series([None,3,1,5,2], index=range(10,15))
a = s.nsmallest(2)
a

rawDescription: getting indexes of smallest items in the presence of NA

description: Getting indexes of smallest items in the presence of NA


rawDescription: Django Rest Frame API: additional fields in ModelSerializer


code:
from glob import glob
filelist = glob('*.csv') #You can pass the sys.argv argument

rawDescription: Passing arguments with wildcards to a Python script


code:
mask = freq>=0
pl.plot(freq[mask]*2*np.pi, np.sqrt(sp[mask].real**2+sp[mask].imag**2))
pl.plot(freq[~mask]*2*np.pi, np.sqrt(sp[~mask].real**2+sp[~mask].imag**2))

rawDescription: how to remove the unecessay straight line in the plot?

description: Remove the unecessay straight line in the plot


code:
from datetime import datetime
from urllib.parse import urljoin

from bs4 import BeautifulSoup

import requests

#Getting the current date
today = datetime.today()

#Here I'm only passing from and to dates (current date) and the industry parameter
payload = {
    'selDay': 31,
    'selMonth': 12,
    'selYear': 2014,
    'selDay1': 31,
    'selMonth1': 12,
    'selYear1': 2014,
    'selIndustry': '',
    'txtPhrase': '',
    'txtInclude': '',
    'txtExclude': '',
    'selSubServices': 'ALL',
    'selServices': 'all',
    'maxresults': 10,
    'pageno': 1,
    'srchInSrchCol': '01',
    'sortOptions': 'date',
    'isSrchInSrch': '01',
    'txtShowQuery': '01',
    'tSearch': 'Find a Rating',
    'txtSearch': '',
    'selArchive': 1,
    'selSector': 148,
    'selCompany': '',
    'x': 40,
    'y': 11,
}

crisil_url = "http://www.crisil.com/ratings/ratings-rationales.jsp?result=true&Sector=true"
r = requests.post(crisil_url, data=payload)

soup = BeautifulSoup(r.content)

crisil_links = lambda tag: getattr(tag, 'name', None) == 'a' and 'stable' in tag.get_text().lower() and 'href' in tag.attrs
results = soup.find_all(crisil_links)
result_links = [urljoin(crisil_url, tag['href']) for tag in results]
print (result_links)

rawDescription: How to give inputs to a website using python

description: Give inputs to a website using python


code:
from os.path import join, splitext

onlyfiles = [splitext(f)[0] for f in listdir(src_dir) if isfile(join(src_dir,f)) ]

rawDescription: Build a list for all the file name of a directory


code:
import scipy.io
import numpy as np
my_list = np.zeros((3,), dtype=np.object)
my_list[:] = ['abc', 'def', 'ghi']
scipy.io.savemat('test.mat', mdict={'my_list': my_list})

rawDescription: Python to MATLAB: exporting list of strings using scipy.io


code: [legname for cow in listofcows for legname in cow.legnames]

rawDescription: How to handle a one line for loop without putting it in a List?

description: Handle a one line for loop without putting it in a List


code:
from kivy.app import App
from kivy.clock import Clock
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from random import random
import time

from kivy.clock import Clock
from functools import partial

def set_color(button, color, *args):
    button.color = color

class MemorizeGame(GridLayout):
    def __init__(self, **kwargs):
        super(MemorizeGame, self).__init__(**kwargs)
        self.cols = 2

        #create buttons
        self.button1 = Button(text='', background_color=(0,0,1,1))
        self.button2 = Button(text='', background_color=(0,1,1,1))
        self.button3 = Button(text='', background_color=(1,0,1,1))
        self.button4 = Button(text='', background_color=(0,1,0,1))
        self.buttonList = [self.button1, self.button2, self.button3, self.button4]

        #add buttons to the screen
        for button in self.buttonList:
            self.add_widget(button)

    def blinkSquare(self):
        self.button1.background_color = (1, 1, 1, 1)
        def reset_color(*args):
            self.button1.background_color = (0, 0, 1, 1)
        Clock.schedule_once(reset_color, 1)

        # alternative:
        # Clock.schedule_once(partial(set_color, self.button1, (0, 0, 1, 1)))

    def on_touch_down(self, touch):
        self.blinkSquare()

class MemorizeApp(App):

    def build(self):
        game= MemorizeGame()
        return game

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

rawDescription: Kivy make button in grid blink

description: Kivy make button in grid blink


code:
import module2

module2.Messages = ...

rawDescription: Monkey patching a class in a function that is called from a child method (Python)


code:
def dp_min_ops(n):
    all_parents = [None] * (n + 1)
    all_min_ops = [0] + [None] * n

    for k in range(1, n + 1):
        curr_parent = k - 1
        curr_min_ops = all_min_ops[curr_parent] + 1

        if k % 3 == 0:
            parent = k // 3
            num_ops = all_min_ops[parent] + 1
            if num_ops < curr_min_ops:
                curr_parent, curr_min_ops = parent, num_ops

        if k % 2 == 0:
            parent = k // 2
            num_ops = all_min_ops[parent] + 1
            if num_ops < curr_min_ops:
                curr_parent, curr_min_ops = parent, num_ops

        all_parents[k], all_min_ops[k] = curr_parent, curr_min_ops

    numbers = []
    k = n
    while k > 0:
        numbers.append(k)
        k = all_parents[k]
    numbers.reverse()

    return all_min_ops, numbers

print(dp_min_ops(5))   # ([0, 1, 2, 2, 3, 4], [1, 3, 4, 5])
print(dp_min_ops(10))  # ([0, 1, 2, 2, 3, 4, 3, 4, 4, 3, 4], [1, 3, 9, 10])

rawDescription: Dynamic Programming - Primitive Calculator Python


code:
def preprocess_colors(data):
    colors = data.pop('colors', None)
    if colors is not None:
        # set primary and secondary colors
        data['primary_color'] = get_primary_color(color)
        data['secondary_color'] = get_secondary_color(colors)

rawDescription: Custom arguments in Flask-Restless?

description: Custom arguments in Flask-Restless


code:
import os
files = os.listdir("your/path/")

rawDescription: Extract names of files from a directory in python


code:
import os

while True:
  os.system('python run.py')

rawDescription: How do I write a script that re-execute a python script after it exits back to cmd prompt?

description: Write a script that re-execute a python script after it exits back to cmd prompt


rawDescription: Python: Elementwise join of two lists of same length


code:
from ast import literal_eval
newlist = [[literal_eval(el) for el in item] for item in mylist]

rawDescription: Converting string list to number equivalent


code:
def _do_subproc(command, bar):
    subprocess.call(command, shell=True)
    glib.idle_add(bar.push, 1, "Done!") # call bar.push in the main GUI thread

def on_button_clicked(self, widget):
    self.statusBar.push(1, "Doing the subprocess...")
    command = '...'
    threading.Thread(target=lambda: _do_subproc(command, self.statusBar)).start()

rawDescription: Run a python command before a subprocess call in same function?


code:
def check(something):
    if something == 1:
        return "foo"
    if something == 2:
        return "bar"
    return "n/a"

rawDescription: When would it be more effective to use if/else combinations rather than elif?


code:
from collections import defaultdict

myList = [['hostile', 'angry'], ['elated', 'happy'], ['elated', 'grateful'], ['depressed', 'sad']]

myDict = defaultdict(list)

for key, value in myList:
    myDict[key].append(value)

rawDescription: How to map to a dictionary

description: Map to a dictionary


code:
import sys
import time
for i in range(100):
    sys.stdout.write("\rInstallation Progress: %d percent" % i)
    time.sleep(.05)
    sys.stdout.flush()

rawDescription: Updating a line of text in Python 3

description: Updating a line of text in Python 3


code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
import time
class MainFrame(wx.Frame):
    def __init__(self, *args, **kwds):
#        kwds["pos"] = (10,10)
        self.frame = wx.Frame.__init__(self, *args, **kwds)
        self.SetTitle("Move around the screen")
        self.InitUI()

    def InitUI(self):
        self.location1 = wx.Point(10,10)
        self.location2 = wx.Point(500,500)
        self.panel1 = wx.Panel(self)
        self.button1 = wx.Button(self.panel1, -1, label="Move", size=(80,25), pos=(10,10))
        self.button1.Bind(wx.EVT_BUTTON, self.OnItem1Selected)
        self.Show()
        self.Move(self.location1)

    def OnItem1Selected(self, event):
        self.MoveAround()

    def MoveAround(self):
        curr_location = self.GetPosition() #or self.GetPositionTuple()
        if curr_location == self.location1:
            print ("moving to ", self.location2)
            self.Move(self.location2) #Any of these 3 commands will work
#            self.MoveXY(500,500)
#            self.SetPosition(wx.Point(500,500), wx.SIZE_USE_EXISTING)
        else:
            print ("moving to ", self.location1)
            self.Move(self.location1) #Any of these 3 commands will work
#            self.MoveXY(10,10)
#            self.SetPosition(wx.Point(10,10), wx.SIZE_USE_EXISTING)

if __name__ == '__main__':
    app = wx.App()
    frame = MainFrame(None)
    app.MainLoop()

rawDescription: How do you re-position an open window in wxpython

description: Re-position an open window in wxpython


code:
if __name__ == '__main__':
    import timeit

    print(timeit.timeit("LongestWordA('hello this is just an example')", number=1000, setup="from __main__ import LongestWordA"))
    print(timeit.timeit("LongestWordB('hello this is just an example')", number=1000, setup="from __main__ import LongestWordB"))

    # LongestWordA 0.013688346021808684
    # LongestWordB 0.004950157948769629

rawDescription: Pythonic methods of returning the longest word in a string


rawDescription: How to redirect page from view

description: Redirect page from view


code:
class Foo(object):
    bar = None  # shared

    def __init__(self):
        type(self).bar = 'baz'  # still shared, *per subclass*
        Foo.bar = 'baz'         # still shared, across all subclasses*

rawDescription: Shared properties between classes and instances


code:
mask = df[['A', 'B', 'C']].eq(df['A'], axis=0).all(axis=1)
mask
df[~mask]

rawDescription: Pandas: Subset Data Where Multiple Row Values Are Not All The Same


code:
def do_GET(self):
    self.send_response(200)
    self.send_header("Content-type", "text/html")
    self.send_header("Content-length", len(DUMMY_RESPONSE))
    self.end_headers()
    self.wfile.write(DUMMY_RESPONSE)

description: SimpleHTTPRequestHandler Override do_GET


rawDescription: perform function using values from 2 columns and return result as new column

description: Perform function using values from 2 columns and return result as new column


rawDescription: how to collapse/compress/reduce string columns in pandas

description: Collapse/compress/reduce string columns in pandas


code:
selection = int(raw_input('-->'))
selected_sql = upgrades[selection - 1]

rawDescription: Use Value From List To Set Variable Interactively


code:
from sys import version_info
if version_info.major == 2:  # pragma: no cover
    from httplib import ACCEPTED, NO_CONTENT  # pylint:disable=import-error
else:  # pragma: no cover
    from http.client import ACCEPTED, NO_CONTENT  # pylint:disable=import-error

rawDescription: How to check http status code in python version agnostic way?

description: Check http status code in python version agnostic way


code:
import pexpect  # $ pip install pexpect

while var3:  # start ./test.sh again
    output = pexpect.run('./test.sh arg1',
        timeout=x,  # terminate child process after x seconds
        events={r'(?i)question 1': var1,  # provide answers
                r'(?i)question 2': var2})

rawDescription: Scripting a bash script from inside python


code:
dfa = pd.DataFrame({'A': range(5)}, index=range(5))
dfb = pd.DataFrame({'A': range(10, 15)}, index=range(3,8))
dfa
dfb
dfb.loc[dfb.index - dfa.index]

rawDescription: how to do right join where key is null in python pandas

description: Do right join where key is null in python pandas


code: eur3m.index = [datetime.datetime.strptime(x, '%d/%m/%Y') for x in eur3m.index]

rawDescription: Handle with European date format in python pandas


code:
@receiver(pre_save, sender=A)
def my_callable(sender, instance, **kwargs):
    A.objects.filter(b=True).update(b=False)

rawDescription: django changing the db

description: Django changing the db


code:
@client_id.expression
def client_id(cls):
    return (
        select([Service.client_id])
        .where(Service.id == cls.owner)
        .as_scalar()
    )

rawDescription: Make a SQL Alchemy Expression return value from a different Table's column for filtering


code: table.heading('#0', text='Name')

rawDescription: Tkinter/Python Treeview change header

description: Tkinter/Python Treeview change header


code:
dic = defaultdict(lambda:1)
dic[5]
dic.default_factory = lambda:2
dic[100]

rawDescription: Change default return value of a defaultdict *after* initialization


code:
import numpy as np
import matplotlib.pyplot as plt
z = np.zeros((400,400))

# specify circle parameters: centre ij and radius
ci,cj=232,145
cr=20

# Create index arrays to z
I,J=np.meshgrid(np.arange(z.shape[0]),np.arange(z.shape[1]))

# calculate distance of all points to centre
dist=np.sqrt((I-ci)**2+(J-cj)**2)

# Assign value of 1 to those points where dist<cr:
z[np.where(dist<cr)]=1

# show result in a simple plot
fig=plt.figure()
ax=fig.add_subplot(111)
ax.pcolormesh(z)
ax.set_aspect('equal')
plt.show()

rawDescription: Python replace zeros in matrix with 'circle' of ones


code:
text = "example@example.com"
element = driver.find_element_by_xpath('//a[contains(@href, "%s")]' % text)

rawDescription: Trying to locate an href that contains text


code:
import bisect
def find_fwd_iter(S, i):
    j = bisect.bisect_left(S, i)
    for k in xrange(j, len(S)):
        yield S[k]
def find_bkwd_iter(S, i):
    j = bisect.bisect_left(S, i)
    for k in xrange(j, -1, -1):
        yield S[k]
L = [100, 150, 200, 300, 400]
list(find_fwd_iter(L, 200))
list(find_bkwd_iter(L, 200))

rawDescription: how to iterate from a specific point in a sequence (Python)

description: Iterate from a specific point in a sequence (Python)


rawDescription: print out all strings between $ and *+2 characters in python

description: Print out all strings between $ and *+2 characters in python


rawDescription: What is a more efficient way to process numpy arrays based on multiple criteria?


code:
import subprocess # This is how we're going to call the commands.

samples = {} # Empty dict
with open('inputfile','r') as f:
    for line in f:
        # Extract sampleID, other things depending on file format...

        samples[sampleID] = [rgid, rglb, grpl, rgpu, rgsm] # Populate dict

for sampleID in samples:
    rgid, rglb, grpl, rgpu, rgsm = samples[sampleID]

    # Now you can run your commands using the subprocess module.
    # Remember to add a change based on sampleID if e.g. the IO files differ.
    subprocess.call(['picard-tools', 'AddOrReplaceReadGroups', 'I=input.bam',
        'O=output.bam', 'RGID=%s' % rgid, 'RGLB=%s' % rglb, 'RGPL=%s' %rgpl,
        'RGPU=%s' % rgpu, 'RGSM=%s' % rgsm, 'VALIDATION_STRINGENCY=SILENT',
        'SORT_ORDER=coordinate', 'CREATE_INDEX=true'])

rawDescription: From spreadsheet to dictionary in ipython/python & more?


code:
def post_handler(self, request):
    payload = request._request_body.decode('utf-8')
    if not payload:
        return {'error': 'Payload not supplied'}

    try:
        json_payload = json.loads(payload)
    except ValueError:
        return {'error': 'Invalid JSON supplied'}
    print('Payload received {0}'.format(json_payload))
    return {'result': 'Payload Received Success'}

rawDescription: AsyncIO python3.4 restserver

description: AsyncIO python3.4 restserver


code:
class SessionManager(models.Manager):
    def new_session(self, visit, **kwargs):
        vs = self.model.objects.filter(visit=visit).order_by("-sequence_no")[:1]
        if len(vs):
            kwargs.update({"sequence_no": vs.sequence_no + 1})
        return Super(SessionManager, self).create(visit=visit, **kwargs)

rawDescription: Help with creating a custom create and a custom get method


code:
class NotifyDict(dict):
    __slots__ = ["callback"]
    def __init__(self, callback, *args, **kwargs):
        self.callback = callback
        dict.__init__(self, *args, **kwargs)
    def _wrap(method):
        def wrapper(self, *args, **kwargs):
            result = method(self, *args, **kwargs)
            self.callback()
            return result
        return wrapper
    __delitem__ = _wrap(dict.__delitem__)
    __setitem__ = _wrap(dict.__setitem__)
    clear = _wrap(dict.clear)
    pop = _wrap(dict.pop)
    popitem = _wrap(dict.popitem)
    setdefault = _wrap(dict.setdefault)
    update =  _wrap(dict.update)

rawDescription: Python Property Change Listener Pattern

description: Python Property Change Listener Pattern


code:
df = pd.read_csv('temp.csv')

df['DATE'] = pd.to_datetime(df['DATE'], format='%m%d%Y')
df['EPOCH'] = pd.to_timedelta((df['EPOCH'].astype(int) * 5).astype('timedelta64[m]'))
df['DATE_TIME'] = df['DATE'] + df['EPOCH']

rawDescription: Concatenating Pandas datetime

description: Concatenating Pandas datetime


code:
d = {}
d["Folder"] = ["C:/blah/blah/Folder", ["file1","file2","file3"]]
d["more"] = ["/home/mydir", ["file1","file2","file3"]]
d["Folder"][0]
d["Folder"][1]
d["Folder"][1].append("file4")
d["Folder"][1]
for entry in d:
    d[entry][1].append("newfile")
d

rawDescription: Attempting to create something using dictionaries but am lost


code:
import picamera

with picamera.PiCamera() as camera:
    camera.resolution = (800, 600)
    camera.start_preview()
    camera.start_recording('foo.h264')
    camera.wait_recording(10)
    camera.capture('foo.jpg', use_video_port=True)
    camera.wait_recording(10)
    camera.stop_recording()

rawDescription: RPi2 - Taking images while recording video


code:
temp = zip(list(data.geom), list(data.address))
output = map(lambda x: {'geometry': x[0], 'properties':{'address':x[1]}}, temp)

rawDescription: Pandas apply to dateframe produces '<built-in method values of ...'


code:
def broadcast_to_players(self, g_id, event, message, update_secret=False, dont_update_self=False):
    the_game = cache.get(g_id)
    player_list = cache.get('game_%s_players' % g_id) #Getting list of players ids
    for player_key in player_list:
        player = cache.get('game_%s_%s' % (g_id, player_key))
        if update_secret == True:
            secret = self.get_secret()
            message['k'] = secret
            player.secret_key = secret
            player.save() #We are storing secret in db, right?
            cache.set('game_secret_%s_%s' % (g_id, secret), player_key) #Making player availiable in game by secret
            cache.set('player_%s_secret' % (player_key, ), secret) #Making player secret available by player id
        if dont_update_self == True:
            if not self.session_id == player.session_id:
                single_session = self.session.server._sessions.get(player.session_id)
                single_session.conn.emit(event, message)
        else:
            single_session = self.session.server._sessions.get(player.session_id)
            single_session.conn.emit(event, message)
    cache.set(g_id, the_game)

def check_player(self, g_id, key):
    return cache.get('game_secret_%s_%s' % (g_id, key))

rawDescription: Django memcached inconsistency

description: Django memcached inconsistency


code: dsn_tns = cx_Oracle.makedsn(ip, port, service_name=SID)

rawDescription: cx_Oracle connection issue

description: Cx_Oracle connection issue


code:
mytext = """Some text
Some more text
etc...
"""

rawDescription: long text as String in python

description: Long text as String in python


code:
import multiprocessing as mp

fd = None

def worker():
    # child closes file, flushing "1"
    fd.close()

def doit():
    global fd
    fd = open('deleteme', 'w')
    fd.write('1')
    p = mp.Process(target=worker)
    p.start()
    p.join()
    # parent closes file, flushing "1"
    fd.close()
    # lets see what we got
    print(open('deleteme').read())

doit()

rawDescription: python garbage collection after start process using multiprocess

description: Python garbage collection after start process using multiprocess


code:
l = ['Fall 2014', 'Spring 2015', 'Fall 2008', 'Spring 2008']
def key(x):
    seas,year = x.split()
    return -int(year), seas != "Spring"

l.sort(key=key)

rawDescription: Python Custom Sort Function for a List

description: Python Custom Sort Function for a List


code:
' something '.strip
' something '.strip()

rawDescription: Python: class method return name

description: Python: class method return name


code:
def readImports(path):
    with open(path) as f:
        for line in f:
            # lines of form "import ___,___"
            # assuming not of form "from ___ import ___ [as ___]"
            if 'import' in line:
                modules = line.split('import')[1]
                for module in modules.split(','):
                    yield module.strip()

linesInExclusion = set(readImports('exclusionlist.txt'))
linesInLibraries = set(readImports('libraries.txt'))

print(linesInExclusion.intersection(linesInLibraries))

rawDescription: comparing contents of two files using python

description: Comparing contents of two files using python


code:
import requests

files = {
    'attachment': ('filename.jpg',
           open('path/to/filename.jpg', 'rb'),
           'image/jpeg; name=filename.jpg',
           {'Content-Transfer-Encoding': 'binary'}),
    'metadata': ('body.xml',
           open('/path/to/body.xml', 'rb'),
           'application/xml; name=body.xml',
           {'Content-Transfer-Encoding': 'binary'})}

response = requests.post(url, files=files)

rawDescription: Sending multipart data with rauth / requests


code:
def remove_doubles(old):
    new = []
    for item in old:
        if new and item == new[-1]:
            continue
        new.append(item)
    return new

rawDescription: Decrement the Variable I'm Incrementing in for loop


code:
from collections import defaultdict

client_requests = defaultdict(int)

class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        ...
        client_requests[self.client_address[0]] += 1
        response = "{} ({}): {}".format(cur_thread.name, client_requests[self.client_address[0]], output)

rawDescription: SocketServer - how to identify clients

description: SocketServer - how to identify clients


code:
x, fs, nbits = audiolab.wavread('schubert.wav')
audiolab.play(x, fs)
N = 4*fs    # four seconds of audio
X = scipy.fft(x[:N])
Xdb = 20*scipy.log10(scipy.absolute(X))
f = scipy.linspace(0, fs, N, endpoint=False)
pylab.plot(f, Xdb)
pylab.xlim(0, 5000)   # view up to 5 kHz

Y = X*H
y = scipy.real(scipy.ifft(Y))

rawDescription: Python: Frequency Analysis of Sound Files


code:
import re
words = ["Hello","name","test"]
Flags=False
my_str = "Hello my name is test"
if any(my_str in word for word in words):
    Flags=True
my_str=re.sub("|".join(words),"******",my_str)

rawDescription: python - replace words from a list

description: Python - replace words from a list


code:
class Geolocation(Base):
    __tablename__ = "geolocation"
    id = Column(Integer, primary_key=True)
    latitude = Column(Float)
    longitude = Column(Float)
    elevation = Column(Float)         # Meters
    # Relationships
    person = relationship('Pin', uselist=False, backref="geolocation")

    def __init__(self, latitude, longitude, elevation):
        self.latitude = latitude
        self.longitude = longitude
        self.elevation = elevation

    def __repr__(self):
        return '<Geolocation %s, %s>' % (self.latitude, self.longitude)

class Pin(Base):
    __tablename__ = 'pin'
    id = Column(Integer, primary_key=True)
    geolocation_id = Column(Integer, ForeignKey('geolocation.id'), unique=True, nullable=False)  # True one to one relationship (Implicit child)
    type = Column('type', String(50))              # discriminator
    __mapper_args__ = {'polymorphic_on': type}

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

class User(Pin):
    __tablename__ = 'user'
    id = Column(Integer, ForeignKey('pin.id'), primary_key=True)
    __mapper_args__ = {'polymorphic_identity': 'user',
                       'inherit_condition': (id == Pin.id)}
    user_id = Column(Integer, autoincrement=True, primary_key=True, unique=True)
    username = Column(String(80), unique=True)
    password_hash = Column(String(120))
    salt = Column(String(120))
    posts = relationship('Posting', primaryjoin="(User.user_id==Posting.user_id)", backref=backref('user'), lazy='dynamic')   #One User to many Postings.

    def __init__(self, username, password_hash, salt, geo_id):
        super(User, self).__init__(geo_id)
        self.username = username
        self.password_hash = password_hash
        self.salt = salt

    def __repr__(self):
        return '<User %s>' % (self.username)

class Posting(Pin):
    __tablename__ = 'posting'
    id = Column(Integer, ForeignKey('pin.id'), primary_key=True)
    __mapper_args__ = {'polymorphic_identity': 'posting',
                        'inherit_condition': (id == Pin.id)}
    posting_id = Column(Integer, autoincrement=True, primary_key=True, unique=True)
    creation_time = Column(DateTime)
    expiration_time = Column(DateTime)
    user_id = Column(Integer, ForeignKey('user.user_id'))              # One User to many Postings

    def __init__(self, creation_time, expiration_time, user_id, geo_id):
        super(Posting, self).__init__(geo_id)
        # For now, require creation time to be passed in. May make this default to current time.
        self.creation_time = creation_time
        self.expiration_time = expiration_time
        self.user_id = user_id

    def __repr__(self):
        #TODO come up with a better representation
        return '<Post %s>' % (self.creation_time)

description: SQLAlchemy Subclass/Inheritance Relationships


code:
def s_exp(x):
    if isinstance(x, (tuple, list)):
        return '(%s)' % (' '.join(map(s_exp, x)))
    return str(x)

rawDescription: Python str() - specify which kind of quotes to add/use?


rawDescription: Django ORM for select max(field1) from table group by (field2);


code:
from datetime import date
from peewee import *

class DrinksModel(Model):
    class Meta:
        database = SqliteDatabase('drinks.db')

class Order(DrinksModel):
    id      = PrimaryKeyField()
    product = CharField()
    user    = CharField()
    amount  = IntegerField()
    price   = DecimalField()
    date    = DateField()

def get_orders_since(year, month=1, day=1):
    orders = Order.select().where(Order.date >= date(year, month, day))

for order in get_orders_since(2014, 2, 14):
    print(
        "{}: {} drank {} x {}"
        .format(order.date, order.user, order.amount, order.product)
    )

rawDescription: Get weekly information about transactions


rawDescription: Filter a reverse manytomany django in one line?


rawDescription: In my date time value I want to use regex to strip out the slash and colon from time and replace it with underscore


code:
health_checks = []

def register_health_check(checker):
    health_checks.append(checker)

def _check_all(sc):
    for hc in health_checks:
        hc.time_passed += 1
        if hc.time_passed == hc.interval_secs:
            hc.reset()
            if not hc.is_healthy():
                hc.on_fail()
    sc.enter(1, 1, _check_all, (sc,))

def start():
    s = sched.scheduler(time.time, time.sleep)
    s.enter(1, 1, _check_all, (s,))
    s.run()

rawDescription: Why does this scheduling function not work as expected?


code:
for input in inputs:
    if input[:5].isnumeric():
        input = input[:5]
        # Takes the first 5 characters from the string

rawDescription: Remove -#### in zipcodes

description: Remove -#### in zipcodes


rawDescription: How to get Numerical Readable Output of Float dtype in Numpy Array?

description: Get Numerical Readable Output of Float dtype in Numpy Array


code:
from django.db.models import Q

Model.objects.filter(
    Q(f1__contains=query) |
    Q(f2__contains=query) |
    Q(f3__contains=query)
)

rawDescription: Django ORM non-strict search through multiple fields


rawDescription: Python Regex Findall javascript

description: Python Regex Findall javascript


code:
from django.core.files.base import ContentFile

if request.FILES.has_key('image_1'):
    image_obj = Image()
    image_obj.file.save(request.FILES['image_1'].name,\
                        ContentFile(request.FILES['image_1'].read()))
    image_obj.save()
    room_obj.image_set.create(image_obj)
    room_obj.save()

rawDescription: Adding a generic image field onto a ModelForm in django


code:
df = pd.DataFrame([[1, 2], [3, 4]], index=list('ab'))
s = pd.Series([2,1], index=list('ab'))
s
s.sort()
df.reindex(s.index)

rawDescription: Pandas: Using a pd.Series to sort a pd.DataFrame with index


code:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure()

ax = fig.add_subplot(111)

gs = gridspec.GridSpec(3,1)
ax.set_position(gs[0:2].get_position(fig))
ax.set_subplotspec(gs[0:2])              # only necessary if using tight_layout()

fig.add_subplot(gs[2])

fig.tight_layout()                       # not strictly part of the question

plt.show()

rawDescription: Changing matplotlib subplot size/position after axes creation


code:
import shlex
filelines = [' '.join(shlex.split(line,True)) for line in file]

rawDescription: How to filter pound signs in a file using python?

description: Filter pound signs in a file using python


code:
terms = set([" ".join(words[j:j + len(words) - i])
               for i in xrange(len(words)) for j in xrange(len(words))])

rawDescription: double list comprehension

description: Double list comprehension


code:
def get_keywords():

        common_words = open('File_Storage/common.txt', 'r').readlines()
        keywords=open(PROJECT_NAME + '/keywords.txt', 'r').read().split('\n')
        f = open(PROJECT_NAME + '/keywords.txt', 'a')
        urls = file_to_set(QUEUE_FILE)
        Hist_queue = urls
        for i in Hist_queue:
            html_content = urllib2.urlopen(i).read()
            soup = BeautifulSoup(html_content)
            for script in soup(["script", "style"]):
                script.extract()
            text = soup.get_text()
            lines = (line.strip() for line in text.splitlines())
            chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
            text = '\n'.join(chunk for chunk in chunks if chunk)
            (text.encode('utf-8'))
            visible_text = soup.getText()
            words = visible_text.split(' ')
            for word in words:
                if word not in common_words and word not in keywords and word.isalnum():
                    f.write(word + '\n')
                    keywords.append(word)
                else:
                        continue

rawDescription: Web scraping wordlists

description: Web scraping wordlists


code:
def sort(sortlist, sortby):
    sortlist.sort(key = lambda x: getattr(x, sortby))

rawDescription: Trying to pass parameters as functions in Python


code:
ts
type(ts.index)
df = ts.reset_index()
df
type(df['index'])
model = pd.ols(y=df[1], x=df['index'], intercept=True)
model

rawDescription: OLS with pandas: datetime index as predictor


code:
from PIL import Image, ImageSequence
im = Image.open("spam.psd")
layers = [frame.copy() for frame in ImageSequence.Iterator(im)]

rawDescription: Python PSD layers?

description: Python PSD layers


code:
class A(str):
   def __new__(cls, color, *args, **kwargs):
       newobj = str.__new__(cls, *args, **kwargs)
       newobj.color = color
       return newobj
a = A("#fff", "horse")
a.color
a
a.startswith("h")

rawDescription: How to bestow string-ness on my class?

description: Bestow string-ness on my class


code:
from django.db import models
from datetime import datetime, timedelta
# Create your models here.
class yourTextLineGroup(models.Model):
    # fields go here
    lock_time = models.DateTimeField(null=True)
    locked_by = models.ForeignKey()#Point me to your user model

    def lock(self):
        if self.is_locked(): #and code here to see if current user is not locked_by user
            #exception / bad return value here
            pass

        self.lock_time = datetime.now()

    def unlock(self):
        self.lock_time = None

    def is_locked(self):
        return self.lock_time and datetime.now() - self.lock_time < timedelta(minutes=10)

rawDescription: Setting a timeout function in django

description: Setting a timeout function in django


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

x,y = np.random.rand(2,10)
img = np.random.rand(10,10)

fig = plt.figure()
ax1 = fig.add_subplot(221)
im = ax1.imshow(img,extent=[0,1,0,1])

plt.colorbar(im)
ax2 = fig.add_subplot(222)
im = ax2.imshow(img,extent=[0,1,0,1])
plt.colorbar(im)

ax3 = fig.add_subplot(223)
ax3.plot(x,y)
ax3.axis([0,1,0,1])

ax4 = fig.add_subplot(224)
im = ax4.imshow(img,extent=[0,1,0,1])
plt.colorbar(im)

pos4 = ax4.get_position().bounds
pos1 = ax1.get_position().bounds
# set the x limits (left and right) to first axes limits
# set the y limits (bottom and top) to the last axes limits
newpos = [pos1[0],pos4[1],pos1[2],pos4[3]]

ax3.set_position(newpos)

plt.show()

rawDescription: changing size of a plot in a subplot figure

description: Changing size of a plot in a subplot figure


code:
nmaj = 10
cmd = 'zenity --question --text="Are you {} years old ?"'.format(nmaj)
subprocess.call(cmd, shell=True)

rawDescription: Python using zenity with var

description: Python using zenity with var


code:
reservation = conn.run_instances( ... )

# NOTE: this isn't ideal, and assumes you're reserving one instance. Use a for loop, ideally.
instance = reservation.instances[0]

# Check up on its status every so often
status = instance.update()
while status == 'pending':
    time.sleep(10)
    status = instance.update()

if status == 'running':
    instance.add_tag("Name","{{INSERT NAME}}")
else:
    print('Instance status: ' + status)
    return None

# Now that the status is running, it's not yet launched. The only way to tell if it's fully up is to try to SSH in.
if status == "running":
    retry = True
    while retry:
        try:
            # SSH into the box here. I personally use fabric
            retry = False
        except:
            time.sleep(10)

# If we've reached this point, the instance is up and running, and we can SSH and do as we will with it. Or, there never was an instance to begin with.

rawDescription: Boto EC2: Create an instance with tags

description: Boto EC2: Create an instance with tags


rawDescription: How can I convert a user-input binary value to ASCII characters in Python?

description: Convert a user-input binary value to ASCII characters in Python


code:
library = ...

good_songs = [ x for x in library if x['rating'] == '5' ]

rawDescription: Checking the value of a key in a dictionary within a list?


code:
def acc(r,m,eps):
    a = np.zeros((len(r),3))
    for i in range(len(r))[:-1]:
        for j in range(len(r))[i+1:]:
            ra2 = ((r[i,:]-r[j,:])**2).sum()
            f= -(r[i,:]-r[j,:])*m[j]/(ra2**1.5)
            a[i,:] += f
            a[j,:] += -f
    return a # return acceleration

rawDescription: How to account for the antisymmetric nature of the gravitational force in a simulation of N gravitational bodies

description: Account for the antisymmetric nature of the gravitational force in a simulation of N gravitational bodies


code:
import wx
import wx.grid as gridlib
class MyGrid(gridlib.Grid):
    def __init__(self, parent):
        """Constructor"""
        gridlib.Grid.__init__(self, parent)
        self.CreateGrid(2, 3)

class MyForm(wx.Frame):
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, parent=None, title="An Eventful Grid",size=(700,700))
        p = wx.Panel(self)

        button2 = wx.Button(p, -1, label="click me")
        st = wx.StaticText(p, -1,"Right-click on the panel to show a popup menu")
        p2 = wx.Panel(p, size=(400,200))
        p2.SetBackgroundColour((100, 0, 0))
        myGrid = MyGrid(p)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(button2)
        sizer.Add(st)
        sizer.Add(myGrid, 1, wx.EXPAND)#,pos=(200,200)
        sizer.Add(p2, 2, wx.EXPAND)
        p.SetSizer(sizer)

if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = MyForm().Show()
    app.MainLoop()

rawDescription: I don't how know to set panels + grid in a frames with wxpython


code:
def your_funcion(parameter_you_need):
    ...

def main():
    ...
    your_function(options.what_you_need_in_function)
    ...

rawDescription: optparse main function, how to use the options inside

description: Optparse main function, how to use the options inside


code: x= math.floor(x)

rawDescription: Keeping track of points in a grid

description: Keeping track of points in a grid


code: len(xrange(start, stop, step))

rawDescription: Pre-compute len(range(start, stop,step) )


code:
import os

def delete_file(name):
    os.remove(name)

import atexit
atexit.register(delete_file, file_path)

rawDescription: Trigger code on program termination

description: Trigger code on program termination


code:
class MainWindow(wx.Frame):
    def __init__(self, title):
        wx.Frame.__init__(self, None, title=title, pos=(150,150), size=(350,200))
        self.Bind(wx.EVT_CLOSE, self.OnClose)

    def OnClose(self, event):
        self.Destroy() # or simply do sys.exit(1) here
if __name__ == "__main__":
    app = wx.App(False)
    frame = MainWindow("MyApp")
    frame.Show()
    app.MainLoop()
sys.exit(1)

rawDescription: How to terminate python.exe*32 process when I exit my application?

description: Terminate python.exe*32 process when I exit my application


code:
# importing numpy as np and
# assign a ndarray to x
ind = np.nonzero(x)[-k:]

rawDescription: MATLAB find function translate to python - 3 input arguments version


code:
from google.appengine.ext import blobstore
from google.appengine.api import files

def iter_blobstore(blob, fetch_size=524288):
  start_index = 0
  end_index = fetch_size

  while True:
    read = blobstore.fetch_data(blob, start_index, end_index)

    if read == "":
      break

    start_index += fetch_size
    end_index += fetch_size

    yield read

PATH = '/gs/backupbucket/'
for df in DocumentFile.all():
  fn = df.blob.filename
  br = blobstore.BlobReader(df.blob)
  write_path = files.gs.create(self.PATH+fn.encode('utf-8'), mime_type='application/zip',acl='project-private')
  with files.open(write_path, 'a') as fp:
    for buf in iter_blobstore(df.blob):
      try:
        fp.write(buf)
      except files.FileNotOpenedError:
        pass
  files.finalize(write_path)

rawDescription: Google App Engine: How to write large files to Google Cloud Storage


code:
# This example taken from http://docs.python.org/library/optparse.html#generating-help
parser.add_option("-m", "--mode",
                  default="intermediate",
                  help="interaction mode: novice, intermediate, "
                       "or expert [default: %default]")

rawDescription: Can Python's optparse display the default value of an option?


code:
import unittest

class TestFileDialog(unittest.TestCase):

    def test_dialog_closed(self):
        filename = ''
        # ...

    def test_incorrect_extension(self):
        filename = '/path/to/another/filetype'
        # ...

    def test_csv_extension(self):
        filename = '/path/to/correct/file.csv'
        # ...

rawDescription: Unittest Tkinter File Dialog

description: Unittest Tkinter File Dialog


code:
# content is a str that stores the content of the link
query = urllib.parse.parse_qs(content)

fullurls = query['url_encoded_fmt_stream_map'][0].split(',')
data = [urllib.parse.parse_qs(i) for i in fullurls]
print(data)

rawDescription: Regular expression to split a huge string into multiple sets of key-value pairs


code:
import csv

if __name__ == '__main__':
    file_path = r"/your/file/path/here.csv"
    file_handle = open(file_path, "r")
    csv_handle = csv.reader(file_handle)
    # Now you can work with the *values* in the csv file.

rawDescription: Custom Python CSV delimiter

description: Custom Python CSV delimiter


code:
def test_overlap(dt1_st, dt1_end, dt2_st, dt2_end):
    return not (dt1_st < dt2_end and dt1_end >dt2_st)

rawDescription: Find if dates are overlapping in a list of N pairs


code:
from osax import *
import time
sa = OSAX()
for i in range(50):
  sa.set_volume(i*2)
  time.sleep(1)

rawDescription: Adjust OSX System Audio Volume in Python


code:
class Singleton(type):
    def __init__(self, name, bases, mmbs):
        super(Singleton, self).__init__(name, bases, mmbs)
        self._instance = super(Singleton, self).__call__()

    def __call__(self, *args, **kw):
        return self._instance

class Test(metaclass = Singleton):
    # __metaclass__ = Singleton # in python 2.7
    def __init__(self, *args, **kw):
        print("Only ever called once")

rawDescription: Why Singleton in python calls __init__ multiple times and how to avoid it?


code:
a1 = 270.00  # This is the price they buy the item in $

c2 = 3.50  # This is the shipping Price in $
c3 = 0.10  # This is the FEE of the store in percentage (10%)
c4 = 0.03  # This is the FEE for the credit card (0.3%)
c5 = 0.35  # This is the Fixed FEE for the store $0.35

d1 = 5.00  # This is the amount they want to earn when they sell the item in $
x = 0.00  # This is the final price they need to sell the item for earn d1

while True:
    # Assumed Formula - this may need to be adjusted to match your criteria
    earnt_amount = ((x - a1 - c2) * (1 - c3 - c4)) - c5
    x += 0.01
    if earnt_amount >= d1:
        break

print ('Price "x" should be: {0}'.format(x))

rawDescription: equivalent of Excel Goal Seek function in Python or MYSQL

description: Equivalent of Excel Goal Seek function in Python or MYSQL


code:
for alb in l.songs:
   if alb.album not in song_database:
       song_database[alb.album] = [alb.name]
   else:
       song_database[alb.album].append(alb.name)

rawDescription: How to build a python dictionary in a loop?

description: Build a python dictionary in a loop


code:
def scan(ipnet, port):
    node_list = []
    for x in range(1,255):
        ip = '{0}.{1}'.format(ipnet, x)

        t = Thread(target=probe, args=(ip, port))
        t.start()

    return node_list

rawDescription: Python module reusing the same object

description: Python module reusing the same object


code:
file = open('IntegerArray.txt','r')
integerArray = []
for line in file.readlines():
    integerArray.append(int(line.strip()))

rawDescription: Merge Sort does not work on large data set


code:
for g, df in test.groupby(np.arange(len(test)) // 400):
    print(df.shape)
# (400, 2)
# (400, 2)
# (311, 2)

rawDescription: Split dataframe into relatively even chunks according to length


code:
import matplotlib.pyplot as plt
import matplotlib.dates as md
import datetime as dt
import numpy as np

np.random.seed(0)
t=md.drange(dt.datetime(2009,10,1),
            dt.datetime(2010,1,15),
            dt.timedelta(days=1))
n=len(t)
x1 = np.cumsum(np.random.random(n) - 0.5) * 40000
x2 = np.cumsum(np.random.random(n) - 0.5) * 0.002

fig = plt.figure()
# fig.autofmt_xdate(rotation=25) # does not work
ax1 = fig.add_subplot(1,1,1)
fig.autofmt_xdate(rotation=25) # works
ax2 = ax1.twinx()
# fig.autofmt_xdate(rotation=25) # does not work
ax1.plot_date(t, x1, 'r-')
ax2.plot_date(t, x2, 'g-')
plt.show()

rawDescription: How to rotate the xlabels while adding another yaxis?

description: Rotate the xlabels while adding another yaxis


code:
for button in btnList:
    button.configure(state='disabled')

rawDescription: How to change the attributes for all objects inside a list in python(3)?

description: Change the attributes for all objects inside a list in python(3)


code:
class File(object):
   # ... all the methods you already have ...

   # context management
   def __enter__(self):
       return self
   def __exit__(self, *exc_info):
       self.close()

rawDescription: How to use Python closing context manager

description: Use Python closing context manager


code:
l = ["TimeStampfromlist","Firstnamefromlist","Secondnamefromlist"]

with open("in.csv", 'r') as data_file:
    lines = data_file.readlines()
    lines[0]= ":".join(l)+"\n" # replace first line, the "header" with list contents
    with open("in.csv", 'w') as out_data:
        for line in lines: # write updated lines
            out_data.write(line)

rawDescription: Replace first row in Python with list

description: Replace first row in Python with list


code:
# upper left corner of the visible region
x0 = self.canvas.canvasx(0)
y0 = self.canvas.canvasy(0)

# given a canvas coordinate cx/cy, convert it to window coordinates:
wx0 = cx-x0
wy0 = cy-y0

rawDescription: Python Tkinter convert canvas coordinate to window coordinate


code:
from lxml import etree

tree = etree.parse('books.xml')

new_entry = etree.fromstring('''<book category="web" cover="paperback">
<title lang="en">Learning XML 2</title>
<author>Erik Ray</author>
<year>2006</year>
<price>49.95</price>
</book>''')

root = tree.getroot()

root.append(new_entry)

f = open('books-mod.xml', 'w')
f.write(etree.tostring(root, pretty_print=True))
f.close()

rawDescription: How to update XML file with lxml

description: Update XML file with lxml


code:
import math

def dotproduct(v1, v2):
  return sum((a*b) for a, b in zip(v1, v2))

def length(v):
  return math.sqrt(dotproduct(v, v))

def angle(v1, v2):
  return math.acos(dotproduct(v1, v2) / (length(v1) * length(v2)))

rawDescription: Angles between two n-dimensional vectors in Python


code:
df1.set_index("id", inplace=True)
df2.set_index("id", inplace=True)
df3 = df1.merge(df2.ix[:,df2.columns-df1.columns], left_index=True, right_index=True, how="outer")

rawDescription: pandas combine_first with particular index columns?

description: Pandas combine_first with particular index columns


code:
import re

star_match = re.compile('from\s(?P<module>[\.\w]+)\simport\s[*]')
now = str(time.time())
error = lambda x: sys.stderr.write(x + '\n')

def replace_imports(lines):
    """
    Iterates through lines in a Python file, looks for 'from module import *'
    statements, and attempts to fix them.
    """
    for line_num, line in enumerate(lines):
        match = star_match.search(line)
        if match:
            newline = import_generator(match.groupdict()['module'])
            if newline:
                lines[line_num] = newline
    return lines

def import_generator(modulename):
    try:
        prop_depth = modulename.split('.')[1:]
        namespace = __import__(modulename)
        for prop in prop_depth:
            namespace = getattr(namespace, prop)
    except ImportError:
        error("Couldn't import module '%s'!" % modulename)
        return
    directory = [ name for name in dir(namespace) if not name.startswith('_') ]
    return "from %s import %s\n"% (modulename, ', '.join(directory))

rawDescription: Reversing from module import *

description: Reversing from module import *


code:
if __name__ == "__main__":
    prime = True
    for i in range(2, 1000):
        for x in range(2, i):
            if i % x == 0:
                prime = False
        if prime:
            print(i)
        prime = True

rawDescription: Writing an algorithm to generate prime numbers in Python within a given range


code:
class Foo:
     def bar(self):
         print('correctly called')

     def baz(self):
         self.bar() # <-- ()

rawDescription: unable to call member function in class python

description: Unable to call member function in class python


code:
@memoized
def search(a, b):
    # Initialize startup variables.
    nodes, index = [], []
    a_size, b_size = len(a), len(b)
    # Begin to slice the sequences.
    for size in range(min(a_size, b_size), 0, -1):
        for a_addr in range(a_size - size + 1):
            # Slice "a" at address and end.
            a_term = a_addr + size
            a_root = list(a)[a_addr:a_term] #change to list
            for b_addr in range(b_size - size + 1):
                # Slice "b" at address and end.
                b_term = b_addr + size
                b_root = list(b)[b_addr:b_term] #change to list
                # Find out if slices are equal.
                if a_root == b_root:
                    # Create prefix tree to search.
                    a_pref, b_pref = list(a)[:a_addr], list(b)[:b_addr]
                    p_tree = search(a_pref, b_pref)
                    # Create suffix tree to search.
                    a_suff, b_suff = list(a)[a_term:], list(b)[b_term:]
                    s_tree = search(a_suff, b_suff)
                    # Make completed slice objects.
                    a_slic = Slice(a_pref, a_root, a_suff)
                    b_slic = Slice(b_pref, b_root, b_suff)
                    # Finish the match calculation.
                    value = size + p_tree.value + s_tree.value
                    match = Match(a_slic, b_slic, p_tree, s_tree, value)
                    # Append results to tree lists.
                    nodes.append(match)
                    index.append(value)
        # Return largest matches found.
        if nodes:
            return Tree(nodes, index, max(index))
    # Give caller null tree object.
    return Tree(nodes, index, 0)

rawDescription: How can memoization be applied to this algorithm?


code:
def MakeBitmap2(self, red, green, blue, alpha=128):
    # Make an array of bytes that is DIM*DIM in size, with enough
    # slots for each pixel to have a RGB and A value
    #arr = makeByteArray( (DIM,DIM, 4) )
    arr = numpy.empty((DIM,DIM, 4), numpy.uint8)

    # just some indexes to keep track of which byte is which
    R, G, B, A = range(4)

    # initialize all pixel values to the values passed in
    arr[:,:,R] = red
    arr[:,:,G] = green
    arr[:,:,B] = blue
    arr[:,:,A] = alpha

    # Set the alpha for the border pixels to be fully opaque
    arr[0,     0:DIM, A] = wx.ALPHA_OPAQUE  # first row
    arr[DIM-1, 0:DIM, A] = wx.ALPHA_OPAQUE  # last row
    arr[0:DIM, 0,     A] = wx.ALPHA_OPAQUE  # first col
    arr[0:DIM, DIM-1, A] = wx.ALPHA_OPAQUE  # last col

    # finally, use the array to create a bitmap
    bmp = wx.BitmapFromBufferRGBA(DIM, DIM, arr)
    return bmp

rawDescription: wxPython, creating bit map

description: WxPython, creating bit map


code:
import os
os.system("pdflatex filename")

rawDescription: Generate TeX/LaTeX file and compile both in Python


code:
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By

driver = WebDriver("path_to_webdriver")
driver.get("http://jsfiddle.net/ksftLk9j/")

wait = WebDriverWait(driver, 20, 2)
wait.until(expected_conditions.frame_to_be_available_and_switch_to_it((By.NAME, 'result')))

element = driver.find_element_by_xpath('//select[@class="gwt-ListBox marginbelow"]/option[@value="Address"]')
element.click()

rawDescription: I am trying to get the XPath for a drop down


code:
denominator = 8
rnd = round(answer * denominator)
frac = Fraction(int(rnd), denonimator)

rawDescription: Less accurate fractions when rounding in Python 2.7


code:
from PyQt4 import QtGui, QtCore

class LineEdit(QtGui.QLineEdit):
    def __init__(self, strings, parent):
        QtGui.QLineEdit.__init__(self, parent)
        self.setCompleter(QtGui.QCompleter(strings, self))

    def focusInEvent(self, event):
        QtGui.QLineEdit.focusInEvent(self, event)
        self.completer().complete()

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        strings = 'one two three four five six seven eight'.split()
        self.edit1 = LineEdit(strings, self)
        self.edit2 = LineEdit(strings, self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.edit1)
        layout.addWidget(self.edit2)

if __name__ == '__main__':

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

rawDescription: AutoCompletion pops up on focusIn but cannot set text in QLineEdit from selection


code:
for comment in comments:
    for comment_user in comment_users:
        if comment_user['_id'] == comment['created_by']:
            comment.user_display_name = comment_user['display_name']
            break

rawDescription: How to set a variable outside of a loop in python

description: Set a variable outside of a loop in python


code:
def transpose(strlist):
    # create an empty list to use as a result
    result = []
    # loop through every element in the input list
    for i in range(len(strlist)):
        # loop through each character in the string
        for j in range(len(strlist[i])):
            # 2 cases to deal with here:
            if len(result) > j:
                # case 1: the result list has a string at the correct index,
                # just add this character to the end of that string
                result[j] = result[j] + strlist[i][j]
            else:
                # case 2: the result list doesn't have enough elements,
                # need to create a new element to store this character
                result.append(strlist[i][j])
    return result

print(transpose(['transpose', '', 'list', 'of', 'strings']))

rawDescription: Adding items to a list by checking if the index exists, and then updating


code:
import wx.lib.agw.ultimatelistctrl as ulc

class MyFrame1 ( wx.Frame ):
    def __init__( self, parent ):
        ...
        self.m_listCtrl9 = ulc.UltimateListCtrl( self.m_panel2, agwStyle=wx.LC_REPORT|ulc.ULC_HAS_VARIABLE_ROW_HEIGHT)
        ...
        self.color_pickers = []
        for i in range(20):
            idx = self.m_listCtrl9.InsertStringItem(0, "212343" + str(i))
            color_picker = wx.ColourPickerCtrl(self.m_listCtrl9, -1)
            self.m_listCtrl9.SetItemWindow(idx, 2, color_picker)
            self.color_pickers.append(color_picker)

rawDescription: ColourPickerCtrl in a ListCtrl

description: ColourPickerCtrl in a ListCtrl


code:
from project import app, db, security, user_datastore
from project.models import User
from flask.ext.security.confirmable import generate_confirmation_link
from flask.ext.security.utils import do_flash, get_message, config_value, send_mail, encrypt_password
from flask.ext.security.signals import user_registered
from flask import current_app

def register_my_user(form, account_id):
    form_data = form.to_dict()
    form_data['password']=encrypt_password(form_data['password'])
    user = user_datastore.create_user(**form_data)
    user.account_id = account_id
    db.session.commit()
    confirmation_link, token = generate_confirmation_link(user)
    do_flash(*get_message('CONFIRM_REGISTRATION', email=user.email))
    user_registered.send(current_app._get_current_object(),
                     user=user, confirm_token=token)
    if config_value('SEND_REGISTER_EMAIL'):
        send_mail(config_value('EMAIL_SUBJECT_REGISTER'), user.email, 'welcome',
              user=user, confirmation_link=confirmation_link)

rawDescription: Error extending RegisterForm in flask-security


code: vars()['lot%d' % someInt]

rawDescription: Set variables from variables?

description: Set variables from variables


code:
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
   }
}

rawDescription: how to disable cache for development in django?

description: Disable cache for development in django


code:
class Prepender:

    def __init__(self, fname, mode='w'):
        self.__write_queue = []
        self.__f = open(fname, mode)

    def write(self, s):
        self.__write_queue.insert(0, s)

    def close(self):
        self.__exit__(None, None, None)

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        if self.__write_queue:
            self.__f.writelines(self.__write_queue)
        self.__f.close()

with Prepender('test_d.out') as f:
    f.write('string 1\n')
    f.write('string 2\n')
    f.write('string 3\n')

rawDescription: Python f.write() at beginning of file?

description: Python f.write() at beginning of file


code:
THREE_CHOICES = 'ABC'
FOUR_CHOICES = 'ABCD'
FIVE_CHOICES = 'ABCDE'

import random

def generate_answers(n):
    '''Generates random answers from number inputted '''
    answerList = ""
    for i in range(0,n):
        answerList += random.choice(FOUR_CHOICES)
    return answerList

rawDescription: Printing out a random string (Python)

description: Printing out a random string (Python)


code:
from tkinter import *

from PIL import Image, ImageTk

root = Tk()
root.title("Title")
root.geometry("600x600")
root.configure(background="black")

class Example(Frame):
    def __init__(self, master, *pargs):
        Frame.__init__(self, master, *pargs)

        self.image = Image.open("./resource/Background.gif")
        self.img_copy= self.image.copy()

        self.background_image = ImageTk.PhotoImage(self.image)

        self.background = Label(self, image=self.background_image)
        self.background.pack(fill=BOTH, expand=YES)
        self.background.bind('<Configure>', self._resize_image)

    def _resize_image(self,event):

        new_width = event.width
        new_height = event.height

        self.image = self.img_copy.resize((new_width, new_height))

        self.background_image = ImageTk.PhotoImage(self.image)
        self.background.configure(image =  self.background_image)

e = Example(root)
e.pack(fill=BOTH, expand=YES)

root.mainloop()

rawDescription: Tkinter resize background image to window size (Python 3.4)


code:
import glob
import os.path

textfiles = glob.glob(os.path.join(rootdir, '*.txt'))
jsonfiles = glob.glob(os.path.join(rootdir, 'subdue', '*.json'))

rawDescription: Reading only the files in top directory in python


code:
import os
import sys
import optparse
def RName_Files():
    #Get the folder to user
    fol = raw_input("Please enter the folder whose files should have numbers stripped from their name: ") #I've never run past this point

    #Iterate through the files in the folder
    for f in os.listdir(fol):
        print("Current file is '" + f)

RName_Files()

rawDescription: Python 2.7.10 Prompt for user input

description: Python 2.7.10 Prompt for user input


code:
string = line.split(':')
print(string[0] + string[-1])

rawDescription: Python - Print last string after line.split


code:
sep_st = {0.0: [1.0, 'LBRG'], 0.26: [31.0, 'STIG']}
sep_dy = {0.61: [29.0, 'STIG'], 0.09: [25.0, 'STIG']}
sep = {"sep_st": sep_st, "sep_dy": sep_dy} # dict instead of list
for item in sep:
  for values in sorted(sep[item].keys()):
    p.write (str(item))
    p.write (str(values))
    p.write (str(sep[item][values]) +'\n')

rawDescription: Print list items - python

description: Print list items - python


code: pbpaste | python

rawDescription: How to run code contained in clipboard

description: Run code contained in clipboard


code:
def get_average(self):
    return sum(self.gradeBook, 0.0) / len(self.gradeBook)

rawDescription: Python get Average

description: Python get Average


code:
import ConfigParser

class MyParser(ConfigParser.ConfigParser):

    def as_dict(self):
        d = dict(self._sections)
        for k in d:
            d[k] = dict(self._defaults, **d[k])
            d[k].pop('__name__', None)
        return d

rawDescription: Read all the contents in ini file into dictionary with Python


code:
import subprocess

lst = ['12345','23456']
cmd = ['test.py', 'pick']
cmd.extend(lst)
subprocess.call(cmd)

rawDescription: Passing List Values as Parameters

description: Passing List Values as Parameters


code:
import tkinter as tk   # python3
#import Tkinter as tk   # python

TITLE_FONT = ("Helvetica", 18, "bold")

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page", font=TITLE_FONT)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",
                            command=lambda: controller.show_frame("PageOne"))
        button2 = tk.Button(self, text="Go to Page Two",
                            command=lambda: controller.show_frame("PageTwo"))
        button1.pack()
        button2.pack()

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=TITLE_FONT)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()

class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 2", font=TITLE_FONT)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

rawDescription: Switch between two frames in tkinter

description: Switch between two frames in tkinter


code:
from matplotlib import pyplot
import numpy as np

def plot_stabilization_diagram(data):

    pyplot.figure(figsize=(8, 6), dpi=80)
    pyplot.subplot(1, 1, 1)

    yaxis = np.ones_like(data)

    for pos, row in enumerate(data):
        for pos2, item in enumerate(row):
            pyplot.plot(item, yaxis[pos2], 'o')

    pyplot.show()

def plot_stabilization_diagram_2(data):

    pyplot.figure(figsize=(8, 6), dpi=80)
    pyplot.subplot(1, 1, 1)

    for pos, row in enumerate(data):
        for pos2, item in enumerate(row):
            pyplot.plot(pos, item, 'o')

    pyplot.show()

model_order = [[],
           [1],
           [1.1],
           [1, 1.5],
           [1, 1.55, 3.5],
           [1.1, 1.45, 3.45, 3.5, 4.8]]

plot_stabilization_diagram(model_order)

rawDescription: How to plot a stabilization diagram?

description: Plot a stabilization diagram


code:
from Tkinter import *

def doDisable():
    b2.configure(state=DISABLED)

root = Tk()
b2 = Button(root, text="Disable button", command=doDisable)
b2.pack()
root.mainloop()

rawDescription: How to lock tkinter button after pressing on it

description: Lock tkinter button after pressing on it


code:
import matplotlib.pyplot as plt

class DataSet(object):
    def __init__(self, name, x_data, y_data, size, color):
        self.name = name
        self.x_data = x_data
        self.y_data = y_data
        self.size = size
        self.color = color

wood = DataSet('wood', [1,2,3,4], [5,7,4,1], 300, 'red')
glass = DataSet('glass', [0,2,0,4], [2,7,4,1], 100, 'blue')
paper = DataSet('paper', [1,7,3,6], [9,9,1,9], 500, '#a5a5a5')
plastic = DataSet('plastic', [3,2,5,5], [1,5,1,8], 700, 'yellow')

categories = [wood, glass, paper, plastic]
#Here we plot all the data:
for cat in categories:
    plt.scatter(cat.x_data, cat.y_data, s=cat.size , color=cat.color, label=cat.name)

plt.legend(loc='lower right', scatterpoints=1)
plt.show()

rawDescription: How do i color a plot using non-numerical values using matplotlib?

description: Color a plot using non-numerical values using matplotlib


code: np.unique(a, return_inverse=True)

rawDescription: Performing an indirect sort in numpy, preserving same indices for identical elements


code:
import itertools

def getxy(point): return point[:2]

sortedpoints = sorted(points, key=getxy)

results = []

for xy, g in itertools.groupby(sortedpoints, key=getxy):
  results.append(max(g, key=operator.itemgetter(2)))

rawDescription: Finding unique maximum values in a list using python


code:
attributes = ['pandas', 'tunas', 'cows']
choice = random.choice(attributes)
setattr(z, choice, getattr(z, choice) + 1)

rawDescription: Given a subset of attributes on a class instance, increment one randomly


code:
def app_lost_focus(self, event):
    if self.focus_get() != self.menu:
        self.destroy_menu(event)

rawDescription: Tk/Tkinter: Detect application lost focus


code:
for line in csv.reader(["each line is enclosed in double-quotes",
                        "Double quotes inside a \"double-quoted\" string!",
                        "This line contains backslashes \\not so cool\\",
                        "too many double-quotes in a line \"\"\"too much\"\"\"",
                        "too many backslashes \\\\\\\"horrible\"\\\\\\",
                        ]):
        print(line)

rawDescription: Unescape strings in Python

description: Unescape strings in Python