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 |
|---|---|---|---|---|---|---|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from typing import Any, Dict
from ..handler import Handler
class CognitoHandler(Handler):
@classmethod
def is_event_match_handler(cls, event: Dict[str, Any]) -> bool:
return all(
key in event
for ... | ideabosque/silvaengine_base | silvaengine_base/handlers/cognito.py | .py | fd00408e180db9f7 | 7 | 0 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from typing import Any, Dict
from silvaengine_dynamodb_base.models import FunctionModel
from silvaengine_constants import AuthorizationAction
from silvaengine_utility import Authorizer
from ..handler import Handler
class HttpHandler(H... | ideabosque/silvaengine_base | silvaengine_base/handlers/http.py | .py | 4acd04a3bbdb99cb | 7 | 0 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Resources module for silvaengine_base.
This module provides the core infrastructure for handling Lambda events.
Plugin management functionality has been migrated to boosters module.
Simplified version - delegate methods removed. Users should use PluginInitializer directly... | ideabosque/silvaengine_base | silvaengine_base/resources.py | .py | 9a4b77bb7bb33bce | 7 | 0 |
#!/usr/bin/env python
# -*- coding: us-ascii -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
"""Command line tool to encrypt/decrypt Tombo CHI Blowfish files
"""
import getpass
import os
from optparse import OptionParser
import sys
import chi_io
is_py3 = sys.version_info >= (3,)
def main(argv=None):
if a... | clach04/chi_io | chi_tool.py | .py | 0bfd44c0b6845acb | 7.15 | 1 |
"""Asynchronous Python client providing Open Data information of Dresden."""
from __future__ import annotations
import asyncio
import socket
from dataclasses import dataclass
from importlib import metadata
from typing import Any, Self
from aiohttp import ClientError, ClientSession
from aiohttp.hdrs import METH_GET
f... | klaasnicolaas/python-dresden | src/dresden/dresden.py | .py | 2096765d9a57cd92 | 7.24 | 2 |
"""Models for Open Data Platform of Dresden."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from typing import Any
import pytz
@dataclass
class DisabledParking:
"""Object representing a DisabledParking."""
entry_id: int
number: int
usage_time:... | klaasnicolaas/python-dresden | src/dresden/models.py | .py | 9967feadd37e1dda | 7.24 | 2 |
#!/usr/bin/env python
"""
Dummy server used for unit testing.
"""
from __future__ import annotations
import logging
import os
import socket
import ssl
import sys
import threading
import typing
import warnings
import trustme
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives... | sailfishos-mirror/urllib3 | dummyserver/socketserver.py | .py | 8cfadfa59ea898bc | 7.15 | 1 |
from __future__ import annotations
import os
import re
import shutil
import sys
from pathlib import Path
import nox
nox.options.error_on_missing_interpreters = True
nox.options.default_venv_backend = "uv"
def tests_impl(
session: nox.Session,
extras: str | None = None,
extra_dependencies: list[str] | N... | sailfishos-mirror/urllib3 | noxfile.py | .py | 1ab6f59f54138775 | 7.15 | 1 |
"""
Python HTTP library with thread-safe connection pooling, file post support, user friendly, and more
"""
from __future__ import annotations
# Set default logging handler to avoid "No handler found" warnings.
import logging
import sys
import typing
import warnings
from logging import NullHandler
from . import exce... | sailfishos-mirror/urllib3 | src/urllib3/__init__.py | .py | 24ca35b60d67215d | 7.15 | 1 |
from __future__ import annotations
import typing
from .util.connection import _TYPE_SOCKET_OPTIONS
from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT
from .util.url import Url
_TYPE_BODY = typing.Union[
bytes, typing.IO[typing.Any], typing.Iterable[bytes | str], str
]
class ProxyConfig(typing.NamedTuple... | sailfishos-mirror/urllib3 | src/urllib3/_base_connection.py | .py | 1f37121077b1803a | 7.15 | 1 |
from __future__ import annotations
import typing
from collections import OrderedDict
from enum import Enum, auto
from threading import RLock
if typing.TYPE_CHECKING:
# We can only import Protocol if TYPE_CHECKING because it's a development
# dependency, and is not available at runtime.
from typing import ... | sailfishos-mirror/urllib3 | src/urllib3/_collections.py | .py | 68e566da62a296fb | 7.15 | 1 |
from __future__ import annotations
import os
import typing
# use http.client.HTTPException for consistency with non-emscripten
from http.client import HTTPException as HTTPException # noqa: F401
from http.client import ResponseNotReady
from ..._base_connection import _TYPE_BODY
from ...connection import HTTPConnect... | sailfishos-mirror/urllib3 | src/urllib3/contrib/emscripten/connection.py | .py | 822125b01a14b0a5 | 7.15 | 1 |
from __future__ import annotations
import json as _json
import logging
import typing
from contextlib import contextmanager
from dataclasses import dataclass
from http.client import HTTPException as HTTPException
from io import BytesIO, IOBase
from ...exceptions import InvalidHeader, TimeoutError
from ...response impo... | sailfishos-mirror/urllib3 | src/urllib3/contrib/emscripten/response.py | .py | 083a58d0616896e4 | 7.15 | 1 |
"""
This module contains provisional support for SOCKS proxies from within
urllib3. This module supports SOCKS4, SOCKS4A (an extension of SOCKS4), and
SOCKS5. To enable its functionality, either install PySocks or install this
module with the ``socks`` extra.
The SOCKS implementation supports the full range of urllib3... | sailfishos-mirror/urllib3 | src/urllib3/contrib/socks.py | .py | 81141f708d6928e0 | 7.15 | 1 |
from __future__ import annotations
import email.utils
import mimetypes
import typing
_TYPE_FIELD_VALUE = typing.Union[str, bytes]
_TYPE_FIELD_VALUE_TUPLE = typing.Union[
_TYPE_FIELD_VALUE,
tuple[str, _TYPE_FIELD_VALUE],
tuple[str, _TYPE_FIELD_VALUE, str],
]
def guess_content_type(
filename: str | No... | sailfishos-mirror/urllib3 | src/urllib3/fields.py | .py | 6862c5015669554f | 7.15 | 1 |
from __future__ import annotations
import binascii
import codecs
import os
import typing
from io import BytesIO
from .fields import _TYPE_FIELD_VALUE_TUPLE, RequestField
writer = codecs.lookup("utf-8")[3]
_TYPE_FIELDS_SEQUENCE = typing.Sequence[
typing.Union[tuple[str, _TYPE_FIELD_VALUE_TUPLE], RequestField]
]
... | sailfishos-mirror/urllib3 | src/urllib3/filepost.py | .py | 53c78d67e9a928a1 | 7.15 | 1 |
from __future__ import annotations
import threading
class _HTTP2ProbeCache:
__slots__ = (
"_lock",
"_cache_locks",
"_cache_values",
)
def __init__(self) -> None:
self._lock = threading.Lock()
self._cache_locks: dict[tuple[str, int], threading.RLock] = {}
s... | sailfishos-mirror/urllib3 | src/urllib3/http2/probe.py | .py | 9e7024a9b8406a43 | 7.15 | 1 |
from __future__ import annotations
import socket
import typing
from ..exceptions import LocationParseError
from .timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT
_TYPE_SOCKET_OPTIONS = list[tuple[int, int, typing.Union[int, bytes]]]
if typing.TYPE_CHECKING:
from .._base_connection import BaseHTTPConnection
def ... | sailfishos-mirror/urllib3 | src/urllib3/util/connection.py | .py | 2633bbdb69731e5c | 7.15 | 1 |
from __future__ import annotations
import io
import sys
import typing
from base64 import b64encode
from enum import Enum
from ..exceptions import UnrewindableBodyError
from .util import to_bytes
if typing.TYPE_CHECKING:
from typing import Final
# Pass as a value within ``headers`` to skip
# emitting some HTTP h... | sailfishos-mirror/urllib3 | src/urllib3/util/request.py | .py | 711d900221a70734 | 7.15 | 1 |
from __future__ import annotations
import http.client as httplib
from email.errors import MultipartInvariantViolationDefect, StartBoundaryNotFoundDefect
from ..exceptions import HeaderParsingError
def is_fp_closed(obj: object) -> bool:
"""
Checks whether a given file-like object is closed.
:param obj:
... | sailfishos-mirror/urllib3 | src/urllib3/util/response.py | .py | bd013adfdba81218 | 7.15 | 1 |
from __future__ import annotations
import email
import logging
import random
import re
import time
import typing
from itertools import takewhile
from types import TracebackType
from ..exceptions import (
ConnectTimeoutError,
InvalidHeader,
MaxRetryError,
ProtocolError,
ProxyError,
ReadTimeoutE... | sailfishos-mirror/urllib3 | src/urllib3/util/retry.py | .py | af28113e0350b332 | 7.15 | 1 |
from __future__ import annotations
import hashlib
import hmac
import os
import socket
import sys
import typing
import warnings
from binascii import unhexlify
from ..exceptions import ProxySchemeUnsupported, SSLError
from .url import _BRACELESS_IPV6_ADDRZ_RE, _IPV4_RE
SSLContext = None
SSLTransport = None
HAS_NEVER_C... | sailfishos-mirror/urllib3 | src/urllib3/util/ssl_.py | .py | 57688d26deaf5ed8 | 7.15 | 1 |
"""The match_hostname() function from Python 3.5, essential when using SSL."""
# Note: This file is under the PSF license as the code comes from the python
# stdlib. http://docs.python.org/3/license.html
# It is modified to remove commonName support.
from __future__ import annotations
import ipaddress
import re
im... | sailfishos-mirror/urllib3 | src/urllib3/util/ssl_match_hostname.py | .py | 16de38289cd3cc63 | 7.15 | 1 |
from __future__ import annotations
import io
import socket
import ssl
import typing
from ..exceptions import ProxySchemeUnsupported
if typing.TYPE_CHECKING:
from typing_extensions import Self
from .ssl_ import _TYPE_PEER_CERT_RET, _TYPE_PEER_CERT_RET_DICT
_WriteBuffer = typing.Union[bytearray, memoryview]... | sailfishos-mirror/urllib3 | src/urllib3/util/ssltransport.py | .py | 133e0ef2947fbd3f | 7.15 | 1 |
from __future__ import annotations
import time
import typing
from enum import Enum
from socket import getdefaulttimeout
from ..exceptions import TimeoutStateError
if typing.TYPE_CHECKING:
from typing import Final
class _TYPE_DEFAULT(Enum):
# This value should never be passed to socket.settimeout() so for s... | sailfishos-mirror/urllib3 | src/urllib3/util/timeout.py | .py | e1e4f5155799654e | 7.15 | 1 |
from __future__ import annotations
import select
import socket
from functools import partial
__all__ = ["wait_for_read", "wait_for_write"]
# How should we wait on sockets?
#
# There are two types of APIs you can use for waiting on sockets: the fancy
# modern stateful APIs like epoll/kqueue, and the older stateless ... | sailfishos-mirror/urllib3 | src/urllib3/util/wait.py | .py | fe987c22b511deca | 7.15 | 1 |
from __future__ import annotations
import errno
import importlib.util
import logging
import os
import platform
import socket
import sys
import typing
import warnings
from collections.abc import Sequence
from functools import wraps
from importlib.abc import Loader, MetaPathFinder
from importlib.machinery import ModuleS... | sailfishos-mirror/urllib3 | test/__init__.py | .py | fddc84d864cbc96f | 7.65 | 1 |
from __future__ import annotations
import contextlib
import os
import random
import textwrap
from collections.abc import Generator
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import pytest
from dummyserver.app import pyodide_testing_app
from dummyserver.hypercornserver import ru... | sailfishos-mirror/urllib3 | test/contrib/emscripten/conftest.py | .py | d824e14e349d430d | 7.65 | 1 |
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by ... | juanmacuevas/consulado-es-amsterdam | consulate_content_scraper.py | .py | bbcaf72db199db3e | 7.39 | 5 |
#!/usr/bin/env python3
import os
import time
import random
import re
import logging
import requests
from bs4 import BeautifulSoup
from markdownify import markdownify
from fake_useragent import UserAgent
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message... | juanmacuevas/consulado-es-amsterdam | download-servicios-consulares.py | .py | 1829470cfc1aa631 | 7.39 | 5 |
import os
from moto import mock_aws
import boto3
import pytest
@pytest.fixture(autouse=True)
def aws_credentials():
"""Mocked AWS Credentials for moto."""
os.environ["AWS_ACCESS_KEY_ID"] = "testing"
os.environ["AWS_SECRET_ACCESS_KEY"] = "testing"
os.environ["AWS_SECURITY_TOKEN"] = "testing"
os.env... | nationalarchives/ds-caselaw-pdf-conversion | queue_listener/conftest.py | .py | 3571801a79a91cd2 | 7.85 | 4 |
import json
import os
import subprocess
import boto3
import botocore
import dotenv
import rollbar
import sys
def eprint(*args, **kwargs):
print(*args, **kwargs, file=sys.stderr)
def would_replace_custom_pdf(s3_client, bucket_name, upload_key):
"""
If a PDF file with the target name already exists, and... | nationalarchives/ds-caselaw-pdf-conversion | queue_listener/queue_listener.py | .py | 48aee70958182d6b | 7.35 | 4 |
"""Typing helpers."""
from __future__ import annotations
from typing import TypedDict
class Config(TypedDict, total=False):
"""Configuration for the archiver."""
client_id: str
"""Client ID for OAuth2."""
client_secret: str
"""Client secret for OAuth2."""
class AuthInfo(TypedDict, total=False):... | Tatsh/gmail-archiver | gmail_archiver/typing.py | .py | fdbbaba2d0416c03 | 7.3 | 3 |
"""Kaartdijin Boodja Accounts Django Application Configuration."""
# Third-Party
from django import apps
class AccountsConfig(apps.AppConfig):
"""Accounts Application Configuration."""
default_auto_field = "django.db.models.BigAutoField"
name = "govapp.apps.accounts"
def ready(self) -> None:
... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/accounts/apps.py | .py | 4af783a664bf6344 | 7 | 0 |
"""Kaartdijin Boodja Publisher Django Application Cron Jobs."""
# Standard
import logging
# Third-Party
from django import conf
from django.core import management
import django_cron
from govapp.apps.publisher.models.publish_channels import GeoServerPublishChannel
# Logging
log = logging.getLogger(__name__)
class... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/accounts/cron.py | .py | d7bce66d2fe40e47 | 7 | 0 |
"""Kaartdijin Boodja Accounts Django Application Filters."""
# Third-Party
from django_filters import rest_framework as filters
from django.contrib import auth
from django.db.models import Q
# Shortcuts
UserModel = auth.get_user_model()
class UserFilter(filters.FilterSet):
"""User Filter."""
order_by = fil... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/accounts/filters.py | .py | bdb4bb6b7a213ab4 | 7 | 0 |
from django.core.management.base import BaseCommand
from govapp import settings
from govapp.apps.publisher.models.geoserver_pools import GeoServerPool
from govapp.common.utils import generate_random_password
class Command(BaseCommand):
help = 'Randomize passwords for all GeoServer user accounts.'
def handl... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/accounts/management/commands/random_password.py | .py | ddaa5c73507ba441 | 7 | 0 |
from django.core.management.base import BaseCommand
from django.contrib import auth
from django.conf import settings
from datetime import datetime
import requests
import json
import codecs
import decouple
import logging
from govapp.apps.accounts import utils, emails
from govapp.apps.publisher.models.geoserver_roles_gro... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/accounts/management/commands/sync_itassets_users.py | .py | 2ab881676e55739b | 7 | 0 |
"""Kaartdijin Boodja Accounts Django Application Serializers."""
# Third-Party
from django.contrib import auth
from django.contrib.auth import models as auth_models
from rest_framework import serializers
# Shortcuts
UserModel = auth.get_user_model()
GroupModel = auth_models.Group
class UserSerializer(serializers.... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/accounts/serializers.py | .py | 4349b7c4acb6afc2 | 7 | 0 |
"""Kaartdijin Boodja Accounts Django Application Views."""
import os
# Third-Party
from django.contrib import auth
from django.contrib.auth import models
from django.http import FileResponse, HttpResponseForbidden
from drf_spectacular import utils
from rest_framework import decorators
from rest_framework import reque... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/accounts/views.py | .py | ecfdbac61dc1d631 | 7 | 0 |
"""Kaartdijin Boodja Catalogue Django Application Absorber."""
# Standard
import datetime
import logging
import pathlib
import shutil
# Third-Party
from django import conf
from django.db import transaction
import pytz
# Local
from govapp.common import sharepoint
from govapp.gis import readers
from govapp.apps.catal... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/catalogue/absorber.py | .py | 0a1f106b1fd60c7c | 7 | 0 |
"""Kaartdijin Boodja Catalogue Django Application Configuration."""
# Third-Party
from django import apps
from django.db.models.signals import post_migrate
class CatalogueConfig(apps.AppConfig):
"""Catalogue Application Configuration."""
default_auto_field = "django.db.models.BigAutoField"
name = "govapp... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/catalogue/apps.py | .py | 275b7008f3570629 | 7 | 0 |
"""Kaartdijin Boodja Catalogue Django Application Notification Utilities."""
# Standard
import shutil
import pathlib
# Local
from govapp import gis, settings
from govapp.common import sharepoint
from govapp.common import local_storage
from govapp.apps.accounts import utils
from govapp.apps.catalogue import emails
fr... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/catalogue/directory_notifications.py | .py | 89675fca86357e76 | 7 | 0 |
"""Kaartdijin Boodja Catalogue Django Application Scanner."""
# Standard
import logging
import os
# Third-Party
from django import conf
# Local
from govapp.common import local_storage
from govapp.apps.catalogue import directory_absorber
from govapp.apps.catalogue import notifications
# Logging
log = logging.getL... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/catalogue/directory_scanner.py | .py | 2a9a9b24fd0c7390 | 7 | 0 |
"""Kaartdijin Boodja Catalogue Django Application Emails."""
# Local
from govapp.apps.emails import emails
class CatalogueEntryLockedEmail(emails.TemplateEmailBase):
"""Catalogue Entry Locked Email Abstraction."""
subject = "[KB] Kaartdijin Boodja Catalogue Entry locked"
html_template = "catalogue_entry... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/catalogue/emails.py | .py | 4ac454f8478b9e88 | 7 | 0 |
"""Kaartdijin Boodja Catalogue Django Application Filters."""
# Third-Party
from django_filters import rest_framework as filters
from django.db.models import F
# Local
from govapp.apps.catalogue import models
class CatalogueEntryFilter(filters.FilterSet):
"""Catalogue Entry Filter."""
updated = filters.IsoD... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/catalogue/filters.py | .py | 12a89966b4d9a8e6 | 7 | 0 |
"""Kaartdijin Boodja Catalogue Absorb Management Command."""
# Standard
import argparse
import pathlib
# Third-Party
from django.core.management import base
# Local
from govapp.apps.catalogue import absorber
# Typing
from typing import Any
class Command(base.BaseCommand):
"""Absorb Management Command."""
... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/catalogue/management/commands/absorb.py | .py | 1ca79d83394f7aca | 7 | 0 |
"""Management command to backfill file_size for existing LayerSubmission records.
Scans all LayerSubmission records where file_size is null and the file field is a
local path that still exists on disk, then populates file_size from the file's
actual size on disk.
Usage:
# Dry-run (no changes written to DB):
p... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/catalogue/management/commands/backfill_layer_submission_file_size.py | .py | 2223ebbae01fa0e3 | 7 | 0 |
"""Kaartdijin Boodja Catalogue Cleanup Pending Imports Management Command."""
# Third-Party
from django.core.management import base
# Local
from govapp.apps.catalogue import pending_imports_cleanup
# Typing
from typing import Any
class Command(base.BaseCommand):
"""Cleanup Pending Imports Management Command."... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/catalogue/management/commands/cleanup_pending_imports.py | .py | a6d669f3657cb081 | 7 | 0 |
"""Kaartdijin Boodja Catalogue Scan Management Command."""
# Third-Party
from django.core.management import base
# Local
from govapp.apps.catalogue import sharepoint_scanner
# Typing
from typing import Any
class Command(base.BaseCommand):
"""Scan Management Command."""
# Help string
help = "Scans the ... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/catalogue/management/commands/get_sharepoint_files.py | .py | 55140e730ffaf22f | 7 | 0 |
"""Management command to redact plaintext passwords from ActionsLogEntry records.
Scans all ActionsLogEntry.what fields that contain 'userpassword' and replaces
the plaintext password value with '***'.
Usage:
# Dry-run (no changes written to DB):
python manage.py redact_subscription_passwords --dry-run
#... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/catalogue/management/commands/redact_subscription_passwords.py | .py | 4efd789d4300ec5c | 7 | 0 |
"""Kaartdijin Boodja Catalogue Scan Management Command."""
# Third-Party
from django.core.management import base
# Local
from govapp.apps.catalogue import scanner
# Typing
from typing import Any
class Command(base.BaseCommand):
"""Scan Management Command."""
# Help string
help = "Scans the staging are... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/catalogue/management/commands/scan.py | .py | 8046a51e572b391f | 7 | 0 |
"""Kaartdijin Boodja Catalogue Scan Management Command."""
# Third-Party
from django.core.management import base
# Local
from govapp.apps.catalogue import directory_scanner
# Typing
from typing import Any
class Command(base.BaseCommand):
"""Scan Management Command."""
# Help string
help = "Scans the s... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/catalogue/management/commands/scan_dir.py | .py | 336de212980fe408 | 7 | 0 |
"""Kaartdijin Boodja Catalogue Scan Management Command."""
# Third-Party
from django.core.management import base
# Local
from govapp.apps.catalogue import postgres_scanner
# Typing
from typing import Any
class Command(base.BaseCommand):
"""Scan Management Command."""
# Help string
help = "Scans the st... | dbca-wa/gis_kaartdijin_boodja | govapp/apps/catalogue/management/commands/scan_postgres.py | .py | 90356d97ec243a60 | 7 | 0 |
"""Asynchronous Python client providing Open Data information of Brussel."""
from __future__ import annotations
import asyncio
import socket
from dataclasses import dataclass
from importlib import metadata
from typing import Any, Self
from aiohttp import ClientError, ClientSession
from aiohttp.hdrs import METH_GET
f... | klaasnicolaas/python-brussel | src/brussel/brussel.py | .py | 19baea0ba0d99d53 | 7 | 0 |
import asyncio
import logging
import os
from dataclasses import dataclass
from typing import Tuple, List
import shlex
from datetime import datetime
from collections import Counter
logger = logging.getLogger(__name__)
COMMIT_HEADER_KEY = "Commit: "
@dataclass
class GitCommitLocal:
"""Represents a Git commit in l... | sonic-net/sonic-pipelines | scripts/code-owners/async_helpers.py | .py | 031d7104c0ba2613 | 7 | 0 |
"""Module for managing contributor information and collections."""
import logging
import os
from typing import Optional, Dict, List, Set
import yaml
import aiofiles
from organization import (
organization_by_company,
organization_by_suffix,
organization_by_emails,
ORGANIZATION,
)
logger = logging.get... | sonic-net/sonic-pipelines | scripts/code-owners/contributor.py | .py | 5cee80a442b72a64 | 7 | 0 |
"""Module for managing folder settings and repository folder analysis."""
import os
from collections import namedtuple
from enum import Enum
import shlex
from typing import Dict, Tuple
import aiofiles
import aiofiles.os
import yaml
from async_helpers import (
async_run_cmd_lines,
)
class FolderType(Enum):
... | sonic-net/sonic-pipelines | scripts/code-owners/folders.py | .py | eb4fd1f9d654e884 | 7 | 0 |
import argparse
import asyncio
import os
from datetime import datetime, timezone, date, timedelta
import logging
import time
import yaml
__version__ = "0.0.5"
from async_github_repo_summary import (
AsyncGitHubRepoSummary,
)
from async_helpers import (
get_remote_owner_repo,
get_commit_count,
)
from contr... | sonic-net/sonic-pipelines | scripts/code-owners/main.py | .py | 946de390f42858d9 | 7 | 0 |
"""Module for managing organization information and classification."""
import enum
from typing import Set
class ORGANIZATION(enum.Enum):
"""Enumeration of supported organizations."""
ANET = "Arista"
AVGO = "Broadcom"
BABA = "Alibaba Inc"
CSCO = "Cisco"
DELL = "Dell technologies"
HCLTECH ... | sonic-net/sonic-pipelines | scripts/code-owners/organization.py | .py | ff499d0f46f92670 | 7 | 0 |
# see https://galea.medium.com/how-to-love-jsonl-using-json-line-format-in-your-workflow-b6884f65175b
import json
def dump_jsonl(data, output_path, append=False):
"""
Write list of objects to a JSON lines file.
"""
mode = 'a+' if append else 'w'
with open(output_path, mode, encoding='utf-8') as f:... | LaggAt/actions | jsonl.py | .py | 6a33c7e6e9f73e87 | 7.15 | 1 |
# stdlib
import atexit
import string
# 3rd party
import araokaat
import pypi_json
import requests
from domdf_python_tools.paths import PathPlus
from packaging.requirements import InvalidRequirement
hit_count = 0
miss_count = 0
# X-Cache HIT or MISS
changed_count = 0
cache_dir = PathPlus.cwd() / "search_cache"
regen... | domdfcoding/pypi_search | get_metadata.py | .py | c062b9557c02971d | 7 | 0 |
# stdlib
import concurrent.futures
import re
import string
import subprocess
import sys
from typing import Tuple
# 3rd party
import click
import platformdirs
from consolekit.options import flag_option
from domdf_python_tools.paths import PathPlus, in_directory
from domdf_python_tools.utils import divide, stderr_writer... | domdfcoding/pypi_search | search.py | .py | 15c40d9d02e29403 | 7 | 0 |
#!/usr/bin/env python3
"""Deterministic gate for the weekly audit workflow.
Fails (exit 1) unless:
* every modified tracked file is inside the audit allowlist
(deadlines/data/manual.yml or deadlines/data/conferences/**), and
* every manual.yml entry is preceded by a comment block containing
'Verified' and ... | SecAI-Lab/secai-lab.github.io | deadlines/scripts/audit_lint.py | .py | b292349efb60411e | 7 | 0 |
#!/usr/bin/env python3
"""Which verified corrections may publish themselves, and which wait for a human.
The gate (verify_citations.py) answers "does the page say this". It cannot
answer "what does being wrong cost". That is this module's job, and the answer
turns on DIRECTION.
Showing a deadline EARLIER than the tru... | SecAI-Lab/secai-lab.github.io | deadlines/scripts/risk_policy.py | .py | 8ca47a8a37e90435 | 7 | 0 |
#!/usr/bin/env python3
"""Tests for audit_lint.py, run against throwaway git repos.
Run: python3 deadlines/scripts/tests/test_audit_lint.py
The lint is the gate that stops the audit writing outside deadlines/data, so
it has to be exercised in isolation - running it in the real working tree only
ever tells you about t... | SecAI-Lab/secai-lab.github.io | deadlines/scripts/tests/test_audit_lint.py | .py | 7aa12d95730d31e6 | 7.5 | 0 |
"""Export Card objects to Anki-importable formats."""
from __future__ import annotations
import hashlib
import json
import urllib.error
import urllib.request
from pathlib import Path
import genanki
from anki_skill.models import Card
def _sanitize_tsv(value: str) -> str:
"""Remove characters that would corrupt... | BENJAMINGLAI/anki-card-skill | src/anki_skill/exporters.py | .py | 4c4e214cd875f539 | 7.15 | 1 |
"""Data models for Anki flashcards."""
from __future__ import annotations
import re
from dataclasses import dataclass, field
@dataclass
class Card:
"""A single Anki flashcard with question, answer, and tags."""
question: str
answer: str
tags: list[str] = field(default_factory=list)
@property
... | BENJAMINGLAI/anki-card-skill | src/anki_skill/models.py | .py | dcddaab6ada8082b | 7.15 | 1 |
"""Parse pipe-delimited flashcard text into Card objects."""
from __future__ import annotations
import sys
from anki_skill.models import Card
def parse_cards(text: str, verbose: bool = False) -> list[Card]:
"""Parse pipe-delimited card text into a list of Card objects.
Expected format per line:
qu... | BENJAMINGLAI/anki-card-skill | src/anki_skill/parser.py | .py | 4fa83b20470510d4 | 7.15 | 1 |
import subprocess
import sys
import tempfile
from pathlib import Path
FIXTURES = Path(__file__).parent / "fixtures"
def _run_cli(*args: str) -> subprocess.CompletedProcess:
return subprocess.run(
[sys.executable, "-m", "anki_skill.cli", *args],
capture_output=True,
text=True,
)
def ... | BENJAMINGLAI/anki-card-skill | tests/test_cli.py | .py | 9b2036d721b02d8b | 7.65 | 1 |
"""Rendering of a Springer Nature article record into a Telegram channel post.
Posts use HTML parse mode rather than Markdown: scientific text is full of
``_``, ``*`` and ``[`` (gene names, formulae, "[sic]"), and any unbalanced pair
makes Telegram reject the whole message. HTML only needs ``&``, ``<`` and ``>``
escap... | faramer86/PaperPulse | post.py | .py | 8ac8a70766958683 | 7.15 | 1 |
"""Memory of which articles have already been posted.
The bot re-queries a rolling window on every run, so the same article comes
back repeatedly until it falls out of the window. This store is what turns
that overlap from duplicate posts into a no-op, and it is why the bot no
longer needs the old two-day publication ... | faramer86/PaperPulse | store.py | .py | b6af9ad796bfb4b5 | 7.15 | 1 |
"""Tests for how the bot is configured to talk to Telegram.
Every post carries a link preview, so Telegram fetches the nature.com page and
its og:image before answering. PTB's default 5s read/write timeout is not
enough for that, and a timeout is ambiguous: the message may already have been
delivered, so a retry can d... | faramer86/PaperPulse | tests/test_delivery.py | .py | 8e1e44ec1a8deaf8 | 7.65 | 1 |
"""Tests for the link preview attached to each post.
Every nature.com article page carries an og:image, so the preview is what puts
a picture on the post. It is pointed at the article URL explicitly rather than
left to Telegram's "first link in the text" rule.
"""
from post import preview_for
ARTICLE = {
'doi': ... | faramer86/PaperPulse | tests/test_preview.py | .py | 44f35867206a4dea | 7.65 | 1 |
"""Tests for the Springer query and the client-side article-type filter.
The Basic plan rejects `articletype:` with HTTP 403 (premium only), so type
filtering happens in Python against the `genre` field every record carries.
"""
import pytest
from paperpulse import build_query, is_wanted
def test_query_uses_a_date... | faramer86/PaperPulse | tests/test_query.py | .py | 467b643a3ea3f934 | 7.65 | 1 |
"""Invariants for the journal/channel routing tables."""
from Vars import JCHANNEL, JID, SPRINGER_URL
def test_api_is_reached_over_tls():
"""The API key travels in the query string, so plain HTTP leaks it."""
assert SPRINGER_URL.startswith('https://')
def test_every_journal_has_a_channel():
assert set(... | faramer86/PaperPulse | tests/test_vars.py | .py | a3341ce7c915d1cc | 7.65 | 1 |
#!/usr/bin/env python
"""
Build the site using Zola.
Zola reads config.toml plus content/, templates/, sass/ and static/, and
writes to _site/ (kept as the output dir so the Pages workflow and the
.gitignore entries do not have to change).
Posts are authored directly in content/blog/. The old blog/posts/ tree and
sc... | veltzer/veltzer.github.io | scripts/build_site.py | .py | aab84a6404b04760 | 7.15 | 1 |
#!/usr/bin/env python
"""
Check that every media item that should have a local image actually has one
in static/images/.
Checks:
- Movies: static/images/movie-{imdb_id}.jpg
- Series: static/images/series-{imdb_id}.jpg
- Audible: static/images/audible-{asin}.jpg
- Audio Courses: static/images/audiocourse-gc-{gc_id}.jp... | veltzer/veltzer.github.io | scripts/check_images.py | .py | 3663f1ac6d807d82 | 7.15 | 1 |
#!/usr/bin/env python
"""
Check that the profile URLs in ../data/yaml/profiles.yaml still resolve.
Those ~30 links are rendered into content/about/ here and into README.md in the
../veltzer repository. They are exactly the kind of URL that dies quietly: a
service shuts down, a username changes, a profile goes private... | veltzer/veltzer.github.io | scripts/check_profile_links.py | .py | 721109d56af41004 | 7.15 | 1 |
#!/usr/bin/env python
"""
Copy media/chess/youtube data from the sibling ../data repo into static/data.
YAML data for the media tracker lives in a separate ../data repository and
is copied in during build. This script validates the sources exist, copies
the plain YAML files, merges the gzipped chess archives, runs th... | veltzer/veltzer.github.io | scripts/copy_data.py | .py | daec4eb34e625e86 | 7.15 | 1 |
#!/usr/bin/env python
"""Convert YouTube CSV export to trimmed YAML for the media viewer."""
import argparse
import csv
import sys
import yaml
FIELDS = [
"title",
"channel",
"upload_date",
"duration",
"view_count",
"categories",
"webpage_url",
]
def parse_int(value):
try:
r... | veltzer/veltzer.github.io | scripts/csv_to_yaml.py | .py | 8e199e5ede07ed6a | 7.15 | 1 |
#!/usr/bin/env python
"""
Fetch cover images for Audible books using the cover_url from the YAML.
Images saved as static/images/audible-{asin}.jpg
Incremental: skips books that already have an image.
Usage:
scripts/fetch_audible_images.py [--force]
"""
import argparse
import os
import time
import urllib.error
im... | veltzer/veltzer.github.io | scripts/fetch_audible_images.py | .py | 48c150bf4e6e460f | 7.15 | 1 |
#!/usr/bin/env python
"""
Fetch cover images for all audio courses.
Priority:
1. great_courses_id -> download from Great Courses CDN
-> audiocourse-gc-{id}.jpg
2. audible_asin -> download from Audible page (og:image)
-> audiocourse-audible-{asin}.jpg
3. Neither -> DuckDuckGo image search with GUI picker
-> a... | veltzer/veltzer.github.io | scripts/fetch_audiocourse_images.py | .py | e87cda8ee35a88df | 7.15 | 1 |
#!/usr/bin/env python
"""
Fetch images for museum visits via DuckDuckGo image search with GUI picker.
Images saved as static/images/museum-{internal_id}.jpg
Incremental: skips museums that already have an image.
The data records one entry per *visit*, so the same museum can appear several
times with different inter... | veltzer/veltzer.github.io | scripts/fetch_museum_images.py | .py | c4e7b0a313331b27 | 7.15 | 1 |
#!/usr/bin/env python
"""
Fetch images for podcasts via DuckDuckGo image search with GUI picker.
Images saved as static/images/podcast-{internal_id}.jpg
Incremental: skips podcasts that already have an image.
Usage:
scripts/fetch_podcast_images.py [--force]
"""
import argparse
import os
from pathlib import Path
... | veltzer/veltzer.github.io | scripts/fetch_podcast_images.py | .py | 1f63fe41d6534402 | 7.15 | 1 |
#!/usr/bin/env python
"""
Render the profile links from ../data/yaml/profiles.yaml into both places that
show them, so the two cannot drift apart.
Targets:
content/about/_index.en.md this site's About page
content/about/_index.he.md its Hebrew translation
static/identity.toml sameA... | veltzer/veltzer.github.io | scripts/gen_profiles.py | .py | 3b5f3cb0573cb445 | 7.15 | 1 |
"""
Shared image search and picker GUI for fetching cover images.
Provides DuckDuckGo image search and a tkinter browser for selecting images.
"""
import json
import os
import re
import shutil
import tkinter as tk
import urllib.error
import urllib.parse
import urllib.request
from image_standard import normalise
from... | veltzer/veltzer.github.io | scripts/image_picker.py | .py | d75ca6cfa999f3a0 | 7.15 | 1 |
#!/usr/bin/env python
"""Import audible.yaml from ../data, keeping only needed fields with correct types."""
import argparse
import sys
import yaml
class QuotedStr(str):
"""String subclass that forces YAML quoting."""
def _quoted_str_representer(dumper, data):
return dumper.represent_scalar("tag:yaml.org... | veltzer/veltzer.github.io | scripts/import_audible.py | .py | 05a558bb0ad9438d | 7.15 | 1 |
#!/usr/bin/env python
"""
Import the teaching-* sites into content/ as native Zola pages.
Each of the sibling repos (../teaching-slides, ../teaching-syllabi,
../teaching-animations) builds a single self-contained `_site/index.html`:
inline <style>, one or two <script> blocks, and its data inline as `const DATA`.
That... | veltzer/veltzer.github.io | scripts/import_teaching.py | .py | 9e1e30a735d9c72b | 7.15 | 1 |
#!/usr/bin/env python
"""
Bring every image in static/images/ down to the site standard.
The fetchers normalise on save (scripts/image_standard.py), so this exists for
two cases: files that predate that change, and files added by hand or by a
contributor without ImageMagick installed.
Idempotent. ImageMagick's `>` g... | veltzer/veltzer.github.io | scripts/normalise_images.py | .py | e4cd74f61565fd31 | 7.15 | 1 |
"""
Shared utilities for fetching poster images from TMDB with OMDB fallback.
"""
import gzip
import json
import os
import subprocess
import sys
import time
import urllib.error
import urllib.request
import yaml
from image_standard import normalise
TMDB_FIND_URL = "https://api.themoviedb.org/3/find/tt{imdb_id}?extern... | veltzer/veltzer.github.io | scripts/poster_utils.py | .py | 3855738ae2ad8d81 | 7.15 | 1 |
#!/usr/bin/env python
"""
Local QA preview of the site as GitHub Pages will serve it.
Why not `zola serve`?
`zola serve` is great for authoring (live rebuild + browser
auto-reload), but it is NOT faithful to what gets deployed:
- It serves from an in-memory build, not the real `_site/` output.
- It skips ... | veltzer/veltzer.github.io | scripts/serve.py | .py | bdc063ee39329c63 | 7.15 | 1 |
#!/usr/bin/env python
"""
Validates that in a given JSON schema, for every object that has a
'propertyOrdering' array, that array is a perfect match for the keys
defined in the 'properties' object.
"""
import argparse
import json
import sys
def validate_schema_object(schema_part, path="root"):
"""
Recursive... | veltzer/schemas | scripts/validate_schema.py | .py | 35fc766945523d91 | 7 | 0 |
"""Shared auth helpers for public/private library access control."""
from fastapi import HTTPException, Request
def require_auth(request: Request) -> str:
"""Raise 401 if no authenticated user. Return username."""
user = request.state.remote_user
if not user:
raise HTTPException(status_code=401, ... | Junior81195/athenaeum | src/api/auth.py | .py | 2b6758c5f32f56a7 | 7.15 | 1 |
"""DB-backed sliding window rate limiter.
Uses PostgreSQL rate_limits table for persistence across restarts.
Falls back to in-memory if DB is unavailable.
"""
import logging
import time
from collections import defaultdict
from threading import Lock
import psycopg2
from fastapi import HTTPException, Request
from con... | Junior81195/athenaeum | src/api/rate_limit.py | .py | 779716a42ec037b9 | 7.15 | 1 |
"""Shared embedding provider using local sentence-transformers model."""
from sentence_transformers import SentenceTransformer
MODEL_NAME = "all-mpnet-base-v2"
EMBEDDING_DIMENSIONS = 768
_model = None
def get_model() -> SentenceTransformer:
global _model
if _model is None:
_model = SentenceTransfor... | Junior81195/athenaeum | src/embeddings/provider.py | .py | 6999a1558e3a1e66 | 7.15 | 1 |
"""Smart text chunking with semantic boundary detection."""
import re
import tiktoken
ENCODER = tiktoken.get_encoding("cl100k_base")
def count_tokens(text: str) -> int:
return len(ENCODER.encode(text))
def chunk_text(text: str, max_tokens: int = 500, overlap_tokens: int = 50) -> list[dict]:
"""Split text... | Junior81195/athenaeum | src/ingestion/chunker.py | .py | ec292ec0afd2c382 | 7.15 | 1 |
"""Auto-discover topics from chunk embeddings using K-Means + keyword extraction.
Multi-library aware: clusters per library_id, stores in topics + document_topics tables.
"""
import json
import logging
import re
from collections import Counter
import numpy as np
import psycopg2
import psycopg2.extras
from sklearn.cl... | Junior81195/athenaeum | src/ingestion/cluster.py | .py | d33ef78935794646 | 7.15 | 1 |
"""Generate embeddings for transcript chunks and store in pgvector."""
import os
import sys
import time
import psycopg2
from google import genai
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
from config.settings import DATABASE_URL
from src.ingestion.chunker import chunk_text
GEMIN... | Junior81195/athenaeum | src/ingestion/embed.py | .py | 06cc1e1d12ee05f7 | 7.15 | 1 |
"""Generate embeddings locally using sentence-transformers (no API cost)."""
import os
import sys
import time
import numpy as np
import psycopg2
from sentence_transformers import SentenceTransformer
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
from config.settings import DATABASE_U... | Junior81195/athenaeum | src/ingestion/embed_local.py | .py | 4b2f7c5c5237bd55 | 7.15 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.