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 |
|---|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
"""
Helper for testing a C++ exception throw aborts the process.
Takes one argument, the name of the function in :mod:`_test_extension_cpp` to call.
"""
import sys
import greenlet
from greenlet.tests import _test_extension_cpp
print('fail_cpp_exception is running')
def run_unhandled_exception_... | kristjanvalur/pytealet | packages/tealet-greenlet/tests/compat_greenlet/fail_cpp_exception.py | .py | a3f65b8a95a29289 | 7.5 | 0 |
"""
Testing initialstub throwing an already started exception.
"""
import greenlet
a = None
b = None
c = None
main = greenlet.getcurrent()
# If we switch into a dead greenlet,
# we go looking for its parents.
# if a parent is not yet started, we start it.
results = []
def a_run(*args):
#results.append('A')
... | kristjanvalur/pytealet | packages/tealet-greenlet/tests/compat_greenlet/fail_initialstub_already_started.py | .py | 184bee75ad762136 | 7.5 | 0 |
"""
Uses a trace function to switch greenlets at unexpected times.
In the trace function, we switch from the current greenlet to another
greenlet, which switches
"""
import greenlet
g1 = None
g2 = None
switch_to_g2 = False
def tracefunc(*args):
print('TRACE', *args)
global switch_to_g2
if switch_to_g2:
... | kristjanvalur/pytealet | packages/tealet-greenlet/tests/compat_greenlet/fail_switch_three_greenlets.py | .py | cd28ad57bae43676 | 7.5 | 0 |
"""
Like fail_switch_three_greenlets, but the call into g1_run would actually be
valid.
"""
import greenlet
g1 = None
g2 = None
switch_to_g2 = True
results = []
def tracefunc(*args):
results.append(('trace', args[0]))
print('TRACE', *args)
global switch_to_g2
if switch_to_g2:
switch_to_g2 = ... | kristjanvalur/pytealet | packages/tealet-greenlet/tests/compat_greenlet/fail_switch_three_greenlets2.py | .py | 14f25e9ec9f6109c | 7.5 | 0 |
# -*- coding: utf-8 -*-
"""
Tests for greenlets interacting with the CPython trash can API.
The CPython trash can API is not designed to be re-entered from a
single thread. But this can happen using greenlets, if something
during the object deallocation process switches greenlets, and this second
greenlet then causes ... | kristjanvalur/pytealet | packages/tealet-greenlet/tests/compat_greenlet/test_greenlet_trash.py | .py | 33de3399e9810021 | 7.5 | 0 |
"""Composition helpers for continuous proactor operation callbacks."""
from __future__ import annotations
import heapq
import socket
from collections.abc import Callable, Iterator
from typing import TYPE_CHECKING, Any, TypeAlias, TypeVar
from .operations import MultishotDelivery, is_io_cancellation
from .socket_help... | kristjanvalur/pytealet | packages/tealetio/src/tealetio/continuous_callbacks.py | .py | df813c2641808e4f | 7 | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Package build script for stepss.
Reads version metadata from the installed :mod:`stepss` package and uses
:func:`setuptools.setup` to define the distribution. Run via
``python setup.py install`` (legacy) or, preferably, with ``pip install .``.
"""
try:
from setupt... | SPS-L/stepss-python-ui | src/setup.py | .py | 678a440cf6c3d6a4 | 7.35 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Global module variables and utilities shared across stepss.
Provides:
- Module-level configuration flags (``__runTimeObs__``) and the resolved
paths to the bundled native libraries: ``__libdir__`` (the ``libs/`` root,
holding the platform-independent C header... | SPS-L/stepss-python-ui | src/stepss/globals.py | .py | 97869880964a657b | 7.35 | 4 |
"""Shared fixtures for the stepss helios test suite.
The tests exercise the bundled helios shared library through the
:class:`stepss.helios.HeliosSession` wrapper, using the 6-bus microgrid
example committed under ``tests/data/``.
Set the ``STEPSS_HELIOS_LIB_DIR`` environment variable to test against a
locally built ... | SPS-L/stepss-python-ui | tests/conftest.py | .py | 78784611a79fa4d1 | 7.85 | 4 |
"""Run every helios example script and require a clean exit."""
import os
import runpy
from pathlib import Path
import pytest
import stepss.helios
from conftest import LIB_DIR
EXAMPLES = sorted((Path(__file__).resolve().parents[1] / "examples" / "helios").glob("*.py"))
@pytest.mark.parametrize("example", EXAMPLES... | SPS-L/stepss-python-ui | tests/test_examples.py | .py | e5be5d6a7aa743a3 | 7.85 | 4 |
"""Nordic voltage-collapse regression gate for the bundled RAMSES library.
Drives the same case the stepss-ramses release gate runs -- dyn_A +
volt_rat_A + short_trip_branch.dst -- but through the C API rather than the
standalone executable, and compares the trajectory against the shared
baseline.
The collapse is by ... | SPS-L/stepss-python-ui | tests/test_nordic.py | .py | 784b554e57a4175e | 7.85 | 4 |
"""The .ssa archive, which both interfaces read and write."""
import shutil
import tarfile
import zipfile
from pathlib import Path
import pytest
from stepss import ssa
from stepss.globals import RAMSESError
FIXTURES = Path(__file__).resolve().parent / "data" / "ssa"
@pytest.fixture
def res(tmp_path):
run = tm... | SPS-L/stepss-python-ui | tests/test_ssa_archive.py | .py | a2ce8f627be191c8 | 7.85 | 4 |
"""The two engine entries: run_ssa and get_state_matrix, through stepss.sim."""
import shutil
from pathlib import Path
import numpy as np
import pytest
import stepss
from stepss import ssa
from stepss.globals import RAMSESError
# sim.__del__ warns on every collection by design, and each test here creates a
# simula... | SPS-L/stepss-python-ui | tests/test_ssa_engine.py | .py | ee46ceade522b416 | 7.85 | 4 |
"""The pure helpers a run needs: validation, the two generated files, clearing."""
import os
import pytest
from stepss import ssa
from stepss.globals import RAMSESError
@pytest.mark.parametrize("name", ["ssa", "run-1", "a.b_c", "X9"])
def test_valid_basenames(name):
assert ssa.valid_basename(name)
@pytest.ma... | SPS-L/stepss-python-ui | tests/test_ssa_run_helpers.py | .py | dae8b8f77ae1bc06 | 7.85 | 4 |
"""
Open API configuration
"""
import os
from pathlib import Path
from typing import Dict
from yaml import load, SafeLoader
from fastapi.openapi.utils import get_openapi
def get_app_info() -> Dict[str, str]:
"""
Get title, version, description from openapi.yml
"""
with open(Path(__file__).parent / '... | NCATSTranslator/NameResolution | api/apidocs.py | .py | 055e4d0d23a50860 | 7.35 | 4 |
import hashlib
from pathlib import Path
import genanki
def _stable_id(seed: str) -> int:
h = int(hashlib.md5(seed.encode("utf-8")).hexdigest()[:8], 16)
return (1 << 30) + (h % (1 << 30))
def _guid_for(native: str) -> str:
# Stable across runs so re-importing updates instead of duplicating.
return g... | ckirby19/AutoSubGen | autosubgen/exporters/anki.py | .py | d85951f6ac3412d6 | 7.35 | 4 |
from dataclasses import dataclass
from .subtitles.model import Cue
@dataclass
class Sentence:
"""One curated study unit -> becomes one note."""
start: float
end: float
native: str
english: str = ""
source: str = ""
def _join_native(a: str, b: str) -> str:
# CJK joins without spaces; thi... | ckirby19/AutoSubGen | autosubgen/segmentation.py | .py | 20fe42d1fceb3e0f | 7.35 | 4 |
import os
import re
import subprocess
import tempfile
from dataclasses import dataclass
from difflib import SequenceMatcher
from pathlib import Path
from ..subtitles.model import Cue
_CJK = re.compile(r"[㐀-鿿]")
_LATIN = re.compile(r"[A-Za-z]")
@dataclass
class OcrLine:
text: str
y: float # vertical... | ckirby19/AutoSubGen | autosubgen/sources/ocr.py | .py | dddf97972d3b0455 | 7.35 | 4 |
import re
from .model import Cue
_CJK = re.compile(r"[㐀-䶿一-鿿豈-々〇]")
_TAGS = re.compile(r"<[^>]+>")
_TIMECODE = re.compile(
r"(?:(\d{1,2}):)?(\d{1,2}):(\d{1,2})[.,](\d{1,3})\s*-->\s*"
r"(?:(\d{1,2}):)?(\d{1,2}):(\d{1,2})[.,](\d{1,3})"
)
def has_cjk(s: str) -> bool:
return bool(_CJK.search(s))
def _hms... | ckirby19/AutoSubGen | autosubgen/subtitles/parse.py | .py | 3580e7f809fb7174 | 7.35 | 4 |
"""Code to handle database connections and error handling."""
import sqlite3
from typing import Generator
class DatabaseException(Exception):
"""Exception class for database errors."""
class Database:
"""Class to handle database connections and queries."""
__slots__ = ('_handler', '_cursor', '_unique_i... | petermcd/ip-obfuscator-and-locater | IpToCountry/database.py | .py | 52ea7dce07c27b51 | 7 | 0 |
"""Code to handle translation of IP addresses to countries."""
import configparser
import json
from typing import Optional
import requests
from IpToCountry.database import Database, DatabaseException
class IpToCountryException(Exception):
"""Exception raised for errors in the IpToCountry class."""
pass
c... | petermcd/ip-obfuscator-and-locater | IpToCountry/ip_to_country.py | .py | 207116987033a2e9 | 7 | 0 |
"""Test file for the IP Obfuscator and Locator package."""
from IpToCountry.ip_to_country import IpToCountry
class TestIpToCountry:
"""Test class for the IpToCountry class."""
def test_ip_to_country_config_parser(self):
"""Test the config parser."""
ip_to_country = IpToCountry()
asser... | petermcd/ip-obfuscator-and-locater | tests/IpToCountry/test_ip_to_country.py | .py | 343dd7458122da65 | 7.5 | 0 |
#!/usr/bin/env python3
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | dseomn/dotfiles | .local/lib/inhibiter/inhibiter.py | .py | a792250773471581 | 7.35 | 4 |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | dseomn/dotfiles | .local/lib/python3/site-packages/config_merge_template/main.py | .py | 2a94bc23d52632df | 7.35 | 4 |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | dseomn/dotfiles | .local/lib/python3/site-packages/snipphthalate/comment_test.py | .py | 96dffd8745156e57 | 7.85 | 4 |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | dseomn/dotfiles | .local/lib/python3/site-packages/snipphthalate/context.py | .py | 5010cf6ac0d80f9d | 7.35 | 4 |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | dseomn/dotfiles | .local/lib/python3/site-packages/snipphthalate/context_test.py | .py | 1db35f23a666a967 | 7.85 | 4 |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | dseomn/dotfiles | .local/lib/python3/site-packages/snipphthalate/plugin.py | .py | 4d3374b5fc35390b | 7.35 | 4 |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | dseomn/dotfiles | .local/lib/python3/site-packages/snipphthalate/plugin_test.py | .py | 6aff1a9c23638782 | 7.85 | 4 |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | dseomn/dotfiles | .local/lib/python3/site-packages/snipphthalate/registry.py | .py | be52c65cc7eed306 | 7.35 | 4 |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | dseomn/dotfiles | .local/lib/python3/site-packages/snipphthalate/snippet.py | .py | 0137ebdb7efb0e25 | 7.35 | 4 |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | dseomn/dotfiles | .local/lib/python3/site-packages/snipphthalate/snippet_test.py | .py | 08019255cf1c3a7d | 7.85 | 4 |
"""Python implementations of maktaba#json#Format() and maktaba#json#Parse().
These will be used in place of the Vimscript implementations in recent versions
of Vim (that are compiled with Python support), unless disabled using
maktaba#SetJsonPythonDisabled().
"""
import json
import vim
def _vim2py_deepcopy(value, n... | dseomn/dotfiles | third_party/vim-maktaba/python/maktabajson.py | .py | a77daa686d67f54c | 7.35 | 4 |
#!/usr/bin/env python
"""axonbot_slack shell script entry point."""
import logging
import os
import sys
import pathlib
import click
import dotenv
import machine
import machine.settings
import machine.core
import machine.singletons
import slackclient
SCRIPT_PATH_FULL = pathlib.Path(sys.argv[0]).absolute().resolve()
S... | edgecases-PurpleHax/axonbot_slack | axonbot_slack/cli.py | .py | f6c768757a986801 | 7.15 | 1 |
import json
from pathlib import Path
from datetime import datetime
from typing import List, Dict, Any, TypeAlias
from .discrepancy import Discrepancy as ImportedDiscrepancy
from .errors import ComparisonError
Discrepancy: TypeAlias = ImportedDiscrepancy # type: ignore[assignment]
class ComparisonReport:
"""Co... | cfe-lab/proviral | scripts/compare_runs/comparison_report.py | .py | 2c5e2fc7afe0c929 | 7 | 0 |
"""
CSV utility functions for the compare_runs script.
This module provides utility functions for working with CSV files,
including validation, metadata extraction, and data type detection.
"""
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Any
def get_file_metadata(... | cfe-lab/proviral | scripts/compare_runs/csv_utils.py | .py | a6a09d0e945f2fd8 | 7 | 0 |
"""
File operations module for compare_runs script.
This module contains functions for file system operations including:
- Finding version directories
- Getting CSV files from proviral subfolders
- Reading CSV file contents
- Building index row mappings
"""
import csv
import logging
from pathlib import Path
from typi... | cfe-lab/proviral | scripts/compare_runs/file_operations.py | .py | b27ece4a31a6bec4 | 7 | 0 |
"""
Row comparison functionality for CSV comparison.
This module provides utilities to analyze and summarize differences between
CSV rows and headers, supporting detailed comparison reporting.
"""
from typing import Dict, List, Optional, Any
from .discrepancy import _trim_value_for_display
from .csv_utils import clas... | cfe-lab/proviral | scripts/compare_runs/row_comparison.py | .py | 2d9fae49d9034578 | 7 | 0 |
"""
Tests for version columns in table_precursor.csv outputs.
"""
import csv
import io
import pandas as pd
from unittest.mock import patch
from cfeproviral import utils
def test_generate_table_precursor_includes_all_version_columns(tmp_path):
"""Test that generate_table_precursor includes all three version colu... | cfe-lab/proviral | tests/test_utils/test_table_precursor_versions.py | .py | 45441b99f2717854 | 7.5 | 0 |
"""
Creates a POSIX user account in LDAP for anyone in the specified Keycloak group.
"""
import asyncio
import logging
import time
from krs.groups import get_group_membership
from krs.ldap import LDAP
from krs.rabbitmq import RabbitMQListener
from krs.token import get_rest_client
logger = logging.getLogger('create_po... | WIPACrepo/keycloak-rest-services | actions/create_posix_account.py | .py | 37e5274fb7f1ad6b | 7.15 | 1 |
import pathlib
import subprocess
import tempfile
import time
from google.auth.exceptions import RefreshError
from googleapiclient.errors import HttpError
QUOTAS = {
# production dirs
'/mnt/homework/homework': '/sbin/zfs set userquota@{uid}=15G homework/homework',
'/mnt/homework/public_html': '/sbin/zfs se... | WIPACrepo/keycloak-rest-services | actions/util.py | .py | f99af96904db061f | 7.15 | 1 |
"""
IceCube Keycloak setup.
Example command:
python -m keycloak_setup.icecube_setup --ldap_url ldaps://XXXX --ldap_admin_user 'uid=admin,XXXX' --ldap_admin_password XXXX --keycloak_realm IceCube -u XXXX -p XXXX https://keycloak.XXXX https://user-mgmt.XXXX
"""
# fmt: off
import argparse
import asyncio
import log... | WIPACrepo/keycloak-rest-services | keycloak_setup/icecube_setup.py | .py | 017adb915b4986e9 | 7.15 | 1 |
"""
RabbitMQ utilities
"""
import asyncio
import logging
import aio_pika
import requests
from rest_tools.utils.json_util import json_decode
from wipac_dev_tools import from_environment
logger = logging.getLogger('rabbitmq')
class RabbitMQListener:
"""
RabbitMQ exchange listener.
Calls `action` with dic... | WIPACrepo/keycloak-rest-services | krs/rabbitmq.py | .py | ac4f45a39dede553 | 7.15 | 1 |
async def keycloak_version(rest_client):
"""
Return the version of the keycloak server rest_client is pointing to.
In theory, RealmRepresentation that is returned by various Keycloak REST
API endpoints should contain the keycloakVersion attribute. As of Keycloak
24.0.1, keycloakVersion is not inclu... | WIPACrepo/keycloak-rest-services | krs/util.py | .py | 4e79ca926abd6b96 | 7.15 | 1 |
"""
Look up all users and write them to a csv file.
Examples::
./setupenv.sh
. env/bin/activate
python scripts/get_users_csv.py users.csv
"""
import asyncio
import csv
import logging
from asyncache import cached
from cachetools import TTLCache
from krs.token import get_rest_client
from krs.users import... | WIPACrepo/keycloak-rest-services | scripts/get_users_csv.py | .py | ea67add8b9d3b484 | 7.15 | 1 |
# pyright: reportPrivateUsage=false
# pylint: disable=protected-access,super-init-not-called
# ruff: noqa: ANN401, SLF001
"""Tests for Model Target Web API detail helpers."""
from typing import Any
import pytest
import requests
from selenium.webdriver.remote.webdriver import WebDriver
import vws_web_tools
class _B... | VWS-Python/vws-web-tools | tests/test_model_target_web_api_details.py | .py | 54566ce0af11f4f6 | 7.5 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Add episode_title column and backfill from RSS feed.
This script:
1. Adds episode_title column to existing databases (if needed)
2. Fetches RSS feed to extract episode titles
3. Updates all links with their episode titles based on episode_date
Usage:
# Dry run (s... | pberry/ridehome | add_episode_title_column.py | .py | 822ffca37b64c379 | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Backfill AI categorization for all links in the database.
This script:
1. Finds all links without AI categorization
2. Processes them in batches using Claude API
3. Stores the results in the database
Usage:
# Dry run (show what would be done, no API calls)
py... | pberry/ridehome | backfill_ai_categories.py | .py | 94bfa1a233b9da73 | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Proof-of-concept: Use Claude API to categorize topics instead of keyword matching.
This demonstrates how to integrate with Claude API for intelligent topic categorization.
Requires: pip install anthropic python-dotenv
"""
import os
import json
import sqlite3
from date... | pberry/ridehome | claude_categorizer.py | .py | c0e51aeba9b82c8f | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Database writer for The Ride Home links.
Handles insertion with duplicate detection and date conversion.
"""
import sqlite3
from datetime import datetime
from typing import List, Dict
import time
def date_to_unix(date_obj: datetime) -> int:
"""
Convert dateti... | pberry/ridehome | db_writer.py | .py | 8a4946aec1033d32 | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Unified RSS feed extractor for The Ride Home podcast.
Extracts show links and/or Friday longreads from feed and outputs to markdown files.
"""
import feedparser
import html2text
import time
import argparse
import os
import re
from datetime import datetime
from zoneinfo... | pberry/ridehome | extract.py | .py | 12b8718f84b2ba97 | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Generate category pages from AI-categorized links in database.
"""
import sqlite3
from datetime import datetime
MONTH_NAMES = [
'', 'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
]
de... | pberry/ridehome | generate_category_pages.py | .py | 97982e1c1256ee6c | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Generate index.md homepage from database.
Builds recent/archive navigation based on current year.
Only links to files that actually exist.
"""
import sqlite3
import os
from pathlib import Path
from datetime import datetime
from zoneinfo import ZoneInfo
from status_gene... | pberry/ridehome | generate_index.py | .py | 4024faa5a5a8c596 | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Generate year-based markdown pages from database.
Creates all-links-YYYY.md and longreads-YYYY.md files.
Uses hash-based comparison to skip unchanged files.
"""
import sqlite3
import hashlib
import os
from pathlib import Path
from datetime import datetime
from zoneinfo... | pberry/ridehome | generate_year_pages.py | .py | 1e392d6466a3e969 | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
HTML Content Parser
Shared module for parsing HTML content from RSS feeds.
Extracts structured sections (Links, Longreads, Sponsors, etc.) from HTML.
"""
import re
from bs4 import BeautifulSoup, NavigableString
def find_section(html, pattern):
"""
Find and... | pberry/ridehome | html_parser.py | .py | ab6e758fe4615abf | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Load markdown files into SQLite database.
One-time import script for existing markdown archives.
"""
import argparse
import sys
from pathlib import Path
from db_schema import create_schema
from markdown_parser import parse_showlinks_file, parse_longreads_file
from db_w... | pberry/ridehome | load_db.py | .py | 852c29f6a898aab1 | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Orchestrator script to rebuild all generated markdown files from database.
Calls all generator scripts in correct order.
"""
import argparse
import sys
from pathlib import Path
from generate_year_pages import generate_all_year_pages
from generate_category_pages import ... | pberry/ridehome | rebuild_all.py | .py | 4b1d931ef1c918ec | 7 | 0 |
"""
Source name normalization for ridehome links database.
Provides canonical source mappings and normalization functions to:
1. Standardize source name variations (e.g., "Wall Street Journal" → "WSJ")
2. Extract sources from URLs for links with NULL sources
3. Remove author attributions (e.g., "Matt Levine/Bloomberg"... | pberry/ridehome | source_normalizer.py | .py | 20b888d12e635fa0 | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Source Race Plot — Horse Race chart of top news sources over time.
Generates an SVG line chart showing monthly link counts for the top N sources
over the last 24 months.
Usage:
uv run source_race_plot.py # Generate (idempotent per month)
uv run sourc... | pberry/ridehome | source_race_plot.py | .py | 12a248ff7c04df73 | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Generate status section for homepage showing:
- Last run date/time
- Total links archived (showlinks and longreads)
- Top 3 sources from last 6 months
- Top 3 topics from last 6 months
"""
import sqlite3
import re
from datetime import datetime, timedelta
from zoneinfo ... | pberry/ridehome | status_generator.py | .py | 4f55c92bb369c1d8 | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Tests for AI categorization backfill functionality.
Run with:
python3 test_backfill.py
"""
import unittest
import sqlite3
import os
import sys
import tempfile
from unittest.mock import patch, MagicMock
from db_schema import create_schema
from backfill_ai_categorie... | pberry/ridehome | test_backfill.py | .py | 56f0eccec2d61965 | 7.5 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Tests for category page generator.
"""
import unittest
import sqlite3
import os
from datetime import datetime
from generate_category_pages import category_to_slug, get_links_for_category, generate_category_markdown
class TestCategorySlugGeneration(unittest.TestCase):... | pberry/ridehome | test_category_pages.py | .py | 49f2a05093d9b6d3 | 7.5 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Tests for CSS rules to ensure accessibility and styling requirements.
"""
import unittest
import re
from pathlib import Path
class TestAICategoryBubbleStyles(unittest.TestCase):
"""Test AI category speech bubble CSS for proper visited link styling."""
def se... | pberry/ridehome | test_css_rules.py | .py | ad9f277ba8b6d536 | 7.5 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Tests for markdown_parser.py
"""
import unittest
from datetime import datetime
from markdown_parser import (
parse_date_header,
parse_date_header_no_year,
parse_link_bullet,
extract_year_from_filename
)
class TestDateParsing(unittest.TestCase):
de... | pberry/ridehome | test_markdown_parser.py | .py | aa29599ef20480ac | 7.5 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Tests for source_race_plot.py
"""
import os
import sqlite3
import tempfile
import unittest
from datetime import datetime, timedelta
from source_race_plot import (
get_top_sources,
get_ever_top_n_sources,
get_monthly_counts,
should_regenerate,
mark_... | pberry/ridehome | test_source_race_plot.py | .py | 9787f13ccfa8b40b | 7.5 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Tests for status_generator.py
"""
import unittest
import tempfile
import sqlite3
from datetime import datetime, timedelta
from status_generator import (
categorize_topic,
get_status_data,
format_status_section,
update_homepage
)
class TestTopicCategor... | pberry/ridehome | test_status_generator.py | .py | 7709c044ac9f9f16 | 7.5 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
The Ride Home - Year Wrapped Report Generator
Generates Spotify Wrapped-style statistics for any year
Usage:
python3 year_wrapped.py 2025
python3 year_wrapped.py 2024
python3 year_wrapped.py --year 2023
"""
import re
import sys
import sqlite3
import argp... | pberry/ridehome | year_wrapped.py | .py | 34c2cd81f37bde18 | 7 | 0 |
#
# Copyright (c) 2015-2019 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from six.moves import configparser
# Configuration Global used by other modules to get access to the configuration
# specified in the config file.
CONFSS = dict()
class ConfigSS(configparser.ConfigParser):
"""Override... | starlingx/gui | starlingx-dashboard/starlingx-dashboard/starlingx_dashboard/configss.py | .py | d23660116785748b | 7.24 | 2 |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | asi-uniovi/power-simulation | simulation/distribution.py | .py | 8f62954a202e5e99 | 7 | 0 |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | asi-uniovi/power-simulation | simulation/fleet_generator.py | .py | 6f40047fc3a74cf0 | 7 | 0 |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | asi-uniovi/power-simulation | simulation/module.py | .py | 707b4f79b21e4adb | 7 | 0 |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | asi-uniovi/power-simulation | simulation/plot.py | .py | 761c2ec69d24b55d | 7 | 0 |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | asi-uniovi/power-simulation | simulation/simulation.py | .py | 55a50b84e8bbd790 | 7 | 0 |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | asi-uniovi/power-simulation | simulation/static.py | .py | c8caf909abc12b9b | 7 | 0 |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | asi-uniovi/power-simulation | tests/distribution_test.py | .py | b10953a4684228c8 | 7.5 | 0 |
#!/usr/bin/env python3
"""Replaces the name of the workstations with some that is anonymous."""
import argparse
import json
import math
import re
import sys
NAME_TEMPL = 'WORKSTATION%s.company1.net'
NAME_PATTERN = re.compile(r'^WORKSTATION\d+\.company1\.net$')
def names_generator(trace):
"""Generates a new PC ... | asi-uniovi/power-simulation | tools/anonymise_trace.py | .py | 2130eecd4571ccbe | 7 | 0 |
#!/usr/bin/env python3
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | asi-uniovi/power-simulation | tools/benchmark.py | .py | dc6136cb8478a208 | 7 | 0 |
#!/usr/bin/env python3
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | asi-uniovi/power-simulation | tools/generate_test_data.py | .py | 886c9eb9694ecaf1 | 7.5 | 0 |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | asi-uniovi/power-simulation | tools/parse_trace.py | .py | 1713d560998cb595 | 7 | 0 |
#!/usr/bin/env python3
#
# Copyright 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | asi-uniovi/power-simulation | tools/plot_distribution.py | .py | 64c8df0eb1b01642 | 7 | 0 |
#!/usr/bin/env python3
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | asi-uniovi/power-simulation | tools/plot_histogram.py | .py | 7adb48c17f04f45c | 7 | 0 |
#!/usr/bin/env python3
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | asi-uniovi/power-simulation | tools/plot_satisfaction.py | .py | b2e00084c2053918 | 7 | 0 |
from __future__ import annotations
import json
import logging
import os
import re
import tempfile
import time
from pathlib import Path
import requests
from ingest_wikimedia.web import USER_AGENT
BANLIST_FILE_NAME = "dpla-id-banlist.txt"
# The committed ``dpla-id-banlist.txt`` is the *floor* of the banlist. On top ... | dpla/ingest-wikimedia | ingest_wikimedia/banlist.py | .py | 2bc58247870a2b32 | 7 | 0 |
import logging
import pywikibot
from pywikibot.site import BaseSite
from ingest_wikimedia.csrf import CsrfRecoveryFailed, with_csrf_recovery
from ingest_wikimedia.wikimedia import get_wikidata_site
# Stable Wikimedia ontology constants — these items will not change
WD_WIKIMEDIA_CONTENT_PARTNERSHIP = "Q97580368" # "... | dpla/ingest-wikimedia | ingest_wikimedia/categories.py | .py | b01bb9e4cbcbc227 | 7 | 0 |
import csv
from typing import IO
CHECKSUM = "sha1"
CONTENT_TYPE = "ContentType"
def load_ids(ids_file: IO) -> list[str]:
dpla_ids = []
csv_reader = csv.reader(ids_file)
for row in csv_reader:
dpla_ids.append(row[0])
return dpla_ids
def null_safe[T](data: dict, field_name: str, identity_elem... | dpla/ingest-wikimedia | ingest_wikimedia/common.py | .py | 3c7edf4be5c7f80b | 7 | 0 |
"""Shared CSRF-session-recovery primitives for every Wikimedia write path.
Pywikibot's :class:`TokenWallet` raises
``KeyError("Invalid token 'csrf' for user '<bot>' on commons:commons
wiki.")`` when the cached session is invalidated by the server (long
idle, forced logout, backend reset). Every subsequent write attemp... | dpla/ingest-wikimedia | ingest_wikimedia/csrf.py | .py | c74123f3dc24c519 | 7 | 0 |
"""Shared Elasticsearch helpers for the get-ids-* tools.
Both tools paginate ES with `search_after` and need the same two protections
against silent partial results:
* a hard wall-clock timeout via SIGALRM (catches ES connections that stall
mid-response — `requests`' timeout only fires when no bytes arrive)
*... | dpla/ingest-wikimedia | ingest_wikimedia/es.py | .py | d8ea1ea1d15b0fdf | 7 | 0 |
"""Per-partner ``hand-fix.jsonl`` sidecar for the SHA1-uniqueness redesign.
When the uploader finds our S3 source's SHA1 already on Commons at a WRONG
title and the canonical title we need is occupied by a DIFFERENT file (a
different SHA1), the rename that would restore the upload invariant is
blocked. Under the one-S... | dpla/ingest-wikimedia | ingest_wikimedia/hand_fix_sidecar.py | .py | c6d35c5758410a0d | 7 | 0 |
import json
import logging
import re
from operator import itemgetter
from urllib.parse import urlparse
import requests
import validators
from requests import Session
from ingest_wikimedia.common import get_list, get_dict, get_str
from ingest_wikimedia.tracker import Tracker, Result
class IIIF:
def __init__(self... | dpla/ingest-wikimedia | ingest_wikimedia/iiif.py | .py | 7ac30b258ee06cf8 | 7 | 0 |
import hashlib
import logging
import os
import tempfile
import magic
from .common import CHECKSUM
class LocalFS:
__temp_dir: tempfile.TemporaryDirectory | None = None
def setup_temp_dir(self) -> None:
"""
Sets up a temporary dir for this process. Not thread-safe.
"""
if self... | dpla/ingest-wikimedia | ingest_wikimedia/localfs.py | .py | 3cfa1f7cf5c46853 | 7 | 0 |
import logging
import os
import sys
from datetime import datetime
from tqdm import tqdm
def _install_logging_excepthook() -> None:
"""Replace ``sys.excepthook`` with a wrapper that logs the
exception via ``logging.critical(exc_info=...)`` before delegating
to whatever hook was previously installed.
... | dpla/ingest-wikimedia | ingest_wikimedia/logs.py | .py | bb240db354b655d1 | 7 | 0 |
from typing import Generator
import logging
import boto3
import json
from botocore.config import Config
from botocore.exceptions import ClientError
from mypy_boto3_s3 import S3ServiceResource
from .common import CHECKSUM
from .localfs import LocalFS
IIIF_JSON = "iiif.json"
FILE_LIST_TXT = "file-list.txt"
TEXT_PLAIN = ... | dpla/ingest-wikimedia | ingest_wikimedia/s3.py | .py | 4a3681d5cd72bf7e | 7 | 0 |
"""Session-state utilities for the ``wikimedia-*`` scripts.
A wikimedia-upload tmux session runs its per-target chain sequentially —
downloader → uploader → sdc-sync per label, then the next label. At any
moment **at most one label is active**; the label whose log file was most
recently written uniquely identifies it.... | dpla/ingest-wikimedia | ingest_wikimedia/session_state.py | .py | f644b8dc8d37f1d0 | 7 | 0 |
"""Per-SHA1 cross-process lock for the uploader's Commons check-then-act.
The uploader parallelizes one partner run across worker processes (a
``multiprocessing`` Pool), and several partner sessions run concurrently on
the wiki box. When two of those processes hold byte-identical source media for
DIFFERENT DPLA items ... | dpla/ingest-wikimedia | ingest_wikimedia/sha1_lock.py | .py | 65b038f564d35217 | 7 | 0 |
"""Shared SSM helpers for Wikimedia pipeline scripts."""
import base64
import hashlib
import shlex
import time
INSTANCE_ID = "i-033eff6c8c168f999"
REGION = "us-east-1"
SSM_POLL_INTERVAL = 5
SSM_MAX_POLLS = 60 # 5 minutes
def ssm_run(client, cmd: str, *, as_root: bool = False) -> str:
"""Run cmd on EC2 via AWS-... | dpla/ingest-wikimedia | ingest_wikimedia/ssm.py | .py | 854736371c1f54fd | 7 | 0 |
"""Shared helpers for bounded async S3 staging in the get-ids-* tools.
Both get-ids-es and get-ids-nara follow the same pattern when writing ES
source documents to S3: a BoundedSemaphore caps in-flight writes so the
executor queue never holds more than n_workers * 4 documents in memory,
and a done callback releases th... | dpla/ingest-wikimedia | ingest_wikimedia/staging.py | .py | 6b15c1c1f4366d2b | 7 | 0 |
import functools
import requests
from requests.adapters import HTTPAdapter
from urllib3 import Retry
RETRY_COUNT = 3
RETRY_BACKOUT_FACTOR = 1
DEFAULT_CONN_TIMEOUT = 45
class Web:
def __init__(self, secrets: dict[str, str]):
self.secrets = secrets
def get_http_session(self, provider: str) -> request... | dpla/ingest-wikimedia | ingest_wikimedia/web.py | .py | d133841c0d7b2e2e | 7 | 0 |
# CIMviews.py
# Updates Commons Impact Metrics (CIM) pageview data on Wikimedia Commons.
#
# Two modes, controlled by --mode:
#
# data (default): For each category tracked by {{views from category}},
# fetches monthly pageview data from the CIM API and writes/updates a
# tabular data page (Data:Views/<categor... | dpla/ingest-wikimedia | metrics/cim-pageviews/CIMviews.py | .py | 976bea8e7f4399f3 | 7 | 0 |
#!/usr/bin/env python3
"""Run retry passes for failed Wikimedia upload and download items.
Triggered by the /wikimedia-upload retry <days> [<partner>] Slack command.
Scans EC2 logs for transient failures, then launches downloader+uploader (for
download failures) or uploader only (for upload failures) for each affected... | dpla/ingest-wikimedia | scripts/wikimedia_retry.py | .py | 032857a4bb8d4f53 | 7 | 0 |
"""Test-suite-wide safety net for Slack-side leakage.
Several scripts in this repo post to the DPLA bot's Slack channel when
they encounter operational failures (``_slack_fail``'s fallback
``post_message`` call in ``wikimedia_launch.py``) or when their no-op
path runs (``post_message`` from the "No retryable failures ... | dpla/ingest-wikimedia | tests/conftest.py | .py | 758d9c0a448a9a96 | 7.5 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.