code:
verts = [(0.2, 0.0),
         (0.8, 0.0), # start of the lower right corner
         (1.0, 0.0), # intermediate point (as if it wasn't rounded)
         (1.0, 0.2), # end point of the lower right corner
         (1.0, 0.8), # move to the next point etc.
         (1.0, 1.0),
         (0.8, 1.0),
         (0.2, 1.0),
         (0.0, 1.0),
         (0.0, 0.8),
         (0.0, 0.2),
         (0.0, 0.0),
         (0.2, 0.0)]

codes = [mpath.Path.MOVETO,
         mpath.Path.LINETO,
         mpath.Path.CURVE3,
         mpath.Path.CURVE3,
         mpath.Path.LINETO,
         mpath.Path.CURVE3,
         mpath.Path.CURVE3,
         mpath.Path.LINETO,
         mpath.Path.CURVE3,
         mpath.Path.CURVE3,
         mpath.Path.LINETO,
         mpath.Path.CURVE3,
         mpath.Path.CURVE3]

rounded_verts = mpath.Path(verts, codes)

fig, ax = plt.subplots(subplot_kw={'aspect': 1.0, 'xlim': [-0.2,1.2], 'ylim': [-0.2,1.2]})

rounded_verts = patches.PathPatch(rounded_verts, facecolor='orange', lw=2)
ax.add_patch(rounded_verts)

rawDescription: matplotlib - radius in polygon edges - is it possible?

description: Matplotlib - radius in polygon edges - is it possible


code:
listOfSteps = [1, 4, 7, 10, 17, 22, 28, 29, 30, 43, 47, 50]
fileNameCreate = 0

it = iter(listOfSteps)

for a in it:
    b = next(it)
    c = next(it)

    session.viewports['Viewport: 1'].odbDisplay.setFrame(step=a, frame=-1)
    session.viewports['Viewport: 2'].odbDisplay.setFrame(step=b, frame=-1)
    session.viewports['Viewport: 3'].odbDisplay.setFrame(step=c, frame=-1)

    # ...

rawDescription: Loop in Python List using more than one item per loop


code:
reportPat=re.compile(
   r'(Clinical details|indication)(?:[:\s]*)?(.*)'
   r'(result|description|report)(?:[:\s]*)?(.*?)'
   r'(?:(Interpretation|conclusion)(?:[:\s]*)?(.*))?$',
   re.IGNORECASE|re.DOTALL)

rawDescription: Python regex string groups capture

description: Python regex string groups capture


code:
my_collection.find(
    {
        '_id.my_string': 'Foo',
        '_id.my_time' :
        {
            '$gte': datetime.datetime(...),
            '$lte': datetime.datetime(...)
        }
    }
    )

rawDescription: Query compound _id for time range in MongoDB using PyMongo


code:
import mimetypes
import os
import urllib2
import urlparse

def filename_from_url(url):
    return os.path.basename(urlparse.urlsplit(url)[2])

def download_file(url):
    """Create an urllib2 request and return the request plus some useful info"""
    name = filename_from_url(url)
    r = urllib2.urlopen(urllib2.Request(url))
    info = r.info()
    if 'Content-Disposition' in info:
        # If the response has Content-Disposition, we take filename from it
        name = info['Content-Disposition'].split('filename=')[1]
        if name[0] == '"' or name[0] == "'":
            name = name[1:-1]
    elif r.geturl() != url:
        # if we were redirected, take the filename from the final url
        name = filename_from_url(r.geturl())
    content_type = None
    if 'Content-Type' in info:
        content_type = info['Content-Type'].split(';')[0]
    # Try to guess missing info
    if not name and not content_type:
        name = 'unknown'
    elif not name:
        name = 'unknown' + mimetypes.guess_extension(content_type) or ''
    elif not content_type:
        content_type = mimetypes.guess_type(name)[0]
    return r, name, content_type

rawDescription: How to download file from ftp?

description: Download file from ftp


code:
import io
data = io.BytesIO(urllib.urlopen(URL).read())

rawDescription: Blender material from URL

description: Blender material from URL


code:
from multiprocessing.pool import ThreadPool
pool = ThreadPool(10)
all(pool.map(foo, l))

rawDescription: Python: parallelizing any/all statements


code: np.all([np.arange(3), np.arange(3)])

rawDescription: matplotlib.pyplot vs matplotlib.pylab

description: Matplotlib.pyplot vs matplotlib.pylab


code:
import boto3

s3_client = boto3.client('s3')
for obj in gcs:
    s3_client.put_object(Bucket='bucket-name', Key=gcs.key, Body=gcs.body)

rawDescription: copy file from gcs to s3 in boto3

description: Copy file from gcs to s3 in boto3


code:
re.match(r'^(?!.*\bo?clock\b).*\btimes\b', a)
re.match(r'^(?!.*\bo?clock\b).*\btimes\b', b)

rawDescription: regex contains "times" but not "clock"

description: Regex contains "times" but not "clock"


code:
buckets = np.where(
    tobebuckets <= 0, 0,
    np.where(
        np.logical_and(tobebuckets > 0, tobebuckets <= 10), 10,
        np.where(
            np.logical_and(tobebuckets > 10,tobebuckets <= 50), 50,
            np.where(
                np.logical_and(tobebuckets > 50, tobebuckets <= 100), 100,
                np.where(
                    np.logical_and(tobebuckets > 100, tobebuckets <= 500), 500,
                    np.where(
                        np.logical_and(tobebuckets > 500, tobebuckets <= 1000),
                        1000, 1001))))))

rawDescription: how to make long line as pep8 compatible in python?

description: Make long line as pep8 compatible in python


code:
def start_requests(self):
    for url in self.start_urls:
        yield self.make_requests_from_url(url)

def make_requests_from_url(self, url):
    return Request(url, dont_filter=True)

rawDescription: the order of Scrapy Crawling URLs with long start_urls list and urls yiels from spider

description: The order of Scrapy Crawling URLs with long start_urls list and urls yiels from spider


code:
from django.contrib.admin.models import LogEntry
def dashboard_view(request):
    log = LogEntry.objects.select_related().all().order_by("id")
    return render_to_response("app_name/dashboard.html", {'log': log},)

rawDescription: Showing Django Admin actions on template


code:
os.popen(' '.join([
    self._ghostscriptPath,
   'gswin32c',
   '-q',
   '-dNOPAUSE',
   '-dBATCH',
   '-sDEVICE=tiffg4',
   '-r196X204',
   '-sPAPERSIZE=a4',
   '-sOutputFile="%s %s"' % (tifDest, pdfSource),
]))

rawDescription: What is the best way on python 2.3 for windows to execute a program like ghostscript with multiple arguments and spaces in paths?


code:
fig = plt.figure()
ax = fig.addsubplot(111)
for mol in mols:
    for energy, density in data:
        ax.cla() # or ax.clear()
        ax.plot(density, energy, 'ro')

        ax.set_xlabel(...)
        ax.set_ylabel(...)
        [a.label.set_color('black') for a in (ax.xaxis, ax.yaxis)]
        # more spines and axis tinkering

        fig.savefig(mol+".png")

rawDescription: Looping over data and creating individual figures


code: wealth = pos.shift() * (1+returns).cumprod(axis=0)

rawDescription: Python Pandas Dataframe: portfolio backtesting investing cashflows on different dates


rawDescription: Loop through dictionary with a math function


rawDescription: How to correctly read csv in Pandas while changing the names of the columns

description: Correctly read csv in Pandas while changing the names of the columns


code:
from wtforms import TextField, validators, PasswordField, TextAreaField, HiddenField
class ArticleCreateForm(Form):
        title = TextField('Title', [validators.Required("Please enter title.")],
                          filters=[strip_filter] )
        body = TextAreaField('Body', [validators.Required("Please enter body.")],
                             filters=[strip_filter])
        category = QuerySelectField('Category', query_factory=category_choice )
        person_name = HiddenField()

rawDescription: How to use hidden input in an html form with Python+Jinja2

description: Use hidden input in an html form with Python+Jinja2


code: data = "hashable=test".encode("ascii")

rawDescription: Simple POST using urllib with Python 3.3


rawDescription: Sympy factoring in Python

description: Sympy factoring in Python


code:
class OfficeSerializer(serializers.ModelSerializer):
    country = serializers.Field(source='country.iso') # this field of the serializer
                                                      # is read-only

rawDescription: Django REST Framework: create and update an object with a nested object value (instead of Primary Key)


code:
from django.contrib import admin
import django.contrib.admin.widgets

from django.db import models

from .models import Cliente, Prodotto, Sede
from apps.recapito.models import RecapitoCliente
from .widgets import NoAddingRelatedFieldWidgetWrapper

class SedeInline(admin.TabularInline):
    model = Sede
    extra = 1

    def provincia(self, obj):
        return obj.comune.provincia

    readonly_fields = ['provincia', ]

class RecapitoInline(admin.TabularInline):
    model = RecapitoCliente
    extra = 1
    readonly_fields = ['cliente', 'tipo', 'recapito', ]

@admin.register(Cliente)
class ClienteAdmin(admin.ModelAdmin):
    list_display = [
        'ragione_sociale', 'forma_societaria', 'titolare', 'partita_iva', ]
    list_filter = ['forma_societaria', ]
    search_fields = ['ragione_sociale', ]
    inlines = [RecapitoInline, SedeInline]
    def get_form(self, request, obj=None, **kwargs):
        form = super(ClienteAdmin, self).get_form(request, obj, **kwargs)
        form.base_fields['prodotto'].widget.can_add_related = False
        return form

rawDescription: Django 1.7 removing Add button from inline form


code:
from collections import defaultdict
from itertools import chain
d=defaultdict(list)
for k,v in zip(chain(*list1),chain(*list2)):
    d[k].append(v)

[(k,sum(v)) for k,v in d.items()]

rawDescription: Reorganise list in list python

description: Reorganise list in list python


code:
imageFile = open('imageFile.png','rb')
imageData = imageFile.read()
mimeType = 'image/png'
binaryParam = (imageData, uuid.uuid4(), mimeType)

rawDescription: How to send a file through Soap in python?

description: Send a file through Soap in python


code:
import kivy
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.app import App

class InterfaceManager(BoxLayout):

    def __init__(self, **kwargs):
        super(InterfaceManager, self).__init__(**kwargs)

        self.first = Button(text="First")
        self.first.bind(on_press=self.show_second)

        self.second = Button(text="Second")
        self.second.bind(on_press=self.show_final)

        self.final = Label(text="Hello World")
        self.add_widget(self.first)

    def show_second(self, button):
        self.clear_widgets()
        self.add_widget(self.second)

    def show_final(self, button):
        self.clear_widgets()
        self.add_widget(self.final)

class MyApp(App):
    def build(self):
        return InterfaceManager(orientation='vertical')

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

rawDescription: Switching kivy widgets

description: Switching kivy widgets


code:
import csv
import shutil
from tempfile import NamedTemporaryFile

TRIAL = 0
IMAGE = 1
KEYPRESS = 4
filename = 'backsorting.csv'
img_resp_map = {}

# first pass
with open(filename, 'rb') as csvfile:
    reader = csv.reader(csvfile)

    # skip over first block
    next(reader)  # header
    while True:
        row = next(reader)
        if not row[TRIAL].isdigit():  # header of second block?
            break

    # use data in second block to create an image-to-response mapping
    for row in reader:
        img_resp_map[row[IMAGE]] = row[KEYPRESS]

# second pass
with open(filename, 'rb') as csvfile:
    reader = csv.reader(csvfile)
    fields = next(reader)  # get header of first block
    with NamedTemporaryFile('wb', dir='.', delete=False) as tempcsv:
        writer = csv.writer(tempcsv)
        writer.writerow(fields + ['Keypress'])  # new header with added field

        # copy and update rows of first block by appending the new field
        for row in reader:
            if not row[TRIAL].isdigit():  # header of second block?
                break
            writer.writerow(row+[img_resp_map[row[IMAGE]]])

        # copy second block of file unchanged
        writer.writerow(row)  # header (already read)
        writer.writerows(reader)

    # NOTE: the following is dangerous since it wipes out the original file
    shutil.move(tempcsv.name, filename)  # replace original file with temp one

