code:
#!/usr/bin/env python3

import tarfile
tarf = tarfile.open('foo.tar.gz', 'r:gz')
print(tarf.getnames())

rawDescription: How do I list contents of a gzip file without extracting it in python?

description: List contents of a gzip file without extracting it in python


rawDescription: Python - Get the min coordinate element of a 2d numpy array


code: [len(line) for line in level.split('\n')]

rawDescription: How to count lines in multi lined strings

description: Count lines in multi lined strings


code: matches = [s for s in mytext if 'foobar' in s]

rawDescription: Pythonic way of searching for a substring in a list


code: url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root':   settings.STATIC_ROOT}),

rawDescription: Django and SSL Server

description: Django and SSL Server


rawDescription: Convert string datetime format into integer time in seconds in python


rawDescription: How to print out specific values from a list

description: Print out specific values from a list


code:
from System.Windows.Controls import Button
from System.Windows.Controls.Primitives import DataGridColumnHeader

for entry in findChildren(self._gridControl, DataGridColumnHeader):
    for button in findChildren(entry, Button):
        button.Click += handler

rawDescription: Access Controls in Silverlight DataGrid Column Header from Code


rawDescription: How to read this file,with skipping some lines using Python?

description: Read this file,with skipping some lines using Python


code: contents = test[0].text_content()

rawDescription: Gathering a portion of text on a webpage


code:
import csv
import numpy as np

desired=[1,3,5]
with open('/tmp/test.csv', 'r') as fin:
    reader=csv.reader(fin)
    result=[[int(s) for s in row] for i,row in enumerate(reader) if i in desired]

print(np.array(result))

rawDescription: How do I load specific rows from a .txt file in Python?

description: Load specific rows from a .txt file in Python


code: s[start: stop : step]

rawDescription: Python: Reversing lists

description: Python: Reversing lists


code:
class Figthter:
    # init(self, name) ...

    def set_combat(combat):
        self.combat = combat

rawDescription: Pattern to access to object instance from other object instances


rawDescription: Count the occurence of specific number from column // convert column data to list


rawDescription: Python - Replace data of an array by 2 values of a second array


rawDescription: Python/Numpy subarray selection

description: Python/Numpy subarray selection


code:
dbconfig = {
  "database": "test",
  "user":     "joe"
}

cnx = mysql.connector.connect(pool_name = "mypool",
                              pool_size = 3,
                              **dbconfig)

rawDescription: How to create a mysql connection pool or any better way to initialize the multiple databases?

description: Create a mysql connection pool or any better way to initialize the multiple databases


rawDescription: How to resample an array in python

description: Resample an array in python


code:
@protect
def show(request):
   ...
   return render_to_response(...)

rawDescription: Going to another view

description: Going to another view


code: teams['Team3'] # returns an empty list

rawDescription: Alternative to Using Expression as Variable?


code:
u = User.objects.get(username='fsmith')
freds_department = u.employee.department

rawDescription: How to Access the custom column from auth_user table in Django?


code:
import sys
with open("source","r") as theFile:
    tweet = {}
    for line in theFile:
        rec_type, content = line.split('\t')
        if rec_type in tweet:
            t, u, w = tweet.get('T',''), tweet.get('U',''), tweet.get('W','')
            result=  "{0}\t{1}\t{2}".format( t, u, w )
            sys.stdout.write( result )
            tweet= {}
        tweet[rec_type]= content
    t, u, w = tweet.get('T',''), tweet.get('U',''), tweet.get('W','')
    result=  "{0}\t{1}\t{2}".format( t, u, w )
    sys.stdout.write( result )

rawDescription: Processing a huge file (9.1GB) and processing it faster -- Python


code:
A = ['x', 'x', 7]
B = [7, 'x', 'x']

for perm in perms(A, B):
    print(perm)

rawDescription: How to get all orderings of a list such that the list is equal to another list?

description: Get all orderings of a list such that the list is equal to another list


code:
numlines = 10

data = np.random.randn(150, numlines).cumsum(axis=0)
plt.plot(data)

rawDescription: Use a colourmap to change line colour

description: Use a colourmap to change line colour


rawDescription: Converting a String to Dictionary?

description: Converting a String to Dictionary


code:
#myapp/views.py:
from django_proj1.myclasses import Alphabet

rawDescription: Where to implement python classes in Django?


code: frame = wx.Frame(None, title="Test", style=wx.DEFAULT_FRAME_STYLE|wx.FULL_REPAINT_ON_RESIZE)

rawDescription: How to make a canvas (rectangle) in wxpython?

description: Make a canvas (rectangle) in wxpython


code: a[i,j]

rawDescription: matlab find() for nonzero element in python

description: Matlab find() for nonzero element in python


code:
from datetime import timedelta

minutes = 60
hours = 60 * minutes
days = 24 * hours

diff = timedelta(days=6)

days_in_the_past = int(diff.total_seconds() / days)
hours_remainder = diff.total_seconds() % days

hours_in_the_past = int(diff.total_seconds() / hours)
seconds_remainder = diff.total_seconds() % hours

rawDescription: Manipulating DateTime and TimeDelta objects in python


code:
mapp = {}
value_holder = set()
for line in f:
    k, v = line.split(None, 1)
    if v not in value_holder:
        mapp[k] = v
        value_holder.add(v)

rawDescription: More efficient way to get unique first occurrence from a Python dict


code:
import itertools

def neighbours(items, fill=None):
    """Yeild the elements with their neighbours as (before, element, after).

    neighbours([1, 2, 3]) --> (None, 1, 2), (1, 2, 3), (2, 3, None)

    """
    before = itertools.chain([fill], items)
    after = itertools.chain(items, [fill]) #You could use itertools.zip_longest() later instead.
    next(after)
    return zip(before, items, after)

def split_not_neighbour(seq, mark):
    """Split the sequence on each item where the item is not the mark, or next
    to the mark.

    split_not_neighbour([1, 0, 2, 3, 4, 5, 0], 0) --> (1, 2), (5)

    """
    output = []
    for items in neighbours(seq):
        if mark in items:
            _, item, _ = items
            if item != mark:
                output.append(item)
        else:
            if output:
                yield output
                output = []
    if output:
        yield output

rawDescription: Finding neighbors in a list

description: Finding neighbors in a list


code:
my_list = [[1, 2], [1, 2], [3, 4]]
result = [list(el) for el in set(tuple(el) for el in my_list)]

rawDescription: Removing repetitive lists in a list of list


code:
circular = []
for p in primes:
   prime_str = str(prime)
   for i in xrange(len(prime_str)):
       if int(prime_str[i:]+prime_str[:i]) not in primes:
            break
   else:
       circular.append(p)

rawDescription: Speeding up string splitting and concatenation


rawDescription: Random sampling and Pandas dataframes

description: Random sampling and Pandas dataframes


code: df['color'] = np.where(df['Set']=='Z', 'green', 'red')

rawDescription: Pandas conditional creation of a series/dataframe column


rawDescription: Scikit Learn HMM training with set of observation sequences


code:
m = max(map(hello.count, hello))
set(x for x in hello if hello.count(x) == m)

rawDescription: Python max with same number of instances


code:
import string
dict_top = dict.fromkeys(list(string.ascii_lowercase),[0])

rawDescription: first python program doesn't look right

description: First python program doesn't look right


code:
x = range(0, 100)
y = map(lambda x: x*x, x)

fig = pyplot.figure()
ax1 = fig.add_subplot(1, 1, 1)
ax1.plot(x, y, 'r.', x, y, 'r-')
xlim = ax1.get_xlim()

rawDescription: Keeping data point annotation on figure

description: Keeping data point annotation on figure


code:
from decimal import Decimal
locals = {'Decimal': Decimal, 'num': 3, 'discount': Decimal('0.1')}
eval(compile(tree, 'dummy.py', 'eval'), locals)

rawDescription: Convert ast.Num to decimal.Decimal for precision in python


code:
import subprocess

processes = subprocess.check_output(['ps', '-f', '-u', 'vinish'])
for line in sorted(processes.splitlines(), key=lambda l: int(l.split()[1])):
    print(line)

rawDescription: Any ways to collect process information?

description: Any ways to collect process information


code:
def dice_roll(sides):
    number = random.randint(1, sides)
    print(number)
    return number

rolls = {}
while True:
    sides = int(input("Which dice would you like to roll? --> "))
    rolls.setdefault(sides, []).append(dice_roll(sides))
    ...

rawDescription: Using return values from a function

description: Using return values from a function


code: Counter(w.lower() for w in re.findall(r"\w+", text))

rawDescription: Python - Number of word occurrences

description: Python - Number of word occurrences


code:
import pprint
from pymongo import MongoClient
import gridfs
client = MongoClient()
db = client.demo
fs = gridfs.GridFS(db)
fs.put('img.jpg', encoding='utf-8')
fs.list()
pprint.pprint(db['fs.files'].find_one())

rawDescription: The gridfs "list" method returns empty list with non empty collection


code:
def mkregex(rule):
    regex = r""
    for ch in rule:
        regex += rule_syntax.get(ch, ch)
    return regex

rawDescription: Python pattern matching of rules to parse text to phonemes


code:
s = """This is a string with a {variable} to fill in.
Here's a {second} one
""".format(variable="field", second="'nother")

