Files
vector/.venv-test/lib/python3.12/site-packages/cryptography/utils.py
T
Sadmin f20080305d feat: ж/д слой + cant_swim в скоринг + профили вне модели
Определение специфических рекомендаций (матрица профилей §8):

1. Ж/д слой (закрыт мёртвый railway ×2.5 у РАС):
   - /api/v1/water/{case_id} отдаёт railway=rail как LineString
     (без service/industrial/military веток), кэш общий v2;
   - railway_warning «перекрыть/проверить немедленно» по профилям;
   - SearchMap: Polyline слой ж/д (тёмно-красный), счётчики 💧/🚂.

2. cant_swim → профиль не_умеет_плавать (water ×3.0, без изменения
   радиуса, critical_warning «обследовать водоёмы НЕМЕДЛЕННО»):
   - раньше чекбокс влиял только на текст, в скоринге был пробел;
   - derive в analyze._derive_profiles — работает и для closed_cases.

3. unmodeled_profiles: ДЦП/слабое зрение/слух — честная пометка
   «вне поведенческой модели» с пояснением (vector_tasks B12:
   профили без аналога не выдавать за учтённые); блок на фронте
   в карточке здоровья.

Площадь воды: сферический эксцесс, проверен на квадрате 53° (744017 м²
vs 743272 точного). Тесты: 202 passed (новый test_cant_swim_profile).
2026-09-09 13:12:55 +03:00

137 lines
4.5 KiB
Python

# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import annotations
import enum
import sys
import types
import typing
import warnings
from collections.abc import Sequence
# We use a UserWarning subclass, instead of DeprecationWarning, because CPython
# decided deprecation warnings should be invisible by default.
class CryptographyDeprecationWarning(UserWarning):
pass
# Several APIs were deprecated with no specific end-of-life date because of the
# ubiquity of their use. They should not be removed until we agree on when that
# cycle ends.
DeprecatedIn36 = CryptographyDeprecationWarning
DeprecatedIn40 = CryptographyDeprecationWarning
DeprecatedIn41 = CryptographyDeprecationWarning
DeprecatedIn42 = CryptographyDeprecationWarning
DeprecatedIn43 = CryptographyDeprecationWarning
DeprecatedIn47 = CryptographyDeprecationWarning
DeprecatedIn50 = CryptographyDeprecationWarning
# If you're wondering why we don't use `Buffer`, it's because `Buffer` would
# be more accurately named: Bufferable. It means something which has an
# `__buffer__`. Which means you can't actually treat the result as a buffer
# (and do things like take a `len()`).
Buffer = typing.Union[bytes, bytearray, memoryview]
def _check_bytes(name: str, value: bytes) -> None:
if not isinstance(value, bytes):
raise TypeError(f"{name} must be bytes")
def _check_byteslike(name: str, value: Buffer) -> None:
if isinstance(value, (bytes, bytearray, memoryview)):
return
try:
memoryview(value)
except TypeError:
raise TypeError(f"{name} must be bytes-like")
def int_to_bytes(integer: int, length: int | None = None) -> bytes:
if length == 0:
raise ValueError("length argument can't be 0")
return integer.to_bytes(
length or (integer.bit_length() + 7) // 8 or 1, "big"
)
class InterfaceNotImplemented(Exception):
pass
class _DeprecatedValue:
def __init__(self, value: object, message: str, warning_class):
self.value = value
self.message = message
self.warning_class = warning_class
class _ModuleWithDeprecations(types.ModuleType):
def __init__(self, module: types.ModuleType):
super().__init__(module.__name__)
self.__dict__["_module"] = module
def __getattr__(self, name: str) -> typing.Any:
obj = getattr(self._module, name)
if isinstance(obj, _DeprecatedValue):
warnings.warn(obj.message, obj.warning_class, stacklevel=2)
obj = obj.value
else:
# Cache non-deprecated attributes in our own `__dict__` so that
# subsequent lookups are ordinary module attribute accesses and
# don't pay for this `__getattr__` (which would otherwise defeat
# CPython's LOAD_ATTR module caching for every attribute of the
# module). `__setattr__` and `__delattr__` keep the cache
# coherent.
self.__dict__[name] = obj
return obj
def __setattr__(self, attr: str, value: object) -> None:
if isinstance(value, _DeprecatedValue):
self.__dict__.pop(attr, None)
else:
self.__dict__[attr] = value
setattr(self._module, attr, value)
def __delattr__(self, attr: str) -> None:
obj = getattr(self._module, attr)
if isinstance(obj, _DeprecatedValue):
warnings.warn(obj.message, obj.warning_class, stacklevel=2)
self.__dict__.pop(attr, None)
delattr(self._module, attr)
def __dir__(self) -> Sequence[str]:
return ["_module", *dir(self._module)]
def deprecated(
value: object,
module_name: str,
message: str,
warning_class: type[Warning],
name: str | None = None,
) -> _DeprecatedValue:
module = sys.modules[module_name]
if not isinstance(module, _ModuleWithDeprecations):
sys.modules[module_name] = module = _ModuleWithDeprecations(module)
dv = _DeprecatedValue(value, message, warning_class)
# Maintain backwards compatibility with `name is None` for pyOpenSSL.
if name is not None:
setattr(module, name, dv)
return dv
# Python 3.10 changed representation of enums. We use well-defined object
# representation and string representation from Python 3.9.
class Enum(enum.Enum):
def __repr__(self) -> str:
return f"<{self.__class__.__name__}.{self._name_}: {self._value_!r}>"
def __str__(self) -> str:
return f"{self.__class__.__name__}.{self._name_}"