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 |
|---|---|---|---|---|---|---|
"""
Test d'intégration pour la route: Streaming de musique (/playlist/<uuid:soundboard_uuid>/<uuid:playlist_uuid>/stream)
"""
from django.test import TestCase, Client, tag
from django.urls import reverse
from django.contrib.auth import get_user_model
import uuid
User = get_user_model()
@tag('integration')
class Stre... | chaBiselx/AmbianceBoard | app/main/TNR/TI/routing/StreamMusicRouteTest.py | .py | 41aed9ea74aa7ed7 | 7.65 | 1 |
"""
Test d'integration pour la route: support (/support)
"""
from django.test import TestCase, Client, tag
from django.urls import reverse
@tag('integration')
class SupportContactRouteTest(TestCase):
"""Tests pour la route support contact"""
def setUp(self):
self.client = Client()
def test_suppo... | chaBiselx/AmbianceBoard | app/main/TNR/TI/routing/SupportContactRouteTest.py | .py | 08c576921e255dc3 | 7.65 | 1 |
import argparse
from Bio import SeqIO
from csv import DictReader
from datetime import date, datetime
import re
import sys
description = """\
Use metadata to relabel sequences in the associated FASTA file.
"header" field of metadata CSV must match the sequence labels.
By default, the script assumes the field to appen... | PoonLab/Bioplus | Bioplus/add_dates.py | .py | cabc3551ea37667d | 7 | 0 |
from Bio import SeqIO
import subprocess
import argparse
import tempfile
from io import StringIO
import os
import sys
def align_amino(records, bin='mafft'):
handle = tempfile.NamedTemporaryFile(delete=False)
for record in records:
aaseq = record.seq.translate()
line = f">{record.name}\n{aaseq}\... | PoonLab/Bioplus | Bioplus/codon_align.py | .py | ff02c4613210ee12 | 7 | 0 |
from Bio import SeqIO
import argparse
import sys
description = """
Generate a consensus sequence from a set of aligned sequences.
While this is possible in BioPython, it is rather convoluted.
"""
mixture_dict = {'W': 'AT', 'R': 'AG', 'K': 'GT', 'Y': 'CT', 'S': 'CG',
'M': 'AC', 'V': 'AGC', 'H': 'ATC',... | PoonLab/Bioplus | Bioplus/consensus.py | .py | ab810fe8a8165a66 | 7 | 0 |
import math
from Bio import AlignIO
import argparse
import csv
import sys
description = """\
Calculate a k-mer distance (Euclidean, spectrum kernel), p-distance or
Jukes-Cantor corrected distance for an alignment of nucleotide sequences."
"""
def kmer(seq, k):
"""
Calculate word counts for words of length k... | PoonLab/Bioplus | Bioplus/dist.py | .py | 68add80afb1dcb1d | 7 | 0 |
from Bio import Entrez, SeqIO, Phylo
import sys
import time
import argparse
import re
from csv import DictWriter
description = """\
Retrieve metadata (e.g., sample collection dates) associated with sequences
in the input file, based on their respective NCBI Genbank accession numbers.
"""
pat1 = re.compile("[A-Z]{1,3... | PoonLab/Bioplus | Bioplus/get_metadata.py | .py | e71cdbe29ddfa7b4 | 7 | 0 |
from io import StringIO
from Bio import SeqIO
import argparse
import sys
import tempfile
import subprocess
try:
from mpi4py import MPI
nprocs = MPI.COMM_WORLD.Get_size()
my_rank = MPI.COMM_WORLD.Get_rank()
except ModuleNotFoundError:
sys.stderr.write("Running in serial mode...\n")
nprocs = 1
my... | PoonLab/Bioplus | Bioplus/pair_align.py | .py | e608e86bd7f04cde | 7 | 0 |
import random
import argparse
description = """
Random permutation of FASTA file.
This script reads a FASTA-formatted file containing aligned sequences and
applies a random permutation of alignment columns (nucleotide sites),
writing the result to a new FASTA file. A random permutation changes the
order of a sequenc... | PoonLab/Bioplus | Bioplus/permute_fasta.py | .py | 29325ab17529a1a3 | 7 | 0 |
import argparse
from Bio import AlignIO, SeqIO, Phylo
import sys
import csv
description = """\
Down-sample a sequence alignment by building a tree and progressively
removing the shortest tips until only a target number of tips remain.
The tip labels are used to select sequences from the alignment.
"""
def prune_tip... | PoonLab/Bioplus | Bioplus/prunetree.py | .py | d776723ccbf9daf0 | 7 | 0 |
description = """
Given a tree where some tips have missing metadata (e.g., subtype, country),
impute these values by propagating labels from neighbouring tips.
"""
import argparse
import sys
import random
from Bio import Phylo
def climb(tips, curnode, pathlen, cutoff):
""" Recursive function for traversing up ... | PoonLab/Bioplus | Bioplus/relabel_tips.py | .py | e1367c4538cb2eca | 7 | 0 |
"""Generic models used for the (websockets) API communication."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
from mashumaro.mixins.orjson import DataClassORJSONMixin
from music_assistant_models.enums import CoreState
from .event import MassEvent
from .helpers... | music-assistant/models | music_assistant_models/api.py | .py | 64302b38e709afae | 7.24 | 2 |
"""Models for effective audio processing details."""
from __future__ import annotations
from dataclasses import dataclass, field
from enum import StrEnum
from mashumaro import DataClassDictMixin
from .dsp import AudioChannel, DSPFilter, DSPState
from .enums import CrossfadeMode, VolumeNormalizationMode
from .media_... | music-assistant/models | music_assistant_models/audio_processing.py | .py | 81a6f6cc076444ee | 7.24 | 2 |
"""Authentication models for Music Assistant API."""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import UTC, datetime
from enum import StrEnum
from typing import Any
from mashumaro.mixins.orjson import DataClassORJSONMixin
class UserRole(StrEnum):
"""
The role ... | music-assistant/models | music_assistant_models/auth.py | .py | 01a7ace66a34572a | 7.24 | 2 |
"""Models for long running background tasks in Music Assistant."""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import UTC, datetime
from typing import Any
from uuid import uuid4
from mashumaro import DataClassDictMixin, field_options
from .enums import TaskScheduleType,... | music-assistant/models | music_assistant_models/background_task.py | .py | ced37f23b61dd6f8 | 7.24 | 2 |
"""Model(s) for dashboards shown on display devices and (api) clients."""
from __future__ import annotations
from dataclasses import dataclass, field
from mashumaro import DataClassDictMixin
from .enums import DashboardType
@dataclass
class DashboardDevice(DataClassDictMixin):
"""Model for a registered dashbo... | music-assistant/models | music_assistant_models/dashboard.py | .py | b76abb982b9e56df | 7.24 | 2 |
"""All DSP (Digital Signal Processing) related models."""
from __future__ import annotations
from dataclasses import dataclass, field
from enum import IntEnum, StrEnum
from typing import Literal
from mashumaro import DataClassDictMixin
# ruff: noqa: S105
class AudioChannel(StrEnum):
"""Enum of all channel tar... | music-assistant/models | music_assistant_models/dsp.py | .py | 0896c01d7ef96709 | 7.24 | 2 |
"""Custom errors and exceptions."""
from typing import Any
class MusicAssistantError(Exception):
"""Custom Exception for all errors."""
error_code = 0
# Default translation key for this error type: a bare slug (e.g. ``media_not_found``). During
# outbound API serialization the error model derives th... | music-assistant/models | music_assistant_models/errors.py | .py | 6257aafd11910b27 | 7.24 | 2 |
"""Generic Utility functions/helpers for the Music Assistant project."""
from __future__ import annotations
import asyncio
import base64
import re
from _collections_abc import dict_keys, dict_values
from asyncio import Task
from types import MethodType
from typing import Any
from unicodedata import combining, normali... | music-assistant/models | music_assistant_models/helpers.py | .py | bbf7a13afd2b5727 | 7.24 | 2 |
"""Model for AudioFormat details."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from mashumaro import DataClassDictMixin
from music_assistant_models.enums import ContentType
MetadataTypes = int | bool | str | list[str]
@dataclass(kw_only=True)
class AudioFormat(Da... | music-assistant/models | music_assistant_models/media_items/audio_format.py | .py | e538da185c7df184 | 7.24 | 2 |
"""Models for MediaItem Metadata."""
from __future__ import annotations
from collections.abc import Callable
from contextvars import ContextVar
from dataclasses import dataclass, fields
from datetime import datetime
from typing import Any
from mashumaro import DataClassDictMixin
from music_assistant_models.enums im... | music-assistant/models | music_assistant_models/media_items/metadata.py | .py | 645ea1cffcd6e49a | 7.24 | 2 |
"""Models and helpers for MediaItem's provider mapping details."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, cast
from mashumaro import DataClassDictMixin
from music_assistant_models.helpers import get_global_cache_value
from .audio_format import ... | music-assistant/models | music_assistant_models/media_items/provider_mapping.py | .py | 407923cb56301a43 | 7.24 | 2 |
"""Model(s) for PlayerQueue."""
from __future__ import annotations
import time
from dataclasses import dataclass, field
from typing import Any
from mashumaro import DataClassDictMixin
from .constants import EXTRA_ATTRIBUTES_TYPES
from .enums import PlaybackState, RepeatMode
from .media_items import ItemMapping
from... | music-assistant/models | music_assistant_models/player_queue.py | .py | a78a8f423bb2e3e8 | 7.24 | 2 |
"""Models for providers and plugins in the MA ecosystem."""
from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from mashumaro.mixins.orjson import DataClassORJSONMixin
from .enums import ProviderFeature, ProviderIconVariant, Pro... | music-assistant/models | music_assistant_models/provider.py | .py | 7674866ff15dfe1d | 7.24 | 2 |
"""Model a QueueItem."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Self
from uuid import uuid4
from mashumaro import DataClassDictMixin
from .constants import EXTRA_ATTRIBUTES_TYPES
from .enums import MediaType
from .media_items import (
ItemMapping,
... | music-assistant/models | music_assistant_models/queue_item.py | .py | 5e4bbccbe4675ea9 | 7.24 | 2 |
"""Model for a step of a running setup flow."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
from mashumaro import DataClassDictMixin, field_options
from .config_entries import ConfigEntry
from .enums import FlowStepType
from .translations import resolve_transla... | music-assistant/models | music_assistant_models/setup_flow.py | .py | 7de70a6e9be1c1ff | 7.24 | 2 |
"""Translation resolution hook used during outbound API serialization."""
from __future__ import annotations
from collections.abc import Callable
from contextvars import ContextVar
# ContextVar set by the Music Assistant server during outbound API serialization.
# When set, model __post_serialize__ hooks use the res... | music-assistant/models | music_assistant_models/translations.py | .py | 37a0abc9b6e38901 | 7.24 | 2 |
"""Representation of a custom List that ensures the items are unique."""
from __future__ import annotations
from collections.abc import Iterable
from typing import TypeVar
_T = TypeVar("_T")
class UniqueList(list[_T]):
"""Custom list that ensures the inserted items are unique."""
def __init__(self, iterab... | music-assistant/models | music_assistant_models/unique_list.py | .py | 7441c912374811d0 | 7.24 | 2 |
"""Tests for the AudioFormat model."""
from unittest.mock import ANY
from music_assistant_models.enums import ContentType
from music_assistant_models.media_items import AudioFormat
def _pcm(content_type: ContentType, bit_depth: int = 32) -> AudioFormat:
return AudioFormat(
content_type=content_type,
... | music-assistant/models | tests/test_audio_format.py | .py | 76eed3e8dcee427f | 7.74 | 2 |
"""Tests for the AudioSource MediaItem and related types."""
from music_assistant_models.enums import MediaType, SourceControl
from music_assistant_models.media_items import (
AudioSource,
ItemMapping,
media_from_dict,
)
from music_assistant_models.media_items.provider_mapping import ProviderMapping
def ... | music-assistant/models | tests/test_audio_source.py | .py | 1164e03615b36eb5 | 7.74 | 2 |
"""Tests for the authentication models."""
import pytest
from music_assistant_models.auth import (
AuthProviderType,
Scope,
User,
UserRole,
)
def test_user_role_validation() -> None:
"""Test that an unknown (builtin) user role raises on validation."""
with pytest.raises(ValueError, match="so... | music-assistant/models | tests/test_auth.py | .py | e352f2fbe2701c53 | 7.74 | 2 |
"""Tests for background task serialization."""
from music_assistant_models.background_task import BackgroundTask
def test_report_defaults_to_none() -> None:
"""A task has no report until its work produces one."""
task = BackgroundTask(name="Test task")
assert task.report is None
assert task.to_dict(... | music-assistant/models | tests/test_background_task.py | .py | b77fab9595cabb83 | 7.74 | 2 |
"""Tests for the one-shot config action result and its message localization."""
from collections.abc import Iterator
from contextlib import contextmanager
from typing import Any
from music_assistant_models.config_entries import ConfigActionResult
from music_assistant_models.translations import TRANSLATION_RESOLVER
... | music-assistant/models | tests/test_config_action_result.py | .py | 3920679625f6e88b | 7.74 | 2 |
"""Tests for config entry types, the storage-only setup_data field and dependency gating."""
from collections.abc import Callable
from typing import Any, cast
import pytest
from music_assistant_models.config_entries import (
UI_ONLY,
ConfigEntry,
ConfigEntryTypeMap,
ConfigValueType,
PlayerConfig,... | music-assistant/models | tests/test_config_entries.py | .py | 220f31eb87b4c632 | 7.74 | 2 |
"""Tests for DSP models."""
import pytest
from music_assistant_models.dsp import (
BalanceFilter,
CompressorFilter,
ConvolutionFilter,
CrossfeedFilter,
DSPConfig,
DSPFilterType,
GainFilter,
HighLowPassFilter,
HighLowPassMode,
HighLowPassSlope,
SafetyLimiterFilter,
Stere... | music-assistant/models | tests/test_dsp.py | .py | e2b54a24207722d3 | 7.74 | 2 |
"""Tests for localized MusicAssistantError messages on ErrorResultMessage."""
from collections.abc import Iterator
from contextlib import contextmanager
from typing import Any
from music_assistant_models.api import ErrorResultMessage
from music_assistant_models.errors import (
ERROR_MAP,
InvalidToken,
Med... | music-assistant/models | tests/test_error_translations.py | .py | 383d0220d5a64513 | 7.74 | 2 |
"""Tests for the Genre.content_type field (taxonomy namespacing) serialization."""
from music_assistant_models.enums import MediaType
from music_assistant_models.media_items import Genre
def test_content_type_defaults_to_none() -> None:
"""A genre with no content_type defaults to None (music/general)."""
gen... | music-assistant/models | tests/test_genre_content_type.py | .py | b2432b29a585f40c | 7.74 | 2 |
"""Tests for utility/helper functions."""
from music_assistant_models import helpers
def test_create_sort_name() -> None:
"""Test create_sort_name helper."""
assert helpers.create_sort_name("The Beatles") == "beatles, the"
assert helpers.create_sort_name("The Rolling Stones") == "rolling stones, the"
... | music-assistant/models | tests/test_helpers.py | .py | 2d1cfd5ead4c32e1 | 7.74 | 2 |
"""Tests for MediaCollection."""
import orjson
from music_assistant_models.enums import MediaType
from music_assistant_models.helpers import get_serializable_value
from music_assistant_models.media_items import Audiobook, MediaCollection, media_from_dict
from music_assistant_models.media_items.media_item import ItemM... | music-assistant/models | tests/test_media_collection.py | .py | 391cfc2f99c992ee | 7.74 | 2 |
"""Tests for MediaItemImage serialization and proxy id injection."""
import hashlib
from music_assistant_models.enums import ImageType
from music_assistant_models.media_items.metadata import (
IMAGE_PROXY_ID_RESOLVER,
MediaItemImage,
)
def _resolver(provider: str, path: str) -> str:
# url-path-segment-s... | music-assistant/models | tests/test_media_item_image.py | .py | 8fd4f6dc226a78bc | 7.74 | 2 |
"""Tests for the Player and PlayerMedia models (serialization/back-compat)."""
from music_assistant_models.audio_processing import ActiveSourceAudioDetails, AudioOutputDetails
from music_assistant_models.enums import (
ContentType,
CrossfadeMode,
MediaType,
PlayerType,
RepeatMode,
)
from music_assi... | music-assistant/models | tests/test_player.py | .py | 8dfa3386cb3de6a7 | 7.74 | 2 |
"""Tests for the PlayerQueue model (deprecated-key back-compat serialization)."""
from music_assistant_models.enums import MediaType
from music_assistant_models.media_items import ItemMapping
from music_assistant_models.player_queue import PlayerQueue
def _queue() -> PlayerQueue:
return PlayerQueue(queue_id="q1"... | music-assistant/models | tests/test_player_queue.py | .py | 80fa7d6d8aea2a2c | 7.74 | 2 |
"""Tests for the Playlist MediaItem."""
from music_assistant_models.enums import MediaType
from music_assistant_models.media_items import Playlist, media_from_dict
def _playlist_dict(supported_mediatypes: list[str] | None = None) -> dict:
playlist: dict = {
"item_id": "1",
"provider": "library",
... | music-assistant/models | tests/test_playlist.py | .py | af69716a2cfb8159 | 7.74 | 2 |
"""Tests for the PlaylogUpdate model and the PLAYLOG_UPDATED event type."""
from music_assistant_models.enums import EventType, MediaType
from music_assistant_models.event import MassEvent
from music_assistant_models.playlog_update import PlaylogUpdate
def test_event_type_playlog_updated_roundtrips() -> None:
""... | music-assistant/models | tests/test_playlog_update.py | .py | 5b6670db5523741e | 7.74 | 2 |
# MIT License
#
# Copyright (c) 2020 Lionkk
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publi... | feagi/embodiment-controllers | embodiments/archive/linux_python_microbit/incomplete_controller_for_python.py | .py | bf0a5129a072a3e9 | 7.35 | 4 |
"""
"""
import zmq
import socket
import requests
def app_host_info():
host_name = socket.gethostname()
ip_address = socket.gethostbyname(socket.gethostname())
return {"ip_address": ip_address, "host_name": host_name}
class Pub:
def __init__(self, address):
context = zmq.Context()
s... | feagi/embodiment-controllers | embodiments/archive/linux_python_microbit/router.py | .py | 58f14f4f44cd2af0 | 7.35 | 4 |
"""
This module needs to be compiled using colcon for ROS2 and is not directly run by FEAGI
Todo: Need to implement an automated method to deploy and compile this method.
1. mkdir -p ~/ros2_ws/src # Create a ros2 workspace
2. cd ~/ros2_ws/src
3. ros2 pkg create --build-type ament_python py_topic # Create a ros... | feagi/embodiment-controllers | embodiments/arduino/archieved/py2arduino.py | .py | c0ca252681a38a68 | 7.35 | 4 |
"""
Copyright (c) 2010, Tino de Bruijn
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute... | feagi/embodiment-controllers | embodiments/arduino/pyfirmata/util.py | .py | d77860fc0d83c56a | 7.35 | 4 |
#!/usr/bin/env python
"""
Cutebot Bluetooth Controller
Simple controller for ELECFREAKS Cutebot using FEAGI Python SDK.
Demonstrates the simplicity of the Bluetooth robot framework!
Copyright 2016-2025 Neuraville Inc. All Rights Reserved.
"""
import asyncio
import argparse
from feagi.agent import BluetoothRobot
cl... | feagi/embodiment-controllers | embodiments/elecfreaks/cutebot/controller.py | .py | f9cbb28d4f7a2835 | 7.35 | 4 |
# This is designed and defined by Freenove using photoresistor.
import smbus
import time
class Adc:
def __init__(self):
# Get I2C bus
self.bus = smbus.SMBus(1)
# I2C address of the device
self.ADDRESS = 0x48
# PCF8591 Command
self.PCF8591_CMD = 0x40 # Command
... | feagi/embodiment-controllers | embodiments/freenove/feagi_connector_freenove/feagi_connector_freenove/ADC.py | .py | d3f0e54be1e1560e | 7.35 | 4 |
# %%
"""
This module contains functions for formatting machine configurations and solving the LED
button problem using Gaussian elimination.
"""
from pathlib import Path
from itertools import product
import numpy as np
HERE = Path(__file__).parent
MODE = "input"
if MODE == "example":
file = HERE / "example.txt"
e... | cjcolman/advent_of_code | 2025/Connor/10/factory.py | .py | f8825acff9a113fa | 7 | 0 |
# %%
def parse_input(filepath):
"""Input comes in two parts, first half is the ranges of fresh ids, e.g. "2390-2602". One per line.
Second half is a list of ids, one per line.
Two halves separeted by a blank line.
Returns a list of tuples representing the ranges and a list of ids to check."""
... | cjcolman/advent_of_code | 2025/Connor/5/cafeteria.py | .py | bf904672c1fa1450 | 7 | 0 |
# %%
import functools
def parse_input(filepath):
grid = {}
with open(filepath, 'r') as file:
data = [line.strip() for line in file.readlines()]
for i in range(len(data)):
for j in range(len(data[0])):
grid[i + 1j*j] = data[i][j]
if data[i][j] == 'S':
... | cjcolman/advent_of_code | 2025/Connor/7/laboratories.py | .py | 881d92a1e1f21cd0 | 7 | 0 |
# %%
with open("input.txt") as f:
lines = f.read().split("\n")
coords = [tuple(int(j) for j in i.split(",")) for i in lines]
# with open("example.txt") as f:
# lines = f.read().split("\n")
# coords = [tuple(int(j) for j in i.split(",")) for i in lines]
# %%
from collections import deque
# %%
max_area... | cjcolman/advent_of_code | 2025/Connor/9/movie_theatre.py | .py | 615eb7669d523a68 | 7 | 0 |
from collections import deque
from datetime import datetime
import logging
from logging import config
logging_config = {
"version": 1,
"formatters": {
"default": {"format": "[%(asctime)s: %(levelname)s/%(name)s]: %(message)s"}
},
"handlers": {
"console": {
"class": "logging.... | TranslatorSRI/TestHarness | test_harness/logger.py | .py | b8fa6f2c5fd938cc | 7.5 | 0 |
"""Render Locust-style time-series charts from a stats_history snapshot."""
from __future__ import annotations
import io
import logging
from datetime import datetime
from typing import Any, Dict, List, Optional, Sequence, Tuple
import matplotlib
matplotlib.use("Agg")
import matplotlib.dates as mdates
import matplo... | TranslatorSRI/TestHarness | test_harness/perf_plots.py | .py | 9e7d08eb5219c0a7 | 7.5 | 0 |
"""Information Radiator Reporter."""
import logging
import os
from datetime import datetime
from typing import List, Union
import httpx
from translator_testing_model.datamodel.pydanticmodel import (
PathfinderTestAsset,
PathfinderTestCase,
PerformanceTestCase,
TestAsset,
TestCase,
)
class Report... | TranslatorSRI/TestHarness | test_harness/reporter.py | .py | f167340735732734 | 7.5 | 0 |
"""Slack notification integration class."""
import json
import logging
import os
import re
import tempfile
import httpx
from slack_sdk import WebClient
# Slack rejects section blocks whose text exceeds 3000 chars. Leave a small
# safety margin so we never end up at the boundary.
SLACK_SECTION_TEXT_LIMIT = 2900
def... | TranslatorSRI/TestHarness | test_harness/slacker.py | .py | ba9ccafde49882be | 7.5 | 0 |
"""General utilities for the Test Harness."""
from dataclasses import dataclass
from enum import Enum
import logging
from typing import Dict, List, Optional, Tuple, Union
import httpx
from translator_testing_model.datamodel.pydanticmodel import (
PathfinderTestAsset,
PathfinderTestCase,
TestAsset,
Tes... | TranslatorSRI/TestHarness | test_harness/utils.py | .py | 097e7c4b92303665 | 7.5 | 0 |
"""Logging setup."""
import logging
class ColoredFormatter(logging.Formatter):
"""Colored formatter."""
prefix = "[%(asctime)s: %(levelname)s/%(name)s]:"
default = f"{prefix} %(message)s"
error_fmt = f"\x1b[31m{prefix}\x1b[0m %(message)s"
warning_fmt = f"\x1b[33m{prefix}\x1b[0m %(message)s"
... | TranslatorSRI/TestHarness | tests/helpers/logger.py | .py | 8e05b44205d076f5 | 7.5 | 0 |
"""Tests for running the harness locally without a Reporter or Slacker.
These cover the ``--local`` switch and the fall-back to local stand-ins when
the Information Radiator / Slack aren't configured, including saving the CSV
and JSON results to disk.
"""
import json
import os
from test_harness.main import main
from... | TranslatorSRI/TestHarness | tests/test_local.py | .py | 3ddd1035d9a9f839 | 7.5 | 0 |
"""Regression tests for test-result propagation to reporting services.
These cover bugs where results were dropped or mangled on their way to the
Information Radiator (Reporter) and/or Slack (via the ResultCollector output):
* A skipped test case left its assets marked FAILED (for ARAs) / NO_RESULTS
(for ARS) inste... | TranslatorSRI/TestHarness | tests/test_reporting.py | .py | 08c35cda1632873d | 7.5 | 0 |
"""Test the Harness run file."""
import pytest
from pytest_httpx import HTTPXMock
from test_harness.run import run_tests
from .helpers.example_tests import example_test_cases
from .helpers.mocks import (
MockReporter,
MockResultCollector,
MockSlacker,
MockQueryRunner,
)
from .helpers.logger import se... | TranslatorSRI/TestHarness | tests/test_run.py | .py | bf87b7c6653b12f1 | 7.5 | 0 |
"""
EM / F1 / accuracy scoring for a predictions CSV.
The CSV needs a ``ground_truth`` and a ``generated_answer`` column, which is
what every runner in ``research/`` writes.
python research/evaluation/cal_f1_em.py --predictions results/<file>.csv
"""
import argparse
import collections
import os
import re
import ... | vertaix/Vendi-RAG | research/evaluation/cal_f1_em.py | .py | 29262fb0380c7902 | 7.15 | 1 |
"""Pluggable text embedders.
Anything with an ``encode(texts) -> (n, d) array`` method works as an embedder
in this package. Two implementations ship here:
* :class:`HashingEmbedder` — pure numpy, no downloads, deterministic. Good
enough for demos, tests, and small corpora, and it lets the whole library run
off... | vertaix/Vendi-RAG | vendirag/embeddings.py | .py | 2f2d8f3ca55b4e38 | 7.15 | 1 |
"""Lightweight data containers shared across the package."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Optional
import numpy as np
__all__ = ["Document", "RetrievalResult"]
@dataclass
class Document:
"""A retrievable chunk of text plus arbitrary metada... | vertaix/Vendi-RAG | vendirag/types.py | .py | 8f49bc76a73f0527 | 7.15 | 1 |
"""
Vendi Score primitives.
The Vendi Score (VS) of a set of items is the exponential of the Shannon
entropy of the eigenvalues of their normalized similarity matrix
(Friedman & Dieng, TMLR 2023):
VS_k(D) = exp( -sum_i lambda_i log lambda_i ),
where lambda_1..lambda_n are the eigenvalues of K / n, with K_ij = k(... | vertaix/Vendi-RAG | vendirag/vendi.py | .py | eacdcdaa24bf0da6 | 7.15 | 1 |
"""
Plots and animations of a Vendi retrieval.
Optional module — needs ``matplotlib`` and ``pillow``::
pip install "vendirag[viz]"
The interesting thing to look at is what happens to the *selected set* as the
diversity weight ``s`` sweeps from pure relevance to pure diversity, so that is
what :func:`make_selecti... | vertaix/Vendi-RAG | vendirag/viz.py | .py | 510139fe6d4ce246 | 7.15 | 1 |
from __future__ import annotations
import json
import logging
from pathlib import Path
import yaml
from ogc.bblocks.transform import _PERMISSION_CHECKED_TYPES as _RISKY_TRANSFORM_TYPES, read_plugin_entries
logger = logging.getLogger(__name__)
_PERMISSIONS_FILE = 'permissions.json'
def _load_cache(sandbox_dir: Pa... | opengeospatial/bblocks-postprocess | ogc/bblocks/permissions.py | .py | 19deb83c8703be62 | 7.15 | 1 |
from __future__ import annotations
import re
import shutil
import sys
from pathlib import Path
from ogc.bblocks.log import run_logged, log_indent
_PYTHON_VERSION = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
SANDBOX_DIR_NAME = '.bblocks-sandbox'
_OLD_SANDBOX_DIR_NAME = '.transforms... | opengeospatial/bblocks-postprocess | ogc/bblocks/sandbox.py | .py | 975f97c6a290c7f9 | 7.15 | 1 |
from __future__ import annotations
import hashlib
import json
import logging
import os
import re
from pathlib import Path
logger = logging.getLogger(__name__)
_TEMPLATE_DIR_ENV = 'BBP_TEMPLATE_DIR'
_HASH_MANIFEST_FILENAME = '.known-template-hashes.json'
_TRACKED_FILES = tuple((Path(__file__).parent / 'tracked_templa... | opengeospatial/bblocks-postprocess | ogc/bblocks/template_sync.py | .py | 3a5f7ec6c88e70bd | 7.15 | 1 |
import os
from typing import Any, Dict, Optional
import requests
from farlog import getLogger
from requests.adapters import HTTPAdapter
from requests.auth import HTTPDigestAuth
from urllib3.util.retry import Retry
logger = getLogger("funget")
class Downloader:
"""下载器基类"""
def __init__(
self,
... | farfarfun/funget | src/funget/download/core.py | .py | 6b642affe79c5b86 | 7 | 0 |
import os
import requests
from funfile import file_tqdm_bar
from farlog import getLogger
from .core import Downloader
logger = getLogger("funget")
class SingleDownloader(Downloader):
"""单线程下载器"""
def download(self, prefix: str = "", chunk_size: int = 2048) -> bool:
"""执行单线程下载"""
try:
... | farfarfun/funget | src/funget/download/single.py | .py | df0f1e829785a0ff | 7 | 0 |
"""
下载器模块测试
"""
import os
import tempfile
import unittest
from unittest.mock import Mock, patch
from funget.download.core import Downloader
from funget.download.multi import MultiDownloader
from funget.download.single import SingleDownloader
class TestDownloader(unittest.TestCase):
"""下载器基类测试"""
def setUp(... | farfarfun/funget | tests/test_downloader.py | .py | 94cb8fffdb1d6c41 | 7.5 | 0 |
# Tests to perform
import json
import time
import os
import config
import boto3
import requests
import pytest
from requests_aws4auth import AWS4Auth
from botocore.exceptions import ClientError
env = os.environ.get("ENVIRONMENT", "local")
workspace = os.environ.get("WORKSPACE", "local")
@pytest.fixture(autouse=True,... | ministryofjustice/opg-data-lpa-instructions-preferences | integration/test_end_to_end.py | .py | 722502a5393b188e | 7.65 | 1 |
import os
import json
import shutil
import datetime
import time
import traceback
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch_all
from app.utility.custom_logging import custom_logger, LogMessageDetails
from app.utility.bucket_manager import BucketManager, ScanLocationStore
from app... | ministryofjustice/opg-data-lpa-instructions-preferences | lambdas/image_processor/app/handler.py | .py | bfc648acb6be32d5 | 7.15 | 1 |
import cv2
import numpy as np
from PIL import Image
from pdf2image import convert_from_bytes
from typing import List, Optional, ByteString, Dict, Any, Tuple
import uuid
from PIL import Image as im
class ImageReader:
"""ImageReader utility class
General purpose class for reading PDF files from a local
pa... | ministryofjustice/opg-data-lpa-instructions-preferences | lambdas/image_processor/app/utility/image_reader.py | .py | 1449b10d3741cf49 | 7.15 | 1 |
import datetime
import json
import boto3
import jwt
import os
import requests
from app.utility.custom_logging import custom_logger
from botocore.exceptions import ClientError
logger = custom_logger("sirius_service")
class SiriusService:
def __init__(self, environment):
self.environment = environment
... | ministryofjustice/opg-data-lpa-instructions-preferences | lambdas/image_processor/app/utility/sirius_service.py | .py | 195c1519fc0b5c09 | 7.15 | 1 |
from copy import deepcopy
from pydantic import BaseModel
from typing import Optional, Union, Dict, Any
from .bounding_box import BoundingBox
class FormField(BaseModel):
"""Form field class.
Represents a field in a form template, typically a PDF
form.
Attributes:
name (Optional[str]): Field ... | ministryofjustice/opg-data-lpa-instructions-preferences | lambdas/image_processor/form-tools/form_tools/form_meta/form_field.py | .py | 2cd36237f035a402 | 7.15 | 1 |
import re
from copy import deepcopy
from warnings import warn
from pydantic import BaseModel, validator
from jsonschema.exceptions import ValidationError
from typing import List, Union, Any, Dict, Optional
from mojap_metadata.metadata.metadata import (
MetadataProperty,
Metadata,
)
from .form_field import For... | ministryofjustice/opg-data-lpa-instructions-preferences | lambdas/image_processor/form-tools/form_tools/form_meta/form_meta.py | .py | ddb8fafe3fbfee5a | 7.15 | 1 |
import cv2
from pydantic import BaseModel, validator
from typing import Dict, List, Optional, Any, Union
class DetectorConfig(BaseModel):
"""Config for opencv detector
Attributes:
name (str): Name of the detector,
either SIFT or ORB
args (Optional[List[Any]]):
Agrumen... | ministryofjustice/opg-data-lpa-instructions-preferences | lambdas/image_processor/form-tools/form_tools/form_operators/operator_configs.py | .py | 34085e50ab3be989 | 7.15 | 1 |
import os
import cv2
import boto3
import tempfile
import numpy as np
import awswrangler as wr
from PIL import Image
from glob import glob
from pathlib import Path
from pdf2image import convert_from_bytes
from typing import List, Tuple, Union, Optional, ByteString, Dict, Any
class ImageReader:
"""ImageReader util... | ministryofjustice/opg-data-lpa-instructions-preferences | lambdas/image_processor/form-tools/form_tools/utils/image_reader.py | .py | 0841fa567e281b0e | 7.15 | 1 |
import json
import os
import re
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch_all
import boto3
import botocore.exceptions
from app.utility.custom_logging import custom_logger, get_event_details_for_logs
logger = custom_logger("request_handler")
patch_all()
class ImageRequestHandl... | ministryofjustice/opg-data-lpa-instructions-preferences | lambdas/image_request_handler/app/handler.py | .py | a3c4a8956e0f17bb | 7.15 | 1 |
import json
import os
import logging
class JsonFormatter(logging.Formatter):
"""
Formatter that outputs JSON strings after parsing the LogRecord.
@param dict fmt_dict: Key: logging format attribute pairs. Defaults to {"message": "message"}.
@param str time_format: time.strftime() format string. Defau... | ministryofjustice/opg-data-lpa-instructions-preferences | lambdas/image_request_handler/app/utility/custom_logging.py | .py | fb4d736c778390d0 | 7.15 | 1 |
#!/usr/bin/env python3
import boto3
import requests
from requests_aws4auth import AWS4Auth
import argparse
from datetime import datetime, timedelta
import time
import json
import sys
def get_role_session(environment, role):
account = {"sirius-dev": "288342028542", "sirius-prod": "649098267436"}
client = boto... | ministryofjustice/opg-data-lpa-instructions-preferences | scripts/post-request.py | .py | 48a79b658e7140aa | 7.15 | 1 |
import logging
from enum import StrEnum
from pynamodb.attributes import (
JSONAttribute,
NumberAttribute,
UnicodeAttribute,
UTCDateTimeAttribute,
)
from pynamodb.exceptions import PutError
from pynamodb.models import Model
from dsc.exceptions import ItemSubmissionCreateError, ItemSubmissionExistsError... | MITLibraries/dspace-submission-composer | dsc/db/models.py | .py | 3a2764bbd37721ef | 7 | 0 |
from __future__ import annotations
import json
import logging
from collections import defaultdict
from dataclasses import dataclass, fields
from typing import TYPE_CHECKING, Any, Literal
from botocore.exceptions import ClientError
from pynamodb.exceptions import DoesNotExist
from dsc.config import Config
from dsc.db... | MITLibraries/dspace-submission-composer | dsc/item_submission.py | .py | 5e80e8afc0def3ad | 7 | 0 |
import logging
from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import UTC, datetime
from io import BytesIO, StringIO
import pandas as pd
import smart_open
from jinja2 import Environment, FileSystemLoader, Template, select_autoescape
from dsc.config import Config
from dsc.db.models ... | MITLibraries/dspace-submission-composer | dsc/reports/base.py | .py | 3374dc48bdf4a3ff | 7 | 0 |
from io import BytesIO, StringIO
import pandas as pd
from lxml import etree
from dsc.db.models import ItemSubmissionOperation, ItemSubmissionStatus
from dsc.reports.base import Attachment, FinalizeReport
class DigitizedThesesFinalizeReport(FinalizeReport):
attachments = (
*FinalizeReport.attachments,
... | MITLibraries/dspace-submission-composer | dsc/reports/digitized_theses.py | .py | 63f6125fdebda482 | 7 | 0 |
"""AWS CloudWatch metrics client for workflow submission tracking."""
from __future__ import annotations
import logging
from dataclasses import dataclass
import boto3
logger = logging.getLogger(__name__)
CLOUDWATCH_METRICS_LIMIT = 1000
UNIT_VALUES = frozenset(
[
"Bits",
"Bits/Second",
... | MITLibraries/dspace-submission-composer | dsc/utils/aws/metrics.py | .py | e9c8d1d6a1be24ff | 7 | 0 |
from __future__ import annotations
import logging
import subprocess
from typing import TYPE_CHECKING
from urllib.parse import urlparse
import boto3
if TYPE_CHECKING: # pragma: no cover
from collections.abc import Iterator
logger = logging.getLogger(__name__)
class S3Client:
"""A class to perform common S... | MITLibraries/dspace-submission-composer | dsc/utils/aws/s3.py | .py | 7cb66356415a5ed2 | 7 | 0 |
from __future__ import annotations
import logging
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from typing import TYPE_CHECKING
from boto3 import client
if TYPE_CHECKING: # pragma: no cover
from io import StringIO
fro... | MITLibraries/dspace-submission-composer | dsc/utils/aws/ses.py | .py | 503698a935e834c6 | 7 | 0 |
from __future__ import annotations
import json
import logging
from typing import TYPE_CHECKING, Any, Literal
from boto3 import client
if TYPE_CHECKING: # pragma: no cover
from collections.abc import Iterator, Mapping
from mypy_boto3_sqs.type_defs import (
EmptyResponseMetadataTypeDef,
Messa... | MITLibraries/dspace-submission-composer | dsc/utils/aws/sqs.py | .py | 82c0ec2930ab3df9 | 7 | 0 |
import logging
import pandas as pd
import smart_open
from dsc.db.models import ItemSubmissionStatus
from dsc.item_submission import ItemSubmission
from dsc.workflows.simple_csv import SimpleCSV
logger = logging.getLogger(__name__)
class ArchivesSpace(SimpleCSV):
"""Workflow for ArchivesSpace deposits.
The... | MITLibraries/dspace-submission-composer | dsc/workflows/archivesspace/workflow.py | .py | 77393ad6b8b74975 | 7 | 0 |
import inspect
from collections.abc import Iterable
from typing import Any, ClassVar
class OpenCourseWareTransformer:
"""Transformer for OpenCourseWare (OCW) source metadata."""
fields: Iterable[str] = [
# fields with derived values
"dc_title",
"dc_date_issued",
"dc_descriptio... | MITLibraries/dspace-submission-composer | dsc/workflows/opencourseware/transformer.py | .py | dd2728ea58a881b8 | 7 | 0 |
import json
import logging
import zipfile
from collections.abc import Iterator
from typing import Any
import smart_open
from dsc.db.models import ItemSubmissionStatus
from dsc.exceptions import ItemMetadataNotFoundError
from dsc.item_submission import ItemSubmission
from dsc.utils.aws.s3 import S3Client
from dsc.work... | MITLibraries/dspace-submission-composer | dsc/workflows/opencourseware/workflow.py | .py | f1f9ff72140937b2 | 7 | 0 |
from dsc.workflows.simple_csv import SimpleCSV
class SCCS(SimpleCSV):
"""Workflow for SCCS-requested deposits.
The deposits managed by this workflow are requested by the Scholarly
Communication and Collection Strategy (SCCS) department
and are for submission to DSpace@MIT.
"""
workflow_name:... | MITLibraries/dspace-submission-composer | dsc/workflows/sccs/workflow.py | .py | 1446639c63b0c874 | 7 | 0 |
import logging
from collections.abc import Iterator
import numpy as np
import pandas as pd
import smart_open
from dsc.db.models import ItemSubmissionStatus
from dsc.exceptions import ItemBitstreamsNotFoundError
from dsc.item_submission import ItemSubmission
from dsc.utils.aws import S3Client
from dsc.workflows.base i... | MITLibraries/dspace-submission-composer | dsc/workflows/simple_csv/workflow.py | .py | 5e25a128d30f260e | 7 | 0 |
# Combine the per-node evaluation results of the additional cohort into a single Excel file
#
# eval_left.py / eval_right.py write one file per node per subject group, with one row per modality
# combination and one column per training trial. This script concatenates those columns across nodes
# and adds the aggregatio... | soumbane/magmsforEZprediction | combine_add_cohort_results.py | .py | 8f458dcb4993c5a2 | 7.15 | 1 |
# Combine the per-node training-time results of the additional cohort into a single Excel file
#
# train_left.py / train_right.py write one results_val.xlsx and one results_train.xlsx per node,
# each holding the balanced accuracy, sensitivity and specificity of the 3 trials. The validation
# numbers are measured on th... | soumbane/magmsforEZprediction | combine_add_cohort_training_results.py | .py | b56e4df49c040162 | 7.15 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.