rawDescription: Backsorting initial CSV values based on later CSV values (Python preferred)


rawDescription: How to plot periodic data with matplotlib

description: Plot periodic data with matplotlib


code:
from five import grok
from zope.interface import Interface
from collective.zamqp.producer import Producer
from collective.zamqp.consumer import Consumer

class CreateItemProducer(Producer):
    """Produces item creation requests"""
    grok.name("amqpdemo.create")  # is also used as default routing key

    connection_id = "superuser"
    serializer = "msgpack"
    queue = "amqpdemo.create"

    durable = False

class ICreateItemMessage(Interface):
    """Marker interface for item creation message"""

class CreateItemConsumer(Consumer):
    """Consumes item creation messages"""
    grok.name("amqpdemo.create")  # is also used as the queue name

    connection_id = "superuser"
    marker = ICreateItemMessage

    durable = False

rawDescription: Using RabbitMQ with Plone - Celery or not?


rawDescription: loop over tree like structure

description: Loop over tree like structure


rawDescription: Filter out dictionary removing duplicates


code:
step_1 = zip(A,B) # creates list of tuples using
step_1
step_2 = sorted(step_1) # key step: the tuples are sorted by
step_2
step_3 = zip(*step_2)   # This is just a trick to get back the original
step_3

rawDescription: sorting the elements in the list

description: Sorting the elements in the list


code:
import re
s = "[greeting] Hello my friends [me] my name is John. [bow] nice to meet you."
re.findall(r'\[[\w\s.]+\]|[\w\s.]+', s)

rawDescription: Split string with delimiters in Python

description: Split string with delimiters in Python


code:
def days_in_month(year, month):
    """
    Return number of days in the specified month (28, 29, 30, or 31)
    """
    if month == 2:    # February
        if not (year % 400):
            return 29
        elif not (year % 100):
            return 28
        elif not (year % 4):
            return 29
        else:
            return 28
    elif month in {1, 3, 5, 7, 8, 10, 12}:
        return 31
    else:
        return 30

def days_in_year(year):
    """
    Return the number of days in the specified year (365 or 366)
    """
    return 337 + days_in_month(year, 2)

def days_this_year(year, month, day):
    """
    Return the number of days so far this year
    """
    return sum(days_in_month(year, m) for m in range(1, month)) + day

def year_days_since(base_year, this_year):
    """
    Return the number of days from the start of base_year to the start of this_year
    """
    if base_year > this_year:
        raise ValueError("base_year must be <= this_year")
    elif base_year == this_year:
        return 0
    else:
        return sum(days_in_year(y) for y in range(base_year, this_year))

rawDescription: Python difference between two dates

description: Python difference between two dates


code: a = numpy.random.randn(10, 2, 2)

rawDescription: Finding which array contributes the maximum value for classification


rawDescription: Parsing <geo:lat>, <geo:long> tags value using feedparser in python!


code:
# Python 3.x
from imp import reload
plotter = reload(plotter)

rawDescription: how to have one file work on objects generated by another in spyder

description: Have one file work on objects generated by another in spyder


rawDescription: Numpy Pure Functions for performance, caching


code:
import re

text = '''\
Anything above this first set of hyphens should not be captured.

---

This is content. It should be captured.
Any sets of three hyphens beyond this point should be ignored.
'''

pat = re.compile(r'(?ms)^---(.*)\Z')
print(re.search(pat, text).group(1))

rawDescription: Matching everything after series of hyphens


code: ['Hello', 'World', 'String 1', 'String 2', 'String 3', 'Sting 4', 'Hello', 'World', 'String 5', 'String 6', 'String 7', 'String 8', 'Hello', 'World', 'String 9', 'String 10', 'String 11', 'String 12']

rawDescription: Python Manipulating String

description: Python Manipulating String


code:
[u'15', u'Shot Rejected', u'29 - 25', u'Zalgiris Kaunas', u'HANLAN, OLIVIER']
[u'15', u'Block', u'29 - 25', u'Real Madrid', u'NOCIONI, ANDRES']
[u'15', u'Off Rebound', u'29 - 25', u'Zalgiris Kaunas', u' ']
[u'15', u'Two Pointer', u'31 - 25', u'Zalgiris Kaunas', u'VENE, SIIM-SANDER']
[u'15', u'Assist', u'31 - 25', u'Zalgiris Kaunas', u'RANDLE, JEROME']
[u'16', u'Minute', u'31 - 25', u' ', u' ']
[u'16', u'Three Pointer', u'31 - 28', u'Real Madrid', u'NOCIONI, ANDRES']
[u'16', u'Assist', u'31 - 28', u'Real Madrid', u'LLULL, SERGIO']
[u'16', u'Two Pointer', u'33 - 28', u'Zalgiris Kaunas', u'RANDLE, JEROME']
[u'16', u'Foul', u'33 - 28', u'Zalgiris Kaunas', u'SAJUS, MARTYNAS']
[u'16', u'Foul Drawn', u'33 - 28', u'Real Madrid', u'LLULL, SERGIO']
[u'16', u'Free Throw In', u'33 - 29', u'Real Madrid', u'LLULL, SERGIO']
[u'16', u'Free Throw In', u'33 - 30', u'Real Madrid', u'LLULL, SERGIO']
[u'16', u'In', u'33 - 30', u'Zalgiris Kaunas', u'JANKUNAS, PAULIUS']

rawDescription: How to handle an inconsistent markup using Scrapy selectors?

description: Handle an inconsistent markup using Scrapy selectors


code:
for path in nx.all_simple_paths(gr, source=2, target=0):
    print(path)
# prints
# [2, 1, 0]
# [2, 3, 0]

rawDescription: How to find the number of edges bewteen any two nodes using networkx?

description: Find the number of edges bewteen any two nodes using networkx


code: pd.isnull([NaN, 2, u'string', None])

rawDescription: Count NaNs when unicode values present

description: Count NaNs when unicode values present


code:
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
    api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
    api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))

rawDescription: Create an sqlite db and save it by means of python and flask


code:
profile = Profile.objects.only('idx').filter(full_name=full_name,
                                             birthday=birthday).first()
profile_idx = profile.idx if profile else None

rawDescription: Getting a single value from MySQL on Django (Python)


code: convert = {"tab1_name": "tab1", "tab2_name": "tab2", "tab3_name": "tab3"}

rawDescription: Convert string into a Tkinter notebook frame


code:
### START MAIN
# copy some rows from a source table to a destination table
# note that the destination table is empty when this script is run
cmd = 'mysql -u ve --skip-column-names --batch --execute="insert into destination (select * from source limit 100000)" test'
subprocess.call(cmd)

# check to see how many rows exist in the destination table
cmd = 'mysql -u ve --skip-column-names --batch --execute="select count(*) from destination" test'
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
try: count = (int(process.communicate()[0][:-1]))
except: count = 0

rawDescription: Why is subprocess.Popen not waiting until the child process terminates?


code:
with open('result2.txt', 'w') as outf:
    outf.write('{0:12.5f}\n'.format(0.0))
    prev_item = 0;
    with open('data.txt') as inf:
        for i, item in enumerate(inf):
            item = float(item.strip())
            val = item - prev_item
            if i > 0:
                outf.write('{0:12.5f}\n'.format(val))
            prev_item = item

rawDescription: Difference of consecutive float numbers in a column


rawDescription: Grouping and aggregating by counts: how to keep column names?


code: element = parent.find('childtoFind')

rawDescription: Search for an XML node in a parent by string with python


code:
import argparse
class X(argparse.Namespace): pass
print(X(a=1, b=2))

rawDescription: Standard Python base class as a container for arbitrary attributes


rawDescription: MD5 hash discrepancy between Python and PHP?


code:
[[{u'member_amt_pledged': u'10.00',
   u'member_amt_recvd': None,
   u'member_id': u'1',
   u'name': u'Murray Hight'},
  {u'member_amt_pledged': u'10.00',
   u'member_amt_recvd': None,
   u'member_id': u'4',
   u'name': u'Martin Tunis'}]]

rawDescription: Retrieving items from a dictionary data type created from a JSON request


rawDescription: Reduce a list of 2-dicts, to a list unique by the one item, concatenating the other items in python3


code:
# -*- coding: utf-8 -*-
import re
import scrapy

class DmozItem(scrapy.Item):
    # define the fields for your item here like:
    link = scrapy.Field()
    attr = scrapy.Field()
    title = scrapy.Field()
    tag = scrapy.Field()

class DmozSpider(scrapy.Spider):
    name = "dmoz"
    allowed_domains = ["raleigh.craigslist.org"]
    start_urls = [
        "http://raleigh.craigslist.org/search/bab"
    ]

    BASE_URL = 'http://raleigh.craigslist.org/'

    def parse(self, response):
        links = response.xpath('//a[@class="hdrlnk"]/@href').extract()
        for link in links:
            absolute_url = self.BASE_URL + link
            yield scrapy.Request(absolute_url, callback=self.parse_attr)

    def parse_attr(self, response):
        match = re.search(r"(\w+)\.html", response.url)
        if match:
            item_id = match.group(1)
            url = self.BASE_URL + "reply/ral/bab/" + item_id

            item = DmozItem()
            item["link"] = response.url
            item["title"] = "".join(response.xpath("//span[@class='postingtitletext']//text()").extract())
            item["tag"] = "".join(response.xpath("//p[@class='attrgroup']/span/b/text()").extract())
            return scrapy.Request(url, meta={'item': item}, callback=self.parse_contact)

    def parse_contact(self, response):
        item = response.meta['item']
        item["attr"] = "".join(response.xpath("//div[@class='anonemail']//text()").extract())
        return item

rawDescription: Scrapy not collecting data

description: Scrapy not collecting data


rawDescription: Less repeating yourself for re.sub with lists


code:
from sphinx.ext.autodoc import ModuleLevelDocumenter, DataDocumenter

def add_directive_header(self, sig):
    ModuleLevelDocumenter.add_directive_header(self, sig)
    # Rest of original method ignored

DataDocumenter.add_directive_header = add_directive_header

rawDescription: Omit (or format) the value of a variable when documenting with Sphinx


rawDescription: Get HEAD revision number of SVN Repository with PYSVN


code:
import requests
from requests.auth import HTTPBasicAuth

requests.get('http://192.168.11.1/userRpm/AssignedIpAddrListRpm.html',
              auth=HTTPBasicAuth('admin', 'password'))

rawDescription: How to write python to fetch page information(user and password needed)

description: Write python to fetch page information(user and password needed)


code:
df = df.set_index(['date', 'colour'])
df

rawDescription: Re-index dataframe by new range of dates


code:
import numpy as np
from guiqwt.pyplot import *
figure("simple plot")
subplot(1, 2, 1)
plot(x, np.tanh(x+np.sin(12*x)), "g-", label="Tanh")
legend()
subplot(1, 2, 2)
plot(x, np.sinh(x), "r:", label="SinH")
show()

rawDescription: matplotlib figures are not displayed when one types imshow(img) in the command prompt in pdb mode

description: Matplotlib figures are not displayed when one types imshow(img) in the command prompt in pdb mode


code:
from bs4 import BeautifulSoup

data = """

"""

soup = BeautifulSoup(data)
print(soup.td['data-tooltip'])

rawDescription: Extract Text from HTML Python (BeautifulSoup, RE, Other Option?)


code:
import copy

my_variable = copy.copy(self.myinstance) # Shallow copy

rawDescription: Python: How to I unbind a variable from instance in a class?


code: sleepEvent = threading.Event()

rawDescription: Make a thread wait for either a Timer or a Signal?


code:
pyplot.locator_params(axis='y',nbins=6)#to specify number of ticks on both or any single axes
pyplot.locator_params(axis='x',nbins=10)

rawDescription: How to: reduce number of ticks with matplotlib


