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 |
|---|---|---|---|---|---|---|
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""nginx-ingress-integrator k8s endpoint slice controller."""
from typing import Dict, List
import kubernetes.client
from controller.resource import ResourceController, _map_k8s_auth_exception
from ingress_definition import IngressDefinition
... | canonical/nginx-ingress-integrator-operator | src/controller/endpoint_slice.py | .py | fe101ed8b14d2441 | 7.15 | 1 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""nginx-ingress-integrator k8s endpoint controller."""
from typing import Dict, List
import kubernetes.client
from controller.resource import ResourceController, _map_k8s_auth_exception
from ingress_definition import IngressDefinition
class... | canonical/nginx-ingress-integrator-operator | src/controller/endpoints.py | .py | 8bf59a9a0b09d4a5 | 7.15 | 1 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""nginx-ingress-integrator k8s ingress controller."""
import contextlib
import logging
import time
from enum import Enum
from typing import Dict, List, Optional
import kubernetes.client
from consts import CREATED_BY_LABEL
from controller.reso... | canonical/nginx-ingress-integrator-operator | src/controller/ingress.py | .py | c2b3dfa4eedc77ea | 7.15 | 1 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""nginx-ingress-integrator k8s resource controllers."""
import abc
import functools
import logging
import typing
import kubernetes.client
from exceptions import InvalidIngressError
from ingress_definition import IngressDefinition
logger = lo... | canonical/nginx-ingress-integrator-operator | src/controller/resource.py | .py | f8af63a0a78abbfc | 7.15 | 1 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""nginx-ingress-integrator k8s secret controller."""
import logging
import typing
import kubernetes.client
from consts import CREATED_BY_LABEL
from controller.resource import ResourceController, _map_k8s_auth_exception
from ingress_definition... | canonical/nginx-ingress-integrator-operator | src/controller/secret.py | .py | 6021bb3af211f1a7 | 7.15 | 1 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""nginx-ingress-integrator k8s service controller."""
import typing
import kubernetes.client
from controller.resource import ResourceController, _map_k8s_auth_exception
from ingress_definition import IngressDefinition
class ServiceControlle... | canonical/nginx-ingress-integrator-operator | src/controller/service.py | .py | 34fd2a8b4be6f85a | 7.15 | 1 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Fixtures for Nginx-ingress-integrator charm tests."""
from pytest import Config, Parser
def pytest_addoption(parser: Parser) -> None:
"""Parse additional pytest options.
Args:
parser: Pytest parser.
"""
parser.addo... | canonical/nginx-ingress-integrator-operator | tests/conftest.py | .py | cfa7111a58fea9fc | 7.65 | 1 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
# This Python script is designed to be loaded into any-charm. Some lint checks do not apply
# pylint: disable=import-error,consider-using-with,duplicate-code
"""This code snippet is used to be loaded into any-charm which is used for integration... | canonical/nginx-ingress-integrator-operator | tests/integration/any_charm_nginx_route.py | .py | 7dc9a472a04199b1 | 7.65 | 1 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""General configuration module for integration tests."""
import shlex
import subprocess
import time
from pathlib import Path
import jubilant
import kubernetes
import pytest
import yaml
from pytest import Config, fixture
def pack(root: Path ... | canonical/nginx-ingress-integrator-operator | tests/integration/conftest.py | .py | 92c935077dec1ee8 | 7.65 | 1 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Integration test relation file."""
import json
import logging
import time
import typing
from pathlib import Path
import jubilant
import pytest
LOGGER = logging.getLogger(__name__)
TLS_CERTIFICATES_PROVIDER_APP_NAME = "self-signed-certific... | canonical/nginx-ingress-integrator-operator | tests/integration/test_cert_relation.py | .py | a619fc357608d815 | 7.65 | 1 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Integration test for ingress relation."""
import json
import pathlib
import textwrap
import jubilant
import pytest
import requests
def make_any_charm_source(strip_prefix: bool = False, model_name: str | None = "testing") -> str:
"""Ge... | canonical/nginx-ingress-integrator-operator | tests/integration/test_ingress_relation.py | .py | 8fb904c13b4b8cdd | 7.65 | 1 |
#!/usr/bin/env python3
"""Flag `*.ibek.support.yaml` descriptions that are missing, empty or trivial.
The sweep deliberately generates no per-pattern README describing the entity
models - the support yaml is meant to be self-documenting. That only holds if
the descriptions are real, so this audit is the other half of ... | epics-containers/builder2ibek | .claude/skills/streamdevice-sweep/audit-descriptions.py | .py | e438bd42e4ab107f | 7.24 | 2 |
#!/usr/bin/env python3
"""Render the sweep's committed skip report.
The skip report is a deliverable, not a diagnostic: it is the backlog for the
next phase of work, so it is generated from the JSON the sweep produced rather
than written by hand. It replaces `BUILD-TIME-ONLY.md` at the root of
ibek-runtime-streamdevic... | epics-containers/builder2ibek | .claude/skills/streamdevice-sweep/render-report.py | .py | c2a99ddbda33a154 | 7.24 | 2 |
#!/usr/bin/env python3
"""Build the sweep's candidate set from /dls_sw/prod.
Seeds from modules that carry a `.proto` / `.protocol` anywhere in their latest
release, rather than sweeping all ~750 modules and rejecting most of them.
Also applies the case-duplicate rule: /dls_sw/prod holds pairs of modules
differing on... | epics-containers/builder2ibek | .claude/skills/streamdevice-sweep/scan-candidates.py | .py | a2022cb6643cc7b4 | 7.24 | 2 |
from pathlib import Path
import typer
from builder2ibek import __version__
from builder2ibek.convert import convert_file
from builder2ibek.db2autosave import parse_templates
from builder2ibek.dbcompare import compare_dbs
from builder2ibek.migrate_autosave import migrate_folder
from builder2ibek.reconvert import recon... | epics-containers/builder2ibek | src/builder2ibek/__main__.py | .py | 1f0c55f4043a7661 | 7.24 | 2 |
"""
Defines classes for reading a builder XML IOC definition
"""
from pathlib import Path
from xml.dom.minidom import Document, parse, parseString
from xml.dom.minidom import Element as DomElement
from builder2ibek.types import Element
class Builder:
"""
A class for interpreting builder XML and creating a l... | epics-containers/builder2ibek | src/builder2ibek/builder.py | .py | fca59f2471d3ab28 | 7.24 | 2 |
"""
Generic XML to YAML conversion functions
"""
import re
from pathlib import Path
from typing import Any
from ruamel.yaml import YAML, CommentedMap
from builder2ibek.builder import Builder, Element
from builder2ibek.moduleinfos import finalizers, module_infos
from builder2ibek.support_defaults import strip_default... | epics-containers/builder2ibek | src/builder2ibek/convert.py | .py | 8e2195db1705c8f6 | 7.24 | 2 |
from builder2ibek.converters.globalHandler import globalHandler
from builder2ibek.types import Entity, Generic_IOC
xml_component = "ADOdin"
# Entity types that are leaf nodes (not cross-referenced by other entities)
# and thus should have 'name' stripped
LEAF_ENTITIES = [
"OdinLogConfig",
"OdinBatchFile",
... | epics-containers/builder2ibek | src/builder2ibek/converters/ADOdin.py | .py | 4de2606aa67a4791 | 7.24 | 2 |
import re
from pathlib import Path
from builder2ibek.converters.globalHandler import globalHandler
from builder2ibek.types import Entity, Generic_IOC
xml_component = "ADPilatus"
TEMPLATE_PATH = Path(
"/dls_sw/prod/R3.14.12.7/support/ADPilatus/2-9dls4/etc/makeIocs/pilatusTemplate.xml"
)
def _substitute_macros(x... | epics-containers/builder2ibek | src/builder2ibek/converters/ADPilatus.py | .py | 3b137792beea028b | 7.24 | 2 |
from builder2ibek.converters.epics_base import add_interrupt_vector
from builder2ibek.converters.globalHandler import globalHandler
from builder2ibek.types import Entity, Generic_IOC
from builder2ibek.utils import int_to_hertz
xml_component = "Hy8401ip-asyn"
_scanMode_map = {0: "Continuous", 1: "Triggered", 2: "Gated... | epics-containers/builder2ibek | src/builder2ibek/converters/Hy8401ip-asyn.py | .py | 46925f50a1a6daa9 | 7.24 | 2 |
"""
Lumache - Python library for cooks and food lovers.
"""
__version__ = "0.1.0"
class InvalidKindError(Exception):
"""Raised if the kind is invalid."""
pass
def get_random_ingredients(kind=None):
"""
Return a list of random ingredients as strings.
:param kind: Optional "kind" of ingredients.... | dominicusin/mydocs | lumache.py | .py | 63c7a6754cf423bc | 7.15 | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : utils.py
# @Time : 2022-08-12 22:14:46
# @Author : Bingjie Yan
# @Email : bj.yan.pa@qq.com
# @License : Apache License 2.0
import os
import base64
import sys
import re
import json
import yaml
from github import Github
import pytz
import report
... | yyyanbj/github-events | src/utils.py | .py | 8fcd2b8b454a4c09 | 7.3 | 3 |
"""HTTP server for /metrics and Kubernetes probes.
Liveness (/healthz): main loop touched the heartbeat recently.
Readiness (/ready): last successful metrics scrape was recent.
"""
from __future__ import annotations
import os
import socket
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServ... | waldur/waldur-prometheus-exporter | src/server.py | .py | 6fe14818804e4b26 | 7 | 0 |
"""The run_cartography_module Temporal activity (sync-worker side).
Runs one cartography sync stage as a subprocess. Security posture: argv is
rebuilt here from the registry after re-validating the payload's ``module`` +
``params`` (Temporal payloads cross the network — never trust a pre-built
command), the operator a... | mappedsky/seizu | cartography_sync/activities.py | .py | 58f4dfd5d95a47bf | 7.39 | 5 |
"""Contract check the registry against the installed Cartography CLI.
``python -m cartography_sync.contract_check`` (run inside the pinned sync
image, e.g. ``make cartography_contract_test``). The module registry is
reviewed against a specific cartography release; this check catches a pin
bump (Dependabot or manual) t... | mappedsky/seizu | cartography_sync/contract_check.py | .py | 4a8bf108b16fd6c2 | 7.39 | 5 |
"""Workflow/activity payload dataclasses for cartography syncs.
Imported by the CartographySyncWorkflow inside the Temporal sandbox and by the
sync image's activity worker — stdlib dataclasses only, no I/O.
"""
from dataclasses import dataclass, field
from typing import Any
# CartographySyncResult.status values.
STA... | mappedsky/seizu | cartography_sync/shared.py | .py | f17af3b5b4d9ce29 | 7.39 | 5 |
import asyncio
import logging
from collections.abc import Callable
from dataclasses import dataclass, field
from datetime import UTC, datetime
import jwt
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from jwt import PyJWKClient
from reporting ... | mappedsky/seizu | reporting/authnz/__init__.py | .py | 39cb2d59118a61c9 | 7.39 | 5 |
"""Resolve a stored user's identity and permissions outside an HTTP request.
Used by headless callers (e.g. Temporal workflow activities) that act on
behalf of a stored user — typically the creator of a scheduled query — and
must enforce that user's RBAC permissions without a bearer token. Permissions
are derived from... | mappedsky/seizu | reporting/authnz/headless.py | .py | 9a6ac1a6d31a2183 | 7.39 | 5 |
"""Baseline the report store and add configurable-workflow fields."""
import sqlalchemy as sa
from alembic import op
from sqlmodel import SQLModel
revision = "0001_workflow_fields"
down_revision = None
branch_labels = None
depends_on = None
def _columns(table: str) -> set[str]:
inspector = sa.inspect(op.get_bin... | mappedsky/seizu | reporting/migrations/versions/0001_workflow_fields.py | .py | 92ecda1904fb3026 | 7.39 | 5 |
"""Add Temporal Schedule reconciliation state to scheduled chats.
Scheduled chats moved from a polling worker to Temporal Schedules; these are
the same reconciliation fields scheduled queries already carry.
"""
import sqlalchemy as sa
from alembic import op
revision = "0004_chat_schedule_sync_fields"
down_revision =... | mappedsky/seizu | reporting/migrations/versions/0004_chat_schedule_sync_fields.py | .py | b605b31183f0c1a6 | 7.39 | 5 |
"""Add the session-retirement claim and the index the reaper sweeps on.
``retiring_at`` is the reaper's claim (SBX-011): set by a conditional update, it
closes the session to every other writer until its checkpoint and sandbox are
gone. The index is what keeps the sweep's "which sessions are idle" query from
scanning ... | mappedsky/seizu | reporting/migrations/versions/0006_chat_session_retirement.py | .py | 8f0a34f94b03c215 | 7.39 | 5 |
"""Add the chat turn event log: turn headers and their append-only batches.
A turn's stream parts are written by whichever process runs the turn and read
back by whichever process is serving the client's SSE connection, so they need
a store both can reach. The records are ephemeral -- they exist only for as long
as a ... | mappedsky/seizu | reporting/migrations/versions/0007_chat_turn_events.py | .py | e513e08ea2e33019 | 7.39 | 5 |
"""Add out-of-band storage for oversized chat turn payloads.
A plan step that runs as its own Temporal activity has to hand its result back
to the turn that scheduled it, and that result carries every tool call the step
made together with what each returned -- bounded per call by
``CHAT_TOOL_RESULT_MAX_BYTES``, so meg... | mappedsky/seizu | reporting/migrations/versions/0008_chat_turn_payloads.py | .py | 48a49989626b07d9 | 7.39 | 5 |
"""BFF auth routes.
Browser-only auth flow that keeps the IDP refresh token out of JavaScript:
- ``GET /api/v1/auth/login`` — start an Authorization Code + PKCE flow
- ``GET /api/v1/auth/callback`` — IDP redirects here; we exchange code, set cookie
- ``POST /api/v1/auth/refresh`` — silent renewal; returns a ... | mappedsky/seizu | reporting/routes/auth.py | .py | 1b2baa631d8005dd | 7.39 | 5 |
"""CRUD for scheduled chats: recurring headless agent runs owned by a user.
Registered only when CHAT_ENABLED and CHAT_SCHEDULES_ENABLED are both true.
Schedules are personal: every route operates on the requesting user's own
schedules, and the worker runs each schedule as its owner.
"""
import logging
from fastapi ... | mappedsky/seizu | reporting/routes/chat_schedules.py | .py | 68efd6af84d6d253 | 7.39 | 5 |
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from reporting.authnz import CurrentUser, sync_user_profile
from reporting.schema.report_config import User
router = APIRouter()
class MeResponse(BaseModel):
"""Current user profile with resolved permissions."""
user: User
permission... | mappedsky/seizu | reporting/routes/me.py | .py | 77cb17d3841ed17e | 7.39 | 5 |
import logging
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query
from reporting.authnz import CurrentUser, require_permission
from reporting.authnz.permissions import Permission
from reporting.schema.report_config import (
CloneReportRequest,
CreateReportRequest,
CreateVe... | mappedsky/seizu | reporting/routes/reports.py | .py | fe3f218510340c84 | 7.39 | 5 |
"""Distinct Cartography SyncMetadata property values.
Feeds the watch-scan autocompletes in the scheduled query and scheduled chat
editors: ``grouptype``, ``syncedtype``, and ``groupid`` are the SyncMetadata
property keys that watch_scans match against.
"""
import logging
from fastapi import APIRouter, Depends, HTTP... | mappedsky/seizu | reporting/routes/sync_metadata.py | .py | 08676253f67d3fb4 | 7.39 | 5 |
#!/usr/bin/env python3
"""Simple script to download data via python build in modules."""
import argparse
import logging
import urllib.request
from pathlib import Path
from typing import Tuple
logging.basicConfig(
format="%(name)s: %(message)s",
level=logging.INFO,
)
logger = logging.getLogger("downloader")
... | freva-org/freva-admin | assets/share/freva/deployment/scripts/download.py | .py | 74ff1efbc593f85c | 7.39 | 5 |
"""Simple script to start and stop the storage service."""
import json
import logging
import subprocess
import time
import urllib.request
# Set up logging
logging.basicConfig(
format="%(name)s - %(levelname)s - %(message)s",
datefmt="[%X]",
level=logging.INFO,
)
logger = logging.getLogger("container-check... | freva-org/freva-admin | assets/share/freva/deployment/vault/checks.py | .py | 8e409fe0a2304c90 | 7.39 | 5 |
"""
This resAPI let's you safely store and retrieve secrets. Such secrets include
the login credentials of the freva database or user name and password for
the django enmail interface.
Overview
--------
"""
import argparse
import base64
import json
import logging
import os
import pathlib
import random
import sys
im... | freva-org/freva-admin | assets/share/freva/deployment/vault/runserver.py | .py | 5cbc20a6b1844f6a | 7.39 | 5 |
"""Simulation of the unix lib fcntl."""
import msvcrt
import os
import struct
from ctypes import c_char
import pywintypes
import wcwidth as ww
import win32api
import win32con
import win32file
LOCK_SH = 0 # Shared lock
LOCK_EX = 1 # Exclusive lock
LOCK_NB = 2 # Non-blocking
LOCK_UN = 3 # Unlock
F_SETFL = 4
F_GETF... | freva-org/freva-admin | assets/unix_mock/src/fcntl/__init__.py | .py | b4ac313e5f9196a2 | 7.39 | 5 |
"""Simulation of the pwd unix library."""
import os
import pywintypes
import win32api
import win32profile
import win32security
class struct_passwd:
def __init__(self, pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell):
self.pw_name = pw_name
self.pw_passwd = pw_passwd
... | freva-org/freva-admin | assets/unix_mock/src/pwd/__init__.py | .py | 9b6caad88582c569 | 7.39 | 5 |
"""Simulation of the tty unix library for Windows."""
import termios
IFLAG = termios.IFLAG
OFLAG = termios.OFLAG
CFLAG = termios.CFLAG
LFLAG = termios.LFLAG
CC = termios.CC
def setraw(fd, when=termios.TCSANOW):
"""Put terminal into raw mode."""
mode = termios.tcgetattr(fd)
mode[termios.IFLAG] = mode[ter... | freva-org/freva-admin | assets/unix_mock/src/tty/__init__.py | .py | b5cd9e67bfe16829 | 7.39 | 5 |
"""Download and extract cowsay binary from an archive."""
import argparse
import os
import tarfile
import tempfile
import zipfile
from pathlib import Path
from urllib.request import urlretrieve
def reporthook(count, block_size, total_size):
if count == 0:
return
frac = count * block_size / total_size... | freva-org/freva-admin | pyinstaller/download_cowsay.py | .py | c6911474f85a4e58 | 7.39 | 5 |
"""Definition of custom Errors."""
import sys
from functools import partial, wraps
from types import TracebackType
from typing import Any, Callable, Optional, Type
from rich import print as pprint
from .logger import logger
class DeploymentError(BaseException):
"""Define an error for when the deployment goes w... | freva-org/freva-admin | src/freva_deployment/error.py | .py | c61bd30abcf25169 | 7.39 | 5 |
"""Generate keys."""
import datetime
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Optional
_CRYPTO = True
try:
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
... | freva-org/freva-admin | src/freva_deployment/keys.py | .py | c97d4fd5ed2d42d8 | 7.39 | 5 |
"""Ansible runner interaction."""
import atexit
import json
import os
import sys
from copy import deepcopy
from getpass import getuser
from multiprocessing import get_context
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory
from typing import Any, Dict, List, Optional, Union
import... | freva-org/freva-admin | src/freva_deployment/runner.py | .py | c527b5ecde77f059 | 7.39 | 5 |
from __future__ import annotations
import curses
import json
import logging
import os
import re
from pathlib import Path
from typing import Any, Optional, cast
import npyscreen
import tomlkit
from npyscreen.wgwidget import Widget
from freva_deployment.utils import AD, asset_dir, config_file
logging.basicConfig(leve... | freva-org/freva-admin | src/freva_deployment/ui/deployment_tui/base.py | .py | ceb6d608f152bd8b | 7.39 | 5 |
"""The Freva deployment Text User Interface (TUI) helps to configure a
deployment setup for a new instance of freva."""
from __future__ import annotations
import json
import signal
import threading
import time
from pathlib import Path
from typing import Any, Dict, List, cast
import appdirs
import npyscreen
import to... | freva-org/freva-admin | src/freva_deployment/ui/deployment_tui/main_window.py | .py | 4ebe8bb180b67797 | 7.39 | 5 |
"""Collection of utils for deployment."""
from __future__ import annotations
import hashlib
import ipaddress
import json
import os
import re
import shutil
import socket
import sys
import sysconfig
from pathlib import Path
from typing import Any, Dict, MutableMapping, NamedTuple, Optional, Union, cast
from urllib.requ... | freva-org/freva-admin | src/freva_deployment/utils.py | .py | 119edcfedaa68cd5 | 7.39 | 5 |
"""Define the version of the microservices."""
import argparse
import json
import os
import ssl
import sys
from pathlib import Path
from typing import Any, Dict, List
from urllib.request import urlopen
from packaging.version import Version
from rich import print as pprint
from rich.prompt import Prompt
from .error i... | freva-org/freva-admin | src/freva_deployment/versions.py | .py | 7096431c5133779b | 7.39 | 5 |
#!/usr/bin/env python3
import argparse
import json
from utils.configclasses import Config
from argparse import RawDescriptionHelpFormatter
from pathlib import Path
def get_config_dict(config_input: dict) -> dict:
configs = {}
repo_info = config_input.get("repo_info", {})
binary_config = config_input.get("... | ManiVaultStudio/DevBundle | makeproject.py | .py | c3b6775a72d095a3 | 7 | 0 |
import enum
import itertools
import logging
import re
from collections.abc import Callable, Iterable, Sequence
from typing import Any
_logger = logging.getLogger("UnicodeDataEntry")
def u_hex(value: int) -> str:
return f"{value:04X}"
def u_enc(c, encoding):
code = 0
for byte in c.encode(encoding, "igno... | kojiishi/unicodedata-reader | src/unicodedata_reader/entry.py | .py | f04c9a79417d8cb5 | 7.24 | 2 |
"""Module for model definitions and utilities."""
from typing_extensions import deprecated
import flax
import flax.linen
import jax
from jax_rtrl.models.cells import CELL_TYPES, ONLINE_CELL_TYPES # noqa
from jax_rtrl.models.feedforward import FADense, FAAffine # noqa
from .seq_models import RNNEnsembleConfig, Seq... | FranzKnut/jax_rtrl | jax_rtrl/models/__init__.py | .py | 6e9cd4f296063c5d | 7.15 | 1 |
'''
Following https://github.com/patrick-kidger/equinox/blob/e50fed9c81605130eede7eb4577db0d71fc2c881/equinox/nn/_rnn.py#L13-108
'''
import math
from typing import Optional
import jax
import jax.nn as jnn
import jax.numpy as jnp
import jax.random as jrandom
from jaxtyping import Array, PRNGKeyArray
from equinox._mis... | FranzKnut/jax_rtrl | jax_rtrl/models/cells/LRC_diagmat.py | .py | a7c4f5c8f993e638 | 7.15 | 1 |
"""Multi-head self-attention cells built with Jax.
author: jlemmel
"""
import jax.numpy as jnp
from flax import linen as nn
def resets_to_mask(resets):
"""Build a self-attention mask that blocks attention across episode boundaries.
A ``True`` value in ``resets[t]`` marks the start of a new episode: positio... | FranzKnut/jax_rtrl | jax_rtrl/models/cells/attention.py | .py | a8a0490e84d20cae | 7.15 | 1 |
"""CTRNN implementation."""
from functools import partial
import flax.linen as nn
import jax
import jax.numpy as jnp
import jax.random as jrand
from chex import PRNGKey
from jax_rtrl.models.cells.ode import ODECell, OnlineODECell, rtrl, snap0
from jax_rtrl.util.jax_util import (
set_matching_leaves,
get_matc... | FranzKnut/jax_rtrl | jax_rtrl/models/cells/ctrnn.py | .py | ad2b7ab3c0cf1076 | 7.15 | 1 |
"""Hopfield Network cell implementation.
Implements both:
- Classical Hopfield Network (Hopfield, 1982): bipolar patterns with a
sign-based activation, framed as a continuous-time ODE.
- Modern Hopfield Network (Ramsauer et al., 2020): continuous patterns with
softmax-based retrieval equivalent to the attention me... | FranzKnut/jax_rtrl | jax_rtrl/models/cells/hopfield.py | .py | 66815650f5d43974 | 7.15 | 1 |
"""Liquid Resistance Liquid Capacitance (LRC) model flax implementation."""
from typing import Literal
import flax.linen as nn
import jax
import jax.numpy as jnp
import jax.random as jrand
from jax.nn import sigmoid
from chex import PRNGKey
from flax.linen import nowrap
from jax_rtrl.models.cells.ode import ODECell, ... | FranzKnut/jax_rtrl | jax_rtrl/models/cells/lrc.py | .py | 4658540fde921cec | 7.15 | 1 |
"""Linear Recurrent Units built with Jax.
author: jlemmel
Stolen from the paper Real-Time Recurrent Learning using Trace Units in Reinforcement Learning
by Elelimy et. al.
NeurIPS 2024
"""
from functools import partial
import flax
import jax
import jax.numpy as jnp
from flax import linen as nn
from ..linear import ... | FranzKnut/jax_rtrl | jax_rtrl/models/cells/lru.py | .py | 8af50f91e8d55b27 | 7.15 | 1 |
"""Liquid Time Constant (LTC) model flax implementation."""
from typing import Literal
import flax.linen as nn
import jax
import jax.numpy as jnp
import jax.random as jrand
from jax.nn import sigmoid
from chex import PRNGKey
from flax.linen import nowrap
from jax_rtrl.models.cells.ode import ODECell, OnlineODECell, r... | FranzKnut/jax_rtrl | jax_rtrl/models/cells/ltc.py | .py | b709e9f3a18a7278 | 7.15 | 1 |
from dataclasses import field
from typing import Literal
from chex import PRNGKey
import flax.linen as nn
import jax
import jax.numpy as jnp
from jax_rtrl.models.wirings import make_mask_initializer
from jax_rtrl.util.jax_util import tree_stack
class ODECell(nn.RNNCellBase):
"""Simple CTRNN cell."""
num_uni... | FranzKnut/jax_rtrl | jax_rtrl/models/cells/ode.py | .py | cf4ec7776b25a51b | 7.15 | 1 |
"""https://github.com/NicolasZucchet/Online-learning-LR-dependencies"""
from functools import partial
import jax
import jax.numpy as jnp
from jax import random
from flax import linen as nn
from models.linear import matrix_init
from models.seq_util import binary_operator_diag_spatial, binary_operator_diag
def nu_init... | FranzKnut/jax_rtrl | jax_rtrl/models/cells/online_lru.py | .py | 70d4b90feb971e4f | 7.15 | 1 |
"""Benna-Fusi model of synaptic plasticity with connected vessel dynamics.
The connected vessels model approximates a power-law memory kernel using a chain of
communicating dynamic variables (vessels). Synaptic weight is read from the first
vessel, while hidden vessels regularize it with the history of modifications.
... | FranzKnut/jax_rtrl | jax_rtrl/models/complex_synapses.py | .py | a58c8d3245c10bde | 7.15 | 1 |
"""Weight consolidation for online continual learning.
This module implements online weight consolidation for continual learning scenarios
where task boundaries are not known explicitly. Based on:
- "Overcoming catastrophic forgetting in neural networks" by Kirkpatrick et al. (2017)
- "Continual Learning Through Synap... | FranzKnut/jax_rtrl | jax_rtrl/models/consolidation.py | .py | a5cd359f7aa45bc3 | 7.15 | 1 |
"""Distributions implemented with distrax."""
from typing import Any
from chex import PRNGKey
import distrax
import jax
import jax.numpy as jnp
class UniformMixture(distrax.MixtureSameFamily):
"""A uniform mixture of distributions."""
def __init__(self, components):
# HACK: Distrax MixtureSameFamil... | FranzKnut/jax_rtrl | jax_rtrl/models/distributions.py | .py | 7bb2400fb0313815 | 7.15 | 1 |
from functools import partial
import jax
import jax.numpy as jnp
from flax import linen as nn
from jax import random
from .seq_util import binary_operator
def matrix_init(key, shape, dtype=jnp.float32, normalization=1):
return random.normal(key=key, shape=shape, dtype=dtype) / normalization
def truncated_norm... | FranzKnut/jax_rtrl | jax_rtrl/models/linear.py | .py | 1f95a76cf1b6989c | 7.15 | 1 |
"""Plasticity Rules for online learning."""
import equinox as eqx
import jax
import jax.numpy as jnp
from jax.nn import initializers
class Plasticity:
"""A generic plasticity rule that serves as a template for other plasticity rules."""
def __init__(self, cell, feedback_alignment=False, key=None):
"... | FranzKnut/jax_rtrl | jax_rtrl/models/plasticity.py | .py | 31231b2f1164adde | 7.15 | 1 |
"""Regularization functions for RNNs."""
import jax.numpy as jnp
import jax
def norm_preserving(de_dh, dh_dh):
"""Incentivice preserving the norm in the direction of the error gradient (Pascanu, 2012)."""
return (jnp.linalg.norm(de_dh * dh_dh) / jnp.linalg.norm(de_dh) - 1) ** 2
def _maybe_reduce_tree(fun, ... | FranzKnut/jax_rtrl | jax_rtrl/models/regularization.py | .py | c850f33eb337fc39 | 7.15 | 1 |
"""
RTUs variations
1. Linear RTUs without gradient corrections in forward pass
3. BPTT for linear RTUs
5. Linear RTUs with gradient corrections in forward pass
6. Real-Time Linear RTUs
7. A Consice interface to Real-Time Linear RTUs
"""
from flax import linen as nn
import jax
import jax.numpy as jnp
import flax
from ... | FranzKnut/jax_rtrl | jax_rtrl/models/rtus/linear_rtus.py | .py | 928deac4a33045bc | 7.15 | 1 |
"""
RTUs variations
1. Non Linear RTUs without gradient corrections in forward pass
2. BPTT for Non-Linear RTUs
5. Non-Linear RTUs with gradient corrections in forward pass
6. Real-Time Non-Linear RTUs
7. A Consice interface to Real-Time Non-Linear RTUs
"""
from flax import linen as nn
import jax
import jax.numpy as j... | FranzKnut/jax_rtrl | jax_rtrl/models/rtus/non_linear_rtus.py | .py | 9d6c37264a0dd081 | 7.15 | 1 |
"""RNN wirings for JAX."""
import jax
import jax.numpy as jnp
import jax.random as jrandom
def fully_connected(output_size: int, input_size: int, **_):
"""Create a fully connected mask.
Args:
output_size (int): output size
input_size (int): input size
Returns:
array: mask of one... | FranzKnut/jax_rtrl | jax_rtrl/models/wirings.py | .py | 91c219148d7f535f | 7.15 | 1 |
"""Convolutional neural network autoencoders built with flax."""
from dataclasses import dataclass, field, replace
from jax_rtrl.models.feedforward import DistributionLayer
from simple_parsing import Serializable
import jax
import jax.numpy as jnp
import jax.random as jrandom
import numpy as np
from typing import Lite... | FranzKnut/jax_rtrl | jax_rtrl/networks/autoencoders.py | .py | 443f4b4392831f88 | 7.15 | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (c) 2022 Nobuo Tsukamoto
This software is released under the MIT License.
See the LICENSE file in the project root for more information.
"""
from functools import partial
from typing import Any, Callable, Dict, Tuple
import jax.numpy as jnp
import jax.nn a... | FranzKnut/jax_rtrl | jax_rtrl/networks/mobilenet_v3.py | .py | 44f169c9e61dd5d8 | 7.15 | 1 |
from dataclasses import dataclass, field, replace
from chex import PRNGKey
from jax import numpy as jnp
import os
from flax import linen as nn
import jax
import jax_rtrl
from jax_rtrl.networks.autoencoders import (
Autoencoder,
AutoencoderConfig,
ConvEncoder,
ConvConfig,
)
from jax_rtrl.models.feedfor... | FranzKnut/jax_rtrl | jax_rtrl/networks/policies.py | .py | 749e64c8e1eee873 | 7.15 | 1 |
""" Datasets for core experimental results """
from functools import partial
from pathlib import Path
import torch
import torchaudio.functional as TF
import torchvision
from einops import rearrange
from typing import Sequence
def is_list(x):
return isinstance(x, Sequence) and not isinstance(x, str)
def deprecat... | FranzKnut/jax_rtrl | jax_rtrl/supervised/dataloaders/base.py | .py | 053eeb36fb4138f2 | 7.15 | 1 |
import math
import numpy as np
# Bit reversal permutation
def bitreversal_po2(n):
"""
From S4 codebase.
:param n:
:return:
"""
m = int(math.log(n) / math.log(2))
perm = np.arange(n).reshape(n, 1)
for i in range(m):
n1 = perm.shape[0] // 2
perm = np.hstack((perm[:n1],... | FranzKnut/jax_rtrl | jax_rtrl/supervised/dataloaders/permutations.py | .py | ed1496eace74f02f | 7.15 | 1 |
"""
Adapted from https://github.com/dwromero/ckconv/blob/dc84dceb490cab2f2ddf609c380083367af21890/datasets/speech_commands.py
which is
adapted from https://github.com/patrick-kidger/NeuralCDE/blob/758d3a7134e3a691013e5cc6b7f68f277e9e6b69/experiments/datasets/speech_commands.py
"""
import os
import pathlib
import tarfil... | FranzKnut/jax_rtrl | jax_rtrl/supervised/dataloaders/sc.py | .py | 0111ebe5db698c04 | 7.15 | 1 |
"""Utilities for writing and reading Flashbax vaults."""
import itertools
from collections.abc import Iterable
import os
import re
from typing import Any
from chex import PRNGKey
import jax
from jax import numpy as jnp, random as jrandom
import numpy as np
from flashbax.vault import Vault
from flashbax.buffers.trajec... | FranzKnut/jax_rtrl | jax_rtrl/supervised/sequential_vault.py | .py | 9187bd9bc0168b97 | 7.15 | 1 |
"""
Databar CLI root application.
Registers all subcommand groups and exposes top-level login/whoami commands.
"""
from __future__ import annotations
import typer
from databar import __version__
from . import enrichments, flows, tables, tasks, waterfalls
from ._auth import app as auth_app
app = typer.Typer(
n... | databar-ai/databar-python | src/databar/cli/app.py | .py | 9ae63bea12b24edf | 7.3 | 3 |
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
"""# [DEPRECATED!] KubernetesServicePatch Library.
The `kubernetes_service_patch` library is DEPRECATED and will be removed in October 2025.
For patching the Kubernetes service created by Juju during the deployment of a charm,
`ops.Unit.set_po... | canonical/argo-operators | charms/argo-controller/lib/charms/observability_libs/v1/kubernetes_service_patch.py | .py | b7414814378cb4ba | 7.15 | 1 |
#!/usr/bin/env python3
# Copyright 2023 Canonical Ltd.
# See LICENSE file for licensing details.
"""Charm for the Argo Workflow Controller.
https://github.com/canonical/argo-operators
"""
import logging
from base64 import b64encode
from urllib.parse import urlparse
import lightkube
from charmed_kubeflow_chisme.comp... | canonical/argo-operators | charms/argo-controller/src/charm.py | .py | 1748e773431da4ce | 7.15 | 1 |
# Copyright 2023 Canonical Ltd.
# See LICENSE file for licensing details.
import logging
from charmed_kubeflow_chisme.components.pebble_component import PebbleServiceComponent
from ops.pebble import Layer
logger = logging.getLogger(__name__)
ARGO_CONTROLLER_CONFIGMAP = "argo-workflow-controller-configmap"
# TODO: Up... | canonical/argo-operators | charms/argo-controller/src/components/pebble_component.py | .py | f8a50dbf656b540d | 7.15 | 1 |
# Copyright 2023 Canonical Ltd.
# See LICENSE file for licensing details.
import logging
from pathlib import Path
import lightkube
import pytest
import yaml
from charmed_kubeflow_chisme.testing import (
GRAFANA_AGENT_APP,
assert_alert_rules,
assert_logging,
assert_metrics_endpoint,
assert_security... | canonical/argo-operators | charms/argo-controller/tests/integration/test_charm_object_storage.py | .py | e7e08f628690099c | 7.65 | 1 |
# Copyright 2023 Canonical Ltd.
# See LICENSE file for licensing details.
import logging
from pathlib import Path
import lightkube
import pytest
import yaml
from charmed_kubeflow_chisme.testing import (
GRAFANA_AGENT_APP,
assert_alert_rules,
assert_logging,
assert_metrics_endpoint,
assert_security... | canonical/argo-operators | charms/argo-controller/tests/integration/test_charm_s3.py | .py | fa3c188df0f3bef4 | 7.65 | 1 |
'''This is a library providing a utility for unittesting events fired on a
Harness-ed Charm.
Example usage:
>>> from charms.harness_extensions.v0.capture_events import capture
>>> with capture(RelationEvent) as captured:
>>> harness.add_relation('foo', 'remote')
>>> assert captured.event.unit.name == 'remote'
'''... | canonical/kubeflow-dashboard-operator | lib/charms/harness_extensions/v0/capture_events.py | .py | 26382628f855f0e7 | 7.15 | 1 |
#!/usr/bin/env python3
from typing import List, Optional
import yaml
from charms.kubeflow_dashboard.v0.kubeflow_dashboard_links import (
DASHBOARD_LINK_LOCATIONS,
DashboardLink,
KubeflowDashboardLinksRequirer,
)
from ops import main
from ops.charm import CharmBase
from ops.model import ActiveStatus
# Map ... | canonical/kubeflow-dashboard-operator | tests/integration/dashboard_links_requirer_tester_charm/src/charm.py | .py | de1ea11086973861 | 7.65 | 1 |
# Copyright 2023 Canonical Ltd.
# See LICENSE file for licensing details.
import json
import logging
import shutil
from dataclasses import asdict
from pathlib import Path
from typing import Dict, List
import aiohttp
import pytest
import pytest_asyncio
import yaml
from charmed_kubeflow_chisme.testing import (
GRAFA... | canonical/kubeflow-dashboard-operator | tests/integration/test_charm.py | .py | f46dd49f71483f77 | 7.65 | 1 |
# Copyright 2023 Canonical Ltd. See LICENSE file for licensing details.
import json
import logging
import shutil
from dataclasses import asdict
from pathlib import Path
from typing import Dict, List
import pytest
import pytest_asyncio
import tenacity
import yaml
from charmed_kubeflow_chisme.testing import (
GRAFAN... | canonical/kubeflow-dashboard-operator | tests/integration/test_charm_ambient.py | .py | aa083d053c65b8db | 7.65 | 1 |
"""Pairwise causal orientation by residual-independence asymmetry (RESIT).
The one tie-breaker observational data still offers after everything else in
this project came up symmetric. For an additive noise model ``Y = f(X) + N``
with ``N`` independent of ``X`` and ``f`` nonlinear, regressing the effect on
the cause l... | AkandaAshraf/DeepFeatSelection | deepfeatselect/anm.py | .py | 825284028bcae88d | 7 | 0 |
"""Grad-CAM-style attribution for tabular networks, and its structure statistics.
Grad-CAM (Selvaraju et al., 2017) weights a convolutional feature map by the
pooled gradient of a class score, ``alpha_k = GAP(d y^c / d A^k)``, and reports
``ReLU(sum_k alpha_k A^k)``. Two ingredients: gradient-times-activation
weighti... | AkandaAshraf/DeepFeatSelection | deepfeatselect/attribution.py | .py | f0e8402980da27a4 | 7 | 0 |
"""Classical feature-importance baselines to compare the gated network against.
A ranking produced by twenty trained networks is only interesting relative to
what a filter or a forest produces in a second, so this module provides four
cheap references: mutual information, L1-penalised logistic regression,
random-fores... | AkandaAshraf/DeepFeatSelection | deepfeatselect/baselines.py | .py | 8ea6b99b9131909c | 7 | 0 |
"""Loading, encoding and splitting for the Cleveland heart-disease data.
The original implementation L2-normalised every column over the *entire*
dataset and fed the raw integer codes of the nominal attributes straight into
the network. Both are fixed here:
* scaling statistics are fitted on the training split only,... | AkandaAshraf/DeepFeatSelection | deepfeatselect/data.py | .py | 333eebbf9a56cc96 | 7 | 0 |
"""Post-training diagnostics: has this network actually learned?
Validation loss answers the question crudely -- it says how well the model
predicts, not whether it found structure or memorised. The literature has better
instruments, and all of them run after training with no extra fitting, which is
what makes them us... | AkandaAshraf/DeepFeatSelection | deepfeatselect/diagnostics.py | .py | a72b5a8389e027f5 | 7 | 0 |
"""Repeated training runs, aggregated into a feature ranking with uncertainty.
A single run's gates are noisy, so the original trained many models and averaged
them. Two changes here:
* every run draws its own stratified split as well as its own weight
initialisation, so the spread across runs reflects sampling va... | AkandaAshraf/DeepFeatSelection | deepfeatselect/experiment.py | .py | e38610ececfaf466 | 7 | 0 |
"""The gated feature-selection network.
The idea carried over from the original implementation: put a single learnable
non-negative scalar in front of every input feature, train the network, and read
those scalars back as importances.
The original built this as one ``Dense(1, use_bias=False)`` layer per feature and
c... | AkandaAshraf/DeepFeatSelection | deepfeatselect/model.py | .py | 5732cdcf23df9123 | 7 | 0 |
"""Detecting when importance rankings are not identifiable.
Proposition 1 says that if a feature is a deterministic function of the others,
every risk-difference importance measure scores it exactly zero. That result is
only actionable if the condition can be checked on data, which is what this
module does: regress e... | AkandaAshraf/DeepFeatSelection | deepfeatselect/redundancy.py | .py | 1023a6a977a66157 | 7 | 0 |
"""A system whose difficulty scales with the number of features.
Built to test one claim: that a trained network finds structure which
subset-enumerating methods cannot reach once the feature count grows.
The system carries three kinds of column.
* ``interaction`` -- k features whose *joint* parity determines part o... | AkandaAshraf/DeepFeatSelection | deepfeatselect/scaling.py | .py | a8e64cd4dc1b8330 | 7 | 0 |
"""Shapley-style global importance, the method built for redundant features.
Proposition 1 kills every importance measure defined as a single risk
difference: if ``X_j`` is a deterministic function of the rest then
``R*(N \\ {j}) = R*(N)`` and leave-one-out importance is exactly zero. But that
difference is only *one... | AkandaAshraf/DeepFeatSelection | deepfeatselect/shapley.py | .py | 25ef8bd2f032202b | 7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.