rawDescription: Are there any equivalent for groovy """ in python?


code:
class STR(str):
    def __add__(self, other):
        print('calling __add__')
        return super().__add__(other)

STR('abc') + STR('def')

rawDescription: Why does + (plus) can concatenate two strings in Python?


code:
svm20average = []
order_function(pricex, pricey, svm20average)

rawDescription: How to design an algorithm that initializes once every 20 times it's called?

description: Design an algorithm that initializes once every 20 times it's called


code:
def rw_in_range(start, low, high):
    print(('' * start) + 'S')
    new_start=start + random_step()
    if new_start<low or new_start>high:
        return False
    rw_in_range(new_start, low, high)

rawDescription: Python: How To Recursively Simulate a Random Walk Within a Range (No Loops)


code:
{'pmid': '19587274', 'abstract': 'To successfully interact with objects in the environment, sensory evidence must\n      be continuously acquired, interpreted, and used to guide appropriate motor\n      responses. For example, when driving, a red \n', 'title': 'Domain general mechanisms of perceptual decision making in human cortex.\n'}
{'pmid': '19583148', 'abstract': 'BACKGROUND: Amyloidosis represents a group of different diseases characterized by\n      extracellular accumulation of pathologic fibrillar proteins in various tissues\n', 'title': 'Ursodeoxycholic acid for treatment of cholestasis in patients with hepatic\n      amyloidosis.\n'}

rawDescription: Match multiple patterns in a multiline string


code: (zip(*[islice(reversed(L),i,None) for i in range(j)]) for j in range(3,6))

rawDescription: Assorting elements in a list into a list of lists of specific lengths


code:
net.layers[1].blobs[0].diff.shape # >> (64, 3, 7, 7)
net.layers[1].blobs[1].diff.shape # >> (64,)

rawDescription: Finding gradient of a Caffe conv-filter with regards to input


code: value = int(value)

rawDescription: Joining a list of string digits to create an integer Python 3


code: df4 = df4.fillna(0)

rawDescription: Iterate through a dataframe to find number of times a str value appears in an array of tuples


code:
from suds.client import Client
url = 'http://localhost:7080/webservices/WebServiceTestBean?wsdl'
client = Client(url)

rawDescription: Python and SOAP

description: Python and SOAP


rawDescription: pyPdf ignores newlines in PDF file

description: PyPdf ignores newlines in PDF file


code:
filename = "/a/text/file"
input_file = open(filename)

rawDescription: Python: How do you read a chunk of text from a file without knowing how long the file actually is?


code:
def printGrid (it, columns):
    items = ['{} {}'.format (idx, item) for idx, item in enumerate (it) ]
    maxWidths = [max (4 + len (item) for item in items [col::columns] ) for col in range (columns) ]
    formatStr = ''.join ('{{:<{}}}'.format (width) for width in maxWidths)
    while True:
        if not items: break
        line = items [:columns]
        items = items [columns:]
        while len (line) < columns: line.append ('')
        print (formatStr.format (*line) )

rawDescription: Fancy String Formating

description: Fancy String Formating


rawDescription: Spark Dataframe distinguish columns with duplicated name


rawDescription: How can I put text into a dictionary with keys that have more than one value?

description: Put text into a dictionary with keys that have more than one value


code:
dt = 'UI32'
print( getattr(MaxVal, dt) )

rawDescription: retrive minimum maximum values of a ctype

description: Retrive minimum maximum values of a ctype


code:
class PinochleDeck(Deck):

    def __init__(self):
        Deck.__init__(self)
        x = 0
        for i in range(4):
            for i in range(7):
                self.pop(x)
                x += 1  #NEED TO INCREMENT EVERY TIME THROUGH!!!
            x += 6

rawDescription: Creating two copies of objects in a list


rawDescription: Python - Start a Function at Given Time

description: Python - Start a Function at Given Time


code:
class Foo(object):
    def __init__(self, *values):
        self.some_sequence = values
    def __iter__(self):
        for key in self.some_sequence:
            yield (key, 'Value for {}'.format(key))

f = Foo('bar', 'baz', 'eggs', 'ham')
dict(f)

rawDescription: Overloading __dict__() on python class

description: Overloading __dict__() on python class


code:
def save(self, force_insert=False, force_update=False, commit=True):
    m = super(CallResultTypeForm, self).save(commit=False)
    # do custom stuff
    if commit:
        m.save()
    return m

rawDescription: Overriding the save method in Django ModelForm


rawDescription: Help on Regular Expression problem

description: Help on Regular Expression problem


code:
rows_reverse = dict((v, k) for k, v in rows)
cols_reverse = dict((v, k) for k, v in cols)

rawDescription: Populate arrays in python (numpy)?

description: Populate arrays in python (numpy)


code:
from djcelery.models import PeriodicTask, CrontabSchedule

every_hours_crontab = CrontabSchedule(minute=0)
every_hours_crontab.save()

periodic_task = PeriodicTask(
    name='Call my task every hour',
    task='myproject.tasks.mytask',
    crontab=every_hours_crontab,
    args=json.dump([arg1, arg2]),
    kwargs=json.dump({'foo': 'bar'})
)
periodic_task.save()

rawDescription: Add, modify, remove celery.schedules at run time


rawDescription: For loop syntax in Python without using range() or xrange()


code:
def add_to_ui(name, age):
    p = Person(name, age)
    persons_count[person] += 1
    # add it to the UI

def remove_from_ui(person):
    persons_count[person] -= 1
    if not persons_count[person]: del persons_count[person]
    # remove from UI

rawDescription: Removing list item if not in another list - python


code:
class TitleTarget(object):
    def __init__(self):
        self.text = []
    def start(self, tag, attrib):
        self.is_title = True #if tag == 'Title' else False
        if self.is_title:
            self.text.append(u'')
    def end(self, tag):
        pass
    def data(self, data):
        if self.is_title:
            self.text[-1] += data
    def close(self):
        return self.text

rawDescription: problem with deserialization xml to objects - unwanted split by special chars

description: Problem with deserialization xml to objects - unwanted split by special chars


code: CustomAvg = Avg[Height] + Avg[Weight]

rawDescription: Evaluating nested variables with pyparsing for a DSL


code:
run_it(o, 'One')
run_it(o, 'nTwo')

rawDescription: Calling unspecified function from another file and another class


code: dateobj = datetime.datetime.strptime(inputstring, '%B %d, %Y %I:%M:%S %p').date()

rawDescription: convert a full string type time into datetime type - Python

description: Convert a full string type time into datetime type - Python


code: self.entries[15].insert(0, '15')

rawDescription: Creating an entry table on TKinter

description: Creating an entry table on TKinter


rawDescription: Pandas merge dataframes based on closest match


code:
with open("file3.txt","wb") as f:
    for row1,row2 in zip(open("file1"),open("file2")):
        f.write("%s\t%s\n"%(row1.strip(),row2.strip()))

rawDescription: Properly combining 2 different files

description: Properly combining 2 different files


rawDescription: How do I delete holidays from a Pandas series?

description: Delete holidays from a Pandas series


code:
Code
#Data setup bit - Input[1] from your notebook
#Note new name for country code country_alpha3

import pandas as pd
import numpy as np

country_data_tmp = pd.DataFrame({'country_names' : np.array(['Argentina', 'Armenia', 'Australia', 'Austria']),
                                 'country_alpha3' : np.array(['ARG','ARM','AUS','AUT']),
                                 'my_rate' : np.array([0.254, 0.3456, 0.26, 0.357])})
country_data_tmp.head()

#map drawing bit Input[2] from your notebook
#Note the changes in variable names

world_topo = r'world-countries.topo.json'

geo_data = [{'name': 'countries',
             'url': world_topo,
             'feature': 'world-countries'}]

vis = vincent.Map(data=country_data_tmp,
                  geo_data=geo_data,
                  scale=1100,
                  data_bind='my_rate',
                  data_key='country_alpha3',
                  map_key={'countries': 'id'})

vis.display()

rawDescription: Why Python Vincent map visuzalization does not map data from Data Frame?


code:
all_data = np.hstack((my_data, new_col))
#or
all_data = np.concatenate((my_data, new_col), 1)

rawDescription: How to add column to numpy array

description: Add column to numpy array


code:
import yaml
conf = yaml.load(open('conf/application.yml'))
email = conf['user']['email']
pwd = conf['user']['password']

server = smtplib.SMTP( "smtp.gmail.com", 587 ) # add these 2 to .yml as well
server.starttls()
server.login(email, pwd)

rawDescription: Hide login credentials in Python script

description: Hide login credentials in Python script


rawDescription: Namespace, argparse, and usage

description: Namespace, argparse, and usage


code:
from django.core.management.commands import makemigrations
from django.db import migrations

class Command(makemigrations.Command):
    def handle(self, *args, **kwargs):
        # Set the flag.
        migrations.MIGRATION_OPERATION_IN_PROGRESS = True

        # Execute the normal behaviour.
        super(Command, self).handle(*args, **kwargs)

rawDescription: Detect whether code is being run in the context of migrate/makemigrations command


rawDescription: Casting string/buffer data using swig wrapped typedef structs and enums in python


code:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout
from kivy.clock import Clock

energy = 100
hours = 4

class Hello(FloatLayout):
    def __init__(self,**kwargs):
        super(Hello,self).__init__(**kwargs)

        self.energy_label = Label(text = "Energy = " + str(energy), size_hint=(.1, .15),pos_hint={'x':.05, 'y':.9})
        self.time_label = Label(text = "Hours = " + str(hours), size_hint=(.1, .15),pos_hint={'x':.9, 'y':.9})
        self.name_label = Label(text = "Game", size_hint=(.1, .15),pos_hint={'x':.45, 'y':.9})
        self.main_label = Label(text = "Default_text", size_hint=(1, .55),pos_hint={'x':0, 'y':.35})

    #Main Buttons
        self.inventory_button = Button(text = "Inventory", size_hint=(.3, .1),pos_hint={'x':.65, 'y':.2})
        self.help_button = Button(text = "Help", size_hint=(.3, .1),pos_hint={'x':.65, 'y':.1},on_press = self.update)
        self.craft_button = Button(text = "Craft", size_hint=(.3, .1),pos_hint={'x':.05, 'y':.1})
        self.food_button = Button(text = "Food", size_hint=(.3, .1),pos_hint={'x':.35, 'y':.2})
        self.go_button = Button(text = "Go", size_hint=(.3, .1),pos_hint={'x':.35, 'y':.1})
        self.walk_button = Button(text = "Walk", size_hint=(.3, .1),pos_hint={'x':.05, 'y':.2})

        self.add_widget(self.energy_label)
        self.add_widget(self.main_label)
        self.add_widget(self.time_label)
        self.add_widget(self.inventory_button)
        self.add_widget(self.help_button)
        self.add_widget(self.craft_button)
        self.add_widget(self.food_button)
        self.add_widget(self.go_button)
        self.add_widget(self.walk_button)
        self.add_widget(self.name_label)
        self.current_text = "Default"

    def update(self,event):
        self.main_label.text = "Changed to change"

class app1(App):
    def build(self):
        return Hello()
if __name__=="__main__":
     app1().run()

rawDescription: Update label's text when pressing a button in Kivy for Python


code:
ancestor_list = []
person = name
while True:
    person = find_parent(relation_dict,person)
    if person == None:
        #Top of the ancestor chain found
        break
    else:
        ancestor_list.append(person)

rawDescription: Looping dictionary values

description: Looping dictionary values


code:
#!/usr/local/bin/pypy
# EASY-INSTALL-ENTRY-SCRIPT: 'pip','console_scripts','pip'
__requires__ = 'pip'
import sys
from pkg_resources import load_entry_point

if __name__ == '__main__':
    sys.exit(
        load_entry_point('pip', 'console_scripts', 'pip')()
    )

rawDescription: Is it possible to run a pypy kernel in the Jupyter notebook?


code:
class Formation(object):
    """A formation of camels."""
    def __init__(self, camels, parent):
        self.camels = camels
        self.current_distance = 0
        self.parent = parent

    @property
    def total_distance(self):
        """The total distance."""
        return self.current_distance + self.heuristic

rawDescription: How to proceed with this python program

description: Proceed with this python program


code:
from sqlalchemy import DATE, cast

expr1 = func.sum(case([(
        and_(
            (func.convert(literal_column('DATE'), pvr_svc.due_dt) == func.convert(literal_column('DATE'), func.getdate())),
            pvr_svc.status.in_(['CLOSED','VOID'])
            ),1
        )],else_=0)).label('completed')

expr2 = func.sum(case([(
    and_(
        func.datediff(literal_column('hh'), cast(func.convert(literal_column('DATE'), func.getdate()), VARCHAR)
            +" "+"00:00:00.000",pvr_svc.due_dt)
            .between(0,12),~pvr_svc.status.in_(['CLOSED','VOID'])
        ),1)],else_=0)).label('Count_0_to_12')

session.query(expr1, expr2).all()

rawDescription: SQLAlchemy : Convert to date type

description: SQLAlchemy : Convert to date type


code:
import requests
import csv
from bs4 import BeautifulSoup

BASE_URL = 'http://www.expatistan.com/cost-of-living/comparison/{home_city}/{city}'
home_city = 'Phoenix'

with open('City.txt') as input_file:
    with open("Expatistan.csv", "w") as output_file:
        writer = csv.writer(output_file)
        writer.writerow(["City", "Food", "Housing", "Clothes", "Transportation", "Personal Care", "Entertainment"])
        for line in input_file:
            city = line.strip()
            url = BASE_URL.format(home_city=home_city, city=city)
            soup = BeautifulSoup(requests.get(url).text)

            table = soup.find("table", class_="comparison")
            differences = []
            for title in table.find_all("tr", class_="expandable"):
                percent_difference = title.find("th", class_="percent")
                if "expensiver" in percent_difference.span['class']:
                    differences.append('+' + percent_difference.span.string)
                else:
                    differences.append('-' + percent_difference.span.string)
            writer.writerow([city] + differences)

rawDescription: Python - Web Scraping - BeautifulSoup & CSV


rawDescription: Python - directed edge list to dictionary of dictionaries


rawDescription: Collecting data in loop using Pythons Pandas Dataframe


code:
class OtherModel(PrintableModel): pass

class SomeModel(PrintableModel):
    value = models.IntegerField()
    value2 = models.IntegerField(editable=False)
    created = models.DateTimeField(auto_now_add=True)
    reference1 = models.ForeignKey(OtherModel, related_name="ref1")
    reference2 = models.ManyToManyField(OtherModel, related_name="ref2")

rawDescription: Convert Django Model object to dict with all of the fields intact


code:
import MySQLdb
db = MySQLdb.connect(host="host", user="username", passwd="your-pass", db="the-db-name")

rawDescription: What is the process for using MySQL from Python in Windows?


rawDescription: Method to get the max distance (step) between values in python?


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

with open("pom.xml") as f:
    xmlstring = f.read()

# Remove the default namespace definition (xmlns="http://some/namespace")
xmlstring = re.sub(r'\sxmlns="[^"]+"', '', xmlstring, count=1)

pom = ET.fromstring(xmlstring)
print(pom.findall("version"))

rawDescription: Python ElementTree default namespace?

description: Python ElementTree default namespace


code:
def genoutput(iterable):
    for line in iterable:
        first, second = (l.strip() for l in line.split('->'))
        for value in second.split(','):
            yield first + value.strip()

rawDescription: Extraction of variables from text, with completely different formatting, using Python


code: lines

rawDescription: Count lines matching different patterns in one pass


code:
list1 = ["well", "455", "antifederalist", "mooooooo"]

next(s for s in list1 if len(s) == 3)

rawDescription: Get string of certain length out of a list


rawDescription: How to sort tire sizes in python

description: Sort tire sizes in python


rawDescription: Numpy indexing multidimensional arrays with array and slice


code:
data = [('a','b'),('b','a'),('c','d')]
data = [tuple(sorted(x)) for x in data]
from collections import Counter
c = Counter(data)
c

rawDescription: Reducing a list of repeated tuples and counting repeats


rawDescription: converting an int to a list containing the int

description: Converting an int to a list containing the int


code:
import json
import sys
from collections import MutableMapping, MutableSequence
from decimal import Decimal

def convert_decimal(json_data):
    stack = [json_data]
    while stack:
        json_data = stack.pop()
        if isinstance(json_data, MutableMapping): # json object
            it = json_data.items()
        elif isinstance(json_data, MutableSequence): # json array
            it = enumerate(json_data)
        else: # scalar data
            continue

        for k, v in it:
            if isinstance(v, Decimal):
                json_data[k] = str(v)
            else:
                stack.append(v)

# convert inplace
convert_decimal(data)
json.dump(data, sys.stdout, indent=2)

rawDescription: Convert python decimal to string in deeply nested and unpredictable list


rawDescription: Extarct particulr part of json string using python regex


code:
#!/usr/bin/env python

import sys, os
import curses

output = sys.stdin.readline(100)

# We're finished with stdin. Duplicate inherited fd 3,
# which contains a duplicate of the parent process' stdin,
# into our stdin, at the OS level (assigning os.fdopen(3)
# to sys.stdin or sys.__stdin__ does not work).
os.dup2(3, 0)

# Now curses can initialize.
screen = curses.initscr()
screen.border(0)
screen.addstr(12, 25, output)
screen.refresh()
screen.getch()
curses.endwin()

rawDescription: Linux: Pipe into Python (ncurses) script, stdin and termios


code: res = ( (t, nt(*t)) for t in pairs )

rawDescription: Pairwise Set Intersection in Python

description: Pairwise Set Intersection in Python


code:
#!/usr/bin/env python3
newFile = open('tests.new','r')
tNew = newFile.read()
# mail
mail = open('mail.txt', 'w', encoding='utf8')
mail.write("New files in module \n")

# BAD PART - FIXED
lines = tNew.split('\n')
i = len(lines)
z = 0
while z < i:
    mail.write(str(lines[z] + '\n'))
    z += 1
mail.close()
newFile.close()

rawDescription: Add '\n' to each line of an open file in Python


code: df['ORG1'][mask] = df['ORG2'][mask]

rawDescription: Moving row values between columns based on other column values in a Pandas DataFrame


rawDescription: associating entries from one pandas data frame to a second one based on time

description: Associating entries from one pandas data frame to a second one based on time


code:
tbl = str.maketrans(' \n', '__')
'a b c\n'.translate(tbl)

rawDescription: Remove space and newlines in pandas columns using idiomatic Python?


code:
df['DateTime'] = pd.to_datetime(df['DateTime'])
df['hours'], df['minutes'] = df['DateTime'].dt.hour, df['DateTime'].dt.minute

rawDescription: Speed up Pandas DateTime variable

description: Speed up Pandas DateTime variable


code:
n = '0xA5423'
n = '0x{:04x}'.format(int(n, 16) & 0xffff)  # => '0x5423'
field = bitstring.BitArray(n)
field[0:4].uint
field[4:12].uint  # 0x42 == 66
field[12:14].uint
field[14:16].uint

rawDescription: Extract bitfields from an int in Python

description: Extract bitfields from an int in Python


code: data['beta']

rawDescription: Python table titles into dictionary

description: Python table titles into dictionary


code:
url(
    regex=r'^account/login/$',
    view=login,
    kwargs={'template_name': 'login.html'}, # NOT  template_name='login.html'
    name='login'
)

rawDescription: url patterns like in two scoops of django

description: Url patterns like in two scoops of django


code:
def minQty(*args):
    return min(args, key=lambda d: d['qty'])

rawDescription: Comparing value of same key between multiple dictionaries


code:
def subDigits3(n, a, b):
    return int(str(n)[a:n])

rawDescription: Is using `str` the correct idiom for working with digits in Python


code:
newtext=""
for row in csv.reader(s.split("\n")):
    newtext+=','.join(row[:5])+","+str(row[5].split(",")[0])+"\n"
print(newtext)

rawDescription: Removing text from field in Mongodb with Python


code:
def msg_generator(self):
    ''' Provides messages until bot dies '''
    while self.alive:
        for msg in self.irc.recv(self.buffer).split(('\r\n').encode()):

            if not len(msg) > 3:
                continue

            yield handle_message(msg)

def handle_message(msg):
    try:
        return Message(msg.decode())
    except Exception as e:
        self.log('%s %s\n' % (except_str, str(e)))

rawDescription: My code nests too deep. Is there a better way?


rawDescription: Resizing matrix getting rid of 0 entries - Python


code:
def movingaverage(interval, window_size):
    window = numpy.ones(int(window_size))/float(window_size)
    return numpy.convolve(interval, window, 'same')

rawDescription: Finding moving average from data points in Python


code: Record = collections.namedtuple('Record', keys)

rawDescription: 'Zip' dictionary of lists in Python

description: 'Zip' dictionary of lists in Python


rawDescription: How to see the "hidden" python built-in?

description: See the "hidden" python built-in


rawDescription: Python logical or operator acting strange


code:
import os

documents = []

for f in os.listdir():
    if f[-4:] == '.txt':
        documents.append(f[:-4])

rawDescription: Python: How to read a directory of texts into a list


code:
def player(l):
    a = b = l[0]
    for v in l[1:]:
        a, b = b, min(a, b) + v
    return b

rawDescription: Need Help Writing Recursive function that find cheapest route through a list of numbers


rawDescription: All possible pairs of factors

description: All possible pairs of factors


rawDescription: Python: Compare dict with a static reference?


rawDescription: How to control windows master audio in python script

description: Control windows master audio in python script


code:
from itertools import chain
list1 = [{'Age': 10, 'id': '123', 'Name': 'Sam'}, {'Age': 10, 'id': '124', 'Name': 'Ajay'}]
list2 = [{'id': '123', 'Name': 'Sam'}, {'id': '124', 'Name': 'Ajay'}, {'id': '125', 'Name': 'Ram'}]
per_id = {}
for info in chain(list1, list2):
    per_id.setdefault(info['id'], {}).update(info)
list(per_id.values())

rawDescription: How to remove a json string from list in python

description: Remove a json string from list in python


rawDescription: In numpy, what is the fastest way to multiply the second dimension of a 3 dimensional array by a 1 dimensional array?


code: subprocess.Popen('cmd /C for /l %i in (5,1,255) do start /B ping -w 1 -n 1 192.168.0.%i | find /i "Reply"', stdout=subprocess.PIPE)

rawDescription: How to run complicated batch command using "subprocess"

description: Run complicated batch command using "subprocess"


rawDescription: Count number of elements in each row in 2D list


code:
from collections import defaultdict

d=defaultdict(list)
for i,j,k in li:
  d[i,j].append(k)

d

rawDescription: Reduce list of lists if entries match

description: Reduce list of lists if entries match


rawDescription: Python 2.7: "import time" Where is python importing this time module from?


code:
for i in range(num_workers):
    p=pool.apply_async(f, args=(i,))
    p.get()

rawDescription: My python multiprocessing program runs the worker programs sequentially


code:
ones.name, twos.name, finished.name = 'one', 'two', 'Finish'
counts = pd.concat([ones, twos, finished], axis=1)
counts
total = counts.fillna(0).cumsum()
total

rawDescription: Convert a list of timestamped state columns into a time-indexed list for each state during that time, as told with Chutes and Ladders


code:
# brings a reference to the x, y, and z attributes of bar (x and y
# come in turn from foo, though that's not relevant to the import;
# it just cares that bar has x, y, and z attributes), in to the
# namespace of baz
from bar import x, y, z
# won't work, because foo is a member of bar, not a submodule
import bar.foo
# will work, for the same reason that importing x, y, and z work
from bar import foo

rawDescription: Importing "sub" modules to be own "sub" modules


code:
def get_value():
   return 5

def print_value(x):
   print(x)

temporary_variable = get_value()

print_value(temporary_variable)

rawDescription: Python/Pygame: How do you take output from a function and use it as input for another?


code:
with open('mapping.txt') as mapfile:
    mapping = {}
    for line in mapfile:
        if line.strip():
            key, value = line.split(None, 1)
            mapping[key] = value

rawDescription: Python program that generate a list from a given list according to a mapping


code:
import base64

base64.b64decode("L2ZpbG0vZmljaGVmaWxtX2dlbl9jZmlsbT0yMjY2NDQuaHRtbA==")

rawDescription: Crawler and "hidden" link

description: Crawler and "hidden" link


rawDescription: python regex, only digit between whitespaces

description: Python regex, only digit between whitespaces


code:
class AllVMeta(type):
    def __new__(typ, name, bases, attrs):
        cls = super(AllVMeta, typ).__new__(typ, name, bases, attrs)
        cls.ALL_V_ELEMENTS = cls.V_1 | cls.V_2
        return cls
class Parent(object, metaclass=AllVMeta):
    V_1 = set()
    V_2 = set()
class Child1(Parent):
    V_1 = {1, }
    V_2 = {4, 7, 10}
class Child2(Parent):
    V_1 = {'a', 'b'}
    V_2 = {'a', 'c'}
Child1.ALL_V_ELEMENTS
Child2.ALL_V_ELEMENTS

rawDescription: Class variable V3 dependent on V1 and V2. How to define V3 in children classes


code: labels = al_df.NAME.values[:]

rawDescription: plotting & formatting seaborn chart from pandas dataframe

description: Plotting & formatting seaborn chart from pandas dataframe


rawDescription: Why is subprocess.call("""scp foo""") broken?


rawDescription: How to find the sum of number layer in ndarray

description: Find the sum of number layer in ndarray


code:
x = get_num("test") # normal int
x = get_num("foo", float)

rawDescription: Changing global variables within a function


code: from ..subpackage2 import module2b

rawDescription: Is it really possible to use a different convention to lay out source directory without breaking intra-package references?


rawDescription: python regex using re.compile and match

description: Python regex using re.compile and match


code:
index('bar', 'foo') is None
index('barfoo', 'foo')
index('\xbarfoo', 'foo')

rawDescription: is there a way find substring index through a regular expression in python?

description: Is there a way find substring index through a regular expression in python


code: x1, res, rnk, s = np.linalg.lstsq(A, b)

rawDescription: How can I obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy?

description: Obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy


code:
class Team(models.Model):
    ...
    url = models.URLField(blank=True)

rawDescription: How can I extend a django admin widget so it's still optional?

description: Extend a django admin widget so it's still optional


code:
seen_qs = Seen.objects.filter(user=request.user)
replies_qs = Reply.objects.prefetch_related(
    Prefetch('seen_set', queryset=seen_qs)
)

rawDescription: How to annotate a related object to queryset, in cases it exists, and None otherwise? (Django)

description: Annotate a related object to queryset, in cases it exists, and None otherwise? (Django)


code:
try:
    rest = s.split('|', 5)[5]
except IndexError:
    rest = ''

rawDescription: Find the sub-string after nth '|'

description: Find the sub-string after nth '|'


code: [key for key,value in sorted(dic.items() ,key=lambda x : x[1]) if value < threshold]

rawDescription: in Python, dictionary sort by value, but only return key

description: In Python, dictionary sort by value, but only return key


rawDescription: Auto increment of Concatenated alpha-numeric. (Python)


code: (item for item in iterable if function(item))

rawDescription: Python 3.4 nested loop using lambda filter working weirdly


code:
### Constructing a tuple ad-hoc. Easy to read/understand, but doesn't scale.
# Note lack of index 1.
b = word in (wordList[0], wordList[2], wordList[3], wordList[4])

### Playing around with iterators. Scales, but rather hard to understand.
from itertools import chain, islice
b = word in chain(islice(wordList, None, 1), islice(wordList, 2, None))

### More efficient, if condition is to be evaluated many times in a loop.
from itertools import chain
words = frozenset(chain(wordList[:1], wordList[2:]))
b = word in words

rawDescription: python check if word is in certain elements of a list

description: Python check if word is in certain elements of a list


rawDescription: Whats the best way to iterate over multidimensional array and tracking/doing operations on iteration index


code:
import site
site._Helper.__call__ = lambda self, *args, **kwargs: partialhelper(*args, **kwargs)

rawDescription: Allow help() to work on partial function object


code:
repr(example)
print(repr(example))

rawDescription: Escape string to be valid python expression


code:
import subprocess

def get_stdout(cmd):
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    result = []
    line = p.stdout.readline()
    while line != '':
        tag = line.split(' ')[0]
        print(tag)
        line = p.stdout.readline()
get_stdout('show images')

rawDescription: How do I capture a specific word on a bash screen using Python?

description: Capture a specific word on a bash screen using Python


code:
def outer():
    data = [0]
    def inner():
       data[0] += 1
    inner()
    return data[0]
outer()

rawDescription: Scope of nested function declarations

description: Scope of nested function declarations


code:
#Keyboard events
events = pygame.event.get()
for event in events:
    if event.type == pygame.QUIT:
        running = 0

#Mouse events
#todo

#Grid update  <------- here you update the grid and the cells are being drawn
cb.draw()

#Graphical output    <------------ here you're filling the WHOLE screen with white
screen.fill(THECOLORS["white"])

pygame.display.flip()

rawDescription: Pygame doesn't draw

description: Pygame doesn't draw


rawDescription: Pandas Group Columns into Level

description: Pandas Group Columns into Level


code:
rows = [{'Type': 'Vegetable', 'Name': 'Lettuce', 'Application': 'StoreA'},
        {'Type': 'Fruit', 'Name': 'Apple', 'Application': 'StoreB'},
        {'Type': 'Vegetable', 'Name': 'Orange', 'Application': 'StoreB'},
        {'Type': 'Fruit', 'Name': 'Pear', 'Application': 'StoreC'},
        {'Type': 'Dairy', 'Name': 'Milk', 'Application': 'StoreA'},
        {'Type': 'Fruit', 'Name': 'Plum', 'Application': 'StoreB'},
        {'Type': 'Fruit', 'Name': 'Plum', 'Application': 'StoreA'}]

rawDescription: How to convert CSV to a more structured dictionary in python?

description: Convert CSV to a more structured dictionary in python


code: boolean_enum = Enum('boolean_enum', [('True', True), ('False', False)])

rawDescription: Python Enum for Boolean variable

description: Python Enum for Boolean variable


code:
class IndexHandler(tornado.web.RequestHandler):

    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self):
        client = tornado.httpclient.AsyncHTTPClient()
        response = yield tornado.gen.Task(client.fetch, "http://twitter.com/",
                                        **config)
        if response.error:
            self.write("Error: %s" % response.error)
        else:
            self.write(response.body)

        self.finish()

rawDescription: Tornado - How to get response of AsynHTTPClient.fetch()?


code:
def modified_integrand(xs):
    x, y = xs
    if norm.ppf(0.001, x, 3) < y < norm.ppf(0.999, x, 3):
        return integrand(xs) # the actual integrand
    else:
        return 0.0

rawDescription: efficiently caclulating double integral

description: Efficiently caclulating double integral


code:
for m in re.finditer('ga_group_create(.*?)ga_group_create', contents, options):
    print(m.groups(0)[0].split())

rawDescription: A rather special parsing of a txt file

description: A rather special parsing of a txt file


rawDescription: Points, Vectors, Dot Product & Cross Product of python


code:
enums = Task.priority.type.enums  # finds the Enum tuple (with the same order you originally gave it)
whens = {priority: index for index, priority in enumerate(enums)}  # dynamically creates whens dict based on the order of the Enum tuple

rawDescription: Specify the sort-order for an Enum field type


code:
import datetime

def chop_microseconds(delta):
    return delta - datetime.timedelta(microseconds=delta.microsecond)

rawDescription: Python timedelta remove microseconds

description: Python timedelta remove microseconds


code:
if "=" in line:
    param, value = line.split("=",1)

rawDescription: Python - how to remove the left part of a string?


rawDescription: Converting column from int64 to datetime in hdf5 file using Python's Pandas package


code: chkseq = [int(line) for line in open("sequence.txt")]

rawDescription: strip ' from all members in a list

description: Strip ' from all members in a list


code:
for curfile in files:
    with open(curfile, 'r+') as infile:
        content = infile.read()
        processed_content = processContent(content)
        infile.truncate(0)   # truncate the file to 0 bytes
        infile.seek(0)       # move the pointer to the start of the file
        infile.write(processed_content)

rawDescription: Reading and writing to files in the same iteration


rawDescription: pandas asfreq returns NaN if exact date DNE

description: Pandas asfreq returns NaN if exact date DNE


code:
import threading
import time

def thread_main():
    time.sleep(10)
t = threading.Thread(target=thread_main)
t.start()
t.join()

rawDescription: Difference between thread.join and thread.abort in python multithreading


code:
class Foo(object):
    def method_one(self, query):
        # Big nasty query that hits the database really hard!!
        return query.all()

rawDescription: Mocks or Stubs?

description: Mocks or Stubs


code:
class DomTreeItem(TreeItem):
    def OnDoubleClick(self):
        if self.GetText() == "level1":
            node2.expand()
            node2.children[0].expand()
            node2.children[0].children[0].select()

[...]

class Application(Frame):
    def __init__(self, parent):
        global node2

rawDescription: Python Tkinter: Tree selection

description: Python Tkinter: Tree selection


code:
from pyroc import *
random_sample  = random_mixture_model()  # Generate a custom set randomly

#Example instance labels (first index) with the decision function , score (second index)
#-- positive class should be +1 and negative 0.
roc = ROCData(random_sample)  #Create the ROC Object
roc.auc() #get the area under the curve
roc.plot(title='ROC Curve') #Create a plot of the ROC curve

rawDescription: Library in python for neural networks to plot ROC, AUC, DET


rawDescription: Delete unusable characters or data in archive with python


code:
class RandomString(object):
    def __init__(self, regex):
        self.possible_strings = list(invRegex.invert(regex))
    def random_string(self):
        return random.choice(self.possible_strings)

rawDescription: Is there a lib to generate data according to a regexp? (Python or other)


code:
def search_s(utest, in_str):
  s = utest.selenium
  s.type('q', in_str)
  s.click('btnG')
  s.wait_for_page_to_load('30000')
  utest.assertEqual("%s - Google Search" % (in_str,), s.get_title())

rawDescription: Selenium, with Python, how to simplify scripts so that I can run them from other python scripts?


code:
r = ['text' + str(i) + '.txt' for i in range(19, 22)]
[x for x in words if x in r]

rawDescription: Python regex equivalent of bash's {1..4}


code:
s = ','.join(str(i) for i in range(10))
s
t = [int(i) for i in s.split(',')]
t
p = zip(t[::2], t[1::2])
p

rawDescription: Pythonic way to split comma separated numbers into pairs


rawDescription: Getting a list of all subdirectories in the current directory


code:
import pandas as pd
import numpy as np
np.random.seed(1)

def combine64(years, months=1, days=1, weeks=None, hours=None, minutes=None,
              seconds=None, milliseconds=None, microseconds=None, nanoseconds=None):
    years = np.asarray(years) - 1970
    months = np.asarray(months) - 1
    days = np.asarray(days) - 1
    types = ('<M8[Y]', '<m8[M]', '<m8[D]', '<m8[W]', '<m8[h]',
             '<m8[m]', '<m8[s]', '<m8[ms]', '<m8[us]', '<m8[ns]')
    vals = (years, months, days, weeks, hours, minutes, seconds,
            milliseconds, microseconds, nanoseconds)
    return sum(np.asarray(v, dtype=t) for t, v in zip(types, vals)
               if v is not None)

def year(dates):
    "Return an array of the years given an array of datetime64s"
    return dates.astype('M8[Y]').astype('i8') + 1970

def month(dates):
    "Return an array of the months given an array of datetime64s"
    return dates.astype('M8[M]').astype('i8') % 12 + 1

def day(dates):
    "Return an array of the days of the month given an array of datetime64s"
    return (dates - dates.astype('M8[M]')) / np.timedelta64(1, 'D') + 1

N = 10
df = pd.DataFrame({
   'start': pd.date_range('2000-1-25', periods=N, freq='D'),
   'months': np.random.randint(12, size=N)})
start = df['start'].values
df['new_date'] = combine64(year(start), months=month(start) + df['months'],
                           days=day(start))

print(df)

rawDescription: Pandas: Quickly add variable number of months to a timestamp column


code:
dt1=np.dtype({"names"   : columns, "formats" : ['i'] + ['int'] * (len(columns) - 1)})
mat2=np.empty((x,),dtype=dt1)

rawDescription: How to initialize NumPy structured array with different default value for each column?

description: Initialize NumPy structured array with different default value for each column


code:
from ctypes import *
from ctypes import wintypes as win

kernel32 = windll.kernel32

GetModuleHandleA = kernel32.GetModuleHandleA
GetModuleHandleA.argtypes = [win.LPCSTR]
GetModuleHandleA.restype = win.HMODULE

GetProcAddress = kernel32.GetProcAddress
GetProcAddress.argtypes = [win.HMODULE,win.LPCSTR]
GetProcAddress.restype = c_void_p

h_kernel32 = GetModuleHandleA(b'kernel32')
load_address = GetProcAddress(h_kernel32, b'LoadLibraryA')
print('{:016X}'.format(h_kernel32))
print('{:016X}'.format(load_address))

rawDescription: How to get the address of LoadLibraryA in Windows XP with Python 3?

description: Get the address of LoadLibraryA in Windows XP with Python 3


code:
input_values = []
for i in range(1, number_of_values + 1):
  input_values.append(self.request.get('input_%d' % i))

rawDescription: Accessing unknown query arguments in Python


rawDescription: python pandas dataframe to csv exporting a formatted text file with unique formats for each column

description: Python pandas dataframe to csv exporting a formatted text file with unique formats for each column


code:
data = np.array([i*np.ones((5,5,3)) for i in range(10)], dtype=np.float64)
data.shape
img = data[0]
img
img.shape
img = data[7]
img
img.shape

rawDescription: Python - read images into image matrix

description: Python - read images into image matrix


code: x = None if x == 'None' else x

rawDescription: Is there a simple way to convert the string "None" to a proper None variable in python?


rawDescription: In Django, how could I in a single query get total row count based on distinct field values?


code:
# construct the top level widget
widget = QWidget()
# construct the top level layout
layout = QVBoxLayout(widget)

# create the widgets to add to the layout
button = QPushButton('My Button')
lineedit = QLineEdit()

# add the widgets to the layout
layout.addWidget(button)
layout.addWidget(lineedit)

# set the layout on the widget
widget.setLayout(layout)
# we now have a single widget that contains a layout and 2 widgets

rawDescription: how to put widgets inside a PyQt QMdiSubWindow

description: Put widgets inside a PyQt QMdiSubWindow


code: b.sort(key = lambda x: a.index(x) )

rawDescription: Python : How to remove duplicate lists in a list of list?


code: from bs4 import BeautifulSoup

rawDescription: python BeautifulSoup soup.findAll(), how to make search result match

description: Python BeautifulSoup soup.findAll(), how to make search result match


code:
print(d['var1'])
'foo'

rawDescription: Python 3.x - How to get the contents of the variables from the file


code:
fig, ax = plt.subplots(1, 1)
ax.hold(True)

# plot the interpolated values as a heatmap
im = ax.pcolormesh(phi_itp, theta_itp, d_itp, cmap=plt.cm.coolwarm)

# plot the original data on top as a colormapped scatter plot
p, t = np.meshgrid(phi, theta)
ax.scatter(p.ravel(), t.ravel(), s=60, c=d.ravel(), cmap=plt.cm.coolwarm,
           norm=norm, clip_on=False)

ax.set_xlabel('$\Phi$', fontsize='xx-large')
ax.set_ylabel('$\Theta$', fontsize='xx-large')
ax.set_yticks(np.linspace(0, np.pi, 3))
ax.set_yticklabels([r'$0$', r'$\frac{\pi}{2}$', r'$\pi$'], fontsize='x-large')
ax.set_xticks(np.linspace(0, 2*np.pi, 5))
ax.set_xticklabels([r'$0$', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{4}$',
                    r'$2\pi$'], fontsize='x-large')
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(0, np.pi)
cb = plt.colorbar(im)
cb.set_label('Voltage', fontsize='x-large')
fig.tight_layout()

rawDescription: Attaching intensity to 3D plot

description: Attaching intensity to 3D plot


code:
r = csv.reader([s])
list(r)

rawDescription: Parse a single CSV string?

description: Parse a single CSV string


rawDescription: spark, small issue about reduceByKey

description: Spark, small issue about reduceByKey


code:
from PIL import Image
img1 = Image.open('image1.jpg')
img2 = Image.open('image2.jpg')

rawDescription: Performing Photoshop's "Luminosity" filter programmatically


rawDescription: ASCII representation of Control-Backslash in python?


code:
def upper_bit(x):
    while x & (x - 1):
        x &= x - 1
    return x

rawDescription: Removing first bit

description: Removing first bit


code:
for line in fileinput.input(hostsFileLoc,inplace =1):
    line = line.strip()
    if line != hostIP:
        sys.stdout.write(line)

rawDescription: Remove line containing specfic string

description: Remove line containing specfic string


code:
@mult.register(list)
@mult.register(tuple)
def _(it):
    return [mult(a, b) for a, b in it]

rawDescription: can a python decorator make a function able to operate on single objects and collection objects intelligently?

description: Can a python decorator make a function able to operate on single objects and collection objects intelligently


code:
def test(event):
    button_map_set(x, y)
    button_map()

btn.bind("<Button-1>", test)

rawDescription: Button parameter “command” executes when declared, but not when pressed


code:
def callback2(self,event): # called by Enter Key press
    self.end=time.time()*1000.0
    self.total_time=self.end-self.start
    print(self.total_time)
    self.pass1.bind('<Key>', self.callback1) # rebind callback1

rawDescription: Binding multiple events on Tkinter Entry?


code:
with open(fname) as f:
    data = np.genfromtxt(filter_lines(f, 8),
                         dtype='f',
                         usecols=(1, 2, 3))

rawDescription: NumPy reading file with filtering lines on the fly


code:
for row in soup.find_all('tr'):
    fragments = row.find_all('span', class_='gw2money-fragment')
    if not fragments:
        continue
    label = row.th or row.td
    print(label.text)
    for fragment in fragments:
        value = fragment.text.split()[0]
        type_ = fragment.i['class'][0].rsplit('-', 1)[-1]
        print('-', value, type_)

rawDescription: beautifulsoup find specific tags

description: Beautifulsoup find specific tags


code:
with open('Input_file_1.txt', 'r') as myfile1:
    tuples1 = myfile1.readlines()

with open('Input_file_2.txt', 'r') as myfile2:
    tuples2 = myfile2.readlines()

rawDescription: Comparing two tuples in two different file


code:
if_true = lambda: ...  # Value to return if `myCondition` is true
if_false = lambda: ...  # Value to return if `myCondition` is false

result = tf.cond(myCondition, if_true, if_false)

rawDescription: Using Tensors in control flow and conditional statements


rawDescription: Return value from button click

description: Return value from button click


code:
class DryMeta(type):
    def __new__(mcls, name, bases, attrs):
        descriptors = sorted((value, key)
                             for key, value
                             in attrs.iteritems()
                             if isinstance(value, DryDescriptor))

        for descriptor, attr in descriptors:
            descriptor.annotate(attr, attrs)

        cls = type.__new__(mcls, name, bases, attrs)
        for descriptor, attr in descriptors:
            descriptor.annotate_class(cls)

        cls._header_descriptors = [getattr(cls, attr) for descriptor, attr in descriptors]
        return cls

rawDescription: OO design: an object that can be exported to a "row", while accessing header names, without repeating myself


code:
def myLeftNeighborGenerator(data):
    for i, row in enumerate(data):
        for j, cell in enumerate(row):
            leftNeighbor = data[i][j-1] if j > 0 else None
            yield cell, leftNeighbor

rawDescription: advanced for loops

description: Advanced for loops


code: RDD.takeOrdered(5, key = lambda x: -x[1])

rawDescription: takeOrdered descending Pyspark

description: TakeOrdered descending Pyspark


code: ax.format_coord = lambda x, y: ''

rawDescription: In a matplotlib figure window (with imshow), how can I remove, hide, or redefine the displayed position of the mouse?


code: num_true = sum(d.values())

rawDescription: Counting booleans in dictionary

description: Counting booleans in dictionary


code:
inds = (index0, 0, slice(0,mesh.shape[2]), slice(0,mesh.shape[3]))
mesh[inds]

rawDescription: Building a general numpy array index dynamically


code: return any(child.contains(other_node) for child in self.children)

rawDescription: Python - How do I write a more efficient, Pythonic reduce?


code: params, pcov = optimize.curve_fit(func, A[:,:2], A[:,2], guess)

rawDescription: Fitting 3D points python

description: Fitting 3D points python


rawDescription: sorting lists in python 3

description: Sorting lists in python 3


code:
class MyClass(object):
    myfn = staticmethod(fn)

rawDescription: Convince Python to run a saved function as static


code:
test_case = ["MyClass","My","myclass","my_class","My_Class","myClass"]
[' '.join(re.findall("([A-Z]?[^A-Z]*)",e)) for e in test_case]

rawDescription: Generate verbose names from CamelCase

description: Generate verbose names from CamelCase


code:
a = test()
a.name = "setting an instance attribute"
test.name = "setting the class attribute"
b = test()
# b has no name yet, so it defaults the to class attribute
assert b.name == "setting the class attribute"

rawDescription: How to initialise class itself as class Object

description: Initialise class itself as class Object


code:
class Ui_Example(QtGui.QDialog):
    def setupUi(self, Dialog):
        self.dialog = Dialog
        Dialog.setObjectName("Dialog")
        Dialog.resize(300,143)
        self.comboBox = QtGui.QComboBox(Dialog)
        self.comboBox.setGeometry(QtCore.QRect(60,20,230,20))
        self.comboBox.setObjectName("comboBox")

        self.mouseFilter = MouseDetector()
        self.comboBox.installEventFilter(self.mouseFilter)

rawDescription: PyQt ComboBox widget not signalling when empty


rawDescription: Python extract text data in dynamic text format


rawDescription: Exploits in Python - manipulating hex strings


code:
continents = df.index[cont][cont.cumsum() - 1]
continents
df.set_index([continents, df.index], inplace=True)
df
df.dropna()

rawDescription: Promote certain rows to index in an ordered pandas dataframe


code: text[a[l]] = text[a[l]]+text[b[m]]

rawDescription: Joining Words in String In-Place

description: Joining Words in String In-Place


rawDescription: Python pandas an efficient way to see which column contains a value and use its coordinates as an offset


code:
for combo in itertools.imap(...):
    if found:
        break
    thread = ...
    thread.start()
if not found:
    ...

rawDescription: Python zipfile library fix

description: Python zipfile library fix


code:
def match(a, b):
    from itertools import chain
    m, n = len(a), len(b)
    unique = set()
    for i, j in chain(((i, 0) for i in xrange(m)),
                      ((0, j) for j in xrange(1, n))):
        k = 0
        while i < m and j < n:
            if a[i] == b[j]:
                k += 1
            elif k:
                unique.add(" ".join(a[i-k: i]))
                k = 0
            i += 1
            j += 1
        if k:
            unique.add(" ".join(a[i-k: i]))
    return unique

rawDescription: Find maximum length of all n-word-length substrings shared by two strings


code: s.replace(' - second - ', '')

rawDescription: Python 3 String Method?

description: Python 3 String Method


code:
', '.join(['One', 'Two', 'Three', 'Four'])
', '.join(['Five', 'Six', 'Seven'])

rawDescription: Getting each word from long list in python


code:
from django.db.models import Count
MemberUnit.objects.values('Unit__Unit_name').annotate(c=Count('Unit'))

rawDescription: How to perform a join and aggregate count in Django

description: Perform a join and aggregate count in Django


code:
li=[ [', , PropertyName, com.bs.ConsoleLogLevel, ', ', , Type, Integer, ', ', , Default, 3, ', ', , Description, "The logging level for outputting to console. (1 - Critical, 2 - Warning, 3 - Info, 4 - Debug, 5 - Trace)", ', ', , Sample, com.bs.ConsoleLogLevel=5, ', ', , DependsOn, com.rim.bs.ConsoleLogEnable, ', ', , Min, 1, ', ', , Max, 5, '],

    [', , PropertyName, com.rim.bs.SyslogProtocol, ', ', , Type, String, ', ', , Default, tcp, ', ', , Description, "The supported protocols are:', ' 1. udp -- The original syslog UDP protocol, pointed to 104.0.0.21 (localhost)', ' 2. tcp -- An implementation of the de-facto TCP/IP syslog protocol, which points to a TCP-capable syslog server, defaulted to 104.0.021 (localhost).', ' 3. unix_syslog -- Native syslog support for Unix platforms', ' 4. unix_socket -- Native socket support for Unix platforms, pointed to the "/var/log" socket", ', ', , Sample, com.bs.SyslogProtocol=tcp, ', ', , DependsOn, com.rim.bs.SyslogEnable, '] ]

result=[]
for l in li:
    fdict={}
    for e in l:
        if e.startswith(', ,'):
            e=e.lstrip(', ,')
            e=e.rstrip().rstrip(',')
            k, sep, v=e.partition(',')
            fdict[k]=v.strip()
        else:
            fdict['Description']+=e
    result.append(fdict)
print(result)

rawDescription: converting list of list to list of dictionaries with a special case in it

description: Converting list of list to list of dictionaries with a special case in it


code:
#!/usr/bin/env python
import os
from contextlib import contextmanager
from shutil     import rmtree
from subprocess import Popen, STDOUT
from tempfile   import mkdtemp

DEVNULL = open(os.devnull, 'wb', 0)

@contextmanager
def named_pipe():
    dirname = mkdtemp()
    try:
        path = os.path.join(dirname, 'named_pipe')
        os.mkfifo(path)
        yield path
    finally:
        rmtree(dirname)

with named_pipe() as path:
    p = Popen(['/usr/bin/time', '--format=%e seconds', '-o', path] +
              ['sleep', '1'], stdout=DEVNULL, stderr=STDOUT)
    with open(path) as file:
        time_output = file.read().strip()
    rc = p.wait()
print(time_output)

rawDescription: Python subprocess with /usr/bin/time: how to capture timing info but ignore all other output?


code: print('\a')

rawDescription: Python Sound ("Bell")

description: Python Sound ("Bell")


code:
def get_short_path_name(long_name):
    """
    Gets the short path name of a given long path.
    http://stackoverflow.com/a/23598461/200291
    """
    output_buf_size = 0
    while True:
        output_buf = ctypes.create_unicode_buffer(output_buf_size)
        needed = _GetShortPathNameW(long_name, output_buf, output_buf_size)
        if output_buf_size >= needed:
            return output_buf.value
        else:
            output_buf_size = needed

rawDescription: How to get Windows short file name in python?

description: Get Windows short file name in python


code: [type(item) for item in pd.Series(l).tolist()]

rawDescription: Reducing pandas series with multiple nan values to a set gives multiple nan values


code: newQuiz = Quiz(self)

rawDescription: PyQt4 Give Focus to Widget as it is called by the MainWindow and set as CentralWidget?


rawDescription: NLTK Brown Corpus - adding own tagged sentences


code: df.sub(df.mean(axis=1), axis=0)

rawDescription: Pandas: Subtract row mean from each element in row


code:
def do_that(self):
    return (1, 2)

rawDescription: using a variable from a method of another class in python

description: Using a variable from a method of another class in python


rawDescription: Python Scrapy, parsing multiple child objects into the same item?


code:
from operator import itemgetter
itemgetter(*indices)(values)
list(itemgetter(*indices)(values))

rawDescription: Extract list from given list and given indices


code:
import os
import re
import readline

COMMANDS = ['extra', 'extension', 'stuff', 'errors',
            'email', 'foobar', 'foo']
RE_SPACE = re.compile('.*\s+$', re.M)

class Completer(object):

    def _listdir(self, root):
        "List directory 'root' appending the path separator to subdirs."
        res = []
        for name in os.listdir(root):
            path = os.path.join(root, name)
            if os.path.isdir(path):
                name += os.sep
            res.append(name)
        return res

    def _complete_path(self, path=None):
        "Perform completion of filesystem path."
        if not path:
            return self._listdir('.')
        dirname, rest = os.path.split(path)
        tmp = dirname if dirname else '.'
        res = [os.path.join(dirname, p)
                for p in self._listdir(tmp) if p.startswith(rest)]
        # more than one match, or single match which does not exist (typo)
        if len(res) > 1 or not os.path.exists(path):
            return res
        # resolved to a single directory, so return list of files below it
        if os.path.isdir(path):
            return [os.path.join(path, p) for p in self._listdir(path)]
        # exact file match terminates this completion
        return [path + ' ']

    def complete_extra(self, args):
        "Completions for the 'extra' command."
        if not args:
            return self._complete_path('.')
        # treat the last arg as a path and complete it
        return self._complete_path(args[-1])

    def complete(self, text, state):
        "Generic readline completion entry point."
        buffer = readline.get_line_buffer()
        line = readline.get_line_buffer().split()
        # show all commands
        if not line:
            return [c + ' ' for c in COMMANDS][state]
        # account for last argument ending in a space
        if RE_SPACE.match(buffer):
            line.append('')
        # resolve command to the implementation function
        cmd = line[0].strip()
        if cmd in COMMANDS:
            impl = getattr(self, 'complete_%s' % cmd)
            args = line[1:]
            if args:
                return (impl(args) + [None])[state]
            return [cmd + ' '][state]
        results = [c + ' ' for c in COMMANDS if c.startswith(cmd)] + [None]
        return results[state]

comp = Completer()
# we want to treat '/' as part of a word, so override the delimiters
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(comp.complete)
raw_input('Enter section name: ')

rawDescription: Tab completion in Python's raw_input()

description: Tab completion in Python's raw_input()


rawDescription: Python: How to split a string of two-digit numbers into an array


code:
from itertools import product

n = 2
l = ["T","A","G","C"]

for prod in (product(l,repeat=n)):
    print("".join(prod))
TT
TA
TG
TC
AT
AA
AG
AC
GT
GA
GG
GC
CT
CA
CG
CC

rawDescription: enumeration in python for the combinations

description: Enumeration in python for the combinations


code:
df['gap'] = diffs > pd.Timedelta(seconds=60)
# In [42]: df['gap']
# Out[42]:
# 0    False
# 1    False
# 2    False
# 3    False
# 4    False
# 5    False
# 6     True
# 7     True
# Name: gap, dtype: bool

rawDescription: Group DataFrame by entries X amount of time from each other


code:
"This is an awesome string".replace("a","@")   # "This is @n @wesome string"

"This is an awesome string".replace("a","@",1) # "This is @n awesome string"

rawDescription: Conditionally format a string - Python

description: Conditionally format a string - Python


code:
monsters = {}
monsters['Monster1'] = Monster()
monsters['Monster2'] = Monster()

rawDescription: Python: Name instance based on variable

description: Python: Name instance based on variable


code: p2.legend(['label1', 'label2'])

rawDescription: Plotting pandas dataframe with string labels


code:
from threading import Thread

i = 0

def func():
    global i
    while i < 1000000:
        i += 1
        if i != i:
            print("i was modified")

for _ in range(10):
    Thread(target=func).start()

rawDescription: CPython and threading module Lock()

description: CPython and threading module Lock()


code:
results = [('7b7', 23522), ('dcd',23501), ('ccc',1)]
sorted(results, key=lambda result: result[0])

rawDescription: Can I manipulate how sorted() organizes things?

description: Manipulate how sorted() organizes things


code: map(lambda frame: frame.query(expr), [df, df2])

rawDescription: Pandas: Applying Lambda to Multiple Data Frames


code:
magic_cmds = """%cd ~/
%load_ext autosave
%autosave 30
"""
if in_ipython():
    for magic_cmd in magic_cmds.splitlines() :
        get_ipython().magic(magic_cmd[1:])

rawDescription: Keep cells or magic functions from saving to python script


code:
html = '''

1 Overview

1 Overview

1 Overview

'''
soup = BeautifulSoup(html)
a_tag = soup.find('a', attrs={'href': re.compile(r'^http.*')})

rawDescription: Webcrawler - Check if <a> tag with href is within an li tag using Beautiful soup?


code: '<Import Project="$(ProjectName).targets" />' in file_content

rawDescription: Add a line to a text file if it not exist using python


code:
def my_function(filepath):
    data = open(filepath, "r")
    ...

rawDescription: How can I pass a .txt file as a function parameter

description: Pass a .txt file as a function parameter


rawDescription: Create a bit mask

description: Create a bit mask


code:
ux, uy = np.triu_indices(10)
p[:, ux, uy] = 0
q[:, ux, uy] = 0
p[:, :, :, :, :, ux, uy] = 0
q[:, :, :, :, :, ux, uy] = 0

print ((p - q) ** 2).sum()  # euclidean distance is 0, so p and q are equal

print ((p ** 2).sum(), (q ** 2).sum())  # prove that not all entries are 0 ;) - This has a negative result due to an overflow

rawDescription: numpy multidimensional indexing and diagonal symmetries

description: Numpy multidimensional indexing and diagonal symmetries


rawDescription: Handling out of range list index in Python 2.7


code:
s = slice(-1, None, None)
s.indices(30)

rawDescription: How do I access the elements of a slice object in python

description: Access the elements of a slice object in python


code:
p = re.compile(r'(?<=\d)(?=(?:\d{3})+$)')
test_str = "2890191245"
tmp = [x.start() for x in re.finditer(p, test_str)]
res = [test_str[0: tmp[0]]] + [(test_str[tmp[i]: tmp[i] + 3]) for i in range(len(tmp))]

rawDescription: Python regular expression?

description: Python regular expression


code:
urlpatterns = patterns('',
    url(r'^new_part/other/$', include(sub_patterns)),
    url(r'^old_part/other/(?P<rest>.*)$',
        RedirectView.as_view(url='new_part/other/%(rest)s', permanent=True)),
)

rawDescription: Support old and new URI versions both working without breaking the reverse()


code:
# map each page to its correct css selector to pull the main text
d = {"dailymail.": "//div[@itemprop='articleBody']//p",
     "telegraph.": "//div[@id='mainBodyArea']//p",
     "bbc.": "//div[@class='story-body']//p",
     "independent.": "//div[@class='text-wrapper']//p",
     "www.mirror.": "//*[@class='live-now-entry' or @class='lead-entry' or @itemprop='articleBody']//p"}

import logging

logger = logging.getLogger(__file__)
logging.basicConfig()
logger.setLevel(logging.DEBUG)

def parse_links_text(links, xpath_d):
    # use regex to extract find out what page the link points to
    # so we can pull the appropriate xpath from the dict
    r = re.compile("telegraph\.|bbc\.|dailymail\.|independent\.|www.mirror.")
    for link in links:
        try:
            cont = requests.get(link).content
        except requests.exceptions.RequestException as e:
            logging.error(e.message)
            continue
        xml = fromstring(cont, HTMLParser())
        xpath = r.search(link)
        if xpath:
            p = "".join(filter(None, ("".join(p.xpath("normalize-space(.//text())"))
                                      for p in xml.xpath(xpath_d[xpath.group()]))))
            if p:
                yield p
        else:
            logger.debug("No match for {}".format(link))

rawDescription: Why does my webcrawler not follow into the next link containing keywords


code:
from gi.repository import Vips

slide = Vips.Image.new_from_file(sys.argv[1])
tile = slide.extract_area(left, top, width, height)
tile.write_to_file(sys.argv[2])

rawDescription: Extract tiles from tiled TIFF and store in numpy array


code: myfile.myVar1 = sys.argv[1]

rawDescription: How should I share a variable across different classes?


code: [['apple', 'banana', 'strawberry'], ['chicken'], ['pork'], ['beef'], ['milk'], ['chicken'], ['pork'], ['beef']]

rawDescription: How to replace one element from a list with several element from another list?

description: Replace one element from a list with several element from another list


rawDescription: Given a list of dictionaries, how can I eliminate duplicates of one key, and sort by another


code:
import pyqtgraph as pg
pg.mkQApp()

# Create remote process with a plot window
import pyqtgraph.multiprocess as mp
proc = mp.QtProcess()
rpg = proc._import('pyqtgraph')
plotwin = rpg.plot()
curve = plotwin.plot(pen='y')

# create an empty list in the remote process
data = proc.transfer([])

# Send new data to the remote process and plot it
# We use the special argument _callSync='off' because we do
# not want to wait for a return value.
data.extend([1,5,2,4,3], _callSync='off')
curve.setData(y=data, _callSync='off')

rawDescription: implementing pyqtgraph for live data graphing

description: Implementing pyqtgraph for live data graphing


rawDescription: Calculate probabilities in a probability tree


code: from requests import Session

rawDescription: Is it possible to make grequests and requests_cache work together?


code:
sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT CAN YOU DO FOR YOUR COUNTRY"
com = zlib.compress(sentence)
with open("listofwords.txt", "wb") as myfile:
    myfile.write(com)

rawDescription: How do I compress an input into a txt file?

description: Compress an input into a txt file


code:
import argparse

description = """
First Group:
  cmd1      Command 1
  cmd2      Command 2