code:
np.set_printoptions(edgeitems=5,linewidth=80,precision=2,suppress=True,threshold=10)
a = np.arange(0,100.)

a
np.set_printoptions(edgeitems=5,linewidth=80,precision=2,suppress=True,threshold=100)
a

rawDescription: Output array after performing fast fast fourier transform of a data set


code:
import itertools

def get_labels(filename):
    index = 0
    with open(filename, 'rb') as f:
        sample = ''.join(x[0] for x in zip(itertools.ifilter(strip, f), range(4)))
        dialect = csv.Sniffer().sniff(sample)
        f.seek(0)
        reader = csv.reader(itertools.ifilter(strip, f), dialect)
        for row in reader:
            if 'TimeStamp (s)' not in row:
                index += 1
            else:
                return row, index + 1

rawDescription: skip blank lines with csv.reader

description: Skip blank lines with csv.reader


rawDescription: Using list comprehension to match values of dictionaries which are stored in lists


code:
import tkinter
import tkinter.filedialog
import getpass
gui = tkinter.Tk()
user = getpass.getuser()
button = tkinter.Button(gui, command=lambda: tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user))
button.grid()
gui.mainloop()

rawDescription: Program runs a button command on startup?


rawDescription: Python csvreader separate lines

description: Python csvreader separate lines


code:
import myhandler

if testing:
    myhandler.session_class = MyTestingSession

rawDescription: Dependency injection in (Python) Google App Engine


code:
class k(y):
  def __repr__(self):
    return 'k(%r)' % self.s.upper()
k1 = k.fromlist(['za','bu'])
k1

rawDescription: What does classmethod do in this code?

description: What does classmethod do in this code


code:
class Parent(object):
    """ This parent has all types of methods. """
    def _will_private_run_test(self):
        self.__private()

    def public(self):
        print('public', self.__class__)

    def _protected(self):
        print('protected', self.__class__)

    def __private(self):
        print('private', self.__class__)

class Child(Parent):
    """ This child only knows parent's methods. """
    pass

class ChildWithOverrides(Parent):
    """ This child overrides all. """
    def public(self):
        print('New', 'public', self.__class__)

    def _protected(self):
        print('New', 'protected', self.__class__)

    def __private(self):
        print('New', 'private', self.__class__)

def run_private(obj):
    if hasattr(obj, '__private'):
        print('A mirracle happened!')

    try:
        obj.__private()
    except AttributeError as ae:
        print(ae)

parent = Parent()
parent._will_private_run_test()

child = Child()
teen = ChildWithOverrides()

parent.public()
child.public()
teen.public()

parent._protected()
child._protected()
teen._protected()

run_private(parent)
run_private(child)
run_private(teen)

rawDescription: Python avoiding implementation method name clashes in subclass


code:
l = ['[A01]apple', '[A02]apple_sauce', '[A03]apple_juice', '[B01]banana', '[A02]banana_bread', '[A03]banana_ice']
[s for s in l if 'A%02d'%(int(s[2:4]) + 2) not in [t[1:4] for t in l]]

rawDescription: Python - Remove "tagged" item from list only if another item with greater "tag" exists


code: INPUT_FILTER = "perl filemod.pl"

rawDescription: Automatically Insert file-modification-time after @date command


code:
def copy_dir():
    dir_path = 'YOUR_DIR_HERE'
    base_dir = os.path.join('MODULE_DIR_HERE', dir_path)
    for (dirpath, dirnames, files) in os.walk(base_dir):
        for f in files:
            yield os.path.join(dirpath.split('/', 1)[1], f)

rawDescription: Copy an entire folder in a setup.py file


code: dict2 = {key: func(value) for key, value in dict1.itervalues()}

rawDescription: Mapping func over dictionary

description: Mapping func over dictionary


rawDescription: Python Image Library - Convert pixels to 2D list


code:
foo = dict(x=1, y=2)
bar = dict(y=2, x=1)
foo == bar

rawDescription: Does Python have anonymous classes?

description: Does Python have anonymous classes


code:
Chloe
attribute1
attribute2
attribute3

rawDescription: Python Splitting a file into many files and adding in extra info


rawDescription: Comparing two lists and inserting Nulls where necessary


code:
def myadd(xs,ys):
     return tuple(x + y for x, y in izip(xs, ys))

rawDescription: How to add with tuples

description: Add with tuples


code:
class Test(object):
       from functools import partial

Test().partial

rawDescription: Python, Django, using Import from inside of a class, can't seem to figure this out


code:
def Density_distribution(H0, Rh, r, z, rho0, Rc, Rd):
      return Density(rho0, r, Rc, Rd) * np.exp(-z / Thickness_H(H0, r, Rh))

rawDescription: define three functions into one in python

description: Define three functions into one in python


code:
x = np.arange(3)
y = np.arange(4)
x[..., None] * y[None, ...]

rawDescription: product of arrays of different sizes in numpy

description: Product of arrays of different sizes in numpy


code:
import numpy as np
a = np.array([[4,9,2],[5,1,3]])
idx = np.argsort(a[1])

rawDescription: 2D Sorting with NumPy - sort 1 row and have the other follow the sorting


rawDescription: Finding the difference between times in different columns through a CSV file


rawDescription: How to create multiple value dictionary from pandas data frame

description: Create multiple value dictionary from pandas data frame


code:
from itertools import ifilterfalse
somelist[:] = list(ifilterfalse(determine, somelist))

rawDescription: Remove items from a list while iterating in Python


rawDescription: Generating cyclic permutations / reduced Latin Squares in Python


code:
def func2(*args): #unpacking
   print(args)  #args is a tuple

func2(1,2)  #prints (1, 2)

rawDescription: Calling python function with an unknown number of arguments


code:
book = models.Book(title='Foo')
chapter = models.Chapter(parent=book, title='dummy')
form = forms.ChapterForm(request.POST, request.FILES, instance=chapter)

rawDescription: Set parent in a ModelForm in Google App Engine


code:
for i in range(2, l + 1):
    replace_index = ("//form[@id='SubAvailSelectForm']/"
                     "font/table[2]/tbody/tr[%d]/td[1]/small") % (i,)
    job_count_array[replace_index] = sel.get_text(replace_index)

rawDescription: How to gracefully break up a long string

description: Gracefully break up a long string


code:
given_dict = dict((j[0],j[1]+[given_list[i]]) for i,j in enumerate(given_dict.items()))
given_dict

rawDescription: Zipping items from a list with lists from an ordered dictionary in Python


code: actualSQL = "INSERT INTO %s (%s) VALUES(%s);"

rawDescription: How to handle apostrophes in MySQL-Python?

description: Handle apostrophes in MySQL-Python


code:
import sys

for line in sys.stdin:
    for j in range(int(line)):
        solve(*[int(i) for i in sys.stdin.next().split()])

rawDescription: Read n test cases from file in Python

description: Read n test cases from file in Python


code:
class Member(models.Model):
    name = models.CharField(max_length=100)
    dob = models.DateField()

class Group(models.Model):
    name = models.CharField(max_length=100)
    owner = models.ForeignKey('Member', related_name='owned_groups')
    members = models.ManyToManyField('Member', related_name='groups')

class Activity(models.Model):
    group = models.ForeignKey(Group)
    topic = models.CharField(max_length=100)
    start_by = models.ForeignKey('Member', related_name='started_activities')
    participants = models.ManyToManyField('Member', related_name='activities')

rawDescription: Django ModelForm Field Filtering with multiple model dependancies


rawDescription: Summation of every row, column and diagonal in a 3x3 matrix numpy


code:
list_of_dictionaries = [{random_key(): random_date()} for _ in range(5)]
list_of_dictionaries
min(list_of_dictionaries, key=lambda d: min(d.values()))

rawDescription: Python: file oldest date value in a list of objects


code: a = [name for name in os.listdir(".") if name.endswith(".txt")]

rawDescription: Getting Every File in a Directory, Python


code:
l = [1.3, 3, 3.4, 34.5, 3.2, 4, 5.6]

def find_fs(l, i, j):
    try:
        start, end = l.index(i), l.index(j)
        return sum(isinstance(ele, float) for ele in islice(l, start + 1, end))
    except IndexError:
        return 0
print(find_fs(l,3, 4))
3

rawDescription: python- finding total number of items of certain range in a list

description: Python- finding total number of items of certain range in a list


code:
import itertools
import math

# iterators
def ihstack(*matrixes):
    return map(lambda rows: itertools.chain(*rows), zip(*matrixes))

def ivstack(*matrixes):
    return itertools.chain(*matrixes)

# main function
def squarejoin(*matrixes):
    size = int(math.sqrt(len(matrixes)))
    assert size ** 2 == len(matrixes), 'Incorrect number of matrices'
    return _matrixjoin(matrixes, size, size)

def _matrixjoin(matrixes, hsize, vsize):
    print(matrixes, hsize, vsize)
    return ivstack(*(ihstack(*itertools.islice(matrixes, i*hsize, (i+1)*hsize)) for i in range(vsize)))

rawDescription: Join matrices in Python without numpy

description: Join matrices in Python without numpy


code: arr = df.values[:, numeric_list_of_cols]

rawDescription: pandas get numpy ndarray using series.values

description: Pandas get numpy ndarray using series.values


code:
for (item,) in x:
    myfunc(item)

rawDescription: Python list of tuples, need to unpack and clean up


rawDescription: XPath with Scrapy node begins with \n

description: XPath with Scrapy node begins with \n


code:
ax2.set_xlim(tick_locations[0], tick_locations[-1])
ax2.set_xticks(tick_locations[1:]) #1, not 0
ax2.set_xticklabels(tick_labels[1:])

rawDescription: Creating 2 x-axes on matplotlib not working


code: [list(df.loc[list(sum(tups, ())), "name"]) for tups in product(*[(permutations(grp.index)) for (name, grp) in age])]

rawDescription: Quick way to find all permutations of a pandas DataFrame that preserves a sort?


code:
vlist = ['a', 'b', 'c']
regexp = '|'.join([s for s in vlist])

rawDescription: Parameterised regular expression in Python


rawDescription: Selective Re-Memoization of DataFrames

description: Selective Re-Memoization of DataFrames


rawDescription: Numpy binary matrix - get rows and columns of True elements


code:
from collections import defaultdict

with open("SchoolPopulation.txt", "r") as schoolPopulation:
    results = defaultdict(int)
    for line in schoolPopulation:
        parts = line.split(",")
        name = parts[0].lower()
        val = int(parts[1])
        results[name] += val

print(results)

rawDescription: Python 3.X combining similar lines in .txt files together


code:
cartesian_exponent([0,1,5], e=2)
cartesian_exponent([2,3], e=3)

rawDescription: how to permute n elements from list recursively in python?

description: Permute n elements from list recursively in python


code:
class MyBrowser(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id,
                   style=wx.DEFAULT_FRAME_STYLE | wx.STAY_ON_TOP)
        self.transparency = 255
        self.dialog = wx.TextEntryDialog(None, message="Enter stuff")
        self.dialog.ShowModal()
        self.dlg_val = self.dialog.GetValue()
        self.Bind(wx.EVT_CHAR_HOOK, self.onKey)

rawDescription: Get user input from a dialog before showing the mainframe


code:
mask = '001001'
num=123456
"".join(x if y!='1' else '0' for x,y in zip(str(num),mask))

rawDescription: How to apply a mask to a number or string in Python?

description: Apply a mask to a number or string in Python


code:
replacement = ["firstthe", "secondthe"]
sentence = "This is the first sentence in the whole universe!"

words = sentence.split()

counter = 0
for i,word in enumerate(words):
    if word == 'the':
        words[i] = replacement[counter]
        counter += 1

sentence = ' '.join(words)

rawDescription: Replacing each match with a different word


rawDescription: Creating a list of numbers one through nth Python


code:
engine = create_engine('sqlite:///:memory:', echo=True)
meta = MetaData(bind=engine)

rawDescription: SQLAlchemy - Dictionary of tags

description: SQLAlchemy - Dictionary of tags


code:
ARR = [True, False, True, False,]
all(ARR)

