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 |
|---|---|---|---|---|---|---|
from typing import List
from bs4.element import Tag
from helpers.chapter import Chapter
from helpers.checkers.base import AbstractChapterChecker
class KunmangaChecker(AbstractChapterChecker):
"""Kunmanga checker"""
URL_SUBSTRING = "kunmanga"
def get_latest_chapter_list(self) -> List[Chapter]:
... | nonjosh/acgn-bot | helpers/checkers/kunmanga.py | .py | e2752ab4d3004804 | 7.42 | 6 |
from typing import List
from urllib.parse import urlparse, urlunparse
from bs4.element import Tag
from helpers.chapter import Chapter
from helpers.checkers.base import AbstractChapterChecker
class LaimanhuaChecker(AbstractChapterChecker):
"""Laimanhua checker"""
URL_SUBSTRING = "laimanhua"
def get_lat... | nonjosh/acgn-bot | helpers/checkers/laimanhua.py | .py | eb71c262db86d463 | 7.42 | 6 |
from typing import List
from urllib.parse import urlparse, urlunparse
from bs4.element import ResultSet, Tag
from helpers.chapter import Chapter
from helpers.checkers.base import AbstractChapterChecker
class LinovelibChecker(AbstractChapterChecker):
"""Linovelib checker"""
URL_SUBSTRING = "linovelib"
... | nonjosh/acgn-bot | helpers/checkers/linovelib.py | .py | c20dae6996a69373 | 7.42 | 6 |
"""Checker for Mangakatana manga pages."""
from typing import override
from urllib.parse import urlparse
from helpers.chapter import Chapter
from helpers.checkers.base import AbstractChapterChecker
class MangakatanaChecker(AbstractChapterChecker):
"""Mangakatana chapter list checker."""
URL_SUBSTRING: str ... | nonjosh/acgn-bot | helpers/checkers/mangakatana.py | .py | d6ac7ea6b205f939 | 7.42 | 6 |
"""Checker for Mangaraw manga pages.
Example manga URL:
https://mangaraw.co.uk/manga/2439
API used:
https://api.mangarw.com/api/v1/manga/2439/chapters
"""
from typing import List, Optional, Tuple
from urllib.parse import urlparse
from helpers.chapter import Chapter
from helpers.checkers.base import Abstract... | nonjosh/acgn-bot | helpers/checkers/mangaraw.py | .py | c8d6458e52118bad | 7.42 | 6 |
import threading
import time
from typing import List
from urllib.parse import urlparse, urlunparse
from bs4.element import Tag
from helpers.chapter import Chapter
from helpers.checkers.base import AbstractChapterChecker
from helpers.utils import get_logger
class ManhuaguiChecker(AbstractChapterChecker):
"""Manh... | nonjosh/acgn-bot | helpers/checkers/manhuagui.py | .py | 30c1e80f98ae5fc2 | 7.42 | 6 |
from typing import List
from urllib.parse import urlparse, urlunparse
from bs4.element import Tag
from helpers.chapter import Chapter
from helpers.checkers.base import AbstractChapterChecker
class Mn4uChecker(AbstractChapterChecker):
"""Mn4u checker"""
URL_SUBSTRING = "mn4u"
def __init__(self, check_u... | nonjosh/acgn-bot | helpers/checkers/mn4u.py | .py | 29bde412a813e44f | 7.42 | 6 |
from typing import List
from urllib.parse import urljoin
from bs4.element import Tag
from helpers.chapter import Chapter
from helpers.checkers.base import AbstractChapterChecker
class PiaotianChecker(AbstractChapterChecker):
"""Piaotian novel checker class"""
URL_SUBSTRING = "piaotia"
def get_latest_c... | nonjosh/acgn-bot | helpers/checkers/piaotian.py | .py | 43966a0e56330d9e | 7.42 | 6 |
from typing import List
from urllib.parse import urljoin, urlparse
from bs4 import BeautifulSoup
from helpers.chapter import Chapter
from helpers.checkers.base import AbstractChapterChecker
class PickmeupgachaChecker(AbstractChapterChecker):
"""Simple checker for pickmeupgacha site"""
URL_SUBSTRING = "pick... | nonjosh/acgn-bot | helpers/checkers/pickmeupgacha.py | .py | b00db13a38e77ba7 | 7.42 | 6 |
import json
from typing import List
from urllib.parse import urlparse, urlunparse
from helpers.chapter import Chapter
from helpers.checkers.base import AbstractChapterChecker
class QimanChecker(AbstractChapterChecker):
"""QimanChecker"""
URL_SUBSTRING = "qmanwu2"
def get_latest_chapter_list(self) -> Li... | nonjosh/acgn-bot | helpers/checkers/qiman.py | .py | 0644f0bad4900cce | 7.42 | 6 |
from typing import List
from bs4.element import Tag
from helpers.chapter import Chapter
from helpers.checkers.base import AbstractChapterChecker
class SixNineShuBaChecker(AbstractChapterChecker):
"""69shu checker class"""
URL_SUBSTRING = "69shu"
def get_latest_chapter_list(self) -> List[Chapter]:
... | nonjosh/acgn-bot | helpers/checkers/six_nine_shu_ba.py | .py | c81050c3c16ab804 | 7.42 | 6 |
from typing import List
from urllib.parse import urlparse, urlunparse
from bs4 import BeautifulSoup
from bs4.element import Tag
from helpers.chapter import Chapter
from helpers.checkers.base import AbstractChapterChecker
class SyosetuChecker(AbstractChapterChecker):
"""Syosetu checker class"""
URL_SUBSTRIN... | nonjosh/acgn-bot | helpers/checkers/syosetu.py | .py | ed6b3bc36bd2ba9a | 7.42 | 6 |
from typing import List
from bs4.element import Tag
from helpers.chapter import Chapter
from helpers.checkers.base import AbstractChapterChecker
class WeixinChecker(AbstractChapterChecker):
"""Weixin checker"""
URL_SUBSTRING = "weixin.qq.com"
def get_latest_chapter_list(self) -> List[Chapter]:
... | nonjosh/acgn-bot | helpers/checkers/weixin.py | .py | ac9f7712bb3cc743 | 7.42 | 6 |
from typing import List
from urllib.parse import urlparse, urlunparse
from bs4.element import Tag
from helpers.chapter import Chapter
from helpers.checkers.base import AbstractChapterChecker
class WxChecker(AbstractChapterChecker):
"""99wx checker class"""
URL_SUBSTRING = "99wx"
def get_latest_chapter... | nonjosh/acgn-bot | helpers/checkers/wx.py | .py | 87e18531ea0a8fb1 | 7.42 | 6 |
from typing import List
from urllib.parse import urljoin
from bs4.element import Tag
from helpers.chapter import Chapter
from helpers.checkers.base import AbstractChapterChecker
class XbiqugeChecker(AbstractChapterChecker):
"""Xbiquge checker"""
URL_SUBSTRING = "xbiquge"
def get_latest_chapter_list(se... | nonjosh/acgn-bot | helpers/checkers/xbiquge.py | .py | 721b29675669835e | 7.42 | 6 |
"""Config helper class"""
import os
from helpers.yml_parser import YmlParser
DEFAULT_LIST_YAML_PATH = "config/list.yaml"
class ConfigHelper:
"""Config helper class"""
def __init__(self):
# Check if CONFIG_YML_URL is set
if "CONFIG_YML_URL" in os.environ:
# Get config from url
... | nonjosh/acgn-bot | helpers/config.py | .py | ec8a0adebb87e51d | 7.42 | 6 |
"""Media Helper class"""
from typing import List, Literal
from helpers.checkers import get_checker_for_url
from helpers.checkers.base import AbstractChapterChecker
from helpers.utils import check_url_valid, get_logger, get_main_domain_name
MediaTypes = Literal["comic", "novel", "anime"]
SUPPORTED_MEDIA_TYPES: tuple[... | nonjosh/acgn-bot | helpers/media.py | .py | 092340f517117376 | 7.42 | 6 |
"""Telegram Helper"""
import os
import telegram
from dotenv import load_dotenv
from telegram import Bot, Update
from telegram.error import NetworkError, TimedOut
from telegram.ext import ApplicationBuilder, CallbackContext, CommandHandler
from helpers.message import MessageHelper
from helpers.utils import get_logger... | nonjosh/acgn-bot | helpers/tg.py | .py | 7d188f457bda1291 | 7.42 | 6 |
"""Utility functions"""
import logging
from collections import Counter
from datetime import datetime
from logging.handlers import TimedRotatingFileHandler
from typing import List
from urllib.parse import urlparse
import requests
from helpers.chapter import Chapter
# Create logging formatter
FORMATTER = logging.Form... | nonjosh/acgn-bot | helpers/utils.py | .py | d4bbd4f30ca0f4a1 | 7.42 | 6 |
"""YML Parser"""
import requests
import yaml
from helpers.media import MEDIA_URL_FIELDS
from helpers.utils import DEFAULT_HEADERS, DEFAULT_REQUEST_TIMEOUT, get_logger
logger = get_logger(__name__)
class YmlParser:
"""YmlParser"""
def __init__(
self,
yml_filepath: str = None,
yml_ur... | nonjosh/acgn-bot | helpers/yml_parser.py | .py | 7e5e41316fcf2202 | 7.42 | 6 |
"""Regression tests for checker and schedule error handling."""
import unittest
from unittest.mock import Mock, patch
import requests
from helpers.checkers.base import AbstractChapterChecker
from helpers.schedule import ScheduleHelper
class NoopChecker(AbstractChapterChecker):
"""Minimal checker for testing ba... | nonjosh/acgn-bot | tests/test_checker_error_handling.py | .py | 0334932727fab0ed | 7.92 | 6 |
"""Test webscrapping function of the checker classes,
will skip if the url is not available."""
import os
import unittest
from typing import List, Type
from unittest.mock import patch
from bs4 import BeautifulSoup
from helpers import checkers
from helpers.chapter import Chapter
from helpers.checkers import AbstractC... | nonjosh/acgn-bot | tests/test_checkers.py | .py | 6bc28695c6a2b82b | 7.92 | 6 |
"""Focused tests for the Mangakatana checker."""
import unittest
from unittest.mock import Mock, patch
from bs4 import BeautifulSoup
from helpers.chapter import Chapter
from helpers.checkers import get_checker_for_url
from helpers.checkers.mangakatana import MangakatanaChecker
class TestMangakatanaChecker(unittest... | nonjosh/acgn-bot | tests/test_mangakatana_checker.py | .py | 63e8f676b15ce741 | 7.92 | 6 |
"""Test basic flow of each job"""
import unittest
from helpers.chapter import Chapter
from helpers.media import MediaHelper
from helpers.utils import check_url_valid, get_chapter_list_diff
class TestMediaHelper(unittest.TestCase):
"""Test MediaHelper"""
def test_chapter_list_change(self) -> None:
"... | nonjosh/acgn-bot | tests/test_media_helper.py | .py | fd9e14aacc03e1d6 | 7.92 | 6 |
import hashlib
import hmac
from dataclasses import dataclass
from typing import Any
import requests
from .exceptions import ConfigException
@dataclass
class ApiClient:
"""
Cliente para interactuar con la API de Flow.
Attributes:
api_url (str): URL base de la API de Flow. Por defecto es "https:/... | mariofix/pyflowcl | pyflowcl/Clients.py | .py | 2a0386e1e5a6c218 | 7.48 | 8 |
from dataclasses import asdict
from typing import Any, cast
from pyflowcl.exceptions import GenericError
from .Clients import ApiClient
from .models import RefundRequest, RefundStatus
def create(apiclient: ApiClient, refund_data: dict[str, Any]) -> RefundStatus:
"""
Este servicio permite crear una orden de ... | mariofix/pyflowcl | pyflowcl/Refund.py | .py | 884a6dd98fb3734f | 7.48 | 8 |
import logging
import os
import streamlink
import shutil
import signal
import sys
from enum import Enum, auto
logger = logging.getLogger(__name__)
class AuthValidationStatus(Enum):
NOT_CONFIGURED = auto()
VALID_OR_NOT_REJECTED = auto()
INVALID = auto()
UNKNOWN = auto()
class StreamlinkManager:
... | liofal/streamlink | streamlink_manager.py | .py | 888f1f3e4472aa09 | 7.57 | 13 |
import unittest
from unittest.mock import MagicMock, patch
from streamlink_manager import AuthValidationStatus, StreamlinkManager
class TestStreamlinkManager(unittest.TestCase):
def setUp(self):
self.config = MagicMock()
self.config.oauth_token = "test_token"
self.config.quality = "best"
... | liofal/streamlink | test_streamlink_manager.py | .py | d5a90755b8c09119 | 7.07 | 13 |
# Add up numeric field values from a DAList object.
from docassemble.base.util import DAValidationError, word
__all__ = ["Addup"]
class Addup:
"""
Utility class for calculating sums of numeric fields across DAList objects.
This class provides functionality to sum specific numeric fields from all
ite... | SuffolkLITLab/docassemble-ALToolbox | docassemble/ALToolbox/Addup.py | .py | 68a7e4cec68cc001 | 7.65 | 19 |
__all__ = ["myTable", "myTextList", "safe_json2"]
# This function creates a Table list to be used in an addendum file. Currently it handles 'Thing' and 'Inidvidual' object type of DAList (special name attribute).
class myTable:
"""
Utility class for creating table representations from DAList objects for adden... | SuffolkLITLab/docassemble-ALToolbox | docassemble/ALToolbox/addenda.py | .py | 72090bbd03a4598d | 7.65 | 19 |
import holidays
import pandas as pd
import datetime
from datetime import date as dt
from docassemble.base.util import as_datetime, DADateTime
from typing import Union, Dict, Iterable, Mapping, Optional
"""
External docs:
1. https://github.com/dr-prodigy/python-holidays (holidays module v0.13, as of 2/2022)
2. h... | SuffolkLITLab/docassemble-ALToolbox | docassemble/ALToolbox/business_days.py | .py | 1cc796e3b247b7a8 | 7.65 | 19 |
"""Minimal docassemble runtime context for the python-only unit tests.
As of docassemble 1.10, per-request state lives in a contextvar exposed as
`docassemble.base.thread_context.this_thread`, and the defaults that back it
(language, locale, timezone, ...) come from pluggy hooks that only
`docassemble.webapp` register... | SuffolkLITLab/docassemble-ALToolbox | docassemble/ALToolbox/conftest.py | .py | baefcabe5ac27c29 | 8.15 | 19 |
# do not pre-load
import unittest
import locale
from decimal import Decimal
from .al_income import (
ALIncome,
ALIncomeList,
ALAsset,
ALAssetList,
ALVehicle,
ALVehicleList,
ALSimpleValue,
ALSimpleValueList,
ALItemizedJob,
ALItemizedJobList,
ALItemizedValueDict,
ALItemiz... | SuffolkLITLab/docassemble-ALToolbox | docassemble/ALToolbox/test_al_income.py | .py | d771e4d846a3c393 | 8.15 | 19 |
# do not pre-load
import unittest
from .business_days import (
is_business_day,
get_next_business_day,
get_date_after_n_business_days,
)
from docassemble.base.util import today, as_datetime
_thread_context = None
def setUpModule() -> None:
"""Initialize docassemble thread context for tests.
Out... | SuffolkLITLab/docassemble-ALToolbox | docassemble/ALToolbox/test_altoolbox.py | .py | 22fd48a9efa09ad2 | 8.15 | 19 |
# do not pre-load
import unittest
from unittest.mock import patch
from .misc import button_array, ButtonDict, true_values_with_other, fa_icon
import defusedxml.ElementTree as ET
class TestButtonArray(unittest.TestCase):
@patch("docassemble.ALToolbox.misc.user_has_privilege", return_value=False)
@patch("ALToo... | SuffolkLITLab/docassemble-ALToolbox | docassemble/ALToolbox/test_misc.py | .py | ae30d4957042239e | 8.15 | 19 |
# do not pre-load
import os
import re
import unittest
from unittest.mock import patch
from .translation_strings import (
ALTOOLBOX_JS_STRINGS,
_catalog_response_body,
_match_shape,
_normalize,
add_translations,
translate,
translation_catalog,
)
FAKE_WORDS = {
"es": {
"Copied!"... | SuffolkLITLab/docassemble-ALToolbox | docassemble/ALToolbox/test_translation_strings.py | .py | c30d089034e4dacb | 8.15 | 19 |
# pre-load
"""Serve docassemble's ``word()`` translations to JavaScript.
Docassemble can translate any string that reaches Python through ``word()``, but
JavaScript running in the browser has no way to reach that catalog. Custom
datatypes, validation messages and small widgets therefore end up hardcoded in
English.
... | SuffolkLITLab/docassemble-ALToolbox | docassemble/ALToolbox/translation_strings.py | .py | 77d95d727da74654 | 7.65 | 19 |
"""Competitive Benchmark for Coordinate Geometric Kernels.
This module compares the geometric calculation speeds (RMSD, center of geometry,
and all-to-all distance matrices) of MolSysMT public APIs, MolSysMT JIT kernels,
MDTraj, and MDAnalysis.
"""
from __future__ import annotations
import os
import sys
from pathlib... | uibcdf/molsysmt | benchmarks/competitors/test_geometry.py | .py | c56f42d02d910bae | 8.09 | 14 |
"""Competitive Benchmark for Trajectory Loading.
This module compares the trajectory loading performance of MolSysMT, MDTraj,
and MDAnalysis on the solvated chicken villin HP35 system (20 frames, 4369 atoms).
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
# Add repository root ... | uibcdf/molsysmt | benchmarks/competitors/test_loading.py | .py | b4e753b57a968219 | 8.09 | 14 |
"""Competitive Benchmark for Selection Language.
This module compares the atom selection speed and parsing overhead of MolSysMT,
MDTraj, and MDAnalysis on a realistic PDB structure (solvated chicken villin, 4369 atoms).
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
# Add repos... | uibcdf/molsysmt | benchmarks/competitors/test_selections.py | .py | 29a92e9e10b44de4 | 8.09 | 14 |
"""MolSysMT Benchmarking Harness.
This module provides the core orchestration engine for isolated repeated
measurements with structured JSON telemetry exports.
"""
from __future__ import annotations
import gc
import json
import os
import platform
import subprocess
import sys
from datetime import datetime, timezone
f... | uibcdf/molsysmt | benchmarks/harness.py | .py | ffae3a1a0b3cc4d7 | 7.59 | 14 |
"""Macro-benchmark for MolSysMT Mathematical Coordinate Kernels.
This script benchmarks RMSD, center of mass, and pairwise distances calculations on a realistic
38-frame, 304-atom Trp-Cage mini-protein (1l2y). It evaluates both the high-level public API wrappers
and the raw JIT-compiled library kernels under GC isolat... | uibcdf/molsysmt | benchmarks/macro/test_kernels.py | .py | 2407d5f7db02239f | 7.09 | 14 |
"""Macro-benchmark for MolSysMT Trajectory Reading & Out-of-Core Streaming.
This script profiles the performance and out-of-core capabilities of MolSysMT when loading
and processing structural trajectories. It benchmarks three methods on the solvated chicken villin
HP35 trajectory (20 frames, 4369 atoms):
1. Eager tra... | uibcdf/molsysmt | benchmarks/macro/test_trajectories.py | .py | 0ab01ced087fb78a | 8.09 | 14 |
"""Repository-wide pytest collection safeguards."""
import importlib
from pathlib import Path
_ROOT = Path(__file__).parent
def pytest_configure(config):
"""Pre-import first-party source packages collected for ``--doctest-modules``.
Every public function in packages such as ``molsysmt.basic`` lives in a mod... | uibcdf/molsysmt | conftest.py | .py | f676b2c7f755cad1 | 7.09 | 14 |
#!/usr/bin/env python
"""
audit_converter_routing.py
Finds converters that call another form's converter on their own `item`.
Every `molsysmt/form/<plugin>/to_<target>.py` receives an `item` of the plugin's own form.
When it needs an intermediate form it must call the sibling in its own directory -- the
converter tha... | uibcdf/molsysmt | devtools/scripts/audit_converter_routing.py | .py | 38800c4c3c1bd8a7 | 7.59 | 14 |
#!/usr/bin/env python
"""Lint the Rust kernels for rounding calls that lower to libm on the x86-64 baseline.
Why this exists
---------------
The x86-64 baseline has no floor/ceil/round instruction (`roundsd` is SSE4.1), so
`f64::floor()` and friends lower to a libm call. Three of them sat in the innermost loop
of `get... | uibcdf/molsysmt | devtools/scripts/check_rust_hot_paths.py | .py | 1fd0edb99417e217 | 7.59 | 14 |
#!/usr/bin/env python3
"""Front matter of the developer-guide work queues.
Shared by `validate_devguide.py`, `devguide_index.py` and `devguide_issue.py`, so the
schema in `devguide/reporting_protocol.md` is described in exactly one place.
The parser deliberately accepts a restricted subset of YAML -- `key:`, `key: sc... | uibcdf/molsysmt | devtools/scripts/devguide_reports.py | .py | c4b423d018c6ca18 | 7.59 | 14 |
#!/usr/bin/env python
"""
generate_converter_arguments.py
Writes the table `convert` is held to: the extra keywords each target form accepts.
`msm.convert(molsys, to_form=...)` forwards anything it does not recognise to the
converter it resolves, so the admissible set is whatever that converter accepts. There are
561... | uibcdf/molsysmt | devtools/scripts/generate_converter_arguments.py | .py | b6c1328e86100851 | 7.59 | 14 |
#!/usr/bin/env python
"""Aggregate the fast release-readiness gates into a single verdict.
This runs every cheap, deterministic gate (the repository validators plus a public-API
smoke) and prints one PASS/FAIL summary. It is the pre-flight a maintainer runs locally
before triggering the heavy gate (`ci-full.yaml`, the... | uibcdf/molsysmt | devtools/scripts/release_gate.py | .py | 1a1820017f3d82db | 7.59 | 14 |
#!/usr/bin/env python
"""
validate_form_adapters.py
Scans all subfolders in molsysmt/form/ and dynamically audits each adapter
against the structural contract defined in molsysmt/form/AGENTS.md.
"""
import os
import sys
import importlib
import inspect
import ast
import json
# Add repository root to python path to imp... | uibcdf/molsysmt | devtools/scripts/validate_form_adapters.py | .py | 99a0f4d452b7c2c8 | 7.59 | 14 |
#!/usr/bin/env python
"""Validate public-function support tiers.
Support tier is derived from the API-stability registry, not from a second registry
(see devguide/archive/resolved_proposals/function_support_tier_classification.md):
stable -> Tier 1 (contractual)
experimental -> Tier 3 (experim... | uibcdf/molsysmt | devtools/scripts/validate_function_tiers.py | .py | 6e7c3634db27153f | 7.59 | 14 |
#!/usr/bin/env python3
"""Public API Signature Stability Guard.
Compares AST signatures and defaults of public callables in modified files against
a base Git reference (default: HEAD~1 or origin/main) to prevent silent signature
mutilation, dropped parameters, inserted parameters, reordered arguments, or unintended de... | uibcdf/molsysmt | devtools/scripts/validate_public_api_stability.py | .py | 33bb2c32a291ea14 | 7.59 | 14 |
class Event: # pylint: disable=too-few-public-methods
TIMER_EXPIRED = 1
MESSAGE_RECEIVED = 2
SHUTDOWN = 3
class EventTimerExpired(Event): # pylint: disable=too-few-public-methods
"""Event used to indicate timer has expired"""
def __init__(self):
# will work but please do this properly
... | faucetsdn/beka | beka/event.py | .py | 112de34a9be76f6b | 7.54 | 11 |
class Timer:
def __init__(self, count):
self.count = count
self.tick = None
def running(self):
"""Return true if timer is set and running"""
return bool(self.tick)
def expired(self, tick):
"""Return true if time has elapsed"""
return self.running() and tick ... | faucetsdn/beka | beka/timer.py | .py | 87e932e705731f85 | 7.54 | 11 |
#!/usr/bin/env python3
"""
Top-level build pipeline for all deployable units
Builds shared libraries first, then dependent services
"""
import os
import subprocess
import sys
import shutil
from pathlib import Path
from typing import List, Dict, Optional
class BuildPipeline:
"""Build pipeline for all deployable u... | wilsonify/base-python-data-science | build.py | .py | 34edb4c3d73dbce3 | 7.48 | 8 |
#!/usr/bin/env python3
"""
Test script to verify that all AMQP strategies are working correctly
"""
import json
# Mock the AMQP dependencies for testing
class MockChannel:
def basic_publish(self, exchange, routing_key, properties, body):
print(f"Published to {exchange}: {body}")
class MockMethod:
pas... | wilsonify/base-python-data-science | src/data-scratch-amqp/test_strategies.py | .py | 4d6045c100e08eb0 | 7.98 | 8 |
"""
Test to ensure the circular import issue is resolved
"""
import unittest
class TestCircularImportFix(unittest.TestCase):
"""Test that the circular import issue is completely resolved"""
def test_import_routing_key_from_main_module(self):
"""Test the original failing import"""
# This w... | wilsonify/base-python-data-science | src/data-scratch-amqp/tests/test_circular_import_fix.py | .py | c40ffc2d91addae4 | 7.98 | 8 |
"""
Comprehensive tests for the dynamic strategy system
"""
import os
import unittest
from unittest.mock import Mock, patch
import inspect
# Import from the built package (no sys.path manipulation)
from data_scratch_amqp.strategies_library.dynamic_strategy import (
create_dynamic_strategy,
get_all_library_fu... | wilsonify/base-python-data-science | src/data-scratch-amqp/tests/test_dynamic_strategy.py | .py | f1e9008201546113 | 7.98 | 8 |
"""
Test for the basic echo strategy
"""
import unittest
from unittest.mock import Mock
class TestEchoStrategy(unittest.TestCase):
"""Test the echo strategy functionality"""
def setUp(self):
"""Set up test fixtures"""
self.mock_channel = Mock()
self.mock_method = Mock()
se... | wilsonify/base-python-data-science | src/data-scratch-amqp/tests/test_echo_strategy.py | .py | 3a3c1c2dd21bf100 | 7.98 | 8 |
# celltype.py
#
# Cell-type specific computations, e.g. classification by spike width
import numpy as np
from sklearn.mixture import GaussianMixture
from .base import find_outliers, get_pca_dimensions, interpolate_extremum_poly2
'''
Cell type classification analysis
'''
def classify_cells_spike_width(waveform_data,... | aolabNeuro/analyze | aopy/analysis/celltype.py | .py | aba290d7e4b17f02 | 7.45 | 7 |
# controllers.py
#
# Code relating to spectral analysis of feedforward & feedback controllers, based on the paper:
#
# Yamagami M, Peterson LN, Howell D, Roth E, Burden SA. Effect of Handedness on Learned Controllers
# and Sensorimotor Noise During Trajectory-Tracking. IEEE Trans Cybern. 2023 Apr;53(4):2039-2050.
# ... | aolabNeuro/analyze | aopy/analysis/controllers.py | .py | 4a60227e0ba5e6f9 | 7.45 | 7 |
# tuning.py
#
# Code related to tuning analysis, e.g. modulation depth, specificity, curve fitting, etc.
import warnings
import numpy as np
from scipy.optimize import curve_fit
from scipy.stats import f_oneway
'''
Curve fitting
'''
# These functions are for curve fitting and getting modulation depth and preferred di... | aolabNeuro/analyze | aopy/analysis/tuning.py | .py | 4ac22a49bfa008f0 | 7.45 | 7 |
import os
import glob
import numpy as np
from open_ephys.analysis import Session
import xml.etree.ElementTree as ETree
import h5py
def load_neuropixel_configuration(data_dir, data_folder, ex_idx=0, port_number=1):
'''
get neuropixel probe information from xml condiguration files made by OpenEphys
... | aolabNeuro/analyze | aopy/data/neuropixel.py | .py | 3f7e5331d7d0a059 | 7.45 | 7 |
import csv
import os
import warnings
from pandas import read_csv
def load_optitrack_metadata(data_dir, filename, metadata_row=0):
'''
This function loads optitrack metadata from .csv file that has 1 rigid body
exported with the following settings:
| **Markers:** Off
| **Unlabeled markers:*... | aolabNeuro/analyze | aopy/data/optitrack.py | .py | edb1ea117eda9d3e | 7.45 | 7 |
import os
import warnings
import pickle as pkl
import re
import json
import numpy as np
from pandas import DataFrame
import xarray as xr
from ..preproc.quality import high_freq_data_detection, saturated_data_detection
def parse_file_info(file_path):
"""parse_file_info
Parses file strings for goose_wireless ... | aolabNeuro/analyze | aopy/data/peslab.py | .py | 75bfd151cbdf4283 | 7.45 | 7 |
# eye.py
#
# Post-processing eye movement data
import numpy as np
def get_saccade_pos(eye_pos, onset_times, duration, samplerate):
'''
Returns the coordinates of the start and end of each given saccade
Args:
eye_pos (nt,nch): eye position data
onset_times (nsaccade): saccade onset tim... | aolabNeuro/analyze | aopy/postproc/eye.py | .py | 9c52ab216d0816ef | 7.45 | 7 |
import os
import numpy as np
from .. import data as aodata
def calc_presence_ratio(data, min_trial_prop=0.9, return_details=False):
'''
Find which units are active on a high proportion of trials.
Args:
data (ntime, nunit, ntrials): trial aligned binned spikes
min_trial_prop (float): p... | aolabNeuro/analyze | aopy/postproc/neuropixel.py | .py | cf891d275dc6aba7 | 7.45 | 7 |
# laser.py
#
# preprocessing laser data
import warnings
import sys
if sys.version_info >= (3,9):
from importlib.resources import files, as_file
else:
from importlib_resources import files, as_file
import numpy as np
import matplotlib.pyplot as plt
from .. import data as aodata
from .. import analysis
from ..... | aolabNeuro/analyze | aopy/preproc/laser.py | .py | c6045baf49576887 | 7.45 | 7 |
# oculomatic.py
#
# preprocessing eye data from oculomatic
import os
import numpy as np
from ..data.bmi3d import load_ecube_data_chunked
from .. import precondition
from .. import data as aodata
from .. import utils
def parse_oculomatic(data_dir, files, samplerate=1000, max_memory_gb=1.0, debug=True, **filter_kwarg... | aolabNeuro/analyze | aopy/preproc/oculomatic.py | .py | e2e475f73f4912be | 7.45 | 7 |
# torch.py
# code using the pytorch library which isn't installed by default. to install use `pip install torch`
import torch
# - - -- --- ----- -------- ---PYTORCH--- -------- ----- --- -- - -
# - - -- --- ----- -------- ---DATASETS-- -------- ----- --- -- - -
class TensorDataset(torch.utils.data.Dataset):
r"""... | aolabNeuro/analyze | aopy/torch.py | .py | e896b65f17cef71e | 7.45 | 7 |
# memory.py
#
# Memory management
import platform
def get_memory_available_gb():
'''
Get the available system memory in gigabytes. Only works on linux platforms.
Note:
The results of this function are equivalent to the terminal commands:
* "grep MemAvailable /proc/meminfo" -> available m... | aolabNeuro/analyze | aopy/utils/memory.py | .py | 348c9d914d96db05 | 7.45 | 7 |
# bmi3d.py
#
# visuzalition specific to BMI3D
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from . import base
from .. import data as aodata
def plot_decoder_weight_matrix(decoder, ax=None):
"""
Plot the decoder weight matrix. Compatible with Decoder objects with
KFDecoder an... | aolabNeuro/analyze | aopy/visualization/bmi3d.py | .py | ea2de19fb90f30bd | 7.45 | 7 |
#!/usr/bin/env python
# -*- coding: latin-1 -*-
#
# Copyright 2020 Blaise Frederick
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.... | bbfrederick/picachooser | picachooser/scripts/grader.py | .py | f9bfe35ea554f418 | 7.45 | 7 |
#!/usr/bin/env python
# -*- coding: latin-1 -*-
#
# Copyright 2020 Blaise Frederick
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.... | bbfrederick/picachooser | picachooser/scripts/melodicomp.py | .py | 3c0338d18388e807 | 7.45 | 7 |
#!/usr/bin/env python
# -*- coding: latin-1 -*-
#
# Copyright 2020 Blaise Frederick
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.... | bbfrederick/picachooser | picachooser/scripts/rtgrader.py | .py | 8a255a7d1d356e08 | 7.45 | 7 |
"""
Weather data client for ISO-DART v2.0
Integrates Meteostat for weather data and NSRDB for solar data.
"""
from typing import Optional, Dict
from datetime import datetime, timedelta, date
from pathlib import Path
import logging
import webbrowser
import configparser
import pandas as pd
from meteostat import Point, ... | llnl/ISO-DART | lib/weather/client.py | .py | e2f56aac6317aca8 | 7.65 | 19 |
"""Generate plots demonstrating piecewise-constant nature of classification metrics.
This script creates visualizations that illustrate why continuous optimizers
can miss the global optimum for metrics like F1 score, and demonstrates the
effectiveness of the fallback mechanism.
"""
import sys
from pathlib import Path... | finite-sample/optimal-classification-cutoffs | docs/generate_plots.py | .py | 30ea93ab1d62bcc5 | 7.54 | 11 |
"""Bayes-optimal decision making.
Clean interface for cost-based optimization without the complexity
of the original BayesOptimal class hierarchy.
"""
import numpy as np
from numpy.typing import NDArray
from ..bayes_core import BayesOptimal, UtilitySpec
from ..core import OptimizationResult
def threshold(
cost... | finite-sample/optimal-classification-cutoffs | optimal_cutoffs/bayes/__init__.py | .py | 842fd118dde762db | 7.54 | 11 |
"""Binary classification threshold optimization.
This module implements threshold optimization for binary classification problems
where we have a single decision threshold τ and predict positive if p ≥ τ.
Key algorithms:
- optimize_f1_binary(): Sort-and-scan O(n log n) for F-measures
- optimize_utility_binary(): Clos... | finite-sample/optimal-classification-cutoffs | optimal_cutoffs/binary.py | .py | 652beb78f65a7ad4 | 7.54 | 11 |
"""Core types and result objects for threshold optimization.
Clean design focused on explainable auto-selection and consistent interfaces.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import TYPE_CHECKING, Any
import numpy as np
if TYPE_CHECKING:... | finite-sample/optimal-classification-cutoffs | optimal_cutoffs/core.py | .py | 47cb13934a7a065c | 7.54 | 11 |
"""Cross-validation for threshold optimization.
Clean interface for validating threshold optimization methods.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import numpy as np
from ..api import optimize_thresholds
from ..core import OptimizationResult
if TYPE_CHECKING:
from numpy.typ... | finite-sample/optimal-classification-cutoffs | optimal_cutoffs/cv/__init__.py | .py | 07fe29075e102a94 | 7.54 | 11 |
"""Clean metrics API.
Provides access to metric registry and built-in metrics without polluting
the root namespace.
"""
# Import from the original metrics module to avoid circular imports
import importlib
# Dynamic import to avoid circular dependency
_metrics_module = importlib.import_module("optimal_cutoffs.metrics... | finite-sample/optimal-classification-cutoffs | optimal_cutoffs/metrics/__init__.py | .py | a864d678ce9210cd | 7.54 | 11 |
"""Multi-class classification threshold optimization.
This module implements threshold optimization for multi-class classification
where we have K mutually exclusive classes and must predict exactly one class.
Key approaches:
1. OvR Independent: Treat each class as independent binary (multi-label style)
2. Margin Rul... | finite-sample/optimal-classification-cutoffs | optimal_cutoffs/multiclass.py | .py | d29f67fc515d35eb | 7.54 | 11 |
"""Multi-label classification threshold optimization.
This module implements threshold optimization for multi-label classification
where we have K independent binary labels, each with its own threshold τ_j.
Key insight: Multi-label problems are K independent binary problems!
- Macro averaging: Optimize each label ind... | finite-sample/optimal-classification-cutoffs | optimal_cutoffs/multilabel.py | .py | 5e9e3986daaa690a | 7.54 | 11 |
"""Centralized Numba import utilities for JIT compilation support.
This module provides a single location for Numba imports and fallback logic,
ensuring consistent behavior across all modules that use JIT compilation.
"""
from typing import Any
# The pure-Python fallbacks are declared first and numba overwrites the... | finite-sample/optimal-classification-cutoffs | optimal_cutoffs/numba_utils.py | .py | c46774cd242dfe26 | 7.54 | 11 |
"""Optimized O(n log n) sort-and-scan kernel for piecewise-constant metrics.
This module provides an exact optimizer for binary classification metrics that are
piecewise-constant with respect to the decision threshold. The algorithm sorts
predictions once and scans all n cuts in a single pass, achieving true O(n log n... | finite-sample/optimal-classification-cutoffs | optimal_cutoffs/piecewise.py | .py | f842685d707517c2 | 7.54 | 11 |
"""Tests for the code coherence improvements implemented in v0.4.0."""
import numpy as np
import pytest
from optimal_cutoffs import optimize_thresholds
from optimal_cutoffs.bayes import threshold as bayes_threshold
from optimal_cutoffs.cv import cross_validate, nested_cross_validate
class TestModeParameter:
"""... | finite-sample/optimal-classification-cutoffs | tests/algorithms/test_api_mode_parameters.py | .py | 86ed3894d4f4e398 | 7.04 | 11 |
"""Tests for multiclass Bayes functionality."""
import numpy as np
import pytest
from optimal_cutoffs import optimize_decisions, optimize_thresholds
from optimal_cutoffs.bayes import threshold, thresholds_from_costs
class TestBayesDecisionFromUtilityMatrix:
"""Test multiclass Bayes result_decisions from utility... | finite-sample/optimal-classification-cutoffs | tests/algorithms/test_bayes_multiclass.py | .py | 74b0a96951396ccd | 8.04 | 11 |
"""Tests for coordinate-ascent multiclass threshold optimization."""
import numpy as np
import pytest
from optimal_cutoffs import optimize_thresholds
from optimal_cutoffs.metrics_core import (
compute_multiclass_metrics_from_labels,
)
from optimal_cutoffs.numba_utils import NUMBA_AVAILABLE
from optimal_cutoffs.op... | finite-sample/optimal-classification-cutoffs | tests/algorithms/test_coordinate_ascent_integration.py | .py | 7b8696fa6a8baab2 | 8.04 | 11 |
"""Unit tests for Dinkelbach expected F-beta optimization method.
This module tests the Dinkelbach algorithm for optimizing expected F-beta scores
under perfect calibration assumptions. The method depends only on predicted
probabilities, not on realized labels.
"""
import warnings
import numpy as np
from optimal_cu... | finite-sample/optimal-classification-cutoffs | tests/algorithms/test_dinkelbach_core.py | .py | 1317cb6ec7aea675 | 8.04 | 11 |
"""Test Dinkelbach method mathematical properties for expected F-beta optimization.
The Dinkelbach method optimizes the EXPECTED F-beta score under the assumption
of perfect calibration, meaning it depends only on predicted probabilities (p),
not on realized labels (y). This module tests these fundamental properties:
... | finite-sample/optimal-classification-cutoffs | tests/algorithms/test_dinkelbach_mathematical_properties.py | .py | a0085fc59dca647f | 7.04 | 11 |
"""Tests for cost/benefit-aware threshold optimization."""
import numpy as np
import pytest
from optimal_cutoffs import optimize_thresholds
from optimal_cutoffs.bayes import threshold as bayes_optimal_threshold
from optimal_cutoffs.metrics_core import (
confusion_matrix_at_threshold,
make_cost_metric,
mak... | finite-sample/optimal-classification-cutoffs | tests/algorithms/test_utility_optimization.py | .py | 1bf675894adbe3d7 | 8.04 | 11 |
"""Pytest configuration and shared fixtures for optimal_cutoffs tests.
This module provides pytest configuration, shared fixtures, and test utilities
that are available across all test modules.
"""
import warnings
import numpy as np
import pytest
def pytest_configure(config):
"""Configure pytest settings and c... | finite-sample/optimal-classification-cutoffs | tests/conftest.py | .py | b5c79844b228f2a6 | 8.04 | 11 |
"""Comprehensive tests for Bayes module edge cases and mathematical correctness."""
import numpy as np
import pytest
from optimal_cutoffs.bayes import (
BayesOptimal,
UtilitySpec,
threshold,
thresholds_from_costs,
)
class TestBinaryMathematicalCorrectness:
"""Test binary decision math for all D ... | finite-sample/optimal-classification-cutoffs | tests/edge_cases/test_bayes_edge_cases.py | .py | 3439e9ebd6a8822b | 8.04 | 11 |
"""Test weight invariance properties and catch integer cast bugs.
This module tests the fundamental properties that weighted metrics must satisfy:
1. Non-integer weights behave like proportional sample duplication
2. Scale invariance: multiplying all weights by a constant doesn't change optimum
3. Fractional weights a... | finite-sample/optimal-classification-cutoffs | tests/edge_cases/test_binary_weights.py | .py | d796a4d514c4482b | 8.04 | 11 |
"""Edge case tests for boundary conditions and extreme scenarios.
This module tests boundary conditions, extreme data distributions, and
numerical precision limits that could cause optimization algorithms to fail.
"""
import numpy as np
import pytest
from optimal_cutoffs import optimize_thresholds
from optimal_cutof... | finite-sample/optimal-classification-cutoffs | tests/edge_cases/test_boundary_conditions.py | .py | 881f9c31d5e0ac11 | 7.04 | 11 |
"""Tests for fallback robustness in optimization algorithms.
This module tests that optimization methods properly fall back to alternative
approaches when primary methods fail or encounter edge cases.
"""
import warnings
import numpy as np
import pytest
from optimal_cutoffs import optimize_thresholds
from optimal_c... | finite-sample/optimal-classification-cutoffs | tests/edge_cases/test_fallback_robustness.py | .py | b9e34114cfc0bdf7 | 7.04 | 11 |
"""Regression tests for the minimize_scalar fallback mechanism.
This tests the specific fix where minimize_scalar can return suboptimal thresholds
for piecewise-constant metrics, and the fallback mechanism ensures we get the
best threshold from the discrete candidate set.
"""
import numpy as np
from scipy import opti... | finite-sample/optimal-classification-cutoffs | tests/edge_cases/test_regression_minimize_fallback.py | .py | 41c97a54ae425145 | 7.04 | 11 |
"""Tests for tied probability scenarios and edge cases.
This module tests the library's handling of tied probability values, which present
unique challenges for threshold optimization algorithms.
"""
import numpy as np
import pytest
from optimal_cutoffs import optimize_thresholds
from optimal_cutoffs.metrics_core im... | finite-sample/optimal-classification-cutoffs | tests/edge_cases/test_tied_probabilities.py | .py | 1cfbf8d45f8f9f9a | 8.04 | 11 |
"""Tests for sample weight functionality."""
import numpy as np
import pytest
from optimal_cutoffs import optimize_thresholds
from optimal_cutoffs.cv import cross_validate, nested_cross_validate
from optimal_cutoffs.metrics_core import (
confusion_matrix_at_threshold,
needs_probability_scores,
register_me... | finite-sample/optimal-classification-cutoffs | tests/edge_cases/test_weight_edge_cases.py | .py | f868e811a291711a | 8.04 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.