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 |
|---|---|---|---|---|---|---|
"""A channel implementation that routes all calls to one service/method combination.
The :class:`Constant` channel wraps an existing
:class:`ClientChannelInterface`. It resolves all method lookups to one
specified ``method`` name. Generated helpers use it for clients that target
one service-method namespace. These cli... | nebius/pysdk | src/nebius/aio/constant_channel.py | .py | f1928238cc511ad4 | 7.62 | 16 |
"""Add idempotency keys to asynchronous gRPC client calls.
The interceptor adds a unique UUID4 key to the ``x-idempotency-key`` header.
It does not replace an existing key. The key lets the server prevent duplicate
effects when a client retries an operation.
"""
from collections.abc import Callable
from logging impor... | nebius/pysdk | src/nebius/aio/idempotency.py | .py | e4f1593f0aa19616 | 7.62 | 16 |
"""gRPC keepalive configuration shared by SDK channels.
Channel constructors accept ``keepalive`` as ``None``/``True`` for SDK defaults,
``False`` to disable SDK keepalive, or explicit :class:`KeepaliveOptions` /
mapping overrides. With the default ``None`` value the SDK reads
``NEBIUS_GRPC_KEEPALIVE_*`` environment v... | nebius/pysdk | src/nebius/aio/keepalive.py | .py | 03495c7854cd02ec | 7.62 | 16 |
"""Namespace-aware transport calls for current and alpha operation services."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, cast
if TYPE_CHECKING:
from grpc.aio import Channel
from ..base.protos.registry import Registry
class OperationServiceTransportStub:
"""Small genera... | nebius/pysdk | src/nebius/aio/operation_service.py | .py | 74a54d41407c4290 | 7.62 | 16 |
"""Define keyword arguments that apply to all SDK requests.
Usage::
from nebius.aio.request_kwargs import RequestKwargs
from typing_extensions import Unpack # or from typing import Unpack in Python 3.11+
from nebius.api.nebius... import SomeService, SomeRequest # illustrative only
def my_request_wra... | nebius/pysdk | src/nebius/aio/request_kwargs.py | .py | cf689ebb2cb2a261 | 7.62 | 16 |
"""Registry-aware representations of final RPC status values."""
from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import TYPE_CHECKING, Any, cast
from grpc import StatusCode
if TYPE_CHECKING:
from ..base.protos.registry import Registry
class Unfinis... | nebius/pysdk | src/nebius/aio/request_status.py | .py | 9ccbba423cd41a8d | 7.62 | 16 |
"""Immutable namespace-aware route metadata emitted by service clients."""
from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True)
class Route:
service: str
method: str
api_service_name: str = ""
registry: object | None = None
@property
def method_name(s... | nebius/pysdk | src/nebius/aio/route.py | .py | e4fef182306fa493 | 7.12 | 16 |
"""Helpers for converting service-level protobuf errors into SDK types.
This module uses :mod:`request_status` to represent detailed service errors.
It uses service semantics and gRPC status codes to decide if a request can
retry.
"""
from __future__ import annotations
import re
from collections.abc import Callable,... | nebius/pysdk | src/nebius/aio/service_error.py | .py | 4fd162e9fa9e07ab | 7.62 | 16 |
"""Token exchange bearer and receiver.
This module implements a bearer that exchanges a permanent service-account JWT
or similar credentials for a short-lived access token using the
``TokenExchangeService``. The exchange is performed via a gRPC call
and the response is converted into a :class:`Token` instance.
The pr... | nebius/pysdk | src/nebius/aio/token/exchangeable.py | .py | 2a216b3856fa725a | 7.62 | 16 |
"""Exchange federated credentials for renewable access tokens.
:class:`FederatedCredentialsBearer` combines a federated-credentials reader
or requester with exchangeable and renewable bearers. It supplies short-lived
access tokens.
The class accepts one of several inputs for ``federated_credentials``:
- a
:class... | nebius/pysdk | src/nebius/aio/token/federated_credentials.py | .py | 0d90a50d485495d6 | 7.62 | 16 |
"""Federation bearer authentication utilities.
This module provides functions to perform OAuth 2.0 authorization code flow
with PKCE for federation bearer token authentication. It handles browser-based
authentication, callback server management, and token exchange.
"""
import asyncio
import ssl
import sys
import urll... | nebius/pysdk | src/nebius/aio/token/federation_bearer/auth.py | .py | 892368a7ebbda1e5 | 7.62 | 16 |
def generate_pkce_code_verifier() -> str:
"""Generate a PKCE code verifier.
Returns
-------
str: A securely generated code verifier.
"""
import base64
import secrets
# Generate a random 32-byte string
random_bytes = secrets.token_bytes(32)
# Base64 URL-safe encode the byt... | nebius/pysdk | src/nebius/aio/token/federation_bearer/pkce.py | .py | 98aa4f6956914b08 | 7.62 | 16 |
"""Federation bearer token server for handling OAuth callbacks.
This module provides a CallbackHandler class that sets up a local HTTP server
to handle OAuth authorization code callbacks during federation bearer token
authentication flows. It uses PKCE (Proof Key for Code Exchange) for security.
"""
import asyncio
im... | nebius/pysdk | src/nebius/aio/token/federation_bearer/server.py | .py | 3c62fc132f6588d0 | 7.62 | 16 |
"""File-backed static token bearer.
This module provides a tiny bearer implementation that reads a raw
access token from a filesystem path. It is useful for local testing,
scripting or environments where a short-lived token is written to a
file by an external process or host system.
The bearer caches tokens for a sho... | nebius/pysdk | src/nebius/aio/token/file.py | .py | 0575e70c327718db | 7.62 | 16 |
"""Asynchronous file lock using portalocker.
This module wraps :mod:`portalocker` for asynchronous use. Use
:class:`Lock` with ``async with`` to get a file lock without blocking the
event loop. The implementation polls with ``asyncio.sleep``.
The lock supports exclusive and shared modes and a configurable
timeout/pol... | nebius/pysdk | src/nebius/aio/token/file_cache/async_flock.py | .py | d821cd8bc2489e4e | 7.62 | 16 |
import logging
import os
import re
import warnings
from getpass import getpass
from importlib.metadata import version
from typing import Any, Optional, Union
import httpx
from rich.logging import RichHandler
from .utils import AutoPrettyPrint
class DatalabAPIError(Exception):
"""Base exception for Datalab API e... | datalab-org/datalab-api | src/datalab_api/_base.py | .py | 36e86f81cadf3cb2 | 7.52 | 10 |
#!/usr/bin/env python3
"""
Download and format videos for each camera in camera_to_workload.json by calling format_avc_mp4.sh.
"""
import json
import sys
import subprocess
from pathlib import Path
import argparse
def process_camera_videos(config_path, script_path):
"""Call format_avc_mp4.sh for each camera in the ... | intel-retail/loss-prevention | download-scripts/download-video.py | .py | 7f93f48328d78899 | 7.42 | 6 |
import sys
import urllib.request
from pathlib import Path
MODEL_NAME = sys.argv[1] if len(sys.argv) > 1 else "efficientnet-b0"
MODELS_BASE_PATH = sys.argv[2] if len(sys.argv) > 2 else "models"
FP16_INT8_BASE_URL = "https://raw.githubusercontent.com/dlstreamer/pipeline-zoo-models/refs/heads/main/storage/efficientnet-b0... | intel-retail/loss-prevention | download-scripts/effnetb0_download.py | .py | 8776ed0f70ced28a | 7.42 | 6 |
import json
from typing import List, Dict, Any, Callable
class ConfigAgent:
def __init__(self, config_file: str):
self.config_file = config_file
self.call_vlm = call_vlm or self._default_vlm_call
def load_config(self, file_path: str) -> List[Dict[str, Any]]:
"""Load configuration file ... | intel-retail/loss-prevention | lp-vlm/src/agent/agent.py | .py | 67ff859cf5ac9637 | 7.42 | 6 |
import os
import sys
import subprocess
from pathlib import Path
import json
import io
from typing import Tuple
from utils.config import MINIO_HOST, logger
from datetime import timedelta
# Create a global MinIO client instance (singleton)
_minio_client = None
MINIO_BUCKET = "loss-prevention-enhanced-vlm-results"
MINIO... | intel-retail/loss-prevention | lp-vlm/src/utils/save_results.py | .py | 3ae0748dd4b5c189 | 7.42 | 6 |
"""Vision Language Model integration for grocery item detection."""
import json
from typing import Dict, Any, Tuple
from io import BytesIO
import os
import time
import numpy as np
from PIL import Image
import requests
from pathlib import Path
from utils.config import OVMS_ENDPOINT, OVMS_MODEL_NAME, logger
from utils.pr... | intel-retail/loss-prevention | lp-vlm/src/utils/vlm.py | .py | 6adc5ee067ee6a88 | 7.42 | 6 |
#!/usr/bin/env python3
import argparse
import json
import logging
import os
from pathlib import Path
from urllib.parse import urlparse
import socket
import subprocess
import time
# -------------------- Logger Setup --------------------
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %... | intel-retail/loss-prevention | lp-vlm/src/workload_utils.py | .py | 9bc4945479e510e3 | 7.42 | 6 |
from collections.abc import Hashable
from typing import Generic, TypeVar
from aidial_sdk.pydantic_v1 import BaseModel
_Index = TypeVar("_Index", bound=Hashable)
class IndexMapper(BaseModel, Generic[_Index]):
"""
Used to maintain consistent mapping between indexed values in the incoming and outgoing streams,... | epam/ai-dial-interceptors-sdk | aidial_interceptors_sdk/chat_completion/index_mapper.py | .py | 7515384b89fd5daa | 7.42 | 6 |
from aidial_sdk.chat_completion import Request
from aidial_interceptors_sdk.chat_completion.element_path import ElementPath
from aidial_interceptors_sdk.chat_completion.helpers import (
traverse_list,
traverse_required_dict_value,
)
from aidial_interceptors_sdk.chat_completion.request_message_handler import (
... | epam/ai-dial-interceptors-sdk | aidial_interceptors_sdk/chat_completion/request_handler.py | .py | f2b00dbb5182baa4 | 7.42 | 6 |
"""
Callbacks to handle messages in the chat completion request.
"""
from abc import ABC
from aidial_sdk.pydantic_v1 import BaseModel
from aidial_interceptors_sdk.chat_completion.element_path import ElementPath
from aidial_interceptors_sdk.chat_completion.helpers import (
traverse_dict_value,
traverse_list,
... | epam/ai-dial-interceptors-sdk | aidial_interceptors_sdk/chat_completion/request_message_handler.py | .py | 2117224f0292f11d | 7.42 | 6 |
"""
CODE-GENERATED from aidial_interceptors_sdk/chat_completion/request_message_handler.py module.
DO NOT MODIFY THIS FILE.
Callbacks to handle messages in the chat completion response.
"""
from abc import ABC
from aidial_sdk.pydantic_v1 import BaseModel
from aidial_interceptors_sdk.chat_completion.element_path imp... | epam/ai-dial-interceptors-sdk | aidial_interceptors_sdk/chat_completion/response_message_handler.py | .py | 8bc28a9b99f176ea | 7.42 | 6 |
import time
from collections import defaultdict
from aidial_sdk.chat_completion import Stage
from aidial_sdk.pydantic_v1 import BaseModel
from typing_extensions import override
from aidial_interceptors_sdk.chat_completion.base import (
ChatCompletionInterceptor,
)
from aidial_interceptors_sdk.chat_completion.elem... | epam/ai-dial-interceptors-sdk | aidial_interceptors_sdk/examples/chat_completion/statistics_reporter.py | .py | 418306be929595c5 | 7.42 | 6 |
# !/usr/bin/env python
# Markham Lee (C) 2023 - 2024
# Finance, Productivity, IoT Dashboard
# https://github.com/MarkhamLee/productivity-music-stocks-weather-IoT-dashboard
# Python script for pulling data from a Nova PM SDS011 air quality sensor
# connected by USB, and then pushing the data to console.
import serial
im... | MarkhamLee/internet-and-iot-data-platform | IoT/examples/air_quality_sensor_novapm_sds011/main_usb.py | .py | 122813f330603bc9 | 7.45 | 7 |
# Simple script to quickly test and troubleshoot a SDS011 Air Quality sensor
import serial
from time import sleep
pm2_bytes = 2
pm10_bytes = 4
device_id = 6
USB = '/dev/ttyUSB0'
serial_connection = serial.Serial(USB)
def parse_value(message, start_byte, num_bytes=2,
byte_order='little', scale=None... | MarkhamLee/internet-and-iot-data-platform | IoT/sds011_air_quality_sensor_testing/main.py | .py | a923787935bf0300 | 7.95 | 7 |
# (C) Markham Lee 2023-2026
# Internet & IoT Data Platform
# https://github.com/MarkhamLee/internet-and-iot-data-platform
# General utlities to support agentic workflows
import requests
from agent_library.logging_util import console_logging
logger = console_logging('agent_utilities_logs')
def send_slack_webhook_basi... | MarkhamLee/internet-and-iot-data-platform | ai_agents/agent_library/agent_utilities.py | .py | fb364d58d5face27 | 7.45 | 7 |
from aidial_adapter_anthropic.dial.request import ModelParameters
from aidial_adapter_bedrock.llm.converse.adapter import ConverseAdapter
class ConverseAdapterWithStreamingEmulation(ConverseAdapter):
"""
Certain Converse API models support tools only in the non-streaming mode.
So we need to run request i... | epam/ai-dial-adapter-bedrock | aidial_adapter_bedrock/llm/model/llama/v3.py | .py | f8d114e4bfdf24cb | 7.57 | 13 |
"""
Some models report cache-write tokens in
`usage.prompt_tokens_details.cache_creation_input_tokens` - a field borrowed
from the Anthropic Messages API, which isn't a part of the Chat Completions API.
The module normalizes it into `usage.prompt_tokens_details.cache_write_tokens`,
which is what DIAL expects.
"""
fro... | epam/ai-dial-adapter-openai | aidial_adapter_openai/chat_completions/cache_tokens.py | .py | ed3532734bf5162f | 7.63 | 17 |
"""
GPT-4o Audio Completions middleware for handling audio responses.
The module provides helpers that extract audio data and transcripts
from GPT-4o audio completions API responses, transforming them into
DIAL-compatible format with attachments and stages.
"""
from collections.abc import AsyncIterator
from typing im... | epam/ai-dial-adapter-openai | aidial_adapter_openai/chat_completions/gpt_audio.py | .py | 851640f377bd68d7 | 7.63 | 17 |
"""
Azure OpenAI documentation doesn't specify exactly how
OpenAI Harmony Response Format (which is used by gpt-oss under the hood)
is mapped unto the Chat Completions API.
Reversed engineering and testing shows that reasoning content is provided
in `message.reasoning_content` field of the response.
The module provid... | epam/ai-dial-adapter-openai | aidial_adapter_openai/chat_completions/gpt_oss.py | .py | 341be50ed827de70 | 7.63 | 17 |
"""
vLLM-specific audio transformer.
Applied as a second pass after the general ``ResourceProcessor`` transformation.
Replaces ``input_audio`` content parts with ``audio_url`` content parts
from ``MultiModalMessage.audios`` in the format expected by vLLM.
See https://docs.vllm.ai/en/latest/features/multimodal_inputs/... | epam/ai-dial-adapter-openai | aidial_adapter_openai/chat_completions/vllm/audio_transformer.py | .py | 83b2c00c97bef4a2 | 7.63 | 17 |
from collections.abc import AsyncIterator
from typing import TypeVar
from pydantic import BaseModel
from aidial_adapter_openai.utils.streaming import map_stream
class _ReasoningResponseTransformer(BaseModel):
"""Extracts reasoning from vLLM responses into DIAL Stages.
vLLM reasoning models (e.g. DeepSeek-R... | epam/ai-dial-adapter-openai | aidial_adapter_openai/chat_completions/vllm/extract_reasoning.py | .py | 652851578e820043 | 7.63 | 17 |
"""
Tokenizer that delegates token counting entirely to a vLLM uplink server.
vLLM exposes a ``/tokenize`` endpoint that accepts a list of messages
(including multi-modal content such as images and files encoded as base64)
and returns the total token count. This tokenizer simply forwards the
already-transformed reque... | epam/ai-dial-adapter-openai | aidial_adapter_openai/chat_completions/vllm/tokenizer.py | .py | 421944e1624bccf3 | 7.63 | 17 |
from aidial_sdk.chat_completion import Response
from aidial_sdk.exceptions import HTTPException as DialException
from aidial_sdk.exceptions import RequestValidationError
class UserError(Exception):
"""
The user errors are aimed to a DIAL chat user.
So whenever an exceptional situation arises that could be... | epam/ai-dial-adapter-vertexai | aidial_adapter_vertexai/chat/errors.py | .py | 830a8b1ec3e0757d | 7.57 | 13 |
from abc import ABC, abstractmethod
from collections.abc import Awaitable, Callable, Sized
from typing import (
Generic,
Self,
TypeVar,
)
from aidial_sdk.exceptions import (
ContextLengthExceededError,
InvalidRequestError,
TruncatePromptSystemAndLastUserError,
)
from aidial_sdk.exceptions impor... | epam/ai-dial-adapter-vertexai | aidial_adapter_vertexai/chat/truncate_prompt.py | .py | 7422a0156acbdc0f | 7.57 | 13 |
import time
from collections.abc import Callable, Coroutine, Mapping
from typing import Any
from aidial_sdk.chat_completion import Response
from aidial_adapter_vertexai.deployments import ChatCompletionDeployment as D
from aidial_adapter_vertexai.utils.log_config import app_logger as log
_DIAL_CACHE_BREAKPOINT_PATH ... | epam/ai-dial-adapter-vertexai | aidial_adapter_vertexai/dial_api/caching.py | .py | bfe61247c7ea12d5 | 7.57 | 13 |
import nox
nox.options.reuse_existing_virtualenvs = True
nox.options.sessions = ["lint", "tests"]
SRC = ["aidial_analytics_realtime", "tests", "noxfile.py"]
@nox.session(python=["3.12"])
def lint(session):
"""Runs linters and fixers"""
session.run("poetry", "install", "--with", "lint", external=True)
se... | epam/ai-dial-analytics-realtime | noxfile.py | .py | 9c04a793de879163 | 7.54 | 11 |
from tests.utils.constants import (
DEFAULT_CHAT_ID,
DEFAULT_DEPLOYMENT,
DEFAULT_EXECUTION_PATH_LIST,
DEFAULT_MODEL,
DEFAULT_PARENT_DEPLOYMENT,
DEFAULT_PROJECT_ID,
DEFAULT_REQUEST_METHOD,
DEFAULT_RESPONSE_ID,
DEFAULT_RESPONSE_STATUS,
DEFAULT_RESPONSE_TIME,
DEFAULT_UPSTREAM_UR... | epam/ai-dial-analytics-realtime | tests/utils/message/chat.py | .py | 4ccfde930c92ddda | 7.04 | 11 |
from tests.utils.constants import (
DEFAULT_CHAT_ID,
DEFAULT_DEPLOYMENT,
DEFAULT_EXECUTION_PATH_LIST,
DEFAULT_MCP_METHOD,
DEFAULT_MCP_TOOL_CALL_NAME,
DEFAULT_PARENT_DEPLOYMENT,
DEFAULT_PROJECT_ID,
DEFAULT_REQUEST_METHOD,
DEFAULT_RESPONSE_STATUS,
DEFAULT_RESPONSE_TIME,
DEFAULT... | epam/ai-dial-analytics-realtime | tests/utils/message/mcp.py | .py | 45b3abe228336040 | 7.04 | 11 |
"""
This package provides convenient utilities and data to write a sphinx config file.
"""
from __future__ import annotations
import json
import warnings
from pathlib import Path
from typing import Optional, Tuple, cast
# See issue 4, we this the best format is Major.YYMM.day,
# in case of multiple releases a day we... | Quansight-Labs/intersphinx_registry | intersphinx_registry/__init__.py | .py | 15e0618beb83859b | 7.66 | 20 |
import shutil
import sys
from datetime import timedelta
from pathlib import Path
import platformdirs
import requests_cache
from . import __version__
def _compress_user_path(path: str) -> str:
"""
Replace home directory with ~ in a path string.
Parameters
----------
path : str
Path to co... | Quansight-Labs/intersphinx_registry | intersphinx_registry/utils.py | .py | fd68e6b6ece55e3b | 7.66 | 20 |
import warnings
from urllib.parse import urljoin
import pytest
import requests
from intersphinx_registry import _ALIASES, _get_all_mappings, get_intersphinx_mapping
MAPPING = _get_all_mappings()
keys = set(MAPPING)
TIMEOUT = 5 # sec
# click does return a 301 instead of a 30
CLICK_WRONG_301 = 301
@pytest.mark.pa... | Quansight-Labs/intersphinx_registry | tests/test_basic.py | .py | 12145056eaa74e27 | 8.16 | 20 |
"""Distributes functional test feature files across CI shards using greedy
bin-packing, with total line count as a proxy for test duration.
Each shard receives an approximately equal share of lines, so that parallel
CI jobs finish in roughly the same time. The assigned feature file paths for
the current shard are wri... | ONSdigital/dis-wagtail | .github/split_functional_test_features.py | .py | 55fa8bb7b10e3270 | 8.06 | 12 |
from typing import TYPE_CHECKING, Any
from django.db.models.signals import post_save
from django.dispatch import receiver
from wagtail import hooks
from wagtail.models import Page
from wagtail.signals import init_new_page, page_published
from cms.articles.models import ArticlesIndexPage, StatisticalArticlePage
from c... | ONSdigital/dis-wagtail | cms/articles/signal_handlers.py | .py | b0a873c50856e07a | 7.56 | 12 |
from datetime import timedelta
from django.test import TestCase
from django.urls import reverse
from wagtail.test.utils import WagtailTestUtils
from wagtail.test.utils.form_data import nested_form_data
from cms.articles.tests.factories import ArticleSeriesPageFactory, StatisticalArticlePageFactory
from cms.topics.tes... | ONSdigital/dis-wagtail | cms/articles/tests/test_wagtail_hooks.py | .py | 32e2f6d5761b475c | 7.06 | 12 |
from __future__ import annotations # needed for unquoted forward references because of Django Views
import logging
from collections.abc import Mapping
from typing import TYPE_CHECKING
from django.conf import settings
from django.contrib.auth import login, logout
from django.contrib.auth.middleware import Authenticat... | ONSdigital/dis-wagtail | cms/auth/middleware.py | .py | 03ac82418ada5d3b | 7.56 | 12 |
import base64
import json
import uuid
from collections import namedtuple
from datetime import UTC, datetime, timedelta
from typing import Any
import jwt
import requests
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from django.conf import settings
fr... | ONSdigital/dis-wagtail | cms/auth/tests/helpers.py | .py | a947b2a807044e19 | 8.06 | 12 |
import uuid
from unittest.mock import patch
from django.conf import settings
from django.test import override_settings
from django.urls import reverse
from cms.auth import wagtail_hooks
from cms.auth.middleware import JWT_SESSION_ID_KEY
from cms.auth.tests.helpers import CognitoTokenTestCase, build_jwt
from cms.users... | ONSdigital/dis-wagtail | cms/auth/tests/test_auth_integration.py | .py | 0a899b30897b2704 | 7.06 | 12 |
from django.conf import settings
from django.test import TestCase, override_settings
from cms.auth.checks import check_aws_cognito, check_identity_api, check_session_config, check_team_sync
class AuthSettingsCheckTests(TestCase):
"""Tests for check_auth_settings which validates AWS Cognito and session configurat... | ONSdigital/dis-wagtail | cms/auth/tests/test_checks.py | .py | 02d6b7bf8c106ecb | 7.06 | 12 |
import base64
import importlib
import json
import uuid
from datetime import UTC, datetime, timedelta
from unittest import mock
import jwt
import requests
from django.conf import settings
from django.core.cache import caches
from django.test import SimpleTestCase, override_settings
from cms.auth import utils
from cms.... | ONSdigital/dis-wagtail | cms/auth/tests/test_utils.py | .py | 733f4901bbe81428 | 7.06 | 12 |
from unittest import mock
from django.conf import settings
from django.contrib import messages
from django.contrib.sessions.middleware import SessionMiddleware
from django.middleware import csrf
from django.test import Client, RequestFactory, TestCase, override_settings
from django.urls import reverse
from django.util... | ONSdigital/dis-wagtail | cms/auth/tests/test_views.py | .py | 7ab3ca7b5a607114 | 8.06 | 12 |
import base64
import json
import logging
from collections.abc import Iterable
from typing import TYPE_CHECKING, Any, cast
import requests
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from django.conf import settings
from jwt import InvalidTokenError,... | ONSdigital/dis-wagtail | cms/auth/utils.py | .py | 5da6bef9e664a8ac | 7.56 | 12 |
import logging
from typing import Any, Protocol, cast
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpRequest, HttpResponse, JsonResponse
from django.views.decorators.cache import never_cache
from django.views.de... | ONSdigital/dis-wagtail | cms/auth/views.py | .py | aeaf49b06187615b | 7.56 | 12 |
from typing import TYPE_CHECKING, Any
from django import forms
from django.core.exceptions import ValidationError
from .mixins import BundledPageMixin
from .models import Bundle
from .viewsets.bundle_chooser import BundleChooserWidget
if TYPE_CHECKING:
from wagtail.models import Page
class AddToBundleForm(form... | ONSdigital/dis-wagtail | cms/bundles/admin_forms.py | .py | aa039cd01b46e3b2 | 7.56 | 12 |
#!/usr/bin/ python3
"""
Script to receive list of
'Latest = False' files found
within the access renditions
backup bucket.
Iterate list checking for versions
that are not the 'latest' or are
not flagged 'Latest', and delete
those using 'version_id' of each
file in case.
2026
"""
import logging
import os
import sys
... | bfidatadigipres/BFI_scripts | black_pearl/Access_rendition_deletion_clean_up.py | .py | ea0d16996edceb7d | 7.54 | 11 |
#!/usr/bin/ python3
"""
Script to frequently back up
MP4 and JPG proxy files created as part
of autoingest to DPI.
Targeting bfi/ subfolders only at this time:
- Checks for modifications in last MOD_MAX days
- Checks if file already in BP bucket
- If yes compares local/remote MD5
- If don't match pushes through to BP... | bfidatadigipres/BFI_scripts | black_pearl/black_pearl_access_rendition_backup.py | .py | 106972f3050d8cce | 7.54 | 11 |
#!/usr/bin/ python3
"""
Script to frequently back up
MP4 and JPG proxy files created as part
of autoingest to DPI.
Initially this script is to be
run with an open modification time but
later to be set to a given amount of
days that matches script run frequency.
2024
"""
# Public imports
import logging
import os
imp... | bfidatadigipres/BFI_scripts | black_pearl/black_pearl_access_rendition_backup_once.py | .py | 5fad2c709fee16ab | 7.54 | 11 |
#! /usr/bin/env python3
"""
RETRIEVE PATH NAME SYS.ARGV[1] FROM CRON LAUNCH
Script to manage retrieval of Ingest jobs from Black Pearl ingest
folders and PUT data to Black Pearl tape library
Script actions:
1. Identify supply path and collection for bucket selection
2. Adds items found top level in black_pearl_(netf... | bfidatadigipres/BFI_scripts | black_pearl/black_pearl_move_put.py | .py | ecc4c9a1df64341b | 7.54 | 11 |
#!/usr/bin/env python3
"""
To be run from a server where Spectra SDK installed
and run from ENV3, so I'd suggest:
BK-CI-DATA11:
`source ENV3/bin/activate`
`python3 fetch_tv_length.py`
I think read/write from separate CSVs will be
quicker than using a Pandas dataframe and allow
for code restart if it should fail midwa... | bfidatadigipres/BFI_scripts | black_pearl/deprecated/fetch_tv_length.py | .py | e432305a4b2e8dab | 7.54 | 11 |
#!/usr/bin/env python3
import csv
import os
import sys
from ds3 import ds3
sys.path.append(os.environ["CODE"])
import utils
# Setup client/paths
CLIENT = ds3.createClientFromEnv()
ADMIN = os.path.join(os.environ["QNAP_FILM"], "test/")
CSV_PATH = os.path.join(ADMIN, "ofcom_dpi_ingest_2.csv")
NEW_CSV_PATH = os.path.j... | bfidatadigipres/BFI_scripts | black_pearl/deprecated/fetch_tv_length_2.py | .py | 67b8610f9d9e71cb | 7.54 | 11 |
"""
Create CSV_PATH with headers:
fname, bucket
To be run from a server where Spectra SDK installed
and run from ENV3, so I'd suggest:
BK-CI-DATA11:
`source /home/datadigipres/code/ENV3/bin/activate`
`python3 fetch_tv_size_pandas.py`
"""
import pandas as pd
from ds3 import ds3
sys.path.append(os.environ["CODE"])
imp... | bfidatadigipres/BFI_scripts | black_pearl/deprecated/fetch_tv_size_pandas.py | .py | 3bc4529222911bd4 | 7.54 | 11 |
#! /usr/bin/env python3
"""
** MUST BE RUN WITH AUTOINGEST PATH AS SYS.ARGV[1] TO TARGET CORRECT PATH **
Script to manage retrieval of Ingest jobs from bp_reingest folders creating
a folder within in this folder called something like ingest_YYYY_MM_DD_HH_MM_SS/
Adds items found top level in bp_reingest to this new in... | bfidatadigipres/BFI_scripts | black_pearl/deprecated/reingest_black_pearl_move_put.py | .py | c92d5b0bbc56eb22 | 7.54 | 11 |
#!/usr/bin/env python3
"""
Parse `global.log` and report on files with outstanding
WARNING alerts issued for the given day.
2022
"""
# Python library imports
import csv
import datetime
# Python library imports
import os
import shutil
import sys
from typing import Final
csv.field_size_limit(10000000)
# Local import... | bfidatadigipres/BFI_scripts | black_pearl/log_parser.py | .py | c7e2bbce2728b3b3 | 7.54 | 11 |
#!/usr/bin/env python3
import os
import sys
sys.path.append(os.path.join(os.environ["CODE"], "black_pearl"))
import autoingest
def test_check_filename():
"""
Using hardcoded names to test naming checks
"""
data1 = autoingest.check_filename("N_123456_new_01of01.mkv")
data2 = autoingest.check_file... | bfidatadigipres/BFI_scripts | black_pearl/test/test_autoingest.py | .py | 0fd77e3125803211 | 8.04 | 11 |
#!/usr/bin/env python3
import datetime
import os
import sys
import pytz
sys.path.append(os.path.join(os.environ["CODE"], "black_pearl"))
import black_pearl_move_put as bp
def test_get_buckets():
"""
Using hardcoded names to test JSON
retrieval of BP buckets
"""
bucket_list1 = bp.get_buckets("bf... | bfidatadigipres/BFI_scripts | black_pearl/test/test_black_pearl_move_put.py | .py | b94a67ef93ea03ff | 8.04 | 11 |
#!/usr/bin/env python3
"""
Special Collections Document Archiving script for OSH
Script stages:
MUST BE SUPPLIED WITH SYS.ARGV[1] AT SUB-FOND LEVEL PATH
1. Iterate through supplied sys.argv[1] folder path
2. For each subfolder split folder name: ob_num / ISAD(G) level / Title
3. Create CID record for each folder foll... | bfidatadigipres/BFI_scripts | born_digital_workflows/special_collections_document_archiving_osh.py | .py | 92415c6b0e576cb7 | 7.04 | 11 |
#!/usr/bin/env python3
"""
Special Collections Born Digital script
Creation of Digital internalobject records
Script stages:
1. Searches STORAGE folder collecting list of 'work' item folders
2. Iterates these folders completing following steps:
a. Extracts work data from folder name
b. Gets list of image file... | bfidatadigipres/BFI_scripts | born_digital_workflows/special_collections_rename_born_digital.py | .py | b6e81c6af575aabd | 8.04 | 11 |
#!/usr/bin/env python3
"""
Special Collections Digital Derivative script
Creation of Analogue and Digital Item records
Script stages:
1. Searches STORAGE folder collecting list of 'works' folders
2. Iterates these works folders completing following steps:
a. Extracts work data from folder name
b. Gets list of... | bfidatadigipres/BFI_scripts | born_digital_workflows/special_collections_rename_digital_derivatives.py | .py | 1418b397f599f0d7 | 7.04 | 11 |
#!/usr/bin/env python3
"""
Special Collections Digital Derivative script
Creation of Digital Item records only linked
to existing Analogue Items.
Script stages:
1. Searches STORAGE folder collecting list of 'analogue' item folders
2. Iterates these folders completing following steps:
a. Extracts work/item data fr... | bfidatadigipres/BFI_scripts | born_digital_workflows/special_collections_rename_partial_digital_derivatives.py | .py | d0f13ac42724649f | 7.04 | 11 |
#!/usr/bin/env python3
"""
Curatorial Donor Acquisition Rename:
*** MUST BE LAUNCHED FROM SHELL START SCRIPT ***
1. Receive list of 'workflow ****' folders at a maximum and minimum depth of 2
folders from the curatorial isilon share. Each entry is passed to this
Python script and populates sys.argv[1] with the ... | bfidatadigipres/BFI_scripts | document_en_15907/curatorial_donor_acquisition_rename.py | .py | 57d7469acbbd3d69 | 7.54 | 11 |
#!/usr/bin/ python3
"""
Script to look for files named 'EDIT_{source_item}',
create new CID item record with VIEW specifics, rename
file then move to autoingest path
NOTES: Integrated with adlib_v3 for test
2024
"""
import datetime
import logging
# Public packages
import os
import shutil
import sys
from typing imp... | bfidatadigipres/BFI_scripts | document_en_15907/document_access_edits.py | .py | 55f607d9fc50d085 | 7.54 | 11 |
#!/usr/bin/ python3
"""
Script to retrieve folders of
Film Fund different audio files named
after CID Item record object_number.
1. Looks for audio processing folders in FF_STORAGE
and find list of subfolders within, add to list
and iterate through the folder names
2. Extract object number from folder name
a... | bfidatadigipres/BFI_scripts | document_en_15907/document_augmented_filmfund_separate_audio.py | .py | fe01e2e068257880 | 7.54 | 11 |
#!/usr/bin/ python3
"""
Script to retrieve folders of
Platform timed text named after
CID Item record object_number.
1. Looks for subfolders in STORAGE path
2. Extract object number from folder name
and makes list of all files within folder
3. Iterates the enclosed files completing stages:
a/ Build dictionary f... | bfidatadigipres/BFI_scripts | document_en_15907/document_augmented_filmfund_timed_text.py | .py | 34178d3f69669da7 | 7.54 | 11 |
from __future__ import annotations # For class method return type hinting
import os
from typing import Sequence
from dotenv import load_dotenv
from sqlalchemy import (
TIMESTAMP,
Column,
Integer,
String,
create_engine,
func,
)
from sqlalchemy.orm import declarative_base, sessionmaker
from sq... | deepmodeling/LAMBench | lambench/databases/base_table.py | .py | 505e2bbe62f3c721 | 7.66 | 20 |
import logging
import numpy as np
import pandas as pd
from collections import defaultdict
from lambench.metrics.vishelper.results_fetcher import DOWNSTREAM_TASK_METRICS
from lambench.metrics.utils import NVEMD_NSTEPS
class MetricsCalculator:
def __init__(self, fetcher):
self.fetcher = fetcher
def cal... | deepmodeling/LAMBench | lambench/metrics/vishelper/metrics_calculations.py | .py | 61e7c14baedb12b1 | 7.66 | 20 |
import logging
from pathlib import Path
from typing import Optional
import yaml
import lambench
from lambench.databases.calculator_table import CalculatorRecord
from lambench.databases.direct_predict_table import DirectPredictRecord
from lambench.metrics.post_process import DIRECT_TASK_WEIGHTS
from lambench.metrics.uti... | deepmodeling/LAMBench | lambench/metrics/vishelper/results_fetcher.py | .py | 52402a6eff91350c | 7.66 | 20 |
import logging
import tempfile
from typing import ClassVar
from pydantic import BaseModel, ConfigDict
from pathlib import Path
from lambench.databases.base_table import BaseRecord
from lambench.models.basemodel import BaseLargeAtomModel
class BaseTask(BaseModel):
"""
BaseTask is a base class for defining and... | deepmodeling/LAMBench | lambench/tasks/base_task.py | .py | f2a2cf626b7cd8fe | 7.66 | 20 |
from typing import ClassVar, Optional
from pathlib import Path
from lambench.tasks.base_task import BaseTask
from lambench.databases.calculator_table import CalculatorRecord
class CalculatorTask(BaseTask):
"""
Support more general calculator tasks interfaced with ASE.
"""
record_type: ClassVar = Calc... | deepmodeling/LAMBench | lambench/tasks/calculator/calculator_tasks.py | .py | 0c36faf8bc26af1c | 7.66 | 20 |
# ruff: noqa: E402
"""
This module has been modified from MatCalc
https://github.com/materialsvirtuallab/matcalc/blob/main/src/matcalc/_elasticity.py
https://github.com/materialsvirtuallab/matcalc/blob/main/LICENSE
BSD 3-Clause License
Copyright (c) 2023, Materials Virtual Lab
Redistribution and use in source and b... | deepmodeling/LAMBench | lambench/tasks/calculator/elastic/elastic.py | .py | c3f240324d0b64c2 | 7.66 | 20 |
from ase.atoms import Atoms
from lambench.models.ase_models import ASEModel
import numpy as np
import math
def get_efv(atoms: Atoms) -> tuple[float, np.ndarray, np.ndarray]:
"""
Perform force field prediction for one system, return energy, forces and stress.
"""
e = atoms.get_potential_energy()
f ... | deepmodeling/LAMBench | lambench/tasks/calculator/inference_efficiency/efficiency_utils.py | .py | 9f8c0d4a2ac5cd89 | 7.66 | 20 |
from lambench.models.ase_models import ASEModel
from lambench.tasks.calculator.inference_efficiency.efficiency_utils import (
binary_search_max_natoms,
get_efv,
find_even_factors,
)
from ase.io import read
import logging
import time
import numpy as np
from pathlib import Path
logging.basicConfig(
level... | deepmodeling/LAMBench | lambench/tasks/calculator/inference_efficiency/inference_efficiency.py | .py | d6e24cd37be92ca7 | 7.66 | 20 |
from lambench.models.ase_models import ASEModel
from ase import Atoms
from ase.calculators.calculator import Calculator
from ase.md.verlet import VelocityVerlet
from ase.md.velocitydistribution import (
MaxwellBoltzmannDistribution,
Stationary,
ZeroRotation,
)
from ase.units import fs
import numpy as np
imp... | deepmodeling/LAMBench | lambench/tasks/calculator/nve_md/nve_md.py | .py | a36d71f39877f1db | 7.66 | 20 |
"""
Code adapted from the following paper and code:
@misc{loew2024universalmachinelearninginteratomic,
title={Universal Machine Learning Interatomic Potentials are Ready for Phonons},
author={Antoine Loew and Dewen Sun and Hai-Chen Wang and Silvana Botti and Miguel A. L. Marques},
year={2024},
... | deepmodeling/LAMBench | lambench/tasks/calculator/phonon/phonon.py | .py | 0d4c6003be8ca359 | 7.66 | 20 |
from ase import Atoms
from phonopy.structure.atoms import PhonopyAtoms
from pathlib import Path
import phonopy
# Constants unit conversion
THz_TO_K = 47.9924
def ase_to_phonopy_atoms(atoms: Atoms) -> PhonopyAtoms:
"""
Convert ASE Atoms object to PhonopyAtoms object.
"""
# Extract atomic symbols and ... | deepmodeling/LAMBench | lambench/tasks/calculator/phonon/phonon_utils.py | .py | bf0cd5658225a4c4 | 7.66 | 20 |
"""
Surface cleavage energy calculation task.
This task evaluates model performance on predicting surface cleavage energies.
Dataset is retrieved from Ardavan Mehdizadeh and Peter Schindler 2025 AI Sci. 1 025002
Only 10% of the dataset is randomly sampled for testing.
"""
import json
import logging
from pathlib imp... | deepmodeling/LAMBench | lambench/tasks/calculator/surface/surface.py | .py | c082421ed41bb323 | 7.66 | 20 |
from pathlib import Path
from typing import ClassVar, Literal
from lambench.tasks.base_task import BaseTask
from lambench.databases.direct_predict_table import DirectPredictRecord
class DirectPredictTask(BaseTask):
"""
Support direct energy force prediction for DP interface, and zero-shot energy force predici... | deepmodeling/LAMBench | lambench/tasks/direct/direct_tasks.py | .py | e51875b8175b314d | 7.66 | 20 |
import sys
import numpy as np
from cect.Cells import get_contralateral_cell
from cect.ConnectomeReader import SYMMETRY_COLORMAP
from cect import print_
import json
import matplotlib.pyplot as plt
all_sym_info = {}
def register_symmetry_info(reader, view, synclass, percentage):
if reader not in all_sym_info:
... | openworm/ConnectomeToolbox | cect/Analysis.py | .py | 721e912e91c4710a | 7.45 | 7 |
"""
This is still a work in progress...
"""
import sys
from cect import print_
from cect.Cells import COOK_GROUPING_1
from cect.Cells import get_standard_color
from matplotlib import pyplot as plt
from cect.Cells import are_bilateral_pair
from cect.Cells import is_bilateral_left
from cect.Cells import is_bilateral_ri... | openworm/ConnectomeToolbox | cect/CellAnalysis.py | .py | c980aee52c1259e2 | 7.45 | 7 |
# Reader for Cook et al 2019 data
from cect.readers.Cook2019DataReader import Cook2019DataReader
from cect.readers.Cook2019DataReader import HERMAPHRODITE
# ruff: noqa: F401
from cect.readers.Cook2019DataReader import WEIGHTS
from cect.ConnectomeDataset import get_dataset_source_on_github
from cect.ConnectomeReader... | openworm/ConnectomeToolbox | cect/readers/Cook2019HermReader.py | .py | 246ebcfa9a7c6c4c | 7.45 | 7 |
# Reader for Durbin JSH data
from cect.readers.DurbinDataReader import DurbinDataReader
from cect.readers.DurbinDataReader import JSH_L4
from cect.readers.DurbinDataReader import filename
# ruff: noqa: F401
from cect.readers.DurbinDataReader import WEIGHTS
from cect.ConnectomeDataset import get_dataset_source_on_gi... | openworm/ConnectomeToolbox | cect/readers/DurbinJSHDataReader.py | .py | 1620f9fb64233da4 | 7.45 | 7 |
# Reader for Durbin N2U data
from cect.readers.DurbinDataReader import DurbinDataReader
from cect.readers.DurbinDataReader import N2U_ADULT
from cect.readers.DurbinDataReader import filename
# ruff: noqa: F401
from cect.readers.DurbinDataReader import WEIGHTS
from cect.ConnectomeDataset import get_dataset_source_on... | openworm/ConnectomeToolbox | cect/readers/DurbinN2UDataReader.py | .py | 94ebb46ccb6a000b | 7.45 | 7 |
# Temporary class to allow this to be used in comparison notebook.
# Should be tidied up.
from cect.readers.WhiteDataReader import WhiteDataReader
from cect.ConnectomeReader import analyse_connections
from cect.ConnectomeDataset import get_dataset_source_on_github
from cect.ConnectomeDataset import LOAD_READERS_FROM_C... | openworm/ConnectomeToolbox | cect/readers/White_A.py | .py | da9c77785a55cf20 | 7.45 | 7 |
# Temporary class to allow this to be used in comparison notebook.
# Should be tidied up.
from cect.readers.WhiteDataReader import WhiteDataReader
from cect.ConnectomeReader import analyse_connections
from cect.ConnectomeDataset import get_dataset_source_on_github
from cect.ConnectomeDataset import LOAD_READERS_FROM_C... | openworm/ConnectomeToolbox | cect/readers/White_L4.py | .py | 560219e6d5a5c3e7 | 7.45 | 7 |
# Temporary class to allow this to be used in comparison notebook.
# Should be tidied up.
import os
from cect.ConnectomeDataset import (
LOAD_READERS_FROM_CACHE_BY_DEFAULT,
get_cache_filename,
get_dataset_source_on_github,
load_connectome_dataset_file,
)
from cect.ConnectomeReader import analyse_conn... | openworm/ConnectomeToolbox | cect/readers/White_whole.py | .py | d196d9d028319be1 | 7.45 | 7 |
from cect.readers.WitvlietDataReader import WitvlietDataReader
from cect.ConnectomeReader import analyse_connections
from cect.ConnectomeDataset import get_dataset_source_on_github
from cect.ConnectomeDataset import LOAD_READERS_FROM_CACHE_BY_DEFAULT
# ruff: noqa: F401
from cect.readers.WitvlietDataReader import WEIG... | openworm/ConnectomeToolbox | cect/readers/WitvlietDataReader1.py | .py | ea37fe8b6d49cebe | 7.45 | 7 |
from cect.readers.WitvlietDataReader import WitvlietDataReader
from cect.ConnectomeReader import analyse_connections
from cect.ConnectomeDataset import get_dataset_source_on_github
from cect.ConnectomeDataset import LOAD_READERS_FROM_CACHE_BY_DEFAULT
# ruff: noqa: F401
from cect.readers.WitvlietDataReader import WEIG... | openworm/ConnectomeToolbox | cect/readers/WitvlietDataReader2.py | .py | 24d781aca8a91423 | 7.45 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.