rawDescription: AND operation for Boolean array's elements


rawDescription: Unable to get wxPython Sizers to work correctly


code: d = {i:[elements.pop(0)] for i in one[:-1]}.update({one[-1]:[elements]})

rawDescription: python- combining list and making them a dictionary

description: Python- combining list and making them a dictionary


code: queue.extend(node for node in graph[vertex] if node not in path)

rawDescription: BFS algorithm in Python

description: BFS algorithm in Python


code: text.set_text("Some other text")

rawDescription: Change matplotlib.pyplot text() object properties


code:
def cleanurl(link_text):
    return link_text.strip("\t\r\n ")

rawDescription: Links with space before and after are not parsed correctly


rawDescription: List cross-identification

description: List cross-identification


rawDescription: How to set store trigger for computed fields in Odoo 8?

description: Set store trigger for computed fields in Odoo 8


rawDescription: networkx add_node with specific position

description: Networkx add_node with specific position


rawDescription: Python help: generating all possible strings given optional character


code:
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from event_test.items import EventItem

class EventSpider(BaseSpider):
    name = "event_spider"
    allowed_domains = ["eventful.com"]
    start_urls = ["http://eventful.com/sanjose/events"]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        events = hxs.select("//li[contains(@class, 'top-events-item')]")
        for event in events:
            item = EventItem()
            item['event_name'] = event.select(".//h2/a/span/text()").extract()[0]
            item['event_locality'] = event.select(".//span[@class='locality']/text()").extract()[0]
            yield item

rawDescription: Scrapy csv output not having multiple rows for each column


code: [p[0] for p in datapoints[0:5]]

rawDescription: Converting JSON String to Dictionary, Not List (Python)


code: list(zip(*sorted(zip(*lst), key=lambda x: x[2])))

rawDescription: Sorting columns in Python 3.3 nested list by partial comparison


