code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def get_backend(backend): """Figure out which backend to use.""" if backend == "random": backends = list_backends() random.shuffle(backends) return backends[0] return backend
Figure out which backend to use.
get_backend
python
dylanaraps/pywal
pywal/colors.py
https://github.com/dylanaraps/pywal/blob/master/pywal/colors.py
MIT
def template(colors, input_file, output_file=None): """Read template file, substitute markers and save the file elsewhere.""" # pylint: disable-msg=too-many-locals template_data = util.read_file_raw(input_file) for i, l in enumerate(template_data): for match in re.finditer(r"(?<=(?<!\{))(...
Read template file, substitute markers and save the file elsewhere.
template
python
dylanaraps/pywal
pywal/export.py
https://github.com/dylanaraps/pywal/blob/master/pywal/export.py
MIT
def flatten_colors(colors): """Prepare colors to be exported. Flatten dicts and convert colors to util.Color()""" all_colors = {"wallpaper": colors["wallpaper"], "alpha": colors["alpha"], **colors["special"], **colors["colors"]} return {k: util.Co...
Prepare colors to be exported. Flatten dicts and convert colors to util.Color()
flatten_colors
python
dylanaraps/pywal
pywal/export.py
https://github.com/dylanaraps/pywal/blob/master/pywal/export.py
MIT
def get_export_type(export_type): """Convert template type to the right filename.""" return { "css": "colors.css", "dmenu": "colors-wal-dmenu.h", "dwm": "colors-wal-dwm.h", "st": "colors-wal-st.h", "tabbed": "colors-wal-tabbed.h", "gtk2": "colors-gtk2.rc", ...
Convert template type to the right filename.
get_export_type
python
dylanaraps/pywal
pywal/export.py
https://github.com/dylanaraps/pywal/blob/master/pywal/export.py
MIT
def get_image_dir_recursive(img_dir): """Get all images in a directory recursively.""" current_wall = wallpaper.get() current_wall = os.path.basename(current_wall) file_types = (".png", ".jpg", ".jpeg", ".jpe", ".gif") images = [] for path, _, files in os.walk(img_dir): for name in fil...
Get all images in a directory recursively.
get_image_dir_recursive
python
dylanaraps/pywal
pywal/image.py
https://github.com/dylanaraps/pywal/blob/master/pywal/image.py
MIT
def get_random_image(img_dir, recursive): """Pick a random image file from a directory.""" if recursive: images, current_wall = get_image_dir_recursive(img_dir) else: images, current_wall = get_image_dir(img_dir) if len(images) > 2 and current_wall in images: images.remove(curre...
Pick a random image file from a directory.
get_random_image
python
dylanaraps/pywal
pywal/image.py
https://github.com/dylanaraps/pywal/blob/master/pywal/image.py
MIT
def get_next_image(img_dir, recursive): """Get the next image in a dir.""" if recursive: images, current_wall = get_image_dir_recursive(img_dir) else: images, current_wall = get_image_dir(img_dir) images.sort(key=lambda img: [int(x) if x.isdigit() else x ...
Get the next image in a dir.
get_next_image
python
dylanaraps/pywal
pywal/image.py
https://github.com/dylanaraps/pywal/blob/master/pywal/image.py
MIT
def xrdb(xrdb_files=None): """Merge the colors into the X db so new terminals use them.""" xrdb_files = xrdb_files or \ [os.path.join(CACHE_DIR, "colors.Xresources")] if shutil.which("xrdb") and OS != "Darwin": for file in xrdb_files: subprocess.run(["xrdb", "-merge", "-quiet", ...
Merge the colors into the X db so new terminals use them.
xrdb
python
dylanaraps/pywal
pywal/reload.py
https://github.com/dylanaraps/pywal/blob/master/pywal/reload.py
MIT
def gtk(): """Reload GTK theme on the fly.""" # Here we call a Python 2 script to reload the GTK themes. # This is done because the Python 3 GTK/Gdk libraries don't # provide a way of doing this. if shutil.which("python2"): gtk_reload = os.path.join(MODULE_DIR, "scripts", "gtk_reload.py") ...
Reload GTK theme on the fly.
gtk
python
dylanaraps/pywal
pywal/reload.py
https://github.com/dylanaraps/pywal/blob/master/pywal/reload.py
MIT
def set_special(index, color, iterm_name="h", alpha=100): """Convert a hex color to a special sequence.""" if OS == "Darwin" and iterm_name: return "\033]P%s%s\033\\" % (iterm_name, color.strip("#")) if index in [11, 708] and alpha != "100": return "\033]%s;[%s]%s\033\\" % (index, alpha, co...
Convert a hex color to a special sequence.
set_special
python
dylanaraps/pywal
pywal/sequences.py
https://github.com/dylanaraps/pywal/blob/master/pywal/sequences.py
MIT
def set_color(index, color): """Convert a hex color to a text color sequence.""" if OS == "Darwin" and index < 20: return "\033]P%1x%s\033\\" % (index, color.strip("#")) return "\033]4;%s;%s\033\\" % (index, color)
Convert a hex color to a text color sequence.
set_color
python
dylanaraps/pywal
pywal/sequences.py
https://github.com/dylanaraps/pywal/blob/master/pywal/sequences.py
MIT
def send(colors, cache_dir=CACHE_DIR, to_send=True, vte_fix=False): """Send colors to all open terminals.""" if OS == "Darwin": tty_pattern = "/dev/ttys00[0-9]*" else: tty_pattern = "/dev/pts/[0-9]*" sequences = create_sequences(colors, vte_fix) # Writing to "/dev/pts/[0-9] lets y...
Send colors to all open terminals.
send
python
dylanaraps/pywal
pywal/sequences.py
https://github.com/dylanaraps/pywal/blob/master/pywal/sequences.py
MIT
def list_out(): """List all themes in a pretty format.""" dark_themes = [theme.name.replace(".json", "") for theme in list_themes()] ligh_themes = [theme.name.replace(".json", "") for theme in list_themes(dark=False)] user_themes = [theme.name.replace(".json", "") ...
List all themes in a pretty format.
list_out
python
dylanaraps/pywal
pywal/theme.py
https://github.com/dylanaraps/pywal/blob/master/pywal/theme.py
MIT
def terminal_sexy_to_wal(data): """Convert terminal.sexy json schema to wal.""" data["colors"] = {} data["special"] = { "foreground": data["foreground"], "background": data["background"], "cursor": data["color"][9] } for i, color in enumerate(data["color"]): data["co...
Convert terminal.sexy json schema to wal.
terminal_sexy_to_wal
python
dylanaraps/pywal
pywal/theme.py
https://github.com/dylanaraps/pywal/blob/master/pywal/theme.py
MIT
def get_random_theme_user(): """Get a random theme file from user theme directories.""" themes = [theme.path for theme in list_themes_user()] random.shuffle(themes) return themes[0]
Get a random theme file from user theme directories.
get_random_theme_user
python
dylanaraps/pywal
pywal/theme.py
https://github.com/dylanaraps/pywal/blob/master/pywal/theme.py
MIT
def hex_to_xrgba(color): """Convert a hex color to xrdb rgba.""" col = color.lower().strip("#") return "%s%s/%s%s/%s%s/ff" % (*col,)
Convert a hex color to xrdb rgba.
hex_to_xrgba
python
dylanaraps/pywal
pywal/util.py
https://github.com/dylanaraps/pywal/blob/master/pywal/util.py
MIT
def get_pid(name): """Check if process is running by name.""" if not shutil.which("pidof"): return False try: if platform.system() != 'Darwin': subprocess.check_output(["pidof", "-s", name]) else: subprocess.check_output(["pidof", name]) except subproces...
Check if process is running by name.
get_pid
python
dylanaraps/pywal
pywal/util.py
https://github.com/dylanaraps/pywal/blob/master/pywal/util.py
MIT
def get_desktop_env(): """Identify the current running desktop environment.""" desktop = os.environ.get("XDG_CURRENT_DESKTOP") if desktop: return desktop desktop = os.environ.get("DESKTOP_SESSION") if desktop: return desktop desktop = os.environ.get("GNOME_DESKTOP_SESSION_ID") ...
Identify the current running desktop environment.
get_desktop_env
python
dylanaraps/pywal
pywal/wallpaper.py
https://github.com/dylanaraps/pywal/blob/master/pywal/wallpaper.py
MIT
def xfconf(img): """Call xfconf to set the wallpaper on XFCE.""" xfconf_re = re.compile( r"^/backdrop/screen\d/monitor(?:0|\w*)/" r"(?:(?:image-path|last-image)|workspace\d/last-image)$", flags=re.M ) xfconf_data = subprocess.check_output( ["xfconf-query", "--channel", "x...
Call xfconf to set the wallpaper on XFCE.
xfconf
python
dylanaraps/pywal
pywal/wallpaper.py
https://github.com/dylanaraps/pywal/blob/master/pywal/wallpaper.py
MIT
def set_wm_wallpaper(img): """Set the wallpaper for non desktop environments.""" if shutil.which("feh"): util.disown(["feh", "--bg-fill", img]) elif shutil.which("xwallpaper"): util.disown(["xwallpaper", "--zoom", img]) elif shutil.which("hsetroot"): util.disown(["hsetroot", "-...
Set the wallpaper for non desktop environments.
set_wm_wallpaper
python
dylanaraps/pywal
pywal/wallpaper.py
https://github.com/dylanaraps/pywal/blob/master/pywal/wallpaper.py
MIT
def set_desktop_wallpaper(desktop, img): """Set the wallpaper for the desktop environment.""" desktop = str(desktop).lower() if "xfce" in desktop or "xubuntu" in desktop: xfconf(img) elif "muffin" in desktop or "cinnamon" in desktop: util.disown(["gsettings", "set", ...
Set the wallpaper for the desktop environment.
set_desktop_wallpaper
python
dylanaraps/pywal
pywal/wallpaper.py
https://github.com/dylanaraps/pywal/blob/master/pywal/wallpaper.py
MIT
def has_im(): """Check to see if the user has im installed.""" if shutil.which("magick"): return ["magick", "convert"] if shutil.which("convert"): return ["convert"] logging.error("Imagemagick wasn't found on your system.") logging.error("Try another backend. (wal --backend)") ...
Check to see if the user has im installed.
has_im
python
dylanaraps/pywal
pywal/backends/wal.py
https://github.com/dylanaraps/pywal/blob/master/pywal/backends/wal.py
MIT
def gen_colors(img): """Format the output from imagemagick into a list of hex colors.""" magick_command = has_im() for i in range(0, 20, 1): raw_colors = imagemagick(16 + i, img, magick_command) if len(raw_colors) > 16: break if i == 19: logging.erro...
Format the output from imagemagick into a list of hex colors.
gen_colors
python
dylanaraps/pywal
pywal/backends/wal.py
https://github.com/dylanaraps/pywal/blob/master/pywal/backends/wal.py
MIT
def adjust(colors, light): """Adjust the generated colors and store them in a dict that we will later save in json format.""" raw_colors = colors[:1] + colors[8:16] + colors[8:-1] # Manually adjust colors. if light: for color in raw_colors: color = util.saturate_color(color, ...
Adjust the generated colors and store them in a dict that we will later save in json format.
adjust
python
dylanaraps/pywal
pywal/backends/wal.py
https://github.com/dylanaraps/pywal/blob/master/pywal/backends/wal.py
MIT
def test_css_template(self): """> Test substitutions in template file (css).""" tmp_file = os.path.join(TMP_DIR, "test.css") export.color(COLORS, "css", tmp_file) self.is_file(tmp_file) self.is_file_contents(tmp_file, " --background: #1F211E;")
> Test substitutions in template file (css).
test_css_template
python
dylanaraps/pywal
tests/test_export.py
https://github.com/dylanaraps/pywal/blob/master/tests/test_export.py
MIT
def test_set_special_alpha(self): """> Create special escape sequence with alpha.""" alpha = "99" result = sequences.set_special(11, COLORS["special"]["background"], "h", alpha) if platform.uname()[0] == "Darw...
> Create special escape sequence with alpha.
test_set_special_alpha
python
dylanaraps/pywal
tests/test_sequences.py
https://github.com/dylanaraps/pywal/blob/master/tests/test_sequences.py
MIT
def verify_checksum(self, subtests, dbc_file: str, msg_name: str, msg_addr: int, test_messages: list[bytes], checksum_field: str = 'CHECKSUM', counter_field = 'COUNTER'): """ Verify that opendbc calculates payload CRCs/checksums matching those received in known-good sample messages Dep...
Verify that opendbc calculates payload CRCs/checksums matching those received in known-good sample messages Depends on all non-zero bits in the sample message having a corresponding DBC signal, add UNKNOWN signals if needed
verify_checksum
python
commaai/opendbc
opendbc/can/tests/test_checksums.py
https://github.com/commaai/opendbc/blob/master/opendbc/can/tests/test_checksums.py
MIT
def verify_fca_giorgio_crc(self, subtests, msg_name: str, msg_addr: int, test_messages: list[bytes]): """Test modified SAE J1850 CRCs, with special final XOR cases for EPS messages""" assert len(test_messages) == 3 self.verify_checksum(subtests, "fca_giorgio", msg_name, msg_addr, test_messages)
Test modified SAE J1850 CRCs, with special final XOR cases for EPS messages
verify_fca_giorgio_crc
python
commaai/opendbc
opendbc/can/tests/test_checksums.py
https://github.com/commaai/opendbc/blob/master/opendbc/can/tests/test_checksums.py
MIT
def test_honda_checksum(self): """Test checksums for Honda standard and extended CAN ids""" # TODO: refactor to use self.verify_checksum() dbc_file = "honda_accord_2018_can_generated" msgs = [("LKAS_HUD", 0), ("LKAS_HUD_A", 0)] parser = CANParser(dbc_file, msgs, 0) packer = CANPacker(dbc_file) ...
Test checksums for Honda standard and extended CAN ids
test_honda_checksum
python
commaai/opendbc
opendbc/can/tests/test_checksums.py
https://github.com/commaai/opendbc/blob/master/opendbc/can/tests/test_checksums.py
MIT
def test_parse_all_dbcs(self, subtests): """ Dynamic DBC parser checks: - Checksum and counter length, start bit, endianness - Duplicate message addresses and names - Signal out of bounds - All BO_, SG_, VAL_ lines for syntax errors """ for dbc in ALL_DBCS: with ...
Dynamic DBC parser checks: - Checksum and counter length, start bit, endianness - Duplicate message addresses and names - Signal out of bounds - All BO_, SG_, VAL_ lines for syntax errors
test_parse_all_dbcs
python
commaai/opendbc
opendbc/can/tests/test_dbc_parser.py
https://github.com/commaai/opendbc/blob/master/opendbc/can/tests/test_dbc_parser.py
MIT
def test_parser_counter_can_valid(self): """ Tests number of allowed bad counters + ensures CAN stays invalid while receiving invalid messages + that we can recover """ msgs = [ ("STEERING_CONTROL", 0), ] packer = CANPacker("honda_civic_touring_2016_can_generated") parser = CANPars...
Tests number of allowed bad counters + ensures CAN stays invalid while receiving invalid messages + that we can recover
test_parser_counter_can_valid
python
commaai/opendbc
opendbc/can/tests/test_packer_parser.py
https://github.com/commaai/opendbc/blob/master/opendbc/can/tests/test_packer_parser.py
MIT
def test_parser_no_partial_update(self): """ Ensure that the CANParser doesn't partially update messages with invalid signals (COUNTER/CHECKSUM). Previously, the signal update loop would only break once it got to one of these invalid signals, after already updating most/all of the signals. """ m...
Ensure that the CANParser doesn't partially update messages with invalid signals (COUNTER/CHECKSUM). Previously, the signal update loop would only break once it got to one of these invalid signals, after already updating most/all of the signals.
test_parser_no_partial_update
python
commaai/opendbc
opendbc/can/tests/test_packer_parser.py
https://github.com/commaai/opendbc/blob/master/opendbc/can/tests/test_packer_parser.py
MIT
def test_scale_offset(self): """Test that both scale and offset are correctly preserved""" dbc_file = "honda_civic_touring_2016_can_generated" msgs = [("VSA_STATUS", 50)] parser = CANParser(dbc_file, msgs, 0) packer = CANPacker(dbc_file) for brake in range(100): values = {"USER_BRAKE": br...
Test that both scale and offset are correctly preserved
test_scale_offset
python
commaai/opendbc
opendbc/can/tests/test_packer_parser.py
https://github.com/commaai/opendbc/blob/master/opendbc/can/tests/test_packer_parser.py
MIT
def disable_ecu(can_recv, can_send, bus=0, addr=0x7d0, sub_addr=None, com_cont_req=b'\x28\x83\x01', timeout=0.1, retry=10): """Silence an ECU by disabling sending and receiving messages using UDS 0x28. The ECU will stay silent as long as openpilot keeps sending Tester Present. This is used to disable the radar i...
Silence an ECU by disabling sending and receiving messages using UDS 0x28. The ECU will stay silent as long as openpilot keeps sending Tester Present. This is used to disable the radar in some cars. Openpilot will emulate the radar. WARNING: THIS DISABLES AEB!
disable_ecu
python
commaai/opendbc
opendbc/car/disable_ecu.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/disable_ecu.py
MIT
def eliminate_incompatible_cars(msg, candidate_cars): """Removes cars that could not have sent msg. Inputs: msg: A cereal/log CanData message from the car. candidate_cars: A list of cars to consider. Returns: A list containing the subset of candidate_cars that could have sent msg. """ ...
Removes cars that could not have sent msg. Inputs: msg: A cereal/log CanData message from the car. candidate_cars: A list of cars to consider. Returns: A list containing the subset of candidate_cars that could have sent msg.
eliminate_incompatible_cars
python
commaai/opendbc
opendbc/car/fingerprints.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/fingerprints.py
MIT
def match_fw_to_car_fuzzy(live_fw_versions: LiveFwVersions, match_brand: str = None, log: bool = True, exclude: str = None) -> set[str]: """Do a fuzzy FW match. This function will return a match, and the number of firmware version that were matched uniquely to that specific car. If multiple ECUs uniquely match to d...
Do a fuzzy FW match. This function will return a match, and the number of firmware version that were matched uniquely to that specific car. If multiple ECUs uniquely match to different cars the match is rejected.
match_fw_to_car_fuzzy
python
commaai/opendbc
opendbc/car/fw_versions.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/fw_versions.py
MIT
def match_fw_to_car_exact(live_fw_versions: LiveFwVersions, match_brand: str = None, log: bool = True, extra_fw_versions: dict = None) -> set[str]: """Do an exact FW match. Returns all cars that match the given FW versions for a list of "essential" ECUs. If an ECU is not considered essential the FW version can be...
Do an exact FW match. Returns all cars that match the given FW versions for a list of "essential" ECUs. If an ECU is not considered essential the FW version can be missing to get a fingerprint, but if it's present it needs to match the database.
match_fw_to_car_exact
python
commaai/opendbc
opendbc/car/fw_versions.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/fw_versions.py
MIT
def get_brand_ecu_matches(ecu_rx_addrs: set[EcuAddrBusType]) -> dict[str, list[bool]]: """Returns dictionary of brands and matches with ECUs in their FW versions""" brand_rx_addrs = {brand: set() for brand in FW_QUERY_CONFIGS} brand_matches = {brand: [] for brand, _, _ in REQUESTS} # Since we can't know what ...
Returns dictionary of brands and matches with ECUs in their FW versions
get_brand_ecu_matches
python
commaai/opendbc
opendbc/car/fw_versions.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/fw_versions.py
MIT
def get_fw_versions_ordered(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_multiplexing: ObdCallback, vin: str, ecu_rx_addrs: set[EcuAddrBusType], timeout: float = 0.1, num_pandas: int = 1, progress: bool = False) -> list[CarParams.CarFw]: """Queries for FW versions ordering...
Queries for FW versions ordering brands by likelihood, breaks when exact match is found
get_fw_versions_ordered
python
commaai/opendbc
opendbc/car/fw_versions.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/fw_versions.py
MIT
def update_blinker_from_lamp(self, blinker_time: int, left_blinker_lamp: bool, right_blinker_lamp: bool): """Update blinkers from lights. Enable output when light was seen within the last `blinker_time` iterations""" # TODO: Handle case when switching direction. Now both blinkers can be on at the same time ...
Update blinkers from lights. Enable output when light was seen within the last `blinker_time` iterations
update_blinker_from_lamp
python
commaai/opendbc
opendbc/car/interfaces.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/interfaces.py
MIT
def update_steering_pressed(self, steering_pressed, steering_pressed_min_count): """Applies filtering on steering pressed for noisy driver torque signals.""" self.steering_pressed_cnt += 1 if steering_pressed else -1 self.steering_pressed_cnt = int(np.clip(self.steering_pressed_cnt, 0, steering_pressed_min_...
Applies filtering on steering pressed for noisy driver torque signals.
update_steering_pressed
python
commaai/opendbc
opendbc/car/interfaces.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/interfaces.py
MIT
def update_blinker_from_stalk(self, blinker_time: int, left_blinker_stalk: bool, right_blinker_stalk: bool): """Update blinkers from stalk position. When stalk is seen the blinker will be on for at least blinker_time, or until the stalk is turned off, whichever is longer. If the opposite stalk direction is seen...
Update blinkers from stalk position. When stalk is seen the blinker will be on for at least blinker_time, or until the stalk is turned off, whichever is longer. If the opposite stalk direction is seen the blinker is forced to the other side. On a rising edge of the stalk the timeout is reset.
update_blinker_from_stalk
python
commaai/opendbc
opendbc/car/interfaces.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/interfaces.py
MIT
def rx(self) -> None: """Drain can socket and sort messages into buffers based on address""" can_packets = self.can_recv(wait_for_one=True) for packet in can_packets: for msg in packet: if msg.src == self.bus and msg.address in self.msg_addrs.values(): self.msg_buffer[msg.address].a...
Drain can socket and sort messages into buffers based on address
rx
python
commaai/opendbc
opendbc/car/isotp_parallel_query.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/isotp_parallel_query.py
MIT
def _can_rx(self, addr, sub_addr=None): """Helper function to retrieve message with specified address and subaddress from buffer""" keep_msgs = [] if sub_addr is None: msgs = self.msg_buffer[addr] else: # Filter based on subaddress msgs = [] for m in self.msg_buffer[addr]: ...
Helper function to retrieve message with specified address and subaddress from buffer
_can_rx
python
commaai/opendbc
opendbc/car/isotp_parallel_query.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/isotp_parallel_query.py
MIT
def update_params(self, stiffness_factor: float, steer_ratio: float) -> None: """Update the vehicle model with a new stiffness factor and steer ratio""" self.cF: float = stiffness_factor * self.cF_orig self.cR: float = stiffness_factor * self.cR_orig self.sR: float = steer_ratio
Update the vehicle model with a new stiffness factor and steer ratio
update_params
python
commaai/opendbc
opendbc/car/vehicle_model.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/vehicle_model.py
MIT
def steady_state_sol(self, sa: float, u: float, roll: float) -> np.ndarray: """Returns the steady state solution. If the speed is too low we can't use the dynamic model (tire slip is undefined), we then have to use the kinematic model Args: sa: Steering wheel angle [rad] u: Speed [m/s] ...
Returns the steady state solution. If the speed is too low we can't use the dynamic model (tire slip is undefined), we then have to use the kinematic model Args: sa: Steering wheel angle [rad] u: Speed [m/s] roll: Road Roll [rad] Returns: 2x1 matrix with steady state solution ...
steady_state_sol
python
commaai/opendbc
opendbc/car/vehicle_model.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/vehicle_model.py
MIT
def curvature_factor(self, u: float) -> float: """Returns the curvature factor. Multiplied by wheel angle (not steering wheel angle) this will give the curvature. Args: u: Speed [m/s] Returns: Curvature factor [1/m] """ sf = calc_slip_factor(self) return (1. - self.chi) / (1. -...
Returns the curvature factor. Multiplied by wheel angle (not steering wheel angle) this will give the curvature. Args: u: Speed [m/s] Returns: Curvature factor [1/m]
curvature_factor
python
commaai/opendbc
opendbc/car/vehicle_model.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/vehicle_model.py
MIT
def roll_compensation(self, roll: float, u: float) -> float: """Calculates the roll-compensation to curvature Args: roll: Road Roll [rad] u: Speed [m/s] Returns: Roll compensation curvature [rad] """ sf = calc_slip_factor(self) if abs(sf) < 1e-6: return 0 else: ...
Calculates the roll-compensation to curvature Args: roll: Road Roll [rad] u: Speed [m/s] Returns: Roll compensation curvature [rad]
roll_compensation
python
commaai/opendbc
opendbc/car/vehicle_model.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/vehicle_model.py
MIT
def get_steer_from_yaw_rate(self, yaw_rate: float, u: float, roll: float) -> float: """Calculates the required steering wheel angle for a given yaw_rate Args: yaw_rate: Desired yaw rate [rad/s] u: Speed [m/s] roll: Road Roll [rad] Returns: Steering wheel angle [rad] """ cur...
Calculates the required steering wheel angle for a given yaw_rate Args: yaw_rate: Desired yaw rate [rad/s] u: Speed [m/s] roll: Road Roll [rad] Returns: Steering wheel angle [rad]
get_steer_from_yaw_rate
python
commaai/opendbc
opendbc/car/vehicle_model.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/vehicle_model.py
MIT
def kin_ss_sol(sa: float, u: float, VM: VehicleModel) -> np.ndarray: """Calculate the steady state solution at low speeds At low speeds the tire slip is undefined, so a kinematic model is used. Args: sa: Steering angle [rad] u: Speed [m/s] VM: Vehicle model Returns: 2x1 matrix with steady st...
Calculate the steady state solution at low speeds At low speeds the tire slip is undefined, so a kinematic model is used. Args: sa: Steering angle [rad] u: Speed [m/s] VM: Vehicle model Returns: 2x1 matrix with steady state solution
kin_ss_sol
python
commaai/opendbc
opendbc/car/vehicle_model.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/vehicle_model.py
MIT
def create_dyn_state_matrices(u: float, VM: VehicleModel) -> tuple[np.ndarray, np.ndarray]: """Returns the A and B matrix for the dynamics system Args: u: Vehicle speed [m/s] VM: Vehicle model Returns: A tuple with the 2x2 A matrix, and 2x2 B matrix Parameters in the vehicle model: cF: Tire s...
Returns the A and B matrix for the dynamics system Args: u: Vehicle speed [m/s] VM: Vehicle model Returns: A tuple with the 2x2 A matrix, and 2x2 B matrix Parameters in the vehicle model: cF: Tire stiffness Front [N/rad] cR: Tire stiffness Rear [N/rad] aF: Distance from CG to front whee...
create_dyn_state_matrices
python
commaai/opendbc
opendbc/car/vehicle_model.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/vehicle_model.py
MIT
def dyn_ss_sol(sa: float, u: float, roll: float, VM: VehicleModel) -> np.ndarray: """Calculate the steady state solution when x_dot = 0, Ax + Bu = 0 => x = -A^{-1} B u Args: sa: Steering angle [rad] u: Speed [m/s] roll: Road Roll [rad] VM: Vehicle model Returns: 2x1 matrix with steady stat...
Calculate the steady state solution when x_dot = 0, Ax + Bu = 0 => x = -A^{-1} B u Args: sa: Steering angle [rad] u: Speed [m/s] roll: Road Roll [rad] VM: Vehicle model Returns: 2x1 matrix with steady state solution
dyn_ss_sol
python
commaai/opendbc
opendbc/car/vehicle_model.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/vehicle_model.py
MIT
def create_lat_ctl_msg(packer, CAN: CanBus, lat_active: bool, path_offset: float, path_angle: float, curvature: float, curvature_rate: float): """ Creates a CAN message for the Ford TJA/LCA Command. This command can apply "Lane Centering" maneuvers: continuous lane centering for traffic ja...
Creates a CAN message for the Ford TJA/LCA Command. This command can apply "Lane Centering" maneuvers: continuous lane centering for traffic jam assist and highway driving. It is not subject to the PSCM lockout. Ford lane centering command uses a third order polynomial to describe the road centerline. The po...
create_lat_ctl_msg
python
commaai/opendbc
opendbc/car/ford/fordcan.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/ford/fordcan.py
MIT
def create_lat_ctl2_msg(packer, CAN: CanBus, mode: int, path_offset: float, path_angle: float, curvature: float, curvature_rate: float, counter: int): """ Create a CAN message for the new Ford Lane Centering command. This message is used on the CAN FD platform and replaces the old Lateral...
Create a CAN message for the new Ford Lane Centering command. This message is used on the CAN FD platform and replaces the old LateralMotionControl message. It is similar but has additional signals for a counter and checksum. Frequency is 20Hz.
create_lat_ctl2_msg
python
commaai/opendbc
opendbc/car/ford/fordcan.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/ford/fordcan.py
MIT
def create_acc_msg(packer, CAN: CanBus, long_active: bool, gas: float, accel: float, stopping: bool, brake_request, v_ego_kph: float): """ Creates a CAN message for the Ford ACC Command. This command can be used to enable ACC, to set the ACC gas/brake/decel values and to disable ACC. Frequency is 50Hz. ""...
Creates a CAN message for the Ford ACC Command. This command can be used to enable ACC, to set the ACC gas/brake/decel values and to disable ACC. Frequency is 50Hz.
create_acc_msg
python
commaai/opendbc
opendbc/car/ford/fordcan.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/ford/fordcan.py
MIT
def create_acc_ui_msg(packer, CAN: CanBus, CP, main_on: bool, enabled: bool, fcw_alert: bool, standstill: bool, show_distance_bars: bool, hud_control, stock_values: dict): """ Creates a CAN message for the Ford IPC adaptive cruise, forward collision warning and traffic jam assist status. ...
Creates a CAN message for the Ford IPC adaptive cruise, forward collision warning and traffic jam assist status. Stock functionality is maintained by passing through unmodified signals. Frequency is 5Hz.
create_acc_ui_msg
python
commaai/opendbc
opendbc/car/ford/fordcan.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/ford/fordcan.py
MIT
def create_lkas_ui_msg(packer, CAN: CanBus, main_on: bool, enabled: bool, steer_alert: bool, hud_control, stock_values: dict): """ Creates a CAN message for the Ford IPC IPMA/LKAS status. Show the LKAS status with the "driver assist" lines in the IPC. Stock functionality is maintained b...
Creates a CAN message for the Ford IPC IPMA/LKAS status. Show the LKAS status with the "driver assist" lines in the IPC. Stock functionality is maintained by passing through unmodified signals. Frequency is 1Hz.
create_lkas_ui_msg
python
commaai/opendbc
opendbc/car/ford/fordcan.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/ford/fordcan.py
MIT
def create_button_msg(packer, bus: int, stock_values: dict, cancel=False, resume=False, tja_toggle=False): """ Creates a CAN message for the Ford SCCM buttons/switches. Includes cruise control buttons, turn lights and more. Frequency is 10Hz. """ values = {s: stock_values[s] for s in [ "HeadLghtHiFla...
Creates a CAN message for the Ford SCCM buttons/switches. Includes cruise control buttons, turn lights and more. Frequency is 10Hz.
create_button_msg
python
commaai/opendbc
opendbc/car/ford/fordcan.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/ford/fordcan.py
MIT
def cluster_points(pts_l: list[list[float]], pts2_l: list[list[float]], max_dist: float) -> list[int]: """ Clusters a collection of points based on another collection of points. This is useful for correlating clusters through time. Points in pts2 not close enough to any point in pts are assigned -1. Args: p...
Clusters a collection of points based on another collection of points. This is useful for correlating clusters through time. Points in pts2 not close enough to any point in pts are assigned -1. Args: pts_l: List of points to base the new clusters on pts2_l: List of points to cluster using pts max_dis...
cluster_points
python
commaai/opendbc
opendbc/car/ford/radar_interface.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/ford/radar_interface.py
MIT
def test_platform_codes_fuzzy_fw(self, data): """Ensure function doesn't raise an exception""" fw_strategy = st.lists(st.binary()) fws = data.draw(fw_strategy) get_platform_codes(fws)
Ensure function doesn't raise an exception
test_platform_codes_fuzzy_fw
python
commaai/opendbc
opendbc/car/ford/tests/test_ford.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/ford/tests/test_ford.py
MIT
def test_correct_ecu_response_database(self, subtests): """ Assert standard responses for certain ECUs, since they can respond to multiple queries with different data """ expected_fw_prefix = HYUNDAI_VERSION_REQUEST_LONG[1:] for car_model, ecus in FW_VERSIONS.items(): with subtests.test(ca...
Assert standard responses for certain ECUs, since they can respond to multiple queries with different data
test_correct_ecu_response_database
python
commaai/opendbc
opendbc/car/hyundai/tests/test_hyundai.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/hyundai/tests/test_hyundai.py
MIT
def test_can_fingerprint(self, car_model, fingerprints): """Tests online fingerprinting function on offline fingerprints""" for fingerprint in fingerprints: # can have multiple fingerprints for each platform can = [CanData(address=address, dat=b'\x00' * length, src=src) for address, length ...
Tests online fingerprinting function on offline fingerprints
test_can_fingerprint
python
commaai/opendbc
opendbc/car/tests/test_can_fingerprint.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/tests/test_can_fingerprint.py
MIT
def test_interface_attrs(self): """Asserts basic behavior of interface attribute getter""" num_brands = len(get_interface_attr('CAR')) assert num_brands >= 12 # Should return value for all brands when not combining, even if attribute doesn't exist ret = get_interface_attr('FAKE_ATTR') assert le...
Asserts basic behavior of interface attribute getter
test_interface_attrs
python
commaai/opendbc
opendbc/car/tests/test_car_interfaces.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/tests/test_car_interfaces.py
MIT
def fake_set_obd_multiplexing(self, obd_multiplexing): """The 10Hz blocking params loop adds on average 50ms to the query time for each OBD multiplexing change""" if obd_multiplexing != self.current_obd_multiplexing: self.current_obd_multiplexing = obd_multiplexing self.total_time += 0.1 / 2
The 10Hz blocking params loop adds on average 50ms to the query time for each OBD multiplexing change
fake_set_obd_multiplexing
python
commaai/opendbc
opendbc/car/tests/test_fw_fingerprint.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/tests/test_fw_fingerprint.py
MIT
def test_dyn_ss_sol_against_yaw_rate(self): """Verify that the yaw_rate helper function matches the results from the state space model.""" for roll in np.linspace(math.radians(-20), math.radians(20), num=11): for u in np.linspace(1, 30, num=10): for sa in np.linspace(math.radians(-20), math.r...
Verify that the yaw_rate helper function matches the results from the state space model.
test_dyn_ss_sol_against_yaw_rate
python
commaai/opendbc
opendbc/car/tests/test_vehicle_model.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/tests/test_vehicle_model.py
MIT
def create_steer_command(packer, steer, steer_req): """Creates a CAN message for the Toyota Steer Command.""" values = { "STEER_REQUEST": steer_req, "STEER_TORQUE_CMD": steer, "SET_ME_1": 1, } return packer.make_can_msg("STEERING_LKA", 0, values)
Creates a CAN message for the Toyota Steer Command.
create_steer_command
python
commaai/opendbc
opendbc/car/toyota/toyotacan.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/toyota/toyotacan.py
MIT
def create_lta_steer_command(packer, steer_control_type, steer_angle, steer_req, frame, torque_wind_down): """Creates a CAN message for the Toyota LTA Steer Command.""" values = { "COUNTER": frame + 128, "SETME_X1": 1, # suspected LTA feature availability # 1 for TSS 2.5 cars, 3 for TSS 2.0. Send base...
Creates a CAN message for the Toyota LTA Steer Command.
create_lta_steer_command
python
commaai/opendbc
opendbc/car/toyota/toyotacan.py
https://github.com/commaai/opendbc/blob/master/opendbc/car/toyota/toyotacan.py
MIT
def add_regen_tests(cls): """Dynamically adds regen tests for all user brake tests.""" # only rx/user brake tests, not brake command found_tests = [func for func in dir(cls) if func.startswith("test_") and "user_brake" in func] assert len(found_tests) >= 3, "Failed to detect known brake tests" for test in f...
Dynamically adds regen tests for all user brake tests.
add_regen_tests
python
commaai/opendbc
opendbc/safety/tests/common.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/common.py
MIT
def _common_measurement_test(self, msg_func: Callable, min_value: float, max_value: float, factor: float, meas_min_func: Callable[[], int], meas_max_func: Callable[[], int]): """Tests accurate measurement parsing, and that the struct is reset on safety mode init""" for val in np.a...
Tests accurate measurement parsing, and that the struct is reset on safety mode init
_common_measurement_test
python
commaai/opendbc
opendbc/safety/tests/common.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/common.py
MIT
def test_steer_req_bit(self): """Asserts all torque safety modes check the steering request bit""" if self.NO_STEER_REQ_BIT: raise unittest.SkipTest("No steering request bit") self.safety.set_controls_allowed(True) self._set_prev_torque(self.MAX_TORQUE) # Send torque successfully, then only ...
Asserts all torque safety modes check the steering request bit
test_steer_req_bit
python
commaai/opendbc
opendbc/safety/tests/common.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/common.py
MIT
def test_steer_req_bit_frames(self): """ Certain safety modes implement some tolerance on their steer request bits matching the requested torque to avoid a steering fault or lockout and maintain torque. This tests: - We can't cut torque for more than one frame - We can't cut torque until...
Certain safety modes implement some tolerance on their steer request bits matching the requested torque to avoid a steering fault or lockout and maintain torque. This tests: - We can't cut torque for more than one frame - We can't cut torque until at least the minimum number of matching ste...
test_steer_req_bit_frames
python
commaai/opendbc
opendbc/safety/tests/common.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/common.py
MIT
def test_steer_req_bit_multi_invalid(self): """ For safety modes allowing multiple consecutive invalid frames, this ensures that once a valid frame is sent after an invalid frame (even without sending the max number of allowed invalid frames), all counters are reset. """ for max_invalid_st...
For safety modes allowing multiple consecutive invalid frames, this ensures that once a valid frame is sent after an invalid frame (even without sending the max number of allowed invalid frames), all counters are reset.
test_steer_req_bit_multi_invalid
python
commaai/opendbc
opendbc/safety/tests/common.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/common.py
MIT
def test_steer_req_bit_realtime(self): """ Realtime safety for cutting steer request bit. This tests: - That we allow messages with mismatching steer request bit if time from last is >= MIN_VALID_STEERING_RT_INTERVAL - That frame mismatch safety does not interfere with this test """ fo...
Realtime safety for cutting steer request bit. This tests: - That we allow messages with mismatching steer request bit if time from last is >= MIN_VALID_STEERING_RT_INTERVAL - That frame mismatch safety does not interfere with this test
test_steer_req_bit_realtime
python
commaai/opendbc
opendbc/safety/tests/common.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/common.py
MIT
def test_button_sends(self): """ Only RES and CANCEL buttons are allowed - RES allowed while controls allowed - CANCEL allowed while cruise is enabled """ self.safety.set_controls_allowed(0) self.assertFalse(self._tx(self._button_msg(Buttons.RESUME, bus=self.BUTTONS_TX_BUS))) self....
Only RES and CANCEL buttons are allowed - RES allowed while controls allowed - CANCEL allowed while cruise is enabled
test_button_sends
python
commaai/opendbc
opendbc/safety/tests/hyundai_common.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/hyundai_common.py
MIT
def test_enable_control_allowed_from_cruise(self): """ Hyundai non-longitudinal only enables on PCM rising edge and recent button press. Tests PCM enabling with: - disallowed: No buttons - disallowed: Buttons that don't enable cruise - allowed: Buttons that do enable cruise - allowed: ...
Hyundai non-longitudinal only enables on PCM rising edge and recent button press. Tests PCM enabling with: - disallowed: No buttons - disallowed: Buttons that don't enable cruise - allowed: Buttons that do enable cruise - allowed: Main button with all above combinations
test_enable_control_allowed_from_cruise
python
commaai/opendbc
opendbc/safety/tests/hyundai_common.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/hyundai_common.py
MIT
def test_sampling_cruise_buttons(self): """ Test that we allow controls on recent button press, but not as button leaves sliding window """ self._rx(self._button_msg(Buttons.SET)) for i in range(2 * PREV_BUTTON_SAMPLES): self._rx(self._pcm_status_msg(False)) self.assertFalse(self.safet...
Test that we allow controls on recent button press, but not as button leaves sliding window
test_sampling_cruise_buttons
python
commaai/opendbc
opendbc/safety/tests/hyundai_common.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/hyundai_common.py
MIT
def test_set_resume_buttons(self): """ SET and RESUME enter controls allowed on their falling edge. """ for btn_prev in range(8): for btn_cur in range(8): self._rx(self._button_msg(Buttons.NONE)) self.safety.set_controls_allowed(0) for _ in range(10): self._rx(s...
SET and RESUME enter controls allowed on their falling edge.
test_set_resume_buttons
python
commaai/opendbc
opendbc/safety/tests/hyundai_common.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/hyundai_common.py
MIT
def test_tester_present_allowed(self, ecu_disable: bool = True): """ Ensure tester present diagnostic message is allowed to keep ECU knocked out for longitudinal control. """ addr, bus = self.DISABLED_ECU_UDS_MSG for should_tx, msg in ((True, b"\x02\x3E\x80\x00\x00\x00\x00\x00"), ...
Ensure tester present diagnostic message is allowed to keep ECU knocked out for longitudinal control.
test_tester_present_allowed
python
commaai/opendbc
opendbc/safety/tests/hyundai_common.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/hyundai_common.py
MIT
def test_disabled_ecu_alive(self): """ If the ECU knockout failed, make sure the relay malfunction is shown """ addr, bus = self.DISABLED_ECU_ACTUATION_MSG self.assertFalse(self.safety.get_relay_malfunction()) self._rx(make_msg(bus, addr, 8)) self.assertTrue(self.safety.get_relay_malfunct...
If the ECU knockout failed, make sure the relay malfunction is shown
test_disabled_ecu_alive
python
commaai/opendbc
opendbc/safety/tests/hyundai_common.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/hyundai_common.py
MIT
def test_angle_measurements(self): """Tests rx hook correctly parses the curvature measurement from the vehicle speed and yaw rate""" for speed in np.arange(0.5, 40, 0.5): for curvature in np.arange(0, self.MAX_CURVATURE * 2, 2e-3): self._rx(self._speed_msg(speed)) for c in (curvature, -cu...
Tests rx hook correctly parses the curvature measurement from the vehicle speed and yaw rate
test_angle_measurements
python
commaai/opendbc
opendbc/safety/tests/test_ford.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/test_ford.py
MIT
def test_set_resume_buttons(self): """ SET and RESUME enter controls allowed on their falling and rising edges, respectively. """ for btn_prev in range(8): for btn_cur in range(8): with self.subTest(btn_prev=btn_prev, btn_cur=btn_cur): self._rx(self._button_msg(btn_prev)) ...
SET and RESUME enter controls allowed on their falling and rising edges, respectively.
test_set_resume_buttons
python
commaai/opendbc
opendbc/safety/tests/test_gm.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/test_gm.py
MIT
def test_set_resume_buttons(self): """ Both SET and RES should enter controls allowed on their falling edge. """ for main_on in (True, False): self._rx(self._acc_state_msg(main_on)) for btn_prev in range(8): for btn_cur in range(8): self._rx(self._button_msg(Btn.NONE)) ...
Both SET and RES should enter controls allowed on their falling edge.
test_set_resume_buttons
python
commaai/opendbc
opendbc/safety/tests/test_honda.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/test_honda.py
MIT
def test_main_cancel_buttons(self): """ Both MAIN and CANCEL should exit controls immediately. """ for btn in (Btn.MAIN, Btn.CANCEL): self.safety.set_controls_allowed(1) self._rx(self._button_msg(btn, main_on=True)) self.assertFalse(self.safety.get_controls_allowed())
Both MAIN and CANCEL should exit controls immediately.
test_main_cancel_buttons
python
commaai/opendbc
opendbc/safety/tests/test_honda.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/test_honda.py
MIT
def test_buttons(self): """ Buttons should only cancel in this configuration, since our state is tied to the PCM's cruise state. """ for controls_allowed in (True, False): for main_on in (True, False): # not a valid state if controls_allowed and not main_on: conti...
Buttons should only cancel in this configuration, since our state is tied to the PCM's cruise state.
test_buttons
python
commaai/opendbc
opendbc/safety/tests/test_honda.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/test_honda.py
MIT
def test_button_sends(self): """ No button send allowed with alt buttons. """ for enabled in (True, False): for btn in range(8): self.safety.set_controls_allowed(enabled) self.assertFalse(self._tx(self._button_msg(btn)))
No button send allowed with alt buttons.
test_button_sends
python
commaai/opendbc
opendbc/safety/tests/test_hyundai_canfd.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/test_hyundai_canfd.py
MIT
def test_lta_steer_cmd(self): """ Tests the LTA steering command message controls_allowed: * STEER_REQUEST and STEER_REQUEST_2 do not mismatch * TORQUE_WIND_DOWN is only set to 0 or 100 when STEER_REQUEST and STEER_REQUEST_2 are both 1 * Full torque messages are blocked if either EPS torque or d...
Tests the LTA steering command message controls_allowed: * STEER_REQUEST and STEER_REQUEST_2 do not mismatch * TORQUE_WIND_DOWN is only set to 0 or 100 when STEER_REQUEST and STEER_REQUEST_2 are both 1 * Full torque messages are blocked if either EPS torque or driver torque is above the threshold ...
test_lta_steer_cmd
python
commaai/opendbc
opendbc/safety/tests/test_toyota.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/test_toyota.py
MIT
def test_angle_measurements(self): """ * Tests angle meas quality flag dictates whether angle measurement is parsed, and if rx is valid * Tests rx hook correctly clips the angle measurement, since it is to be compared to LTA cmd when inactive """ for steer_angle_initializing in (True, False): ...
* Tests angle meas quality flag dictates whether angle measurement is parsed, and if rx is valid * Tests rx hook correctly clips the angle measurement, since it is to be compared to LTA cmd when inactive
test_angle_measurements
python
commaai/opendbc
opendbc/safety/tests/test_toyota.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/test_toyota.py
MIT
def test_acc_cancel(self): """ Regardless of controls allowed, never allow ACC_CONTROL if cancel bit isn't set """ for controls_allowed in [True, False]: self.safety.set_controls_allowed(controls_allowed) for accel in np.arange(self.MIN_ACCEL - 1, self.MAX_ACCEL + 1, 0.1): self.ass...
Regardless of controls allowed, never allow ACC_CONTROL if cancel bit isn't set
test_acc_cancel
python
commaai/opendbc
opendbc/safety/tests/test_toyota.py
https://github.com/commaai/opendbc/blob/master/opendbc/safety/tests/test_toyota.py
MIT
async def search(self, query, limit): """Make search API call and return result.""" url = f"{self.API_URL}/gifs/search" params = { "q": query, "api_key": self._api_key, "limit": limit, } async with ClientSession(timeout=self._timeout) as sessio...
Make search API call and return result.
search
python
ets-labs/python-dependency-injector
examples/miniapps/aiohttp/giphynavigator/giphy.py
https://github.com/ets-labs/python-dependency-injector/blob/master/examples/miniapps/aiohttp/giphynavigator/giphy.py
BSD-3-Clause
async def search(self, query, limit): """Search for gifs and return formatted data.""" if not query: return [] result = await self._giphy_client.search(query, limit) return [{"url": gif["url"]} for gif in result["data"]]
Search for gifs and return formatted data.
search
python
ets-labs/python-dependency-injector
examples/miniapps/aiohttp/giphynavigator/services.py
https://github.com/ets-labs/python-dependency-injector/blob/master/examples/miniapps/aiohttp/giphynavigator/services.py
BSD-3-Clause
def search_repositories(self, query, limit): """Search for repositories and return formatted data.""" repositories = self._github_client.search_repositories( query=query, **{"in": "name"}, ) return [ self._format_repo(repository) for reposi...
Search for repositories and return formatted data.
search_repositories
python
ets-labs/python-dependency-injector
examples/miniapps/django/githubnavigator/services.py
https://github.com/ets-labs/python-dependency-injector/blob/master/examples/miniapps/django/githubnavigator/services.py
BSD-3-Clause
def wire( # noqa: C901 container: Container, *, modules: Optional[Iterable[ModuleType]] = None, packages: Optional[Iterable[ModuleType]] = None, ) -> None: """Wire container providers with provided packages and modules.""" modules = [*modules] if modules else [] if packages: for pa...
Wire container providers with provided packages and modules.
wire
python
ets-labs/python-dependency-injector
src/dependency_injector/wiring.py
https://github.com/ets-labs/python-dependency-injector/blob/master/src/dependency_injector/wiring.py
BSD-3-Clause
def unwire( # noqa: C901 *, modules: Optional[Iterable[ModuleType]] = None, packages: Optional[Iterable[ModuleType]] = None, ) -> None: """Wire provided packages and modules with previous wired providers.""" modules = [*modules] if modules else [] if packages: for package in packages: ...
Wire provided packages and modules with previous wired providers.
unwire
python
ets-labs/python-dependency-injector
src/dependency_injector/wiring.py
https://github.com/ets-labs/python-dependency-injector/blob/master/src/dependency_injector/wiring.py
BSD-3-Clause
def as_view(provider, name=None): """Transform class-based view provider to view function.""" if isinstance(provider, providers.Factory): def view(*args, **kwargs): self = provider() return self.dispatch_request(*args, **kwargs) assert name, 'Argument "endpoint" is requ...
Transform class-based view provider to view function.
as_view
python
ets-labs/python-dependency-injector
src/dependency_injector/ext/flask.py
https://github.com/ets-labs/python-dependency-injector/blob/master/src/dependency_injector/ext/flask.py
BSD-3-Clause
def run(self): """Run all tests for all provider modules.""" for module in self.provider_modules: print("\n") print("Running tests for module - \"{module}\":" .format(module=module.__name__)) gc.disable() for test in self.tests: ...
Run all tests for all provider modules.
run
python
ets-labs/python-dependency-injector
tests/performance/test.py
https://github.com/ets-labs/python-dependency-injector/blob/master/tests/performance/test.py
BSD-3-Clause
def test_factory_3_factory_kw_injections(self, providers): """Test factory with 3 keyword argument injections via factories.""" class A(object): pass class B(object): pass class C(object): pass class Test(object): def __init__(se...
Test factory with 3 keyword argument injections via factories.
test_factory_3_factory_kw_injections
python
ets-labs/python-dependency-injector
tests/performance/test.py
https://github.com/ets-labs/python-dependency-injector/blob/master/tests/performance/test.py
BSD-3-Clause
def test_factory_6_factory_kw_injections_0_context(self, providers): """Test factory with 6 keyword argument injections.""" class Test(object): def __init__(self, a, b, c, d, e, f): pass test_factory = providers.Factory(Test, a=1, b=2, c=3, d=4, e=5, f=6) for...
Test factory with 6 keyword argument injections.
test_factory_6_factory_kw_injections_0_context
python
ets-labs/python-dependency-injector
tests/performance/test.py
https://github.com/ets-labs/python-dependency-injector/blob/master/tests/performance/test.py
BSD-3-Clause
async def test_init_and_shutdown_ordering(): """Test init and shutdown resources. Methods .init_resources() and .shutdown_resources() should respect resources dependencies. Initialization should first initialize resources without dependencies and then provide these resources to other resources. Resourc...
Test init and shutdown resources. Methods .init_resources() and .shutdown_resources() should respect resources dependencies. Initialization should first initialize resources without dependencies and then provide these resources to other resources. Resources shutdown should follow the same rule: first s...
test_init_and_shutdown_ordering
python
ets-labs/python-dependency-injector
tests/unit/containers/instance/test_async_resources_py36.py
https://github.com/ets-labs/python-dependency-injector/blob/master/tests/unit/containers/instance/test_async_resources_py36.py
BSD-3-Clause
def folderAnnotation2folders(sourceFolder, targetFolder): """ Break an audio stream to segments of interest for all files in the sourceFolder - sourceFolder: path to Folder of all source audio file and .segments file - targetFolder: path to Folder where user want to store the ...
Break an audio stream to segments of interest for all files in the sourceFolder - sourceFolder: path to Folder of all source audio file and .segments file - targetFolder: path to Folder where user want to store the class folders
folderAnnotation2folders
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audacityAnnotation2WAVs.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audacityAnnotation2WAVs.py
Apache-2.0
def convert_dir_mp3_to_wav(audio_folder, sampling_rate, num_channels, use_tags=False): """ This function converts the MP3 files stored in a folder to WAV. If required, the output names of the WAV files are based on MP3 tags, otherwise the same names are used. ARGUMENTS: ...
This function converts the MP3 files stored in a folder to WAV. If required, the output names of the WAV files are based on MP3 tags, otherwise the same names are used. ARGUMENTS: - audio_folder: the path of the folder where the MP3s are stored - sampling_rate: the sampling rate of the g...
convert_dir_mp3_to_wav
python
tyiannak/pyAudioAnalysis
pyAudioAnalysis/audioBasicIO.py
https://github.com/tyiannak/pyAudioAnalysis/blob/master/pyAudioAnalysis/audioBasicIO.py
Apache-2.0