code:
import numpy as np
import pandas as pd

np.random.seed(2016)
N = 600
result = pd.DataFrame(
    {'Cellule': np.arange(N),
     'InternalRes': np.random.uniform(30, 60, size=N),
     'Capacity': np.random.uniform(3000, 4000, size=N)})

final = result.groupby('Cellule')['InternalRes','Capacity'].mean()
final = final.sort_values('Capacity', ascending=False)
final = final.iloc[:418]

final = final.sort_values('InternalRes')
groups = [final.iloc[i:i+11] for i in range(0, 418, 11)]

rawDescription: Pandas DataFrame: keep best row combination


code: return ''.join(sorted(comb_))

rawDescription: Sorting elements in string with Python

description: Sorting elements in string with Python


code:
def get(img, y0, y1, x0, x1, mode="nearest"):
    xs, ys = numpy.mgrid[y0:y1, x0:x1]
    height, width = img.shape

    if mode == "nearest":
        xs = numpy.clip(xs, 0, height-1)
        ys = numpy.clip(ys, 0, width-1)

    elif mode == "wrap":
        xs = xs % height
        ys = ys % width

    elif mode == "reflect":
        maxh = height-1
        maxw = width-1

        # An unobvious way of performing reflecting modulo
        # You should comment this
        xs = numpy.absolute((xs + maxh) % (2 * maxh) - maxh)
        ys = numpy.absolute((ys + maxw) % (2 * maxw) - maxw)

    elif mode == "constant":
        output = numpy.empty((y1-y0, x1-x0))
        output.fill(0) # WHAT THE CONSTANT IS

        # LOADS of bounds checks and restrictions
        # You should comment this
        target_section = output[max(0, -y0):min(y1-y0, -y0+height), max(0, -x0):min(x1-x0, -x0+width)]
        new_fill = img[max(0, y0):min(height, y1), max(0, x0):min(width, x1)]

        # Crop both the sections, so that they're both the size of the smallest
        # Use more lines; I'm too lazy right now
        target_section[:new_fill.shape[0], :new_fill.shape[1]] = new_fill[:target_section.shape[0], :target_section.shape[1]]

        return output

    else:
        raise NotImplementedError("Unknown mode")

    return img[xs, ys]

rawDescription: How to get area of image with boundary conditions?

description: Get area of image with boundary conditions


code:
# myapp/models.py
class User(models.Model):
    user = models.ForeignKey(
        USER,
        related_name="%(app_label)s_%(class)s_related"
    )

    class Meta:
        abstract = True

class TestModel(User):
     title = models.CharField(max_length=80)

rawDescription: Dynamically creating the related_name from META class


code:
rest_type = graph.merge_one("Cuisine", "cuisine", cuisine)
graph.create_unique(rel(restaurant,"SERVES", rest_type))
loc = graph.merge_one("Location", "location", location)
graph.create_unique(rel(restaurant, "IN", loc))

rawDescription: Create relationship on pre-existing node in py2neo


code:
import sys
from PyQt4 import QtGui

app = QtGui.QApplication(sys.argv)
main = QtGui.QMainWindow()
toolbar = QtGui.QToolBar()

# spacer widget for left
left_spacer = QtGui.QWidget()
left_spacer.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
# spacer widget for right
# you can't add the same widget to both left and right. you need two different widgets.
right_spacer = QtGui.QWidget()
right_spacer.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)

# here goes the left one
toolbar.addWidget(left_spacer)
# some dummy actions
toolbar.addAction('one')
toolbar.addAction('two')
toolbar.addAction('three')
# and the right one
toolbar.addWidget(right_spacer)

main.addToolBar(toolbar)
main.show()
sys.exit(app.exec_())

rawDescription: PyQT center toolbar buttons

description: PyQT center toolbar buttons


code:
string = '$20 - $40'  #'$20' will also work
x = re.findall(r'\$(\d+)', string)
1. * sum(map(int, x)) / len(x)

rawDescription: Breaking up cost string into integer values


code:
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _, ungettext
from django.contrib.comments.admin import CommentsAdmin
from django.contrib.comments import get_model

from comments_app.models import CommentWithAddedFields

class MyCommentsAdmin(CommentsAdmin):
    # Same fieldsets as parent admin, but include 'company'
    fieldsets = (
        (None,
           {'fields': ('content_type', 'object_pk', 'site')}
        ),
        (_('Content'),
           {'fields': ('user', 'user_name', 'user_email', 'user_url', 'company', 'comment')}
        ),
        (_('Metadata'),
           {'fields': ('submit_date', 'ip_address', 'is_public', 'is_removed')}
        ),
     )

# Only register the admin if the comments model is CommentWithAddedFields
# The equivalent section in django.contrib.comments.admin is what prevents
# the admin from being registered when you set COMMENTS_APP = 'comments_app'
# in your settings file
if get_model() is CommentWithAddedFields:
    admin.site.register(CommentWithAddedFields, MyCommentsAdmin)

rawDescription: Customising the Django comment app

description: Customising the Django comment app


code: link = url_for("abc_pages", projectName = "project_B", pageName = "page_B2")

rawDescription: Controlling URL sequence in Flask applicaiton


code:
import requests
from requests.packages.urllib3 import add_stderr_logger

add_stderr_logger()
s = requests.Session()

s.headers['User-Agent'] = 'Mozilla/5.0'

# after examining the HTML of the website you're trying to log into
# set name_form to the name of the form element that contains the name and
# set password_form to the name of the form element that will contain the password
login = {name_form: username, password_form: password}
login_response = s.post(url, data=login)
for r in login_response.history:
    if r.status_code == 401:  # 401 means authentication failed
        sys.exit(1)  # abort

pdf_response = s.get(pdf_url)  # Your cookies and headers are automatically included

rawDescription: Scraping a website that requires being logged in


code:
bus1 = dbus.bus.BusConnection("tcp:host=192.168.0.1,port=1234")
bus2 = dbus.bus.BusConnection("tcp:host=192.168.0.2,port=1234")

rawDescription: multiple d-bus session bus objects in python

description: Multiple d-bus session bus objects in python


code:
def common(first, second):
    return list(set(first.split(',')) & set(second.split(',')))

common("hello,world,pie", "hello,earth,pie")

rawDescription: Comparing two separate string inputs and finding what they have in common


code:
import re
re.split('[\x00-\x1f\x7f]', 'Test String\x01111\x05Test String\x02GG\x01TEXT123')
re.split('[\x00-\x1f\x7f]', 'Test String\x01\x05Test String2')

rawDescription: Extract data from a string that is between hex values


rawDescription: Changing range of numbers in Python

description: Changing range of numbers in Python


code:
a = np.matrix(np.random.rand(3,3))
b = np.matrix(np.random.rand(3,3))
a * b
np.asarray(a) * np.asarray(b)
np.multiply(a, b)

rawDescription: How can I do element-wise arithmetic on Numpy matrices?

description: Do element-wise arithmetic on Numpy matrices


code:
def play_songs(file_list):
    random.shuffle(file_list)
    pygame.mixer.music.load(file_list[songNumber])
    pygame.mixer.music.play(1)

    for num, song in enumerate(file_list):
        if num == songNumber:
            continue # already playing
        pygame.mixer.music.queue(song)

rawDescription: python - pygame audio player. Get end of the song to play the next in line

description: Python - pygame audio player. Get end of the song to play the next in line


code:
labels = {}
maps = Maps.objects.all()
for lm in maps:
    name, description = getDescription(lm.name, lm.type)
    if name not in labels:
        labels[name] = description

rawDescription: dictionary in django python

description: Dictionary in django python


code:
from Tkinter import *
import ttk

class Application(Frame):
    def __init__(self, master):
        Frame.__init__(self, master, relief="sunken", border=1)
        self.master = master
        self.box_list = []
        self.labels = []
        self.radiobuttons = []
        self.winlabels = []
        self.loselabels = []
        self.drawlabels = []
        self.create_widgets()
        self.grid()

    def create_widgets(self):
        for i in range(9):
            box = ttk.Combobox(self, state="readonly")
            box.grid(row=1+i, column=2)
            box["values"] = ("team A", "team B", "team C", "team D", "team E", "team F", "team G", "team H", "team I")
            box.current(i)
            self.box_list.append(box)
            box.bind("<<ComboboxSelected>>")
        self.RBval = IntVar()
        for i in range(9):
            selection = i
            radiobutton = Radiobutton(self, value=selection, text=selection+1, variable=self.RBval)
            radiobutton.grid(row=1+i, column=0)
            self.radiobuttons.append(radiobutton)

        self.headings = ("Classes", "Win Lose Draw", "Declare Result!")
        for i in range(3):
            label = Label(self, text=self.headings, relief="sunken")
            label["text"] = self.headings[i]
            label.grid(row=0, column=i*3+1, columnspan=3, sticky=E+W+N+S)
        for i in range(9):
            stats = Label(self, relief="sunken")
            stats["text"] = 0
            stats.grid(row=1+i, column=4, sticky=E+W+N+S)
            self.winlabels.append(stats)
        for i in range(9):
            stats = Label(self, relief="sunken")
            stats["text"] = 0
            stats.grid(row=1+i, column=5, sticky=E+W+N+S)
            self.loselabels.append(stats)
        for i in range(9):
            stats = Label(self, relief="sunken")
            stats["text"] = 0
            stats.grid(row=1+i, column=6, sticky=E+W+N+S)
            self.drawlabels.append(stats)
        buttonwin = Button(self, text="Win", bg="green", command=self.win)
        buttonwin.grid(row=1, column=7, pady=1, padx=1, rowspan=3, columnspan=3, sticky=E+W+N+S)
        buttonlose = Button(self, text="Lose", bg="red", command=self.lose)
        buttonlose.grid(row=4, column=7, pady=1, padx=1, rowspan=3, columnspan=3, sticky=E+W+N+S)
        buttondraw = Button(self, text="Draw", bg="white", command=self.draw)
        buttondraw.grid(row=7, column=7, pady=1, padx=1, rowspan=3, columnspan=3, sticky=E+W+N+S)

    def win(self):
        i = self.RBval.get()
        self.winlabels[i]["text"] += 1

    def lose(self):
        i = self.RBval.get()
        self.loselabels[i]["text"] += 1

    def draw(self):
        i = self.RBval.get()
        self.drawlabels[i]["text"] += 1

root = Tk()
root.title("Stats Tracker")
root.geometry("500x250")
app = Application(root)
root.mainloop()

rawDescription: Python Tkinter: Inheritance Syntax or Reference mistake?


code:
import random
x = range(10)
y = random.sample(x, 4) # Pick 4 distinct elements from x

rawDescription: Not using an element in a list once randomly chosen


code:
from collections import defaultdict
counts = defaultdict(int)
with open("file.txt") as f:
    for line in f:
        id, content = line.split("\\t")
        if "$" in content:
            counts[id] += 1

rawDescription: python check unique id in file and count

description: Python check unique id in file and count


code: {{ chef.meal|join:", " }}

rawDescription: How to Display Data from MultipleChoiceField that renders in Unicode


rawDescription: Converting a number to binary with a fixed length


code:
datax=np.genfromtxt('Delta R.csv')
datay=np.genfromtxt('Example R.csv')

z = np.polyfit(datax,datay,5)
p = np.poly1d(z)

plt.title ('Test graph ')
plt.xlabel('x axis')
plt.ylabel('y axis ')

plt.plot(datax, datay,'o-')
plt.plot(datax, p(datax), '-')

datax_os = np.linspace(np.min(datax), np.max(datax), 1024)
plt.plot(datax_os, f(datax_os)) # 'smoother' line

plt.show()

rawDescription: plotting polynomial regression in same plot as the real data

description: Plotting polynomial regression in same plot as the real data


code:
from collections import defaultdict
dict_needed = defaultdict(list)
for d in dictlist:
    for k, v in d.iteritems():
        dict_needed[k].append(v)

rawDescription: Grouping dictionaries by common keys

description: Grouping dictionaries by common keys


rawDescription: Python 3: Removing brackets from a list

description: Python 3: Removing brackets from a list


code:
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient, ComputeManagementClientConfiguration

credentials = ServicePrincipalCredentials(
    client_id = '<client-id>',
    secret = '<key>',
    tenant = '<tenant-id>'
)