Second Group:
  cmd3      Command 3
  cmd4      Command 4"""

parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter)
sp = parser.add_subparsers(title='commands',description=description)
sp.add_parser('cmd1')
sp.add_parser('cmd2')
sp.add_parser('cmd3')
sp.add_parser('cmd4')

parser.print_help()

rawDescription: Grouping argparse subparser arguments

description: Grouping argparse subparser arguments


code: count = len([name for name in os.listdir(DIR) if name.startswith(".")])

rawDescription: How to exclude .DS_Store from file count?

description: Exclude .DS_Store from file count


rawDescription: Finding which rows have all elements as zeros in a matrix with numpy


code:
new_lis = sorted(lis,key=lambda x : (x[0],x[2]),reverse = True) #lis is your list
new_lis

rawDescription: Sorting list of tuples based on multiple keys and returning top results


code:
from contextlib import contextmanager
import io
import os

@contextmanager
def inplace(filename, mode='r', buffering=-1, encoding=None, errors=None,
            newline=None, backup_extension=None):
    """Allow for a file to be replaced with new content.

    yields a tuple of (readable, writable) file objects, where writable
    replaces readable.

    If an exception occurs, the old file is restored, removing the
    written data.

    mode should *not* use 'w', 'a' or '+'; only read-only-modes are supported.

    """

    # move existing file to backup, create new file with same permissions
    # borrowed extensively from the fileinput module
    if set(mode) & set('wa+'):
        raise ValueError('Only read-only file modes can be used')

    backupfilename = filename + (backup_extension or os.extsep + 'bak')
    try:
        os.unlink(backupfilename)
    except os.error:
        pass
    os.rename(filename, backupfilename)
    readable = io.open(backupfilename, mode, buffering=buffering,
                       encoding=encoding, errors=errors, newline=newline)
    try:
        perm = os.fstat(readable.fileno()).st_mode
    except OSError:
        writable = open(filename, 'w' + mode.replace('r', ''),
                        buffering=buffering, encoding=encoding, errors=errors,
                        newline=newline)
    else:
        os_mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
        if hasattr(os, 'O_BINARY'):
            os_mode |= os.O_BINARY
        fd = os.open(filename, os_mode, perm)
        writable = io.open(fd, "w" + mode.replace('r', ''), buffering=buffering,
                           encoding=encoding, errors=errors, newline=newline)
        try:
            if hasattr(os, 'chmod'):
                os.chmod(filename, perm)
        except OSError:
            pass
    try:
        yield readable, writable
    except Exception:
        # move backup back
        try:
            os.unlink(filename)
        except os.error:
            pass
        os.rename(backupfilename, filename)
        raise
    finally:
        readable.close()
        writable.close()
        try:
            os.unlink(backupfilename)
        except os.error:
            pass

rawDescription: Add columns to CSV while writing the CSV


code: lst = [input("Enter word {}:".format(i)) for i in range(3)] #Change 3 to the number of elements you want to take input from user.

rawDescription: Creating a program that prints true if three words are entered in dictionary order


rawDescription: Learning python... stumped. Where is the loop in this function?


code:
Point = namedtuple('Point', 'x y')
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5)

from math import sqrt
# use index referencing
line_length = sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)
 # use tuple unpacking
x1, y1 = pt1

rawDescription: What are "named tuples" in Python?

description: What are "named tuples" in Python


code:
class TaskServer(tornado.web.Application):
    def __init__(self, newHandlers = [], debug = None):
        request_format = "(\.[a-zA-Z]+$)?"
        baseHandlers = [
            (r"/jobs" + request_format, JobsHandler),
            (r"/jobs/", JobsHandler),
            (r"/jobs/new" + request_format, NewJobsHandler),
            (r"/jobs/([0-9]+)/edit" + request_format, EditJobsHandler)
        ]
        for handler in newHandlers:
            baseHandlers.append(handler)

    tornado.web.Application.__init__(self, baseHandlers, debug = debug)

rawDescription: Rendering requested type in Tornado

description: Rendering requested type in Tornado


code:
import unittest

from ddt import ddt, data, unpack

@ddt
class TestName(unittest.TestCase):

        # simple decorator usage:
        @data(1, 2)
        def test_greater_than_zero(self, value):
            self.assertGreater(value, 0)

        # passing data in tuples to achieve the
        # scenarios from your given example:
        @data(('Bob', 'Bob'), ('Alice', 'Alice'))
        @unpack
        def test_name(self, first_value, second_value):
            name, expected_name = first_value, second_value
            self.assertEquals(name, expected_name)

if __name__ == '__main__':
        unittest.main(verbosity=2)

rawDescription: unittest - run the same test for a list of inputs and outputs

description: Unittest - run the same test for a list of inputs and outputs


code:
class webService(webapp2.RequestHandler):

    def get(self):
        self.response.headers.add_header('Access-Control-Allow-Origin', '*')
        self.response.headers['Content-Type'] = 'application/json'
        # do something

    def post(self):
        self.response.headers.add_header('Access-Control-Allow-Origin', '*')
        self.response.headers['Content-Type'] = 'application/json'
        # do something

    def options(self):
        self.response.headers['Access-Control-Allow-Origin'] = '*'
        self.response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
        self.response.headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE'

rawDescription: CORS - Using AJAX to post on a Python (webapp2) web service


code:
from IPython.html.widgets import *
from IPython.display import display

def widget_function_factory(arts):
    """
    Generate fulnction + args to pass to interactive
    Parameters
    ----------
    arts : dict
        dictionary of Line2D

    """

    name = Dropdown(options=list(arts.keys()))

    def set_all(_, old_line, new_line):
        ln = arts[new_line]
        lw.value = ln.get_lw()
        alph.value = ln.get_alpha() or 1
        visible.value = ln.get_visible()
        markevery.value = ln.get_markevery()
        marker.value = ln.get_marker()

    def set_lw(_, old_lw, new_lw):
        ln = arts[name.value]
        arts[name.value].set_lw(new_lw)
        arts[name.value].axes.legend()

    def set_alpha(_, old_value, new_value):
        ln = arts[name.value]
        ln.set_alpha(new_value)
        ln.axes.legend()

    def set_visible(_, old_value, new_value):
        ln = arts[name.value]
        ln.set_visible(new_value)
        ln.axes.legend()

    def set_markevery(_, old_value, new_value):
        ln = arts[name.value]
        ln.set_markevery(new_value)

    def set_marker(_, old_value, new_value):
        ln = arts[name.value]
        ln.set_marker(new_value)
        ln.axes.legend()

    lw = FloatSlider(min=1, max=5, description='lw: ')
    alph = FloatSlider(min=0, max=1, description='alpha: ')
    visible = Checkbox(description='visible: ')
    markevery = IntSlider(min=1, max=15, description='markevery: ')
    marker = Dropdown(options={v:k for k, v in matplotlib.markers.MarkerStyle.markers.items()},
                     description='marker: ')

    name.on_trait_change(set_all, 'value')
    lw.on_trait_change(set_lw, 'value')
    alph.on_trait_change(set_alpha, 'value')
    visible.on_trait_change(set_visible, 'value')
    markevery.on_trait_change(set_markevery, 'value')
    marker.on_trait_change(set_marker, 'value')
    display(name, lw, alph, marker, markevery, visible)
    set_all(None, None, name.value)

rawDescription: IPython Notebook/Matplotlib: Interactive show/hide graphs on a plot, is it possible?


code: WaitingUser.objects.exclude(id__in = MarkedUserIds.objects.filter(marked_user_id = {specific_one_user_id}).values_list('id', flat=True))

rawDescription: How to select users which is not paired with a custom user through many-to-one?

description: Select users which is not paired with a custom user through many-to-one


code:
main_list = [12, 10, 30, 10, 11,10, 31]
get_indices = [1, 0, 1, 1, 0, 0, 0]
result = [x for i, x in enumerate(main_list) if get_indices[i]]
result

rawDescription: Use bool list to retrieve elements from another list - Python


code:
isinstance(A, (types.FunctionType, types.BuiltinFunctionType))
isinstance(a, (types.FunctionType, types.BuiltinFunctionType))
isinstance(A.__call__, (types.FunctionType, types.BuiltinFunctionType))
isinstance(a.__call__, (types.FunctionType, types.BuiltinFunctionType))

rawDescription: How to distinguish bound method or a function from a class?

description: Distinguish bound method or a function from a class


code:
def _lcs_diff_cent(s1, s2):
    """
    Calculates Longest Common Subsequence Count Difference in percentage between two strings or lists.

    LCS reference: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem.
    Returns an integer from 0-100. 0 means that `s1` and `s2` have 0% difference, i.e. they are same.
    """
    m = len(s1)
    n = len(s2)

    if s1 == s2:
        return 0
    if m == 0: # When user given query is empty then that is like '*'' (match all)
        return 0
    if n == 0:
        return 100

    matrix = [[0] * (n + 1)] * (m + 1)
    for i in range(1, m+1):
        for j in range(1, n+1):
            if s1[i-1] == s2[j-1]:
                matrix[i][j] = matrix[i-1][j-1] + 1
            else:
                matrix[i][j] = max(matrix[i][j-1], matrix[i-1][j])

    return int( ( 1 - float(matrix[m][n]) / m ) * 100 )

rawDescription: Which data structure should I use for geocoding?


rawDescription: Is there a better way to combine multiple items in a python list


code:
import timeit
timeit.Timer('filter(lambda x: sum(x) in spectrum, lst)', 'from __main__ import lst, spectrum').repeat()
timeit.Timer('[x for x in lst if sum(x) in spectrum]', 'from __main__ import lst, spectrum').repeat()

rawDescription: How to filter a list of sublists

description: Filter a list of sublists


code:
import numpy as np
arr = np.random.rand(5,5)

# Top left 2*2 grid
np.sum(arr[:2, :2])

rawDescription: Processing a select range of values in a numpy array


code: subprocess.Popen('start cmd /C executable.exe', shell=True)

rawDescription: Executing a program from python so that it opens in separate cmd.exe window


code:
import pandas as pd
import numpy as np

np.random.seed(1)
data = pd.DataFrame({'time':np.sort(np.random.uniform(0,100,size=50)),
                     'value':np.random.uniform(-1,1,size=50)})

intervals = pd.DataFrame(
    {'interval_id':np.arange(9),
     'start_time':np.random.uniform(0,5,size=9) + np.arange(0,90,10),
     'end_time':np.random.uniform(5,10,size=9) + np.arange(0,90,10)})

def using_loop():
    data['interval_id'] = np.nan
    for index, ser in intervals.iterrows():
        in_interval = (data['time'] >= ser['start_time']) & \
                      (data['time'] <= ser['end_time'])
        data['interval_id'][in_interval] = ser['interval_id']

    result = data.merge(intervals, how='outer').sort('time').reset_index(drop=True)
    return result

def using_searchsorted():
    start_idx = np.searchsorted(intervals['start_time'].values, data['time'].values)-1
    end_idx = np.searchsorted(intervals['end_time'].values, data['time'].values)
    mask = (start_idx == end_idx)
    result = data.copy()
    result['interval_id'] = result['start_time'] = result['end_time'] = np.nan
    result['interval_id'][mask] = start_idx
    result.ix[mask, 'start_time'] = intervals['start_time'][start_idx[mask]].values
    result.ix[mask, 'end_time'] = intervals['end_time'][end_idx[mask]].values
    return result

rawDescription: Merge pandas DataFrames based on irregular time intervals


rawDescription: Using Pandas read_csv() on an open file twice


rawDescription: Obtaining an elasticsearch query from Kibana


rawDescription: Numpy: order array as other array - by string order


code:
with open("newfile.txt", "r") as f:
    sorted_data = sorted(f.readlines(), key=lambda item: int(item.strip().split("\t")[-1]))

     # No need for extra splitting and stripping now.
     # sort = [" ".join(line.strip().split("\t")) for line in sorted_data]

    for line in sorted_data:
        print(line)

rawDescription: How to sort contents of a file.txt in python numerically

description: Sort contents of a file.txt in python numerically


code:
class1 = " Jenny, 8, 1, 5, Elizabeth, 2, 7, 3,  Anna,  9, 6, 4 , Victoria,  1, 4, 6"

#Split on commas and then remove leading and trail spaces
data = [word.strip() for word in class1.split(",")]
print('Input:  ', data)

student_scores = []
for i in range(0, len(data), 4):
    #Get next name & 3 scores
    name, scores = data[i], data[i+1:i+4]
    #Convert scores in list from string to int
    scores = [int(s) for s in scores]
    #Save the name and scores, with the scores sorted from high to low
    student_scores.append((name, sorted(scores, reverse=True)))

print('Alpha:  ', sorted(student_scores))

def mean_score(student):
    scores = student[1]
    return sum(scores) / len(scores)

print('Average:', sorted(student_scores, key=mean_score, reverse=True))

rawDescription: How do I sort a text file in python?

description: Sort a text file in python


code:
import itertools as it
x=np.random.random(1e6)
y=np.random.random(1e6)
connection = oursql.connect(
    host=config.HOST, user=config.USER, passwd=config.PASS, db='test')
with connection.cursor() as cursor:
    sql='INSERT INTO foo (x,y) VALUES (?,?)'
    cursor.executemany(sql,it.izip(x,y))
    print(cursor.lastrowid)

rawDescription: Fast way to convert array to tuple/list in python?


code:
def convert(a_dict):
    return convert_dict_list([a_dict])[0]

def convert_dict_list(dict_list):
    sorted_items = (zip(*sorted(d.iteritems())) for d in dict_list)
    tmp_dict = dict((tuple(keys), map(convert_value, values))
        for (keys, values) in sorted_items)
    return map(dict, [zip(k, v) for (k, v) in tmp_dict.iteritems()])

def convert_value(val):
    return convert_dict_list(val) if isinstance(val, list) else val

rawDescription: Convert a nested dict to a dict that only include list items that has a unique set of keys


code:
class dance(object):
    dance_move=staticmethod(fish_slap)

rawDescription: Assigning functions as attributes of an object, then calling without the implied 'self' arguement?


code: [int(x) for x in MyList]

rawDescription: Mapping Int to a List - Python

description: Mapping Int to a List - Python


code:
class Eel(object):
    MAX_EELS = 20
    n_eels = 0

    def __new__(cls, *args, **kwargs):
        if cls.n_eels == cls.MAX_EELS:
            raise HovercraftFull()

        obj = super(Eel, cls).__new__(cls)
        cls.n_eels += 1
        return obj

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

    def __del__(self):
        type(self).n_eels -= 1

    def electric(self):
        """Is this an electric eel?"""
        return self.voltage > 0

rawDescription: __new__ and __init__ in Python

description: __new__ and __init__ in Python


code: go -abc

rawDescription: Difference between single dash and double dash in argparse


code:
for idx, myDict in enumerate([dict1, dict2, dict3]):
  myDict['position'] = idx

rawDescription: Editing multiple dictionaries with a single function:


rawDescription: How to remove parenthesis from elements in a list (Python)

description: Remove parenthesis from elements in a list (Python)


code:
import re
from string import punctuation
strs = "Johnny.Appleseed!is:a*good&farmer"
r = re.compile(r'[{}]'.format(punctuation))
new_strs = r.sub(' ',strs)
len(new_strs.split())
strs = "Johnny.Appleseed!is:a*good&farmer"
re.split(r'[^0-9A-Za-z]+',strs)

rawDescription: Trying to count words in a string [python]


code: other_data = ["BANKL", "BANKN", "BANKS", "BEGRU", "BUKRS", "C_Block"]

rawDescription: How to convert few columns of pandas dataframe into JSON record within another record?

description: Convert few columns of pandas dataframe into JSON record within another record


code: earnings[currency] = value

rawDescription: Most concise way to define multiple variables


code:
ax1.set_yticks(np.linspace(ax1.get_ybound()[0], ax1.get_ybound()[1], 5))
ax2.set_yticks(np.linspace(ax2.get_ybound()[0], ax2.get_ybound()[1], 5))

rawDescription: matplotlib align twinx tick marks

description: Matplotlib align twinx tick marks


code:
df
pd.crosstab(df['Col X'], df['Col Y'])

rawDescription: Pivot Tables or Group By for Pandas?

description: Pivot Tables or Group By for Pandas


code:
import rpy2.robjects as ro

ro.globalenv['dr'] = dr

ro.r("""
library(ggplot2)
names(dr) <- c('letters','bool','n','value')

