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
"""Audio-source catalog `CATALOG` is the single definition of the audio sources Audera supports. Provisioning, the Sources tab, the Players tab, and the rendered `snapserver.conf` all derive from it. Three rules follow from upstream Snapcast behaviour. 1. A `SourceDefinition.id` is immutable. The id is the URI's `?n...
Eleff-org/audera
audera/domains/sources/catalog.py
.py
4a15bc95343db230
7.15
1
"""Applying a source toggle to the host. The `page`-free middle of the Sources tab's enable/disable choreography. The lock, the data-access-layer write, group reassignment, the readiness wait, and the notifications stay with the handlers, which read `page`. `domains/sources/__init__.py` must not import this module. T...
Eleff-org/audera
audera/domains/sources/toggle.py
.py
3ea07350d6f80ec5
7.15
1
"""Typed exceptions for command failures. Every write path raises one of these at its translation boundary, so the UI can catch a single hierarchy and show the right message without inspecting exception types from three libraries. """ class CommandError(Exception): """A command targeting a service or the local f...
Eleff-org/audera
audera/errors.py
.py
73e93f09c98ff3a6
7.15
1
"""DSP configuration""" from __future__ import annotations from typing import Literal from pydantic import BaseModel, Field # Butterworth Q ≈ 1/√2 — the maximally-flat response with no resonant peak; the standard # default when a filter specifies no Q. DEFAULT_Q = 0.707 # Pass filters (`Lowpass`/`Highpass`) carry ...
Eleff-org/audera
audera/models/dsp.py
.py
fd3ba7faba485d94
7.15
1
"""Audio-player""" from __future__ import annotations from typing import List from pydantic import BaseModel, Field class Player(BaseModel): """A `class` that represents a Snapcast client. Attributes ---------- id: `str` The Snapcast client identifier. host: `str` The ip-addres...
Eleff-org/audera
audera/models/player.py
.py
de03bc6875cf03be
7.15
1
"""Audio stream""" from __future__ import annotations from typing import Literal, Optional from pydantic import BaseModel, field_validator class Stream(BaseModel): """A `class` that represents what PlexAmp is currently playing. Unrelated to a Snapcast stream. Built fresh from `PlexAmpClient.get_now_playin...
Eleff-org/audera
audera/models/stream.py
.py
c6616d2a446c1e46
7.15
1
"""Access point management""" import socket import time from typing import Literal from audera import io from audera.errors import CommandError from audera.services import netifaces, platform, system class AccessPoint: """A `class` that represents a Wi-Fi access point. Parameters ---------- name: `...
Eleff-org/audera
audera/services/ap.py
.py
401c0c19cce09307
7.15
1
"""Operating-system management""" import os import platform from typing import Callable, Literal import dotenv # Load the dietpi os environment dotenv.load_dotenv('/boot/dietpi/.version') NAME = 'dietpi' if os.getenv('G_DIETPI_VERSION_CORE') else platform.system().strip().lower() VERSION = ( '.'.join( [...
Eleff-org/audera
audera/services/platform.py
.py
e52f7702403c5a94
7.15
1
"""Systemd unit management""" import logging import subprocess from audera.errors import ServiceError, Unreachable from audera.services import platform # Bounds every call. A `systemctl` verb that has not returned in 15 seconds is hung. TIMEOUT: float = 15 # `CalledProcessError.__str__` carries the argv and the exi...
Eleff-org/audera
audera/services/system.py
.py
b9ed593a1292e04d
7.15
1
"""Frequency-response chart for the parametric-EQ editor""" import math from nicegui import ui from audera.domains.dsp import response_curve from audera.models.dsp import DSPConfig from audera.ui.components import theme # The visible frequency window (Hz); the y-axis auto-min tracks only the curve inside it. _X_MIN...
Eleff-org/audera
audera/ui/components/response_plot.py
.py
04ab29bbfa7c25e6
7.15
1
"""Brand theme adapter for NiceGUI / Quasar apps. Serves ``brand/tokens.css`` and the self-hosted woff2 font files as NiceGUI static assets, maps brand tokens to Quasar color slots, and injects page-level CSS that applies the light palette. Call ``apply_defaults()`` once from ``run()`` before ``ui.run()``. Call ``app...
Eleff-org/audera
audera/ui/components/theme.py
.py
5cd6ab6e51e4c940
7.15
1
"""UX optionality feature-flag catalog""" from __future__ import annotations from dataclasses import dataclass from audera.models.settings import Settings @dataclass(frozen=True) class Option: """A `class` that represents a single selectable option for a `Feature`. Attributes ---------- value: `st...
Eleff-org/audera
audera/ui/features.py
.py
98be73f74dfd09dd
7.15
1
"""Mock seams for running the local UI apps off-device. The setup app cannot run off-device as written: `Page.__init__` and the whole `AccessPoint` are `@platform.requires('dietpi')`, and `get_wifi_networks()` shells out to `nmcli`. This module stands in for the device so the wizard is reachable and screenshotable on ...
Eleff-org/audera
audera/ui/setup/_mock.py
.py
69270c060aca2f85
7.15
1
"""Remote audio device setup pages""" import asyncio import json import time from typing import Dict, List, Literal, Optional, Union from fastapi.responses import RedirectResponse, Response from nicegui import app, ui import audera from audera.ui import components # The connectivity-check URLs each OS probes on joi...
Eleff-org/audera
audera/ui/setup/pages.py
.py
54865fdab9c0f060
7.15
1
"""Audera app""" import asyncio from nicegui import app, ui import audera from audera.dal import settings as settings_dal from audera.dal import sources as sources_dal from audera.dal import volume as volume_dal from audera.settings import settings from audera.ui import components from audera.ui.streamer import brok...
Eleff-org/audera
audera/ui/streamer/__init__.py
.py
46a5cc91d2e8196f
7.15
1
from django.contrib.auth.password_validation import validate_password from rest_framework import serializers from .models import Usuario class UsuarioSerializer(serializers.ModelSerializer): """ Cadastro publico (/autenticacao/signup/). Os campos sao listados um a um de proposito. Com 'fields = "__all__"...
PatrikiGss/Projeto-gestao-pecuaria
backend/apps/autenticacao/serializers.py
.py
31d0d0e4e4f11368
7
0
from rest_framework.views import APIView from rest_framework import status from rest_framework.response import Response from rest_framework.exceptions import NotFound from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework_simplejwt.token_blacklist.models import OutstandingToken, Blackliste...
PatrikiGss/Projeto-gestao-pecuaria
backend/apps/autenticacao/views.py
.py
733726c95032415e
7
0
import django_filters from .models import AnaliseSolo, Recomendacao class AnaliseSoloFilter(django_filters.FilterSet): """ Filtros da listagem de analises. Com o historico paginado, o cliente precisa conseguir chegar direto ao que procura em vez de percorrer pagina por pagina. 'propriedade' atravess...
PatrikiGss/Projeto-gestao-pecuaria
backend/apps/core/filtros.py
.py
27cd74eb96e33ba9
7
0
from django.db import migrations from django.db.models import F def trocar_p_e_k(apps, schema_editor): """ Corrige a inversao entre fosforo e potassio nas analises ja gravadas. O formulario da tela de analise tinha os dois rotulos trocados entre si: o campo rotulado "Potassio (K)" gravava na coluna '...
PatrikiGss/Projeto-gestao-pecuaria
backend/apps/core/migrations/0007_corrige_inversao_p_k.py
.py
6fd24d6fdb69220a
7
0
""" Validadores de dominio compartilhados entre as apps. Fica na raiz de 'apps/', que o config/settings.py acrescenta ao sys.path, e por isso e importavel como 'validadores' tanto de core quanto de autenticacao. Os validadores sao declarados nos campos dos models. Assim valem de uma vez no DRF (que os aplica ao monta...
PatrikiGss/Projeto-gestao-pecuaria
backend/apps/validadores.py
.py
756d12d549c6297d
7
0
""" Tratamento de excecoes da API. EXISTE POR CAUSA DO on_delete=PROTECT Os models de dominio usam PROTECT nas chaves que apontam para AnaliseSolo, para que apagar um cadastro auxiliar nunca leve o historico junto. So que o DRF nao conhece ProtectedError: sem este arquivo a excecao sobe sem tratamento e vira HTTP 500...
PatrikiGss/Projeto-gestao-pecuaria
backend/config/excecoes.py
.py
9c564e92dd9f1a1f
7
0
# Copyright 2023 Canonical Ltd. # See LICENSE file for licensing details. """Library for the certificate_transfer relation. This library contains the Requires and Provides classes for handling the ertificate-transfer interface. ## Getting Started From a charm directory, fetch the library using `charmcraft`: ```shel...
canonical/certificate-transfer-interface
lib/charms/certificate_transfer_interface/v0/certificate_transfer.py
.py
2a7bcf2a51f09144
7
0
"""Common data model objects used across this library. These are typically small objects reusable in different contexts. """ from dataclasses import dataclass from typing import ClassVar from mashumaro.config import BaseConfig from mashumaro.mixins.yaml import DataClassYAMLMixin __all__ = [ "DeviceInfo", "S...
allenporter/synthetic-home
synthetic_home/common.py
.py
bcbb3d5f5016e0a1
7.15
1
"""Data model for device type definitions. These device types are responsible for: - Describing infroation about a device such as name, make, model info. - How devices are made from a set of entities A device type may also pre-define the concept of a device state. The device state is a name like "idle" that describes...
allenporter/synthetic-home
synthetic_home/device_types.py
.py
32554c6fdeac4929
7.15
1
"""Data model for home assistant synthetic home.""" import logging import pathlib from dataclasses import dataclass, field from typing import Any import slugify from mashumaro.codecs.yaml import yaml_decode from synthetic_home.device_types import ( DeviceState, DeviceStateStrategy, DeviceTypeRegistry, ...
allenporter/synthetic-home
synthetic_home/synthetic_home.py
.py
75e3c17f2ad42fb9
7.15
1
"""Helper scripts for synthetic home.""" import argparse import asyncio import importlib import logging import sys from pathlib import Path from . import create_inventory, export_inventory _LOGGER = logging.getLogger(__name__) def get_base_arg_parser() -> argparse.ArgumentParser: """Get a base argument parser....
allenporter/synthetic-home
synthetic_home/tool/__main__.py
.py
53392120e558ade5
7.15
1
"""Create inventory files from a synthetic home device file. Given a home yaml file: ``` --- name: Family Farmhouse devices: Family Room: - name: Family Room Lamp device_type: light device_info: manufacturer: Phillips model: Hue - name: Family Room device_type: hvac d...
allenporter/synthetic-home
synthetic_home/tool/create_inventory.py
.py
a87649c997539020
7.15
1
"""Export an inventory from a Home Assistant instance. You can create a synthetic home inventory copied from an existing home assistant instance. You need to create an access token and export an inventory like this: ```bash $ HASS_URL="http://home-assistant.home-assistant:8123" $ API_TOKEN="XXXXXXXXXXX" $ synthetic-h...
allenporter/synthetic-home
synthetic_home/tool/export_inventory.py
.py
53048dfa377772b6
7.15
1
"""Command to dump out all of the synthetic home device types.""" import argparse import dataclasses import yaml from synthetic_home import device_types def create_arguments(args: argparse.ArgumentParser) -> None: """Get parsed passed in arguments.""" args.add_argument( "--device_type", typ...
allenporter/synthetic-home
synthetic_home/tool/list_device_types.py
.py
97467af6d0b73347
7.15
1
"""Global fixtures for Synthetic Home tests.""" import pathlib import pytest from syrupy import SnapshotAssertion from syrupy.extensions.amber import AmberSnapshotExtension from syrupy.location import PyTestLocation DIFFERENT_DIRECTORY = "snapshots" class DifferentDirectoryExtension(AmberSnapshotExtension): ""...
allenporter/synthetic-home
tests/conftest.py
.py
84bc7ed00a2c5073
7.65
1
"""Test for device_types.""" from synthetic_home import device_types def test_load_device_type_registry() -> None: """Test loading the device type registry.""" reg = device_types.load_device_type_registry() for name, device_type in reg.device_types.items(): assert name assert device_type...
allenporter/synthetic-home
tests/test_device_types.py
.py
41a1df33011983a0
7.65
1
"""Test for inventory.""" from synthetic_home import inventory INVENTORY = """ --- areas: - name: Backyard id: backyard floor: Ground - name: Frontyard id: frontyard floor: Ground - name: Living Room id: living_room floor: Ground - name: Loft id: loft floor: Upstairs - name: Basement id: basement ""...
allenporter/synthetic-home
tests/test_inventory.py
.py
7c98674c59f49782
7.65
1
"""Test for synthetic_home.""" import pathlib import pytest from syrupy import SnapshotAssertion from synthetic_home import device_types, inventory, synthetic_home TEST_HOMES = pathlib.Path("tests/homes") TEST_FIXTURES = pathlib.Path("tests/fixtures") HOME1 = TEST_HOMES / "home1.yaml" def test_load_synthetic_home...
allenporter/synthetic-home
tests/test_synthetic_home.py
.py
e01bb6f6f3b52e18
7.65
1
#!/usr/bin/env python3 """ Auto-solver for daily LeetCode problems using OpenAI GPT-5-mini. This script fetches the daily problem (or a specific problem by ID), uses AI to solve it, and creates a solution file. Usage: python3 auto_solver.py # Solve today's daily problem python3 auto_solver.py 123 ...
ContextLab/leetcode-solutions
auto_solver.py
.py
db6edd8bf4d9901f
7.35
4
""" Common data structures used in LeetCode problems. """ from typing import Optional class TreeNode: """ Definition for a binary tree node. This is the standard TreeNode class used in LeetCode binary tree problems. """ def __init__(self, val=0, left=None, right=None): self.val = val ...
ContextLab/leetcode-solutions
helpers/data_structures.py
.py
143bc02b7cd97fbb
7.35
4
#!/usr/bin/env python3 """ Helper script to identify missing problems and create batch files for bulk solving. """ import os import sys import tempfile from pathlib import Path def get_problems_from_readme(): """Extract problem numbers from README.""" import re problems = set() with open('README...
ContextLab/leetcode-solutions
identify_missing.py
.py
bde98b23a1fc067b
7.35
4
from typing import Optional, Tuple, Union import torch from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, UNet2DConditionModel from diffusers.pipeline_utils import ImagePipelineOutput from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm imp...
rsrinath14/Inpainting_with_Stable_Artist
examples/community/bit_diffusion.py
.py
6c9ad8a93086d118
7
0
import glob import os from typing import Dict, List, Union import torch from diffusers import DiffusionPipeline, __version__ from diffusers.pipeline_utils import ( CONFIG_NAME, DIFFUSERS_CACHE, ONNX_WEIGHTS_NAME, SCHEDULER_CONFIG_NAME, WEIGHTS_NAME, ) from huggingface_hub import snapshot_download ...
rsrinath14/Inpainting_with_Stable_Artist
examples/community/checkpoint_merger.py
.py
379aea515b758766
7
0
import inspect from typing import List, Optional, Union import torch from torch import nn from torch.nn import functional as F from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, UNet2DConditionModel, ) from diffusers.pipelines.stable_d...
rsrinath14/Inpainting_with_Stable_Artist
examples/community/clip_guided_stable_diffusion.py
.py
dff509dbafe96bb1
7
0
""" modified based on diffusion library from Huggingface: https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py """ import inspect import warnings from typing import List, Optional, Union import torch from diffusers.models import AutoencoderKL, UN...
rsrinath14/Inpainting_with_Stable_Artist
examples/community/composable_stable_diffusion.py
.py
103d4c4a9a5edddb
7
0
""" modified based on diffusion library from Huggingface: https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py """ import inspect from typing import Callable, List, Optional, Union import torch from diffusers.models import AutoencoderKL, UNet2DCo...
rsrinath14/Inpainting_with_Stable_Artist
examples/community/seed_resize_stable_diffusion.py
.py
7ecb406996fed47b
7
0
# coding=utf-8 # Copyright 2022 HuggingFace Inc.. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
rsrinath14/Inpainting_with_Stable_Artist
examples/test_examples.py
.py
3dc4f04b8ee0f23a
7.5
0
# coding=utf-8 # Copyright 2022 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
rsrinath14/Inpainting_with_Stable_Artist
scripts/convert_ldm_original_checkpoint_to_diffusers.py
.py
57540643190e5ff7
7
0
# coding=utf-8 # Copyright 2022 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
rsrinath14/Inpainting_with_Stable_Artist
scripts/convert_ncsnpp_original_checkpoint_to_diffusers.py
.py
29cd56f5f88bed65
7
0
# # Python Imaging Library # $Id$ # # stuff to read (and render) GIMP gradient files # # History: # 97-08-23 fl Created # # Copyright (c) Secret Labs AB 1997. # Copyright (c) Fredrik Lundh 1997. # # See the README file for information on usage and redistribution. # """ Stuff to translate curve segments to pa...
bardsley/merseysidelatinfestival
functions/_layers/brevo/python/PIL/GimpGradientFile.py
.py
82aa949036ca5450
7
0
# # Python Imaging Library # $Id$ # # stuff to read GIMP palette files # # History: # 1997-08-23 fl Created # 2004-09-07 fl Support GIMP 2.0 palette files. # # Copyright (c) Secret Labs AB 1997-2004. All rights reserved. # Copyright (c) Fredrik Lundh 1997-2004. # # See the README file for information on usage ...
bardsley/merseysidelatinfestival
functions/_layers/brevo/python/PIL/GimpPaletteFile.py
.py
8481d0f4b279ae2d
7
0
# # The Python Imaging Library. # $Id$ # # macOS icns file decoder, based on icns.py by Bob Ippolito. # # history: # 2004-10-09 fl Turned into a PIL plugin; removed 2.3 dependencies. # 2020-04-04 Allow saving on all operating systems. # # Copyright (c) 2004 by Bob Ippolito. # Copyright (c) 2004 by Secret Labs. #...
bardsley/merseysidelatinfestival
functions/_layers/brevo/python/PIL/IcnsImagePlugin.py
.py
76bfe9ebc936102a
7
0
"""Cas""" import base64 import json import logging from typing import Any, Dict, List, Optional from session import MagicSession # 配置日志 logger = logging.getLogger(__name__) class Cas: """Cas""" def __init__(self, work_session): self.session = work_session self.session_token = None ...
muidea/magicTest
cas/cas/cas.py
.py
9551cd1bc66c8b1a
7
0
"""Endpoint""" import logging from session import session from cas import cas from mock import common # 配置日志 logger = logging.getLogger(__name__) class Endpoint: """Endpoint""" def __init__(self, work_session): self.session = work_session def filter_endpoint(self, param): val = self.se...
muidea/magicTest
cas/endpoint/endpoint.py
.py
d344e3036fd1f75b
7
0
"""Namespace""" import logging import time as dt from session import session from cas import cas from mock import common # 配置日志 logger = logging.getLogger(__name__) class Namespace: """Namespace""" def __init__(self, work_session, defaultNamespace = None): self.session = work_session self.d...
muidea/magicTest
cas/namespace/namespace.py
.py
7593055c91a06b31
7
0
"""Role""" import logging from session import session from cas import cas from mock import common # 配置日志 logger = logging.getLogger(__name__) class Role: """Role""" def __init__(self, work_session): self.session = work_session def filter_role(self, param): val = self.session.get('/api/...
muidea/magicTest
cas/role/role.py
.py
f9e10ed2c0a89e7c
7
0
"""common - Faker-based mock data generator""" import random import uuid as id import time as dt from datetime import datetime, timedelta from faker import Faker # Create Faker instances for different locales _faker_en = Faker() _faker_zh = Faker('zh_CN') def generate_uuid(): """Generate a random UUID (hex stri...
muidea/magicTest
mock/common.py
.py
865aeb7541243b0a
7
0
# Copyright © LFV from enum import Enum, unique import os from typing import ReadOnly, TypedDict from ruamel.yaml import YAML import ast from reqstool_python_decorators.decorators.decorators import Requirements @unique class DECORATOR_TYPES(Enum): FUNCTION = ("FUNCTION", "METHOD") ASYNCFUNCTION = ("ASYNCFUN...
reqstool/reqstool-python-decorators
src/reqstool_python_decorators/processors/decorator_processor.py
.py
52504c3063fa784d
7.15
1
"""The OpenAI Conversation integration.""" from __future__ import annotations from pathlib import Path from types import MappingProxyType import openai from openai.types.images_response import ImagesResponse from openai.types.responses import ( EasyInputMessageParam, Response, ResponseInputMessageContent...
lenaxia/talos-ops-prod
kubernetes/apps/home/home-assistant/app/openai/__init__.py
.py
2e84fc4a8e5704b2
7.3
3
"""Conversation support for OpenAI.""" from typing import Literal from homeassistant.components import conversation from homeassistant.config_entries import ConfigSubentry from homeassistant.const import CONF_LLM_HASS_API, MATCH_ALL from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platfo...
lenaxia/talos-ops-prod
kubernetes/apps/home/home-assistant/app/openai/conversation.py
.py
43afe6b656b7e5ff
7.3
3
""" IAM by Keycloak """ import requests import os from fastapi import APIRouter from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from fastapi.security import HTTPBasic, HTTPBasicCredentials from jose import jwt as jose_jwt, JWTError from dotenv i...
ABI-CTT-Group/digitaltwins-api
app/routers/auth.py
.py
72443d88a9808267
7.35
4
"""Shared FastAPI dependency factories used across multiple routers.""" from fastapi import Depends from digitaltwins import Querier, Uploader, Downloader, Deleter from .auth import validate_credentials def get_querier(credentials: dict = Depends(validate_credentials)) -> Querier: """Create a per-request Querie...
ABI-CTT-Group/digitaltwins-api
app/routers/dependencies.py
.py
cec40cb550bb9735
7.35
4
""" Example for generating a SDS primary dataset """ import os.path from sparc_me import Dataset def add_dataset_description(dataset, save_dir): """ the values can be filled in by 2 methods, set_field() or set_field_using_row_name(). This example will use Dataset.set_field() # You can get the row_in...
ABI-CTT-Group/digitaltwins-api
examples/generate_primary_dataset.py
.py
2fbba03cd9b03aec
7.35
4
import os import psycopg2 from dotenv import load_dotenv load_dotenv() class Connection(object): """ Class for connecting to the digitaltwins platform. """ def __init__(self, host=None, port=None, database=None, user=None, password=None): self._cur = None self._conn = None ...
ABI-CTT-Group/digitaltwins-api
src/digitaltwins/core/connection.py
.py
de40c45c54b9deb3
7.35
4
"""Core orchestrator for dataset deletion. Coordinates Postgres and MinIO deletions within a single transaction so that either everything succeeds or everything is rolled back. """ import os import logging from typing import Optional import psycopg2 from dotenv import load_dotenv load_dotenv() from ..utils.config...
ABI-CTT-Group/digitaltwins-api
src/digitaltwins/core/deleter.py
.py
e01e8e1ced009635
7.35
4
import os from dotenv import load_dotenv load_dotenv() from ..postgres.querier import Querier as PostgresQuerier from ..gen3.querier import Querier as Gen3Querier class QuerierFactory: """ static factory """ @staticmethod def create(): """ static method for creating Querier insta...
ABI-CTT-Group/digitaltwins-api
src/digitaltwins/core/querier_factory.py
.py
833e5280a4073246
7.35
4
import os from dotenv import load_dotenv load_dotenv() from ..utils.config_loader import is_truthy from ..airflow.workflow import Workflow as AirflowWorkflow class Workflow(object): def __init__(self): self._airflow_enabled = is_truthy(os.getenv("AIRFLOW_ENABLED")) if self._airflow_enabled: ...
ABI-CTT-Group/digitaltwins-api
src/digitaltwins/core/workflow.py
.py
3562eaf4a7268abf
7.35
4
import datetime as dt import logging import os from concurrent.futures import as_completed from concurrent.futures.process import ProcessPoolExecutor from enum import Enum from pathlib import Path from typing import Any import pandas as pd from pydantic import BaseModel, Field, field_validator from tqdm import tqdm f...
mmocchi/pycodemetrics
src/pycodemetrics/cli/analyze_committer/handler.py
.py
a5dfe944e9c321d4
7
0
"""coupling分析ハンドラーモジュール。 このモジュールは、プロジェクト全体のモジュール結合度分析を行うためのハンドラーを提供します。 プロジェクト構造の分析、結合度メトリクスの計算、結果の表示・エクスポートなどの機能を提供します。 主な機能: - プロジェクトルートの検証 - モジュール結合度の計算と分析 - 結果のフィルタリングとソート - プロジェクトサマリーの生成 - 結果の表示とエクスポート 処理フロー: 1. 入力パラメータの検証 2. プロジェクト全体の結合度分析 3. 結果のフィルタリングとソート 4. サマリー情報の生成(オプショ...
mmocchi/pycodemetrics
src/pycodemetrics/cli/analyze_coupling/handler.py
.py
aefa03db587a3dbf
7
0
"""健康度分析ハンドラーモジュール。 このモジュールは、健康度分析のCLI処理を実行するためのハンドラー関数とパラメータクラスを提供します。 """ import logging from enum import Enum from pathlib import Path from typing import Any from pydantic import BaseModel from pycodemetrics.services.analyze_health import ( HealthAnalysisSettings, analyze_project_health, ) logger = logg...
mmocchi/pycodemetrics
src/pycodemetrics/cli/analyze_health/handler.py
.py
90aa887da44ab435
7
0
import datetime as dt import logging import os from concurrent.futures import as_completed from concurrent.futures.process import ProcessPoolExecutor from enum import Enum from pathlib import Path import pandas as pd from pydantic import BaseModel, Field, field_validator from tqdm import tqdm from pycodemetrics.cli.d...
mmocchi/pycodemetrics
src/pycodemetrics/cli/analyze_hotspot/handler.py
.py
cd95b82970f015ed
7
0
"""Pythonコード分析ハンドラーモジュール。 このモジュールは、Pythonコードのメトリクス分析を行うためのハンドラーを提供します。 分析対象のファイルの取得、分析の実行、結果の表示・エクスポートなどの機能を提供します。 主な機能: - 分析対象ファイルの取得と検証 - コードメトリクスの計算と分析 - 結果の表示形式の制御 - 分析結果のエクスポート 処理フロー: 1. 入力パラメータの検証 2. 分析対象ファイルの取得 3. コードメトリクスの計算 4. 結果のフィルタリングとソート 5. 結果の表示とエクスポート 制限事項: - 分...
mmocchi/pycodemetrics
src/pycodemetrics/cli/analyze_python/handler.py
.py
d999a0e7ab459176
7
0
from enum import Enum import pandas as pd import tabulate class DisplayFormat(str, Enum): """ Display format for the result. TABLE: Display the result as a table. CSV: Display the result as a CSV format. JSON: Display the result as a JSON format. """ TABLE = "table" CSV = "csv" ...
mmocchi/pycodemetrics
src/pycodemetrics/cli/display_util.py
.py
319ab17ea3be041c
7
0
from enum import Enum from pathlib import Path import pandas as pd class ExportFormat(str, Enum): """ Export format for analyze_hotspot_metrics Args: CSV: Export the result as a CSV. JSON: Export the result as a JSON. """ CSV = "csv" JSON = "json" @classmethod def t...
mmocchi/pycodemetrics
src/pycodemetrics/cli/exporter.py
.py
c6bfe23b5c579eb7
7
0
import datetime as dt from pathlib import Path from pydantic import BaseModel class GitFileCommitLog(BaseModel, frozen=True, extra="forbid"): """ Git file commit log. filepath (Path): The path to the file. commit_hash (str): The commit hash. author (str): The author of the commit. commit_dat...
mmocchi/pycodemetrics
src/pycodemetrics/gitclient/models.py
.py
3b63f7c593ada1d9
7
0
"""モジュール結合度分析モジュール。 このモジュールは、Pythonプロジェクト内のモジュール間の結合度を分析します。 プロジェクト全体の構造的メトリクスを提供し、アーキテクチャの品質評価を行います。 主な機能: - プロジェクト全体の依存関係収集 - Afferent Coupling (Ca) - 入力結合度の計算 - Efferent Coupling (Ce) - 出力結合度の計算 - Instability (I) - 不安定度の計算 - Abstractness (A) - 抽象度の計算(将来実装) - モジュール間の依存関係グラフ構築 結合度メトリクスの解釈: ...
mmocchi/pycodemetrics
src/pycodemetrics/metrics/coupling.py
.py
7aa826f3e6064b37
7
0
"""健康度メトリクス計算モジュール。 このモジュールは、プロジェクトの健康度を計算するためのメトリクス機能を提供します。 複数の指標を統合して総合的な健康度スコアを算出します。 """ import logging import statistics from pathlib import Path from typing import Any from pydantic import BaseModel logger = logging.getLogger(__name__) class HealthMetrics(BaseModel, frozen=True, extra="forbid"): """健康度...
mmocchi/pycodemetrics
src/pycodemetrics/metrics/health.py
.py
11a6a420578838ad
7
0
import ast class ImportAnalyzer(ast.NodeVisitor): def __init__(self): self.imports = [] def visit_Import(self, node): for alias in node.names: self.imports.append(alias.name) def visit_ImportFrom(self, node): for alias in node.names: self.imports.append(no...
mmocchi/pycodemetrics
src/pycodemetrics/metrics/py/import_analyzer.py
.py
4b8f4366d2444deb
7
0
from pydantic import BaseModel from pycodemetrics.metrics.py.cognitive_complexity import get_cognitive_complexity from pycodemetrics.metrics.py.import_analyzer import analyze_import_counts from pycodemetrics.metrics.py.raw.radon_wrapper import ( get_complexity, get_maintainability_index, get_raw_metrics, )...
mmocchi/pycodemetrics
src/pycodemetrics/metrics/py/python_metrics.py
.py
565b612a802fe803
7
0
import ast from cognitive_complexity.api import get_cognitive_complexity from pydantic import BaseModel class FunctionCognitiveComplexity(BaseModel, frozen=True): """ 関数の認知的複雑度を表すデータクラス。 このクラスは、特定の関数の認知的複雑度を計算し、その結果を保持します。 認知的複雑度は、コードの理解や保守の難易度を示す指標です。 Attributes: function_name (str): 関...
mmocchi/pycodemetrics
src/pycodemetrics/metrics/py/raw/cc_wrapper.py
.py
fcdeab312e626e3c
7
0
from enum import Enum from pydantic import BaseModel from radon.metrics import mi_visit from radon.raw import analyze from radon.visitors import Class, ComplexityVisitor, Function class BlockType(Enum): FUNCTION = "Function" METHOD = "Method" CLASS = "Class" UNKNOWN = "Unknown" class RawMetrics(Bas...
mmocchi/pycodemetrics
src/pycodemetrics/metrics/py/raw/radon_wrapper.py
.py
4657658b9a0db65b
7
0
import datetime as dt from collections import Counter from enum import Enum from pathlib import Path from typing import Any from pydantic import BaseModel from pycodemetrics.config.config_manager import UserGroupConfig from pycodemetrics.gitclient.gitcli import get_file_gitlogs from pycodemetrics.gitclient.gitlog_par...
mmocchi/pycodemetrics
src/pycodemetrics/services/analyze_committer.py
.py
233cb51a0801f124
7
0
"""結合度分析サービスモジュール。 このモジュールは、プロジェクト全体のモジュール結合度分析を行うためのサービスレイヤーを提供します。 ビジネスロジックの中核となる機能を集約し、CLIレイヤーとメトリクス計算レイヤーを仲介します。 主な機能: - プロジェクト結合度分析の実行 - 結果のフィルタリングと分類 - メトリクスの統計情報計算 - 推奨アクションの生成 - エラーハンドリングとログ記録 処理パターン: 1. プロジェクト検証とメタデータ収集 2. 結合度メトリクスの計算 3. 結果の分析と分類 4. 推奨アクションの生成 5. 統計情報...
mmocchi/pycodemetrics
src/pycodemetrics/services/analyze_coupling.py
.py
a8faf68e3b99f3fc
7
0
"""健康度分析サービスモジュール。 このモジュールは、プロジェクトの健康度を分析するためのサービス機能を提供します。 複数のメトリクスを統合して総合的な健康度スコアを算出します。 """ import logging from pathlib import Path from typing import Any from pydantic import BaseModel from pycodemetrics.metrics.health import ( ProjectHealthResult, analyze_project_health_metrics, ) from pycodemetrics.se...
mmocchi/pycodemetrics
src/pycodemetrics/services/analyze_health.py
.py
0ad92816f2531972
7
0
import datetime as dt from enum import Enum from pathlib import Path from typing import Any from pydantic import BaseModel from pycodemetrics.config.config_manager import UserGroupConfig from pycodemetrics.gitclient.gitcli import get_file_gitlogs from pycodemetrics.gitclient.gitlog_parser import parse_gitlogs from py...
mmocchi/pycodemetrics
src/pycodemetrics/services/analyze_hotspot.py
.py
fcbf3f9c489c8034
7
0
import logging from enum import Enum from pathlib import Path from typing import Any from pydantic import BaseModel from pycodemetrics.config.config_manager import UserGroupConfig from pycodemetrics.metrics.py.python_metrics import PythonCodeMetrics, compute_metrics from pycodemetrics.util.file_util import CodeType, ...
mmocchi/pycodemetrics
src/pycodemetrics/services/analyze_python_metrics.py
.py
76c0a337742ca0a8
7
0
"""健康度分析ハンドラーのテストモジュール。""" from pathlib import Path from unittest.mock import Mock, patch from pycodemetrics.cli.analyze_health.handler import ( DisplayFormat, DisplayParameter, ExportParameter, InputTargetParameter, RuntimeParameter, _get_status_emoji, _get_status_text, run_analyze_he...
mmocchi/pycodemetrics
tests/pycodemetrics/cli/analyze_health/test_handler.py
.py
cd411f6c2ecfb3a8
7.5
0
"""Pythonコード分析ハンドラーのテストモジュール。 このモジュールは、pycodemetrics.cli.analyze_python.handlerモジュールの機能をテストします。 Pythonコードのメトリクス分析機能と、結果の表示・エクスポート機能を検証します。 """ from pathlib import Path import pandas as pd import pytest from pycodemetrics.cli.analyze_python.handler import ( DisplayFormat, DisplayParameter, ExportParamete...
mmocchi/pycodemetrics
tests/pycodemetrics/cli/analyze_python/test_handler.py
.py
0c9d52498ee7a682
7.5
0
import json from typing import Any, Callable import logging logger = logging.getLogger(__name__) class Cache: cache_dir: str = "cache" def __init__(self, cache_dir: str = "cache"): self.cache_dir = cache_dir def get(self, key: str) -> Any: """ Get the value from the cache for th...
autotaker/diff-insight
src/cache.py
.py
30de726dc0665701
7.24
2
from typing import Any, Optional import yaml import logging logger = logging.getLogger(__name__) class CategoryClassifier: """ Classify patches into categories. """ config: dict[str, Any] def __init__(self, config_path): """ Initialize the classifier. Args: ...
autotaker/diff-insight
src/category_classifier.py
.py
3f9cd7d0a610ff54
7.24
2
# src/github_api.py import requests from typing import Dict, Any, Optional import logging logger = logging.getLogger(__name__) class GitHubAPI: def __init__(self, token: str): """ Initialize GitHubAPI with an authentication token. :param token: GitHub Personal Access Token for authenti...
autotaker/diff-insight
src/github_api.py
.py
af40ba43e29705ef
7.24
2
# src/llm_api.py import hashlib import json import textwrap from openai import OpenAI from typing import Any, Optional import logging import locale import re logger = logging.getLogger(__name__) def parse_summary(diff_item: dict[str, Any], explanation: str) -> dict[str, str]: """ Parse the summary from the ...
autotaker/diff-insight
src/llm_api.py
.py
cf03773aa7194a77
7.24
2
# src/main.py from datetime import datetime import hashlib import json import os import typer from cache import Cache from category_classifier import CategoryClassifier from github_api import GitHubAPI from llm_api import LLMAPI from report_generator import ReportGenerator import logging app = typer.Typer() token = ...
autotaker/diff-insight
src/main.py
.py
748ac52b731edba3
7.24
2
# src/report_generator.py from datetime import date import os from typing import Any, List, Dict import yaml # Define a custom representer for multi-line strings def str_presenter(dumper, data): if "\n" in data: # Use block style for multi-line strings return dumper.represent_scalar("tag:yaml.org...
autotaker/diff-insight
src/report_generator.py
.py
89e577ab8834eabc
7.24
2
#!/usr/bin/env python3 """Add ``# yaml-language-server: $schema=<url>`` modelines to Kubernetes manifests. Walks the kubernetes/ tree, parses each YAML file, and for every document with a known (apiVersion, kind) emits a modeline after the leading ``---`` marker. For files that lack a leading ``---``, inserts both the...
AlinaNova21/home-ops
kubernetes/scripts/add-yaml-modelines.py
.py
bdd37540ac345ead
7.15
1
import requests from bs4 import BeautifulSoup import re # Standard headers for requests headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3' } def fetch_article_data(article_url): """ Fetches the content of an articl...
ALeX400/Multi-RSS
patterns/Example/tepmplate_pattern.py
.py
180059683e7df2ae
7.24
2
"""Exact per-prediction feature attribution for the deployed LightGBM models. Uses LightGBM's native ``pred_contrib=True``, which is exact TreeSHAP. The ``shap`` package would give the same numbers for these models while adding a dependency, and requirements.txt pins library versions precisely so the model pickles sta...
levonrush/footy-tipper
pipeline/common/explain/contributions.py
.py
c2d7075b656eea20
7.39
5
"""Feature-family taxonomy for explainability. Groups the ~600 raw predictors into a handful of families with plain-English labels. Reason codes and cohort analyses are only readable at this altitude: "team-list strength" means something, "lineup_avg_spine_margin_rating_delta" does not. This deliberately lives here r...
levonrush/footy-tipper
pipeline/common/explain/families.py
.py
416c329ec28ccf1f
7.39
5
"""Persistence for per-game explanations. Explanations live in their own table rather than as extra columns on predictions_table. That table is the published tips contract: ten columns spread across two SQL files, a view, a contract test and two duplicated column-migration helpers, and a Drive CSV whose shape depends ...
levonrush/footy-tipper
pipeline/common/explain/store.py
.py
e6328f684db76e85
7.39
5
"""Reading the deployed probability stack, exactly as inference assembles it. The published conditional home-win probability is built in three steps: experts (Tier A / Tier B / Tier C / market) -> SimplexLogitPool: pooled_logit = sum_i w_i * logit(p_i) -> TemperatureCalibrator: published_logit = poo...
levonrush/footy-tipper
pipeline/common/explain/trace.py
.py
cb62504087bd4ded
7.39
5
"""Convert link-scale contributions into units a human can act on. LightGBM hands back contributions on the link scale: log-odds for the binary classifier, log-mean for the Poisson score models. Neither is readable. These helpers map them to probability points and points of margin. The link is nonlinear, so linearise...
levonrush/footy-tipper
pipeline/common/explain/units.py
.py
e12faf9bccd22f26
7.39
5
"""Proper scoring rules for sample-based predictive distributions. The score models draw from a Poisson family for every match, but only three integers ever reach the predictions table. Every scoring rule elsewhere in the pipeline (log loss, Brier, Poisson deviance) scores the binary win probability, so the score dist...
levonrush/footy-tipper
pipeline/common/model_training/distributional_metrics.py
.py
757048c777e60e67
7.39
5
"""Derived per-round team performance rows in the feed_cache_performance schema. Semantics verified against the cached feed: each (competition_year, round_id, team) row holds that round's SINGLE-GAME stats (not season-to-date); bye rounds are all-zero rows. R selects the same team's latest prior finalized match in the...
levonrush/footy-tipper
pipeline/common/nrl_data/performance.py
.py
e0202468b5107fc3
7.39
5
"""Weather observations for games via Open-Meteo (free, no key). Historical rows use the ERA5 archive; upcoming games use the forecast API (16-day horizon comfortably covers the prediction window). Values are stored in `weather_observations` keyed by game_id; the feature builder only reads the table, so fetch failures...
levonrush/footy-tipper
pipeline/common/nrl_data/weather.py
.py
0720a3985141aedd
7.39
5
"""Shared HTTP helpers for nrl.com ingestion. Mirrors the session conventions used by pipeline/common/lineups/ingest.py (browser-like headers, robots.txt awareness, polite request delay) so both scrapers present the same footprint to nrl.com. """ from __future__ import annotations import html import json import time...
levonrush/footy-tipper
pipeline/common/nrl_data/web.py
.py
c1b740bef4b83147
7.39
5