subscription_id = '<subscription-id>'

compute_config = ComputeManagementClientConfiguration(credentials, subscription_id, api_version='2015-05-01-preview')
compute_client = ComputeManagementClient(compute_config)
resource_group_name = '<resource-group>'
vm_name = '<vm-name>'
result = compute_client.virtual_machines.deallocate(resource_group_name, vm_name)

rawDescription: Azure sdk for python

description: Azure sdk for python


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

x = np.array([[1.0,2.0], [-3.0,-2.0]], dtype='float')

plt.imshow(x, interpolation='none')
plt.colorbar()
plt.show()

rawDescription: Python: display a matrix with negative and positive values


code:
import pygame
import pygame.camera

pygame.camera.init()
cam = pygame.camera.Camera(0,(640,480))
cam.start()
img = cam.get_image()
pygame.image.save(img,"filename.jpg")

rawDescription: taking webcam photos in python 3 and windows

description: Taking webcam photos in python 3 and windows


code:
from __future__ import print_function
import os
import subprocess

for root, dirs, files in os.walk("C:\comp"):
    for file in files:
        if file.endswith(".pdf"):
            filename = os.path.join(root, file)
            print (filename)
            arg1= '-sOutputFile=' + "c" +  file #added a c to the filename
            p = subprocess.Popen(['C:/Program Files/gs/gs9.15/bin/gswin64c.exe',
                                  '-sDEVICE=pdfwrite',
                                  '-dCompatibilityLevel=1.4',
                                  '-dPDFSETTINGS=/screen', '-dNOPAUSE',
                                  '-dBATCH', '-dQUIET', str(arg1), filename],
                                 stdout=subprocess.PIPE)
            print (p.communicate())

rawDescription: Python script to compress all pdf files in a directory on Windows 7


code: 7 in a

rawDescription: Fastest way to check if a value exist in a list


code:
#!/usr/bin/env python
"""Printing out gnome multi media keys via dbus-python.
"""
import gobject
import dbus
import dbus.service
import dbus.mainloop.glib

def on_mediakey(comes_from, what):
    """ gets called when multimedia keys are pressed down.
    """
    print ('comes from:%s  what:%s') % (comes_from, what)
    if what in ['Stop','Play','Next','Previous']:
        print ('Got a multimedia key!')
    else:
        print ('Got a multimedia key...')

# set up the glib main loop.
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.Bus(dbus.Bus.TYPE_SESSION)
bus_object = bus.get_object('org.gnome.SettingsDaemon',
                            '/org/gnome/SettingsDaemon/MediaKeys')

# this is what gives us the multi media keys.
dbus_interface='org.gnome.SettingsDaemon.MediaKeys'
bus_object.GrabMediaPlayerKeys("MyMultimediaThingy", 0,
                               dbus_interface=dbus_interface)

# connect_to_signal registers our callback function.
bus_object.connect_to_signal('MediaPlayerKeyPressed',
                             on_mediakey)

# and we start the main loop.
mainloop = gobject.MainLoop()
mainloop.run()

rawDescription: How do you listen for Mediakey events under gnome 3 using python?

description: Listen for Mediakey events under gnome 3 using python


code:
lines.linewidth : 2

axes.grid : True
axes.linewidth : 0

xtick.major.width : 0
ytick.major.width : 0

grid.color : black

rawDescription: Use spines and tick_params in Matplotlib style sheet


code:
with tf.variable_scope('h1') as h1_scope:  # we save the scope object in h1_scope
  w = tf.get_variable('Weights', [])

with tf.variable_scope('foo'):
  with tf.variable_scope(h1_scope, reuse=True):  # get h1_scope back
    w2 = tf.get_variable('Weights')

assert w == w2

rawDescription: Accessing variables with absolute scopes


code:
class BaseHandler(webapp.RequestHandler):
    def __init__(self):
        pass

    def render(self, template_filename, template_args):
        nick = users.get_current_user().nickname()
        template_args['nick'] = nick

        self.response.out.write(
            template.render(
                self.template_path(template_filename), template_args))

rawDescription: Store user's name on Google App Engine, without calling get_current_user every time?


code:
from sqlalchemy import (Table, Column, Integer, String, create_engine,
    MetaData, ForeignKey)
from sqlalchemy.orm import mapper, create_session
from sqlalchemy.ext.declarative import declarative_base

e = create_engine('sqlite:////tmp/foo.db', echo=True)
Base = declarative_base(bind=e)

class Employee(Base):
    __tablename__ = 'employees'

    employee_id = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(30), nullable=False)

    __mapper_args__ = {'polymorphic_on': type}

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

class Manager(Employee):
    __tablename__ = 'managers'
    __mapper_args__ = {'polymorphic_identity': 'manager'}

    employee_id = Column(Integer, ForeignKey('employees.employee_id'),
        primary_key=True)
    manager_data = Column(String(50))

    def __init__(self, name, manager_data):
        super(Manager, self).__init__(name)
        self.manager_data = manager_data

class Owner(Manager):
    __tablename__ = 'owners'
    __mapper_args__ = {'polymorphic_identity': 'owner'}

    employee_id = Column(Integer, ForeignKey('managers.employee_id'),
        primary_key=True)
    owner_secret = Column(String(50))

    def __init__(self, name, manager_data, owner_secret):
        super(Owner, self).__init__(name, manager_data)
        self.owner_secret = owner_secret

Base.metadata.drop_all()
Base.metadata.create_all()

s = create_session(bind=e, autoflush=True, autocommit=False)
o = Owner('nosklo', 'mgr001', 'ownerpwd')
s.add(o)
s.commit()

rawDescription: Is multi-level polymorphism possible in SQLAlchemy?


code:
# text_buffer is a gtk.TextBuffer
end_iter = text_buffer.get_end_iter()
text_buffer.insert(end_iter, "The text to insert at the end")

rawDescription: Python Gtk TextView insert text at end

description: Python Gtk TextView insert text at end


code:
import pygame

# --- constants ---- UPPERCASE

SIZE = WIDTH, HEIGHT = 720, 480
SPEED = [2, 2]

# Colours

BLACK = (0,0,0)
BLUE = (0,0,255)
GREEN = (0,200,0)
RED = (200,0,0)
GREEN_BRIGHT = (0,255,0)
RED_BRIGHT = (255,0,0)

# --- functions ---

def text_objects(text, font):
    text_surface = font.render(text, True, BLACK)
    return text_surface, text_surface.get_rect()

def game_intro():

    large_text = pygame.font.Font('freesansbold.ttf', 115)
    text_surf, text_rect = text_objects("Broom!", large_text)

    # center using screen
    text_rect.center = screen.get_rect().center

    button_green_rect = pygame.Rect(75,400,100,50)
    button_red_rect = pygame.Rect(550,400,100,50)

    intro = True

    while intro:

        # --- events ---

        for event in pygame.event.get():
            print(event)
            if event.type == pygame.QUIT:
                intro = False

        mouse = pygame.mouse.get_pos()

        # --- draws ----

        screen.fill(BLUE)

        screen.blit(text_surf, text_rect)

        #Button

        if button_green_rect.collidepoint(mouse):
              pygame.draw.rect(screen, GREEN_BRIGHT, button_green_rect)
        else:
              pygame.draw.rect(screen, GREEN, button_green_rect)

        if button_red_rect.collidepoint(mouse):
              pygame.draw.rect(screen, RED_BRIGHT, button_red_rect)
        else:
              pygame.draw.rect(screen, RED, button_red_rect)

        pygame.display.flip()

        clock.tick(15)

# --- main ---

pygame.init()

screen = pygame.display.set_mode(SIZE)

pygame.display.set_caption("BETA::00.0.1")

clock = pygame.time.Clock()

game_intro()

pygame.quit()

rawDescription: Python. Pygame - Interactive button does not respond


rawDescription: Conversion a hex string adding 0x30 to each byte


code:
from collections import Counter

count = Counter(map(tuple, d.values()))

rawDescription: Matching/Counting lists in python dictionary


code:
env = db.DBEnv()
env.open(None, db.DB_CREATE | db.DB_INIT_MPOOL)
internal_db = db.DB(env)
internal_db.open("the filename", "the internal db name", db.DB_BTREE, db.DB_RDONLY)

rawDescription: bsddb and reprepro (berkeley) database

description: Bsddb and reprepro (berkeley) database


code:
import os

def encode(rawBytes):
    data = [ord(i) for i in rawBytes]
    length = len(rawBytes) + 128
    Bytes = [0x81, length]
    index = 2
    masks = os.urandom(4)
    for i in range(len(masks)):
           Bytes.insert(i + index, masks[i])
    for i in range(len(data)):
        data[i] ^= masks[i % 4]
        Bytes.insert(i + index + 4, data[i])
    return [hex(i) for i in Bytes]

rawDescription: encode data to send to a websocket server

description: Encode data to send to a websocket server


code: plt.subplot(212, sharex = ax1, sharey = ax1)

rawDescription: set axis limits in matplotlib pyplot

description: Set axis limits in matplotlib pyplot


code:
import cPickle
# save the classifier
with open('my_dumped_classifier.pkl', 'wb') as fid:
    cPickle.dump(gnb, fid)

# load it again
with open('my_dumped_classifier.pkl', 'rb') as fid:
    gnb_loaded = cPickle.load(fid)

rawDescription: Save classifier to disk in scikit-learn

description: Save classifier to disk in scikit-learn


code:
fig, ax = plt.subplots(1, 1)
x = np.arange(11)
ax.plot(x, 'r')
ax2 = ax.twinx()
ax2.plot(x ** 2, 'g')
plt.draw()

rawDescription: Plotting multiple lines with different scales on the same graph


code:
expr = t *(h +l )/(l *(h +l *sin (theta ))*cos (theta ))
expr
repl1 = [x-h/l, y-t/l]
repl2 = solve(repl1, t, l)
repl2
simplify(expr.subs(repl2)).subs({x: h/l, y: t/l})

rawDescription: Collecting a fraction expression within a larger fraction (sympy)


code:
class Node:
    #children = [] # not here...
    parent = 0     # might want to rethink where you initialize these
    visited = 0
    cost = 0
    position = (0, 0)
    leaf = 0

    def __init__(self, parent, pos):
        self.parent = parent
        self.position = pos
        self.children = [] # ...but here

    def addChild(self, node):
        self.children += [node]

rawDescription: Python Stack Corruption?

description: Python Stack Corruption


code:
def employee_creation():

    result = [((item[0] +", "+ item[1]).ljust(30), int(item[2]), item[3].ljust(15), int(item[4])) for item in data]
    for items in result:
            result1.append((items[0][0:30], format(items[1], "^5d"), items[2][0:15], "£"+format((items[3]),"<8d")))

    return result # no need for () here

result = employee_creation() # store the return value of your function
print(result)

rawDescription: Python return function not working for me


rawDescription: manipulating linewidth for hatching in matplotlib

description: Manipulating linewidth for hatching in matplotlib


rawDescription: Python hex string operation: need to preserve the leading zeros


code:
list_ = ['a','b','c','d','e','f','g','h']
n = 3  # group size
m = 1  # overlap size
[list_[i:i+n-m+1] for i in xrange(0,len(list_), n-m)]

rawDescription: Splitting a python list into a list of overlapping chunks


code:
query_list = []
for field_name in ['student_process', 'student_status', 'student_number', 'student_region', ]:
    value = request.GET.get(field_name, None)
    if value:
        query_list.append(Q(**{field_name+'s_icontains': value}))
queryset = Student.objects.filter(reduce(operator.and_, query_list))

rawDescription: How can i make long query in django

description: Make long query in django


code:
import requests
import urllib
r = requests.get("https://play.google.com/store/apps/details?id=com.facebook.katana")
from bs4 import BeautifulSoup
soup = BeautifulSoup(r.content)

img = soup.find("img",{"class":"cover-image"})["src"]
urllib.urlretrieve(img,"fb.jpg")

rawDescription: Downloading Image with no Extension

description: Downloading Image with no Extension


code:
import binascii
from tkinter import filedialog

file_path = filedialog.askopenfilename()

