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 abc import abstractmethod
from pathlib import Path
from typing import Iterable, Union
import SimpleITK as sitk
from ..mnts_logger import MNTSLogger
__all__ = ['MNTSFilter', 'MNTSFilterPipeline', 'MNTSFilterRequireTraining']
class MNTSFilter(object):
def __init__(self):
r"""
Base class of fi... | alabamagan/mri_normalization_tools | mnts/filters/mnts_filters.py | .py | ae351ac5e8a04cf4 | 7.3 | 3 |
import pydicom
from pydicom import *
from pathlib import Path
from typing import Optional
from tqdm import auto
def remove_info(dataset,
data_element,
va_type=["PN", "LO", "SH", "AE", "DT", "DA"],
tags=[(0x0010, 0x0040), # sex
(0x0002, 0x0016) # ... | alabamagan/mri_normalization_tools | mnts/utils/dcm_anonymize.py | .py | c9c6a98c6e8cbd4a | 7.3 | 3 |
import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask.json import JSONEncoder
from datetime import datetime
import decimal
# instantiate the extensions
bootstrap = Bootstrap()
def create_app(script_info=None):
# instantiate the app
app = Flask(
__name__,
templat... | dataesr/person-matcher | project/server/__init__.py | .py | 3fc1b00aef1d3535 | 7 | 0 |
"""String utils."""
import re
import string
import unicodedata
from tokenizers import normalizers
from tokenizers.normalizers import BertNormalizer, Sequence, Strip
from tokenizers import pre_tokenizers
from tokenizers.pre_tokenizers import Whitespace
from project.server.main.logger import get_logger
logger = get_log... | dataesr/person-matcher | project/server/main/strings.py | .py | 19adcc0d31fa9588 | 7 | 0 |
# Copyright (C) 2016 - 2022 Marie E. Rognes (meg@simula.no), Jørgen S. Dokken
#
# SPDX-License-Identifier: MIT
#
# Last changed: 2022-12-12
import dolfinx
import ufl
__all__ = ["Markerwise", "rhs_with_markerwise_field"]
class Markerwise:
"""
A container class representing an object defined by a number of... | jorgensd/cbcbeatx | src/cbcbeatx/markerwisefield.py | .py | 50241f1c6bca83e9 | 7.15 | 1 |
# Copyright (C) 2013 - 2022 Johan Hake (hake@simula.no), Jørgen S. Dokken
#
# SPDX-License-Identifier: MIT
#
# Last changed: 2022-12-12
import typing
from petsc4py import PETSc
import dolfinx.fem.petsc
import numpy as np
import ufl
from .markerwisefield import Markerwise, rhs_with_markerwise_field
__all__ = ["Mo... | jorgensd/cbcbeatx | src/cbcbeatx/monodomainsolver.py | .py | f34b1e7422540a2c | 7.15 | 1 |
from mpi4py import MPI
from petsc4py import PETSc
import dolfinx
import numpy as np
import pytest
import ufl
from cbcbeatx import MonodomainSolver
class TestMonodomainSolver:
def setUp(self):
N = 5
self.mesh = dolfinx.mesh.create_unit_cube(MPI.COMM_WORLD, N, N, N)
# Create stimulus
... | jorgensd/cbcbeatx | tests/test_monodomain.py | .py | e4c82a8c1bc62f25 | 7.65 | 1 |
import smtplib, ssl
from email.message import EmailMessage
from smtplib import SMTP
import pitschi.config as config
import logging, time
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s [%(name)s] %(levelname)s : %(message)s')
logger = logging.getLogger(__name__)
def connect_smtp():
... | UQ-RCC/pitschi-xapi | pitschi/mail.py | .py | ab0485f53efaadaf | 7 | 0 |
import json
import logging
import pitschi.config as config
import pitschi.db as pdb
from pitschi.ppms import get_ppms_user, get_ppms_user_by_id, get_ppms_users, get_cores, get_system_pids, get_systems, get_projects, get_rdm_collections, get_project_members
import pitschi.mail as mail
from sqlalchemy.orm import Session
... | UQ-RCC/pitschi-xapi | pitschi/routers/ppms_utils.py | .py | aea0f7a016b281fe | 7 | 0 |
import pitschi.config as config
import datetime, pytz
import os
from chardet import detect
from random import randrange
def get_db_connection():
return (f"{config.get('database', 'type')}://"
f"{config.get('database', 'username')}:"
f"{config.get('database', 'password')}@"
f"{config.get('da... | UQ-RCC/pitschi-xapi | pitschi/utils.py | .py | bc0ecfd2345d0e7b | 7 | 0 |
from __future__ import annotations
import logging
from urllib.parse import parse_qsl
from config import LASTFM_API_KEY
from flask import (
Response,
jsonify,
redirect,
render_template,
request,
send_file,
url_for,
)
from src.main import lastfm_app
from src.utils.api import LastFmException... | soksanichenko/lastfm-userbar | sources/src/main/views.py | .py | f0ab33c998589102 | 7 | 0 |
from __future__ import annotations
import logging
import os
from io import BytesIO
from config import LASTFM_API_KEY, PATH_TO_FONT
from PIL import Image, ImageDraw, ImageFont
from src.main import lastfm_app
from src.utils.api import LastFmException, User
logger = logging.getLogger(__name__)
RGBColor = tuple[int, i... | soksanichenko/lastfm-userbar | sources/src/utils/main.py | .py | 1f9d789edc9c9c9e | 7 | 0 |
from __future__ import annotations
from collections.abc import Callable
from functools import wraps
from typing import Any
from flask import make_response
def nocache(view: Callable[..., Any]) -> Callable[..., Any]:
"""Decorator that adds no-cache headers to any Flask view response."""
@wraps(view)
def... | soksanichenko/lastfm-userbar | sources/src/utils/nocache.py | .py | 1acb5e29cdc31422 | 7 | 0 |
from __future__ import annotations
def parse_color_string(color: str) -> tuple[int, int, int]:
"""Parse an underscore-separated RGB string into a tuple.
Args:
color: Color encoded as 'R_G_B' (e.g. '255_128_0').
Returns:
RGB tuple of ints.
Raises:
ValueError: If the string is... | soksanichenko/lastfm-userbar | sources/src/utils/utils.py | .py | 77539e3a48bafbc3 | 7 | 0 |
#!/usr/bin/env python3
"""
Example: Running orchestration with token awareness
This script demonstrates how to run the parallel orchestration
with proper token tracking and configuration.
"""
import asyncio
import os
from src.agentic.flow import parallel_orchestration_flow, weekly_content_flow
def calculate_estimate... | mekitmedia/cncf-landscape-a-to-z | examples/orchestration_token_aware.py | .py | 424516499e25b9bf | 7.15 | 1 |
import os
from pydantic_ai.models.google import GoogleModel
from src.config import load_config
def get_model(agent_name: str):
"""Get the model for a specific agent based on configuration."""
cfg = load_config()
# Priority:
# 1. Agent-specific model in config.yaml
# 2. Global default_model in ... | mekitmedia/cncf-landscape-a-to-z | src/agentic/config.py | .py | e5af3bbd76b8867f | 7.15 | 1 |
import asyncio
import os
import glob
from typing import List, Optional
from pydantic import BaseModel, Field
from pydantic_ai import Agent
from src.agentic.models import ProjectMetadata, BlogPostDraft
from src.agentic.config import get_model
import logging
# Setup logger
logger = logging.getLogger(__name__)
# Judge M... | mekitmedia/cncf-landscape-a-to-z | src/agentic/evals.py | .py | 9cd2e58d3158366e | 7.15 | 1 |
import os
import glob
from pydantic_ai import RunContext
from src.config import week_id
from src.agentic.deps import AgentDeps
def check_week_status(ctx: RunContext[AgentDeps], week_letter: str) -> str:
"""Checks if the blog post for the given week letter exists."""
# Validate input to prevent path traversal
... | mekitmedia/cncf-landscape-a-to-z | src/agentic/tools/editor.py | .py | de9eee4d616939fd | 7.15 | 1 |
from pydantic_ai import RunContext
from pydantic import BaseModel, Field
from src.tracker import get_tracker, TaskStatus, ReadyTask
from src.agentic.deps import AgentDeps
import logging
from typing import List
logger = logging.getLogger(__name__)
def update_tracker_status(ctx: RunContext[AgentDeps], item_name: str, t... | mekitmedia/cncf-landscape-a-to-z | src/agentic/tools/tracker.py | .py | f5540a72c5a7d090 | 7.15 | 1 |
import fire
import asyncio
import logging
import os
from src.pipeline.runner import run_etl
from src.agentic.observability import setup_observability
# Setup logger
logger = logging.getLogger(__name__)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
cla... | mekitmedia/cncf-landscape-a-to-z | src/cli.py | .py | 21ad589e0758cf51 | 7.15 | 1 |
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Optional
import os
import tempfile
from functools import lru_cache
import yaml
def _repo_root() -> Path:
"""Return the repository root (one level above src/)."""
return Path(__file__).... | mekitmedia/cncf-landscape-a-to-z | src/config.py | .py | cf26b7424571212e | 7.15 | 1 |
import yaml
from pathlib import Path
from src.config import load_config, resolve_data_dirs, week_id
from src.logger import get_logger
import jinja2
logger = get_logger(__name__)
def to_yaml(data: dict, path: str):
"""
This function saves a dictionary to a yaml file
"""
logger.info(f"Saving data to {pa... | mekitmedia/cncf-landscape-a-to-z | src/pipeline/load.py | .py | 67784b5ca62e92b8 | 7.15 | 1 |
from src.logger import get_logger
import yaml
from pathlib import Path
from src.config import load_config
def _get_overlay_data() -> dict:
config = load_config()
overlay_path = config.data_dir / "overlay" / "overlay.yaml"
if overlay_path.exists():
with open(overlay_path, 'r') as f:
ret... | mekitmedia/cncf-landscape-a-to-z | src/pipeline/transform.py | .py | f763be453ba1e680 | 7.15 | 1 |
"""Task type configuration and definitions."""
from typing import List, Optional
from pydantic import BaseModel, Field
class TaskTypeConfig(BaseModel):
"""Configuration for a task type."""
name: str = Field(description="Unique name of the task type")
depends_on: List[str] = Field(default_factory=list, de... | mekitmedia/cncf-landscape-a-to-z | src/tracker/config.py | .py | 63cb873eaeb8ce34 | 7.15 | 1 |
"""Pydantic models for task tracking."""
from enum import Enum
from typing import Dict, Optional, Any
from datetime import datetime
from pydantic import BaseModel, Field, ConfigDict
class TaskStatus(str, Enum):
"""Status of a task."""
PENDING = "pending"
IN_PROGRESS = "in_progress"
COMPLETED = "compl... | mekitmedia/cncf-landscape-a-to-z | src/tracker/models.py | .py | 0f8763d1b7db3f01 | 7.15 | 1 |
"""
Tests for parallel orchestration flow with iteration control.
Tests simulate orchestration with configurable iterations to verify:
1. Token tracking accuracy
2. Early exit behavior
3. Task batch sizing
4. Dependency graph enforcement
"""
import pytest
import asyncio
import sys
from pathlib import Path
from unitte... | mekitmedia/cncf-landscape-a-to-z | tests/test_orchestration_iterations.py | .py | 6b98029880b592d4 | 7.65 | 1 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
from datetime import date
from pydantic import field_validator
from pydantic_core import PydanticCustomError
from etl_entities.hwm.column.column_hwm import ColumnHWM
from etl_entities.hwm.hwm_type_registry import register_hwm_type
... | MTSWebServices/etl-entities | etl_entities/hwm/column/date_hwm.py | .py | b8c6c105680282e9 | 7.39 | 5 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
from datetime import datetime
from pydantic import field_validator
from pydantic_core import PydanticCustomError
from etl_entities.hwm.column.column_hwm import ColumnHWM
from etl_entities.hwm.hwm_type_registry import register_hwm_ty... | MTSWebServices/etl-entities | etl_entities/hwm/column/datetime_hwm.py | .py | 4fe7e8b58c7fcc77 | 7.39 | 5 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
from decimal import Decimal, InvalidOperation
from pydantic import StrictInt, field_validator
from etl_entities.hwm.column.column_hwm import ColumnHWM
from etl_entities.hwm.hwm_type_registry import register_hwm_type
@register_hwm_... | MTSWebServices/etl-entities | etl_entities/hwm/column/int_hwm.py | .py | 6286c6cb05867280 | 7.39 | 5 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
from abc import abstractmethod
from typing import Any, Generic, TypeVar
from pydantic import ConfigDict, Field, field_validator
from etl_entities.hwm.file.absolute_path import AbsolutePath, parse_absolute_path
from etl_entities.hwm.... | MTSWebServices/etl-entities | etl_entities/hwm/file/file_hwm.py | .py | 50655d85c9ce857d | 7.39 | 5 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
import sys
from abc import abstractmethod
from copy import deepcopy
from datetime import datetime
from typing import Any, Generic, TypeVar
from pydantic import ConfigDict, Field
from etl_entities.entity import BaseModel
from etl_ent... | MTSWebServices/etl-entities | etl_entities/hwm/hwm.py | .py | 9155153dcb4cd042 | 7.39 | 5 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
from typing import TYPE_CHECKING, ClassVar
if TYPE_CHECKING:
from etl_entities.hwm.hwm import HWM
class HWMTypeRegistry:
"""Registry class for HWM types"""
_name_to_type: ClassVar[dict[str, type["HWM"]]] = {}
_type... | MTSWebServices/etl-entities | etl_entities/hwm/hwm_type_registry.py | .py | e659ce859c232d70 | 7.39 | 5 |
# SPDX-FileCopyrightText: 2024-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
import sys
from typing import Generic, TypeVar
from pydantic import Field, field_validator
from etl_entities.hwm.hwm import HWM
if sys.version_info < (3, 11):
from typing_extensions import Self
else:
from typing import Self... | MTSWebServices/etl-entities | etl_entities/hwm/key_value/key_value_hwm.py | .py | 2083fafe46458201 | 7.39 | 5 |
# SPDX-FileCopyrightText: 2024-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
import sys
from collections.abc import Mapping
from pydantic import field_validator
from etl_entities.hwm.hwm_type_registry import HWMTypeRegistry, register_hwm_type
from etl_entities.hwm.key_value.key_value_hwm import KeyValueHWM
... | MTSWebServices/etl-entities | etl_entities/hwm/key_value/key_value_int_hwm.py | .py | f503921b729282d6 | 7.39 | 5 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
import logging
from abc import ABC, abstractmethod
from typing import Any
from etl_entities.entity import BaseModel
from etl_entities.hwm import HWM
log = logging.getLogger(__name__)
class BaseHWMStore(BaseModel, ABC):
def __e... | MTSWebServices/etl-entities | etl_entities/hwm_store/base_hwm_store.py | .py | 62e6830afa88b334 | 7.39 | 5 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
from typing import TYPE_CHECKING, ClassVar, TypeVar
from etl_entities.hwm_store.base_hwm_store import BaseHWMStore
if TYPE_CHECKING:
from collections.abc import Collection
T = TypeVar("T", bound=BaseHWMStore)
class HWMStoreCl... | MTSWebServices/etl-entities | etl_entities/hwm_store/hwm_store_class_registry.py | .py | ad8238a9eafd22fe | 7.39 | 5 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
from collections.abc import Callable, Mapping, Sequence
from functools import wraps
from typing import Any
from etl_entities.hwm_store.hwm_store_class_registry import HWMStoreClassRegistry
def parse_config(value: Any, key: str) -> ... | MTSWebServices/etl-entities | etl_entities/hwm_store/hwm_store_detect.py | .py | bd627a08d7faa917 | 7.39 | 5 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
from collections import deque
from typing import ClassVar
from etl_entities.hwm_store.base_hwm_store import BaseHWMStore
from etl_entities.hwm_store.hwm_store_class_registry import HWMStoreClassRegistry
class HWMStoreStackManager:
... | MTSWebServices/etl-entities | etl_entities/hwm_store/hwm_store_stack_manager.py | .py | 4dbfa6754892e06d | 7.39 | 5 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
from pydantic import ConfigDict, PrivateAttr
from etl_entities.hwm import HWM
from etl_entities.hwm.hwm_type_registry import HWMTypeRegistry
from etl_entities.hwm_store.base_hwm_store import BaseHWMStore
from etl_entities.hwm_store.h... | MTSWebServices/etl-entities | etl_entities/hwm_store/memory_hwm_store.py | .py | 32b6bb29c6aa11e9 | 7.39 | 5 |
# SPDX-FileCopyrightText: 2023-present MTS PJSC
# SPDX-License-Identifier: Apache-2.0
import inspect
import logging
import textwrap
from importlib_metadata import EntryPoint, entry_points
from etl_entities.version import __version__
log = logging.getLogger(__name__)
def _prepare_error_msg(plugin_name: str, package... | MTSWebServices/etl-entities | etl_entities/plugins/import_plugins.py | .py | 8bdfa90c229b4d3e | 7.39 | 5 |
#!/usr/bin/env python3
"""
SCORE to Kubernetes Manifest Generator for Fawkes
This script translates score.yaml workload specifications into Kubernetes manifests.
It serves as a reference implementation and bridge to the official score-k8s tool.
Usage:
python generator.py --score score.yaml --environment dev --out... | paruff/fawkes | charts/score-transformer/generator.py | .py | f9b2d2561d2242b0 | 7.3 | 3 |
"""
Integration with docker-compose
"""
import sys
from os import environ
from pathlib import Path
from time import sleep
from typing import Callable, Optional
import click
import typer
from typer import Context, Typer
from macrostrat.utils import get_logger
from .base import check_status, compose
from .follow_logs ... | UW-Macrostrat/python-libraries | app-frame/macrostrat/app_frame/compose/__init__.py | .py | d8c0b07762b98e61 | 7 | 0 |
from rich.console import Console
from macrostrat.utils import cmd, get_logger
console = Console()
log = get_logger(__name__)
def compose(*args, **kwargs):
"""Run docker compose commands in the appropriate context"""
return cmd("docker", "compose", *args, **kwargs)
def check_status(app_name: str, command_... | UW-Macrostrat/python-libraries | app-frame/macrostrat/app_frame/compose/base.py | .py | 9295f03699c3213e | 7 | 0 |
# Typer command-line application
from functools import update_wrapper
from os import environ
from typing import Optional
from typer import Context, Option, rich_utils
from typer.models import TyperInfo
from macrostrat.utils import get_logger
from .core import Application
from .utils import CommandBase, ControlComman... | UW-Macrostrat/python-libraries | app-frame/macrostrat/app_frame/control_command.py | .py | 5917dbb3c7c9a66f | 7 | 0 |
from typing import Optional
from ..exc import ApplicationError
class ApplicationBase:
name: str
command_name: str
app_module: Optional[str]
class SubsystemError(ApplicationError):
pass
class Subsystem:
"""A base subsystem
app_version can be set to a specifier of valid versions of the host... | UW-Macrostrat/python-libraries | app-frame/macrostrat/app_frame/subsystems/defs.py | .py | bf7fb16b17755f6a | 7 | 0 |
"""Utilities for Typer and Click command-line interfaces."""
from os import environ
from typing import List, Optional
import typer
from click import Parameter
from typer import Context, Typer
from typer.core import TyperGroup
from macrostrat.utils import get_logger
log = get_logger(__name__)
DELIMITER = ", "
cla... | UW-Macrostrat/python-libraries | app-frame/macrostrat/app_frame/utils/__init__.py | .py | 6cca1999e10f3ed5 | 7 | 0 |
import datetime
from contextvars import ContextVar
from typing import Optional
from sqlalchemy import Engine, select, update
from sqlalchemy.orm import Session, declarative_base, sessionmaker
from macrostrat.database import Database
from .schema import Token
def get_access_token(token: str):
"""The sole databa... | UW-Macrostrat/python-libraries | auth-system/macrostrat/auth_system/core/database.py | .py | 33c43161dd7593da | 7 | 0 |
import os
from typing import Annotated, Optional
import bcrypt
from fastapi import Depends, HTTPException, Request
from fastapi.security import (
HTTPAuthorizationCredentials,
HTTPBearer,
OAuth2AuthorizationCodeBearer,
)
from fastapi.security.utils import get_authorization_scheme_param
from jose import JWT... | UW-Macrostrat/python-libraries | auth-system/macrostrat/auth_system/core/main.py | .py | 034581d86a288c8c | 7 | 0 |
"""
JSON Web Token authentication.
"""
import time
import warnings
from typing import Any, Tuple
import jwt
from starlette.authentication import (
AuthCredentials,
AuthenticationBackend,
AuthenticationError,
BaseUser,
SimpleUser,
UnauthenticatedUser,
)
from starlette.requests import Request
fr... | UW-Macrostrat/python-libraries | auth-system/macrostrat/auth_system/legacy/backend.py | .py | 62679364f3c53f09 | 7 | 0 |
from warnings import warn
import psycopg.sql as psql3
import psycopg2.sql as psql2
def update_legacy_identifier(identifier):
"""
For backwards compatibility with current code, we need to map psycopg2 identifiers to their equivalents in psycopg3,
while printing a warning that the mapping is deprecated.
... | UW-Macrostrat/python-libraries | database/macrostrat/database/compat.py | .py | 72aa5ca18b7bb1e2 | 7 | 0 |
import warnings
from contextlib import contextmanager
from pathlib import Path
from typing import Optional, Union
from psycopg.errors import InvalidSavepointSpecification
from psycopg.sql import Identifier
from sqlalchemy import URL, Engine, MetaData, inspect
from sqlalchemy.exc import IntegrityError, OperationalError... | UW-Macrostrat/python-libraries | database/macrostrat/database/core.py | .py | 8207bc08fe7395dc | 7 | 0 |
from warnings import warn
# Drag in geographic types for database reflection
from geoalchemy2 import Geography, Geometry
from sqlalchemy.ext.automap import generate_relationship
from macrostrat.database.utils import reflect_table
from macrostrat.utils.logs import get_logger
from .cache import DatabaseModelCache
from... | UW-Macrostrat/python-libraries | database/macrostrat/database/mapper/__init__.py | .py | 61a64bed0abd6b5e | 7 | 0 |
from .utils import primary_key
class ModelHelperMixins:
"""
Standard mixins for database models
"""
loaded_from_cache = False
def to_dict(self):
res = {}
for k, v in self.__table__.c.items():
res[k] = getattr(self, k)
return res
def __repr__(self):
... | UW-Macrostrat/python-libraries | database/macrostrat/database/mapper/base.py | .py | e8a1087847e07f4a | 7 | 0 |
def primary_key(instance):
"""Get primary key properties for a SQLAlchemy model.
:param model: SQLAlchemy model class
"""
mapper = instance.__class__.__mapper__
prop_list = [mapper.get_property_by_column(column) for column in mapper.primary_key]
return {prop.key: getattr(instance, prop.key) for ... | UW-Macrostrat/python-libraries | database/macrostrat/database/mapper/utils.py | .py | 9c77d0f852c4f7c8 | 7 | 0 |
import asyncio
import sys
import zlib
from aiofiles.threadpool import AsyncBufferedIOBase
from macrostrat.utils import get_logger
from .utils import console
log = get_logger(__name__)
async def print_stream_progress(
input: asyncio.StreamReader | asyncio.subprocess.Process,
out_stream: asyncio.StreamWrite... | UW-Macrostrat/python-libraries | database/macrostrat/database/transfer/stream_utils.py | .py | 0441d12009e191a5 | 7 | 0 |
from urllib.parse import quote
from rich.console import Console
from sqlalchemy.engine import Engine
from sqlalchemy.engine.url import URL
from sqlalchemy_utils import create_database, database_exists, drop_database
from macrostrat.utils import ApplicationError, get_logger
console = Console()
log = get_logger(__nam... | UW-Macrostrat/python-libraries | database/macrostrat/database/transfer/utils.py | .py | d6295415a06710a8 | 7 | 0 |
from contextlib import contextmanager
from time import sleep
from typing import Union
from uuid import uuid4
from warnings import warn
from click import echo
from psycopg.errors import AdminShutdown
from psycopg.sql import Identifier
from sqlalchemy import MetaData
from sqlalchemy import create_engine as base_create_e... | UW-Macrostrat/python-libraries | database/macrostrat/database/utils.py | .py | cc848b28501d8f4d | 7 | 0 |
"""Tests for reset_sequence and serial_to_identity functionality."""
from pytest import fixture, raises
from macrostrat.database import Database
from macrostrat.database.sequences import (
ConvertToIdentityResult,
ResetSequenceResult,
reset_sequence,
serial_to_identity,
)
from macrostrat.database.util... | UW-Macrostrat/python-libraries | database/tests/test_sequences.py | .py | aa59d8b7211b6a8b | 7.5 | 0 |
"""
Tests for functionality to create temporary databases
"""
from pytest import mark
from sqlalchemy_utils import database_exists
from macrostrat.database.query import run_query
from macrostrat.database.utils import temporary_database, template_database
@mark.parametrize("force_drop", [True, False])
def test_temp_... | UW-Macrostrat/python-libraries | database/tests/test_temp_database.py | .py | 4f11d763a63770a9 | 7.5 | 0 |
#!/usr/bin/env python3
"""Convertors
File storing functions for encoding and decoding messages into/from images
--------
Version: 1.0
------------
----------
Since: 1.0
----------
---------------
Author: Karafra
---------------
"""
# region Imports
import logging
from typing import Optional
import cv2
from simple_... | karafra/steg-utility | simple_steganography/convert.py | .py | 9a53b93ddc55c8fe | 7.39 | 5 |
#!/usr/bin/env python3
"""Decorator for arguments which can not be null.
----------
Since:
1.0
----------
------------
Version:
1.0
------------
---------------
Author:
Karafra
---------------
"""
# region Imports
import logging
# endregion
# region Constants
LOGGER = logging.getLogger(__name__)
# endregion
... | karafra/steg-utility | simple_steganography/decorators/notNone.py | .py | a49efeae008064aa | 7.39 | 5 |
#!/usr/bin/env python3
"""Type representing modes in which can be script run.
----------
Since:
1.0
----------
------------
Version:
1.0
------------
---------------
Author:
Karafra
---------------
"""
# region Imports
from enum import Enum
# endregion
# region Logic
class Modes(Enum):
"""
----------
Mo... | karafra/steg-utility | simple_steganography/types/Modes.py | .py | b7b70c5d0be5bb74 | 7.39 | 5 |
import unittest
from mockito import mock
import numpy as np
from simple_steganography.utilities.binary import message2binary
class Test_message2binary(unittest.TestCase):
def test_should_convert_string_to_binary(self):
"""Should convert string to binary"""
# Given
# When
result = message2binary("... | karafra/steg-utility | test/unit/utilities/TestBinary.py | .py | f4daa0532e94a0cb | 7.89 | 5 |
import unittest
from mockito import mock, when
from simple_steganography.utilities.stegUtils import verify_payload
class Test_verify_payload(unittest.TestCase):
def test_should_not_allow_None_payload(self):
"""Should not allow None as payload"""
# Given
img = mock()
# When
with self.assertR... | karafra/steg-utility | test/unit/utilities/TestStegUtils.py | .py | fa5a5a501f0511c7 | 7.89 | 5 |
import os
import subprocess
import random
import logging
import json
from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode
from typing import Tuple, Optional
from daphne.messages import HtmlMessage, author_tag
logger = logging.getLogger(__name__)
USER_AGENTS = [
"Mozilla/5.0 (Windows NT 10.0; Win64... | azusachino/daphne | src/daphne/downloader.py | .py | a0608f0831b194dc | 7.24 | 2 |
import os
import subprocess
import logging
logger = logging.getLogger(__name__)
# gallery-dl writes arbitrary image types; we only forward the ones Telegram can
# render as a photo/media group.
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp"}
# Telegram caps a single media group at 10 items.
MEDIA_GRO... | azusachino/daphne | src/daphne/gallery.py | .py | c8fef9f1bcdedae2 | 7.24 | 2 |
import asyncio
import re
import os
import httpx
import tempfile
import logging
from telegram import Update
from telegram.ext import ContextTypes
from daphne.messages import HtmlMessage, PARSE_MODE_HTML, author_tag, sender_attribution
from daphne.twitter import send_photos, try_delete_message
from daphne.downloader imp... | azusachino/daphne | src/daphne/instagram.py | .py | b79aa2dafa52e140 | 7.24 | 2 |
import os
import sys
import logging
import argparse
# Setup basic logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger("daphne.main")
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(lo... | azusachino/daphne | src/daphne/main.py | .py | ad42b8e045436d30 | 7.24 | 2 |
import os
import time
from typing import List, Dict, Optional
# Use the locally cached embedding model; skip Hugging Face Hub checks on every run.
os.environ.setdefault("HF_HUB_OFFLINE", "1")
os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")
import chromadb
from chromadb.utils import embedding_functions
from... | ralfzosel/zk-smart-search | indexer.py | .py | c289d4ed1af5483a | 7.3 | 3 |
#!/usr/bin/env python3
"""
MCP Server for zk-smart-search.
Exposes Zettelkasten search functionality to AI assistants.
"""
import asyncio
import sys
import os
from unittest.mock import MagicMock, patch
from typing import Any, List, Dict
# Quiet noisy ML/HF tooling before those libraries are imported. This only
# reduc... | ralfzosel/zk-smart-search | mcp_server.py | .py | 0003d57aa436b85d | 7.3 | 3 |
import unittest
import os
import sys
from unittest.mock import MagicMock, patch, mock_open
# Add parent directory to path so we can import modules
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Mock external ML libraries BEFORE importing indexer
sys.modules['chromadb'] = MagicMock()
sy... | ralfzosel/zk-smart-search | tests/test_indexer.py | .py | 52ef1d8d1f85add3 | 7.8 | 3 |
import unittest
import sys
import os
import asyncio
from unittest.mock import patch, MagicMock
# Add parent directory to path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from mcp_server import list_tools, call_tool
class TestMCPServerIntegration(unittest.TestCase):
def test_list_... | ralfzosel/zk-smart-search | tests/test_mcp_integration.py | .py | 525112c86f3f65aa | 7.8 | 3 |
import pytest
import asyncio
from unittest.mock import patch, MagicMock
from zkss_markdown import convert_rich_to_markdown
from mcp_server import perform_keyword_search, perform_semantic_search, read_note_content, format_note_hit
def test_convert_rich_to_markdown_basic():
"""Test basic green (stripped) and yellow ... | ralfzosel/zk-smart-search | tests/test_mcp_output.py | .py | fa141a4f28ba804a | 7.8 | 3 |
import unittest
import os
import sys
from unittest.mock import MagicMock, patch, mock_open
# Add parent directory to path so we can import zkss
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from zkss import ZKSearcher
from settings import DEFAULT_RESULTS
class TestZKSearcher(unittest.T... | ralfzosel/zk-smart-search | tests/test_zkss.py | .py | c913fe385a0d161f | 7.8 | 3 |
import os
import re
import sys
import argparse
from typing import List, Callable, Optional
from rich.console import Console
from rich import print
from settings import ZK_BASE_DIR, ENDING, DEFAULT_RESULTS
class ZKSearcher:
SPLIT_CHARACTERS = r"[ \.,\[\]\(\)\n]"
def __init__(self, base_dir: str = ZK_BASE_DIR... | ralfzosel/zk-smart-search | zkss.py | .py | 35c39dc1706da00f | 7.3 | 3 |
import json
import shlex
import subprocess
import sys
from collections import OrderedDict
from typing import Any
def json_line(line: str) -> dict[str, Any]:
"""
Format str line to str that can be parsed with json.
In case line is not formatted for json for example:
'{"title": "Revert "feat: Use git c... | myk-org/github-webhook-server | scripts/generate_changelog.py | .py | 83f40dcdca2fdf23 | 7.15 | 1 |
from __future__ import annotations
from typing import Any
from pi_sidecar_client import AIResult, call_ai_once, check_sidecar_available
__all__ = ["AIResult", "call_ai", "get_ai_config"]
async def call_ai(
prompt: str,
ai_provider: str,
ai_model: str,
cwd: str,
timeout_minutes: int | None = Non... | myk-org/github-webhook-server | webhook_server/libs/ai_cli.py | .py | 71ffe428bbd68318 | 7.15 | 1 |
import os
from logging import Logger
from typing import Any
import github
import yaml
from github.GithubException import UnknownObjectException
from simple_logger.logger import get_logger
from webhook_server.utils.constants import CONFIGURABLE_LABEL_CATEGORIES
class Config:
def __init__(
self,
l... | myk-org/github-webhook-server | webhook_server/libs/config.py | .py | 327f7b812e3af94c | 7.15 | 1 |
import asyncio
from typing import TYPE_CHECKING
import webcolors
from github.GithubException import UnknownObjectException
from github.PullRequest import PullRequest
from github.Repository import Repository
from timeout_sampler import TimeoutWatch
from webhook_server.libs.handlers.owners_files_handler import OwnersFi... | myk-org/github-webhook-server | webhook_server/libs/handlers/labels_handler.py | .py | 5c3b377920c41182 | 7.15 | 1 |
import json
import logging as python_logging
import os
from dataclasses import dataclass
from datetime import datetime, timedelta
from pathlib import Path
from unittest.mock import Mock
import pytest
import yaml
from starlette.datastructures import Headers
from webhook_server.libs.handlers.owners_files_handler import... | myk-org/github-webhook-server | webhook_server/tests/conftest.py | .py | 4e9c4345bf05c969 | 7.65 | 1 |
"""Utility functions for E2E testing infrastructure.
This module provides utility functions for managing the E2E testing infrastructure:
- Smee client lifecycle management
- Docker Compose container lifecycle management
- Container health monitoring
"""
import json
import subprocess
from simple_logger.logger import ... | myk-org/github-webhook-server | webhook_server/tests/e2e/server_utils.py | .py | 03082f6607785911 | 7.65 | 1 |
"""Tests for webhook_server.libs.ai_cli module."""
from __future__ import annotations
from webhook_server.libs.ai_cli import get_ai_config
class TestGetAiConfig:
"""Test suite for get_ai_config function."""
def test_get_ai_config_returns_tuple(self) -> None:
result = get_ai_config({"ai-provider": "... | myk-org/github-webhook-server | webhook_server/tests/test_ai_cli.py | .py | b6f7ffac32313651 | 7.65 | 1 |
"""Tests for comment_utils module."""
from webhook_server.utils.comment_utils import comment_with_details
class TestCommentWithDetails:
"""Test suite for comment_with_details function."""
def test_basic_comment_formatting(self) -> None:
"""Test basic comment with simple title and body."""
re... | myk-org/github-webhook-server | webhook_server/tests/test_comment_utils.py | .py | 06f038cde9764b8d | 7.65 | 1 |
"""Tests for custom exceptions."""
import pytest
from webhook_server.libs.exceptions import (
NoApiTokenError,
RepositoryNotFoundInConfigError,
)
def test_repository_not_found_error():
"""Test RepositoryNotFoundInConfigError can be raised."""
with pytest.raises(RepositoryNotFoundInConfigError):
... | myk-org/github-webhook-server | webhook_server/tests/test_exceptions.py | .py | 18d5270c460788ba | 7.65 | 1 |
from qcodes import Instrument, InstrumentChannel
from ctypes import *
import os
class ATTENVaunixChannel(InstrumentChannel):
def __init__(self, parent:Instrument, name:str, index:int) -> None:
super().__init__(parent, name)
self._index = index
self._parent = parent
self.add_paramet... | sqdlab/SQDToolz | sqdtoolz/Drivers/ATTEN_Vaunix.py | .py | 21e3c4c8345156fb | 7.35 | 4 |
import RPi.GPIO as GPIO
import time
import os
"""
Classes for Device Management
"""
class Device() :
"""
Class that contains all functions to interface with a device
over a serial port
"""
def __init__(self, pins = None) :
"""
Class constructor
@param pins: list of GPIO pins... | sqdlab/SQDToolz | sqdtoolz/Drivers/Dependencies/RPi_gpio_interface.py | .py | c04569c0f47e94ab | 7.35 | 4 |
import serial
import time
import os
"""
Classes for Device Management
"""
class Device() :
"""
Class that contains all functions to interface with a device
over a serial port
"""
def __init__(self, comPort) :
self._ser = self.setup_serial(comPort)
def setup_serial(self, com = "/dev... | sqdlab/SQDToolz | sqdtoolz/Drivers/Dependencies/RPi_serial_interface.py | .py | 1f844635c36c7161 | 7.35 | 4 |
from qcodes import Instrument, InstrumentChannel, VisaInstrument, validators as vals
from sqdtoolz.Drivers.MWS_WFSynthHDProV2 import MWS_WFSynthHDProV2, MWS_WFSynthHDProV2_Channel
import re
class MWS_WFSynthHDProV2_RPi_Device(MWS_WFSynthHDProV2):
"""
Driver for the Windfreak SynthHD PRO v2.
"""
def __i... | sqdlab/SQDToolz | sqdtoolz/Drivers/MWS_WFSynthHDProV2_RPi.py | .py | 945d73f1634c29c3 | 7.35 | 4 |
from qcodes import Instrument, InstrumentChannel, VisaInstrument, validators as vals
import numpy as np
class SMU_B2901A(VisaInstrument):
"""This class represents and controls a Keysight B2901A SMU. For operating
details of this instrument, refer to Keysight document B2910-90030, titled
"Keysight B2900 SC... | sqdlab/SQDToolz | sqdtoolz/Drivers/SMU_B2901A.py | .py | 50771c32f7745d79 | 7.35 | 4 |
from qcodes import VisaInstrument
from qcodes.utils import validators as vals
import time
class SW_BJT_RPi(VisaInstrument):
"""
RPi Driver for switch
P0 is dedicated state for reset, do not overwrite
"""
def __init__(self, name, address, \
pins = {"P0" : 10, "P1" : 3, "P2" : 5, "P3" : 7, "P... | sqdlab/SQDToolz | sqdtoolz/Drivers/SW_BJT_RPi.py | .py | 56386e59d42b7a6e | 7.35 | 4 |
from qcodes import Instrument, InstrumentChannel, VisaInstrument
from qcodes.utils import validators as vals
import time
class SW_BJT_RPi_Multi_Channel(InstrumentChannel):
def __init__(self, parent:Instrument, sw_num, leName, pins) -> None:
super().__init__(parent, leName)
self._parent = parent
... | sqdlab/SQDToolz | sqdtoolz/Drivers/SW_BJT_RPi_Multi.py | .py | 2b1c5452b58db114 | 7.35 | 4 |
from qcodes import Instrument, InstrumentChannel, VisaInstrument
from qcodes.utils import validators as vals
import time
class SW_RFSwitchController_CryoRadiall_Channel(InstrumentChannel):
def __init__(self, parent:Instrument, sw_num, leName, switch_type) -> None:
super().__init__(parent, leName)
s... | sqdlab/SQDToolz | sqdtoolz/Drivers/SW_RFSwitchController_CryoRadiall.py | .py | 9442194d55f7eb0d | 7.35 | 4 |
from qcodes import VisaInstrument
from sqdtoolz.Drivers.SW_BJT_RPi import SW_BJT_RPi
import time
class SW_RpiIQBox(SW_BJT_RPi):
"""
RPi Driver for switch
P0 is dedicated state for reset, do not overwrite
"""
def __init__(self, name, address, **kwargs):
self._GPIO_LED = 16
super().__... | sqdlab/SQDToolz | sqdtoolz/Drivers/SW_RpiIQBox.py | .py | 3f025fc15535cd45 | 7.35 | 4 |
from qcodes import Instrument, InstrumentChannel, VisaInstrument, validators as vals
from functools import partial
import serial
import datetime
class THERM_TC0309_Channel(InstrumentChannel):
def __init__(self, parent:Instrument, name:str, chan_ind) -> None:
super().__init__(parent, name)
self._par... | sqdlab/SQDToolz | sqdtoolz/Drivers/THERM_TC0309.py | .py | c99f95f2946d872e | 7.35 | 4 |
from __future__ import annotations
import functools
import re
import requests
from bs4 import BeautifulSoup, ResultSet
from kubernetes.dynamic import DynamicClient
from ocp_resources.cluster_version import ClusterVersion
from semver import Version
from simple_logger.logger import get_logger
from ocp_utilities.except... | RedHatQE/openshift-python-utilities | ocp_utilities/cluster_versions.py | .py | 43860f3e16dfb4c9 | 7 | 0 |
import os
from web_pdb import WebPdb
class WebDebugger(WebPdb):
"""
Project home:
https://github.com/romanvm/python-web-pdb
port 1212 (default) needs to be export in the docker container
To set different port export os environment PYTHON_REMOTE_DEBUG_PORT
Usage:
pytest --pdbcls=... | RedHatQE/openshift-python-utilities | ocp_utilities/debugger.py | .py | 7670393b0cc12df6 | 7 | 0 |
from __future__ import annotations
import base64
import importlib
import json
import os
import re
import shlex
from typing import Any
import urllib3
from deprecation import deprecated
from kubernetes.dynamic import DynamicClient
from kubernetes.dynamic.exceptions import ResourceNotFoundError
from ocp_resources.image_... | RedHatQE/openshift-python-utilities | ocp_utilities/infra.py | .py | 0db57c9166172a2e | 7 | 0 |
from __future__ import annotations
import json
import re
from json import JSONDecodeError
from typing import Any
import requests
from kubernetes.dynamic import DynamicClient
from ocp_resources.resource import get_client
from ocp_resources.route import Route
from simple_logger.logger import get_logger
from timeout_sam... | RedHatQE/openshift-python-utilities | ocp_utilities/monitoring.py | .py | 37854aab4f5f52ad | 7 | 0 |
import os
import shlex
import shutil
from pathlib import Path
from pyhelper_utils.shell import run_command
from simple_logger.logger import get_logger
LOGGER = get_logger(name=__name__)
def run_must_gather(
image_url: str = "",
target_base_dir: str = "",
kubeconfig: str = "",
skip_tls_check: bool = ... | RedHatQE/openshift-python-utilities | ocp_utilities/must_gather.py | .py | e31b15c75acad364 | 7 | 0 |
import sys
import os
import pwd
import grp
import subprocess
import configparser
import re
import json
def _stop_with_error(message):
sys.stderr.write(f"ERROR: {message}\n")
sys.exit(1)
def _parse_config(file_name, section):
if not os.path.exists(file_name):
_stop_with_error(f"could not find con... | NordicHPC/dusage | _dusage/dusage_backend.py | .py | 1d2c3741bf853fc8 | 7.24 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.