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
"""Pure, synchronous decisions for the admin XP tools (leveling L5). An admin adjusts a member's XP through the ``/xp`` group (give / take / set / reset / resetall). This module answers the small, testable questions those commands lean on with no discord, no database, no awaits: are the amounts in range, what is the r...
yaniswav/Yasuho
cogs/community/leveling/admin_rules.py
.py
1e21741fd044822f
7.24
2
"""Pure, synchronous decision engine for level-up role rewards (leveling L2). A guild's admin configures "reach level N, get role R" rules (the level_rewards table). This module answers exactly one question with no discord, no database, no awaits: given the guild's rules, its rewards_mode, and a member who just levele...
yaniswav/Yasuho
cogs/community/leveling/reward_rules.py
.py
90895de075214239
7.24
2
"""Purpose: the AniList profile connector - link a public AniList username, cache its stats, draw a sober card section from that cache. ``link`` is a single PUBLIC GraphQL request (the query AniList's own ``USER_STATS_QUERY`` already uses for ``/anilist profile`` - reused verbatim rather than restated, since the two s...
yaniswav/Yasuho
cogs/community/profile/connectors/anilist.py
.py
842901e127a91449
7.24
2
"""Purpose: the reference implementation of :class:`~.base.Connector` - the one connector P3 ships, and the double every test in this package drives. It exists for two reasons. First, an interface nobody implements is a guess: the example proves the contract is implementable end to end (validate offline, hand back a n...
yaniswav/Yasuho
cogs/community/profile/connectors/example.py
.py
4dbf04d35eae219b
7.24
2
"""Purpose: the osu! profile connector - a public username, cached into a sober card section (rank, pp, accuracy, level, country). Uses the osu! API v1 ``get_user`` endpoint and the ``osuKey`` already sitting in tokens.ini for the existing ``?osu`` lookup command (cogs/utility/searchweb.py) - the same key, read the sa...
yaniswav/Yasuho
cogs/community/profile/connectors/osu.py
.py
d2af58c6af39947c
7.24
2
import numpy as np import cv2 class Face: """ structure to store information about detected faces """ def __init__(self, img_path: str, img_width: int, img_height: int, img_resized_width: int, img_resized_height: int...
peterjakubowski/Face-Labeler-Pilot-Workflow
models/face.py
.py
45deaeca9fdb1005
7
0
#!/usr/bin/env python3 # Copyright 2024 Canonical Ltd. # See LICENSE file for licensing details. import os import pytest def pytest_addoption(parser: pytest.Parser) -> None: """Add options to the pytest command line. This is a pytest hook that is called when the pytest command line is being parsed. Ar...
canonical/notary-k8s-operator
tests/integration/conftest.py
.py
10d3395dde66d782
7.65
1
#!/usr/bin/env python3 # Copyright 2024 Canonical Ltd. # See LICENSE file for licensing details. import json import logging import tempfile from datetime import timedelta from pathlib import Path import jubilant import pytest import yaml from charmlibs.interfaces.tls_certificates import ( CertificateSigningReques...
canonical/notary-k8s-operator
tests/integration/test_charm.py
.py
f06ab0b1846b2eba
7.65
1
from fastapi import FastAPI, Request, HTTPException from contextlib import asynccontextmanager import os import requests #ENV variables GITHUB_DISPATCH_URL = os.getenv('GITHUB_DISPATCH_URL') GITHUB_TOKEN = os.getenv('GITHUB_TOKEN') @asynccontextmanager async def lifespan(app: FastAPI): """Startup function to test...
GlueOps/gatekeeper
main.py
.py
79f401b95bc8ef1d
7.15
1
from typing import Dict, List, Iterable, Callable, Sequence, TypeVar, Tuple from matplotlib.axes import Axes from numpy.typing import NDArray import os import copy import numpy as np from sqlalchemy.orm import Session from tqdm import tqdm from ehk.common.plotting import plt_figure, plt_save_and_close, setup_paper_p...
billstark001/extended-hk-model
experiments/paper/main_scan/plot.py
.py
48e09ccf8367ef0d
7
0
from __future__ import annotations from typing import TYPE_CHECKING, List, Sequence import argparse import networkx as nx import matplotlib.pyplot as plt from matplotlib.axes import Axes from matplotlib.gridspec import GridSpec from ehk.common.plotting import ( plt_figure, setup_paper_params, plot_network...
billstark001/extended-hk-model
experiments/paper/mechanism_cases/plot_baseline.py
.py
ce5ecb59e4823f53
7
0
from typing import Tuple from numpy.typing import NDArray import numpy as np from scipy.stats import gaussian_kde def linear_func(x, a, b): """Simple linear function: f(x) = a*x + b""" return a * x + b def scale_array( arr: NDArray, range_from: Tuple[float, float], range_to: Tuple[float, float], ): ...
billstark001/extended-hk-model
experiments/paper/pathway_index/data_utils.py
.py
3fdb185fc709c4f5
7
0
"""Configuration for the paper's counterfactual landscape comparison.""" from __future__ import annotations from dataclasses import dataclass from typing import Any from ehk.common.settings import register_path NORMALIZED_TIMES = tuple(i / 10 for i in range(11)) # Use common random numbers across scenarios to red...
billstark001/extended-hk-model
experiments/theory_guided/social_force_probe/scenarios.py
.py
c81e13fa4087896a
7
0
import argparse import os from typing import List, Optional def get_files_with_prefix(files: List[str], prefix: str) -> List[str]: """Return all files in the list that start with the given prefix.""" return [f for f in files if f.startswith(prefix)] def get_latest_file(files: List[str], dir_path: str) -> Option...
billstark001/extended-hk-model
scripts/maintenance/clear_dir.py
.py
5294aefe0d1927ac
7
0
import argparse import asyncio import json import os import random import re import time import traceback from datetime import datetime, timedelta, timezone from pathlib import Path from urllib.parse import urljoin, urlparse import aiohttp import requests import tldextract from aiohttp import ClientSession, ClientTime...
navchandar/civic-media-scout
civic_media_scout/civic_media_scout.py
.py
7a3142abb873e18d
7.39
5
"""Verify the parsers against a real SMS backup file. The unit suite proves the parsers behave correctly on hand-built messages. This script proves they still behave correctly on ~4,700 real ones — which is where a regex change that passes every unit test quietly loses 40 transactions shows up. Run it after any change...
ssahmed532/sms_msgs_scraper
scripts/verify_against_backup.py
.py
b7f983fb2424d18d
7
0
from collections import namedtuple from dataclasses import dataclass from datetime import datetime from zoneinfo import ZoneInfo """A namedtuple to represent and combine the two important attributes of a Credit Card transaction: currency: the currency of the transaction amount: the amount of the transaction (...
ssahmed532/sms_msgs_scraper
src/cc_txn.py
.py
116d82d1450e7ec1
7
0
"""The shared Rich console, theme and formatting helpers behind everything this tool prints. Every module renders through the single `console` defined here rather than through bare `print()`, so that one theme decides what a bank tag, a currency, an amount, a txn type or a warning looks like — wherever it is rendered....
ssahmed532/sms_msgs_scraper
src/console_ui.py
.py
e9fdf6b58d535bb5
7
0
from dataclasses import dataclass from datetime import datetime from enum import StrEnum, auto from cc_txn import CurrencyAmountTuple class DebitTxnType(StrEnum): """The kind of account debit a DebitTxnDC represents.""" CARD_PURCHASE = auto() ATM_WITHDRAWAL = auto() ACCOUNT_DEBIT = auto() FUNDS_...
ssahmed532/sms_msgs_scraper
src/debit_txn.py
.py
8191018a7841434d
7
0
import re import xml import xml.etree.ElementTree as ET from datetime import datetime from cc_txn import CreditCardTxnDC, CurrencyAmountTuple from common import DEFAULT_TZ from console_ui import printWarning class FBLSmsParser: ID = "FBL" # SMS messages from any one of these short codes will be assumed to ...
ssahmed532/sms_msgs_scraper
src/parser/fbl_sms_parser.py
.py
d8649551ef76c16b
7
0
import re import xml import xml.etree.ElementTree as ET from datetime import datetime from cc_txn import CreditCardTxnDC, CurrencyAmountTuple from console_ui import printError class HBLSmsParser: ID = "HBL" # SMS messages from any one of these short codes will be assumed to # be from HBL Bank. # HBL ...
ssahmed532/sms_msgs_scraper
src/parser/hbl_sms_parser.py
.py
159c9ab0f34506f6
7
0
import re import xml.etree.ElementTree from datetime import datetime from cc_txn import CurrencyAmountTuple from common import DEFAULT_TZ from console_ui import printError from debit_txn import DebitTxnDC, DebitTxnType class MeznSmsParser: ID = "MEZN" # SMS messages from any one of these short codes will be ...
ssahmed532/sms_msgs_scraper
src/parser/mezn_sms_parser.py
.py
fe1fbb851c9274c7
7
0
import re import xml.etree.ElementTree as ET from datetime import datetime from cc_txn import CreditCardTxnDC, CurrencyAmountTuple from common import DEFAULT_TZ from console_ui import printWarning class SCBSmsParser: ID = "SCB" # SMS messages from any one of these short codes will be assumed to be # from...
ssahmed532/sms_msgs_scraper
src/parser/scb_sms_parser.py
.py
1eaf2b3090b42d37
7
0
import hashlib import xml import xml.etree.ElementTree as ET from collections import defaultdict from console_ui import ( EMPTY_VALUE, bankText, countText, labelText, printSideBySide, summaryTable, ) from parser.fbl_sms_parser import FBLSmsParser from parser.hbl_sms_parser import HBLSmsParser f...
ssahmed532/sms_msgs_scraper
src/sms_backup_file_parser.py
.py
1378c96abc4fe593
7
0
import re import tempfile import tomllib import unittest import xml.etree.ElementTree as ET from datetime import datetime from pathlib import Path from click.testing import CliRunner from cc_txn import CreditCardTxnDC, CurrencyAmountTuple from common import DEFAULT_TZ from sms_txn_query_tool import _filterTxnsByBank,...
ssahmed532/sms_msgs_scraper
tests/test_cli_commands.py
.py
73c03cf519fdee9f
7.5
0
import unittest from datetime import datetime import click from cc_txn import CreditCardTxnDC, CurrencyAmountTuple from common import DEFAULT_TZ from debit_txn import DebitTxnDC, DebitTxnType from sms_txn_query_tool import _dateRangeLabel, _filterTxnsByDateRange class TestDateRangeFilter(unittest.TestCase): de...
ssahmed532/sms_msgs_scraper
tests/test_date_range_filter.py
.py
bc02be7be97a98f5
7.5
0
import tempfile import unittest import xml.etree.ElementTree as ET from datetime import datetime from parser.fbl_sms_parser import FBLSmsParser from pathlib import Path from common import DEFAULT_TZ from sms_backup_file_parser import SmsBackupFileParser # A single well-formed FBL CC txn msg body, reused across the te...
ssahmed532/sms_msgs_scraper
tests/test_fbl_sms_parser.py
.py
0bfe7eb300762a72
7.5
0
import unittest import xml import xml.etree.ElementTree as ET from datetime import datetime, timedelta from parser.hbl_sms_parser import HBLSmsParser from cc_txn import CurrencyAmountTuple from common import DEFAULT_TZ class TestHBLSmsParser(unittest.TestCase): def _createBaseSmsMsg(self) -> ET.Element: ...
ssahmed532/sms_msgs_scraper
tests/test_hbl_sms_parser.py
.py
a01d2922abf2e5c0
7.5
0
#!/usr/bin/env python3 """ Skill Initializer - Creates a new skill from template Usage: init_skill.py <skill-name> --path <path> Examples: init_skill.py my-new-skill --path skills/public init_skill.py my-api-helper --path skills/private init_skill.py custom-skill --path /custom/location """ import sy...
hydrosolutions/SAPPHIRE_Forecast_Tools
.claude/skills/skill-creator/scripts/init_skill.py
.py
ff282c4a54ef92f0
7.15
1
#!/usr/bin/env python3 """ Skill Packager - Creates a distributable .skill file of a skill folder Usage: python scripts/package_skill.py <path/to/skill-folder> [output-directory] Example: python scripts/package_skill.py skills/public/my-skill python scripts/package_skill.py skills/public/my-skill ./dist "...
hydrosolutions/SAPPHIRE_Forecast_Tools
.claude/skills/skill-creator/scripts/package_skill.py
.py
c6487dfc6fb70cf8
7.15
1
import os import sys from dataclasses import dataclass from types import ModuleType from src.gettext_config import _ import src.processing as processing from src.environment import load_configuration import src.gettext_config as localize @dataclass(frozen=True) class DashboardConfig: """Immutable container for al...
hydrosolutions/SAPPHIRE_Forecast_Tools
apps/forecast_dashboard/dashboard/config.py
.py
87a3b3e880611504
7.15
1
#!/usr/bin/env python3 """CLI tool for inspecting forecast data from the SAPPHIRE API. Produces matplotlib plots: 1. Forecast time series — forecasted discharge per model with quantile bands 2. Model comparison — bar chart of forecast values across models for a date 3. Forecast vs observed — scatter (when observ...
hydrosolutions/SAPPHIRE_Forecast_Tools
apps/forecast_dashboard/dev_code/inspect_forecasts.py
.py
c2201234dd5b4346
7.65
1
import panel as pn import param import os from datetime import datetime import zipfile import io import pathlib from .gettext_config import translation_manager, _ import logging logger = logging.getLogger(__name__) class FileDownloader(param.Parameterized): """A Panel component for downloading files from a specif...
hydrosolutions/SAPPHIRE_Forecast_Tools
apps/forecast_dashboard/src/file_downloader.py
.py
249ac4cf58d3d29c
7.15
1
# gettext_config.py import os import gettext import param class TranslationManager(param.Parameterized): language = param.String(default='en') def __init__(self, **params): super().__init__(**params) self.locale_dir = 'locale' # Default locale directory self.translations = {} ...
hydrosolutions/SAPPHIRE_Forecast_Tools
apps/forecast_dashboard/src/gettext_config.py
.py
a8aa7ec171c8b511
7.15
1
# src/month_lead.py """Shared monthly-lead accessor for the UI layer. ``src/db.py`` resolves "what lead does the main monthly panel show" with a nested ``_safe_lead`` closure inside ``_get_data_monthly`` — not importable from outside that function. This module mirrors that same fallback + warn semantics as standalone,...
hydrosolutions/SAPPHIRE_Forecast_Tools
apps/forecast_dashboard/src/month_lead.py
.py
b59a691981080aeb
7.15
1
# Description: This file contains the code for generating reports. import os import time # ieasyreports from ieasyreports.core.report_generator import DefaultReportGenerator from ieasyreports.settings import TagSettings, ReportGeneratorSettings from ieasyreports.core.tags.tag import Tag # Logging import logging logg...
hydrosolutions/SAPPHIRE_Forecast_Tools
apps/forecast_dashboard/src/reports.py
.py
3acd7b17975eee3f
7.15
1
"""Snow display-window helpers shared by dashboard data and plotting.""" from datetime import date, timedelta import pandas as pd def snow_display_window( start_month: int, start_day: int, ref_date: date, ) -> tuple[pd.Timestamp, pd.Timestamp]: """Return (begin, end) Timestamps for the snow display ...
hydrosolutions/SAPPHIRE_Forecast_Tools
apps/forecast_dashboard/src/snow_window.py
.py
5cf6832c8490bd64
7.15
1
#!/usr/bin/env python3 """Generate deterministic fixture JSON files for forecast_dashboard tests. All values are hand-calculable so tests can assert on exact numbers. Stations: 99001 — TFT best, LR available 99002 — TiDE best, LR available 99003 — LR only (no ML models) Run: cd apps/forecast_dashboar...
hydrosolutions/SAPPHIRE_Forecast_Tools
apps/forecast_dashboard/tests/generate_dashboard_test_data.py
.py
181d8f659912c287
7.65
1
import enum class Drops(enum.Enum): """Перечисление сбрасывающих кодов ANSI.""" RESET = 0 DEFAULT_COLOR = 39 DEFAULT_BACKGROUND = 49 DISABLE_BOLD = 22 DISABLE_ITALIC = 23 DISABLE_UNDERLINED = 24 DISABLE_BLINCKED = 25 DISABLE_THROUGHLINED = 29 DISABLE_UPPERLINED = 29 class Colors(enum.Enum): """Перечисле...
DUB1401/dublib
src/dublib/cli/text_styler/codes.py
.py
ae6d546c791f2928
7.15
1
from dataclasses import dataclass from .codes import BackgroundsColors as _BackgroundsColorsCodes from .codes import Colors as _ColorsCodes from .codes import Decorations as _DecorationsCodes from .codes import Drops as _DropsCodes @dataclass(frozen = True) class Drops: """Набор специальных управляющих последователь...
DUB1401/dublib
src/dublib/cli/text_styler/escapes.py
.py
ad9666669fd91eb5
7.15
1
import logging from .cli.text_styler import FastStyler, GetStyledTextFromHTML class ColorFormatter(logging.Formatter): """Форматировщик вывода в консоль с поддержкой цветов.""" def format(self, record: logging.LogRecord) -> str: """ Форматирует записи с поддержкой цветной палитры. :param record: Запись лога...
DUB1401/dublib
src/dublib/core.py
.py
771d7d1d46d96f01
7.15
1
from datetime import datetime class AuthorizationRedefining(Exception): """Исключение: переопределение заголовка _Authorization_.""" def __init__(self): """Исключение: переопределение заголовка _Authorization_""" super().__init__("Generate \"Authorization\" by headers subsystem.") class HeaderRedefi...
DUB1401/dublib
src/dublib/exceptions/web_requestor.py
.py
17047480d9aa8340
7.15
1
import copy from typing import Any, Sequence, overload import orjson from . import dictionary as dictionary from . import string as string def Copy(data: Any) -> Any: """ Выполняет глубокое копирование объекта с автоматическим определением наилучшего метода. Объекты, которые могут быть сериализованы...
DUB1401/dublib
src/dublib/functions/data/__init__.py
.py
73c8b9cb152f27f2
7.15
1
from typing import Any import more_itertools def InsertAfterKey(base_dictionary: dict, insertable_dictionary: dict, target_key: Any, overwrite: bool = False) -> dict: """ Вставляет словарь после определённого ключа. При конфликте ключей приоритет расположения отдаётся порядку ключей из вставляемого словаря. :para...
DUB1401/dublib
src/dublib/functions/data/dictionary.py
.py
37ba55d0345022ed
7.15
1
import subprocess import sys def CheckPythonMinimalVersion(major: int, minor: int, raise_exception: bool = True) -> bool: """ Проверяет, соответствует ли используемая версия Python минимальной требуемой. :param major: Идентификатор Major-версии Python. :type major: int :param minor: Идентификатор Minor-версии Py...
DUB1401/dublib
src/dublib/functions/system.py
.py
796cb7d6ccfdbf44
7.15
1
from functools import wraps from time import sleep from telebot import apihelper def ignore_frecuency_errors(function): """ Декоратор. Игнорирует ошибки частоты запросов, автоматически выжидая необходимый интервал. :param function: Функция или метод из библиотеки **pyTelegramBotAPI**. """ @wraps(function) def...
DUB1401/dublib
src/dublib/telebot_utils/master/decorators.py
.py
f47cbf000547326f
7.15
1
# Copyright 2023 Canonical Ltd. # See LICENSE file for licensing details. """# Juju Charm Library for the `ldap` Juju Interface. This juju charm library contains the Provider and Requirer classes for handling the `ldap` interface. ## Requirer Charm The requirer charm is expected to: - Provide information for the p...
canonical/sssd-operator
lib/charms/glauth_k8s/v0/ldap.py
.py
896c7fbcc1427bf4
7
0
#!/usr/bin/env python3 # Copyright 2023-2026 Canonical Ltd. # # 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 applicabl...
canonical/sssd-operator
src/charm.py
.py
336caa5c69484096
7
0
# Copyright 2023-2026 Canonical Ltd. # # 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 agreed to in w...
canonical/sssd-operator
src/sssd.py
.py
6c3bc7188a8e78a5
7
0
# Copyright 2026 Canonical Ltd. # # 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 agreed to in writin...
canonical/sssd-operator
tests/integration/test_edge.py
.py
df16bd29528a54cd
7.5
0
# Given two strings needle and haystack, # return the index of the first occurrence of needle in haystack # , or -1 if needle is not part of haystack. needle = "sad" haystack = "sadbutsad" class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: st...
danmcg1/randomProgrammingProjects
projects/leetCode/firstOccurrenceOfString.py
.py
850be10291674e99
7.15
1
# Given a string s consisting of words and spaces, # return the length of the last word in the string. # A word is a maximal consisting of non-space characters only. s = " fly me to the moon " class Solution(object): def lengthOfLastWord(self, s): """ :type s: str :rtype: int ...
danmcg1/randomProgrammingProjects
projects/leetCode/lengthOfLastWord.py
.py
e3335ce0c281b4f1
7.15
1
# Write a function to find the longest common prefix string amongst an array of strings. # If there is no common prefix, return an empty string "". strs = ["flower","flow","float"] strs = [""] def singleEnum(list): enum = [] enum += enumerate(list) return enum class Solution(object): def longestComm...
danmcg1/randomProgrammingProjects
projects/leetCode/longestCommonPrefix.py
.py
7dd7807454e05e6a
7.15
1
# You are given a large integer represented as an integer array digits, # where each digits[i] is the ith digit of the integer. # The digits are ordered from most significant to least significant in left-to-right order. # The large integer does not contain any leading 0's. # Increment the large integer by one and r...
danmcg1/randomProgrammingProjects
projects/leetCode/plusOne.py
.py
b0daf59339697947
7.15
1
# Given an integer array nums sorted in non-decreasing order, # remove the duplicates in-place such that each unique element appears only once. # The relative order of the elements should be kept the same. # Consider the number of unique elements in nums to be k​​​​​​​​​​​​​​. # After removing duplicates, return th...
danmcg1/randomProgrammingProjects
projects/leetCode/removeDupesFromArray.py
.py
6cce3162308f647a
7.15
1
# Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. # The order of the elements may be changed. # Then return the number of elements in nums which are not equal to val. # Consider the number of elements in nums which are not equal to val be k, # to get accepted, you nee...
danmcg1/randomProgrammingProjects
projects/leetCode/removeElement.py
.py
fb8c213dfbd1d082
7.15
1
# Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. # Symbol Value # I 1 # V 5 # X 10 # L 50 # C 100 # D 500 # M 1000 # For example, 2 is written as II in Roman numeral, just two ones added toget...
danmcg1/randomProgrammingProjects
projects/leetCode/romanNumerals.py
.py
ec35e297e4cfdcb5
7.15
1
# Given a non-negative integer x, return the square root of x rounded down to the nearest integer. # The returned integer should be non-negative as well. # You must not use any built-in exponent function or operator. x = 4 class Solution(object): def mySqrt(self, x): """ :type x: int :rt...
danmcg1/randomProgrammingProjects
projects/leetCode/squareRoot.py
.py
6675c842b591ac52
7.15
1
# Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. # You may assume that each input would have exactly one solution, and you may not use the same element twice. # You can return the answer in any order. nums = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,1...
danmcg1/randomProgrammingProjects
projects/leetCode/twoSum.py
.py
9c59197ae271878c
7.15
1
# Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. # An input string is valid if: # Open brackets must be closed by the same type of brackets. # Open brackets must be closed in the correct order. # Every close bracket has a corresponding open br...
danmcg1/randomProgrammingProjects
projects/leetCode/validParentheses.py
.py
341a0f60e73723a4
7.15
1
"""Automated daily sign-in for gamer.com.tw (Bahamut). Logs in with credentials from the BAHA_ACCOUNT / BAHA_PASSWORD environment variables; the daily reward is claimed automatically on sign-in. Designed to run headless in CI (e.g. GitHub Actions). """ import logging import os import sys import random import time f...
Matthew-HMS/baha_login
baha.py
.py
aa523b6242577014
7.35
4
"""Validate build logs for warnings that should fail strict builds.""" from __future__ import annotations import argparse import json import re import sys from pathlib import Path WARNING_LINE_PATTERNS: tuple[re.Pattern[str], ...] = ( re.compile(r"^\s*(?:LaTeX|Package|Class)\b.*Warning:"), # \vbox too: a ver...
Kataglyphis/Kataglyphis-DocumANTation
md2pdfLib/check_build_log.py
.py
e5429a71879de4d2
7.24
2
"""Shared pandoc build utilities for every document type in md2pdfLib.presets.""" from __future__ import annotations import re import subprocess import sys from dataclasses import dataclass, field from pathlib import Path PROJECT_ROOT = Path(__file__).resolve().parent.parent class BuildError(Exception): """Rai...
Kataglyphis/Kataglyphis-DocumANTation
md2pdfLib/pandoc_builder.py
.py
cc49978e4b017492
7.24
2
"""Finish an emitted deck: layout media, slide numbers, code boxes. Pandoc copies slide layouts and their relationship parts verbatim from the reference deck, but rebuilds ppt/media/ only from what the *slides* embed -- media referenced solely by a layout (the brand title background) is silently left behind, so the la...
Kataglyphis/Kataglyphis-DocumANTation
md2pdfLib/presentation/pptx/finalize_deck.py
.py
9893ec8dae236915
7.24
2
"""Keep a frame title inside its box, the way the beamer deck keeps it there. The beamer theme sets frametitles small enough that even the longest one in this deck -- "2.7 Code example: Rust (tiny CLI-like utility)" -- stays on a single line. Pandoc's pptx writer leaves the title run unsized, so it renders at the mast...
Kataglyphis/Kataglyphis-DocumANTation
md2pdfLib/presentation/pptx/fit_titles.py
.py
a3070b4063b0c810
7.24
2
"""Give pptx code blocks the beamer code box: dark, framed, and sized to fit. The slides render fenced code inside the shared brand tcolorbox (md2pdfLib/common/latex/brand-code-block.tex): dark fill, accent frame, rounded corners, and \\scriptsize verbatim that wraps instead of overflowing. Pandoc's pptx writer has no...
Kataglyphis/Kataglyphis-DocumANTation
md2pdfLib/presentation/pptx/style_code.py
.py
f1681df23855dbe8
7.24
2
"""Fail the build if a generated pptx is not on-brand. The strict gate reads pandoc's log, so it catches what pandoc *complains* about. It cannot catch a deck that builds perfectly and looks wrong -- if pandoc stopped honouring --reference-doc, or --syntax-highlighting was dropped, every existing check would still pas...
Kataglyphis/Kataglyphis-DocumANTation
md2pdfLib/presentation/pptx/verify_brand.py
.py
4cbfccfb65d01ebb
7.24
2
"""Preset BuildConfig factories for all document types.""" from collections.abc import Callable from md2pdfLib.pandoc_builder import BuildConfig # Generated from brand.json at build time, not committed -- see # presentation/pptx/make_reference.py. PPTX_REFERENCE = "data/out/reference.pptx" # Lua filter mapping fenc...
Kataglyphis/Kataglyphis-DocumANTation
md2pdfLib/presets.py
.py
2264ed262b23e108
7.24
2
"""Binary assets get the same discipline the brand tokens already get. ``tests/test_generate_style.py`` fails if a colour is declared in brand.json and nothing reads it, and ``style/generate_style.py --check`` fails if one of the three generated ``brand.tokens.json`` copies drifts. Nothing applied either rule to the i...
Kataglyphis/Kataglyphis-DocumANTation
tests/test_assets_are_single_copies.py
.py
3184781c053488aa
7.74
2
"""Keep AGENTS.md's version table from drifting away from the Dockerfile. The table calls itself a snapshot, and a snapshot nobody checks goes stale: the Pandoc and uv rows were both wrong against the Dockerfile they name as the authority, and they went stale twice in one afternoon because the pins are synced in from ...
Kataglyphis/Kataglyphis-DocumANTation
tests/test_docs_versions.py
.py
143644bd54302251
7.74
2
"""Identity belongs to style/brand.json, exactly like the colours do. AGENTS.md has stated the rule for a long time -- "All \\url{}, \\email{}, \\github{} references must use consistent values. The canonical URL is ... and GitHub handle is ..." -- and nothing enforced it. So the author name was typed by hand into 16 f...
Kataglyphis/Kataglyphis-DocumANTation
tests/test_identity_is_single_source.py
.py
2440a57915e14537
7.74
2
"""Tests for frame-title fitting (keeping a title out of the separator rule). Pandoc leaves the title run unsized, so it renders at the master's 33pt, where seven of this deck's titles need a second line that falls out of the placeholder and through the accent rule beneath it. The beamer deck keeps the same strings on...
Kataglyphis/Kataglyphis-DocumANTation
tests/test_pptx_titles.py
.py
7297a2f90bd327c5
7.74
2
"""Tests for the document build presets.""" from __future__ import annotations from md2pdfLib.pandoc_builder import BuildConfig from md2pdfLib.presets import PPTX_REFERENCE, PRESETS, beamer, book, demo, example, pptx def test_presets_registry_keys(): assert set(PRESETS) == {"book", "beamer", "demo", "example", ...
Kataglyphis/Kataglyphis-DocumANTation
tests/test_presets.py
.py
dd6851787c645db4
7.74
2
"""Every preset must be buildable, and every source must be built by a preset. Two orphan classes hid here for a long time, both silent: - ``data/example/`` had no preset at all. Its own getting-started chapter told the reader to put their Markdown there and run ``make book`` -- which builds ``data/book/`` -- so ...
Kataglyphis/Kataglyphis-DocumANTation
tests/test_presets_reach_every_source.py
.py
779bd453ab5dd61d
7.74
2
from abc import ABC, abstractmethod from enum import Enum from typing import Any, Optional import requests from requests import structures from pydantic import BaseModel from acslib.base import status from acslib.base.config import ACSConfig class ACSConnectionException(Exception): pass class ACSRequestExcept...
ncstate-sat/acslib
acslib/base/connection.py
.py
58d776482d5d9b96
7
0
"""Use CCure CRUD operations to perform some common actions""" from datetime import datetime, timezone from typing import Optional from acslib.base import ( ACSRequestData, ACSRequestResponse, ACSRequestException, status, ) from acslib.ccure.base import CcureACS from acslib.ccure.connection import Ccu...
ncstate-sat/acslib
acslib/ccure/actions.py
.py
74bcdc2cd48b8123
7
0
from typing import Optional, Any from acslib.base import AccessControlSystem, ACSRequestData, ACSRequestResponse, ACSRequestException from acslib.ccure.connection import CcureConnection, ACSRequestMethod from acslib.ccure.filters import CcureFilter, NFUZZ, PersonnelFilter class CcureACS(AccessControlSystem): """...
ncstate-sat/acslib
acslib/ccure/base.py
.py
d3e9ad4e0fdbe977
7
0
# Licensed under the MIT License # https://github.com/craigahobbs/bare-script-py/blob/main/LICENSE """ bare-script setup """ from setuptools import setup, Extension from setuptools.command.build_ext import build_ext class OptionalBuildExt(build_ext): """ Build C extensions optionally - if compilation fails,...
craigahobbs/bare-script-py
setup.py
.py
c5bbf333acd2f41f
7
0
# Licensed under the MIT License # https://github.com/craigahobbs/bare-script-py/blob/main/LICENSE """ bare-script command-line interface (CLI) """ import argparse from functools import partial import os import sys import time from .options import fetch_read_write, log_stdout, url_file_relative from .runtime import ...
craigahobbs/bare-script-py
src/bare_script/bare.py
.py
467f5aaf8430e9ff
7
0
# Licensed under the MIT License # https://github.com/craigahobbs/bare-script-py/blob/main/LICENSE """ BareScript value utilities """ import datetime import json import math import re import uuid def value_type(value): """ Get a value's type string :param value: The value :return: The type string (...
craigahobbs/bare-script-py
src/bare_script/value.py
.py
b979bb9c02764f68
7
0
from fastapi import FastAPI, Request, HTTPException, BackgroundTasks from contextlib import asynccontextmanager import os import glueops.setup_logging import schedule import time import traceback from utils.github import projects, auth, hooks # Initialize Logger log_level = os.environ.get('LOG_LEVEL', 'INFO') logger ...
GlueOps/storypoints
app/main.py
.py
c5356a0ce9d6b6bf
7
0
import os import datetime import jwt import time import requests import traceback from threading import Lock from typing import Dict, Optional, Any import glueops.setup_logging # Initialize Logger logger = glueops.setup_logging.configure(level=os.environ.get('LOG_LEVEL', 'INFO')) GITHUB_GRAPHQL_URL = "https://api.gi...
GlueOps/storypoints
app/utils/github/auth.py
.py
b43f3c91ad876a5f
7
0
import os import json import time import datetime import traceback from typing import List, Dict, Any, Optional import requests import glueops.setup_logging from utils.github import auth # Initialize Logger logger = glueops.setup_logging.configure(level=os.environ.get('LOG_LEVEL', 'INFO')) GITHUB_GRAPHQL_URL = "htt...
GlueOps/storypoints
app/utils/github/hooks.py
.py
c491a529ed185ebc
7
0
#!/usr/bin/env python3 """Vendor-neutral command guard: given a shell command about to run against this repo, report known-dangerous patterns before they execute. This is the AUTHORITATIVE guard logic — agent-product hooks (e.g. .claude/hooks/bash_guard.py) are thin adapters over it, and safety never depends on it alo...
gnosischain/dbt-cerebro
scripts/agent_context/guard.py
.py
9d21d84b327c36d7
7
0
#!/usr/bin/env python3 """ Add `as_of_date` to point-in-time api endpoints that lack a date column. For each target api view, find the nearest upstream model that has a date column (BFS over depends_on) and wrap the view body to expose `as_of_date = toDate(max(<that date col>))` of that ancestor — the data's real fres...
gnosischain/dbt-cerebro
scripts/checks/add_as_of_date.py
.py
d890d4fe19d8f253
7
0
#!/usr/bin/env python3 """Add/normalize a recency-bounded dbt_utils.unique_combination_of_columns test on every in-scope incremental model that meets the write-time no-duplicate invariant (append/insert_overwrite/table — NOT the allowlisted delete+insert exceptions). The combination key is the model's ReplacingMergeTre...
gnosischain/dbt-cerebro
scripts/checks/add_unique_tests.py
.py
226f6968a3298bd7
7.5
0
#!/usr/bin/env python3 """ CI guard for the API/MCP exposure convention. Every `production` model carrying an `api:` tag (an exposed endpoint) must: 1. have an `api:<resource>` tag whose name does NOT end in a time-grain or window suffix (grain/window live in `granularity:` / `window:` tags, not the endpoint id...
gnosischain/dbt-cerebro
scripts/checks/check_api_tags.py
.py
69099a6176c7ed3f
7
0
#!/usr/bin/env python3 """CI guard: reject schema-generator noise in model meta. DENYLIST gate, deliberately NOT a whitelist: model meta carries real runtime and privacy contracts (owner, authoritative, full_refresh, inference_notes, agent, api.exclude_from_api, privacy_tier, expose_to_mcp, ...) that a naive whitelist...
gnosischain/dbt-cerebro
scripts/checks/check_meta_keys.py
.py
04d1226fc2013fb5
7
0
#!/usr/bin/env python3 """ CI guard for the envio_ga (gnosis_app_gt) build policy. Complements no_delete_insert.py (which already bans delete+insert and requires partition_by on every insert_overwrite model project-wide). File-based (no manifest needed). For every model whose SQL references the envio_ga source, enforc...
gnosischain/dbt-cerebro
scripts/checks/envio_ga_policy.py
.py
0c2ddb4840361cbd
7
0
#!/usr/bin/env python3 """Measure memory/storage for dbt tables & views (metadata-only, cheap). Two dimensions: - STORAGE (tables only): system.parts -> bytes_on_disk, rows, and the RAM the table costs just by existing (primary-key index + marks held in memory). Views have no parts -> 0 storage; their cost i...
gnosischain/dbt-cerebro
scripts/checks/measure_memory.py
.py
62fcf5a49ea15eb2
7
0
#!/usr/bin/env python3 """One-shot migration helper: flip incremental models to the new write policy. Class A (append + microbatch tag): decode_logs/decode_calls models, Circles event intermediates, live/low-latency tables, raw event streams. Class B (insert_overwrite): everything else incremental that declares partit...
gnosischain/dbt-cerebro
scripts/checks/migrate_incremental_strategy.py
.py
61efb4140c0375bd
7
0
#!/usr/bin/env python3 """CI guard: enforce the zero-duplicate, mutation-free incremental policy. Scope: FIRST-PARTY models only (package_name == 'gnosis_dbt'). Vendored dbt packages (e.g. Elementary) ship their own materialization strategy that we do not control and must not edit — `dbt deps` would clobber any change...
gnosischain/dbt-cerebro
scripts/checks/no_delete_insert.py
.py
fa81e4b9f5ba3915
7
0
#!/usr/bin/env python3 """Classify failed dbt nodes from stashed per-batch run_results.json files. Reads every *.json under --stash-dir, inspects each node with status == "error", and partitions the unique_ids into TRANSIENT (retry-worthy ClickHouse errors) vs PERMANENT (logic/SQL bugs). Emits two lines on stdout cons...
gnosischain/dbt-cerebro
scripts/refresh/classify_failed_nodes.py
.py
34de92fefa470e68
7
0
"""Run-state identity shared by the refresh runners. Both scripts/full_refresh/refresh.py and scripts/refresh/dbt_incremental_runner.py persist resume state. Historically each used ONE fixed path, so a new invocation with a different --select silently clobbered a pending --resume (docs/lessons/refresh-state-collision....
gnosischain/dbt-cerebro
scripts/refresh/run_state.py
.py
f454d894ac0b2548
7
0
#!/usr/bin/env python3 """Generate the entity overlay from the entity dictionary. Scans every project model's PHYSICAL columns (manifest + catalog merge) against ``semantic/entity_dictionary.yml`` and writes two generated files: * ``semantic/authoring/generated/entities_generated.yml`` — per-model entity annotation...
gnosischain/dbt-cerebro
scripts/semantic/generate_entities.py
.py
807a73675f8038b1
7
0
#!/usr/bin/env python3 """ Fetch a contract ABI from Blockscout and append it to seeds/contracts_abi.csv. Unlike `dbt run-operation fetch_and_insert_abi`, this writes to the CSV (the canonical source of truth) rather than directly to the ClickHouse contracts_abi table. Running this then `dbt seed --select contracts_ab...
gnosischain/dbt-cerebro
scripts/signatures/fetch_abi_to_csv.py
.py
c0fb98b76ffee230
7
0
"""Dataset loading, validation, and deterministic demo-data generation.""" from __future__ import annotations import csv from collections import Counter from dataclasses import dataclass from pathlib import Path import numpy as np import pandas as pd from sklearn.datasets import make_classification DEFAULT_TARGET =...
Mohamed-ahmed-shokry/Credit-Card-Fraud-Detection
src/fraud_detection/data.py
.py
028686f32130ba96
7
0
"""Feature-distribution profiling and Population Stability Index reporting.""" from __future__ import annotations from dataclasses import asdict, dataclass from typing import Any, cast import numpy as np import pandas as pd STABLE_THRESHOLD = 0.1 DRIFT_THRESHOLD = 0.25 _EPSILON = 1e-6 class DriftError(ValueError)...
Mohamed-ahmed-shokry/Credit-Card-Fraud-Detection
src/fraud_detection/drift.py
.py
d814dd6bfdda3714
7
0
"""Threshold selection and metrics for imbalanced fraud classification.""" from __future__ import annotations from dataclasses import asdict, dataclass import numpy as np from sklearn.metrics import ( average_precision_score, balanced_accuracy_score, brier_score_loss, confusion_matrix, f1_score, ...
Mohamed-ahmed-shokry/Credit-Card-Fraud-Detection
src/fraud_detection/evaluation.py
.py
abcee7fe27a4a15c
7
0
#!/usr/bin/env python3 """ Generate apm.yml by walking cloned repositories and discovering all installable skills and plugins. Skills are any directories containing a SKILL.md file, found by walking the given root directories recursively with os.walk. """ import argparse import os import sys import yaml def find_s...
cheesesashimi/containerfiles
ai-sandbox/generate-apm-yml.py
.py
3965eee1c86651ef
7
0