x = ""
with open(file_path, 'rb') as f:
    for chunk in iter(lambda: f.read(32), b''):
        x += str(binascii.hexlify(chunk)).replace("b","").replace("'","")
b = bin(int(x, 16)).replace('b','')
g = [b[i:i+2] for i in range(0, len(b), 2)]
dna = ""
for i in g:
    if i == "00":
        dna += "A"
    elif i == "01":
        dna += "T"
    elif i == "10":
        dna += "G"
    elif i == "11":
        dna += "C"
print(x) #hexdump
print(b) #converted to binary
print(dna) #converted to "DNA"

rawDescription: Convert file to binary code in Python

description: Convert file to binary code in Python


code:
from pprint import pprint

def matrix(rows,cols):
    grid = [[0 for i in range(cols)] for i in range(rows)]
    return grid

rows = 5
cols = 5
pprint(matrix(rows,cols))

rawDescription: Insert newline print statement into (nested)? for loop?


code:
import dateutil.parser
import csv

data_dict = {}
with open('data.csv', 'r') as csvfile:
    csvreader = csv.reader(csvfile)
    for row in csvreader:
        dt = dateutil.parser.parse(row[0])
        if not data_dict.get(dt.hour,''):
            data_dict[dt.hour] = {}
        if not data_dict[dt.hour].get(dt.minute,''):
            data_dict[dt.hour][dt.minute]=[]
        data_dict[dt.hour][dt.minute].append(row[1:])

rawDescription: creating dictionary within a dictionary in python reading some data is a csv file

description: Creating dictionary within a dictionary in python reading some data is a csv file


code:
import Tkinter as tk
import ImageTk

root = tk.Tk()

img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")

def callback(e):
    img2 = ImageTk.PhotoImage(Image.open(path2))
    panel.configure(image = img2)
    panel.image = img2

root.bind("<Return>", callback)
root.mainloop()

rawDescription: How to update the image of a Tkinter Label widget?

description: Update the image of a Tkinter Label widget


code:
row = []
for x in (['string1', 'string2', 'string3', 'string4'], ['string5'], ['string6', 'string7', 'string8', 'string9', 'string10', 'string11', 'string12']):
    row = row + x

rawDescription: Writing list of lists properly to CSV

description: Writing list of lists properly to CSV


code:
x = []
y = []
for theta in linspace(0,10*pi):
    r = ((theta)**2)
    x.append(r*cos(theta))
    y.append(r*sin(theta))

plt.plot(x,y)
plt.show()

rawDescription: Plot a spiral where r=theta^2 for 0<= theta <= 10*pi ...in python


code:
from Tkinter import *

root = Tk()

left = Frame(root)
right = Frame(root)

t_start = Text(left, width=20)
t_start.pack(side=LEFT, fill=Y)
s_start = Scrollbar(left)
s_start.pack(side=RIGHT, fill=Y)
s_start.config(command=t_start.yview)
t_start.config(yscrollcommand=s_start.set)

t_end = Text(right, width=20)
t_end.pack(side=LEFT, fill=Y)
s_end = Scrollbar(right)
s_end.pack(side=RIGHT, fill=Y)
s_end.config(command=t_end.yview)
t_end.config(yscrollcommand=s_end.set)

left.pack(side=LEFT, fill=Y)
right.pack(side=RIGHT, fill=Y)

root.geometry("500x200")
root.mainloop()

rawDescription: python tkinter scrollbar and text widget issues

description: Python tkinter scrollbar and text widget issues


code:
class SelectionWindow(QtGui.QMainWindow):
    ...
    def getSelection(self):
        result = self.exec_()
        if result:
            # User clicked Ok - read currentRow
            selectedRow = self.ui.myQtTreeViewWidget.currentIndex()
        else:
            # User clicked Cancel
            selectedRow = None
        return selectedRow
    ...

rawDescription: PyQt4: Adding QtMessageBox.information functionality to custom window


rawDescription: how to pack and unpack data using python 2.5

description: Pack and unpack data using python 2.5


rawDescription: Create array of outer products in numpy

description: Create array of outer products in numpy


code:
with open("file", 'r') as f:
    for line in f:
        print(line.replace('e', 'bob'), end="")

rawDescription: How to split a sting into letters

description: Split a sting into letters


code:
from sklearn.linear_model import SGDClassifier
import random
clf2 = SGDClassifier(loss='log') # shuffle=True is useless here
shuffledRange = range(len(X))
n_iter = 5
for n in range(n_iter):
    random.shuffle(shuffledRange)
    shuffledX = [X[i] for i in shuffledRange]
    shuffledY = [Y[i] for i in shuffledRange]
    for batch in batches(range(len(shuffledX)), 10000):
        clf2.partial_fit(shuffledX[batch[0]:batch[-1]+1], shuffledY[batch[0]:batch[-1]+1], classes=numpy.unique(Y))

rawDescription: Sklearn SGDClassifier partial fit

description: Sklearn SGDClassifier partial fit


code:
from ssReader import Reader
from theCalcs import ACalc, AnotherCalc
from theDB import Loader

def main( sourceFileName ):
    rdr= Reader( sourceFileName )
    c1= ACalc( options )
    c2= AnotherCalc( options )
    ldr= Loader( parameters )
    for myObj in rdr.readAll():
        c1.thisOp( myObj )
        c2.thatOp( myObj )
        ldr.laod( myObj )

rawDescription: How many Python classes should I put in one file?


code:
import visa
rm = visa.ResourceManager()

rm.list_resources() # ('ASRL1::INSTR', 'ASRL2::INSTR', 'GPIB0::12::INSTR')
ud = rm.open_resource('GPIB0::12::INSTR') #You need to specify your device here.

#Read the file into data
f = open('file.dat', 'rb')
data = list(f.read())

#Write file into device
ud.write_raw(data)

rawDescription: Equivalent function ibwrtfW and ibwrtfA in python visa/gpib module


code:
import re

fr=open("various.multi").read()
gr=open("locus.txt",'w')

for m in re.finditer(r"\bSP_LINE\b",fr):
    for n in re.finditer(r"//", fr[m.end():]):
        gr.write(fr[m.start():m.end()+n.end()])
        break
gr.close()

rawDescription: Writing a block of text into file

description: Writing a block of text into file


code:
samples = [['asdf', '1'], ['asdf', '0']]
# turn the samples into dicts
samples = [dict(enumerate(sample)) for sample in samples]

# turn list of dicts into a numpy array
vect = DictVectorizer(sparse=False)
X = vect.fit_transform(samples)

clf = DecisionTreeClassifier()
clf.fit(X, ['2', '3'])

rawDescription: scikit-learn CART String Data

description: Scikit-learn CART String Data


code:
from math import *

hard_limit = 32767
linear_limit = 23197  # -3 dB
clip_limit = linear_limit + int(pi/2 * (hard_limit - linear_limit))

def soft_clip(n):
    amplitude, sign = abs(n), 1 if n >= 0 else -1
    if amplitude <= linear_limit:
        return n
    if amplitude >= clip_limit:
        return hard_limit * sign
    scale = hard_limit - linear_limit
    compression = scale * sin(float(amplitude - linear_limit) / scale)
    return (linear_limit + int(compression)) * sign

rawDescription: Clipping Tops of Waveforms in Python

description: Clipping Tops of Waveforms in Python


code: differences = [array[index+1]-array[index] for index in range(len(array))-1]

rawDescription: Concise way to create an array of differences (from an array)


code:
with open('file1.csv') as f, open('file2.csv') as g:
    old, new = set(f), set(g)
for added in new - old:
    print('added', added)
for deleted in old - new:
    print('deleted', deleted)

rawDescription: How to compare 2 csv files with > 1000 rows and find the difference?

description: Compare 2 csv files with > 1000 rows and find the difference


code:
import base64
import cStringIO

buffer = cStringIO.StringIO()
image.save(buffer, format="JPEG")
img_str = base64.b64encode(buffer.getvalue())

rawDescription: How to convert PIL Image.image object to base64 string?

description: Convert PIL Image.image object to base64 string


code:
import os, re

def purge(dir, pattern):
    for f in os.listdir(dir):
    	if re.search(pattern, f):
    		os.remove(os.path.join(dir, f))

rawDescription: Delete multiple files matching a pattern


code:
@property
def is_redirect(self):
    """True if this Response is a well-formed HTTP redirect that could have
    been processed automatically (by :meth:`Session.resolve_redirects`).
    """
    return ('location' in self.headers and self.status_code in REDIRECT_STATI)

rawDescription: Requests library GET method redirects all responses with a location in the header or only responses with status code of 300s?


code:
from signxml import xmldsig

cert = open("example.pem").read()
key = open("example.key").read()
root = ElementTree.fromstring(data)
xmldsig(root).verify()

rawDescription: Validating SAML signature in python

description: Validating SAML signature in python


code:
import datetime
d = datetime.date.today()
str(d)
repr(d)

rawDescription: When to use %r instead of %s in Python?

description: When to use %r instead of %s in Python


code:
def run(filename):
    for directoy,files,dirs in os.walk("C:\\"):
        if filename in files:
           return os.startfile(os.path.join(directory,filename))

rawDescription: Opening Files From Any Directory

description: Opening Files From Any Directory


code:
# each JSON is small, there's no need in iterative processing
import json
with open(filename, 'r') as f:
    for line in f:
        data = json.loads(line)
        # data[u'name'], data[u'engine_speed'], data[u'timestamp'] now
        # contain correspoding values

rawDescription: Using python ijson to read a large json file with multiple json objects


rawDescription: Pandas Crosstab with frequency, row percentage and col percentage on the same output


rawDescription: Converting subset of strings to integers in a list


rawDescription: Splitting a Graphlab SFrame Date column into three columns (Year Month Day)


code:
import concurrent.futures

with concurrent.futures.ProcessPoolExecutor(max_workers=5) as worker_pool:
    futures = [executor.submit(task) for task in tasks]
    for future in concurrent.futures.as_completed(futures):
        # completed task is yielded first
        result = future.result()

rawDescription: How to get the first finished async result from pool

description: Get the first finished async result from pool


code:
def __getattribute__(self, item):
    try:
        return object.__getattribute__(item)
    except AttributeError:
        pass  # fallback to dict
    try:
        return self.dict[item]
    except KeyError:
        raise AttributeError("The object doesn't have such attribute") from None

rawDescription: Are nested try/except blocks in python a good programming practice?


code:
pipe = Popen(command_2, shell=True, stdin=PIPE, stdout=PIPE)
pipe.stdin.write(result_1)
pipe.communicate()

rawDescription: Shell piping with subprocess in Python

description: Shell piping with subprocess in Python


rawDescription: change unicode string into list?

description: Change unicode string into list


code:
from itertools import product
l1 = ['a','b','c','d']
l2 = ['new']
list(product(l1,l2))

rawDescription: how to produce a nested list from two lists in python

description: Produce a nested list from two lists in python


rawDescription: SQLAlchemy - using column in LIKE

description: SQLAlchemy - using column in LIKE


code:
import ConfigParser

config = ConfigParser.RawConfigParser()
config.add_section('sec')
config.set('sec', 'name', 'foo')

with open('a.init', 'w') as f:
   config.write(f)

rawDescription: Python simple ini writing

description: Python simple ini writing


code:
class MplWidget(QtGui.QWidget):
     def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.canvas = MplCanvas()
        self.mpl_toolbar = NavigationToolbar(self.canvas, self)
        self.vbl = QtGui.QVBoxLayout()
        self.vbl.addWidget(self.canvas)
        self.vbl.addWidget(self.mpl_toolbar)
        self.setLayout(self.vbl)

rawDescription: Embedding the matplotlib toolbar in pyqt4 using matplotlib custom widget


rawDescription: Python: right way to build a string by joining a smaller substring N times


code:
if 'this' in csvLine and not 'that' in csvLine:
    do_something()

rawDescription: List Comprehension: Contains This and not That (Python)


code:
import wx

