Skip to content

Instantly share code, notes, and snippets.

View sloria's full-sized avatar

Steven Loria sloria

View GitHub Profile
@sloria
sloria / recorder.py
Last active April 12, 2024 11:43
WAV recording functionality using pyaudio
# -*- 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):
# 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
# 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:
# 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):
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')
# 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:
# At initiation `point` is not well-formed
point = Point()
point.x = 12
point.y = 5
# Better
point = Point(x=12, y=5)
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)
def send_task(self, task, job, obligation):
...
processed = ...
...
copied = ...
...
executed = ...
100 more lines
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):