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 |
|---|---|---|---|---|---|---|
#!/usr/bin/env python
# coding: utf-8
'''
A module for working on a calendar within a specific year
'''
# import sys
# sys.path.append(r"C:\Users\Alexey\Dropbox\Мои\RAnDan\myModules")
# sys & subprocess -- эти пакеты должны быть предустановлены. Если с ними какая-то проблема, то из этого скрипта решить их сложно
impo... | RandanCSS/randan | randan/tools/calendarWithinYear.py | .py | eb8eae0a2bd18546 | 7.39 | 5 |
#!/usr/bin/env python
# coding: utf-8
'''
A module for saving a dataframe to a file of one of the formats: CSV, Excel and JSON. It facilitates working with data from social media
'''
# sys & subprocess -- эти пакеты должны быть предустановлены. Если с ними какая-то проблема, то из этого скрипта решить их сложно
impor... | RandanCSS/randan | randan/tools/df2file.py | .py | e0c4b0dc799db953 | 7.39 | 5 |
#!/usr/bin/env python
# coding: utf-8
'''
A module for preprocessing variables of nominal, ordinal, interval, and higher-level measurement
Авторский модуль для предобработки переменных номинального, порядкового, интервального и более высокого типа шкалы
'''
# sys & subprocess -- эти пакеты должны быть предустановлены... | RandanCSS/randan | randan/tools/varPreprocessor.py | .py | 2387fd5ac23c785f | 7.39 | 5 |
#!/usr/bin/env python
# coding: utf-8
'''
A module for creating a matrix `documents-tokens` from a corpus of documents using the methods of the CountVectorizer and TfidfVectorizer classes
'''
# sys & subprocess -- эти пакеты должны быть предустановлены. Если с ними какая-то проблема, то из этого скрипта решить их сло... | RandanCSS/randan | randan/tools/vectorizer.py | .py | df812fa91c58b4b7 | 7.39 | 5 |
# Модуль для для выяснения, какие инструменты (акции, облигации и т.д.) есть в портфеле, на основе брокерских отчётов
# 0. Активировать требуемые для работы скрипта модули и пакеты
# sys & subprocess -- эти пакеты должны быть предустанавлены. Если с ними какая-то проблема, то из этого скрипта решить их сложно
import ... | RandanCSS/randan | randan/trading/getAssets.py | .py | 8f058c74db0914b4 | 7.39 | 5 |
# Модуль для выгрузки характеристик торгуемых на МосБирже облигаций
# 0. Активировать требуемые для работы скрипта модули и пакеты
# sys & subprocess -- эти пакеты должны быть предустанавлены. Если с ними какая-то проблема, то из этого скрипта решить их сложно
import sys
from subprocess import check_call
# --- остал... | RandanCSS/randan | randan/trading/getMoExData.py | .py | 886290ae2e4d9817 | 7.39 | 5 |
def genome_from_a_file(file_name: str) -> None:
"""Example usage of reference genome from file name."""
# pylint: disable=import-outside-toplevel
from gain.genomic_resources.reference_genome import (
build_reference_genome_from_file,
)
file_genome = build_reference_genome_from_file(file_na... | iossifovlab/gpf | core/demo_scripts/working_reference_genome.py | .py | 15513a27ce7ac7e8 | 7.35 | 4 |
from __future__ import annotations
import json
import logging
import os
from typing import Any, cast
from gpf.common_reports.denovo_report import DenovoReport
from gpf.common_reports.family_report import FamiliesReport
from gpf.common_reports.people_counter import PeopleReport
logger = logging.getLogger(__name__)
... | iossifovlab/gpf | core/gpf/common_reports/common_report.py | .py | e171639101505a80 | 7.35 | 4 |
"""Provides family report class."""
from __future__ import annotations
from collections.abc import Iterable
from typing import Any
from gpf.common_reports.family_counter import FamiliesGroupCounters
from gpf.pedigrees.families_data import FamiliesData
from gpf.person_sets import PersonSetCollection
class FamiliesRe... | iossifovlab/gpf | core/gpf/common_reports/family_report.py | .py | ef2dc1e72f6d86f4 | 7.35 | 4 |
from __future__ import annotations
import glob
import logging
import os
from collections.abc import Callable
from copy import deepcopy
from typing import Any, ClassVar, cast
import fsspec
import toml
import yaml
from box import Box
from cerberus import Validator
from gain.utils.dict_utils import recursive_dict_update... | iossifovlab/gpf | core/gpf/configuration/gpf_config_parser.py | .py | 51ee66f9b4901033 | 7.35 | 4 |
from __future__ import annotations
import pathlib
from typing import Annotated, Any, Literal
from pydantic import (
AnyUrl,
BaseModel,
ByteSize,
ConfigDict,
HttpUrl,
UrlConstraints,
)
from pydantic.functional_validators import AfterValidator
def _validate_abs_path(path: pathlib.Path) -> path... | iossifovlab/gpf | core/gpf/duckdb_storage/duckdb_storage_config.py | .py | 073e1433fa9b12f8 | 7.35 | 4 |
from __future__ import annotations
import abc
import logging
from collections.abc import Iterable
from typing import Any, cast
from gain.genomic_resources.repository import GenomicResource
from gain.genomic_resources.resource_implementation import (
ResourceConfigValidationMixin,
get_base_resource_schema,
)
... | iossifovlab/gpf | core/gpf/enrichment_tool/base_enrichment_background.py | .py | f4456f9d72e119b8 | 7.35 | 4 |
from __future__ import annotations
import logging
from collections.abc import Iterable
from typing import Any, cast
import pandas as pd
from gain.genomic_resources.repository import GenomicResource
from gain.genomic_resources.resource_implementation import (
get_base_resource_schema,
)
from scipy import stats
fr... | iossifovlab/gpf | core/gpf/enrichment_tool/samocha_background.py | .py | 2d7f685fc8f4cb4e | 7.35 | 4 |
"""``click`` options regarding targets."""
from collections.abc import Callable
from enum import Enum, unique
from pathlib import Path
from typing import Any
import click
from beartype import beartype
target_id_option: Callable[..., Any] = click.option(
"--target-id",
type=str,
help="The ID of a target i... | VWS-Python/vws-cli | src/vws_cli/options/targets.py | .py | 568f2bfefe76657d | 7.35 | 4 |
"""``click`` options regarding timeouts."""
from collections.abc import Callable
from typing import Any
import click
from beartype import beartype
@beartype
def connection_timeout_seconds_option(
command: Callable[..., Any],
) -> Callable[..., Any]:
"""An option decorator for the connection timeout."""
... | VWS-Python/vws-cli | src/vws_cli/options/timeout.py | .py | fb2d4e0519dd4d21 | 7.35 | 4 |
"""``click`` options for VWS API options."""
from collections.abc import Callable
from typing import Any
import click
from beartype import beartype
@beartype
def database_id_option(
command: Callable[..., Any],
) -> Callable[..., Any]:
"""An option decorator for the Vuforia database ID."""
return click.... | VWS-Python/vws-cli | src/vws_cli/options/vws.py | .py | 367d7d75f866bb54 | 7.35 | 4 |
"""A CLI for the Vuforia Cloud Recognition Service API."""
import contextlib
import dataclasses
import io
import sys
from collections.abc import Generator
from pathlib import Path
import click
import yaml
from beartype import beartype
from vws import CloudRecoService
from vws.exceptions.base_exceptions import CloudRe... | VWS-Python/vws-cli | src/vws_cli/query.py | .py | 5b2e35c74689e756 | 7.35 | 4 |
"""``pytest`` fixtures."""
from collections.abc import Iterator
import pytest
from mock_vws import MockVWS
from mock_vws.database import CloudDatabase, VuMarkDatabase
from mock_vws.target import VuMarkTarget
from vws import VWS, CloudRecoService
@pytest.fixture(name="mock_database")
def fixture_mock_database() -> I... | VWS-Python/vws-cli | tests/conftest.py | .py | 285b5a2f0eec4577 | 7.85 | 4 |
"""Tests for shared error handling through public CLI commands."""
import io
from pathlib import Path
import pytest
from click.testing import CliRunner
from mock_vws import MockVWS, VuMarkGenerationFailure
from mock_vws.database import CloudDatabase
from vws import VWS
from vws_cli import vws_group
from vws_cli.vuma... | VWS-Python/vws-cli | tests/test_error_handling.py | .py | 9733bc9eb9631998 | 7.85 | 4 |
import logging
import emoji_data_python
from django import template
from response.slack.cache import get_user_profile
from response.slack.reference_utils import slack_to_human_readable
register = template.Library()
logger = logging.getLogger(__name__)
@register.filter
def unslackify(value):
"""Takes a string ... | ministryofjustice/opg-incident-response | opgincidentresponse/templatetags/unslackify.py | .py | 1673b6f0a54e1ed5 | 7.35 | 4 |
"""Functions to create datasets."""
import datetime
import numpy as np
import pandas as pd
import requests
from covid.utils import fill_dates
IN_STATE_POSTAL = "data/state-postal.csv"
def get_data(n=7):
"""Get covid data for countries, states, and counties"""
state_postal = pd.read_csv(IN_STATE_POSTAL)
... | rwright88/covid | covid/data.py | .py | 8a3505adbbb21809 | 7 | 0 |
# Utilities
from itertools import product
import numpy as np
import pandas as pd
def ffill(x):
"""Fill missing values with last non-missing value, 1-d"""
mask = np.isnan(x)
ind = np.where(~mask, np.arange(len(mask)), 0)
np.maximum.accumulate(ind, out=ind)
out = x[ind]
return out
def fill_d... | rwright88/covid | covid/utils.py | .py | ca0e01393ca6e17c | 7 | 0 |
"""Constants used to make the VWS mock."""
from enum import Enum, unique
from beartype import beartype
VUMARK_PNG = (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00"
b"\x01\x08\x04\x00\x00\x00\xb5\x1c\x0c\x02\x00\x00\x00\x0bIDATx\xdac"
b"\xfc\xff\x1f\x00\x03\x03\x02\x00\xee\xd9\x97\xa9... | VWS-Python/vws-python-mock | src/mock_vws/_constants.py | .py | 7a576ff3f97abbe9 | 7.24 | 2 |
"""A fake implementation of the Vuforia Web Query API using Flask.
See
https://developer.vuforia.com/library/web-api/vuforia-query-web-api
"""
import email.utils
import time
from enum import StrEnum, auto
from http import HTTPMethod, HTTPStatus
from typing import assert_never
import requests
from beartype import bea... | VWS-Python/vws-python-mock | src/mock_vws/_flask_server/vwq.py | .py | 666c56dc058aedad | 7.24 | 2 |
"""Common utilities for creating mock routes."""
import email.utils
import json
import uuid
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from typing import Any
from beartype import beartype
from mock_vws._constants import ResultCodes
from mock_vws.target import ImageTarget
# A dat... | VWS-Python/vws-python-mock | src/mock_vws/_mock_common.py | .py | 02e6e7ebc2759685 | 7.24 | 2 |
"""Validators of the date header to use in the mock query API."""
import contextlib
import datetime
import logging
from collections.abc import Mapping
from zoneinfo import ZoneInfo
from beartype import beartype
from mock_vws._query_validators.exceptions import (
DateFormatNotValidError,
DateHeaderNotGivenErr... | VWS-Python/vws-python-mock | src/mock_vws/_query_validators/date_validators.py | .py | be37f00a33c2f834 | 7.24 | 2 |
"""A fake implementation of the Vuforia reco counts report endpoints."""
import datetime
import email.utils
import json
import logging
import re
import uuid
from http import HTTPStatus
from typing import Any, Protocol, runtime_checkable
from zoneinfo import ZoneInfo
from beartype import beartype
from mock_vws._const... | VWS-Python/vws-python-mock | src/mock_vws/_reco_counts_web_api.py | .py | 39f5c3bda2f0ac38 | 7.24 | 2 |
"""A fake implementation of the Vuforia Web Query API.
See
https://developer.vuforia.com/library/web-api/vuforia-query-web-api
"""
import email.utils
from collections.abc import Callable, Iterable, Mapping
from http import HTTPMethod, HTTPStatus
from typing import ParamSpec, Protocol, runtime_checkable
from beartype... | VWS-Python/vws-python-mock | src/mock_vws/_requests_mock_server/mock_web_query_api.py | .py | 0a8a3827d4c13c71 | 7.24 | 2 |
"""Helpers for mocking Vuforia with httpx via respx."""
import re
from collections.abc import Callable, Mapping
from typing import Protocol
from urllib.parse import urlparse
import httpx
import respx
from mock_vws._mock_common import RequestData, Route
_ResponseType = tuple[int, Mapping[str, str], str | bytes]
cl... | VWS-Python/vws-python-mock | src/mock_vws/_respx_mock_server/decorators.py | .py | f66902ed9e36979d | 7.24 | 2 |
"""Validators of the date header to use in the mock services API."""
import datetime
import logging
from collections.abc import Mapping
from http import HTTPStatus
from zoneinfo import ZoneInfo
from beartype import beartype
from mock_vws._services_validators.exceptions import (
FailError,
RequestTimeTooSkewe... | VWS-Python/vws-python-mock | src/mock_vws/_services_validators/date_validators.py | .py | 8cf4e69425dfa3cf | 7.24 | 2 |
"""Validators for given JSON."""
import json
import logging
from http import HTTPMethod, HTTPStatus
from json.decoder import JSONDecodeError
from beartype import beartype
from mock_vws._services_validators.exceptions import (
BadRequestError,
FailError,
UnnecessaryRequestBodyError,
)
_LOGGER = logging.g... | VWS-Python/vws-python-mock | src/mock_vws/_services_validators/json_validators.py | .py | 5307039b5c27d4df | 7.24 | 2 |
"""
统计 ETF 收盘价从每月第四个星期三到次月第四个星期三的涨跌幅分布。
用法:
python etf_fourth_wednesday.py SZ159915
python etf_fourth_wednesday.py SZ159915 --db finance.db
python etf_fourth_wednesday.py SZ159915 --plot
"""
import sqlite3
import sys
import os
from datetime import date, timedelta
from calendar import monthrange
from colle... | zhuyanxi/CarnoFinance | cmd/etf_fourth_wednesday.py | .py | 8247202f2b0754b9 | 7.15 | 1 |
"""
统计 ETF 每月第四个星期三收盘价起,波动达到 ±10% 所需的天数分布。
以每月第四个星期三收盘价为基准,向后逐日扫描,记录收盘价首次偏离基准
超过 ±10% 所需的自然天数。若数据范围内未触及则标记为"未触及"。
用法:
python etf_volatility_days.py SZ159915
python etf_volatility_days.py SZ159915 --threshold 0.15 --db finance.db
python etf_volatility_days.py SZ159915 --plot
"""
import sqlite3
import sys
... | zhuyanxi/CarnoFinance | cmd/etf_volatility_days.py | .py | ba1899d90262990d | 7.15 | 1 |
import argparse
import math
import os
import sqlite3
from datetime import datetime, timezone, timedelta
import numpy as np
import pandas as pd
# etfs = ["SZ159915", "SH515100", "SH513100", "SH518880"]
# -----------------------------
# 参数(与 JoinQuant 保持一致)
# -----------------------------
# ETF_POOL = ["SZ159915", "SH5... | zhuyanxi/CarnoFinance | cmd/get_kalmanfilter_score.py | .py | 375914e9974920a9 | 7.15 | 1 |
"""
交割单统计分析脚本
用法: python cmd/trade_stats.py data/kalmanfilter-rsrs.csv
"""
import argparse
import sys
from pathlib import Path
import pandas as pd
def parse_symbol_label(raw: str) -> str:
"""从 '50ETF(510050.XSHG)' 提取标的名称和代码"""
return raw.strip()
def compute_stats(df: pd.DataFrame, label: str = "") -> dict:... | zhuyanxi/CarnoFinance | cmd/trade_stats.py | .py | 39420fa7fd7f9d97 | 7.15 | 1 |
# 克隆自聚宽文章:https://www.joinquant.com/post/42673
# 标题:【回顾3】ETF策略之核心资产轮动
# 作者:wywy1995
import numpy as np
import pandas as pd
#初始化函数
def initialize(context):
# 设定基准
set_benchmark('399300.XSHE')
# 用真实价格交易
set_option('use_real_price', True)
# 打开防未来函数
set_option("avoid_future_data", True)
# 设置滑... | zhuyanxi/CarnoFinance | joinquant/ETF轮动/kalmanfilter-rsrs.py | .py | cbdad9baf89af6f6 | 7.15 | 1 |
#!/usr/bin/env python3
"""Unit tests for grafana-sqlite-backup.py.
Stdlib `unittest` only, for the same reason as
`test_cloudflare_analytics_ingest.py`: this repo has no Python toolchain, no
virtualenv and no pytest, so a suite that needed installing would not get run.
`make check-script-lint` executes every `test_*.p... | mnbf9rca/kubernetes_config | homelab/health/scripts/test_grafana_sqlite_backup.py | .py | 456f7545060455ff | 7.74 | 2 |
#!/usr/bin/env python3
"""Assert every standalone `kind: Job` sets `spec.ttlSecondsAfterFinished`.
A Job's `spec.template` is immutable. A completed Job that is never garbage
collected therefore pins the version of itself that ran, and the next apply
that changes it fails with `field is immutable`. Because `kubectl ap... | mnbf9rca/kubernetes_config | scripts/check-job-ttl.py | .py | 97afbd161a5a5953 | 7.24 | 2 |
#!/usr/bin/env python3
"""Report FreshRSS WebSub subscription health, without leaking callback secrets.
Each `!hub.json` under FreshRSS's PubSubHubbub state directory holds that feed's
callback secret in a `key` field, so the files must never be printed whole. This
reads them inside the pod and emits only the derived ... | mnbf9rca/kubernetes_config | scripts/freshrss-websub-status.py | .py | 6707265414b194b7 | 7.24 | 2 |
#!/usr/bin/env python3
"""Karakeep tag consolidation via LLM-driven clustering + tags.merge.
Strategy: instead of re-tagging (which regenerates a long tail), take the
existing tags as input, ask a strong model to cluster them into a target
taxonomy of N tags, then apply the merges via the tags.merge endpoint.
Bookmark... | mnbf9rca/kubernetes_config | scripts/karakeep-tag-consolidate.py | .py | 1456e90b36afdad1 | 7.24 | 2 |
import hashlib
import html
import json
import os
import re
import sys
import time
from datetime import datetime
from pathlib import Path
from shutil import copy
import requests
from Crypto.Cipher import AES
PROGRAM_VERSION = 2.0
DECRYPT_KEY_HASH = "24e0dc62a15c11d38b622162ea2b4383"
REGION_CODE = "ar,at,au,be,bg,br,c... | liu246542/switcheroo-lite | switcheroo_lite.py | .py | 72ab94a4fdd6e50f | 7.3 | 3 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2022-2025 CERN.
#
# CDS-RDM is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""CDS-RDM migration errors module."""
class CDSMigrationException(Exception):
"""CDSDoJSONException class."""
... | CERNDocumentServer/cds-migrator-kit | cds_migrator_kit/errors.py | .py | b87f4575d2f9c3a8 | 7.35 | 4 |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# cds-migrator-kit is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""CDS Migrator app extension."""
from . import config
from .reports.views ... | CERNDocumentServer/cds-migrator-kit | cds_migrator_kit/ext.py | .py | fef0d8628cff171e | 7.35 | 4 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2022 CERN.
#
# CDS-RDM is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""CDS-RDM migration extract module."""
import json
from os import listdir
from os.path import isfile, join
from pathlib ... | CERNDocumentServer/cds-migrator-kit | cds_migrator_kit/extract/extract.py | .py | c41ed7b29cc01e3a | 7.35 | 4 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2024 CERN.
#
# CDS-RDM is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""CDS-RDM migration load module."""
import json
import logging
import os
import psycopg2
from cds_rdm.legacy.models impo... | CERNDocumentServer/cds-migrator-kit | cds_migrator_kit/rdm/affiliations/load.py | .py | 18bc30251e4040c2 | 7.35 | 4 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2022 CERN.
#
# CDS-RDM is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""CDS-RDM migration record stats logger module."""
import logging
class AffiliationsLogger:
"""Migrator affiliatio... | CERNDocumentServer/cds-migrator-kit | cds_migrator_kit/rdm/affiliations/log.py | .py | e73bf66fb2469b9d | 7.35 | 4 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2022 CERN.
#
# Invenio-RDM-Migrator is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""InvenioRDM migration streams runner."""
from pathlib import Path
from invenio_rdm_migrator.streams impor... | CERNDocumentServer/cds-migrator-kit | cds_migrator_kit/rdm/affiliations/runner.py | .py | c56a717ebf037d1c | 7.35 | 4 |
# -*- coding: utf-8 -*-
#
# This file is part of CERN Document Server.
# Copyright (C) 2024 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your opti... | CERNDocumentServer/cds-migrator-kit | cds_migrator_kit/rdm/affiliations/xml_processing/models/affiliations.py | .py | 058355b4218b19d8 | 7.35 | 4 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2026 CERN.
#
# CDS-Migrator-Kit is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""CDS-Migrator-Kit comments extract module."""
import json
from pathlib import Path
import click
from invenio_... | CERNDocumentServer/cds-migrator-kit | cds_migrator_kit/rdm/comments/extract.py | .py | b39d5b197ec13451 | 7.35 | 4 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2026 CERN.
#
# CDS-Migrator-Kit is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""CDS-Migrator-Kit comments logger module."""
import csv
import logging
import os
from pathlib import Path
fro... | CERNDocumentServer/cds-migrator-kit | cds_migrator_kit/rdm/comments/log.py | .py | dde4ece9a4cb2e27 | 7.35 | 4 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2026 CERN.
#
# CDS-Migrator-Kit is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""CDS-Migrator-Kit comments runner module."""
import os
from pathlib import Path
import yaml
from invenio_rdm_... | CERNDocumentServer/cds-migrator-kit | cds_migrator_kit/rdm/comments/runner.py | .py | f40f45cf45da2083 | 7.35 | 4 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2026 CERN.
#
# CDS-RDM is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""CDS-RDM EP approval request validation and creation."""
from datetime import datetime, timezone
from cds_rdm.requests... | CERNDocumentServer/cds-migrator-kit | cds_migrator_kit/rdm/records/load/approval_request.py | .py | f17d9273deafe7ba | 7.35 | 4 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2026 CERN.
#
# CDS-RDM is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""CDS-RDM migration load module for records with EP approval."""
import json
from cds_rdm.legacy.resolver import get_pid... | CERNDocumentServer/cds-migrator-kit | cds_migrator_kit/rdm/records/load/ep_approval_load.py | .py | 72feb8e8008b39b6 | 7.35 | 4 |
"""ADB device discovery and selection.
Used by every ``android-*`` command. Wraps ``adb devices`` and exposes a
small API:
from toolscripts.adb import select_device, list_devices, get_device_model
serial = select_device() # may prompt the user
serials = list_devices() # returns all serials,... | jie-meng/toolscripts | src/toolscripts/adb/devices.py | .py | f05df3b8a544fef3 | 7.15 | 1 |
"""``ai-links`` - link AGENTS.md / .agents/{agents,skills} into per-tool config.
For every AI coding tool selected by the user, ``ai-links`` creates up to
three symlinks at the repository root:
* ``<tool's instructions filename> -> AGENTS.md`` — only for tools that
insist on their own filename (claude → ``CLAUDE.md... | jie-meng/toolscripts | src/toolscripts/commands/ai/ai_links.py | .py | cc0175a6974f3ce0 | 7.15 | 1 |
"""Shared registry of AI coding-tool integrations.
Single source of truth for every ``commands/ai/`` command that needs to know
where each AI tool keeps its config, what filename it reads at the repo
root, and how it discovers skills. When a vendor changes a path, you update
this file once and all of ``agents-setup``,... | jie-meng/toolscripts | src/toolscripts/commands/ai/tools.py | .py | b5cfe7dcca100ae5 | 7.15 | 1 |
"""A Spawner for the EGI Notebooks service"""
import base64
import uuid
from kubernetes_asyncio.client import V1ObjectMeta, V1Secret
from kubernetes_asyncio.client.rest import ApiException
from kubespawner import KubeSpawner
from traitlets import Bool, Unicode
class EGISpawner(KubeSpawner):
token_secret_name_te... | EGI-Federation/egi-notebooks-hub | egi_notebooks_hub/egispawner.py | .py | 567aab427462ea97 | 7.39 | 5 |
"""
A service to manage shares and release access tokens for running servers
It wraps some of the sharing functions of the Hub API with extra checks to
ensure access tokens cannot be obtained when the server is shared.
It requires the service to be configured with the right scopes:
* `read:users` to get information a... | EGI-Federation/egi-notebooks-hub | egi_notebooks_hub/services/share_manager.py | .py | 3ec12d05fa295d42 | 7.39 | 5 |
"""Handler for a simple welcome page for EGI Notebooks"""
from jupyterhub.handlers.base import BaseHandler
from tornado.escape import url_escape
from tornado.httputil import url_concat
class WelcomeHandler(BaseHandler):
"""Render the welcome home page.
For using it, define the following config:
from eg... | EGI-Federation/egi-notebooks-hub | egi_notebooks_hub/welcome.py | .py | 9d3c8517af95c890 | 7.39 | 5 |
"""
Additional Phase 2 tests for EGISpawner configuration assembly.
These tests focus on Python-side spawner configuration before Kubernetes receives
the resulting objects: Secret manifests, volume definitions, mounts, environment
variables, profile filtering, and hook sequencing.
"""
import types
from types import S... | EGI-Federation/egi-notebooks-hub | tests/phase2extended/test_egispawner_manifest_config.py | .py | 42d1d6cac70e6ea5 | 7.89 | 5 |
"""
Phase 4 integration tests for service-to-service flows.
These tests combine multiple service-level components and mocks to validate
complete request paths without a real Hub, IdP, or Kubernetes cluster.
The goal is to exercise realistic service behavior while still keeping the
tests fast, deterministic, and CI-fri... | EGI-Federation/egi-notebooks-hub | tests/phase4/test_api_wrapper_integration.py | .py | a796bcfa08c5bb9b | 7.89 | 5 |
"""
Additional Phase 4 integration-style tests for EGISpawner configuration flows.
These tests combine multiple EGISpawner methods with an in-memory Kubernetes API
replacement. They verify method interactions and resulting configuration without
requiring a live cluster.
"""
import types
from types import SimpleNamesp... | EGI-Federation/egi-notebooks-hub | tests/phase4/test_spawner_integration_config.py | .py | a169957173a7c3fd | 7.89 | 5 |
"""
Additional Phase 5 Kubernetes-backed tests for EGISpawner behavior.
This file is meant to be added next to the existing Phase 5 k3s tests as:
tests/phase5-k3s/test_spawner_k3s_additional.py
The tests intentionally use a real Kubernetes/k3s API server. They extend the
first Phase 5 file with coverage for:
- c... | EGI-Federation/egi-notebooks-hub | tests/phase5-k3s/test_spawner_k3s_additional.py | .py | 2510a197ce4a9f31 | 7.89 | 5 |
"""
Shared fixtures and helpers for Phase 6 running-Hub tests.
"""
import os
import shutil
import subprocess
import sys
import tempfile
import time
import uuid
from collections.abc import Iterator
from pathlib import Path
from typing import Any
import httpx
import pytest
PHASE6_TOKEN = "phase6-test-admin-token"
HUB_... | EGI-Federation/egi-notebooks-hub | tests/phase6/conftest.py | .py | c65e8f87a311d84e | 7.89 | 5 |
"""
Phase 6 service tests against a running JupyterHub process.
These tests intentionally distinguish between two different JupyterHub routes:
- /hub/api/services/<name> checks Hub service registry metadata.
- /services/<name> checks the real proxied service endpoint.
The share-manager service is a JupyterHub servic... | EGI-Federation/egi-notebooks-hub | tests/phase6/test_hub_services.py | .py | f25f44e82757c61d | 7.89 | 5 |
"""
Phase 6 spawner lifecycle tests against a running JupyterHub process.
"""
import json
import time
from pathlib import Path
import httpx
from .conftest import HUB_URL, api_delete, api_get, api_post, create_user, delete_user
def _events_path(running_hub):
return Path(running_hub["log_path"]).parent / "spawne... | EGI-Federation/egi-notebooks-hub | tests/phase6/test_hub_spawner.py | .py | db1cbdc8324b5ea6 | 7.89 | 5 |
#!/usr/bin/env python3
"""
Simple unified test runner for egi-notebooks-hub.
Usage:
python tests/run_tests.py --list
python tests/run_tests.py phase1
python tests/run_tests.py phase2
python tests/run_tests.py phase3
python tests/run_tests.py phase4
python tests/run_tests.py phase5
python te... | EGI-Federation/egi-notebooks-hub | tests/run_tests.py | .py | 4e8b56f17dccb3c6 | 7.89 | 5 |
"""
Background substraction is a necessary component of reflectometry reduction,
where the background scattering is removed from the reflected intensity.
Herein are some functions to enable that for a two-dimensional detector image,
as well as simple dataclasses in which we can store some information relating to
the b... | DiamondLightSource/islatu | src/islatu/background.py | .py | 078287d8143c14a6 | 7.15 | 1 |
"""
module to load in process configurations and check against preset schemas
"""
import os
import ast
from schema import Or, And, Use,Schema, SchemaError,Optional
import yaml
import numpy as np
import datetime
def validate_instrument(inst):
"""
check instrument is from allowed types
"""
valid_ins... | DiamondLightSource/islatu | src/islatu/config_loader.py | .py | 23db5837280d975c | 7.15 | 1 |
"""
Reflectometry data must be corrected as a part of reduction.
These functions facilitate this, including the footprint and
DCD q-variance corrections.
"""
import numpy as np
from scipy.interpolate import splrep
from scipy.stats import norm
def footprint_correction(beam_width, sample_size, theta):
"""
The ... | DiamondLightSource/islatu | src/islatu/corrections.py | .py | af818ab810a6b8da | 7.15 | 1 |
"""
This module contains both the Data class and the MeasurementBase class.
In a reflectometry measurement, the experimental data corresponds to the
reflected intensity as a function of scattering vector Q. In a typical
diffractometer, Q is a virtual axis, calculated geometrically from various motor
positions. The Data... | DiamondLightSource/islatu | src/islatu/data.py | .py | 78ee0687e6e34a79 | 7.15 | 1 |
"""
Islatu's simple Debug class.
"""
DEFAULT_LOG_LEVEL = 1
class Debug:
"""
A simple logger.
Attrs:
logging_level:
Current logging level. Higher means more unimportant messages will
be shown.
"""
def __init__(self, logging_level):
self.logging_level = log... | DiamondLightSource/islatu | src/islatu/debug.py | .py | 717757ba15fa68fd | 7.15 | 1 |
"""
A profile is a measurement resulting from a scan, or a series of scans. Profiles
are the central objects in the islatu library, containing the total reflected
intensity as a function of scattering vector data.
"""
from islatu.data import Data
from islatu.scan import Scan
from islatu.stitching import concatenate, r... | DiamondLightSource/islatu | src/islatu/refl_profile.py | .py | 9109c9fa9780f939 | 7.15 | 1 |
"""
This module defines the Region object, whose instances define regions of
interest in images.
"""
class Region:
"""
Instances of this class define regions of interest.
"""
def __init__(self, x_start, x_end, y_start, y_end):
# Make sure that x_end > x_start, etc.
if x_end < x_start... | DiamondLightSource/islatu | src/islatu/region.py | .py | 5223050431b5c67e | 7.15 | 1 |
"""
As reflectometry measurements typically consist of multiple scans at different
attenutation, we must stitch these together.
"""
import numpy as np
import pandas as pd
from islatu.debug import debug
from islatu.scan import Scan
def concatenate(scan_list: list[Scan]):
"""
Concatenate each of the datasets ... | DiamondLightSource/islatu | src/islatu/stitching.py | .py | 882dbbc2bd5b02fe | 7.15 | 1 |
"""
Module for testing the config loader module
"""
import copy
from schema import SchemaError
import pytest
from pytest_lazyfixture import lazy_fixture as lazy
from islatu.config_loader import check_config_schema,validate_new_axis,validate_new_type
@pytest.mark.parametrize(
'recipe',
[lazy('example_recipe_... | DiamondLightSource/islatu | tests/unit/test_config.py | .py | 998971bfc883891a | 7.65 | 1 |
"""Reversal-calibration statistics.
An inclinometer's zero offset cannot be separated from a real tilt by measuring
once. Measuring the same physical tilt twice, 180 degrees apart, does separate
them: the true tilt changes sign between the two readings while the sensor's
offset does not, so averaging the pair leaves t... | mgaliazzi/rotolevel | src/rotolevel/analysis.py | .py | 9f704fe003afb309 | 7 | 0 |
"""Runtime configuration, resolved from environment variables.
Every setting has a working default, so ``Config.from_env()`` succeeds on a bare
checkout. Only the MySQL credentials have no sensible default -- they are read
from the environment (optionally via a ``.env`` file) and never stored in source.
See ``.env.exa... | mgaliazzi/rotolevel | src/rotolevel/config.py | .py | fe59893a170fc851 | 7 | 0 |
"""Drift-free loop pacing.
The original code paced its sampling loops with::
try:
time.sleep(samplingTime - (stop - start))
except:
logger.warning("Not able to keep the period")
which relies on :func:`time.sleep` raising on a negative argument to detect an
overrun -- using an exception as the... | mgaliazzi/rotolevel | src/rotolevel/timing.py | .py | 0c0cc10b5518f775 | 7 | 0 |
"""
This script adds a new indicator to this implementation of Open SDG.
Usage example: the following would add 1.1.z, called "My indicator name",
as a new indicator:
python scripts/batch/add_indicator.py 1.1.z "My indicator name"
What this script actually does:
1. This script creates a file in the meta/ folder, ... | armstat/sdg-data-armenia | scripts/batch/add_indicator.py | .py | c2bf914994face84 | 7.24 | 2 |
# -*- coding: utf-8 -*-
"""
This script imports existing data for Armenia from an Excel file.
"""
import glob
import os.path
import pandas as pd
import numpy as np
import yaml
# For more readable code below.
HEADER_YEAR = 'Year'
HEADER_VALUE = 'Value'
HEADER_UNIT = 'Units'
FOLDER_DATA_CSV = 'data'
FOLDER_METADATA_YAM... | armstat/sdg-data-armenia | scripts/batch/initial-import.py | .py | daa14b4d5999b690 | 7.24 | 2 |
import feedparser
import pathlib
import re
import time
import asyncio
import os
import aiohttp
from github_stats import Stats
root = pathlib.Path(__file__).parent.resolve()
def replace_chunk(content, marker, chunk):
r = re.compile(
r"<!\-\- {} starts \-\->.*<!\-\- {} ends \-\->".format(marker, marker),
... | burnpiro/burnpiro | build_readme.py | .py | 24ff68f10ef3774b | 7 | 0 |
"""
Helper function for indexes manipulation
"""
import operator
from typing import List, Tuple
import pandas as pd
import numpy as np
__all__ = (
"join_indices",
"join_indices_dataframe",
)
def join_indices(index1, index2, operation: str):
"""
Join two indices `index1` and `index2` using operator... | pawlyk/dsml-tools | dsmlt/utils/pandas/indices.py | .py | 6cc0278ce0c25989 | 7.15 | 1 |
"""
Accounting operations
Creates the proper configuration files for cASO and runs it to get accounting
records for fedcloud sites
"""
import datetime
import json
import logging
import os.path
import subprocess
import sys
import tempfile
from dateutil import tz
from oslo_config import cfg
from .config import CONF
f... | EGI-Federation/fedcloud-catchall-operations | src/fedcloud_catchall/accounting.py | .py | 9765381b9873d0e7 | 7.39 | 5 |
"""
Configuration discovery for the different sites
"""
import glob
import logging
import os.path
from urllib.parse import urlparse
import httpx
import hvac
import jwt
import yaml
from hvac.exceptions import VaultError
from .config import CONF
from .token_generator import generate_token, get_oidc_config
_hvac_clien... | EGI-Federation/fedcloud-catchall-operations | src/fedcloud_catchall/discovery.py | .py | 84f79256ee27e39a | 7.39 | 5 |
"""
Accounting operations
Removes existing records to avoid filling up disk space
This is mostly a substitute for SSM while we decide whether to
actually send the records or not
"""
import glob
import logging
import sys
from dirq.QueueSimple import QueueSimple
from .config import CONF
def remove_records(site_dir)... | EGI-Federation/fedcloud-catchall-operations | src/fedcloud_catchall/record_cleaner.py | .py | 24597591a2570c58 | 7.39 | 5 |
"""Refreshes credentials for the cloud-info-provider
Takes its own configuration from env variables:
CHECKIN_SECRETS_FILE: yaml file with the check-in secrets to get access tokens
CHECKIN_SCOPES: Scopes to request in the access token
CHECKIN_OIDC_URL: Discovery URL for Check-in
ACCESS_TOKEN_SECRETS_FILE: File where to... | EGI-Federation/fedcloud-catchall-operations | src/fedcloud_catchall/token_generator.py | .py | b07c181eb87b0d4c | 7.39 | 5 |
# -*- coding: utf-8 -*-
"""
`db_update_sqlite.py` - Syncs data from external database into local SQLite DB.
- It will be run as a standalone operation via cron.
"""
import configparser
import logging
import os
import sys
import django
from django.db import DatabaseError
import pandas as pd
from ... | apel/monitoring | monitoring/db_update_sqlite.py | .py | c12ac3e5266fe949 | 7 | 0 |
# -*- coding: utf-8 -*-
"""
- Syncs data from external database into local SQLite DB.
- It will be run as a standalone operation via cron.
"""
import configparser
import logging
import os
import sys
import django
from django.db import DatabaseError
from django.utils.timezone import make_aware, is_naive
BASE_DIR = os... | apel/monitoring | monitoring/iris_db_update_sqlite.py | .py | 7e6ba1ab17833c3f | 7 | 0 |
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
# Apel loader and record-checking class imports
from apel.db import ApelDbException
from apel.db.loader.loader import Loader, LoaderException
from apel.db.loader.record_factory import RecordFactory, RecordFactoryException... | apel/monitoring | monitoring/validator/views.py | .py | 1b991cee9b4ce9b0 | 7 | 0 |
"""
A BufferReader gives data access to any number of consumers and provides methods to seek data such
as next(), range(), head(), tail(). Each BufferReader instance has it's own cursor keeping track of
what data was last seen."""
__all__ = ["BufferReader"]
from contextlib import suppress
import threading
import tim... | i2mint/stream2py | stream2py/buffer_reader.py | .py | 643ecd6eb725c150 | 7.35 | 4 |
"""Examples"""
from stream2py import SourceReader
class SimpleCounterString(SourceReader):
"""Count in range returning a string formatted as f's{count}'"""
def __init__(self, start, stop):
assert start < stop
self.start = start
self.stop = stop
self.range_iterator = None
... | i2mint/stream2py | stream2py/examples/source_reader.py | .py | d313da7fba368413 | 7.35 | 4 |
"""Examples"""
from stream2py.stream_source import StreamSource
class SimpleCounterString(StreamSource):
"""Count in range returning a string formatted as f's{count}'"""
def __init__(self, *, start=0, stop=1):
StreamSource.__init__(self)
assert start < stop
self.start = start
... | i2mint/stream2py | stream2py/examples/stream_source.py | .py | 94ff4c2e69231d8f | 7.35 | 4 |
"""
Helper Function to construct a SourceReader and StreamBuffer in one
Example of usage:
::
from stream2py.simply import mk_stream_buffer
counter = iter(range(10))
with mk_stream_buffer(
read_stream=lambda open_inst: next(counter),
open_stream=lambda: print('open'),
close_strea... | i2mint/stream2py | stream2py/simply.py | .py | 63d76192061c8789 | 7.35 | 4 |
"""
A SourceReader defines how to get data with the methods: open(), read(), and close(), and also how
the data is ordered with the key() method and an info property describing the instance."""
__all__ = ["SourceReader"]
from abc import ABCMeta, abstractmethod
import time
from typing import Optional, Any, Union, New... | i2mint/stream2py | stream2py/source_reader.py | .py | 80fa62b0d6f891de | 7.35 | 4 |
"""
HTTP Response streaming reader with no external dependencies
--------------
.. autoclass:: stream2py.sources.net.HTTPResponseReader()
:members:
:show-inheritance:
.. automethod:: __init__
"""
import urllib.request
from typing import Union, Optional
import time
from stream2py import SourceReader
from... | i2mint/stream2py | stream2py/sources/http.py | .py | 32e44d91a78e4021 | 7.35 | 4 |
"""
A StreamBuffer has 2 jobs: First, it manages the open, read, and close of a SourceReader
and puts read data onto a thread-safe buffer.
Second, it is a factory of BufferReaders instances for multiple consumers.
"""
from __future__ import annotations
__all__ = ["StreamBuffer"]
import logging
import threading
impor... | i2mint/stream2py | stream2py/stream_buffer.py | .py | 9a036d3d6a43fb0d | 7.35 | 4 |
"""
A BufferReader gives data access to any number of consumers and provides methods to seek data such
as next(), range(), head(), tail(). Each BufferReader instance has it's own cursor keeping track of
what data was last seen."""
from abc import ABCMeta, abstractmethod
import time
from typing import Optional, Union
... | i2mint/stream2py | stream2py/stream_source.py | .py | 9d6e9046fd763a96 | 7.35 | 4 |
"""Tests for BufferReader blocking parameter"""
import time
import threading
from stream2py import StreamBuffer
from stream2py.tests.utils_for_testing import SimpleSourceReader
from itertools import count
def test_buffer_reader_blocking():
"""Test that blocking parameter works correctly for BufferReader.read()"""... | i2mint/stream2py | stream2py/tests/test_buffer_reader_blocking.py | .py | 0d36fd50f5097fb5 | 7.85 | 4 |
"""Tests for BufferReader StopIteration behavior (Issue #10)"""
import pytest
from stream2py import StreamBuffer
from stream2py.tests.utils_for_testing import SimpleSourceReader
def test_next_raises_stopiteration_when_stopped():
"""Test that __next__() raises StopIteration when stream is stopped and no data avail... | i2mint/stream2py | stream2py/tests/test_buffer_reader_stopiteration.py | .py | cc64ee8c7e761e90 | 7.85 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.