DATA = [("0", "Zero"), ("1", "One"), ("2", "Two")]

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.panel = wx.Panel(self)

        self.list = wx.ListCtrl(self.panel, style=wx.LC_REPORT)
        self.list.InsertColumn(0, "#")
        self.list.InsertColumn(1, "Number")
        for data in DATA:
            self.list.Append((data[0], data[1]))

        self.button = wx.Button(self.panel, label="Delete index 0")
        self.button.Bind(wx.EVT_BUTTON, self.OnButton)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.list, 1, wx.ALL | wx.EXPAND, 5)
        self.sizer.Add(self.button, 0, wx.ALL | wx.EXPAND, 5)
        self.panel.SetSizerAndFit(self.sizer)

        self.Show()

    def OnButton(self, e):
        self.list.DeleteItem(0)

if __name__ == "__main__":
    app = wx.App(False)
    win = MainWindow(None)
    app.MainLoop()

rawDescription: Deleting from listctrl in python

description: Deleting from listctrl in python


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

count = 3
Xs = np.arange(3)
Ys = np.random.random(3)
Xlabs = ('Blue', 'Red', 'Green')

plt.figure(1)
ax = plt.subplot(111)
ax.bar(Xs, Ys, color="grey", width=1)
ax.set_xticks([i + .5 for i in range(0, count)])
ax.set_xticklabels(Xlabs, rotation=270)

colors = ['b', 'r', 'g']
for xtick, color in zip(ax.get_xticklabels(), colors):
    xtick.set_color(color)
plt.show()

rawDescription: matplotlib different colors for each axis label

description: Matplotlib different colors for each axis label


code:
import pandas as pd

AA  = ['Aero&Def','REITs', 'Auto&Parts']

# assuming that ['Ticker','Sector','Identifier'] columns are in 'B,D,E' Excel columns
xl_cols='B,D,E'

dfs = [ pd.read_excel('FTSEASX_{0}_Price.xlsx'.format(f),
                      'Price_Data',
                      parse_cols=xl_cols,
                     ).query('Identifier == Identifier')
        for f in AA]

df = pd.concat(dfs, ignore_index=True)

print(df[['Ticker', 'Sector']])

rawDescription: Append a dataframe with a loop

description: Append a dataframe with a loop


code:
import csv
import matplotlib.pyplot as plt

### Making test CSV file ###
data = [['2011/12/15,5'],['2011/12/11,4'],['2011/12/19,2'],['2011/12/16,3'],['2011/12/20,8'],['2011/12/14,4'],['2011/12/10,10'],['2011/12/9,7']]
with open('test.csv', 'wb') as f:
    writer = csv.writer(f)
    for i in data:
        writer.writerow(i)

### Extract data from CSV ###
with open('test.csv', 'rb') as n:
    reader = csv.reader(n)
    dates = []
    freq = []
    for row in reader:
        values = row[0].split(',')
        dates.append(values[0])
        freq.append(values[1])

### Do plot ###
false_x = [x for x in range(len(dates))]
plt.plot(false_x,freq, 'o-')
plt.xticks(range(len(dates)), (dates), rotation=45)
# plt.axis([xmin, xmax, ymin, ymax]) - sets axes limits on graph
plt.axis([-1, 8, 0, 11])
plt.show()

rawDescription: Python plot dates using matplotlib

description: Python plot dates using matplotlib


code:
from __main__ import Bob

class Dave(Bob): pass
Dave()
Bob()

rawDescription: Get imported module objects

description: Get imported module objects


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

x = np.random.rand(50)
y = np.random.rand(50)

fig = plt.figure()

gs = GridSpec(4,4)

ax_joint = fig.add_subplot(gs[1:4,0:3])
ax_marg_x = fig.add_subplot(gs[0,0:3])
ax_marg_y = fig.add_subplot(gs[1:4,3])

ax_joint.scatter(x,y)
ax_marg_x.hist(x)
ax_marg_y.hist(y,orientation="horizontal")

# Turn off tick labels on marginals
plt.setp(ax_marg_x.get_xticklabels(), visible=False)
plt.setp(ax_marg_y.get_yticklabels(), visible=False)

# Set labels on joint
ax_joint.set_xlabel('Joint x label')
ax_joint.set_ylabel('Joint y label')

# Set labels on marginals
ax_marg_y.set_xlabel('Marginal x label')
ax_marg_x.set_ylabel('Marginal y label')
plt.show()

rawDescription: matplotlib: plotting histogram plot just above scatter plot

description: Matplotlib: plotting histogram plot just above scatter plot


rawDescription: Can I make a regular expression negative lookbehind assertion apply to the whole expression?

description: Make a regular expression negative lookbehind assertion apply to the whole expression


code:
#!/usr/bin/env python

import commands
...

rawDescription: Why different behaviors between running Python module as an executable vs. Python [filename]


rawDescription: Why do Python emit STORE_SUBSTR when there's already an INPLACE_ADD?


code:
import collections

my_data = ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd']
result = collections.defaultdict(list)
for k, v in collections.Counter(my_data).items():
    result[v].append(k)

rawDescription: Counter in Python

description: Counter in Python


