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 |
|---|---|---|---|---|---|---|
"""JSONL-based activity logger for analysis DCR wizard / creation events.
Each call to ``log_dcr_event`` appends one JSON object (one line) to
``<data_folder>/logs/analysis_dcr_events.jsonl`` using Python's
``TimedRotatingFileHandler`` (daily rotation, one year retention).
Inputs are assumed to be small and well-form... | MaastrichtU-IDS/cohort-explorer | backend/src/analysis_dcr_logging.py | .py | 4f96409a9d173c77 | 7.42 | 6 |
import base64
import json
import time
from datetime import datetime, timezone
from typing import Optional, Any
from urllib.parse import urlencode
import httpx
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from fastapi.responses import RedirectResponse
from fastapi.security import OAuth2Autho... | MaastrichtU-IDS/cohort-explorer | backend/src/auth.py | .py | fc0ad2d79a5f2186 | 7.42 | 6 |
import logging
import os
from dataclasses import dataclass, field
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv(".env")
# NOTE: using dataclass instead of pydantic due to dependency conflict with `decentriq_platform` preventing to use pydantic v2
@dataclass
class Settings:
... | MaastrichtU-IDS/cohort-explorer | backend/src/config.py | .py | ee36a98d470dba0a | 7.42 | 6 |
import os
import logging
import json
from typing import Any
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import FileResponse
from src.auth import get_current_user
from src.config import settings
from src.models import Cohort
from src.utils import retrieve_... | MaastrichtU-IDS/cohort-explorer | backend/src/explore.py | .py | c9473846d78c7f19 | 7.42 | 6 |
import asyncio
from typing import List
import requests
from langchain_core.callbacks import CallbackManagerForRetrieverRun
from langchain_core.documents import Document
from langchain_core.retrievers import BaseRetriever
from pydantic import BaseModel, Field
class AthenaFilters(BaseModel):
conceptClass: list[str... | MaastrichtU-IDS/cohort-explorer | backend/src/mapping_generation/athena_api_retriever.py | .py | e322e18b741dbdc1 | 7.42 | 6 |
import re
import requests
import concurrent.futures
from datetime import datetime, timezone
import json
import logging
# Enhanced regex for efficiency (more strict IP pattern, reduced backtracking)
domain_regex = re.compile(
r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[... | ghostnetic/adblock-filter-compiler | adblock_filter_compiler.py | .py | 70975a03c40ec778 | 7.57 | 13 |
#!/usr/bin/env python3
"""Build docs/data/*.json for the exploratory frontend from data/raw/*.jsonl.
Replaces the old tag_and_clean_data.py -> standardize_sponsors.py ->
create_minimal_json.py chain with a single pass: read every raw filing,
classify it by its FCC public-file folder path, normalize the sponsor name,
a... | dwillis/fcc_publicfile_tracker | build_site.py | .py | 94ab914fe7d173c1 | 7.45 | 7 |
#!/usr/bin/env python3
"""One-time migration: radio_ads.json -> data/raw/YYYY.jsonl.
Splits the old monolithic (and pretty-printed) raw archive into compact,
append-friendly JSONL shards by filing year, dropping the office/sponsor/
facility_id fields that build_site.py re-derives from the title anyway.
Run once, then ... | dwillis/fcc_publicfile_tracker | scripts/migrate_raw.py | .py | 72993392a8662702 | 7.45 | 7 |
import csv
import requests
from bs4 import BeautifulSoup
# URL of the Wikipedia page
url = "https://en.wikipedia.org/wiki/List_of_urban-format_radio_stations_in_the_United_States"
def fetch_html(url):
"""Fetches the HTML content from the provided URL."""
response = requests.get(url)
if response.status_cod... | dwillis/fcc_publicfile_tracker | scripts/setup/fetch_radio_stations.py | .py | eec9df96a75a3078 | 7.45 | 7 |
import csv
import requests
# CSV file containing the stations' information
input_csv_file = 'urban_radio_stations.csv'
output_csv_file = 'urban_radio_stations_checked.csv'
# FCC API endpoint
api_url = "https://publicfiles.fcc.gov/api/service/facility/search/"
# Dictionary to map full state names to their two-letter ... | dwillis/fcc_publicfile_tracker | scripts/setup/get_fcc.py | .py | 7715e00f3ed73bcb | 7.45 | 7 |
import csv
import requests
# Input CSV file
input_csv = 'urban_radio_stations_checked.csv'
# Output CSV file with status code
output_csv = 'urban_radio_stations_with_status.csv'
def check_url_status(url):
"""Check the HTTP status code of a given URL."""
try:
response = requests.get(url)
return... | dwillis/fcc_publicfile_tracker | scripts/setup/url_checker.py | .py | aedb0bf57180d57c | 7.45 | 7 |
#!/usr/bin/env python3
"""Sponsor-name normalization.
Pulled out of the old standardize_sponsors.py as pure functions (no file
I/O) so build_site.py can call them per-record instead of running a
separate standardization pass over an intermediate file.
"""
import re
# Canonical names for major presidential campaigns, ... | dwillis/fcc_publicfile_tracker | sponsors.py | .py | 0ecf2501abc88c8f | 7.45 | 7 |
"""
case_state.py — Serialization policy and I/O for the CrocoDash case state file.
The case state is written to ``crocodash_state.json`` inside the case root at the
end of ``Case.__init__``. This module owns:
- the schema version used to gate compatibility checks;
- which ``Case.__init__`` arguments are excluded fr... | CROCODILE-CESM/CrocoDash | CrocoDash/case_state.py | .py | a16044e47b81be67 | 7.6 | 15 |
import shutil
import xesmf as xe
import xarray as xr
import cftime
import numpy as np
from netCDF4 import default_fillvals
def process_bgc_ic(file_path, output_path):
"""
Copy BGC initial condition file
Parameters:
- file_path: str, path to the original BGC IC file
- output_path: str, path to sav... | CROCODILE-CESM/CrocoDash | CrocoDash/extract_forcings/bgc.py | .py | 9c46c42238ef82a7 | 7.6 | 15 |
import os
import re
from pathlib import Path
from collections import defaultdict
from datetime import datetime, timedelta
from CrocoDash import logging
from CrocoDash.raw_data_access.registry import ProductRegistry
logger = logging.setup_logger(__name__)
_NETCDF_MAGIC = (b"\x89HDF", b"CDF\x01", b"CDF\x02")
def pars... | CROCODILE-CESM/CrocoDash | CrocoDash/extract_forcings/utils.py | .py | 0d7571d80aa43b9a | 7.6 | 15 |
from pathlib import Path
from typing import List, Dict
from abc import ABC, abstractmethod
from visualCaseGen.custom_widget_types.case_tools import (
xmlchange,
append_user_nl,
)
from CrocoDash.logging import setup_logger
import inspect
from typing import Optional, Any
import copy
import subprocess
import json
... | CROCODILE-CESM/CrocoDash | CrocoDash/forcing_configurations/base.py | .py | 3e2651c6dd977ff4 | 7.6 | 15 |
"""
Raw Data Access Module Requirements:
1. Must enforce a certain amount of metadata for each product (things like z coordinate name, u velocity name, etc) (from the parent class)
2. Must enforce specific keyword args in each access function (from the parent class)
3. There must be some sort of registry that can list/... | CROCODILE-CESM/CrocoDash | CrocoDash/raw_data_access/base.py | .py | f9db2bb7f4ece148 | 7.6 | 15 |
"""
Data Access Module -> Glorys
"""
import xarray as xr
import glob
import os
import copernicusmarine
import regional_mom6 as rm6
from pathlib import Path
import pandas as pd
from CrocoDash.raw_data_access.datasets.utils import make_dates_end_inclusive
from CrocoDash.raw_data_access.base import *
from mom6_forge.util... | CROCODILE-CESM/CrocoDash | CrocoDash/raw_data_access/datasets/glorys.py | .py | 23ca342f221af919 | 7.6 | 15 |
from pathlib import Path
from CrocoDash.raw_data_access.datasets import utils
from CrocoDash.raw_data_access.base import *
class SeaWIFS(BaseProduct):
product_name = "seawifs"
description = "SEAWIFS is a Chlorophyll Dataset for MOM6"
link = "https://oceandata.sci.gsfc.nasa.gov/getfile/SEASTAR_SEAWIFS_GAC.... | CROCODILE-CESM/CrocoDash | CrocoDash/raw_data_access/datasets/seawifs.py | .py | 50e59b4d399cc9f8 | 7.6 | 15 |
import inspect
from CrocoDash.raw_data_access.datasets import load_all_datasets
class ProductRegistry:
"""Static registry that tracks all products and provides driver-like introspection."""
loaded = False
products = {} # product_name → class
@classmethod
def register(cls, product_cls):
... | CROCODILE-CESM/CrocoDash | CrocoDash/raw_data_access/registry.py | .py | b421b221a3b54387 | 7.6 | 15 |
"""
recipe.py — Creating a Case directly from a YAML config dict or file.
Built on top of case.py, which handles the actual case creation through API calls,
This module adds the layer for creating a case from a yaml file, which is a convenient way to create a case without having to write a script.
The YAML file can be... | CROCODILE-CESM/CrocoDash | CrocoDash/recipe.py | .py | 0461c36e87fb1281 | 7.6 | 15 |
from datetime import datetime
import pandas as pd
import requests
from pathlib import Path
from generate_info import generate_dict
from CrocoDash.raw_data_access.registry import ProductRegistry
def main():
print("🔍 Generating product dictionary...")
product_info_dict = generate_dict()
print(f" → Found ... | CROCODILE-CESM/CrocoDash | docs/source/raw_data_access/check_raw_data.py | .py | fc747f3451faad4b | 7.6 | 15 |
"""RERUN THIS WHEN TABLES NEED TO BE UPDATED"""
from CrocoDash.raw_data_access.datasets import load_all_datasets
from CrocoDash.raw_data_access.registry import ProductRegistry
from pathlib import Path
import csv
def main():
product_info_dict = generate_dict()
script_dir = Path(__file__).parent
# --- Writ... | CROCODILE-CESM/CrocoDash | docs/source/raw_data_access/generate_info.py | .py | cb0943da4bc1b0b8 | 7.6 | 15 |
import pytest
import pathlib
# # Add these lines to run CESM tests
# import os
# os.environ["CESMROOT"] = "/home/manishrv/CROCESM"
# os.environ["CIME_MACHINE"] = "ubuntu-latest"
# Dynamically discover all fixtures in fixtures directories
fixtures_dir = pathlib.Path(__file__).parent / "fixtures"
pytest_plugins = [
... | CROCODILE-CESM/CrocoDash | tests/conftest.py | .py | c1ef8dd13316aff9 | 7.1 | 15 |
import subprocess
import json
def test_case_integration_driver(CrocoDash_case_factory, tmp_path, skip_if_not_glade):
"""Verify configure_forcings creates extract_forcings/ and crocodash process can load it."""
case = CrocoDash_case_factory(tmp_path)
case.configure_forcings(
date_range=["2020-01-01... | CROCODILE-CESM/CrocoDash | tests/extract_forcings/test_case_integration.py | .py | 87514c9f9acf4904 | 8.1 | 15 |
#!/usr/bin/env python3
"""Realtime transcription with failover across multiple endpoints.
Stream live audio to a primary endpoint; when it fails beyond recovery,
resume on the next endpoint in the ring, carrying over any speech that was
never transcribed so nothing is lost across the switch.
The SDK handles transient... | togethercomputer/together-py | examples/realtime_failover.py | .py | 6966e396b0e88ff8 | 7.54 | 11 |
#!/usr/bin/env python3
"""Realtime transcription that rides out failures on a single endpoint.
The SDK recovers from transient failures on its own: if the connection drops
mid-conversation, it reconnects with backoff and replays the speech the
server never transcribed — the application just keeps feeding audio. You'll... | togethercomputer/together-py | examples/realtime_single_endpoint_failover.py | .py | be70afbf92648fc9 | 7.54 | 11 |
#!/usr/bin/env python3
"""Realtime transcription of live audio.
Stream PCM audio as it is captured and receive interim text while a phrase
is being spoken, plus a finalized transcript per utterance. The WAV file
here stands in for a live source (microphone, phone call, meeting audio).
Usage:
uv add "together[real... | togethercomputer/together-py | examples/realtime_transcription.py | .py | 9cde48e19a317e1f | 7.54 | 11 |
import os
import logging
import argparse
from typing import Dict, List
from functools import partial
from multiprocessing import cpu_count
from datasets import Dataset, load_dataset # type: ignore
from transformers import ( # type: ignore
AutoTokenizer,
BatchEncoding,
PreTrainedTokenizerBase,
)
# see de... | togethercomputer/together-py | examples/tokenize_data.py | .py | df47ef4cd1fdf3cb | 7.54 | 11 |
from __future__ import annotations
from os import PathLike
from typing import (
IO,
TYPE_CHECKING,
Any,
Dict,
List,
Type,
Tuple,
Union,
Mapping,
TypeVar,
Callable,
Iterable,
Iterator,
Optional,
Sequence,
AsyncIterable,
)
from typing_extensions import (
... | togethercomputer/together-py | src/together/_types.py | .py | 8a5287e89781f98d | 7.54 | 11 |
from __future__ import annotations
from typing import Any
from typing_extensions import override
from ._proxy import LazyProxy
class ResourcesProxy(LazyProxy[Any]):
"""A proxy for the `together.resources` module.
This is used so that we can lazily import `together.resources` only when
needed *and* so t... | togethercomputer/together-py | src/together/_utils/_resources_proxy.py | .py | 45ffe53ffbdb3aa1 | 7.54 | 11 |
from __future__ import annotations
import os
import re
import inspect
import functools
from typing import (
Any,
Tuple,
Mapping,
TypeVar,
Callable,
Iterable,
Sequence,
cast,
overload,
)
from pathlib import Path
from datetime import date, datetime
from typing_extensions import TypeGu... | togethercomputer/together-py | src/together/_utils/_utils.py | .py | 44a7afe394e6ef1f | 7.54 | 11 |
from __future__ import annotations
import os
import re
import sys
import json
import time
import uuid
import platform
import threading
import urllib.error
import urllib.request
from enum import Enum
from typing import Any, TypeVar, Callable, cast
from pathlib import Path
from detect_agent import determine_agent
from ... | togethercomputer/together-py | src/together/lib/cli/_track_cli.py | .py | b3f112d3a91941e4 | 7.54 | 11 |
from __future__ import annotations
import re
import math
from typing import Any, List, Union, Literal, Sequence
from datetime import datetime
from cyclopts import Parameter
from together.lib.utils.tools import localize_datetime
from together.lib.types.fine_tuning import COMPLETED_STATUSES, FinetuneResponse
from toge... | togethercomputer/together-py | src/together/lib/cli/api/_utils.py | .py | 6e2437eb753d8b23 | 7.54 | 11 |
"""Live activity store for hidden sub-agent runs (the pinned-TUI "agents" panel).
Foreground spawns, background spawns, and orchestrator subtask workers all run
``quiet`` — their model output and tool calls are deliberately suppressed so
they don't corrupt the main display. That leaves the user blind to what those
age... | brunopistone/mnemoai | src/mnemoai/client/agent/agent_activity.py | .py | f6cca5ecde8c58b3 | 7.42 | 6 |
"""Model-initiated multiple-choice question (``ask_user_question``) — pure logic
plus the agent-arg driver.
The model calls ``ask_user_question`` when a decision is genuinely the user's to
make; the call is intercepted client-side (the MCP server is a piped subprocess
and can't prompt the terminal) and answered throug... | brunopistone/mnemoai | src/mnemoai/client/agent/ask_user.py | .py | 8c6df5809d078a07 | 7.42 | 6 |
"""Registry for background (detached) sub-agents.
A background sub-agent runs on a daemon thread while the parent turn continues,
so the user keeps interacting. This module is the thread-safe bookkeeping: it
tracks each background run's status/result and persists a small record under
``tasks_dir()`` so ``list``/``get`... | brunopistone/mnemoai | src/mnemoai/client/agent/background_agents.py | .py | 264ff0c86637f6c0 | 7.42 | 6 |
"""Cooperative cancel for a running turn (thread-safe helpers).
``agent._cancel_event`` (a ``threading.Event``) is set from the UI thread on
Esc/Ctrl+C; the blocking waits ``.wait()`` on it and poll it so a turn tears down
immediately instead of after a C-level blocking wait returns.
Functions take the agent as the f... | brunopistone/mnemoai | src/mnemoai/client/agent/cancellation.py | .py | 4856493dbc78de3b | 7.42 | 6 |
"""Client-side destructive-tool confirmation gate (agent-arg helpers).
The hard client-side gate that asks the user before running a destructive tool —
shell (``execute_bash``), file writes (``fs_write``/``file_edit``), and memory
writes — each behind its ``REQUIRE_*`` toggle. It must live client-side: the MCP
server ... | brunopistone/mnemoai | src/mnemoai/client/agent/confirmation_gate.py | .py | 7daec627ad983ec7 | 7.42 | 6 |
"""Repair orphaned tool-call/result pairs in a message history (pure).
Extracted from ``agent.py``: no agent state. ``LangGraphAgent`` keeps a thin
``_sanitize_tool_pairs`` delegator so its historical surface (used by the unit
tests and by ``AgentConversationManager`` via ``getattr``) is unchanged.
"""
from typing im... | brunopistone/mnemoai | src/mnemoai/client/agent/message_sanitizer.py | .py | 6f24cf97f680f210 | 7.42 | 6 |
"""Orchestrator for decomposing complex tasks into worker subtasks."""
import json
import re
from typing import Any, Dict, List
from mnemoai.utils.config import config
from mnemoai.utils.logger import logger
def get_orchestrator_prompt() -> str:
"""Get the ORCHESTRATOR_PROMPT (task-decomposition) from prompts.y... | brunopistone/mnemoai | src/mnemoai/client/agent/orchestrator.py | .py | 1e1a90d4e9d8c30a | 7.42 | 6 |
"""Plan-mode enforcement policy (pure logic).
Plan mode is a user-toggled client-side hard gate: while active, mutating/
shell-executing tools are blocked at the tool chokepoint. Functions take an
explicit ``plan_active`` flag (not agent state) to stay pure and testable; the
agent keeps thin delegating methods over th... | brunopistone/mnemoai | src/mnemoai/client/agent/plan_policy.py | .py | f3696275842773a3 | 7.42 | 6 |
"""Shared helpers for handling reasoning/thinking models.
Auxiliary LLM calls (query classification, task decomposition) need a direct,
structured answer rather than chain-of-thought. Reasoning models (e.g. qwen3 via
Ollama, Claude extended thinking) place their output in a separate reasoning
field, leaving ``response... | brunopistone/mnemoai | src/mnemoai/client/agent/reasoning_utils.py | .py | 21bfba884dbbf0f7 | 7.42 | 6 |
"""Provider-agnostic model-output parsing (pure logic).
Pulls reasoning/thinking and visible answer text out of a completed response or a
streaming chunk across the shapes each provider emits — Bedrock Converse
(``reasoning_content`` / ``thinking`` blocks), OpenAI Responses (``reasoning``
summary blocks), and plain-st... | brunopistone/mnemoai | src/mnemoai/client/agent/response_parsing.py | .py | 9aabb6833cfa656d | 7.42 | 6 |
"""Provider retry/error classification policy (pure logic).
Decides — from an exception's text alone — whether a model call failed because
the prompt overflowed the context window (the caller must compact, never retry)
or because of a transient connection/5xx failure (retry on a fresh connection
with backoff), and com... | brunopistone/mnemoai | src/mnemoai/client/agent/stream_policy.py | .py | 48f5b9a94072b428 | 7.42 | 6 |
"""Model-initiated sub-agent lifecycle — spawn / resume / background (helpers).
The envelope AROUND the shared model↔tool loop for ``spawn_agent`` /
``resume_agent``: tool-subset resolution from a sub-agent type's allowlist,
callback-free model copies, single + parallel-batch + background(daemon)
execution, and backgr... | brunopistone/mnemoai | src/mnemoai/client/agent/subagent_runner.py | .py | ab1d2f696c40b0df | 7.42 | 6 |
"""Sub-agent type registry — the built-in agent types ``spawn_agent`` can run.
A *sub-agent* is a fresh, isolated model↔tool loop the parent model spawns via
the ``spawn_agent`` tool to hand off a self-contained task (research, planning,
a focused edit). Each type carries its own system prompt and a tool allowlist, so... | brunopistone/mnemoai | src/mnemoai/client/agent/subagents.py | .py | cb7821461db9da75 | 7.42 | 6 |
"""Pure helpers for rendering, normalizing, and error-mapping tool calls.
Extracted from ``agent.py`` (no agent state); the agent keeps thin delegating
methods so its historical surface — and the unit tests — stay unchanged.
"""
import re
from typing import Any
# A key that is really a ``field="value"`` expression —... | brunopistone/mnemoai | src/mnemoai/client/agent/tool_formatting.py | .py | a56d1ed89ba8bd7b | 7.42 | 6 |
"""The shared model↔tool execution loop (agent-arg helper).
One tool call, start to finish: normalize the args, short-circuit the client-side
stubs, resolve the tool, then the gates in their required order — plan mode blocks
BEFORE anything else (a blocked tool must never even ask), then the user's
``PreToolUse`` hook... | brunopistone/mnemoai | src/mnemoai/client/agent/tool_loop.py | .py | ec359789edd417cb | 7.42 | 6 |
"""System-prompt building + per-turn context injection (client collaborators).
Assembles the frozen session-start system prompt (base prompt + profile summary +
curated MEMORY.md + skill/sub-agent metadata) and the per-turn context the client
prepends to a query: episodic-memory recall, the plan-mode banner, and the
s... | brunopistone/mnemoai | src/mnemoai/client/context_injection.py | .py | 91b0abaffe0df025 | 7.42 | 6 |
"""Where the context window actually goes (``/context``).
``/usage`` answers "what has this session spent"; this answers the different
question "what is my next turn paying for, and which part of it can I shrink".
The two big surprises it exists to expose are the ones nothing else shows: a
large steering file (re-sent... | brunopistone/mnemoai | src/mnemoai/client/context_report.py | .py | ef5bd57d424cd7aa | 7.42 | 6 |
"""User-scriptable hooks around tool calls (``~/.mnemoai/hooks/hooks.json``).
A hook is a shell command run before or after a tool call. It exists for the
things a prompt cannot reliably enforce: format every file the agent writes,
refuse writes under a path you never want touched, auto-approve the read-only
commands ... | brunopistone/mnemoai | src/mnemoai/client/hooks.py | .py | 6ae371e9456ad909 | 7.42 | 6 |
"""Loader for external MCP servers declared in ``~/.mnemoai/mcp.json``.
mnemoai always runs its own built-in MCP server (the one under
``server/server.py``). On top of that, users can declare *additional* stdio MCP
servers in an ``mcp.json`` file using the same ``mcpServers`` schema as Claude
Code / Claude Desktop / k... | brunopistone/mnemoai | src/mnemoai/client/mcp_config.py | .py | 3fc14d7ffca8fad1 | 7.42 | 6 |
import os
from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional
import chromadb
from mnemoai.client.memory.similarity import (
SCORING_VERSION,
l2_normalize,
squared_l2_to_unit,
)
from mnemoai.utils.bm25 import BM25
from mnemoai.utils.config import config
from mnemoai.utils... | brunopistone/mnemoai | src/mnemoai/client/memory/chroma_store.py | .py | 0d346fc3147fe3ab | 7.42 | 6 |
import json
import os
from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional
import faiss
from mnemoai.client.memory.similarity import (
SCORING_VERSION,
cosine_to_unit,
l2_normalize,
)
from mnemoai.utils.bm25 import BM25
from mnemoai.utils.config import config
from mnemoai.... | brunopistone/mnemoai | src/mnemoai/client/memory/faiss_store.py | .py | 3b71de51d7697dd5 | 7.42 | 6 |
"""Playbook Store - Manages strategy entries with append-only updates and lazy deduplication."""
import json
import os
from datetime import datetime
from typing import Any, Dict, List
from mnemoai.client.memory.reflector import PlaybookEntry
from mnemoai.utils.atomic_write import atomic_write_json
from mnemoai.utils.... | brunopistone/mnemoai | src/mnemoai/client/memory/playbook_store.py | .py | dde90b4aaddf4ad6 | 7.42 | 6 |
"""One similarity scale for both episodic backends.
A single config knob -- ``EPISODIC_MEMORY.RETRIEVAL_THRESHOLD`` -- gates recall
for whichever store is configured, so the two backends MUST produce comparable
numbers. They natively do not:
* FAISS ``IndexFlatIP`` returns a raw inner product (unbounded, and only equ... | brunopistone/mnemoai | src/mnemoai/client/memory/similarity.py | .py | 6991f66642c21063 | 7.42 | 6 |
"""Agent Skills: authored, on-demand instruction packs.
A *skill* is a directory under the skills root containing a ``SKILL.md`` file:
YAML frontmatter (at least ``name`` + ``description``) followed by a markdown
body of instructions, optionally bundling ``reference.md`` docs and ``scripts/``
executables alongside it.... | brunopistone/mnemoai | src/mnemoai/client/memory/skill_store.py | .py | 4ba9b61392bf5c4c | 7.42 | 6 |
"""User-authored, always-on steering instructions (``STEERING.md``/``CLAUDE.md``).
Instructions the USER writes to steer the agent every turn — conventions, commands,
"always do X" rules. It is read-only from the app's perspective (the agent never writes it),
which is the key distinction from ``MEMORY.md`` (agent-cura... | brunopistone/mnemoai | src/mnemoai/client/memory/steering_store.py | .py | 57e75bd0b8b45fe7 | 7.42 | 6 |
"""Per-instance session id + RAG/chunk-cache artifact lifecycle (client helpers).
Mints this instance's session id, sweeps its own prior-run artifacts on startup
(a ``/model`` restart re-execs and mints a new id, orphaning the old store/cache),
and flushes them on ``/clear`` — all scoped to a single ``session_id`` so ... | brunopistone/mnemoai | src/mnemoai/client/session_artifacts.py | .py | 0c4609252ee8d9a9 | 7.42 | 6 |
"""Render a conversation to a shareable Markdown/plain-text transcript (``/export``).
Distinct from ``/save``: that writes re-importable JSON for ``/load``. This is a
**one-way human-readable artifact** — the thing you paste into a bug report, a PR
description, or a message to a colleague. Nothing here is designed to ... | brunopistone/mnemoai | src/mnemoai/client/transcript_export.py | .py | 526f8a6ba37c0d6b | 7.42 | 6 |
import sys
import threading
import time
# Braille frames shared by the stdout animation (Spinner._spin) and the
# pinned-toolbar renderer (spinner_toolbar_text).
_SPINNER_FRAMES = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
class SpinnerStatus:
"""Thread-safe status shared between the ``Spinner`` (worker thread) and the
pinned status line... | brunopistone/mnemoai | src/mnemoai/client/ui/spinner.py | .py | ae225e4d8ea3cbef | 7.42 | 6 |
"""The pinned footer line: what the NEXT turn costs, always in view.
Replaces the per-turn ``[Context: N tokens]`` notice — a number that mattered
every turn but scrolled away with the turn that printed it, and read as debug
output. Here it sits under the input, with a meter that colors amber past 70% of
the window an... | brunopistone/mnemoai | src/mnemoai/client/ui/status_bar.py | .py | e8fbb93e3ffd8c14 | 7.42 | 6 |
"""Streaming spinner callback handler."""
import threading
from typing import Optional
from langchain_core.callbacks import BaseCallbackHandler
from mnemoai.client.ui.spinner import Spinner
class StreamingCallbackHandler(BaseCallbackHandler):
"""Callback handler for spinner control during streaming."""
de... | brunopistone/mnemoai | src/mnemoai/client/ui/streaming_callback.py | .py | 32797b64e4a055c7 | 7.42 | 6 |
"""Compatibility data between the Infrahub Python SDK and Infrahub server.
This module provides structured data for auto-generating the compatibility
matrix documentation page. Update the lists below when new releases are made.
"""
from __future__ import annotations
from dataclasses import dataclass
@dataclass
cla... | opsmill/infrahub-sdk-python | docs/docs_generation/compatibility.py | .py | d51fb7c87c35fe76 | 7.64 | 18 |
from __future__ import annotations
from abc import ABC, abstractmethod
class ADocContentGenMethod(ABC):
"""Strategy for producing documentation content as a string.
Each subclass implements ``apply()`` for a specific content source
(Jinja2 template, CLI command, pre-generated file, ...).
"""
@a... | opsmill/infrahub-sdk-python | docs/docs_generation/content_gen_methods/base.py | .py | 916b41644e2f6ff1 | 7.14 | 18 |
from __future__ import annotations
from abc import ABC
from .command import ACommand
class ATyperCommand(ACommand, ABC):
def __init__(self, name: str) -> None:
self.name = name
class TyperSingleCommand(ATyperCommand):
"""A single (non-group) infrahubctl command."""
def build(self) -> str:
... | opsmill/infrahub-sdk-python | docs/docs_generation/content_gen_methods/command/typer_command.py | .py | 67f16bfe042c3548 | 7.64 | 18 |
from __future__ import annotations
from typing import TYPE_CHECKING
from .base import ADocContentGenMethod
if TYPE_CHECKING:
from docs.docs_generation.content_gen_methods.mdx.mdx_code_doc import MdxFile
class FilePrintingDocContentGenMethod(ADocContentGenMethod):
"""Return the content of an already-generat... | opsmill/infrahub-sdk-python | docs/docs_generation/content_gen_methods/file_printing_method.py | .py | 50a3af0096325045 | 7.64 | 18 |
from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING, Any
from .base import ADocContentGenMethod
if TYPE_CHECKING:
from infrahub_sdk.template import Jinja2Template
class Jinja2DocContentGenMethod(ADocContentGenMethod):
"""Render a template using a ``Jinja2Template``.
The ... | opsmill/infrahub-sdk-python | docs/docs_generation/content_gen_methods/jinja2_method.py | .py | a49821ef7b43e5bf | 7.64 | 18 |
from __future__ import annotations
import tempfile
from abc import ABC, abstractmethod
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from invoke import Context
def _wrap_doctest_examples(content: str) -> str:
"""Wrap bare ``>>>`` doctest blocks... | opsmill/infrahub-sdk-python | docs/docs_generation/content_gen_methods/mdx/mdx_code_doc.py | .py | d770813795ccb2bb | 7.64 | 18 |
from __future__ import annotations
from dataclasses import dataclass
from itertools import groupby
from typing import TYPE_CHECKING
from .mdx_code_doc import ACodeDocumentation, MdxFile
from .mdx_collapsed_overload_section import CollapsedOverloadSection, MethodSignature
from .mdx_section import ASection, MdxSection,... | opsmill/infrahub-sdk-python | docs/docs_generation/content_gen_methods/mdx/mdx_collapsed_overload_code_doc.py | .py | 04f853e7f6aa32ee | 7.64 | 18 |
from __future__ import annotations
import re
from dataclasses import dataclass, field
from .mdx_section import ASection, MdxSection
@dataclass
class CollapsedOverloadSection(ASection):
"""Collapse a group of overloaded method sections into a primary entry plus a details block.
The remaining overloads are p... | opsmill/infrahub-sdk-python | docs/docs_generation/content_gen_methods/mdx/mdx_collapsed_overload_section.py | .py | 1211adf867e1d06d | 7.64 | 18 |
from __future__ import annotations
from dataclasses import dataclass
from .mdx_priority import SectionPriority
from .mdx_section import ASection, MdxSection, _parse_sections
@dataclass
class OrderedMdxSection(ASection):
"""Decorator around MdxSection that reorders child sections by priority.
Reorders immed... | opsmill/infrahub-sdk-python | docs/docs_generation/content_gen_methods/mdx/mdx_ordered_section.py | .py | 0d26a89e1b68af60 | 7.64 | 18 |
from __future__ import annotations
from dataclasses import dataclass, field
def _duplicates(items: list[str]) -> list[str]:
"""Return items that appear more than once, in order of first extra occurrence."""
seen: set[str] = set()
dupes: list[str] = []
for item in items:
if item in seen and it... | opsmill/infrahub-sdk-python | docs/docs_generation/content_gen_methods/mdx/mdx_priority.py | .py | 4520125e057e814c | 7.64 | 18 |
from __future__ import annotations
import re
from abc import ABC, abstractmethod
from collections.abc import Sequence
from dataclasses import dataclass, field
class ASection(ABC):
"""Abstract base for MDX section types."""
@property
@abstractmethod
def heading(self) -> str: ...
@property
@a... | opsmill/infrahub-sdk-python | docs/docs_generation/content_gen_methods/mdx/mdx_section.py | .py | f42b21f89b86ecd7 | 7.64 | 18 |
from __future__ import annotations
from collections import defaultdict
from typing import Any
from pydantic_settings import EnvSettingsSource
from infrahub_sdk.config import ConfigBase
def get_env_vars() -> dict[str, list[str]]:
"""Extract environment variable names for each field of ``ConfigBase``.
Retur... | opsmill/infrahub-sdk-python | docs/docs_generation/helpers.py | .py | e6df0da439066345 | 7.64 | 18 |
from __future__ import annotations
import re
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from docs.docs_generation.content_gen_methods import ADocContentGenMethod
class DocPage:
"""A documentation page whose content is produced by an injected generation method.
Args:
... | opsmill/infrahub-sdk-python | docs/docs_generation/pages/base.py | .py | 912d5ff69dc2d24f | 7.64 | 18 |
#!/usr/bin/env python3
"""Fetch Infrahub/SDK version mappings from GitHub and update compatibility.py.
Queries the GitHub API to discover Infrahub release tags, resolve the SDK
version pinned via the python_sdk submodule for each release, and rewrite
the RELEASE_MAPPINGS and VERSION_RANGES lists in compatibility.py.
... | opsmill/infrahub-sdk-python | docs/docs_generation/update_compatibility.py | .py | bc56b95b3444b7b7 | 7.64 | 18 |
"""
Logging module for Slack Bot V2
Provides structured logging with different levels and modules
"""
import logging
import sys
import os
from datetime import datetime
from typing import Optional
from logging.handlers import RotatingFileHandler, QueueHandler, QueueListener
import queue
import threading
import warnings
... | protella/chatgpt-bots | logger.py | .py | 5893808fea4db9c9 | 7.42 | 6 |
"""Message processor package.
`MessageProcessor` is resolved lazily. `message_processor.base` pulls in the whole
processing graph — the Slack and OpenAI clients, the streaming package, the tool
handlers — and several of those reach back into this package for leaf modules
(`prompts`, `message_markers`, `tool_registry`,... | protella/chatgpt-bots | message_processor/__init__.py | .py | aa727b1ebc55171d | 7.42 | 6 |
"""Dev-only turn barriers (spec §13 live checks, plan §4a).
Named seams where a live battery can freeze a turn and look at the world before it moves on. Some
claims are only checkable mid-flight: "the stream a turn renders is current as of admission" cannot
be observed from the outside once the reply has landed, and n... | protella/chatgpt-bots | message_processor/dev_barriers.py | .py | aba5a8e7a846210b | 7.42 | 6 |
"""F51 — the model-callable `fetch_url` tool.
The SAME hardened fetcher that backs ambient link capture, exposed so a directly-asked "read this
link" actually opens the URL instead of relying on web_search luck (the Reuters incident proved
web_search cited other domains and never retrieved the linked article). One fet... | protella/chatgpt-bots | message_processor/fetch_url_tool.py | .py | 87513c0f9cb2ffbb | 7.42 | 6 |
"""
Shared continuation-marker and message-splitting helpers.
Single source of truth for the "Continued..." markers used when a long reply is
split across multiple Slack messages, plus the helpers that keep splits safe
(code fences closed/reopened, Slack <entities> never cut mid-token) and the
rebuild-side strippers t... | protella/chatgpt-bots | message_processor/message_markers.py | .py | 670a2bfc753a0481 | 7.42 | 6 |
"""Per-message timestamps for model-visible thread context (F10).
Claude Tag stamps every message in its context with a local timestamp, letting it
reason across time gaps ("last night" vs "this morning", "you asked an hour ago"). Our
rebuilt history was bare `username: text` — the message `ts` lived only in metadata,... | protella/chatgpt-bots | message_processor/message_timestamps.py | .py | a53a3af4802f7a93 | 7.42 | 6 |
"""Test the 'znflow.DiGraph' class."""
import znflow
@znflow.nodify
def add(*args):
"""Add node."""
return sum(args)
class ComputeSum(znflow.Node):
"""Compute sum node."""
def __init__(self, inputs):
self.inputs = inputs
self.outputs = None
def run(self):
"""run method... | zincware/ZnFlow | tests/test_digraph.py | .py | 126c84781ac1393d | 7.92 | 6 |
"""Test the 'znflow.utils' module."""
import pytest
from znflow import utils
class ConvertToString(utils.IterableHandler):
"""Convert any value to a string."""
def default(self, value, **kwargs):
"""Update 'value'."""
text = kwargs.pop("text", None)
return str(value) + text if text ... | zincware/ZnFlow | tests/test_utils.py | .py | d3fabeeb473a2285 | 7.92 | 6 |
"""Support for 'pydantic' based Nodes.
Between building the graph and 'graph.run()' a field of a Node holds a
connection - a 'Connection', a 'CombinedConnections', a 'FunctionFuture' or a
'Node' - instead of the actual value. Pydantic validates every field against its
annotation, so it would coerce or reject such a co... | zincware/ZnFlow | znflow/_pydantic.py | .py | 5da31ca405f2e13a | 7.42 | 6 |
"""ZnFlow deployment using Dask."""
import dataclasses
import typing
import typing as t
import uuid
from dask.distributed import Client, Future
from znflow import handler
from znflow.handler import UpdateConnectionsWithPredecessor
from znflow.node import Node
from .base import DeploymentBase
if typing.TYPE_CHECKIN... | zincware/ZnFlow | znflow/deployment/dask_depl.py | .py | 4da1e9231198f84d | 7.42 | 6 |
import contextlib
import dataclasses
import functools
import logging
import typing
import uuid
import networkx as nx
from znflow import handler
from znflow.base import (
Connection,
FunctionFuture,
NodeBaseMixin,
empty_graph,
get_graph,
set_graph,
)
from znflow.deployment import VanillaDeploym... | zincware/ZnFlow | znflow/graph.py | .py | 4a74256553ad45c3 | 7.42 | 6 |
import dataclasses
from znflow import utils
from znflow.base import CombinedConnections, Connection, FunctionFuture
from znflow.node import Node
class AttributeToConnection(utils.IterableHandler):
def default(self, value):
if not isinstance(value, (FunctionFuture, Node)):
return value
... | zincware/ZnFlow | znflow/handler.py | .py | c76742e6d9251f10 | 7.42 | 6 |
from __future__ import annotations
import functools
import inspect
import uuid
from znflow import exceptions
from znflow._pydantic import allow_connections
from znflow.base import (
UNRESOLVED,
Connection,
FunctionFuture,
NodeBaseMixin,
carries,
disable_graph,
empty_graph,
get_graph,
)... | zincware/ZnFlow | znflow/node.py | .py | 31e08887efd7fb8f | 7.42 | 6 |
"""Computed fields for 'pydantic' based Nodes.
A computed attribute is a graph visible port: inside a 'znflow.DiGraph' reading
it yields a 'Connection', so another Node can be connected to it, and outside the
graph it is computed from the fields it reads. 'pydantic.computed_field' makes
such an attribute part of the m... | zincware/ZnFlow | znflow/pydantic.py | .py | da40ac47aa825b15 | 7.42 | 6 |
"""Utils of the 'ZnFlow' package."""
import abc
import functools
class IterableHandler(abc.ABC):
"""Iterable handler using single dispatch.
Attributes
----------
updated : bool, default=False
Set to True if handle updated data.
"""
updated: bool = False
def __init__(self):
... | zincware/ZnFlow | znflow/utils.py | .py | b18011220a7b4342 | 7.42 | 6 |
"""The 'ZnFlow' visualization module."""
import math
import networkx as nx
def get_count(node, graph) -> int:
"""Get the number of successors for the given node."""
successors = list(graph.predecessors(node))
return sum(get_count(x, graph) for x in successors) if len(successors) else 1
def get_colors(... | zincware/ZnFlow | znflow/visualize.py | .py | 5a0700ebf5636b19 | 7.42 | 6 |
"""Package metadata for tutor-contrib-aspects."""
import io
import os
import re
from setuptools import find_packages, setup
HERE = os.path.abspath(os.path.dirname(__file__))
class MultipleConstraintException(BaseException):
"""
Exception raised when multiple constraints are provided.
"""
def load_req... | openedx/tutor-contrib-aspects | setup.py | .py | 71186be1937fbb68 | 7.59 | 14 |
"""Aspects module for tutor v1 commands"""
from __future__ import annotations
import string
import sys
import click
from tutor import env
from tutoraspects.asset_command_helpers import (
ASSETS_PATH,
SupersetCommandError,
deduplicate_superset_assets,
import_superset_assets,
delete_aspects_unused... | openedx/tutor-contrib-aspects | tutoraspects/commands_v1.py | .py | e29ffe080211d8ac | 7.09 | 14 |
from alembic import op
import sqlalchemy as sa
revision = "0001"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
"""
-- Create the terrible user defined function to parse the org out of course URLs
-- if we need to update this just add a COALESCE around the whole thing and put ... | openedx/tutor-contrib-aspects | tutoraspects/templates/aspects/apps/aspects/migrations/alembic/versions/0001_get_org_from_course_url.py | .py | 2d0d6e53458c68a8 | 8.09 | 14 |
"""
add additional fields to course_names_dict and and course_names
"""
from alembic import op
revision = "0014"
down_revision = "0011"
branch_labels = None
depends_on = None
on_cluster = " ON CLUSTER '{{CLICKHOUSE_CLUSTER_NAME}}' " if "{{CLICKHOUSE_CLUSTER_NAME}}" else ""
def upgrade():
# We include these drop... | openedx/tutor-contrib-aspects | tutoraspects/templates/aspects/apps/aspects/migrations/alembic/versions/0014_add_course_names_fields.py | .py | a73267d15d1c99da | 7.09 | 14 |
"""
add additional fields to course_block_names_dict and course_block_names
"""
from alembic import op
revision = "0015"
down_revision = "0014"
branch_labels = None
depends_on = None
on_cluster = " ON CLUSTER '{{CLICKHOUSE_CLUSTER_NAME}}' " if "{{CLICKHOUSE_CLUSTER_NAME}}" else ""
engine = "ReplicatedReplacingMergeTr... | openedx/tutor-contrib-aspects | tutoraspects/templates/aspects/apps/aspects/migrations/alembic/versions/0015_add_course_key_blocks.py | .py | 91afa8f0fda4c809 | 7.09 | 14 |
"""
create user_profile sink table
This table is always created, but it will only be populated if ASPECTS_ENABLE_PII.
.. pii: Stores Open edX user profile data.
.. pii_types: user_id, name, username, location, phone_number, email_address, birth_date, biography, gender
.. pii_retirement: local_api, consumer_api
"""
fr... | openedx/tutor-contrib-aspects | tutoraspects/templates/aspects/apps/aspects/migrations/alembic/versions/0016_event_sink_user_profile.py | .py | 5ce97b4efda5c6e4 | 8.09 | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.