Skip to content

Commit

Permalink
Format providers using black
Browse files Browse the repository at this point in the history
Command used:

    black . --line-length 79 --extend-exclude "/vendor/"
  • Loading branch information
pieqq committed Apr 10, 2024
1 parent 2a7e832 commit bb3a1be
Show file tree
Hide file tree
Showing 180 changed files with 14,387 additions and 8,286 deletions.
97 changes: 61 additions & 36 deletions providers/base/bin/accelerometer_test.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
'''
"""
script to test accerometer functionality
Copyright (C) 2012 Canonical Ltd.
Expand All @@ -22,7 +22,7 @@
The purpose of this script is to simply interact with an onboard
accelerometer, and check to be sure that the x, y, z axis respond
to physical movement of hardware.
'''
"""

from argparse import ArgumentParser
import gi
Expand All @@ -32,12 +32,13 @@
import sys
import threading
import time
gi.require_version('Gdk', '3.0')
gi.require_version('GLib', '2.0')

gi.require_version("Gdk", "3.0")
gi.require_version("GLib", "2.0")
gi.require_version("Gtk", "3.0")
from gi.repository import Gdk, GLib, Gtk # noqa: E402
from subprocess import Popen, PIPE, check_output, STDOUT # noqa: E402
from subprocess import CalledProcessError # noqa: E402
from gi.repository import Gdk, GLib, Gtk # noqa: E402
from subprocess import Popen, PIPE, check_output, STDOUT # noqa: E402
from subprocess import CalledProcessError # noqa: E402
from checkbox_support.parsers.modinfo import ModinfoParser # noqa: E402

handler = logging.StreamHandler()
Expand Down Expand Up @@ -77,19 +78,25 @@ def __init__(self):
w_table.attach(Gtk.Label(message), 0, 0, 4, 1)

w_table.attach(self.up_icon, 2, 2, 1, 1)
w_table.attach_next_to(self.debug_label, self.up_icon,
Gtk.PositionType.BOTTOM, 1, 1)
w_table.attach_next_to(self.down_icon, self.debug_label,
Gtk.PositionType.BOTTOM, 1, 1)
w_table.attach_next_to(self.left_icon, self.debug_label,
Gtk.PositionType.LEFT, 1, 1)
w_table.attach_next_to(self.right_icon, self.debug_label,
Gtk.PositionType.RIGHT, 1, 1)
w_table.attach_next_to(
self.debug_label, self.up_icon, Gtk.PositionType.BOTTOM, 1, 1
)
w_table.attach_next_to(
self.down_icon, self.debug_label, Gtk.PositionType.BOTTOM, 1, 1
)
w_table.attach_next_to(
self.left_icon, self.debug_label, Gtk.PositionType.LEFT, 1, 1
)
w_table.attach_next_to(
self.right_icon, self.debug_label, Gtk.PositionType.RIGHT, 1, 1
)

def update_axis_icon(self, direction):
"""Change desired directional icon to checkmark"""
exec('self.%s_icon.set_from_stock' % (direction) +
'(Gtk.STOCK_YES, size=Gtk.IconSize.BUTTON)')
exec(
"self.%s_icon.set_from_stock" % (direction)
+ "(Gtk.STOCK_YES, size=Gtk.IconSize.BUTTON)"
)

def update_debug_label(self, text):
"""Update axis information in center of UI"""
Expand Down Expand Up @@ -139,8 +146,9 @@ def __init__(self, device_path, ui_control=None):
def grab_current_readings(self):
"""Search device path and return axis tuple"""
time.sleep(0.5) # Sleep to accomodate slower processors
data_file = os.path.join("/sys", self.device_path,
"device", "position")
data_file = os.path.join(
"/sys", self.device_path, "device", "position"
)

# Try and retrieve positional data from kernel
try:
Expand Down Expand Up @@ -226,17 +234,22 @@ def insert_supported_module(oem_module):
"""Try and insert supported module to see if we get any init errors"""
try:
stream = check_output(
['modinfo', oem_module], stderr=STDOUT, universal_newlines=True)
["modinfo", oem_module], stderr=STDOUT, universal_newlines=True
)
except CalledProcessError as err:
print("Error accessing modinfo for %s: " % oem_module, file=sys.stderr)
print(err.output, file=sys.stderr)
return err.returncode

parser = ModinfoParser(stream)
module = os.path.basename(parser.get_field('filename'))
module = os.path.basename(parser.get_field("filename"))

insmod_output = Popen(['insmod %s' % module], stderr=PIPE,
shell=True, universal_newlines=True)
insmod_output = Popen(
["insmod %s" % module],
stderr=PIPE,
shell=True,
universal_newlines=True,
)

error = insmod_output.stderr.read()
if "Permission denied" in error:
Expand All @@ -248,13 +261,17 @@ def insert_supported_module(oem_module):
def check_module_status():
"""Looks to see if it can determine the hardware manufacturer
and report corresponding accelerometer driver status"""
oem_driver_pool = {"hewlett-packard": "hp_accel",
"toshiba": "hp_accel",
"ibm": "hdaps", "lenovo": "hdaps"}
oem_driver_pool = {
"hewlett-packard": "hp_accel",
"toshiba": "hp_accel",
"ibm": "hdaps",
"lenovo": "hdaps",
}

oem_module = None
dmi_info = Popen(['dmidecode'], stdout=PIPE, stderr=PIPE,
universal_newlines=True)
dmi_info = Popen(
["dmidecode"], stdout=PIPE, stderr=PIPE, universal_newlines=True
)

output, error = dmi_info.communicate()

Expand All @@ -281,7 +298,7 @@ def check_module_status():
if insert_supported_module(oem_module) is not None:
logging.error("Failed module insertion")
# Check dmesg status for supported module
driver_status = Popen(['dmesg'], stdout=PIPE, universal_newlines=True)
driver_status = Popen(["dmesg"], stdout=PIPE, universal_newlines=True)
module_regex = oem_module + ".*"
kernel_notes = re.findall(module_regex, driver_status.stdout.read())
# Report ALL findings, it's useful to note it the driver failed init
Expand Down Expand Up @@ -320,12 +337,20 @@ def main():

parser = ArgumentParser(description="Tests accelerometer functionality")

parser.add_argument('-m', '--manual', default=False,
action='store_true',
help="For manual test with visual notification")
parser.add_argument('-a', '--automated', default=True,
action='store_true',
help="For automated test using defined parameters")
parser.add_argument(
"-m",
"--manual",
default=False,
action="store_true",
help="For manual test with visual notification",
)
parser.add_argument(
"-a",
"--automated",
default=True,
action="store_true",
help="For automated test using defined parameters",
)

args = parser.parse_args()

Expand All @@ -350,5 +375,5 @@ def main():
time.sleep(5)


if __name__ == '__main__':
if __name__ == "__main__":
main()
38 changes: 20 additions & 18 deletions providers/base/bin/alsa_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,10 @@ def fft(x):
return x
even = fft(x[0::2])
odd = fft(x[1::2])
T = [cmath.exp(-2j*cmath.pi*k/N) * odd[k] for k in range(N//2)]
return ([even[k] + T[k] for k in range(N//2)] +
[even[k] - T[k] for k in range(N//2)])
T = [cmath.exp(-2j * cmath.pi * k / N) * odd[k] for k in range(N // 2)]
return [even[k] + T[k] for k in range(N // 2)] + [
even[k] - T[k] for k in range(N // 2)
]


def sine(freq, length, period_len, amplitude=0.5):
Expand All @@ -43,7 +44,8 @@ def sine(freq, length, period_len, amplitude=0.5):
sample = []
for i in range(period_len):
sample.append(
amplitude * math.sin(2 * math.pi * ((t + i) / (RATE / freq))))
amplitude * math.sin(2 * math.pi * ((t + i) / (RATE / freq)))
)
yield sample
t += period_len

Expand All @@ -53,7 +55,7 @@ def __init__(self, device=None):
if not device:
available_pcms = alsaaudio.pcms(alsaaudio.PCM_PLAYBACK)
if not available_pcms:
raise SystemExit('No PCMs detected')
raise SystemExit("No PCMs detected")
self.pcm = alsaaudio.PCM(device=available_pcms[0])
else:
self.pcm = alsaaudio.PCM(device=device)
Expand All @@ -62,10 +64,10 @@ def __init__(self, device=None):
self.pcm.setperiodsize(PERIOD)

def play(self, chunk):
assert (len(chunk) == PERIOD)
assert len(chunk) == PERIOD
# alsa expects bytes, so we need to repack the list of floats into a
# bytes sequence
buff = b''.join([struct.pack("<f", x) for x in chunk])
buff = b"".join([struct.pack("<f", x) for x in chunk])
self.pcm.write(buff)

@contextlib.contextmanager
Expand Down Expand Up @@ -139,7 +141,7 @@ def generator():
samples = samples[0:real_len]

Y = fft(samples)
freqs = [abs(y) for y in Y[:int(RATE/2)]]
freqs = [abs(y) for y in Y[: int(RATE / 2)]]
dominant = freqs.index(max(freqs)) / real_seconds
print("Dominant frequency is {}, expected {}".format(dominant, freq))

Expand All @@ -152,22 +154,22 @@ def generator():

def main():
actions = {
'playback': playback_test,
'loopback': loopback_test,
"playback": playback_test,
"loopback": loopback_test,
}
parser = argparse.ArgumentParser(description='Sound testing using ALSA')
parser.add_argument('action', metavar='ACTION', choices=actions.keys())
parser.add_argument('--duration', type=int, default=5)
parser.add_argument('--device', type=str)
parser = argparse.ArgumentParser(description="Sound testing using ALSA")
parser.add_argument("action", metavar="ACTION", choices=actions.keys())
parser.add_argument("--duration", type=int, default=5)
parser.add_argument("--device", type=str)
args = parser.parse_args()
if args.device:
device = args.device
elif 'ALSADEVICE' in os.environ:
device = os.environ['ALSADEVICE']
elif "ALSADEVICE" in os.environ:
device = os.environ["ALSADEVICE"]
else:
device = None
return (actions[args.action](args.duration, device))
return actions[args.action](args.duration, device)


if __name__ == '__main__':
if __name__ == "__main__":
sys.exit(main())
10 changes: 6 additions & 4 deletions providers/base/bin/ansi_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def parse_buffer(input):
row -= len(output)
elif ch in "K":
if escape == "1":
output[row] = " " * (col + 1) + output[row][col + 1:]
output[row] = " " * (col + 1) + output[row][col + 1 :]
elif escape == "2":
output[row] = ""
else:
Expand Down Expand Up @@ -104,7 +104,7 @@ def parse_buffer(input):
ch = "?"
if len(output[row]) < col:
output[row] += " " * (col - len(output[row]))
output[row] = output[row][:col] + ch + output[row][col + 1:]
output[row] = output[row][:col] + ch + output[row][col + 1 :]
col += 1

return "\n".join(output)
Expand All @@ -129,9 +129,11 @@ def main(args):
usage = "Usage: %prog [OPTIONS] [FILE...]"
parser = OptionParser(usage=usage)
parser.add_option(
"-o", "--output",
"-o",
"--output",
metavar="FILE",
help="File where to output the result.")
help="File where to output the result.",
)
(options, args) = parser.parse_args(args)

# Write to stdout
Expand Down
27 changes: 16 additions & 11 deletions providers/base/bin/audio_driver_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
name_regex = re.compile(r"(?<=name:).*")


class PacmdAudioDevice():
class PacmdAudioDevice:
"""
Class representing an audio device with information gathered from pacmd
"""
Expand All @@ -49,7 +49,7 @@ def __str__(self):
return retstr

def _modinfo_parser(self, driver):
cmd = ['/sbin/modinfo', driver]
cmd = ["/sbin/modinfo", driver]
try:
stream = check_output(cmd, stderr=STDOUT, universal_newlines=True)
except CalledProcessError as err:
Expand All @@ -68,13 +68,13 @@ def _modinfo_parser(self, driver):
def _find_driver_ver(self):
# try the version field first, then vermagic second, some audio
# drivers don't report version if the driver is in-tree
if self._modinfo['version']:
return self._modinfo['version']
if self._modinfo["version"]:
return self._modinfo["version"]
else:
# vermagic will look like this (below) and we only care about the
# first part:
# "3.2.0-29-generic SMP mod_unload modversions"
return self._modinfo['vermagic'].split()[0]
return self._modinfo["vermagic"].split()[0]


def list_device_info():
Expand All @@ -85,12 +85,14 @@ def list_device_info():
retval = 0
for vtype in TYPES:
try:
pacmd_entries = check_output(["pacmd", "list-%ss" % vtype],
universal_newlines=True)
pacmd_entries = check_output(
["pacmd", "list-%ss" % vtype], universal_newlines=True
)
except Exception as e:
print(
"Error when running pacmd list-%ss: %s" % (vtype, e),
file=sys.stderr)
file=sys.stderr,
)
return 1

entries = entries_regex.findall(pacmd_entries)
Expand All @@ -99,9 +101,12 @@ def list_device_info():
if name_match:
name = name_match.group().strip()
else:
print("Unable to determine device bus information from the"
" pacmd list-%ss output\npacmd output was: %s" %
(vtype, pacmd_entries), file=sys.stderr)
print(
"Unable to determine device bus information from the"
" pacmd list-%ss output\npacmd output was: %s"
% (vtype, pacmd_entries),
file=sys.stderr,
)
return 1

driver_name = driver_regex.findall(entry)
Expand Down
Loading

0 comments on commit bb3a1be

Please sign in to comment.