code:
def problem_a(n):
    if n == 1:
        return [n]
    elif n % 2 == 0:
        return [n] + problem_a(n // 2)
    else:
        return [n] + problem_a(3*n + 1)

rawDescription: Making recursive function in python

description: Making recursive function in python


code:
import matplotlib.pyplot as mplt
fig = mplt.figure()
ax = fig.add_subplot(111)
mplt.plot([1,2,3],[1,2,1])
plotlim = mplt.xlim() + mplt.ylim()
ax.imshow([[0,0],[1,1]], cmap=mplt.cm.Greens, interpolation='bicubic', extent=plotlim)
mplt.draw()

rawDescription: Subplot background gradient color

description: Subplot background gradient color


code:
import re
old_list = ["I love #stackoverflow because #people are very #helpful!","But I dont #love hastags",
"So #what can you do","Some simple senetnece","where there is no hastags","however #one can be good"]
hash_regex = re.compile('#(\w+)')
[(hash_regex.findall(l), l) for l in old_list]

rawDescription: Append List with reg. expression

description: Append List with reg. expression


code:
import hide_code.hide_code as hc
dir = "<full path to Jupyter config directory>"
hc.install(dir)

rawDescription: add hide_code to jupyter notebook

description: Add hide_code to jupyter notebook


code: style = wx.SYSTEM_MENU | wx.CLOSE_BOX | wx.CLIP_CHILDREN

rawDescription: wxPython Frame with wx.CAPTION style, an upper left Icon and a closebox?

description: WxPython Frame with wx.CAPTION style, an upper left Icon and a closebox


code:
class Urlregex(db.Model):
    """
    the data field is structured as a newline separated record list
    and each record is a space separated list of regex's and
    dispatch key. Example of one such record

    domain_tld: google.com
    data:
        ^(.*)google.com/search(.*) google-search

    """
    domain_tld = db.StringProperty()
    data = db.TextProperty()

class Urldispatch(db.Model):
    urlkey = db.StringProperty()
    data = db.TextProperty()

rawDescription: how would i design a db to contain a set of url regexes (python) that could be matched against an incoming url

description: How would i design a db to contain a set of url regexes (python) that could be matched against an incoming url


code:
import pandas as pd
import urllib
import matplotlib.pyplot as plt
import seaborn as sbn

content = urllib.urlopen('https://eu-ats.googlecode.com/svn/trunk/data/new/eur-fix.csv')
df = pd.read_csv(content, header=0)
df['Time'] = pd.to_datetime(df['Time'], format='%Y-%m-%d %H:%M:%S:%f')

every30 = df.loc[df.index % 30 == 0, 'Time'].values
fig, ax = plt.subplots(1, 1, figsize=(9, 5))
df.plot(x='Time', y='Bid', ax=ax)
ax.set_xticks(every30)

rawDescription: python pandas plot with uneven timeseries index (with count evenly distributed)

description: Python pandas plot with uneven timeseries index (with count evenly distributed)


code:
from itertools import izip
import csv

with open('data.txt') as inf, open('data.csv','wb') as outf:
    lines = (line[2:].rstrip() for line in inf)
    rows = (data[1:89] for data in izip(*([lines]*92)))
    csv.writer(outf).writerows(rows)

rawDescription: Converting a large ASCII to CSV file in python or java or something else on Linux or Win7


code:
def create_event(date1, date2):
    # Create JSON payload
    data = {
      "Subject": admin.longname,
      "Body": {
        "ContentType": "HTML",
        "Content": ""
      },
      "Start": date1,
      "StartTimeZone": "Central Standard Time",
      "End": date2,
      "EndTimeZone": "Central Standard Time",
    }

    json_payload = json.dumps(data)

    # Build the HTTP request
    opener = urllib2.build_opener(urllib2.HTTPHandler)
    request = urllib2.Request(url, data=json_payload)
    auth = base64.encodestring('%s:%s' % (user, pwd)).replace('\n', '')
    request.add_header('Authorization', 'Basic %s' % auth)
    request.add_header('Content-Type', 'application/json')
    request.add_header('Accept', 'application/json')
    request.get_method = lambda: 'POST'
    # Perform the request
    result = opener.open(request)

def A( weeka, weekb ):
    today = datetime.date.today()
    firstday = today + relativedelta(weekday=SU(+ weeka))
    for i in range(5):
        firstday += datetime.timedelta(days=1)
        date1 = '%sT07:00:00-05:00' % firstday
        date2 = '%sT16:00:00-05:00' % firstday
        create_event(date1, date2)

A(1,2)

rawDescription: Creating multiple events in office365 rest api


code:
suggestion_list = pyenchant_function(document_filled_with_typos)
number_of_suggestions = len(suggestion_list)
MAX_SUGGESTIONS = 3 # you choose what you like
if number_of_suggestions > MAX_SUGGESTIONS:
    answer = suggestion_list[0:(MAX_Suggestions-1)] # python lists are indexed to 0
else:
    answer = suggestion_list

rawDescription: Pyenchant Module - Spell checker

description: Pyenchant Module - Spell checker


code:
class Array(list):
    @property        #example
    def length(self):
        return len(self)

    def __getitem__(self, index):
        if isinstance(index, slice):
            return Array(super().__getitem__(index))
        return super().__getitem__(index)

rawDescription: Best way to implement recursive slicing of an object e.g. for merge-sort

description: Implement recursive slicing of an object e.g. for merge-sort


code:
class FibTree(object):
    def __init__(self, n):
        self.n = n
        if n < 2:
            self.value = n
        else:
            self.left = FibTree(n - 1)
            self.right = FibTree(n - 2)
            self.value = self.left.value + self.right.value

rawDescription: How can I recursively insert the Fibonacci sequence into a binary tree

description: Recursively insert the Fibonacci sequence into a binary tree


code:
candies = 0
while True:
    print('You have', candies, 'candies!', end='\r')
    time.sleep(1)
    candies += 1

rawDescription: How to replace characters that have already been printed in a previous line

description: Replace characters that have already been printed in a previous line


code:
from bz2 import BZ2File
from datetime import datetime
from hashlib import sha512
from os.path import dirname, abspath, join
from shutil import copyfileobj

def backup_target_database(target_path):
    backup_dir = dirname(abspath(target_path))
    hash_path = join(backup_dir, 'last_hash')
    old_hash = open(hash_path, 'rb').read()
    hasher = sha512()
    with open(target_path, 'rb') as target:
        while True:
            data = target.read(1024)
            if not data:
                break
            hasher.update(data)
        new_hash = hasher.digest()
    if new_hash != old_hash:
        fmt = '%Y%m%d-%H%M.sqlite3.bz2'
        snapshot_path = join(backup_dir, datetime.now().strftime(fmt))
        with open(target_path, 'rb') as target:
            with BZ2File(snapshot_path, 'wb', compresslevel=9) as snapshot:
                copyfileobj(target, snapshot)

rawDescription: Reccommended way to redirect file-like streams in Python?


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

rgb = np.random.random((100, 3))

fig, ax = plt.subplots()
coll = ax.pcolor(np.zeros((10, 10)))

# If we left out the "array=None", the colors would still be controlled by the
# values of the array we passed in, and the "facecolors" kwarg would be
# ignored. This is equivalent to calling `coll.set_array(None)` and then
# `coll.set_facecolors(rgb)`.
coll.set(array=None, facecolors=rgb)

plt.show()

rawDescription: Create matplotlib PolyCollection colormap mapping each cell to a color


code:
client = app.test_client()
response = client.get('/your/url', headers=list(request.headers))

rawDescription: How do I call one Flask view from another one?

description: Call one Flask view from another one


code:
base = '''
test = '''
env = jinja2.Environment(loader=jinja2.DictLoader({ 'base': base, 'test': test }))
print(env.get_template('test').render().strip('\n'))

rawDescription: Selective Override Jinja2

description: Selective Override Jinja2


code:
import os
file_list = range(1, 20)

f = {}
for x in file_list:
    f[x] = open(os.path.join(file_path, '{0}.txt'.format(x)), 'w')

rawDescription: problems porting python code to python 3

description: Problems porting python code to python 3


code:
import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')

csr = conn.cursor()
csr.close()
del csr
conn.close()     #<--- Close the connection

rawDescription: Python Database connection Close

description: Python Database connection Close


code:
import win32api
import win32con
import ctypes

ctypes.windll.gdi32.AddFontResourceA("C:\\Users\\Username\\Desktop\\fontname.ttf")
win32api.SendMessage(win32con.HWND_BROADCAST, win32con.WM_FONTCHANGE)

rawDescription: Installing TTF fonts on windows with python


code:
new_class = type(name, (models.Model,), attrs)
mod = sys.modules[new_class.__module__]
mod.__dict__[new_class.__name__] = new_class

rawDescription: Using Django's memcache API on Dynamically created models


code:
import pandas as pd
from scipy.spatial.distance import euclidean, pdist, squareform

def similarity_func(u, v):
    return 1/(1+euclidean(u,v))

DF_var = pd.DataFrame.from_dict({"s1":[1.2,3.4,10.2],"s2":[1.4,3.1,10.7],"s3":[2.1,3.7,11.3],"s4":[1.5,3.2,10.9]})
DF_var.index = ["g1","g2","g3"]

dists = pdist(DF_var, similarity_func)
DF_euclid = pd.DataFrame(squareform(dists), columns=DF_var.index, index=DF_var.index)

rawDescription: Most efficient way to construct similarity matrix


code:
words = ['fist','second','thrid']

for word in words:
    yourText = yourText.replace('theOldWord',word,1)

rawDescription: Python - replace word with another

description: Python - replace word with another


code:
from django.db.models import Count
qs = FooBar.objects.filter(example__pk__lt=50)
qs = qs.annotate(num_examples=Count('example')).filter(num_examples__gt=1)

rawDescription: Django non-distinct query

description: Django non-distinct query


rawDescription: Filling the area under plotted lines

description: Filling the area under plotted lines


code:
class X(object):
    def __new__(cls, param):
        self1 = object.__new__(cls)
        self1.__init__(param)
        self2 = object.__new__(cls)
        self2.__init__(param)
        return self1, self2

rawDescription: Cannot create new object instance with overriding __new__


code:
xr = xrange(100)
it = iter(xr)
it
next(it)
next(it)

rawDescription: I read xrange is lazy it works at the last moment is it


code:
from nltk.corpus import brown
corpus = brown.sents()
LS = corpus[0:250]
print('type(corpus)[0:250]: {0}'.format(type(LS)))
my_list = list(LS)
print('type(my_list): {0}'.format(type(my_list)))

rawDescription: Convert NLTK LazySubsequence to a list

description: Convert NLTK LazySubsequence to a list


code:
line = ''

while "!finish" != line:
    line = input(">")
    file.write(line+"\n")

rawDescription: How to check for a string is equivalent to a user input in Python?

description: Check for a string is equivalent to a user input in Python


code:
seen = {}
for x in my_objects:
    if x.id in seen:
        seen[x.id].score += x.score
    else:
        seen[x.id] = x
my_objects[:] = seen.values()

rawDescription: More concise way of writing a loop inside a loop in python


code:
import sqlite3
con = sqlite3.connect('C:\\Users\\joey\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History')
cursor = con.cursor()
cursor.execute("SELECT url FROM urls")
urls = cursor.fetchall()
print('\n'.join(urls))

rawDescription: python 3.4 Google Chrome history

description: Python 3.4 Google Chrome history


code:
df = pd.DataFrame([[1, 2], [1, 2], [1, 2], [3, 4]])
df[~(df.duplicated() | df.duplicated(take_last=True))]

rawDescription: Removing every instance of a duplicate from a dataframe


code:
def get_accessor_name(self):
    # This method encapsulates the logic that decides what name to give an
    # accessor descriptor that retrieves related many-to-one or
    # many-to-many objects. It uses the lower-cased object_name + "_set",
    # but this can be overridden with the "related_name" option.
    if self.field.rel.multiple:
        # If this is a symmetrical m2m relation on self, there is no reverse accessor.
        if getattr(self.field.rel, 'symmetrical', False) and self.model == self.parent_model:
            return None
        return self.field.rel.related_name or (self.opts.object_name.lower() + '_set')
    else:
        return self.field.rel.related_name or (self.opts.object_name.lower())

rawDescription: Django Tutorial: Where does the other objects come from?


code:
d1 = mysql.connect(database1)
d2 = mysql.connect(database2)

with d2 as c2: # new transaction
    c2.execute("SELECT f1, f2, f3 FROM table")
    with d1 as c1:
        c1.executemany("INSERT INTO table (f1, f2, f3) VALUES (%s, %s, %s)", c2)

rawDescription: How to append data to an existing database, without affecting the data already present?

description: Append data to an existing database, without affecting the data already present


code:
tom = Person(key_name='Tom')

photo_query = Photo.all()
photo_query.ancestor(tom)

rawDescription: Wait for datastore changes before redirecting


code:
ind = (2, 3)
s = slice(None) # equivalent to ':'
foo[(s,) + ind] # add s to tuples

rawDescription: Numpy array indexing with partial indices


code:
def emails(self):
    mail_body = None
    mails_folder = os.listdir(self.path_to_mails_directory)
    for mail in mails_folder:
        if mail.startswith("!"):
            pass
        else:
            with open(self.path_to_mails_directory+"/"+mail) as an_e_mail:
                mail_body = an_e_mail.read()
            yield mail, mail_body

rawDescription: IndexError while iterating through a generator


code:
import matplotlib.pyplot as plt
plt.spy(df.isnull())

rawDescription: Visually inspecting NaNs in a Pandas dataframe


code:
outfile = open(path+'filename.csv', 'wb')
df.to_csv(outfile)
oufile.close()

rawDescription: Closing file after using to_csv()

description: Closing file after using to_csv()


rawDescription: random.randint(1,n) in Python

description: Random.randint(1,n) in Python


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

def main():
    x = np.arange(0, 25, 0.01)
    y = x + np.random.randn(x.size)
    plot = DotDashHist(figsize=(10, 8))
    plot.plot(x, y, whis=1.0, sym='r.')
    plot.title('This is a Test')
    plt.show()

class DotDashHist(object):
    def __init__(self, **kwargs):
        self.fig = plt.figure(**kwargs)
        gs = GridSpec(6, 6)
        self.ax = self.fig.add_subplot(gs[1:, :-1])
        self.topax = self.fig.add_subplot(gs[0, :-1], sharex=self.ax)
        self.rightax = self.fig.add_subplot(gs[1:, -1], sharey=self.ax)
        for ax in [self.topax, self.rightax]:
            ax.set_axis_off()

    def plot(self, x, y, **kwargs):
        _, _, self.topbars = self.topax.hist(x, normed=1, bins=50)
        _, _, self.rightbars = self.rightax.hist(y, normed=1, bins=50,
                                                 orientation='horizontal')
        boxes = collections.defaultdict(list)
        for X, Y in zip(x, y):
            boxes[int(X)].append(Y)

        kwargs.pop('positions', None)
        self.boxes = self.ax.boxplot(boxes.values(), **kwargs)

    def title(self, *args, **kwargs):
        self.topax.set_title(*args, **kwargs)

if __name__ == '__main__':
    main()

rawDescription: Object-oriented matplotlib usage mysteriously produces boxplots without whiskers or median lines


code:
def readFile(ui):
    L = []
    with open(ui, 'r') as f:
        for line in f.readlines():
            L.append(float(line))
    return sorted(L)

def fileAddValue(ui, val):
    with open(ui, 'a') as f:
        f.write(str(val) + '\n')

ui = raw_input("Please enter your file name:")
L = readFile(ui)
print('original file:')
print(L)
val = float(raw_input("Enter the value you would like to add to the list: "))
fileAddValue(ui, val)
L = readFile(ui)
print('updated file:')
print(L)

rawDescription: Python Files, adding values to/from a list


code:
from oauth2client.client import SignedJwtAssertionCredentials

def authenticate_and_get_spreadsheet():
    scope = ['https://spreadsheets.google.com/feeds']
    client_email = get_client_email() # something that looks like 962835581947-l1r8s2brhu5sjfljkg7ve54fcfxuio2b@developer.gserviceaccount.com
    private_key = get_private_key()
    credentials = SignedJwtAssertionCredentials(client_email, private_key, scope)
    gc = gspread.authorize(credentials)
    return gc

def get_spreadsheet():
    gc = authenticate_and_get_spreadsheet()
    ss = gc.open_by_key('1FxDkjsdhffQOPC-f93Cccebkjasd5NMzl4AahDk')  # document key
    return ss # now you can read/write this spreadsheet

rawDescription: how to get data from google spread sheet on python using link

description: Get data from google spread sheet on python using link


code:
from glob import glob
from process import process_one_file

for i in range(100):
    process_one_file(glob('prefix_foo_{}_*'.format(i)))

rawDescription: Looping over filenames in python

description: Looping over filenames in python


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

d1 = []
d2 = []
for x in range(10):
    d1.append([])
    d2.append([])
    for y in range(30):
        d1[-1].append(y+x)

    for y in range(37):
        d2[-1].append(y+x)

fig, axes = plt.subplots(ncols=4, figsize=(10,4))

# your first two examples
axes[0].pcolormesh(np.array(d1), cmap=plt.cm.coolwarm)
axes[1].pcolormesh(np.array(d2), cmap=plt.cm.coolwarm)

# let's reset the x-lims on this
axes[2].pcolormesh(np.array(d2), cmap=plt.cm.coolwarm)
axes[2].set_ylim(bottom=0, top=d2.shape[0])
axes[2].set_xlim(left=0, right=d2.shape[1])
# or more concisely (thanks Joe):
axes[2].axis('tight')

# and use imshow here
axes[3].imshow(np.array(d2), cmap=plt.cm.coolwarm)

rawDescription: pcolormesh adds empty white columns

description: Pcolormesh adds empty white columns


code:
import xlsxwriter

workbook = xlsxwriter.Workbook('example.xlsx')
worksheet1 = workbook.add_worksheet()
worksheet2 = workbook.add_worksheet('Original data')

center = workbook.add_format({'align': 'center', 'fg_color': 'yellow'})

worksheet1.merge_range('F16:H16',
                       """=IF('Original data'!B4<>"",'Original data'!B4,"")""",
                       center)

worksheet2.write('B4', 'Hello')

workbook.close()

rawDescription: how to combine merge_range and write_formula with xlsxwriter python

description: Combine merge_range and write_formula with xlsxwriter python


code:
import random
def main():
    capitals={"Washington":"Olympia","Oregon":"Salem",\
                    "California":"Sacramento","Ohio":"Columbus",\
                    "Nebraska":"Lincoln","Colorado":"Denver",\
                    "Michigan":"Lansing","Massachusetts":"Boston",\
                    "Florida":"Tallahassee","Texas":"Austin",\
                    "Oklahoma":"Oklahoma City","Hawaii":"Honolulu",\
                    "Alaska":"Juneau","Utah":"Salt Lake City",\
                    "New Mexico":"Santa Fe","North Dakota":"Bismarck",\
                    "South Dakota":"Pierre","West Virginia":"Charleston",\
                    "Virginia":"Richmond","New Jersey":"Trenton",\
                    "Minnesota":"Saint Paul","Illinois":"Springfield",\
                    "Indiana":"Indianapolis","Kentucky":"Frankfort",\
                    "Tennessee":"Nashville","Georgia":"Atlanta",\
                    "Alabama":"Montgomery","Mississippi":"Jackson",\
                    "North Carolina":"Raleigh","South Carolina":"Columbia",\
                    "Maine":"Augusta","Vermont":"Montpelier",\
                    "New Hampshire":"Concord","Connecticut":"Hartford",\
                    "Rhode Island":"Providence","Wyoming":"Cheyenne",\
                    "Montana":"Helena","Kansas":"Topeka",\
                    "Iowa":"Des Moines","Pennsylvania":"Harrisburg",\
                    "Maryland":"Annapolis","Missouri":"Jefferson City",\
                    "Arizona":"Phoenix","Nevada":"Carson City",\
                    "New York":"Albany","Wisconsin":"Madison",\
                    "Delaware":"Dover","Idaho":"Boise",\
                    "Arkansas":"Little Rock","Louisiana":"Baton Rouge"}

    wrong=[]

    print ("STATE TEST \n")

    incorrect_answers = False

    while len(capitals)>0:
        pick=random.choice(list(capitals.keys()))
        correct_answer=capitals.get(pick)
        print ("What is the capital city of",pick,"?")
        answer=raw_input("Your answer: ")
        if answer.lower()==correct_answer.lower():
            print ("That's Correct!\n")
        else:
            print ("That's Incorrect.")
            print ("The correct answer is",correct_answer)
            wrong.append(pick)
            incorrect_answers = True
    del capitals[pick]

    print ("You missed",len(wrong),"states.\n")

    if incorrect_answers:
        print ("Here are the ones that you may want to brush up on:\n")
        for each in wrong:
            print (each)
    else:
        print ("Perfect!")
main()

rawDescription: Using a dictionary for a quiz?

description: Using a dictionary for a quiz


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

h, w = 600, 700
r, c = 250, 350

def make_mask():
    x, y = np.ogrid[:h, :w]
    y -= c
    x -= r
    theta = np.arctan2(y, x)
    rad = 200 + 100*(np.sin(theta+np.pi/2)**2)
    mask = (x**2 + y**2) < rad**2
    return mask

mask = make_mask()
x, y = np.ogrid[:h, :w]
distance_sq = (x-r)**2+(y-c)**2
radius = np.sqrt((distance_sq[~mask]).min())

fig, ax = plt.subplots()
ax.imshow(mask)
ax.add_patch(patches.Circle((c,r), radius=radius))
plt.show()

yields

rawDescription: Fitting circle inside image. Exit condition for loop


code:
class Rectangle:
    def __init__ (self):
        self.height = 0
        self.width = 0

    def setData(self, height, width):
        if type(height) != int or type(width) != int:
            raise TypeError()
        if height <0 or width <0:
            raise ValueError()
            self.height = height
            self.width = width

    def __str__(self):
        return "height = %i, and width = %i" % (self.height, self.width)

r1 = Rectangle()
try:
       r1.setData("N",5)
except ValueError:
   print ("can't set the Rectangle to a negative number")
except TypeError:
   print ("can't set the Rectangle to a non-integer value")

print (r1)

rawDescription: Python3 : Fail to raise TypeError

description: Python3 : Fail to raise TypeError


code:
d = {}
for name, value in my_list:
    if value > d.get(name, None):
        d[name] = value

d

rawDescription: Subset a list of tuples by max value in Python


code:
import sniffer_wideband_v09
import multiprocessing
from Tkinter import *
root = Tk()
def handle_click():
    global t

    t = multiprocessing.Process(target=sniffer_wideband_v09.main, args=(sampling_rates, center_frequencies, gains, file_dir, files_names))
    t.start()
root.mainloop()

rawDescription: How to run an infinite loop in background and stop it?

description: Run an infinite loop in background and stop it


rawDescription: Python subprocess.Popen result stored in a variable


code:
dev_engine = create_engine('mysql://...')

get_prod_instrument = "select * from market_instrument inner join exchange_instrument on market_instrument.id = exchange_instrument.instrument_id \
inner join tick_size on market_instrument.id = tick_size.instrument_id \
left join futures on market_instrument.id = futures.instrument_id \
inner join (select distinct(substring(m.symbol, 1, 2)) as product from market_instrument as m inner join fills as f on m.id=f.instrument_id where symbol<>\"\" and fill_timestamp between CURDATE() - INTERVAL " + str(last_days) + \
                         " DAY AND NOW()) r on market_instrument.symbol like concat(r.product, '%') \
where symbol not like '%_old%' and symbol not like '%:%';"

result = dev_engine.execute(get_prod_instrument)
# getting columns
description_tuple = result.cursor.description
headers = [k[0] for k in description_tuple] # a list of the column names

rawDescription: Getting Column Names from SQL Alchemy result when not using Declarative Syntax


rawDescription: OneToMany queries in Django

description: OneToMany queries in Django


code:
import numpy as np
from matplotlib.pyplot import (tripcolor, triplot, scatter,
    show, title, savefig, colorbar)
from matplotlib.tri import Triangulation, TriAnalyzer

# Coordinates
x = np.random.random(100)
y = np.random.random(100)

# Triangulation
tri = Triangulation(x, y)

# Remove flat triangles
mask = TriAnalyzer(tri).get_flat_tri_mask(0.01)
tri.set_mask(mask)

# Coordinates of the edges
ii1, ii2, ii3 = tri.triangles.T
x1 = x[ii1] ; y1 = y[ii1]
x2 = x[ii2] ; y2 = y[ii2]
x3 = x[ii3] ; y3 = y[ii3]

# Surfaces
surf = 0.5*np.abs((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1))

# Density
dens = 1/(surf*3) # 3 points per triangle!

# Plot
xd = (x1+x2+x3)/3.
yd = (y1+y2+y3)/3.
tripcolor(xd, yd, dens, cmap='cool')
colorbar()
triplot(tri, color='k', linewidth=0.3)
scatter(x,y)
title('Density')
savefig('density.png')
show()

rawDescription: Plot areas of high occupancy as a densitymap or contour in Python


code:
from requests.packages.urllib3.exceptions import ProtocolError
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener

CKEY = 'NlilpJMYf7i4dGYXtJJONrDt5'
CSECRET = 'S1xIaTJs2M1S4Okfm3LF1JkjGkNBOaDpkNl6HayOPcLFLWMrak'
ATOKEN = '1144571546-MnpLF9GQqVdo5QzBysL1iZFW0p49kixER1xkHvK'
ASECRET = 'LnVOgnFlgIaVd0qBYf7bJ9Dzl0nE2oKrjBDYc0L69XEsH'

class Listener(StreamListener):

    @staticmethod
    def on_data(data):
        print(data)
        return True

    @staticmethod
    def on_error(status):
        print(status)

def main():
    auth_handler = OAuthHandler(CKEY, CSECRET)
    auth_handler.set_access_token(ATOKEN, ASECRET)

    while True:
        try:
            stream = Stream(auth_handler, Listener())
            stream.filter(
                track=[
                    'nepal', 'police', 'army', 'constitution', 'earthquake',
                    'government', 'minister', 'kathmandu post', 'janakpur',
                    'everest',
                ]
            )
        except ProtocolError as error:
            print(error)

if __name__ == '__main__':
    main()

rawDescription: getting error in downloading twitter data through Streaming API

description: Getting error in downloading twitter data through Streaming API


code:
def activate_self(self):
    """ Activate this window. """
    shell = win32com.client.Dispatch('WScript.Shell')
    shell.AppActivate(str(self.title))
    shell = None

rawDescription: Tkinter activate window on Windows XP

description: Tkinter activate window on Windows XP


code:
import networkx as nx
import matplotlib.pyplot as plt
G=nx.complete_graph(4)
pos=nx.spring_layout(G)

fig=plt.figure(figsize=(5,5))
ax=plt.axes([0,0,1,1])
ax.set_aspect('equal')
nx.draw_networkx_edges(G,pos,ax=ax)

plt.xlim(-0.5,1.5)
plt.ylim(-0.5,1.5)

trans=ax.transData.transform
trans2=fig.transFigure.inverted().transform

piesize=0.2
p2=piesize/2.0
for n in G:
    xx,yy=trans(pos[n]) # figure coordinates
    xa,ya=trans2((xx,yy)) # axes coordinates
    a = plt.axes([xa-p2,ya-p2, piesize, piesize])
    a.set_aspect('equal')
    fracs = [15,30,45, 10]
    a.pie(fracs)

plt.savefig('pc.png')

rawDescription: Pie chart as nodes in networkx

description: Pie chart as nodes in networkx


code:
@app.route('/')
def hello():
     session['name'] = 'Foo'
     return Bar

@app.route('/name/')
def name():
    name = session.get('name')
    return name

rawDescription: is there a Flask equivalent to MeteorJS Session functionality?

description: Is there a Flask equivalent to MeteorJS Session functionality


code:
def validate_captcha(view):
    def wrap(request, *args, **kwargs):
        if request.method == 'POST':

            url = "https://www.google.com/recaptcha/api/siteverify"
            values = {
                'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
                'response': request.POST.get(u'g-recaptcha-response', None),
                'remoteip': request.META.get("REMOTE_ADDR", None),
            }

            data = urllib.urlencode(values)
            req = urllib2.Request(url, data)
            response = urllib2.urlopen(req)
            result = json.loads(response.read())

            # result["success"] will be True on a success
            if result["success"]:
                return view
            else:
                return fail
        return fail
    return wrap

rawDescription: I need the request in my decorator but I can't figure out how to get it in there


code:
class Order_productTable(tables.Table):
    order_id2 = tables.Column()
    product_id2 = tables.Column()
    customer = tables.Column(accessor="order_id2.customer")
    publication_date = tables.Column(accessor="order_id2.publication_date")

rawDescription: Displaying different models with django_tables2


code:
import win32com.client
h = win32com.client.Dispatch('matlab.application')

rawDescription: Running m-files from Python

description: Running m-files from Python


code:
from collections import defaultdict
import csv

with open('test1.csv', 'rb') as f:
    reader = csv.reader(f)
    header = next(reader)
    columns = defaultdict(list)
    for row in reader:
        for col,value in zip(header, row):
            columns[col].append(value)
    num_rows = len(columns[header[0]])

# now write data back out in same order

with open('test2.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerow(header)
    writer.writerows(
        tuple(columns[col][row] for col in header) for row in xrange(num_rows))

rawDescription: Writing arrays to a csv in columns

description: Writing arrays to a csv in columns


rawDescription: Filter Floating IPs with Neutron Python API


code:
import pyglet
sound = pyglet.media.load('mysound.mp3', streaming=False)
sound.play()
pyglet.app.run()

rawDescription: Playing audio file with Python

description: Playing audio file with Python


code:
from datetime import timedelta
ns = 45900482044637
print(timedelta(microseconds=round(ns, -3) // 1000))

rawDescription: How to convert nanoseconds of uptime into a readable date time format

description: Convert nanoseconds of uptime into a readable date time format


code:
def sign_up(request):
    if request.POST:
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            return HttpResponseRedirect(reverse('account:login'))
        ...

rawDescription: Django only login for shell created users


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

# Generate some sample data similar to your post
X = np.arange(1,1000,1)
Y = np.log(X**3) + 10*np.random.random(X.shape)

Y2 = sg_filter.savitzky_golay(Y, 101, 3)

plt.plot(X,Y,linestyle='-', linewidth=2,alpha=.5)
plt.plot(X,Y2,color='r')

plt.show()

rawDescription: How to make this matplotlib plot less noisy?

description: Make this matplotlib plot less noisy


code:
fp = open('D://source.txt',"r+")

fg = open('D://target.txt',"w")

for line in fp:

    if line.find("banana") != -1:
        new_line = line.replace(line,"i like banana\n")
        fg.write(new_line)

    else:
        fg.write(line)

fg.close()

fp.close()

rawDescription: Python find word and replace line in file


code:
## removing from top
html = re.sub('.*?
', "", html)

## remove from bottom
html = re.sub('
.*', "", html)

## then match
links = re.findall('
]*>\s*<a href="(https?://[^"]*)"', html, re.IGNORECASE)
## you can push the text rss inside the pattern if you want

rawDescription: Find rss links in a webpage using regex

description: Find rss links in a webpage using regex


code:
import unittest

from dower import Installer
from mock import patch

class Deployer:
    def deploy(self):
        with Installer('foo', 'bar', 1) as installer:
            installer.install()

class DeployerTest(unittest.TestCase):
    @patch('test.Installer', autospec=True)
    def testInstaller(self, mock_installer):
        deployer = Deployer()
        deployer.deploy()
        mock_installer.assert_called_once_with('foo', 'bar', 1)

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

rawDescription: python unittest mock can't handle partially qualified name

description: Python unittest mock can't handle partially qualified name


code:
from google.appengine.api import users
from tipfy import RequestHandler
from tipfy.ext.jinja2 import render_response

class UserPageHandler(RequestHandler):
    def __init__(self, app, request):
        super(UserPageHandler, self).__init__(app, request)

        self.user = users.get_current_user()

    def user_response(self, template_name):
        return render_response(template_name, user=self.user)

def WhateverHandler(UserPageHandler):
    def get(self):
        return self.user_response('template_name.html')

rawDescription: Access user's OpenID info in templates on Google app engine (tipfy)


code:
app.add_url_rule('/css/<path:filename>', endpoint='css',
                 view_func=app.send_static_file)

rawDescription: url_for: how to look into another folder other than static

description: Url_for: how to look into another folder other than static


code:
import sys
py3 = sys.version_info[0] >= 3

class DummyCollector(pytest.collect.File):
   def collect(self):
      return []

def pytest_pycollect_makemodule(path, parent):
  bn = path.basename
  if "py3" in bn and not py3 or ("py2" in bn and py3):
     return DummyCollector(path, parent=parent)

rawDescription: py.test running Python2 and Python3

description: Py.test running Python2 and Python3


code: sorted_data = sorted(list, key=lambda t: int(t[2]))

rawDescription: Values sorted as String but I want to sort them as number in Python


code:
def pascal(n):
    answer = ""
    for rows in range(n):
        answer = str(rows) + "|"
        for col in range(rows+1):
            answer = answer + str(col)
        print(answer)

pascal(5)

rawDescription: Making a nested for loop (Python 3.x)

description: Making a nested for loop (Python 3.x)


rawDescription: Track value changes in a repetitive list in Python


code:
def str_to_bool(s):
    if s == 'True':
         return True
    elif s == 'False':
         return False
    else:
         raise ValueError # evil ValueError that doesn't tell you what the wrong value was

rawDescription: Convert True/False value read from file to boolean


code:
from django.contrib.admin.models import LogEntry

class LogEntryAdmin(admin.ModelAdmin):
    readonly_fields = ('content_type', 'user', 'action_time')

admin.site.register(LogEntry, LogEntryAdmin)

rawDescription: Make django admin logEntry read only?

description: Make django admin logEntry read only


code:
class UpdateOrCreateView(UpdateView):
    def get_object(self, queryset=None):
        # or any other condition
        if not self.kwargs.get('pk', None):
            return None
        return super(UpdateOrCreateView, self).get_object(queryset)

rawDescription: How to re-use a view to update objects in Django?

description: Re-use a view to update objects in Django


code: from line import line

rawDescription: Alias to python module

description: Alias to python module


code:
import dateutil.tz

cet = dateutil.tz.gettz('CET')

cesttime = datetime.datetime(2010, 4, 1, 12, 57, tzinfo=cet)
cesttime.isoformat()
'2010-04-01T12:57:00+02:00'

cettime = datetime.datetime(2010, 1, 1, 12, 57, tzinfo=cet)
cettime.isoformat()
'2010-01-01T12:57:00+01:00'

# does not automatically parse the time zone portion
dateutil.parser.parse('Feb 25 2010, 16:19:20 CET')\
    .replace(tzinfo=dateutil.tz.gettz('CET'))

rawDescription: Parse timezone abbreviation to UTC

description: Parse timezone abbreviation to UTC


code:
from skimage import io, data
io.use_plugin('qt')
io.imshow(data.camera(), fancy=True)

rawDescription: Scientific image display python

description: Scientific image display python


code:
@app.before_request
def before_request():
    try:
        g.user = User.query.filter_by(username=session['username']).first()
    except Exception:
        g.user = None

rawDescription: Global function to authenticate user sessions in Python's Flask


code:
import time
time.strptime("30 Nov 00", "%d %b %y")

rawDescription: Is it possible to construct a Python date using only standard libs with a http string timestamp


code:
with open('example.txt', 'r') as a_file:
    for line in a_file:
        print(line)

rawDescription: Reading and outputting a file line by line - why is this solution failing?


code: members = [getattr(self, attr) for attr in dir(self) if not attr.startswith("__")]

rawDescription: Looping over class variable's values in python


code:
value = 10.01
int(round(value))
value = 10.55
int(round(value))

rawDescription: python round leaving a trailing 0

description: Python round leaving a trailing 0


code:
import sys
import urllib2

from PyQt4 import QtCore, QtGui

class DownloadThread(QtCore.QThread):
    def __init__(self, url, list_widget):
        QtCore.QThread.__init__(self)
        self.url = url
        self.list_widget = list_widget

    def run(self):
        info = urllib2.urlopen(self.url).info()
        self.list_widget.addItem('%s\n%s' % (self.url, info))

class MainWindow(QtGui.QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.list_widget = QtGui.QListWidget()
        self.button = QtGui.QPushButton("Start")
        self.button.clicked.connect(self.start_download)
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.button)
        layout.addWidget(self.list_widget)
        self.setLayout(layout)

    def start_download(self):
        urls = ['http://google.com', 'http://twitter.com', 'http://yandex.ru',
                'http://stackoverflow.com/', 'http://www.youtube.com/']
        self.threads = []
        for url in urls:
            downloader = DownloadThread(url, self.list_widget)
            self.threads.append(downloader)
            downloader.start()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())

rawDescription: PyQt - running a loop inside GUI

description: PyQt - running a loop inside GUI


code:
import gevent.monkey
gevent.monkey.patch_all()
...
p = gevent.spawn(producer)
p.join()

rawDescription: gevent pool.wait_available() method meaning

description: Gevent pool.wait_available() method meaning


code:
verbose = False

def verbose_print(msg):
    global verbose
    if verbose:
        print(msg)

if __name__ == "__main__":
    started_at = time.time()
    #declare argparse logic separately from main functionality
    parser = argparse.ArgumentParser()
    parser.add_argument('-v', '--verbose', action='store_true')
    parser.add_argument('-m', '--use_math',   action='store_true')
    args = parser.parse_args()
    verbose_print("Began...") # won't print since this will always be lambda x:0
    global verbose
    verbose = args.verbose and not args.quiet
    global math_foo
    math_foo = lambda x, y: x^(x+y) if args.use_math else y
    main_func(args) #run main function
    finished_at = time.time()
    verbose_print("Finished (Took {} seconds)".format((finished_at-started_at)))

rawDescription: Conditional Global Lambdas in Python

description: Conditional Global Lambdas in Python


code:
print ('Luke\n-----')
print ('Year\tPrincipal\tInterest\t Total')

LU_RATE = .05
YEAR = 1
Principal = 100
Prev_Principal = 100   #added to store previous year principal

for YEAR in range (1,28):

    # Calculating Luke's total using formula for compounding interest
    Lu_Total = (Principal * ((1 + LU_RATE) ** YEAR))

    Lu_Interest = Lu_Total - Prev_Principal

    Lu_Principal = Lu_Total - Lu_Interest

    Prev_Principal = Lu_Total

    # Displaying the Principal, Interest, and Total over the 27
    print (YEAR,'\t%.02f\t\t %.02f\t\t %.02f' %(Lu_Principal, Lu_Interest, Lu_Total))

rawDescription: python compounding interest

description: Python compounding interest


code:
from itertools import islice

with open('input') as f:
    while True:
        lines = [line.strip() for line in islice(f, 4) if line.strip()]
        if not lines:
            break
        print(lines)    # or otherwise process them

rawDescription: Match text blocks enclosed by newlines

description: Match text blocks enclosed by newlines


code:
import subprocess

def winexists(target):
    for line in subprocess.check_output(['wmctrl', '-l']).splitlines():
        window_name = line.split(None, 3)[-1].decode()
        if window_name == target:
            return True
    return False

rawDescription: How to check if window exists in Python3.x on Linux

description: Check if window exists in Python3.x on Linux


code:
monkeys = models.Monkey.query.outerjoin(models.Friendship, db.func.count(models.Monkey.id == models.Friendship.monkey))

#or if you really want to stick to your above query

monkeys = models.Monkey.query.outerjoin(models.Friendship, db.func.SUM(func.IF(models.Monkey.id == models.Friendship.monkey, 1, 0)))

rawDescription: from raw sql to flask-sqlalchemy

description: From raw sql to flask-sqlalchemy


code:
## For each row in the lookup compute the partial ratio
for row in parse_csv("names_2.csv"):

    for found, score, matchrow in process.extract(row, data, limit=1):
        if score >= 60:
            print('%d%% partial match: "%s" with "%s" ' % (score, row, found))
            Digi_Results = [row, score, found]
            writer.writerow(Digi_Results)

rawDescription: Python Fuzzy Matching (FuzzyWuzzy)

description: Python Fuzzy Matching (FuzzyWuzzy)


code: select_s = ", ".join('ADD COLUMN %s FLOAT' % cat for cat in categories)

rawDescription: List comprehension and simplifying code

description: List comprehension and simplifying code


code: webbrowser.open('https://www.google.com') # open a passed URL string using default browser

rawDescription: Open URL from Python 2.7

description: Open URL from Python 2.7


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

class MyItem(scrapy.Item):
    name = scrapy.Field()
    story = scrapy.Field()

class MySpider(scrapy.Spider):

    name = 'medical'
    allowed_domains = ['yananow.org']
    start_urls = ['http://yananow.org/query_stories.php']

    def parse(self, response):

        rows = response.xpath('//a[contains(@href,"display_story")]')

        #loop over all links to stories
        for row in rows:
            myItem = MyItem() # Create a new item
            myItem['name'] = row.xpath('./text()').extract() # assign name from link
            story_url = response.urljoin(row.xpath('./@href').extract()[0]) # extract url from link
            request = scrapy.Request(url = story_url, callback = self.parse_detail) # create request for detail page with story
            request.meta['myItem'] = myItem # pass the item with the request
            yield request

    def parse_detail(self, response):
        myItem = response.meta['myItem'] # extract the item (with the name) from the response
        text_raw = response.xpath('//font[@size=3]//text()').extract() # extract the story (text)
        myItem['story'] = ' '.join(map(unicode.strip, text_raw)) # clean up the text and assign to item
        yield myItem # return the item

rawDescription: Scrapy Spider cannot Extract contents of web page using xpath


code:
from pylab import *
x = logspace(log10(1),log10(100),11)
y = linspace(1,100,21)

data = rand(20,10)
pcolormesh(x,y,data)
show()

rawDescription: How to plot 2D matrix whose data is not equally spaced along x-axis using Python?

description: Plot 2D matrix whose data is not equally spaced along x-axis using Python


code:
d.addCallbacks(lambda _: "success",
               lambda _: "fail")
d.addCallback(request.write)
d.addBoth(lambda _: request.finish())
return server.NOT_DONE_YET

rawDescription: how can twisted Resource object render_Post return certain value after some defer

description: How can twisted Resource object render_Post return certain value after some defer


code:
cap[0].set(cv2.CAP_PROP_FPS, 15.0)
cap[1].set(cv2.CAP_PROP_FPS, 15.0)

rawDescription: OpenCV multiple USB camera on Raspberry Pi 3


code:
from thrift.transport.THttpClient import THttpClient
socket = THttpClient(server_url)
socket.setTimeout(SERVICE_TIMEOUT_IN_mS)
transport = TTransport.TBufferedTransport(socket)
protocol = TBinaryProtocol.TBinaryProtocol(transport)

rawDescription: How to set rpc timeout in thrift python client?

description: Set rpc timeout in thrift python client


rawDescription: Clamping floating numbers in Python?

description: Clamping floating numbers in Python


code:
#!/usr/bin/python

import matplotlib.pyplot as plt
import networkx as nx

g = nx.Graph()
g.add_node( 'a' )
g.add_node( 'b' )
g.add_node( 'c' )
g.add_node( 'd' )
g.add_edge( 'a', 'b' )
g.add_edge( 'c', 'd' )

h = nx.Graph()
h.add_node( 'c' )
h.add_node( 'd' )

# Define the positions of a, b, c, d
positions = nx.spring_layout( g )

nx.draw( g, positions )

# Save the computed x and y dimensions for the entire drawing region of graph g
xlim = plt.gca().get_xlim()
ylim = plt.gca().get_ylim()

# Produce image of graph g with a, b, c, d and some edges.
plt.savefig( "g.png" )
#plt.show()

# Clear the figure.
plt.clf()

# Produce image of graph h with two nodes c and d which should be in
# the same positions of those of graph g's nodes c and d.
nx.draw( h, positions )

# Ensure the drawing area and proportions are the same as for graph g.
plt.axis( [ xlim[0], xlim[1], ylim[0], ylim[1] ] )

#plt.show()
plt.savefig( "h.png" )

rawDescription: pos argument to networkx.draw() not working

description: Pos argument to networkx.draw() not working


rawDescription: replace integers in array Python

description: Replace integers in array Python


code:
import cv2
import numpy as np
from matplotlib import pyplot as plt
from math import hypot

img = cv2.imread('asd.png',0)
img = cv2.medianBlur(img,5)

circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,120,param1=50,param2=50,minRadius=30,maxRadius=0)
circles = np.uint16(np.around(circles))

x, y, r = circles[0,:][0]
rows, cols = img.shape

for i in range(cols):
    for j in range(rows):
        if hypot(i-x, j-y) > r:
            img[j,i] = 0

cv2.imwrite("iris.jpg",img)
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])
plt.show()