x <- ggplot() +
  geom_bar(data=dr, aes(y = value, x = letters, fill = bool),
           stat="identity", position='stack') +
  theme_bw() +
  facet_grid( ~ n)

print(x)
""")

rawDescription: Pandas stacked multilevel index plot

description: Pandas stacked multilevel index plot


code:
def my_print(*args):
    print(*args)

rawDescription: print tuple as number of arguments

description: Print tuple as number of arguments


code: input.insert(tkinter.END, "I'd like to suggest that coconuts migrate.")

rawDescription: Python Tkinter read only text field

description: Python Tkinter read only text field


rawDescription: How to test each specific digit or character

description: Test each specific digit or character


code:
COL_NAME = 2
COL_PHONENUM = -1

with open('new_main.txt', 'w') as outfile:
    # zip corresponding lines from each file
    for entry in zip(open('names.txt'), open('number.txt'), open('main.txt')):
        main_data = entry[2].split()
        main_data[COL_NAME] = entry[0].strip()
        main_data[COL_PHONENUM] = entry[1].strip()
        outfile.write('{}\n'.format(' '.join(main_data)))

rawDescription: How to read and replace text in files in python line by line

description: Read and replace text in files in python line by line


rawDescription: Create overlapping groups with pandas timegrouper


code:
def __pow__(self, other):
    return matrix_power(self, other)

rawDescription: Any difference between the .I and **-1 for matrix inversion in mpmath?


code:
import re
with open('output.txt', 'w') as f:
    for line in lines:
        line = re.sub("(\$\d+)$", r" \1", line, 1)
        f.write(line)

rawDescription: Beautiful Soup - how to clean extracting data?


code:
from collections import defaultdict
d0 = {"a": "hello", "b": "world", "c": 11}
d1 = {"a": "hello", "b": "world", "c": 100}
d2 = {"a": "goodbye", "b": "world", "c": 10}
keyed = defaultdict(int)
for d in (d0, d1, d2):
    keyed[(d['a'], d['b'])] += d['c']

keyed
[{'a': a, 'b': b, 'c': c} for (a, b), c in keyed.items()]

rawDescription: "Adding" dictionaries in python if some (key, value) pairs match


code:
from PIL import Image
from numpy import*

temp=Image.open('THIS.bmp')
temp=temp.convert('1')      # Convert to black&white
A = array(temp)             # Creates an array, white pixels==True and black pixels==False
new_A=empty((A.shape[0],A.shape[1]),None)    #New array with same size as A

for i in range(len(A)):
    for j in range(len(A[i])):
        if A[i][j]==True:
            new_A[i][j]=0
        else:
            new_A[i][j]=1

rawDescription: import image to python as 2D array

description: Import image to python as 2D array


code:
import copy
list1 = [1,2,3,4,5]
list2 = copy.copy(list1)
for i in range(len(list2)):
    list2[i] += 1
list1

rawDescription: How do I keep the values in my original list from changing

description: Keep the values in my original list from changing


code:
def number_to_list(number):
    head = tail = None        #you can chain assignments if they have the same value
    for x in str(number):
        if not x.isdigit():
            continue # skip leading `-`
        node = Node(x)
        if head is not None:  #more pythonic than `if head`
           tail.next = node
        else:
           head = node
           tail = node
    return head    # don't forget your return code

rawDescription: How to convert a number into a linked list of its digits in python

description: Convert a number into a linked list of its digits in python


code:
@static_init
class Foo:
    _PARAM = None

    @classmethod
    def static_init(cls, param):
        cls._PARAM = param

    def test(self):
        print(Foo._PARAM)

Foo.static_init('param')
f = Foo()
f.test()  # param

rawDescription: Best way to make class variables initialization mandatory

description: Make class variables initialization mandatory


code:
import sys
paras = [int(x) for x in sys.argv[1:]]
print(paras)

rawDescription: Taking multiple lines of strings as command line input in Python


rawDescription: How to parse ambiguous characters with BioPython

description: Parse ambiguous characters with BioPython


code:
EuroMDYScales = [TimeScale(day_of_month=range(1,31,3), formatter=MyFormatter()),
             TimeScale(day_of_month=(1,8,15,22), formatter=MyFormatter()),
             TimeScale(day_of_month=(1,15), formatter=MyFormatter()),
             TimeScale(month_of_year=range(1,13), formatter=MyFormatter()),
             TimeScale(month_of_year=range(1,13,3), formatter=MyFormatter()),
             TimeScale(month_of_year=(1,7), formatter=MyFormatter()),
             TimeScale(month_of_year=(1,), formatter=MyFormatter())]

rawDescription: python chaco axis labels time formatting

description: Python chaco axis labels time formatting


code:
screen.blit(map,(0,0))
screen.blit(player.image,(player.rect.x,player.rect.y))
for monster in monster_list:
    screen.blit(monster.image,(monster.rect.x,monster.rect.y)) # of course if you're using sprites, it's be best to just use  group.draw()
pygame.display.update()

rawDescription: Saving pygame display as pygame.Subsurface


code: sorted(zip(L1, L2), key=lambda x: x[1], reverse=True)[:3]

rawDescription: Python Converting a sorted dictionary to list?


rawDescription: Not finding the strings expected with pyparsing


code:
def log(s):
    with open("my_log.txt",w) as f:
        data = f.write("the time - " + s)

log("hello")

rawDescription: How do I give a string object a custom method in Python?

description: Give a string object a custom method in Python


code:
vowels = "aeiouAEIOU"
def get(x, step):
    yield from (x[i:i+step] for i in range(len(x[:-1])))

print([x for x in s.split() if any(set(pr).issubset(vowels) for pr in get(x, 2))])

rawDescription: Delete words which have 2 consecutive vowels in it


code: data.apply(lambda row: row * beta, axis=1)

rawDescription: Python numpy or pandas equivalent of the R function sweep()


rawDescription: Print file age in seconds using Python

description: Print file age in seconds using Python


code: crontab -e

rawDescription: How to write a cron job for a python method

description: Write a cron job for a python method


code:
class Base:
    def do( self ):
        self._member1 = 0
        self._member2 = 1

def make_do(a, b):
    def do(self):
        Base.do(self)
        self._member3 = a
        self._member4 = b
    return do

class Derived1(Base):
    do = make_do(0, 1)

class Derived2(Base):
    do = make_do(2, 3)

class Derived3(Base):
    do = make_do(9, 3)

rawDescription: Python: Simplify inheritor method

description: Python: Simplify inheritor method


code:
ts = pd.Series(1, dti)
ts.head()

rawDescription: .json extension file + timestamp + Pandas + Python


rawDescription: Extract row with maximum value in a group pandas dataframe


code: # END DEBUG

rawDescription: How to prevent a part of arbitrary code to be compiled in Python?

description: Prevent a part of arbitrary code to be compiled in Python


code:
response = mechanize.urlopen("http://foo.bar.com/")
html = response.read() # or readlines

rawDescription: Force python http request to refresh

description: Force python http request to refresh


rawDescription: What version of this Python code is faster?


rawDescription: optimizing matrix operations in python, numpy

description: Optimizing matrix operations in python, numpy


code:
a = [[1, 2],
     [3, 4]]
b = [[5, 6],
     [7, 8]]

H = [a, b]

for arr_i, arr in enumerate(H):
    print('array {}'.format(arr_i))

    for row_i, row in enumerate(arr):
        print('\trow {}'.format(row_i))

        for el in row:
            print('\t{}'.format(el))

rawDescription: Accessing rows of an array, inside an array of arrays?


code:
if not headers_written:
    writer.writerow(headers)
    headers_written = True

writer.writerow(somerow)

rawDescription: Writing headers in CSV file

description: Writing headers in CSV file