text
stringlengths
185
73.3k
repo
stringlengths
7
100
path
stringlengths
4
146
language
stringclasses
7 values
hash
stringlengths
16
16
score
float64
7
8.5
stars
int64
0
237k
"""%there magic Python code shortcuts.""" # pylint: disable=invalid-name from base64 import b64decode from io import BytesIO, StringIO import click from herethere.there.commands import there_code_shortcut, there_group from IPython.display import display from PIL import Image as PILImage KV_COMMAND_TEMPLATE = r""" fr...
b3b/pythonhere
pythonhere/magic_here/shortcuts.py
.py
8d435363cdffcd00
7.45
7
"""PythonHere app.""" # pylint: disable=wrong-import-order,wrong-import-position from launcher_here import try_startup_script try: try_startup_script() # run script entrypoint, if it was passed except Exception as exc: startup_script_exception = exc # pylint: disable=invalid-name else: startup_script_e...
b3b/pythonhere
pythonhere/main.py
.py
955e16cffe78921c
7.45
7
"""Network addresses discovering.""" from collections.abc import Iterator from kivy import platform if platform == "android": from jnius import autoclass # pylint: disable=import-error NetworkInterface = autoclass("java.net.NetworkInterface") Inet4Address = autoclass("java.net.Inet4Address") else: ...
b3b/pythonhere
pythonhere/network_here.py
.py
7b71439417173da4
7.45
7
"""Monkey patching Kivy @('_')@.""" import kivy.uix.widget from kivy.factory import Factory from kivy.lang.builder import BuilderBase _original_factory_register = Factory.register _original_builderbase_match = BuilderBase.match # pylint: disable=protected-access _original_widget_destructor = kivy.uix.widget._widget_d...
b3b/pythonhere
pythonhere/patches_here.py
.py
cc1ece85b9393c85
7.45
7
"""SSH server.""" import asyncio from pathlib import Path from exception_manager_here import show_exception_popup from herethere.here.server import ServerConfig, SSHServerHere, start_server from kivy.app import App from kivy.logger import Logger class PythonHereServer(SSHServerHere): """SSH server protocol hand...
b3b/pythonhere
pythonhere/server_here.py
.py
76134c263d406f3e
7.45
7
"""Connection information widgets.""" from kivy.clock import Clock, mainthread from kivy.logger import Logger from kivy.properties import StringProperty # pylint: disable=no-name-in-module from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from network_here import get_all_available_ipv4_adrre...
b3b/pythonhere
pythonhere/ui_here/connection_address_here.py
.py
fcd336989b973368
7.45
7
"""%here server screen.""" from enum_here import ServerState from kivy.app import App from kivy.clock import Clock, mainthread from kivy.uix.screenmanager import ScreenManager class ServerScreenManager(ScreenManager): """Screen manager for server %here section.""" def __init__(self, *args, **kwargs): ...
b3b/pythonhere
pythonhere/ui_here/server_screen_here.py
.py
db342fd5816688a3
7.45
7
"""Settings panel widgets.""" import webbrowser from typing import Any from kivy.app import App from kivy.config import Config from kivy.properties import ( # pylint: disable=no-name-in-module BooleanProperty, ObjectProperty, StringProperty, ) from kivy.uix.anchorlayout import AnchorLayout from kivy.uix....
b3b/pythonhere
pythonhere/ui_here/settings_here.py
.py
ecd7e564152a6360
7.45
7
"""Utilities for working with Kivy window.""" import time from base64 import b64encode from pathlib import Path from kivy.app import App from kivy.lang import Builder from kivy.uix.boxlayout import BoxLayout def reset_window_environment() -> BoxLayout: """Remove PythonHere app widgets and styles.""" # impor...
b3b/pythonhere
pythonhere/window_here.py
.py
a053e834c19a7c6a
7.45
7
"""Plasma: Light FX Sequencer.""" import time class Sequence(object): """PlasmaFX Sequence. A PlasmaFX sequence is responsible for a sequence of Plasma light groupings. LEDs can be grouped into "lights" such as the 4 on a Plasma PCB or the 12+ on an Adafruit NeoPixel ring. """ def __in...
pimoroni/plasma-python
fx/plasmafx/plasmafx/__init__.py
.py
0acce9f2f418a6c6
7.64
18
"""Plasma: Light FX Sequencer - Plugin base class.""" class Plugin(object): """PlasmaFX Plugin. A PlasmaFX plugin is responsible for the 4 lights on a single Plasma light board. """ def __init__(self, pixel_count=1): """Initialise PlasmaFX: Base Plugin.""" self._pixel_count = pi...
pimoroni/plasma-python
fx/plasmafx/plasmafx/core.py
.py
f61b9757154baf2b
7.64
18
"""Plasma: Light FX Sequencer - Colour Cycling Plugin.""" from colorsys import hsv_to_rgb from plasmafx.core import Plugin class Cycle(Plugin): """Plasma: Light FX Sequencer - Colour Cycling Plugin.""" def __init__(self, pixel_count=1, speed=1.0, spread=360.0, offset=0.0, saturation=1.0, value=1.0): ...
pimoroni/plasma-python
fx/plasmafx_plugin_cycle/plasmafx_plugin_cycle/__init__.py
.py
818252baae77dd15
7.64
18
"""Plasma multi device LED driver.""" import pathlib import sys from importlib.metadata import PackageNotFoundError, version try: __version__ = version("plasmalights") except PackageNotFoundError: __version__ = "0.0.0" def auto(default=None, descriptor=None): """Return a Plasma device instance. Will...
pimoroni/plasma-python
plasma/__init__.py
.py
6430a1c08916fda2
7.64
18
"""Plasma support for APA102 style pixels.""" import time from .core import Plasma class PlasmaAPA102(Plasma): """Plasma support for APA102 style pixels.""" name = "APA102" options = { 'pixel_count': int, "gpio_data": int, "gpio_clock": int, "gpio_cs": int } opt...
pimoroni/plasma-python
plasma/apa102.py
.py
8314e05acf625df0
7.64
18
"""Base class for Plasma LED devices.""" import atexit class Plasma(): """Base class for Plasma LED devices.""" name = "" options = { 'pixel_count': int, } option_order = [] def __init__(self, pixel_count=1): """Initialise Plasma device. :param pixel_count: Number ...
pimoroni/plasma-python
plasma/core.py
.py
d01f9bd39bd225ae
7.64
18
"""Combine multiple LED strip types into a single logical strip.""" import pathlib import yaml class PlasmaMatrix(): """Combine multiple LED strip types into a single logical strip.""" def __init__(self, config_file=None): """Initialise a matrix. :param config_file: Path to yml configuratio...
pimoroni/plasma-python
plasma/matrix.py
.py
fac80184190bd5ae
7.64
18
"""Serial class for Plasma light devices over USB Serial/UART.""" from serial import Serial from .core import Plasma class PlasmaSerial(Plasma): """Serial class for Plasma light devices over USB Serial/UART.""" name = "Serial" options = { 'pixel_count': int, "port": str } optio...
pimoroni/plasma-python
plasma/serial.py
.py
bc96596489da81ca
7.64
18
"""Class for Plasma light devices in the WS281X/SK6812 family.""" from .core import Plasma class PlasmaWS281X(Plasma): """Class for Plasma light devices in the WS281X/SK6812 family.""" name = "WS281X" options = { 'pixel_count': int, "gpio_pin": int, "strip_type": str, "ch...
pimoroni/plasma-python
plasma/ws281x.py
.py
d0deb1a622b8dcdc
7.64
18
"""Test configuration. These allow the mocking of various Python modules that might otherwise have runtime side-effects. """ import pathlib import sys import tempfile import mock import pytest @pytest.fixture(scope='function', autouse=True) def cleanup_plasma(): """This fixture removes all plasma modules from s...
pimoroni/plasma-python
tests/conftest.py
.py
6f0bbc5cc8dce381
8.14
18
"""Test Plasma APA102 initialisation.""" import mock def test_apa102_setup(GPIO): """Test init succeeds and GPIO pins are setup.""" from plasma.apa102 import PlasmaAPA102 plasma = PlasmaAPA102(10, gpio_data=10, gpio_clock=11) plasma.show() GPIO.setmode.assert_called_once_with(GPIO.BCM) GPIO.s...
pimoroni/plasma-python
tests/test_apa102.py
.py
03ad19e8c8e34c0f
7.14
18
"""Test Plasma GPIO (APA102 wrapper) initialisation.""" import mock def test_legacy_gpio_setup(GPIO): """Test init succeeds and GPIO pins are setup.""" from plasma.gpio import PlasmaGPIO plasma = PlasmaGPIO(10, gpio_data=10, gpio_clock=11) plasma.show() GPIO.setmode.assert_called_once_with(GPIO.B...
pimoroni/plasma-python
tests/test_legacy_gpio.py
.py
9e4b5d05cad661bd
8.14
18
"""Test Plasma Serial initialisation.""" def test_serial_setup(serial): """Test init succeeds and GPIO pins are setup.""" from plasma.serial import PlasmaSerial plasma = PlasmaSerial(10, port="/dev/ttyAMA0", baudrate=8000) plasma.show() serial.Serial.assert_called_once_with("/dev/ttyAMA0", baudra...
pimoroni/plasma-python
tests/test_serial.py
.py
4723051eb3f7254f
7.14
18
"""Test Plasma WS281X initialisation.""" def test_apa102_setup(rpi_ws281x): """Test init succeeds and GPIO pins are setup.""" from plasma.ws281x import PlasmaWS281X plasma = PlasmaWS281X(10) plasma.show() rpi_ws281x.PixelStrip.assert_called_once() def test_apa102_parse_options(rpi_ws281x): ...
pimoroni/plasma-python
tests/test_ws281x.py
.py
02460520b7ed3379
8.14
18
#!/usr/bin/env python3 """Command line tool to start/stop/restart the task runner in a tmux session.""" import subprocess import sys from pathlib import Path import psutil ATLASSERVERPATH = Path(__file__).resolve().parent.parent def run_command(commands: list[str], print_output: bool = True) -> int: """Run a c...
lukeshingles/atlasserver
atlasserver/atlastaskrunner.py
.py
ceb96863ddcd9498
7.57
13
#!/usr/bin/env python3 """Command line tool to start/stop/restart the ATLAS Apache server.""" import os import platform import signal import subprocess import sys import time from pathlib import Path import psutil from dotenv import load_dotenv APACHEPATH = Path("/tmp/atlasforced") # where this file actually lives....
lukeshingles/atlasserver
atlasserver/atlaswebserver.py
.py
9bf5ccb9badbb276
7.57
13
from typing import override from django.apps import AppConfig class ForcephotConfig(AppConfig): # job filenames are only ever built from the id (f"job{id:05d}"), never parsed at a fixed # width, so widening the id does not change any path that already exists on disk or on sc01 default_auto_field = "djang...
lukeshingles/atlasserver
atlasserver/forcephot/apps.py
.py
bcd4ee102bc25a03
7.57
13
"""Template context shared by every page.""" import typing as t from django.conf import settings from django.http import HttpRequest from django.utils.functional import SimpleLazyObject from atlasserver.forcephot.models import Task from atlasserver.taskrunner import status as runnerstatus def static_version(reques...
lukeshingles/atlasserver
atlasserver/forcephot/context_processors.py
.py
3bfe2f628d50c7fb
7.57
13
from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ def email_is_taken(email: str, exclude_user=None) -> bool: """Return True if another acc...
lukeshingles/atlasserver
atlasserver/forcephot/forms.py
.py
f5d0d241f7bc9950
7.57
13
"""Stop *new* accounts sharing an email address, while leaving existing ones alone. forms.email_is_taken() has always checked this, but only in a form clean() method, so two concurrent registrations could both pass validation, and the admin and the shell bypassed it altogether. Duplicates make the password reset flow ...
lukeshingles/atlasserver
atlasserver/forcephot/migrations/0005_auth_user_email_unique.py
.py
b03a4005c16045e4
7.57
13
"""Require every task to have a target: an MPC object name, or both coordinates. ForcePhotTaskSerializer.validate() has always enforced this, but it was the only thing that did, so the admin and the shell could create a task with no target at all -- Task.__str__ still carries a branch for exactly that case. Deploy no...
lukeshingles/atlasserver
atlasserver/forcephot/migrations/0006_task_task_target_is_mpcname_or_radec.py
.py
9d6d10ed7b8f0bc6
7.57
13
"""Guarantee that mpc_name is NULL, "" or a real name -- never whitespace alone. Task.save() normalises the field, but bulk_create, bulk_update, QuerySet.update() and raw SQL do not go through it, so the guarantee has to be in the database. What it buys is that every reader can test the field for truth instead of re-d...
lukeshingles/atlasserver
atlasserver/forcephot/migrations/0008_mpc_name_not_blank.py
.py
41bb9768b364c717
7.57
13
import datetime import logging import multiprocessing import typing as t from multiprocessing.process import BaseProcess from pathlib import Path from typing import override import fundamentals.logs import julian import pycountry from astrocalc.coords.unit_conversion import unit_conversion from django.http import Http...
lukeshingles/atlasserver
atlasserver/forcephot/misc.py
.py
09a500e5a1098669
7.57
13
"""Client IP addresses: which one a request really came from, and which ones are public. Deliberately free of imports beyond the standard library, and of Django: the callers include webhooks (which decides whether the server may be pointed at an address) and the GeoIP lookup in views (which decides whether an address ...
lukeshingles/atlasserver
atlasserver/forcephot/netaddr.py
.py
2da4e51fbcb02850
7.57
13
import typing as t from collections import OrderedDict from typing import override from django.db.models import QuerySet from rest_framework.pagination import _reverse_ordering from rest_framework.pagination import CursorPagination from rest_framework.request import Request from rest_framework.response import Response...
lukeshingles/atlasserver
atlasserver/forcephot/pagination.py
.py
bece715c9b00c5ea
7.57
13
"""Queue ordering: assigning each unfinished task its position in the execution order. Lives outside views.py so that the task runner can import it without pulling in DRF, bokeh and the rest of the web stack, and so that the two processes cannot drift on what "queue position" means. """ import datetime import operato...
lukeshingles/atlasserver
atlasserver/forcephot/queue.py
.py
f7942274d6ddb349
7.57
13
import math import typing as t from typing import override from django.contrib.staticfiles.storage import staticfiles_storage from django.core.exceptions import ObjectDoesNotExist from rest_framework import serializers from rest_framework.reverse import reverse from atlasserver.forcephot.models import get_mjd_min_def...
lukeshingles/atlasserver
atlasserver/forcephot/serializers.py
.py
d51485a5c736417b
7.57
13
import typing as t from typing import override from django.core.cache import caches # the same tuple ForcePhotPermission branches on, so the two cannot drift on what counts as a read. # Safe methods are throttled far more loosely than writes, but not exempt: the queue page polls the # task list every few seconds, so ...
lukeshingles/atlasserver
atlasserver/forcephot/throttles.py
.py
3668c63e225bad8a
7.57
13
"""Email address verification for new registrations. Registration used to log the new account straight in without proving the address belonged to whoever typed it, so the address that receives job completion mail (and password resets) was unverified. Anyone could sign up as someone else's address, and the owner's only...
lukeshingles/atlasserver
atlasserver/forcephot/verification.py
.py
d446fa41737ed927
7.57
13
"""Optional completion callbacks for API-submitted tasks. API clients have no way to be told that a task finished — result emails are skipped for API-originated tasks — so every API user polls, which is a large share of the server's request volume. A task may carry a callback_url that is POSTed a small JSON body once ...
lukeshingles/atlasserver
atlasserver/forcephot/webhooks.py
.py
f011a4f16ee723f7
7.57
13
#!/usr/bin/env python3 """Input a job data file and produce a zip of FITS images. This script is to be run on sc01.""" import shutil import subprocess import sys import tempfile from pathlib import Path import pandas as pd def main() -> None: if len(sys.argv) != 3: print("ERROR: exactly two argument mus...
lukeshingles/atlasserver
atlasserver/taskrunner/atlas_gettaskimages.py
.py
1a5f9a48d99e1cef
7.57
13
"""The task runner's configuration that the web app also needs. Where the runner writes its status snapshot, how often, and how many tasks it runs at once. Split out of `main` so that the web server can read these without importing the runner. Importing `atlasserver.taskrunner.main` runs `django.setup()` and pulls in...
lukeshingles/atlasserver
atlasserver/taskrunner/status.py
.py
6d0cf899ea023508
7.57
13
"""Utility functions for 21cmSense.""" import numpy as np from astropy import units as un from astropy.coordinates import EarthLocation, SkyCoord from astropy.time import Time from lunarsky import MoonLocation from lunarsky import SkyCoord as LunarSkyCoord from lunarsky import Time as LTime from pyuvdata import utils ...
rasg-affiliates/21cmSense
src/py21cmsense/_utils.py
.py
5245ad147f366b07
7.59
14
"""A module defining baseline filters. While you can simply use a function that takes a single baseline (with three co-ordinates) and returns a bool, this module provides standard kinds of filters (eg. using baselines within a certain length range). It also enables loading the filters from string names, useful for YAM...
rasg-affiliates/21cmSense
src/py21cmsense/baseline_filters.py
.py
318307fade80eca4
7.59
14
"""Simplistic beam definitions.""" from __future__ import annotations from abc import ABCMeta, abstractmethod import attr from astropy import constants as cnst from astropy import units as un from hickleable import hickleable from . import _utils as ut from . import units as tp @hickleable(evaluate_cached_propert...
rasg-affiliates/21cmSense
src/py21cmsense/beam.py
.py
35acda68d6867817
7.59
14
"""A module defining interferometric observation objects.""" from __future__ import annotations import collections from collections import defaultdict from functools import cached_property from os import path from typing import Any, Callable import attr import numpy as np from astropy import units as un from astropy...
rasg-affiliates/21cmSense
src/py21cmsense/observation.py
.py
ad73279381a049e0
7.59
14
"""Module dealing with types and units throughout the package.""" from __future__ import annotations from typing import Any, Callable import attr from astropy import constants as cnst from astropy import units as un from astropy.cosmology.units import littleh, redshift un.add_enabled_units([littleh, redshift]) cl...
rasg-affiliates/21cmSense
src/py21cmsense/units.py
.py
8f46b4d9aeb5d9c1
7.59
14
"""Module defining new YAML tags for py21cmsense.""" import inspect import pickle from functools import wraps import numpy as np import yaml from astropy import units as un from astropy.io.misc.yaml import AstropyLoader _DATA_LOADERS = {} _YAML_LOADERS = (yaml.FullLoader, yaml.SafeLoader, yaml.Loader, AstropyLoader...
rasg-affiliates/21cmSense
src/py21cmsense/yaml.py
.py
412222e4d67f43ee
7.59
14
"""Test the antenna positions.""" import numpy as np import pytest from astropy import units as un from py21cmsense.antpos import hera @pytest.mark.parametrize("n", [3, 5, 8]) def test_hera_split_core(n): # https://en.wikipedia.org/wiki/Centered_hexagonal_number # 3*n^2 - 3n + 1 antpos1 = hera(hex_num=n...
rasg-affiliates/21cmSense
tests/test_antpos.py
.py
ce1a5f959ea43640
8.09
14
"""Test baseline_filters module.""" import numpy as np import pytest from astropy import units as un from py21cmsense.baseline_filters import BaselineRange # Test IDs for parametrization happy_path_ids = [ "east-west_min", "north-south_min", "magnitude_min", "east-west_max", "north-south_max", ...
rasg-affiliates/21cmSense
tests/test_baseline_filters.py
.py
760870af232c4e0a
8.09
14
"""Tests for the Observation class.""" import copy import pickle import numpy as np import pytest from astropy import units from astropy.cosmology.units import littleh from py21cmsense import GaussianBeam, Observation, Observatory @pytest.fixture(scope="module") def bm(): return GaussianBeam(150.0 * units.MHz,...
rasg-affiliates/21cmSense
tests/test_observation.py
.py
0a110ddc0a249191
8.09
14
"""Tests of the phasing code for calculating UVWs.""" import numpy as np import pytest from astropy import units as un from astropy.coordinates import EarthLocation, SkyCoord from astropy.time import Time from pyuvdata import utils as uvutils from py21cmsense._utils import phase_past_zenith @pytest.mark.parametrize...
rasg-affiliates/21cmSense
tests/test_uvw.py
.py
22c46eceb6cb96c4
7.09
14
"""Error codes used in different error messages.""" from enum import IntEnum class ErrorSeverity(IntEnum): """Severity codes for errors.""" ERROR = 1 WARNING = 10 class ErrorContext: """Context this error took place in, each error potentially having multiple contexts.""" # Use this one to dis...
hed-standard/hed-python
hed/errors/error_types.py
.py
50317ac3227e1e9e
7.64
18
"""HED exceptions and exception codes.""" class HedExceptions: """HED exception codes.""" GENERIC_ERROR = "GENERIC_ERROR" # A list of all exceptions that can be generated by the hedtools. URL_ERROR = "URL_ERROR" FILE_NOT_FOUND = "FILE_NOT_FOUND" BAD_PARAMETERS = "BAD_PARAMETERS" CANNOT_PA...
hed-standard/hed-python
hed/errors/exceptions.py
.py
0ab7f7eeb479f8b7
7.64
18
""" Utilities to support HED searches based on strings. """ import re from collections import defaultdict from itertools import combinations, product import pandas as pd def find_matching(series, search_string, regex=False): """Find lines in the series that match the search string and returns a mask. Synta...
hed-standard/hed-python
hed/models/basic_search.py
.py
cb718216b4dd7dd1
7.64
18
"""Defined constants for definitions, def labels, and expanded labels.""" from enum import IntEnum class TopTagReturnType(IntEnum): """Return-type selector for :meth:`~hed.models.HedString.find_top_level_tags`. Pass one of these constants as the ``include_groups`` argument to control whether the method ...
hed-standard/hed-python
hed/models/model_constants.py
.py
c24b01f13b1f7baa
7.64
18
"""Functions to get and use HED queries.""" import pandas as pd from hed.models import QueryHandler def get_query_handlers(queries, query_names=None) -> tuple[list[QueryHandler | None], list[QueryHandler | None], list]: """Return a list of query handlers, query names, and issues if any. Parameters: ...
hed-standard/hed-python
hed/models/query_service.py
.py
935198669b7108be
7.64
18
"""Classes representing HED search results and tokens.""" class SearchResult: """Holder for and manipulation of search results. Represents a query match result consisting of: - group: The containing HedGroup where matches were found. - children: The specific matched elements (tags/groups) within tha...
hed-standard/hed-python
hed/models/query_util.py
.py
8907749fca545e7e
7.64
18
"""Schema lookup table for ancestor-aware string search. Generates a compact mapping from every tag's casefolded short name to its full ``tag_terms`` tuple (all slash-path components from root to self), which is the same information stored in :attr:`~hed.schema.HedTagEntry.tag_terms` after schema loading. This lookup...
hed-standard/hed-python
hed/models/schema_lookup.py
.py
b8167d5104074eef
7.64
18
"""Contents of a JSON file or merged JSON files.""" import json import re from hed.errors import ErrorHandler from hed.errors.error_types import ErrorContext from hed.errors.exceptions import HedExceptions, HedFileError from hed.models.column_metadata import ColumnMetadata, ColumnType from hed.models.definition_dict ...
hed-standard/hed-python
hed/models/sidecar.py
.py
5cd5a51e30ab2dd1
7.64
18
"""A spreadsheet of HED tags.""" from hed.models.base_input import BaseInput from hed.models.column_mapper import ColumnMapper class SpreadsheetInput(BaseInput): """A spreadsheet of HED tags.""" def __init__( self, file=None, file_type=None, worksheet_name=None, tag_c...
hed-standard/hed-python
hed/models/spreadsheet_input.py
.py
6e04fe58b923d2d4
7.64
18
"""A BIDS tabular file with sidecar.""" from __future__ import annotations from typing import TYPE_CHECKING from hed.models.base_input import BaseInput from hed.models.column_mapper import ColumnMapper from hed.models.sidecar import Sidecar if TYPE_CHECKING: from hed.models.definition_dict import DefinitionDict...
hed-standard/hed-python
hed/models/tabular_input.py
.py
3c2779cf70d5ee56
7.64
18
"""A BIDS time series tabular file.""" from hed.models.base_input import BaseInput class TimeseriesInput(BaseInput): """A BIDS time series tabular file.""" HED_COLUMN_NAME = "HED" def __init__(self, file=None, sidecar=None, extra_def_dicts=None, name=None): """Constructor for the TimeseriesInpu...
hed-standard/hed-python
hed/models/timeseries_input.py
.py
f0519b347cb5b61b
7.64
18
"""Support utilities for hed_cache locking""" import os import time import portalocker TIMESTAMP_FILENAME = "last_update.txt" CACHE_TIME_THRESHOLD = 300 * 6 class CacheError(Exception): """Exception for cache locking or threshold errors.""" pass class CacheLock: """Class to lock the cache folder to ...
hed-standard/hed-python
hed/schema/hed_cache_lock.py
.py
4619c75195aa10bd
7.64
18
"""Enumeration constants and string literals used throughout HED schema loading and validation.""" from enum import Enum class HedSectionKey(Enum): """Keys designating specific sections in a HedSchema object.""" # overarching category listing all tags Tags = "tags" # Overarching category listing all...
hed-standard/hed-python
hed/schema/hed_schema_constants.py
.py
a1fbc948325e43fb
7.64
18
"""Container for multiple HED schemas used together in multi-library validation.""" from __future__ import annotations import json from hed.errors import ErrorHandler, ValidationErrors from hed.errors.exceptions import HedExceptions, HedFileError from hed.schema.hed_schema import HedSchema from hed.schema.hed_schema...
hed-standard/hed-python
hed/schema/hed_schema_group.py
.py
d64551dc8eddd30c
7.64
18
"""Main command.""" from __future__ import annotations from pathlib import Path from shlex import quote from typing import TYPE_CHECKING, Any, BinaryIO, cast import json import logging import os import re import socket import struct import subprocess as sp import sys from bascom import setup_logging from open_in_mpv ...
Tatsh/open-in-mpv
open_in_mpv/main.py
.py
abcbffa59f3e1ca1
7.65
19
from __future__ import annotations from typing import TYPE_CHECKING, Any import json import re import struct from open_in_mpv.main import get_callback, get_mpv_path, main, spawn import pytest if TYPE_CHECKING: from unittest.mock import MagicMock from click.testing import CliRunner from pytest_mock impor...
Tatsh/open-in-mpv
tests/test_main.py
.py
808d83e008b5ba84
7.15
19
""" Tests for issue #1344: get_current_configuration must not create duplicate Configuration rows under concurrency, and must never expose a Configuration with an empty versions set. """ import threading import pytest from django.db import connection from topobank.analysis.tasks import get_current_configuration from...
ContactEngineering/topobank
tests/analysis/test_configuration_race.py
.py
f6039017d10915a9
8
9
""" Tests for issue #1345: when a workflow fails because a dependency failed, the parent must surface the dependency's real error/traceback, not a generic one. """ import pytest from topobank.analysis.models import Workflow, WorkflowResult from topobank.analysis.tasks import execute_workflow, schedule_workflow from t...
ContactEngineering/topobank
tests/analysis/test_dependency_traceback.py
.py
a326e28734495c0b
8
9
"""Tests for topobank.analysis.exceptions.""" from topobank.analysis.exceptions import SubjectNotReadyException def test_subject_not_ready_exception_message(): exc = SubjectNotReadyException("my-subject") assert isinstance(exc, Exception) message = str(exc) assert "my-subject" in message assert "...
ContactEngineering/topobank
tests/analysis/test_exceptions.py
.py
9ad11acfd76d25b8
8
9
""" Tests for bundling workflow results into a ZIP archive (``topobank.analysis.export_zip`` and ``topobank.analysis.zip_model``). """ import datetime import io import zipfile import pytest from django.conf import settings from django.core.exceptions import PermissionDenied from django.core.files.base import ContentF...
ContactEngineering/topobank
tests/analysis/test_export_zip.py
.py
0385dd2e7bce74e7
7
9
""" Tests for workflow output schema infrastructure. """ import pydantic import pytest from topobank.analysis.models import Workflow from topobank.analysis.outputs import OutputFile, get_outputs_schema from topobank.analysis.workflows import WorkflowImplementation class TestOutputFile: """Tests for the OutputFi...
ContactEngineering/topobank
tests/analysis/test_outputs.py
.py
46aa8c53a2cb82ec
8
9
""" Tests for the metadata that accompanies a split-off data series. Series data lives in its own file in the object store, so anything a plot needs before fetching them has to be recorded next to the reference. That includes the extent of the data, which is what lets a plot combining several results choose a display ...
ContactEngineering/topobank
tests/analysis/test_series_metadata.py
.py
b819864c8f76c2b4
8
9
""" Tests for issue #1343: the check-then-create dedup in submit / submit_for_surfaces must be serialized so concurrent identical submissions do not create duplicate WorkflowResults. """ import threading import pytest from django.db import connection from topobank.analysis.models import WorkflowResult from topobank....
ContactEngineering/topobank
tests/analysis/test_submit_dedup_race.py
.py
6b7c2ed074a2c5ed
8
9
""" Tests for invalidation and cleanup of surface-set (M2M) analyses (issue #1340). Surface-set analyses store their subjects via the ``WorkflowResult.surfaces`` M2M and have ``subject_surface`` NULL, so the invalidation signals and the custodian must match them through the M2M, not only the legacy subject FKs. """ i...
ContactEngineering/topobank
tests/analysis/test_surface_set_invalidation.py
.py
3fed550c004b7714
7
9
""" Tests for issue #1346: AnalysisController._get_unique_kwargs must return the true intersection of kwargs across analyses (dropping keys absent from or differing in any analysis) without mutating any analysis's stored kwargs. """ from types import SimpleNamespace from topobank.analysis.controller import AnalysisCo...
ContactEngineering/topobank
tests/analysis/test_unique_kwargs.py
.py
dd98ecb4f208bf9e
8
9
import pytest from topobank.analysis.models import Workflow from topobank.analysis.registry import get_workflow_names from topobank.testing.workflows import TestImplementation @pytest.mark.django_db def test_retrieve_registry_workflows(): names = get_workflow_names() assert TestImplementation.Meta.name in n...
ContactEngineering/topobank
tests/analysis/test_workflows.py
.py
873755afcce0c81d
8
9
import pytest from topobank.authorization import ( get_anonymous_user, get_organization_model, get_permission_model, get_user_permission_model, ) from topobank.authorization.models import levels_with_access def test_levels_with_access(): assert levels_with_access("full") == {"full"} assert le...
ContactEngineering/topobank
tests/authorization/test_utils.py
.py
96b4006b1a1d675d
7
9
""" Regression tests for management commands in topobank.manager. These exercise the command entry points on a (mostly) empty database. They are deliberately light-weight: the commands iterate over real objects and do heavy file I/O in production, so here we only ensure the commands are wired up and run end-to-end wit...
ContactEngineering/topobank
tests/manager/test_commands.py
.py
2cd8dd7c0388f4cf
7
9
""" Functional tests that import a real published surface container from contact.engineering and exercise the topography data pipeline end to end: file reading, the Celery task runner, metadata caching, and deepzoom / squeezed-data generation. The container is the published dataset https://doi.org/10.57703/ce-867nv ("...
ContactEngineering/topobank
tests/manager/test_container_pipeline.py
.py
d0c4d0e681d58dc7
8
9
""" Tests for writing surface containers """ import json import os import tempfile import zipfile import pytest from notifications.models import Notification import topobank from topobank.manager.export_zip import export_container_zip from topobank.manager.import_zip import import_container_zip, load_container_metad...
ContactEngineering/topobank
tests/manager/test_containers.py
.py
f2752358c4d82a61
8
9
"""Tests for the periodic cleanup task in topobank.manager.custodian.""" import datetime import pytest from django.utils import timezone from topobank.manager.custodian import periodic_cleanup from topobank.manager.models import Surface, Topography from topobank.testing.factories import SurfaceFactory, Topography2DF...
ContactEngineering/topobank
tests/manager/test_custodian.py
.py
13d7d69bc65c140a
7
9
import logging import pytest from topobank.testing.factories import Topography2DFactory @pytest.mark.django_db def test_deepzoom_creation_fails(mocker): topo = Topography2DFactory(size_x=1, size_y=1) topo.refresh_cache() # should have a deepzoom images assert topo.deepzoom is not None mocker.pa...
ContactEngineering/topobank
tests/manager/test_deepzoom.py
.py
5ef6885fc333f026
8
9
""" Tests for the trend that detrending subtracts from a measurement. `Topography.detrend_parameters` records what was removed — the slope of the tilt, the radius of the curvature — so the UI can show which correction is in effect rather than only naming the mode. """ import numpy as np import pytest from SurfaceTopo...
ContactEngineering/topobank
tests/manager/test_detrend_parameters.py
.py
900cbec6bf976d5d
7
9
""" Tests for the ``import_datasets`` management command. The command imports a surface from a previously-downloaded container archive (ONLY FOR USE WITH FILES FROM TRUSTED SOURCES). We build a real archive on disk with ``export_container_zip`` and import it back, which exercises the full command path: user lookup, ar...
ContactEngineering/topobank
tests/manager/test_import_datasets.py
.py
29047eeefcef3ecd
8
9
""" Tests for importing a dataset from another instance (``topobank.manager.tasks.import_container_from_url``). The remote describes how to obtain the container: a publication with an archived container advertises it as 'download_url' and it can simply be fetched, while otherwise the remote has to assemble one first, ...
ContactEngineering/topobank
tests/manager/test_import_from_url.py
.py
8e01e77f83f26a73
8
9
""" Tests for the `TOPOBANK_REJECT_INCOMPLETE_METADATA` global flag. A file can be of a supported format and read successfully, yet not contain the metadata (physical size, unit) required to process it. By default such a file is accepted and the user is expected to fill in the missing metadata through the UI. When `TO...
ContactEngineering/topobank
tests/manager/test_incomplete_metadata.py
.py
9872efa38b353df9
8
9
""" Tests for soft-delete bookkeeping on Surface and Topography. `lazy_delete` records the user who performed the deletion in `deleted_by`, on the object itself and on everything the call cascades to, so a recycle-bin view can report who deleted what while the object is still recoverable. """ import pytest from topo...
ContactEngineering/topobank
tests/manager/test_lazy_delete.py
.py
119136f4712d988c
7
9
""" Tests related to the models in topobank.manager app """ import datetime import pytest from django.apps import apps from django.core.files.base import ContentFile from django.db import transaction from django.db.utils import IntegrityError from notifications.models import Notification from notifications.signals im...
ContactEngineering/topobank
tests/manager/test_models.py
.py
1aae25dabd356695
7
9
""" Tests for the full-text search index on `Surface`. `Surface.build_search_document` assembles the searchable text from a dataset and its measurements, and the signal handlers in `manager.signals` keep `Surface.search_vector` current as either changes. These tests pin down what ends up in the index and, just as impo...
ContactEngineering/topobank
tests/manager/test_search_vector.py
.py
fb611ab8a2280751
7
9
""" Tests for issue #1342: Topography.save() with a restricted update_fields must still persist the pending task state that run_task sets in memory. Otherwise a recompute is dispatched while the DB keeps task_state=SUCCESS (get_task_state() then wrongly reports "done"), and the in-flight re-dispatch guard — which keys...
ContactEngineering/topobank
tests/manager/test_topography_task_state.py
.py
217860dde82c4f44
8
9
""" Tests for how much of a measurement is undefined. A measurement can carry data points that hold no value, because the instrument could not resolve them. `Topography.has_undefined_data` records that this is the case and `Topography.undefined_data_fraction` how much of the data it affects, both describing the data a...
ContactEngineering/topobank
tests/manager/test_undefined_data.py
.py
d304203f4fe2f200
8
9
""" Tests for the interface to topography files and other things in topobank.manager.utils """ import pytest from topobank.manager.models import Surface, Topography from topobank.manager.utils import ( subjects_from_base64, subjects_from_dict, subjects_to_base64, subjects_to_dict, to_natural_lengt...
ContactEngineering/topobank
tests/manager/test_utils.py
.py
246f0b1279660a0e
8
9
"""Tests for topobank.manager.zip_model.ZipContainer.""" import json import zipfile import pytest from django.core.exceptions import PermissionDenied from topobank.manager.zip_model import ZipContainer from topobank.testing.factories import SurfaceFactory, UserFactory from topobank.testing.mock_auth.authorization.mo...
ContactEngineering/topobank
tests/manager/test_zip_model.py
.py
7a8df020a655aaec
7
9
from django.test import TestCase from django.urls import reverse from articles.models import Article from faker import Faker from datetime import timedelta from main_app.tests.make_fakes import ( make_fake_user, ) # run with `python -Wa manage.py test articles.tests.test_articles` # the -Wa flag tells Python to d...
DDMAL/CantusDB
django/cantusdb_project/articles/tests/test_articles.py
.py
18bf166241889e88
8.02
10
""" A collection of functions for fetching data from Cantus Index's (CI's) various APIs. """ import json from typing import Optional, Union, Callable, TypedDict, Any import requests from requests.exceptions import SSLError, Timeout, HTTPError from main_app.models import Genre CANTUS_INDEX_DOMAIN: str = "https://can...
DDMAL/CantusDB
django/cantusdb_project/cantusindex.py
.py
8697cadc08002527
7.52
10
""" Utilities for parsing IIIF manifests and generating folio-to-image mappings. Supports both IIIF Presentation API 2.x and 3.0 manifests. """ import csv import io import json import re import time from dataclasses import dataclass import requests # A manifest is JSON metadata, not image data: the largest one we'v...
DDMAL/CantusDB
django/cantusdb_project/main_app/iiif_utils.py
.py
66e580de7b0fc044
7.52
10
""" This command is meant to be used one time toward solving issue 1542, assigning chants and sequences, where necessary, to their appropriate "project". This command assigns sequences to the Bower project. Chants (in non-Bower sources) currently have project. Note: This command can only be run *after* the Bower proj...
DDMAL/CantusDB
django/cantusdb_project/main_app/management/commands/assign_sequences_to_bower_project.py
.py
31ac96cde5e1271e
7.52
10
"""Copy chants from student-work sources into the Kaiatonsera master source. One-shot command for issue #2038. `--dry-run` previews counts and sanity checks; the real run is guarded against drift, malformed folios, and slot collisions before any write. """ import argparse import re from collections.abc import Callabl...
DDMAL/CantusDB
django/cantusdb_project/main_app/management/commands/copy_chants_to_master_source.py
.py
54abc8ce4b316679
7.52
10
"""Full-service interface to converting, validating, and registering biological sequence variation.""" import datetime import importlib.util import logging import os import warnings from collections.abc import Iterable from urllib.parse import urlparse from ga4gh.vrs import models as vrs_models from anyvar.core impo...
biocommons/anyvar
src/anyvar/anyvar.py
.py
9e61206d7ef94c5f
7.63
17