rawDescription: How to mask circular area?

description: Mask circular area


code:
def spin(self):
    def change_name():
        index = random.randrange(len(self.name_list))
        self.lbl["text"] = self.name_list[index]
        self.lbl.grid()
    def finish_spinning():
        index = random.randrange(len(self.name_list))
        self.lbl["text"] = self.name_list[index]
        self.lbl.grid()
        self.name_list.pop(index)
    if self.name_list:
        name_changes = 5
        for i in range(name_changes):
            self.after(100*i, change_name)
        self.after(100*name_changes, finish_spinning)
    else:
        self.lbl["text"] = "No more names"
        self.lbl.grid()

rawDescription: I need to slow down a loop in a python tkinter app


code:
from collections import Counter

def isValidWord(word, hand, wordList):
    # Check for membership first and early out if fails
    # Otherwise, see if the count of any letter in word exceeds that of the hand
    return word in wordList and all(hand.get(let, -1) >= cnt for let, cnt in Counter(word).items())

rawDescription: Python - Neaten up Code - Loops and Recursive features


code:
from joblib import Parallel, delayed
from sklearn.svm import LinearSVC
import numpy as np

def train_model(X, y, seed):
    model = LinearSVC(random_state=seed)
    return model.fit(X, y)

X = np.array([[1,2,3],[4,5,6]])
y = np.array([0, 1])
result = Parallel(n_jobs=4)(delayed(train_model)(X, y, seed) for seed in range(10))
# result is a list of 10 models trained using different seeds

