Skip to content

Instantly share code, notes, and snippets.

Steven Loria sloria

Block or report user

Report or block sloria

Hide content and notifications from this user.

Learn more about blocking users

Contact Support about this user’s behavior.

Learn more about reporting abuse

Report abuse
View GitHub Profile
@sloria
sloria / recorder.py
Last active Jan 16, 2020
WAV recording functionality using pyaudio
View recorder.py
# -*- coding: utf-8 -*-
'''recorder.py
Provides WAV recording functionality via two approaches:
Blocking mode (record for a set duration):
>>> rec = Recorder(channels=2)
>>> with rec.open('blocking.wav', 'wb') as recfile:
... recfile.record(duration=5.0)
Non-blocking mode (start and stop recording):
View slow_init.py
# The slow way
class Person:
def __init__(self, name, occupation):
self.name = name
self.occupation = occupation
self.relatives = self._get_all_relatives()
def _get_all_relatives():
...
# This is an expensive operation
View lazy_init.py
# Better
class Person:
def __init__(self, name, occupation):
self.name = name
self.occupation = occupation
self._relatives = None
@property
def relatives(self):
if self._relatives is None:
View lazy_init_with_decorator.py
# Even better
def lazy_property(fn):
'''Decorator that makes a property lazy-evaluated.
'''
attr_name = '_lazy_' + fn.__name__
@property
def _lazy_property(self):
if not hasattr(self, attr_name):
View gist:5895669
class Boiler:
def safety_check(self):
# Convert fixed-point floating point
temperature = self.modbus.read_holding()
pressure_psi = self.abb_f100.register / F100_FACTOR
if (psi_to_pascal(pressure_psi) > MAX_PRESSURE or
temperature > MAX_TEMPERATURE):
# Shutdown!
self.pnoz.relay[15] &= MASK_POWER_COIL
self.pnoz.port.write('$PL,15\0')
View gist:5895673
# Better
class Boiler:
def safety_check(self):
if any([self.temperature > MAX_TEMPERATURE,
self.pressure > MAX_PRESSURE]):
if not self.shutdown():
self.alarm()
def alarm(self):
with open(BUZZER_MP3_FILE) as f:
View gist:5895677
# At initiation `point` is not well-formed
point = Point()
point.x = 12
point.y = 5
# Better
point = Point(x=12, y=5)
View gist:5895679
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
@classmethod
def polar(cls, r, theta):
return cls(r * cos(theta),
r * sin(theta))
point = Point.polar(r=13, theta=22.6)
View gist:5895682
def send_task(self, task, job, obligation):
...
processed = ...
...
copied = ...
...
executed = ...
100 more lines
View gist:5895686
class TaskSender:
def __init__(self, task, job obligation):
self.task = task
self.job = job
self.obligation = obligation
self.processed = []
self.copied = []
self.executed = []
def __call__(self):
You can’t perform that action at this time.