Skip to content

Commit

Permalink
Enable and fix more ruff lints
Browse files Browse the repository at this point in the history
  • Loading branch information
daoo committed Oct 20, 2024
1 parent b671540 commit d79ec12
Show file tree
Hide file tree
Showing 39 changed files with 142 additions and 99 deletions.
14 changes: 8 additions & 6 deletions autodesk/__main__.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import logging
import os
from contextlib import closing

import yaml
from aiohttp import web
from pandas import Timedelta

from autodesk.api import setup_app
from autodesk.application.autodeskservicefactory import AutoDeskServiceFactory
from autodesk.hardware import create_pin_factory
from contextlib import closing
from pandas import Timedelta
import logging
import os
import yaml


def read_yaml(path):
with open(path, "r") as file:
with open(path) as file:
return yaml.load(file, Loader=yaml.SafeLoader)


Expand Down
16 changes: 9 additions & 7 deletions autodesk/api.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
from aiohttp import web
from autodesk.button import Button
from autodesk.hardware.error import HardwareError
from autodesk.states import Desk, Session, deserialize_session, deserialize_desk
import aiohttp_jinja2
import asyncio
import autodesk.plots as plots
import jinja2
import logging
import traceback

import aiohttp_jinja2
import jinja2
from aiohttp import web

import autodesk.plots as plots
from autodesk.button import Button
from autodesk.hardware.error import HardwareError
from autodesk.states import Desk, Session, deserialize_desk, deserialize_session

logger = logging.getLogger("api")


Expand Down
4 changes: 2 additions & 2 deletions autodesk/application/autodeskservicefactory.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from pandas import Timedelta

from autodesk.application.autodeskservice import AutoDeskService
from autodesk.application.deskservice import DeskService
from autodesk.application.sessionservice import SessionService
Expand All @@ -10,8 +12,6 @@
from autodesk.sqlitedatastore import SqliteDataStore
from autodesk.timer import Timer

from pandas import Timedelta