rawDescription: Train multiple models in parallel with sklearn?


code:
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(4,GPIO.OUT)
GPIO.setup(17,GPIO.OUT)
GPIO.setup(22,GPIO.OUT)
GPIO.setup(23,GPIO.OUT)
GPIO.output(4,1)
GPIO.output(17,0)
GPIO.output(22,1)
GPIO.output(23,0)
i=GPIO.input(4)
j=GPIO.input(17)
k=GPIO.input(22)
l=GPIO.input(23)
data=[i,j,k,l]
ser.write(data)

rawDescription: Read status of GPIO pins of Raspberry pi and send it through serial port


code:
from jinja2.nodes import Extends

env = Environment(loader = FileSystemLoader(['_templates']))
template_source = env.loader.get_source(env, 'test.html')[0]
parsed_template = env.parse(template_source)
extends_node = parsed_template.find(Extends)
parent_name = extends_node.template.value
parent_template = env.get_template(parent_name)

rawDescription: Jinja2 api: how to get the inherited template of a template?


code: word in dict(list_of_tuples)

rawDescription: Check if word is inside of list of tuples


code: p = sp.Popen("echo Hello $FOO", env={"FOO":"42"}, shell=True)

rawDescription: Expanding/substituting variables in a popen call


code:
with open('file2') as f:
    values = [i.strip() for i in f if i.strip() != '']