code: [i//2 for i in xrange(10)]

rawDescription: Create a list of integers with duplicate values in Python


code:
def bind(val, func):
    if val is None:
        return None
    else:
        return(func(val))

rawDescription: simplifying maybe Monad

description: Simplifying maybe Monad


code: dict(((path, shutil.disk_usage(path).free) for path in storage_locations))

rawDescription: Find path from tuple with most free space


code:
def format_float(value, ndigits=4):
    j = min(i-1 for i in range(ndigits+1) if value >= 10 ** (ndigits - i))
    return '{:.0{num_digits}f}'.format(value, num_digits=max(0,j))

rawDescription: Decimal formatting based on number of digits in integer and decimal parts


code:
from django.db.models.loading import get_model

z = ContentType.objects.get(model='modelb')
ModelB = get_model(z.app_label, 'ModelB')

rawDescription: Querying a django model using a model name string input


code: d = map(list, d)

rawDescription: Python: Produce increments from a list to form an array


code:
for rowi, row in enumerate(reader):
    for coli, value in enumerate(row):
        try:
            value = int(value)
        except ValueError as e:
            pass
        sheet.write(rowi, coli, value)

rawDescription: read csv file with header and data, and convert to xls file

description: Read csv file with header and data, and convert to xls file


code:
@memoized
def f():
   # expensive calculation here ...
   return calculated_value

rawDescription: Python: Redefining function from within the function


code:
idx = mydf.columns.get_level_values('level_2').to_series().str.contains('mystring')
mydf.loc[:, idx.values]

rawDescription: In pandas, select all columns whose label contains a given string at a specified level


code:
f1 = open("/path/to/file1", "r")
f2 = open("/path/to/file2", "r")

file1_raw = f1.read()
file2_raw = f1.read()

file1_words = file1_raw.split()
file2_words = file2_raw.split()

rawDescription: comparing two text files and remove duplicates in python

description: Comparing two text files and remove duplicates in python


code:
upper_bound = float("inf") # any value that compares larger than all the values in both of your lists
peek_a = PeekIterator(a, upper_bound)
peek_b = PeekIterator(b, upper_bound)
merged = [next(peek_a) if peek_a.peek() <= peek_b.peek() else next(peek_b)
          for _ in range(len(a)+len(b))]

rawDescription: Python: Sorted merge using list comprehension


code: x=my_array.astype('U');"Mary has an {} and a {}".format(x[0],x[1])

rawDescription: Numpy String Encoding

description: Numpy String Encoding


code:
class MyModel(Base):
    # ...
    size = Column(StringFloat)
    # ...

rawDescription: Convert string to float SQLAlchemy

description: Convert string to float SQLAlchemy


code:
True
False

rawDescription: compare the int in the strings

description: Compare the int in the strings


code:
import re
p = re.compile(r'\(([^);]+)')
test_str = "1. yada yada yada (This is a string; \"This is a thing\")\n2. blah blah blah (This is also a string)"
print(p.findall(test_str)) # => ['This is a string', 'This is also a string']

rawDescription: regex to match between certain characters

description: Regex to match between certain characters


rawDescription: Best way to encode tuples with json

description: Encode tuples with json


code:
import random
def sample_from_cdf(val_and_cdf):
    (val, cdf) = val_and_cdf;
    rand = random.uniform(0, val)
    # use bisect.bisect_left to reduce search time from O(n) to O(log n).
    return [key for index, key in cdf if index > rand][0]

rawDescription: Sampling keys due to their values

description: Sampling keys due to their values


code:
import lxml.html as LH

text = '''

I dont need

I dont need

I dont need

Text that i need

'''

doc = LH.fromstring(text)
print(doc.xpath('//div[@id = "CategoryBreadcrumb"]/ul/li/text()'))

# ['Text that i need']

rawDescription: HXS filtering with scrapy - python

description: HXS filtering with scrapy - python


code: A_new, B_new, C_new = zip(*coords_sorted_by_z)

rawDescription: how to sort the following

description: Sort the following


code: orders_list = [row[0].replace("http://", "").replace("www.", "") for row in reader2]

rawDescription: Getting urls with csv reader and putting them into a list


code:
SomeScript.py
foo
bar

rawDescription: Passing command line parameters to IronPython from C# application?


code:
import collections
by_sender = collections.defaultdict(list)
file_read = open('Names_Text_full_clean.csv', 'rU')
reader = csv.reader(file_read)
for match in reader:
    by_sender[match[0]].append(match)

rawDescription: Optimizing an indexing script for a bipartite graph


rawDescription: item frequency in a python list of dictionaries

description: Item frequency in a python list of dictionaries


code:
u,s,v = linalg.svd(A)
s

rawDescription: Using numpy to Obtain Submatrix

description: Using numpy to Obtain Submatrix


code:
import datetime as dt
from time import sleep

now = dt.datetime.now()
pause = dt.datetime(now.year, now.month, now.day, 4)
start = dt.datetime(now.year, now.month, now.day, 5)

if now >= pause and now < start:
    sleep((start - now).seconds)

rawDescription: Python checking daytime

description: Python checking daytime


code:
a = {
    'searchResult' : [{
                       'resultType' : 'station',
                       'ranking' : 0.5
                      }, {
                       'resultType' : 'station',
                       'ranking' : 0.35
                      }, {
                      'resultType' : 'station',
                      'ranking' : 0.40
                      }]
  }

a["searchResult"].sort(key=lambda d: d["ranking"], reverse=True)

rawDescription: Sorting by nested dictionary in Python dictionary


code: self.firstel = q[0]  # and stays this value once and for all

rawDescription: Numpy array assignment inside class

description: Numpy array assignment inside class


code:
itemIDsRef = clr.Reference[Array[int]]()
itemNamesRef = clr.Reference[Array[String]]()
GetItems(itemIDs, itemNames)
itemIDs, itemNames = itemIDsRef.Value, itemNamesRef.Value

rawDescription: How to use a .NET method which modifies in place in Python?

description: Use a .NET method which modifies in place in Python


code:
def transform_point(self, x=None, y=None):
    if x is None:
        x = self.x
    if y is None:
        y = self.y

rawDescription: Default to class variables in a python class method?


code:
from itertools import chain, islice, izip, cycle
list(islice(cycle(chain.from_iterable(izip(server1, server2, server3))), 0, 18))

rawDescription: cycle through multiple list using itertools.cycle()

description: Cycle through multiple list using itertools.cycle()


code: js_assets = [js for js in locate('*.js', '/../../nodes')]

rawDescription: search in wildcard folders recursively in python

description: Search in wildcard folders recursively in python


code:
def Energy(coeffs, k):
    return np.sqrt(np.sum(np.array(coeffs[-k]) ** 2)) / len(coeffs[-k])

rawDescription: Energy for 1-D wavelet in Python

description: Energy for 1-D wavelet in Python


code:
for w in listdefault[::-1]:
    if w.istitle():
        w = w.lower()
        uncrypted.append(w)

rawDescription: Uncrypting a very simple code in python

description: Uncrypting a very simple code in python


rawDescription: Selenium - get all children divs but not grandchildren


code:
import json
import codecs

json.load(codecs.open('sample.json', 'r', 'utf-8-sig'))

rawDescription: Python load json file with UTF-8 BOM header


code:
from Tkinter import *

def func():
    for child in f2.winfo_children():
        child.configure(state = 'disable')

import tkMessageBox
import ttk

root = Tk()

root.title("Pantai Hospital")
root.geometry("200x200")

Label(root, text = "Welcome to Pantai Hospital!").grid()

f1 = Frame(root, width = 350, height = 110)

f2 = Frame(f1, relief = GROOVE, borderwidth = 2)

l9 = Label(f2, text = "Choose your specialist:")
l9.grid()

specialistchoose = IntVar()

r1 = Radiobutton (f2, text = "Cardiology", variable = specialistchoose, value = 1, command=func)
r1.grid(row = 1, column = 0, stick = W)

r2 = Radiobutton (f2, text = "Gastroenterology", variable = specialistchoose, value = 2, command=func)
r2.grid(row = 1, column = 1,stick = W )

r3 = Radiobutton (f2, text = "Dermatology", variable = specialistchoose, value = 3, command=func)
r3.grid (row = 1, column = 2,stick = W )

r4 = Radiobutton (f2, text = "Psychiatry", variable = specialistchoose, value = 4, command=func)
r4.grid (row = 3, column = 0,stick = W )

r5 = Radiobutton (f2, text = "Dentist", variable = specialistchoose, value = 5, command=func)
r5.grid(row = 3, column = 1,stick = W  )

f2.place(relx = 0.01, rely = 0.125, anchor = NW)
Label(f1, text = "Specialist").place(relx = .06, rely = 0.125, anchor = W)

f1.grid()

f3 = Frame(root, width = 350, height = 110)
f4 = Frame(f3, relief = GROOVE, borderwidth = 2)

l15 = Label (f4, text = "Choose your preferred day:")
l15.grid(columnspan = 2, sticky = W)

day = IntVar()

cb1 = Checkbutton(f4, text = "Monday", variable = day, onvalue = 1, offvalue = 0)
cb1.grid(row = 4, column = 0,stick = W )
cb2 = Checkbutton(f4, text = "Tuesday", variable = day, onvalue = 2, offvalue = 0)
cb2.grid(row = 4, column = 1,stick = W )
cb3 = Checkbutton(f4, text = "Wednesday", variable = day, onvalue = 3, offvalue = 0)
cb3.grid(row = 4, column = 2, stick = W)
cb4 = Checkbutton(f4, text = "Thursday", variable = day, onvalue = 4, offvalue = 0)
cb4.grid(row = 4, column = 3,stick = W )
cb5 = Checkbutton (f4, text = "Friday", variable = day, onvalue = 5, offvalue = 0)
cb5.grid(row = 5, column = 0, stick = W )
cb6 = Checkbutton(f4, text = "Saturday", variable = day, onvalue = 6, offvalue = 0)
cb6.grid(row = 5, column = 1, stick = W )
cb7 = Checkbutton (f4, text = "Sunday", variable = day, onvalue = 7, offvalue = 0)
cb7.grid(row = 5, column = 2, stick = W )

f4.place(relx = 0.01, rely = 0.125, anchor = NW)
Label(f3, text = "Day").place(relx = .06, rely = 0.125, anchor = W)

f3.grid()
root.mainloop()

rawDescription: Gray out a frame after clicking a radiobutton Tkinter


rawDescription: How to sort dictionary on first element of the key (tuple)

description: Sort dictionary on first element of the key (tuple)


code:
from operator import getitem

reduce(getitem, l, d)

rawDescription: Any Functional Programming method of traversing a nested dictionary?


rawDescription: Complex query in Django ORM

description: Complex query in Django ORM


code: np.apply_along_axis(lambda x: np.bincount(x, minlength=2), axis=1, arr=m)

rawDescription: Can numpy bincount work with 2D arrays?

description: Can numpy bincount work with 2D arrays


code:
import pandas as pd
from StringIO import StringIO

data = \
"""A,B,D,E,None
B,C,E,None,None
A,B,D,E,None
A,B,C,E,None
A,B,C,D,E"""

# Creation of the dataframe
df = pd.read_csv(StringIO(data),sep = ',',header=None)
# Perform the magic operation (stack and value_counts) on the dataframe
res = df.stack().value_counts()

rawDescription: Count items in a Pandas DataFrame

description: Count items in a Pandas DataFrame


rawDescription: Is it possible to split a dictionary and group the values then return each group with respective key?


code:
import re
re.sub("a|b", "c", str)

rawDescription: python replace two optional strings with a third (looking for a neat way)

description: Python replace two optional strings with a third (looking for a neat way)


code:
class ListProxy(object):
    def __init__(self, l):
        self.list = l
    def __getitem__(self, i):
        return self.list[i]

rawDescription: Avoid expansion of sys.argv keyword argument in Sphinx documentation


code:
with open ("newhosts.txt", "w") as thefile:
    for item in hostnameIP:
        thefile.write("%s\n" % ", ".join(item))

rawDescription: python write list to file

description: Python write list to file


code:
import urllib
url = 'http://www.ssa.gov/cgi-bin/popularnames.cgi'

post_params = { # member was blank, so I'm excluding it.
    'top'  : '25',
    'year' : year
    }
post_args = urllib.urlencode(post_params)

rawDescription: a (presumably basic) web scraping of http://www.ssa.gov/cgi-bin/popularnames.cgi in urllib

description: A (presumably basic) web scraping of http://www.ssa.gov/cgi-bin/popularnames.cgi in urllib


code: data = collection.find().sort(fieldname, validSortOrders[sortOrder])

rawDescription: Ascending and descending not working while passing as argument in mongodb with python


code:
import urlparse, urllib

def opener(fun):
    def wrapper(url):
        if urlparse.urlparse(url)[0] in ('http', 'https', 'ftp'):
            return fun(urllib.urlopen(url))
        return fun(open(url))
    return wrapper

@opener
def read(stream):
   return stream.read()

read('myfile')
read('http://www.wikipedia.org')

rawDescription: Canonical/Idiomatic "do what I mean" when passed a string that could a filename, URL, or the actual data to work on


rawDescription: Rounding Error in Python

description: Rounding Error in Python


code: matching_results = filter(lambda t: t[0]==c_code, list_)

rawDescription: How can I get a Tuple from a list in python (3.3)

description: Get a Tuple from a list in python (3.3)


rawDescription: Python: Combining two CSV files with header row and matched values with DictReader and DictWriter


rawDescription: Column filtering in PySpark

description: Column filtering in PySpark


rawDescription: Speed up comparison of floats between lists


code: [[item["No"], item["Size"], item["Name"]] for item in items]

rawDescription: Python: Get multiple random lines for a given category


rawDescription: nested classes in Python

description: Nested classes in Python


code:
import inputs   #import the module here, so that it can be reloaded.
reload(inputs)
from inputs import A # or whatever name you want.

rawDescription: Python reload file

description: Python reload file


code: match = re.match(r'(.*?)=(.*)', line)

rawDescription: Python re.search - searching from left to right


code:
cmap = make_colormap([(0,1,0), c('dark green')])
cmap.set_under('burnt red')
cmap.set_over('yellow green')

rawDescription: Discrete then linear colormap in matplotlib


code:
class SearchTerm(ParsedObject):
    def queryString(self):
        text = ' '.join(self.tokens.search_text)
        if self.tokens.field:
            return '%s: %s' % (' '.join(f.lower()
                                        for f in self.tokens.field[0]),text)
        else:
            return text
search_term.setParseAction(SearchTerm)

rawDescription: pyparsing one query format to another one

description: Pyparsing one query format to another one


code:
a=0
bool(a)
a=26
bool(a)
a=""
bool(a)
a=" " #this has a gap, its not "".Realize that, its different than the last example.
bool(a)

rawDescription: python: don't understand "while len(list1) and len(list2):"

description: Python: don't understand "while len(list1) and len(list2):"


code:
from pyspark.ml.feature import StringIndexer
from pyspark.ml.classification import RandomForestClassifier

df = sqlContext.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")

indexer = StringIndexer(inputCol="label", outputCol="indexed").fit(df)
df_indexed = indexer.transform(df)

model = RandomForestClassifier(
    numTrees=3, maxDepth=2, labelCol="indexed", seed=42
).fit(df_indexed)

rawDescription: How to access individual predictions in Spark RandomForest?

description: Access individual predictions in Spark RandomForest


code:
start, _, end = text.rpartition('(')
result = start or end

rawDescription: Exclude last matching portion of the text


rawDescription: Plotting CDF of a pandas series in python


code:
df2 = df.loc[idx, ['word', 'tag']].set_index('word')
df2
df2.to_dict()['tag']

rawDescription: python pandas, DF.groupby().agg(), column reference in agg()

description: Python pandas, DF.groupby().agg(), column reference in agg()


code:
occurrences_dict = {}
for seqrecord in records:
    idkeep, rest = seqrecord.id.split(';',1)
    occurrences_dict[idkeep] = occurrences_dict.get(idkeep, 0) + 1

rawDescription: Parsing fasta file with biopython to count number sequence reads belonging to each ID


rawDescription: Spark: Manipulation of Multiple RDDs

description: Spark: Manipulation of Multiple RDDs


code:
ordered = Ordered()
ordered.ordered_fields

rawDescription: How can I get fields in an original order?

description: Get fields in an original order


rawDescription: Python/Numpy C++ extension: memory issue


code:
s = 'Reading from EEPROM: addr = 30 value = h11c13����'
s
filter(lambda x: ord(x)<128,s)

rawDescription: Howto Remove Garbage Data from String

description: Howto Remove Garbage Data from String


code:
my_xtick_labels = np.arange(0,25)
my_xticks = (my_xticks*scaler.std_) + scaler.mean_
plt.set_xticks( my_xticks )
plt.set_xticklables( my_xtick_labels )

rawDescription: matplotlib: Rescale axis labels

description: Matplotlib: Rescale axis labels


code:
df = pd.DataFrame({col: pd.Series(range(df[col].iloc[0],
                                        df[col].iloc[-1] + 1)) for col in df.columns })

rawDescription: Appending variable length columns in Pandas dataframe Python


code: expr << var('var*') + ZeroOrMore(Literal('+') + expr)

rawDescription: pyparsing: named results?

description: Pyparsing: named results


code: sum(c1 == c2 for c1, c2 in itertools.izip(s1, s2))

rawDescription: How do I count the number of identical characters in a string by position using python?

description: Count the number of identical characters in a string by position using python


code:
import pandas as pd
import numpy as np

df = pd.DataFrame({'var1': np.random.randint(1, 10, 10),
                   'var2': np.random.randint(1, 10, 10),
                   'var3': np.random.randint(1, 10, 10)})

# Use the sum method:
df[['var1', 'var2', 'var3']].sum(axis='columns')

# Use eval
df.eval('var1 + var2 + var3')

rawDescription: Elegantly summing named DataFrame columns in python


code:
print ("name ==", name)
if name == "Sam":
    print ("Your name is Sam")

rawDescription: Why doesn't the result of input() match what I expect to get?


code:
for row in cur:
    channel = row[0].encode('ascii')
    channelList.append(channel)

    # set the channels text
    for index in range(0, channels_per_page):
         if index >= len(channel):
            self.setControlLabel(4010 + index, channel)

rawDescription: how to put number of strings in each label

description: Put number of strings in each label


code:
def make_function():
    def f(value=[]):
            value.append('hello')
            return value
    return f

f1 = make_function()
f2 = make_function()
f1()
f1()
f2()

rawDescription: question about python names using a default parameter value

description: Question about python names using a default parameter value


code:
with mgf.read(mgf_file) as temp_read:
    reader = list(temp_read)

rawDescription: Copying dicts from csv to a new dict-python


code:
from math import log10

class Formatter(object):
    def __init__(self):
        self.formats = (('%1.1f', 0),
                        ('%2.1f', 0),
                        ('%1.2f K', 3),
                        ('%1.2f K', 3),
                        ('%2.1f K', 3),
                        ('%1.2f M', 6),
                        ('%1.2f M', 6),
                        ('%2.1f M', 6),
                        ('%1.2f B', 9),
                        ('%1.2f B', 9),
                        ('%2.1f B', 9),
                        ('%1.2f T', 12),
                        ('%1.2f T', 12),
                        ('%2.1f T', 12))

    def human_readable(self, x):
        if x == 0: return '0'
        magnitude = int(log10(abs(x)))
        if magnitude > 13: format_str, denominator_mag = '%i T', 12
        else: format_str, denominator_mag = self.formats[magnitude]
        return (format_str % (x * 1.0 / (10 ** denominator_mag))).lstrip('0')

rawDescription: Python formatting large values

description: Python formatting large values


code:
class BaseDevice:
    def start(self):
        raise NotImplementedError
    def stop(self):
        raise NotImplementedError
    def pause(self):
        raise NotImplementedError
    def resume(self):
        raise NotImplementedError

class RealDevice(BaseDevice):
    def start(self):
        self.device.do_start()
    def stop(self):
        self.device.do_stop()
    def pause(self):
        self.device.do_pause()
    def resume(self):
        self.device.do_resume()

class SimuDevice(BaseDevice):
    def start(self):
        self._state = "running"
        print("started")
    def stop(self):
        self._state = "stopped"
        print("stopped")
    def pause(self):
        self._state = "paused"
        print("paused")
    def resume(self):
        self._state = "running"
        print("resumed")

rawDescription: simulation/operation mode in class

description: Simulation/operation mode in class


code:
class Bar(Foo):
    def myFunc(self, data):
        print("myFunc: %s"% data)

bar = Bar()
bar.myFunc(5)

rawDescription: Intercept method calls in Python

description: Intercept method calls in Python


code:
for i in range(1000):
    f=open('test2.txt', 'a')
    f.write('\n')
    f.close()

rawDescription: Python file open/close everytime vs keeping it open until the process is finished


code:
def fibList(n):

        if n <= 0:
                fibnums = []
        elif n == 1:
                fibnums = [0]
        elif n >= 2:
                fibnums = [0, 1]
                for i in range(2,n):
                        fibnums.append(fibnums[i-1]+fibnums[i-2])
        return fibnums

rawDescription: how to fix python fibonacci sequence script?

description: Fix python fibonacci sequence script


code:
sol = result[0].T.reshape(x.shape)
sol

rawDescription: Broadcasting issues with numpy.linalg.lstsq


code:
ff.zap = lambda x: x + ff.y
_ff = dill.loads(dill.dumps(ff))
_ff.zap(2)
dill.dumps(ff, byref=True)
dill.dumps(ff, byref=False)

rawDescription: Why dill dumps external classes by reference, no matter what?


code: SyncManager.register('set', set)

rawDescription: Using sets with the multiprocessing module


code:
command = ['ping', '-W', '2', '-c', '2']
ip_template = '64.233.{}.{}'

for i in range(160, 165):
     for j in range(5):
          ip_address = ip_template.format(i, j)
          proc = subprocess.Popen(command + [ip_address], stdout=subprocess.PIPE)
          result, _ = proc.communicate()

rawDescription: Implementing ping using Python

description: Implementing ping using Python


code:
#!/usr/bin/env python
import csv
import sys
import urllib2
from bs4 import BeautifulSoup # $ pip install beautifulsoup4

soup = BeautifulSoup(urllib2.urlopen('http://poj.org/status'))

writer = csv.writer(sys.stdout)
for tr in soup.find('table', 'a')('tr'):
    writer.writerow([td.get_text() for td in tr('td')])

rawDescription: How to get the content from a certain <table> using python?

description: Get the content from a certain <table> using python


code:
pic = None
tkPic = None
tkPic2 = None
picToConvert = None
canvas1 = None

rawDescription: Having some trouble converting a tk PhotoImage back to a PIL image to save


rawDescription: Variables and Assign range to it in Python


code: df.to_csv('test.csv', mode='a', header=False, index=False)

rawDescription: Keep header while appending to Pandas dataframe w/ Python


code:
class B(A):
    dictionary = A.dictionary.copy()
    dictionary['key'] = 'value'

rawDescription: Alter superclass' variable from subclass on Python


rawDescription: Padding or truncating a Python list

description: Padding or truncating a Python list


code:
wrong_date1 = datetime.datetime(2014, 3, 29, 0, 0, tzinfo=tzone)
# datetime.datetime(2014, 3, 29, 0, 0, tzinfo=<DstTzInfo 'Europe/Budapest' LMT+1:16:00 STD>)

rawDescription: Difference of two timedelta objects, with timezones


rawDescription: Django: get info from same table based on column vsalue for data record


code: df = pd.DataFrame({'gof_test': gof_test, 'gof_train': gof_train})

rawDescription: Python: beautify numerical and dict outputs


rawDescription: Efficient algorithm for pairwise computation


rawDescription: Password Validating Program

description: Password Validating Program


code:
# class_library_1_wrapper.py
import clr
clr.AddReference("ClassLibrary1")
import ClassLibrary1

class Class1:
    def __init__(self):
        self._clr_object = ClassLibrary1.Class1()

    def some_method():
        return self._clr_object.SomeMethod()

    @staticmethod
    def test():
        return "george"

rawDescription: Use IronPython to override DLL function

description: Use IronPython to override DLL function


code:
from scipy.signal import convolve
import numpy as np
from matplotlib import pyplot as plt
#Obtaining derivative
kernel = [1, 0, -1]
dY = convolve(Y, kernel, 'valid')

#Checking for sign-flipping
S = np.sign(dY)
ddS = convolve(S, kernel, 'valid')

#These candidates are basically all negative slope positions
#Add one since using 'valid' shrinks the arrays
candidates = np.where(dY < 0)[0] + (len(kernel) - 1)

#Here they are filtered on actually being the final such position in a run of
#negative slopes
peaks = sorted(set(candidates).intersection(np.where(ddS == 2)[0] + 1))

plt.plot(Y)

#If you need a simple filter on peak size you could use:
alpha = -0.0025
peaks = np.array(peaks)[Y[peaks] < alpha]

plt.scatter(peaks, Y[peaks], marker='x', color='g', s=40)

rawDescription: find peaks location in a spectrum numpy

description: Find peaks location in a spectrum numpy


rawDescription: get prime numbers from numpy array

description: Get prime numbers from numpy array


code:
usa_date = datetime.datetime.strptime(
    usa_raw_date[-1].childNodes[0].nodeValue, '%Y-%m-%d %H:%M')
canada_date = datetime.datetime.strptime(
    canada_raw_date[-1].childNodes[0].nodeValue, '%Y-%m-%d %H:%M')
return max(usa_date, canada_date)

rawDescription: How do I quickly compare dates from parsed XML in Python?

description: Quickly compare dates from parsed XML in Python


code:
def onSize(self, event):
    event.Skip()
    wx.CallAfter(yourHtmlWindow.Scroll, -1, self.GetClientSize()[0])

rawDescription: wxPython - wxHtmlWindow, can the scrollbar be kept at the veyr bottom at all times?

description: WxPython - wxHtmlWindow, can the scrollbar be kept at the veyr bottom at all times


code:
{
   "results" : [
      {
         "address_components" : [
             # component dictionaries
         ],
         "formatted_address" : "Virginia Tech Trail, Virginia Beach, VA 23455, USA",
         "geometry" : {
             # geometry dictionary
         },
         "partial_match" : true,
         "place_id" : "ChIJw0P35CuUuokROoH5mxE5Pyg",
         "types" : [ "route" ]
      }
   ],
   "status" : "OK"
}

rawDescription: Calling a JSON API

description: Calling a JSON API


code:
import tkinter

class Store:
    def __init__(self):
        self.variable = tkinter.IntVar()

    def add(self, value):
        var = self.variable
        var.set(var.get() + value)
        return var.get()

class Main(tkinter.Tk):
    def __init__(self, *args, **kwargs):
        tkinter.Tk.__init__(self, *args, **kwargs)
        var = Store()
        self.label  = tkinter.Label(self, textvariable=var.variable)
        self.button = tkinter.Button(self, command=lambda: var.add(1), text='+1')
        self.label.pack()
        self.button.pack()

root = Main()
root.mainloop()

rawDescription: tkinter variable in another class

description: Tkinter variable in another class


code: subprocess.Popen(['myscript.sh "var=11; ignore all" %s' % path_to_files], shell=True, executable="/bin/bash")

rawDescription: python subprocess calling bash script - need to print the quotes out too

description: Python subprocess calling bash script - need to print the quotes out too


code: [y[0] for y in tuple_list].index('kumquat')

rawDescription: Using Python's list index() method on a list of tuples or objects?


code:
df['incomebracket'] = 0 #default
df.incomebracket[(df.income >= 100000) & (df.income < 150000)] = 1

rawDescription: Create dataframe column based on other column


rawDescription: Selecting 3D surfaces with a selection box (in two different ways)


code:
class WTS(dict):
    def __missing__(self, key):
        return 1 if key[1] == somevalue else 0

wts = WTS()

rawDescription: How to use defaultdict to create a dictionary with a lambda function?

description: Use defaultdict to create a dictionary with a lambda function


code:
s = np.random.random((3,4))
t = np.matrix(s)
t.I
np.linalg.inv(t)

rawDescription: Scipy inv(A) vs A.I

description: Scipy inv(A) vs A.I


rawDescription: Deleting a div with a particlular class using BeautifulSoup


code:
import collections
answer = collections.defaultdict(list)
with open('path/to/file') as infile:
    for line in infile:
        key, value = line.strip().split()
        answer[key].append(value)

rawDescription: Combining the use of update and append for dictionaries


code:
import shutil
from tempfile import NamedTemporaryFile

rtf_filename = time.strftime("%d") + ".rtf" # rtf filename in date format
template = open("template.rtf").read() # rtf template
template_append = open("template_append.rtf").readlines()
data_source = {'data': 'test_data'}

if os.path.isfile(rtf_filename) is True: # RTF file might exist
    with open(rtf_filename) as rtf_file, NamedTemporaryFile(dir='.', delete=False) as tmp_file:
        lines = rtf_file.readlines()[:-1]    # reads all lines and truncates the last one
        lines.extend([s % data_source for s in template_append])
        tmp_file.writelines(lines)
    shutil.move(tmp_file.name, rtf_filename)
else:
    with open(rtf_filename, "w") as f:
        f.write(template % data_source)

rawDescription: Python - removing last line of target when appending


code:
# contents of foo-bar.py
baz = 'quux'

rawDescription: How to import python module when module name has a '-' dash or hyphen in it?

description: Import python module when module name has a '-' dash or hyphen in it


code: subtracted_data = np.array([x - np.mean(x, 0) for x in data])

rawDescription: Trouble indexing lists of NUMPY arrays properly


code:
data_aux = pd.DataFrame(list(tableA.ColofInt.str.split(';').apply(lambda x: x[:-1])))
cols = []
for e in data_aux .columns:
    cols.append('ColofInt' + str(e+1))
data_aux .columns = cols

rawDescription: How do I manipulate pandas DataFrame with a column that has rows with strings that needs spliting

description: Manipulate pandas DataFrame with a column that has rows with strings that needs spliting


code:
# create NetCDF file
nco = netCDF4.Dataset('/usgs/data2/notebook/cold_days.nc','w',clobber=True)
nco.createDimension('x',nx)
nco.createDimension('y',ny)

cold_days_v = nco.createVariable('cold_days', 'i4',  ( 'y', 'x'))
cold_days_v.units='days'
cold_days_v.long_name='total number of days below 0 degC'
cold_days_v.grid_mapping = 'Lambert_Conformal'

lono = nco.createVariable('lon','f4',('y','x'))
lato = nco.createVariable('lat','f4',('y','x'))
xo = nco.createVariable('x','f4',('x'))
yo = nco.createVariable('y','f4',('y'))
lco = nco.createVariable('Lambert_Conformal','i4')

# copy all the variable attributes from original file
for var in ['lon','lat','x','y','Lambert_Conformal']:
    for att in f.variables[var].ncattrs():
        setattr(nco.variables[var],att,getattr(f.variables[var],att))

# copy variable data for lon,lat,x and y
lono[:]=f.variables['lon'][:]
lato[:]=f.variables['lat'][:]
xo[:]=f.variables['x'][:]
yo[:]=f.variables['y'][:]

#  write the cold_days data
cold_days_v[:,:]=cold_days

# copy Global attributes from original file
for att in f.ncattrs():
    setattr(nco,att,getattr(f,att))

nco.Conventions='CF-1.6'
nco.close()

rawDescription: Loop through netcdf files and run calculations - Python or R


code:
def CRC(bytearray_in):
    '''Calculates a Cyclical Redundancy Checksum (CRC16).'''
    crc = 0xFFFF
    for work_byte in bytearray_in:
        crc ^= work_byte
        n = 0
        while n in range(8):
            if (crc & 0x0001):
                crc >>= 1
                crc ^= 0xA001
            else:
                crc >>= 1
            n += 1
    return crc

rawDescription: Inheriting and modifying __init__() method


code: {k:[x-y for x, y in zip(d1[k], d2[k])] for k in d1}

rawDescription: subtracting all values in dictionaries were values are list of floats

description: Subtracting all values in dictionaries were values are list of floats


code:
from __future__ import print_function
# Note: If you are using Python 3 leave this line out
# This must be the first statement before other statements.
# You may only put a quoted or triple quoted string,
# Python comments or blank lines before the __future__ line.
import sys

def print(*args, **kwargs):
    """My custom print() function."""
    # Adding new arguments to the print function signature
    # is probably a bad idea.
    # Instead consider testing if custom argument keywords
    # are present in kwargs
    sys.stdout.write('hello')
    return __builtins__.print(*args, **kwargs)

print ("hello there")
print (" hi again")

rawDescription: Appending to every printed message

description: Appending to every printed message


code:
questions = [ "Enter the name of a male acquaintance: ",
  "Enter the name of a place: ",
  ... ]

rawDescription: How to change number in Mad Libs game?

description: Change number in Mad Libs game


code:
df = pd.read_fwf("weekend.dat", widths=(26, 20, 9), parse_dates=[0])
df = df.fillna(method="ffill")
df

rawDescription: Pandas Shaping Data for Covariance

description: Pandas Shaping Data for Covariance


rawDescription: Implicit functions, looking to perform different math functions based on a key


code:
keywords = ['word1', 'word2', 'word3']
keywords_condition = or_(*[Item.title.like('%{}%'.format(keyword)) for keyword in keywords])
keywords_condition

rawDescription: mysql sqlalchmey keywords search

description: Mysql sqlalchmey keywords search


code:
import re
strings = []

with open("test.txt") as f:
    for line in f:
        if "test" in line:
            strings.extend(re.findall(r'"(.*?)"', line, re.DOTALL))

rawDescription: Extract text enclosed in quotes when reading a file


rawDescription: Populating backend script for Django form


code:
FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logger = logging.getLogger('tcpserver')
logger.warning('Protocol problem: %s', 'connection reset', extra=d)

rawDescription: how to formatting the default message for python logger

description: Formatting the default message for python logger


code:
def edit_contact(request, contact_pk=None):
    if contact_pk:
        my_contact = Contact.objects.get(pk=contact_pk)
    else:
        my_contact = Contact()
    CommunicationFormSet = inlineformset_factory(Contact, Communication)
    if request.POST:
        contact_form = ContactForm(request.POST, instance=my_contact)
        communication_set = CommunicationFormSet(request.POST,
                                                 instance=my_contact)
        if contact_form.is_valid() and communication_set.is_valid():
            contact_form.save()
            communication_set.save()
    else:
        contact_form = ContactForm(instance=my_contact)
        communication_set = CommunicationFormSet(instance=my_contact)

    return render_to_response('my_template.html',
                              {'form': contact_form, 'formset':communication_set})

rawDescription: How to have a nested inline formset within a form in Django?

description: Have a nested inline formset within a form in Django


rawDescription: Iterate through items of an arbitrary layered dictionary in Python


code:
X_test = np.random.randn(5, 20)
gram_test = linear_kernel(X_test, X)

rawDescription: SKLearn Kernel PCA "Precomputed" argument


rawDescription: How to read UTF-8 files with Pandas?

description: Read UTF-8 files with Pandas


code:
if True:
 #my statements
 #which I don't want to execute right now
 pass # or do_stuff()

rawDescription: How to test python code containing blank lines in the interpreter

description: Test python code containing blank lines in the interpreter


code:
import glob
file_path = glob.glob('\\folder\\todolist\\grocerylist_*.csv')[0]

rawDescription: Python Open File path that changes dynamically


code:
calculated = (scipy.misc.comb(n, r, exact=True)
              for n in range(1,maxn+1) for r in range(0,n+1))
[comb for comb in calculated if comb > threshold]

rawDescription: List comprehension with repeated computation


rawDescription: Optimization of Recursive Pascal Triangle Function


code:
if exam_solution[answers] == student_answers[answers]:
    i += 1
else:
    questions_missed.append(answers + 1)

rawDescription: Using two lists to compare elements and creating a list of non-same elements within those two lists?


code:
df.sort_index(ascending=False)
df.sort_index(ascending=False) == 0
(df.sort_index(ascending=False) == 0).cumsum()
(df.sort_index(ascending=False) == 0).cumsum() < 2
df[(df.sort_index(ascending=False) == 0).cumsum() < 2]

rawDescription: Pandas: complex filtering with apply

description: Pandas: complex filtering with apply


rawDescription: Formatting datetime variables give missing time values as 00:00:00. Using Python


code:
class met(type):
    def __init__(cls, name, bases, dct):
        super(met, cls).__init__(name, bases, dct)
        cls._test_member = "test_value"

object = met('object', (object,), {})

class A(object):
    pass

print(A._test_member)

rawDescription: Python default metaclasses

description: Python default metaclasses


code:
s
root = ET.fromstring(s)
root.findall('.//probe[@kind="condition"]')
root.findall('.//probe[@kind="condition"][@event="full"]')

rawDescription: How to handle multiple search condition of xpath in python Element Tree

description: Handle multiple search condition of xpath in python Element Tree


code:
def getElements(data, n):
    for i in xrange(0, len(data), n):
        yield data[i:i+n]

rawDescription: How to get elements from a list, by groups of 10? (or 5, or 3, etc)

description: Get elements from a list, by groups of 10? (or 5, or 3, etc)


rawDescription: scipy.sparse dot extremely slow in Python

description: Scipy.sparse dot extremely slow in Python


code: trialList = [{'target':target[i], 'distractor':distractor[i]} for i in indices]

rawDescription: Shuffle two lists in the same order in python


rawDescription: using rpyc to update properties on a remote object

description: Using rpyc to update properties on a remote object


rawDescription: Python add a string to all set's elements


code:
import numpy as np
import scipy.stats

# generate data samples
data = scipy.stats.expon.rvs(loc=0, scale=1, size=1000, random_state=123)

rawDescription: how to plot Probability density Function (PDF) of inter-arrival time of events?

description: Plot Probability density Function (PDF) of inter-arrival time of events


code:
class Home(Edifice):
    def __init__(self, storeys, area, bedrooms):
        super().__init__(storeys, area)
        self.__bedrooms = bedrooms
        self.message = "For human habitation: {} bedrooms"

    def show_info(self):
        super(Home, self).show_info()
        print("{}".format(self.message.format(self.__bedrooms)))

rawDescription: Inheritance and classes

description: Inheritance and classes


code:
with open('/home/path/file.csv', 'r+') as csvfile:
    with open('/home/path/file.enc', 'w') as csvencryptedfile:
        for row in csv.reader(csvfile, delimiter='\t'):
            y = []
            for i in range(0, len(row)):
                x = encrypt(row[i], password)
                y.append(x)
            csvencryptedfile.write('\t'.join(y))
            csvencryptedfile.write('\n')

rawDescription: Problems with handling files in Python

description: Problems with handling files in Python


code:
import argparse
class CustomAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        if not 'ordered_args' in namespace:
            setattr(namespace, 'ordered_args', [])
        previous = namespace.ordered_args
        previous.append((self.dest, values))
        setattr(namespace, 'ordered_args', previous)
parser = argparse.ArgumentParser()
parser.add_argument('--test1', action=CustomAction)
parser.add_argument('--test2', action=CustomAction)

rawDescription: argparse argument order

description: Argparse argument order


code:
review = {'positive':5, 'negative':1, 'negative':0}
maxNr = max(review, key=review.get)
maxNr
ReviewList = []
ReviewList.append(maxNr)
ReviewList

rawDescription: Showing up the "variable" not the number Python


code:
datetime.datetime.utcnow()
# returns datetime.datetime(2013, 4, 4, 10, 39, 1, 303329)

rawDescription: What does a utc replace do on a utc timestamp?


code:
def reversed(seq):
    try:
        return seq.__reversed__()
    except AttributeError:
        return (seq[i] for i in xrange(len(seq) - 1, -1 , -1))

rawDescription: Does reverse actually reverse a Python iterator?


code:
for func in myList[0:5]:
  if func is not None: func()

rawDescription: Python: How to access only some boolean elements of a list with a loop?


code: ids = self.get_arguments('agencyID')

rawDescription: Is it possible to get values from query string with same name?


code: ' '.join(tokens[1:3])

rawDescription: Extracting a specific PIECE of a line from a textfile(Python)


rawDescription: Python join elements with same index

description: Python join elements with same index


code:
import collections

class FrozenDict(collections.Mapping):
    """Don't forget the docstrings!!"""

    def __init__(self, *args, **kwargs):
        self._d = dict(*args, **kwargs)
        self._hash = None

    def __iter__(self):
        return iter(self._d)

    def __len__(self):
        return len(self._d)

    def __getitem__(self, key):
        return self._d[key]

    def __hash__(self):
        # It would have been simpler and maybe more obvious to
        # use hash(tuple(sorted(self._d.iteritems()))) from this discussion
        # so far, but this solution is O(n). I don't know what kind of
        # n we are going to run into, but sometimes it's hard to resist the
        # urge to optimize when it will gain improved algorithmic performance.
        if self._hash is None:
            self._hash = 0
            for pair in self.iteritems():
                self._hash ^= hash(pair)
        return self._hash

rawDescription: What would a "frozen dict" be?

description: What would a "frozen dict" be


rawDescription: Reading adjacent elements in graph in python


rawDescription: How to get the first and last second in python using datetime module

description: Get the first and last second in python using datetime module


code:
import xattr
xattr.listxattr("/bin/ping")
xattr.getxattr("/bin/ping", "security.capability")

rawDescription: How to read file capabilities using Python?

description: Read file capabilities using Python


code:
from collections import OrderedDict

people = OrderedDict()
with(open("ieca_first_col_fake_text.txt", "rU")) as f:
    sheet = csv.DictReader(f,delimiter="\t")
    for row in sheet:
        name = row.get('name')
        if name:
            contact_information = people.setdefault(name, {})
            contact_information.setdefault('phone', set()).add(row.get('phone'))
            contact_information.setdefault('email', set()).add(row.get('email'))
            contact_information.setdefault('website', set()).add(row.get('website'))

    write_file = csv.DictWriter(open('duplicates_deleted.csv','w'), ['name','phone','email','website'], restval='', delimiter = '\t')
    for name, contact_information in people:
        row_dict = {'name': name}.update({list(contact_field) for contact_field in contact_information.values()})
        write_file.writerow(row_dict)

rawDescription: Script only prints out final entry instead of removing duplicates


rawDescription: Error while trying to interpolate across rows in pandas dataframe


code: pi

rawDescription: naming collision in namespaces in modules of python

description: Naming collision in namespaces in modules of python


code:
b = np.array([f+b for f, b in zip(foo_list, bar_list)])
b.shape
b[0]
b[0, -1]

rawDescription: How to do numpy structural arrays

description: Do numpy structural arrays


code: import this

rawDescription: How to skip or ignore python decorators

description: Skip or ignore python decorators


code:
MyDict = dict(zip(IncompleteList, MyList))

[MyDict.get(k, '') for k in CompleteList]
Out[108]: ['22', '33', '', '25', '13']

rawDescription: Include empty values in a list according to specific positions (Python)


code:
comments = Comment.objects.all()
actions = Action.objects.all()
from itertools import chain
wall = list(chain(comments, actions))

rawDescription: Order 2 different querysets by date

description: Order 2 different querysets by date


code:
for name, values in groupby(data, itemgetter(0)):
    _, first, second, *_ = zip(*values)
    print(name, max(first), min(second))

rawDescription: arrange values in a python 2D array

description: Arrange values in a python 2D array


rawDescription: Matplotlib - Resizing x-axis

description: Matplotlib - Resizing x-axis


code:
visual_props = dict(
    vertex_size = rescale(graph.degree(), out_range=(0, 10)),
    edge_width = rescale(graph.es["weight"], out_range=(0, 5), scale=log10)
)
plot(g, **visual_props)

rawDescription: How to use igraph python's metamagic class?

description: Use igraph python's metamagic class


code:
from itertools import product

for combo in product(*filter(None, yourlist)):
    print(combo)

rawDescription: getting all possible cases in Python3

description: Getting all possible cases in Python3


code:
c = collections.defaultdict(int)
for x, y in (t for x in lst for t in x):
    c[x] += y
return [(k, c[k]) for k in sorted(c, key=c.get, reverse=True)][:2]

rawDescription: What is the fastest way to combine and sort lists of tuples?


code:
import numpy as np

n_features = 10

# Make some data
A = np.random.randn(3, n_features)
B = np.random.randn(5, n_features)
C = np.random.randn(4, n_features)
D = np.random.randn(7, n_features)
E = np.random.randn(9, n_features)

# Group it
K1 = np.concatenate([A, B])
K2 = np.concatenate([C, D])
K3 = E

data = np.concatenate([K1, K2, K3])

# Make some dummy prediction target
target = np.random.randn(len(data)) > 0

# Make the corresponding labels
labels = np.concatenate([[i] * len(K) for i, K in enumerate([K1, K2, K3])])

from sklearn.cross_validation import LeaveOneLabelOut, cross_val_score

cv = LeaveOneLabelOut(labels)

# Use some classifier in crossvalidation on data
from sklearn.linear_model import LogisticRegression

lr = LogisticRegression()
scores = cross_val_score(lr, data, target, cv=cv)

rawDescription: Custom cross validation split sklearn

description: Custom cross validation split sklearn


code:
file_name = "outfile%s"
for (descr, records) in collected.items():   # iteritems in python2
    with open(os.path.join(file_path, file_name % descr), 'w') as f:
        SeqIO.write(records, f, 'fasta')

rawDescription: Extract sequences from a FASTA file to multiple files, file based on header_IDs in a separate file


code:
next(inst for inst in instances
          if all(get_key_value(inst, pkey) == kw[pkey] for pkey in primary_keys))

rawDescription: Find object in a list with multiple primary keys in Python


rawDescription: Optional closing symbol and several words capturing with regex


code: A_B = {k: dict(A.get(k, {}), **B.get(k, {})) for k in A.viewkeys() | B.viewkeys()}

rawDescription: How can I merge two nested dictionaries together?

description: Merge two nested dictionaries together


code: most_common = max(counts, key=counts.__getitem__)  # maximum by value

rawDescription: How to apply a for loop to a string in Python

description: Apply a for loop to a string in Python


rawDescription: Rendering multiple webpages in memory using QtWebKit breaks on second page, why?


code: [i.strip() for i in re.split(r'[{},[\]]',s) if i and '=' not in i]

rawDescription: Python string split multiple brackets

description: Python string split multiple brackets


code: cmap = plt.get_cmap('jet')

rawDescription: Elegant way to match a string to a random color matplotlib


rawDescription: Find the perfect square in the string

description: Find the perfect square in the string


rawDescription: Pandas: read head and middle of a file

description: Pandas: read head and middle of a file


rawDescription: Fill missing dates by group in pandas

description: Fill missing dates by group in pandas


code:
import unicodedata
unicodedata.name(u'a')
unicodedata.name(u'我')
unicodedata.name(u'今')

rawDescription: Converting unicode to Chinese

description: Converting unicode to Chinese


code:
from lxml import html
import requests

url = 'http://abcnews.go.com/US/wireStory/man-jail-writing-racist-graffiti-refugees-homes-33488053'
page = requests.get(url)

tree = html.fromstring(page.text)
p_elements = tree.cssselect('p[itemprop="articleBody"]')
print(p_elements)

rawDescription: lxml.cssselect CSSSelector doesn't support attributes

description: Lxml.cssselect CSSSelector doesn't support attributes


code:
import _thread # C-module
_allocate_lock = _thread.allocate_lock

class Condition:
    ...
    def wait(self, timeout=None):
        if not self._is_owned():
            raise RuntimeError("cannot wait on un-acquired lock")
        waiter = _allocate_lock()
        waiter.acquire()
        self._waiters.append(waiter)
        saved_state = self._release_save()
        gotit = False
        try:    # restore state no matter what (e.g., KeyboardInterrupt)
            if timeout is None:
                waiter.acquire()
                gotit = True
            else:
                if timeout > 0:
                    gotit = waiter.acquire(True, timeout)  # This calls C code
                else:
                    gotit = waiter.acquire(False)
            return gotit
        finally:
            self._acquire_restore(saved_state)
            if not gotit:
                try:
                    self._waiters.remove(waiter)
                except ValueError:
                    pass

class Event:
    def __init__(self):
        self._cond = Condition(Lock())
        self._flag = False

    def wait(self, timeout=None):
        self._cond.acquire()
        try:
            signaled = self._flag
            if not signaled:
                signaled = self._cond.wait(timeout)
            return signaled
        finally:
            self._cond.release()

rawDescription: Python time.sleep() vs event.wait()

description: Python time.sleep() vs event.wait()


code:
cokeprice = 1
mdmaprice = 1
speedprice = 1
weedprice = 1
heroinprice = 1
pillsprice = 1

rawDescription: Python text game code review. I'm not using my classes and i think i've got too many embedded loops


code: ''.join(chr(i^j) for i,j in zip(s1,s2))

rawDescription: Xor bits in python

description: Xor bits in python


code:
def guess(start,limit):
    return random.randint(start, limit)

rawDescription: List index out of range even though I'm asking for [0]?


rawDescription: Creating an sqlite database with a diff file


code:
import datetime
a = datetime.date(2011, 2, 8)
b = datetime.date(2010, 5, 14)
months(a, b)
b = datetime.date(2010, 5, 30)
months(a, b)

rawDescription: Subtract dates in Django?

description: Subtract dates in Django


code:
import code, dis
c = code.compile_command('x = []; x.append("foo")')
dis.disassemble(c)

rawDescription: What is a .pyc_dis file?

description: What is a .pyc_dis file


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

def main():
    data = [[np.random.normal(i, 1, 30) for i in range(2)],
            [np.random.normal(i, 1.5, 30) for i in range(3)],
            [np.random.normal(i, 2, 30) for i in range(4)]]

    fig, ax = plt.subplots()
    groups = grouped_boxplots(data, ax, max_width=0.9,
                              patch_artist=True, notch=True)

    colors = ['lavender', 'lightblue', 'bisque', 'lightgreen']
    for item in groups:
        for color, patch in zip(colors, item['boxes']):
            patch.set(facecolor=color)

    proxy_artists = groups[-1]['boxes']
    ax.legend(proxy_artists, ['Group A', 'Group B', 'Group C', 'Group D'],
              loc='best')
    ax.set(xlabel='Year', ylabel='Performance', axisbelow=True,
           xticklabels=['2012', '2013', '2014'])

    ax.grid(axis='y', ls='-', color='white', lw=2)
    ax.patch.set(facecolor='0.95')
    plt.show()

def grouped_boxplots(data_groups, ax=None, max_width=0.8, pad=0.05, **kwargs):
    if ax is None:
        ax = plt.gca()

    max_group_size = max(len(item) for item in data_groups)
    total_padding = pad * (max_group_size - 1)
    width = (max_width - total_padding) / max_group_size
    kwargs['widths'] = width

    def positions(group, i):
        span = width * len(group) + pad * (len(group) - 1)
        ends = (span - width) / 2
        x = np.linspace(-ends, ends, len(group))
        return x + i

    artists = []
    for i, group in enumerate(data_groups, start=1):
        artist = ax.boxplot(group, positions=positions(group, i), **kwargs)
        artists.append(artist)

    ax.margins(0.05)
    ax.set(xticks=np.arange(len(data_groups)) + 1)
    ax.autoscale()
    return artists

main()

rawDescription: Pyplot boxplots centered around xticks

description: Pyplot boxplots centered around xticks


code:
def __call__(self, cls):
    def init(cls_self, *args, **kw):
        if len(args)+len(kw) != len(self.params):
            raise RuntimeError("Wrong number of arguments")
        for param, value in zip(self.params, args):
            setattr(cls_self, param, value)
        vars(cls_self).update(kw)
    cls.__init__ = init
    return cls

rawDescription: Create a python function procedurally (specifically the arguments)


code: grouped.apply(lambda x: linregress(x['col_X'], x['col_Y']))

rawDescription: How to apply linregress in Pandas bygroup

description: Apply linregress in Pandas bygroup


rawDescription: How to multiply python string and integer arrays

description: Multiply python string and integer arrays


code:
cursor.execute('SELECT entry FROM table')
rows = [entry for entry, in cursor.fetchall()]
#                      ^

rawDescription: Generate single-dimensional array with MySQL query


code:
class Node:
    def display(self): # Here
        if not self.children:
            return self.name

        child_strs = [child.display() for child in self.children]
        child_widths = [block_width(s) for s in child_strs]

        # How wide is this block?
        display_width = max(len(self.name),
                    sum(child_widths) + len(child_widths) - 1)

        # Determines midpoints of child blocks
        child_midpoints = []
        child_end = 0
        for width in child_widths:
            child_midpoints.append(child_end + (width // 2))
            child_end += width + 1

        # Builds up the brace, using the child midpoints
        brace_builder = []
        for i in xrange(display_width):
            if i < child_midpoints[0] or i > child_midpoints[-1]:
                brace_builder.append(' ')
            elif i in child_midpoints:
                brace_builder.append('+')
            else:
                brace_builder.append('-')
        brace = ''.join(brace_builder)

        name_str = '{:^{}}'.format(self.name, display_width)
        below = stack_str_blocks(child_strs)

        return name_str + '\n' + brace + '\n' + below

    # SNIP (your other methods)

rawDescription: Displaying a tree in ASCII

description: Displaying a tree in ASCII


rawDescription: Limit the number of sentences in a string


code:
m = MemoryManager()
with m as b:
    # __enter__ got called, set the manager to buffer mode
    # data won't store
    for i in xrange(100):
        # don't store data
        m[i] = i + 5    # in with block, so __store won't be called

pass
# __exit__ got called, __store automatically and leave buffer mode
m[0] = 10  # not in buffer mode, __store will be called

rawDescription: Python disable while iterating

description: Python disable while iterating


code:
ec2 = boto3.resource('ec2', region_name='us-west-2')

# This client is now a US-West-2 client
client = ec2.meta.client

rawDescription: How can I access a low-level client from a Boto 3 resource instance?

description: Access a low-level client from a Boto 3 resource instance


code:
Definition: Series.to_csv(self, path, index=True, sep=',', na_rep='',
float_format=None, header=False, index_label=None, mode='w', nanRep=None,
encoding=None)

rawDescription: Writing DataFrame column to a file

description: Writing DataFrame column to a file


code:
def __iter__(self):
    for key in dir(self):
        if not key.startswith("_"):
            value = getattr(self, key)
            if not callable(value):
                yield key, value

rawDescription: How can I make a custom conversion from an object to a dict?

description: Make a custom conversion from an object to a dict


rawDescription: What's the best way to read the following log file (rseqc ouput) into python (3)?


code: from mpl_toolkits.axisartist.grid_finder import MaxNLocator

rawDescription: How to change ticklabels within figure created with axisartist

description: Change ticklabels within figure created with axisartist


code:
newSentence +=  pig_latinify_word(word)
newSentence += " "

rawDescription: Python 3 Pig Latin Sentence

description: Python 3 Pig Latin Sentence


code:
df
type(df['Time'][0])
df['Time'] = df['Time'].apply(lambda x: x.replace(microsecond=0))
df

rawDescription: Python: reduce precision pandas timestamp dataframe


rawDescription: setDefault for Nested dictionary in python

description: SetDefault for Nested dictionary in python


code:
newdf = df.dropna()
result = newdf[(newdf['bookings'] - newdf['rolling_mean']) > (2 * newdf['rolling_std_dev'])]

rawDescription: How to return new data frame when using a apply function on old dataframe?

description: Return new data frame when using a apply function on old dataframe


code:
pattern = Compile(
    'a',
    Capture(
        '[bc]',
        'd+',
        'e*',
    ),
    Look_ahead('foo'),
)

rawDescription: is there need for a more declarative way of expressing regular expressions ? :)

description: Is there need for a more declarative way of expressing regular expressions ? :)


code: super_dot = lambda v, w: FB.dgemm(alpha=1., a=v.T, b=w.T, trans_b=True)

rawDescription: Is there an "enhanced" numpy/scipy dot method?


code:
dic = {'shape': ['a', 'b', 'c'], 'item1_item2_item3': ['1_2_3', '5_6_10', '3_7_9']}
new = {}
for key, value in dic.items():
    if '_' not in key:
        new[key] = value
        continue
    for new_key, new_value in zip(key.split('_'), value):
        new[new_key] = new_value.split('_')

new
{nk: (nv.split('_') if '_' in k else v)
 for k, v in dic.items() for nk, nv in zip(k.split('_'), v)}

rawDescription: split a key in a dic and its values to multiple keys/values

description: Split a key in a dic and its values to multiple keys/values


code:
import os

for filename in os.listdir(r'C:\Users\output'):
    print(filename)

rawDescription: Confused about how lists or os.listdir() work in Python 3


code:
for value in customRange(['A1', 'D1']):
    print(value)

A1
B1
C1
D1

rawDescription: Range with alphabets Python

description: Range with alphabets Python


code: number_list[2*i::i] = False

rawDescription: Array initialized with numpy is much slower in a loop with if statement


rawDescription: How do I avoid looping through an image pixel by pixel with opencv & numpy

description: Avoid looping through an image pixel by pixel with opencv & numpy


rawDescription: Conditional regular expression to split on commas


rawDescription: remove all elements in list that do not end in a number in python

description: Remove all elements in list that do not end in a number in python


rawDescription: in python, how to match Strings based on Regular Expression and get the non-matching parts as a list?

description: In python, how to match Strings based on Regular Expression and get the non-matching parts as a list