class AutoDeskServiceFactory:
def __init__(
Expand Down
3 changes: 2 additions & 1 deletion autodesk/application/deskservice.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from autodesk.hardware.error import HardwareError
import logging

from autodesk.hardware.error import HardwareError


class DeskService:
def __init__(self, operation, model, desk_controller, time_service):
Expand Down
4 changes: 2 additions & 2 deletions autodesk/application/sessionservice.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from autodesk.application.timeservice import TimeService
from autodesk.hardware.error import HardwareError
import logging

from autodesk.application.timeservice import TimeService
from autodesk.hardware.error import HardwareError
from autodesk.lightcontroller import LightController
from autodesk.model import Model
from autodesk.states import Session
Expand Down
1 change: 1 addition & 0 deletions autodesk/hardware/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from autodesk.hardware.logging import LoggingPinFactory

import logging


Expand Down
11 changes: 6 additions & 5 deletions autodesk/hardware/ft232h.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from autodesk.hardware.error import HardwareError
from pyftdi.ftdi import FtdiError
from pyftdi.gpio import GpioMpsseController
from pyftdi.usbtools import UsbTools, UsbToolsError
from usb.core import USBError

from autodesk.hardware.error import HardwareError


def set_bit(mask, bit, value):
if value == 0:
Expand Down Expand Up @@ -34,7 +35,7 @@ def _setup(self):
invalid_pins = ((valid_pins | used_pins) & ~valid_pins) & used_pins
if invalid_pins != 0:
formatted = [i for i in range(0, 16) if invalid_pins & 1 << i != 0]
raise HardwareError("Cannot use pin(s) {} as GPIO.".format(formatted))
raise HardwareError(f"Cannot use pin(s) {formatted} as GPIO.")
# A low bit (equal to 0) indicates an input pin.
# A high bit (equal to 1) indicates an output pin.
new_direction = self.output_pins & ~self.input_pins
Expand Down Expand Up @@ -90,8 +91,8 @@ def _reconnect_and_try_again(self, action):
self.disconnect()
self._connect()
return action()
except FtdiError:
raise HardwareError(error1)
except FtdiError as err:
raise HardwareError(error1) from err

def read(self, pin):
return self._reconnect_and_try_again(lambda: self._read_no_error_handling(pin))
Expand All @@ -107,7 +108,7 @@ def __init__(self, wrapper, pin):

def write(self, value):
if value != 0 and value != 1:
raise ValueError("Pin value must be 0 or 1 but got {0}".format(value))
raise ValueError(f"Pin value must be 0 or 1 but got {value}")
self.wrapper.write(self.pin, value)


Expand Down
2 changes: 1 addition & 1 deletion autodesk/hardware/raspberrypi.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def __init__(self, pin):

def write(self, value):
if value != 0 and value != 1:
raise ValueError("Pin value must be 0 or 1 but got {0}".format(value))
raise ValueError(f"Pin value must be 0 or 1 but got {value}")
gpio_value = GPIO.LOW if value == 0 else GPIO.HIGH
GPIO.output(self.pin, gpio_value)

Expand Down
13 changes: 8 additions & 5 deletions autodesk/model.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from autodesk.sqlitedatastore import SqliteDataStore
from autodesk.states import INACTIVE, ACTIVE, DOWN, Desk, Session
from typing import Any, Generator
from pandas import Timedelta, Timestamp
from collections.abc import Generator
from typing import Any

import numpy as np
import pandas as pd
from pandas import Timedelta, Timestamp

from autodesk.sqlitedatastore import SqliteDataStore
from autodesk.states import ACTIVE, DOWN, INACTIVE, Desk, Session


def enumerate_hours(start, end) -> Generator[tuple[int, int], None, None]:
Expand Down Expand Up @@ -102,7 +105,7 @@ def get_active_time(self, initial: Timestamp, final: Timestamp) -> Timedelta:
def compute_hourly_count(self, initial: Timestamp, final: Timestamp):
spans = self.get_session_spans(initial, final)

rows = np.zeros((7 * 24))
rows = np.zeros(7 * 24)
for span in spans[spans.state == ACTIVE].itertuples():
for day, hour in enumerate_hours(span.start, span.end):
rows[day * 24 + hour] += 1
Expand Down
5 changes: 3 additions & 2 deletions autodesk/operation.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from autodesk.states import ACTIVE
from datetime import time
import logging
from datetime import time

from autodesk.states import ACTIVE


class Operation:
Expand Down
3 changes: 2 additions & 1 deletion autodesk/plots.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from io import BytesIO
import base64
from io import BytesIO

import matplotlib.pyplot as plt


Expand Down
3 changes: 2 additions & 1 deletion bin/ft232h-button-test.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#!/usr/bin/env python
from pyftdi.gpio import GpioMpsseController
import time

from pyftdi.gpio import GpioMpsseController

pin = 4
delay = 0.1
controller = GpioMpsseController()
Expand Down
3 changes: 2 additions & 1 deletion bin/ft232h-control.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#!/usr/bin/env python
from pyftdi.gpio import GpioMpsseController
import time

from pyftdi.gpio import GpioMpsseController


def toggle(gpio, delay):
gpio.write(0x0000 & gpio.direction)
Expand Down
5 changes: 3 additions & 2 deletions bin/ft232h-reconnect-test.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env python
from pyftdi.gpio import GpioMpsseController
import traceback

from pyftdi.gpio import GpioMpsseController
from pyftdi.usbtools import UsbTools

print("Creating, configuring, writing and closing a GpioMpsseController...")
Expand All @@ -11,7 +12,7 @@
gpio = controller.get_gpio()
gpio.write(0xFFFF & gpio.direction) # type: ignore
value = gpio.read()[0] # type: ignore
print(" Success (read {0})!".format(hex(value)))
print(f" Success (read {hex(value)})!")

input("Now, disconnect and reconnect hardware and press enter.")
try:
Expand Down
9 changes: 5 additions & 4 deletions bin/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@
# ]
# ///

import sys
from datetime import datetime

import requests
from gi.repository import GLib
from pydbus import SystemBus
import requests
import sys


def notify(url, active):
Expand All @@ -31,7 +32,7 @@ def program(hostname):
bus = SystemBus()
login = bus.get("org.freedesktop.login1")
for _, _, _, _, path in login.ListSessions():
print("Connecting to {}".format(path))
print(f"Connecting to {path}")
sessionbus = bus.get("org.freedesktop.login1", path)
sessionbus.PropertiesChanged.connect(
lambda interface, changed, invalidated: properties_handler(
Expand All @@ -43,7 +44,7 @@ def program(hostname):

def main():
if len(sys.argv) != 2:
sys.stderr.write("Usage: {} URL\n".format(sys.argv[0]))
sys.stderr.write(f"Usage: {sys.argv[0]} URL\n")
sys.exit(1)

try:
Expand Down
7 changes: 4 additions & 3 deletions bin/migrator.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import pandas as pd
import sqlite3
import sys

import pandas as pd

old = sqlite3.connect(sys.argv[1])
desks = pd.read_sql_query("SELECT * FROM desk ORDER BY date ASC", old)
sessions = pd.read_sql_query("SELECT * FROM session ORDER BY date ASC", old)
Expand All @@ -13,12 +14,12 @@

for desk in desks.itertuples():
state = "up" if desk.state == 1 else "down"
print("INSERT INTO desk values({0}, {1})".format(desk.date, state))
print(f"INSERT INTO desk values({desk.date}, {state})")
new.execute("INSERT INTO desk values(?, ?)", (desk.date, state))

for session in sessions.itertuples():
state = "active" if session.active == 1 else "inactive"
print("INSERT INTO session values({0}, {1})".format(session.date, state))
print(f"INSERT INTO session values({session.date}, {state})")
new.execute("INSERT INTO session values(?, ?)", (session.date, state))

new.commit()
Expand Down
6 changes: 4 additions & 2 deletions bin/plot.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import sys

from pandas import Timestamp

from autodesk.model import Model
from autodesk.plots import plot_weekday_hourly_count
from autodesk.sqlitedatastore import SqliteDataStore
from pandas import Timestamp
import sys

model = Model(SqliteDataStore.open(sys.argv[1]))
figure = plot_weekday_hourly_count(
Expand Down
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,8 @@ dev-dependencies = [
"ruff>=0.6.8",
]

[tool.ruff.lint]
select = ["F", "E", "W", "N", "UP", "ASYNC", "A", "C4"]

[tool.pytest.ini_options]
asyncio_default_fixture_loop_scope = "function"
6 changes: 3 additions & 3 deletions tests/autodeskservice.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from pandas import Timedelta, Timestamp

from autodesk.application.autodeskservice import AutoDeskService
from autodesk.operation import Operation
from autodesk.scheduler import Scheduler
from autodesk.states import INACTIVE, ACTIVE
from pandas import Timestamp, Timedelta

from autodesk.states import ACTIVE, INACTIVE

TIME_ALLOWED = Timestamp(2018, 4, 23, 13, 0)
TIME_DENIED = Timestamp(2018, 4, 23, 21, 0)
Expand Down
15 changes: 8 additions & 7 deletions tests/component/test_api.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
import base64
import os

import pytest
from pandas import Timedelta, Timestamp

import autodesk.api as api
from autodesk.application.autodeskservice import AutoDeskService
from autodesk.application.deskservice import DeskService
from autodesk.application.sessionservice import SessionService
Expand All @@ -7,14 +14,8 @@
from autodesk.model import Model
from autodesk.operation import Operation
from autodesk.scheduler import Scheduler
from autodesk.states import DOWN, UP, INACTIVE, ACTIVE
from pandas import Timestamp, Timedelta
from autodesk.states import ACTIVE, DOWN, INACTIVE, UP
from tests.stubdatastore import fake_data_store
import autodesk.api as api
import base64
import os
import pytest


SESSION_EVENTS = [
# Tuesdays
Expand Down
3 changes: 2 additions & 1 deletion tests/integration/test_program.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import os
import subprocess

import pytest
import requests
import subprocess


@pytest.fixture
Expand Down
8 changes: 5 additions & 3 deletions tests/unit/test_api.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from autodesk.hardware.error import HardwareError
from autodesk.states import DOWN, UP, INACTIVE, ACTIVE
import asyncio
import autodesk.api as api

import pytest

import autodesk.api as api
from autodesk.hardware.error import HardwareError
from autodesk.states import ACTIVE, DOWN, INACTIVE, UP


@pytest.fixture
def service_mock(mocker):
Expand Down
7 changes: 4 additions & 3 deletions tests/unit/test_autodeskservice_desk.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import pytest
from pandas import Timedelta

from autodesk.hardware.error import HardwareError
from autodesk.states import ACTIVE, DOWN, UP
from pandas import Timedelta
from tests.autodeskservice import TIME_ALLOWED, DESK_DENIED, create_service
import pytest
from tests.autodeskservice import DESK_DENIED, TIME_ALLOWED, create_service


@pytest.mark.parametrize("session,now", DESK_DENIED)
Expand Down
5 changes: 3 additions & 2 deletions tests/unit/test_autodeskservice_init.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from autodesk.hardware.error import HardwareError
from autodesk.states import INACTIVE, ACTIVE, DOWN
from pandas import Timedelta

from autodesk.hardware.error import HardwareError
from autodesk.states import ACTIVE, DOWN, INACTIVE
from tests.autodeskservice import TIME_ALLOWED, TIME_DENIED, create_service


Expand Down
5 changes: 3 additions & 2 deletions tests/unit/test_autodeskservice_session.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from autodesk.hardware.error import HardwareError
from autodesk.states import INACTIVE, ACTIVE, DOWN, UP
from pandas import Timedelta

from autodesk.hardware.error import HardwareError
from autodesk.states import ACTIVE, DOWN, INACTIVE, UP
from tests.autodeskservice import TIME_ALLOWED, create_service


Expand Down
Loading

0 comments on commit d79ec12

Please sign in to comment.