d = dict([i.split() for i in values])
with open('file1') as f:
    keys = [i.strip() for i in f if i.strip() != '']
with open('file3', 'w') as f:
    for i, j in [i.split() for i in keys]:
        f.write(d[i]+' '+d[j]+'\n')

rawDescription: How to substitute numbers in a two column array with corresponding strings in another file using Python or bash?

description: Substitute numbers in a two column array with corresponding strings in another file using Python or bash


code:
def stringfor(command, data, accesskey='\0'*6, tid=1):
  length = 16 + len(data)
  prefix = struct.pack('>BBIBB6s', 6, 2, length, tid, command, accesskey)
  checksum = sum(ord(c) for c in prefix) &0xFF
  return prefix + chr(checksum) + chr(3)

rawDescription: python send/receive hex data via TCP socket

description: Python send/receive hex data via TCP socket


code:
import os
from django.conf import settings
...
...
path = os.path.join(settings.MEDIA_ROOT, 'images', file.name)

rawDescription: Where can I find the admin code for uploading an image in django?


rawDescription: Read rdtsc in Python

description: Read rdtsc in Python


code:
with open(filename) as file:
   input_data = file.readlines()

for line in input_data:
   columns = line.strip().split(' ')
   if len(columns)<3:
      continue
   device = columns[0]
   IP_address = columns[1]
   actions = columns[2:]
   open_connection(IP_address) #whatever this may be
   for action in actions:
      perform_action(action) #whatever this may be

rawDescription: Create a python dictionary from a text file of variable columns


code:
f=open('output.$2k','r+')
f.seek(300)
f.write('\n')
f.close()

rawDescription: file pointer down then over

description: File pointer down then over


code: df.groupby(level=0, sort=False).transform(lambda x: sorted(x,key=pd.isnull))

rawDescription: Pandas force NaN to bottom of each column at each index


code:
def _create_fs(mimetype, content):
    fs = cgi.FieldStorage()
    fs.file = fs.make_file()
    fs.type = mimetype
    fs.file.write(content)
    fs.file.seek(0)
    return fs

rawDescription: How to create cgi.FieldStorage for testing purposes?

description: Create cgi.FieldStorage for testing purposes


code: type(field).__name__  # get name of the field class, instead of field.get_internal_type()

rawDescription: get_internal_error() returns CharField instead of EmailField & URLField

description: Get_internal_error() returns CharField instead of EmailField & URLField


code:
@registered_class
class SomeClass(object):

    @classmethod
    @import_string_decorator(**opt_dict)
    def double_decorated_function(cls, *args, **kwargs):
        pass

rawDescription: Retrieve Import string from a decorated classmethod


code:
import matplotlib.pyplot as plt
import numpy as np
#data
x = np.linspace(0, 2 * np.pi, 400)

y = [np.sin(x), np.sin(x**2), np.cos(x**2)]
title = ['y1','y2','y3']

#plot
numPlots = len(y)
f = plt.figure()
ax = []
for i in range(numPlots):
    ax.append(f.add_subplot(numPlots,1,i+1))
    ax[i].plot(x, y[i])
    ax[i].set_title(title[i])
    f.subplots_adjust(hspace=0.3)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
plt.show()

rawDescription: Automate the Populating of Subplots with different data


code:
from jinja2 import Environment, Undefined

def custom_sort(iterable, somearg):
    if iterable is None or isinstance(iterable, Undefined):
        return iterable

    # Do custom sorting of iterable here

    return iterable

# ...

env = Environment()
env.filters['customsort'] = custom_sort

rawDescription: Custom jinja2 filter for iterator

description: Custom jinja2 filter for iterator


code:
def inorder(p, q):
  if p and q:
    if not inorder(p.left, q.left):
      return False
    if p.val != q.val:
      return False
    return inorder(p.right, q.right)
  return not p and not q

rawDescription: Python Weird Return Issue

description: Python Weird Return Issue


code:
# new_csv_writer = open file for writing
for record in file1:
    new_csv_writer.writerow([record[0], int(record[1]) * int(record[4])])

rawDescription: Python CSV.. Outputting a CSV file to another CSV file with different number of columns


code:
import os
import subprocess
subprocess.call(["ls", "-l"], stdout=open(os.devnull, "w"), stderr=subprocess.STDOUT)

rawDescription: In Python - how to execute system command with no output


code:
from flask.views import MethodViewType

class CombinedType(ResourceRegistry, MethodViewType):
    pass

class BaseRegistered(object):
    __metaclass__ = Combinedtype

rawDescription: How can I use multiple inheritance with a metaclass?

description: Use multiple inheritance with a metaclass


code:
import dbus
import dbus.service
import dbus.glib
import gtk
import guake.common
dbus.glib.threads_init()

DBUS_PATH = '/org/guake/RemoteControl'
DBUS_NAME = 'org.guake.RemoteControl'

class DbusManager(dbus.service.Object):
    def __init__(self, guakeinstance):
        self.guake = guakeinstance
        self.bus = dbus.SessionBus()
        bus_name = dbus.service.BusName(DBUS_NAME, bus=self.bus)
        super(DbusManager, self).__init__(bus_name, DBUS_PATH)

    @dbus.service.method(DBUS_NAME)
    def show_hide(self):
        self.guake.show_hide()

rawDescription: python gtk gobject toggle visibility of windows

description: Python gtk gobject toggle visibility of windows


code:
# Copyright (C) 2005 Florent Rougon
#               2006 Darren Dale
#
# This file is an example program for matplotlib. It may be used and
# modified with no restriction; raw copies as well as modified versions
# may be distributed without limitation.

from __future__ import unicode_literals
import sys, os, random
from PyQt4 import QtGui, QtCore
from numpy import arange, sin, pi
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

class MplCanvas(FigureCanvas):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)

        # We want the axes cleared every time plot() is called
        self.axes.hold(False)

        self.compute_initial_figure()
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                                   QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

class DynamicMplCanvas(MplCanvas):
    """A canvas that updates itself every second with a new plot."""
    def __init__(self, *args, **kwargs):
        MplCanvas.__init__(self, *args, **kwargs)
        timer = QtCore.QTimer(self)
        QtCore.QObject.connect(timer,
                               QtCore.SIGNAL("timeout()"),
                               self.update_figure)
        timer.start(1000)

    def compute_initial_figure(self):
        self.axes.plot([0, 1, 2, 3], [1, 2, 0, 4], 'r')

    def update_figure(self):
        # Build a list of 4 random integers between 0 and 10 (both inclusive)
        l = [ random.randint(0, 10) for i in range(4) ]
        self.axes.plot([0, 1, 2, 3], l, 'r')
        self.draw()

rawDescription: I thought that everything in matplotlib is a QWidget. Apparently Figure is not. My interface accepts QWidgets. What to do?


code:
df
df.loc[:, 'DUMMY 1':'DUMMY 3'].mul(df['VALUE'], axis=0)

rawDescription: Python Pandas create dummy variables with values other than 1 or 0?


code:
def insert_before_back(lines, thingsToAdd):
    backIndex = lines.index('Back:\n')
    for item in reversed(thingsToAdd):
        lines.insert(backIndex, item)
    return lines

def add_inventory(lines, shopName):
    shopFound = 0
    for i in range(len(lines)):
        if shopName in lines[i]:
            shopFound = 1
        if 'InventoryLocation:' in lines[i] and shopFound:
            shopFound = 0
            lineSplit = lines[i].split(': ')
            incrementInventory = str(int(lineSplit[-1]) + 1)
            lineSplit[-1] = incrementInventory + '\n'
            lines[i] = ': '.join(lineSplit)

newLines = []
with open('input.txt', 'r') as f:
    inputLines = f.readlines()
    newLines = insert_before_back(inputLines, ['Hello\n', 'From\n', 'heinst\n'])
    add_inventory(newLines, 'HadesKitty')

with open('output.txt', 'w') as f:
    for line in newLines:
        f.write(line)

rawDescription: Append at certain point in file, increment a value each time