Skip to content

Instantly share code, notes, and snippets.

Avatar

Jonathan Sharpe textbook

View GitHub Profile
View race.py
import datetime
from operator import itemgetter
def get_int_input(prompt, min_=0, max_=None):
"""Get a valid integer input."""
while True:
try:
i = int(input(prompt))
except ValueError:
print("Please enter an integer.")
View rangeset.py
class Cached(object):
"""Cache classes with positional arguments."""
_cache = {}
def __new__(cls, *args):
if args not in cls._cache:
cls._cache[args] = super(Cached, cls).__new__(cls)
return cls._cache[args]
@textbook
textbook / valid_input.py
Last active Aug 29, 2015
Class-based user input validation (comment at http://codereview.stackexchange.com/q/80525/32391)
View valid_input.py
"""Functionality for validating user inputs."""
# pylint: disable=too-few-public-methods
from __future__ import print_function
import getpass
import re
import string
import sys
View switch_case.py
class Switch(object):
"""A class for faking switch syntax with a context manager.
Args:
value (object): The stored value to compare any cases to.
Example:
>>> with Switch(1) as case:
... if case(1):
@textbook
textbook / ProblemSet2.py
Created Nov 1, 2012
MIT 6.00x - PSet 2 answers by jonrsharpe
View ProblemSet2.py
# 1. Paying the minimum
totalPaid = 0
for month in range(12):
print("Month: {0:d}".format(month + 1))
minPayment = balance * monthlyPaymentRate
totalPaid += minPayment
print("Minimum monthly payment: {0:.2f}".format(minPayment))
balance -= minPayment
balance *= (1 + (annualInterestRate / 12))
print("Remaining balance: {0:.2f}".format(balance))
@textbook
textbook / ProblemSet5.py
Created Nov 9, 2012
MIT 6.00x - PSet 5 answers by jonrsharpe
View ProblemSet5.py
from string import ascii_lowercase as lower, ascii_uppercase as upper, ascii_letters as both
# 1. Build a coder
def buildCoder(shift):
return dict(zip(both, (lower[shift:] + lower[:shift] + upper[shift:] + upper[:shift])))
# 2. Apply the coder
def applyCoder(text, coder):
return "".join([coder.get(letter, letter) for letter in text])
@textbook
textbook / testing.py
Last active Dec 27, 2015
Collection of useful bits and pieces of Python code, plus a few simple test routines - now pylint compliant
View testing.py
"""Simple unit testing functionality."""
from __future__ import print_function
def _run_function_test(function, expected, args=None, kwargs=None):
"""Check whether function returns/raises expected with supplied args."""
if args is None:
args = tuple()
if kwargs is None:
kwargs = dict()
@textbook
textbook / Flask on CF.md
Last active Mar 8, 2016 — forked from ihuston/Flask on CF.md
Simple Flask application for Cloud Foundry
View Flask on CF.md

Simple Python Flask app on Cloud Foundry

This is a (very) simple Flask application that shows how the built-in Python buildpack detection on Cloud Foundry works.

To push to Cloud Foundry, log in and then use

$ cf push myapp-name

Python on Cloud Foundry

@textbook
textbook / keymap.cson
Last active Jul 9, 2016
JetBrains-style Atom keymap
View keymap.cson
# JetBrains-style
'.platform-darwin':
'cmd-1': 'tree-view:toggle'
'cmd-shift-a': 'command-palette:toggle'
'.platform-darwin .tree-view':
'cmd-1': 'tree-view:toggle'
'.platform-darwin atom-text-editor':
'cmd-b': 'symbols-view:go-to-declaration'
'cmd-d': 'editor:duplicate-lines'
'cmd-l': 'go-to-line:toggle'
View demo.py
VERB_QUIET = 0
class VerbosityLevel(object):
def __init__(self, level):
self.level = level
def __get__(self, obj, _):
return obj.level >= self.level