file_path
stringlengths
21
202
content
stringlengths
19
1.02M
size
int64
19
1.02M
lang
stringclasses
8 values
avg_line_length
float64
5.88
100
max_line_length
int64
12
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/tests/test__all__.py
import collections import numpy as np def test_no_duplicates_in_np__all__(): # Regression test for gh-10198. dups = {k: v for k, v in collections.Counter(np.__all__).items() if v > 1} assert len(dups) == 0
221
Python
21.199998
78
0.638009
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/tests/test_numpy_version.py
""" Check the numpy version is valid. Note that a development version is marked by the presence of 'dev0' or '+' in the version string, all else is treated as a release. The version string itself is set from the output of ``git describe`` which relies on tags. Examples -------- Valid Development: 1.22.0.dev0 1.22.0.dev0+5-g7999db4df2 1.22.0+5-g7999db4df2 Valid Release: 1.21.0.rc1, 1.21.0.b1, 1.21.0 Invalid: 1.22.0.dev, 1.22.0.dev0-5-g7999db4dfB, 1.21.0.d1, 1.21.a Note that a release is determined by the version string, which in turn is controlled by the result of the ``git describe`` command. """ import re import numpy as np from numpy.testing import assert_ def test_valid_numpy_version(): # Verify that the numpy version is a valid one (no .post suffix or other # nonsense). See gh-6431 for an issue caused by an invalid version. version_pattern = r"^[0-9]+\.[0-9]+\.[0-9]+(a[0-9]|b[0-9]|rc[0-9]|)" dev_suffix = r"(\.dev0|)(\+[0-9]*\.g[0-9a-f]+|)" if np.version.release: res = re.match(version_pattern + '$', np.__version__) else: res = re.match(version_pattern + dev_suffix + '$', np.__version__) assert_(res is not None, np.__version__) def test_short_version(): # Check numpy.short_version actually exists if np.version.release: assert_(np.__version__ == np.version.short_version, "short_version mismatch in release version") else: assert_(np.__version__.split("+")[0] == np.version.short_version, "short_version mismatch in development version")
1,575
Python
34.022221
77
0.653333
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/tests/test_warnings.py
""" Tests which scan for certain occurrences in the code, they may not find all of these occurrences but should catch almost all. """ import pytest from pathlib import Path import ast import tokenize import numpy class ParseCall(ast.NodeVisitor): def __init__(self): self.ls = [] def visit_Attribute(self, node): ast.NodeVisitor.generic_visit(self, node) self.ls.append(node.attr) def visit_Name(self, node): self.ls.append(node.id) class FindFuncs(ast.NodeVisitor): def __init__(self, filename): super().__init__() self.__filename = filename def visit_Call(self, node): p = ParseCall() p.visit(node.func) ast.NodeVisitor.generic_visit(self, node) if p.ls[-1] == 'simplefilter' or p.ls[-1] == 'filterwarnings': if node.args[0].s == "ignore": raise AssertionError( "warnings should have an appropriate stacklevel; found in " "{} on line {}".format(self.__filename, node.lineno)) if p.ls[-1] == 'warn' and ( len(p.ls) == 1 or p.ls[-2] == 'warnings'): if "testing/tests/test_warnings.py" == self.__filename: # This file return # See if stacklevel exists: if len(node.args) == 3: return args = {kw.arg for kw in node.keywords} if "stacklevel" in args: return raise AssertionError( "warnings should have an appropriate stacklevel; found in " "{} on line {}".format(self.__filename, node.lineno)) @pytest.mark.slow def test_warning_calls(): # combined "ignore" and stacklevel error base = Path(numpy.__file__).parent for path in base.rglob("*.py"): if base / "testing" in path.parents: continue if path == base / "__init__.py": continue if path == base / "random" / "__init__.py": continue # use tokenize to auto-detect encoding on systems where no # default encoding is defined (e.g. LANG='C') with tokenize.open(str(path)) as file: tree = ast.parse(file.read()) FindFuncs(path).visit(tree)
2,280
Python
29.413333
79
0.556579
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/_utility_functions.py
from __future__ import annotations from ._array_object import Array from typing import Optional, Tuple, Union import numpy as np def all( x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ) -> Array: """ Array API compatible wrapper for :py:func:`np.all <numpy.all>`. See its docstring for more information. """ return Array._new(np.asarray(np.all(x._array, axis=axis, keepdims=keepdims))) def any( x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ) -> Array: """ Array API compatible wrapper for :py:func:`np.any <numpy.any>`. See its docstring for more information. """ return Array._new(np.asarray(np.any(x._array, axis=axis, keepdims=keepdims)))
824
Python
20.710526
81
0.618932
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/_sorting_functions.py
from __future__ import annotations from ._array_object import Array import numpy as np # Note: the descending keyword argument is new in this function def argsort( x: Array, /, *, axis: int = -1, descending: bool = False, stable: bool = True ) -> Array: """ Array API compatible wrapper for :py:func:`np.argsort <numpy.argsort>`. See its docstring for more information. """ # Note: this keyword argument is different, and the default is different. kind = "stable" if stable else "quicksort" if not descending: res = np.argsort(x._array, axis=axis, kind=kind) else: # As NumPy has no native descending sort, we imitate it here. Note that # simply flipping the results of np.argsort(x._array, ...) would not # respect the relative order like it would in native descending sorts. res = np.flip( np.argsort(np.flip(x._array, axis=axis), axis=axis, kind=kind), axis=axis, ) # Rely on flip()/argsort() to validate axis normalised_axis = axis if axis >= 0 else x.ndim + axis max_i = x.shape[normalised_axis] - 1 res = max_i - res return Array._new(res) # Note: the descending keyword argument is new in this function def sort( x: Array, /, *, axis: int = -1, descending: bool = False, stable: bool = True ) -> Array: """ Array API compatible wrapper for :py:func:`np.sort <numpy.sort>`. See its docstring for more information. """ # Note: this keyword argument is different, and the default is different. kind = "stable" if stable else "quicksort" res = np.sort(x._array, axis=axis, kind=kind) if descending: res = np.flip(res, axis=axis) return Array._new(res)
1,754
Python
34.099999
81
0.63626
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/_creation_functions.py
from __future__ import annotations from typing import TYPE_CHECKING, List, Optional, Tuple, Union if TYPE_CHECKING: from ._typing import ( Array, Device, Dtype, NestedSequence, SupportsBufferProtocol, ) from collections.abc import Sequence from ._dtypes import _all_dtypes import numpy as np def _check_valid_dtype(dtype): # Note: Only spelling dtypes as the dtype objects is supported. # We use this instead of "dtype in _all_dtypes" because the dtype objects # define equality with the sorts of things we want to disallow. for d in (None,) + _all_dtypes: if dtype is d: return raise ValueError("dtype must be one of the supported dtypes") def asarray( obj: Union[ Array, bool, int, float, NestedSequence[bool | int | float], SupportsBufferProtocol, ], /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None, copy: Optional[Union[bool, np._CopyMode]] = None, ) -> Array: """ Array API compatible wrapper for :py:func:`np.asarray <numpy.asarray>`. See its docstring for more information. """ # _array_object imports in this file are inside the functions to avoid # circular imports from ._array_object import Array _check_valid_dtype(dtype) if device not in ["cpu", None]: raise ValueError(f"Unsupported device {device!r}") if copy in (False, np._CopyMode.IF_NEEDED): # Note: copy=False is not yet implemented in np.asarray raise NotImplementedError("copy=False is not yet implemented") if isinstance(obj, Array): if dtype is not None and obj.dtype != dtype: copy = True if copy in (True, np._CopyMode.ALWAYS): return Array._new(np.array(obj._array, copy=True, dtype=dtype)) return obj if dtype is None and isinstance(obj, int) and (obj > 2 ** 64 or obj < -(2 ** 63)): # Give a better error message in this case. NumPy would convert this # to an object array. TODO: This won't handle large integers in lists. raise OverflowError("Integer out of bounds for array dtypes") res = np.asarray(obj, dtype=dtype) return Array._new(res) def arange( start: Union[int, float], /, stop: Optional[Union[int, float]] = None, step: Union[int, float] = 1, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None, ) -> Array: """ Array API compatible wrapper for :py:func:`np.arange <numpy.arange>`. See its docstring for more information. """ from ._array_object import Array _check_valid_dtype(dtype) if device not in ["cpu", None]: raise ValueError(f"Unsupported device {device!r}") return Array._new(np.arange(start, stop=stop, step=step, dtype=dtype)) def empty( shape: Union[int, Tuple[int, ...]], *, dtype: Optional[Dtype] = None, device: Optional[Device] = None, ) -> Array: """ Array API compatible wrapper for :py:func:`np.empty <numpy.empty>`. See its docstring for more information. """ from ._array_object import Array _check_valid_dtype(dtype) if device not in ["cpu", None]: raise ValueError(f"Unsupported device {device!r}") return Array._new(np.empty(shape, dtype=dtype)) def empty_like( x: Array, /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None ) -> Array: """ Array API compatible wrapper for :py:func:`np.empty_like <numpy.empty_like>`. See its docstring for more information. """ from ._array_object import Array _check_valid_dtype(dtype) if device not in ["cpu", None]: raise ValueError(f"Unsupported device {device!r}") return Array._new(np.empty_like(x._array, dtype=dtype)) def eye( n_rows: int, n_cols: Optional[int] = None, /, *, k: int = 0, dtype: Optional[Dtype] = None, device: Optional[Device] = None, ) -> Array: """ Array API compatible wrapper for :py:func:`np.eye <numpy.eye>`. See its docstring for more information. """ from ._array_object import Array _check_valid_dtype(dtype) if device not in ["cpu", None]: raise ValueError(f"Unsupported device {device!r}") return Array._new(np.eye(n_rows, M=n_cols, k=k, dtype=dtype)) def from_dlpack(x: object, /) -> Array: from ._array_object import Array return Array._new(np.from_dlpack(x)) def full( shape: Union[int, Tuple[int, ...]], fill_value: Union[int, float], *, dtype: Optional[Dtype] = None, device: Optional[Device] = None, ) -> Array: """ Array API compatible wrapper for :py:func:`np.full <numpy.full>`. See its docstring for more information. """ from ._array_object import Array _check_valid_dtype(dtype) if device not in ["cpu", None]: raise ValueError(f"Unsupported device {device!r}") if isinstance(fill_value, Array) and fill_value.ndim == 0: fill_value = fill_value._array res = np.full(shape, fill_value, dtype=dtype) if res.dtype not in _all_dtypes: # This will happen if the fill value is not something that NumPy # coerces to one of the acceptable dtypes. raise TypeError("Invalid input to full") return Array._new(res) def full_like( x: Array, /, fill_value: Union[int, float], *, dtype: Optional[Dtype] = None, device: Optional[Device] = None, ) -> Array: """ Array API compatible wrapper for :py:func:`np.full_like <numpy.full_like>`. See its docstring for more information. """ from ._array_object import Array _check_valid_dtype(dtype) if device not in ["cpu", None]: raise ValueError(f"Unsupported device {device!r}") res = np.full_like(x._array, fill_value, dtype=dtype) if res.dtype not in _all_dtypes: # This will happen if the fill value is not something that NumPy # coerces to one of the acceptable dtypes. raise TypeError("Invalid input to full_like") return Array._new(res) def linspace( start: Union[int, float], stop: Union[int, float], /, num: int, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None, endpoint: bool = True, ) -> Array: """ Array API compatible wrapper for :py:func:`np.linspace <numpy.linspace>`. See its docstring for more information. """ from ._array_object import Array _check_valid_dtype(dtype) if device not in ["cpu", None]: raise ValueError(f"Unsupported device {device!r}") return Array._new(np.linspace(start, stop, num, dtype=dtype, endpoint=endpoint)) def meshgrid(*arrays: Array, indexing: str = "xy") -> List[Array]: """ Array API compatible wrapper for :py:func:`np.meshgrid <numpy.meshgrid>`. See its docstring for more information. """ from ._array_object import Array # Note: unlike np.meshgrid, only inputs with all the same dtype are # allowed if len({a.dtype for a in arrays}) > 1: raise ValueError("meshgrid inputs must all have the same dtype") return [ Array._new(array) for array in np.meshgrid(*[a._array for a in arrays], indexing=indexing) ] def ones( shape: Union[int, Tuple[int, ...]], *, dtype: Optional[Dtype] = None, device: Optional[Device] = None, ) -> Array: """ Array API compatible wrapper for :py:func:`np.ones <numpy.ones>`. See its docstring for more information. """ from ._array_object import Array _check_valid_dtype(dtype) if device not in ["cpu", None]: raise ValueError(f"Unsupported device {device!r}") return Array._new(np.ones(shape, dtype=dtype)) def ones_like( x: Array, /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None ) -> Array: """ Array API compatible wrapper for :py:func:`np.ones_like <numpy.ones_like>`. See its docstring for more information. """ from ._array_object import Array _check_valid_dtype(dtype) if device not in ["cpu", None]: raise ValueError(f"Unsupported device {device!r}") return Array._new(np.ones_like(x._array, dtype=dtype)) def tril(x: Array, /, *, k: int = 0) -> Array: """ Array API compatible wrapper for :py:func:`np.tril <numpy.tril>`. See its docstring for more information. """ from ._array_object import Array if x.ndim < 2: # Note: Unlike np.tril, x must be at least 2-D raise ValueError("x must be at least 2-dimensional for tril") return Array._new(np.tril(x._array, k=k)) def triu(x: Array, /, *, k: int = 0) -> Array: """ Array API compatible wrapper for :py:func:`np.triu <numpy.triu>`. See its docstring for more information. """ from ._array_object import Array if x.ndim < 2: # Note: Unlike np.triu, x must be at least 2-D raise ValueError("x must be at least 2-dimensional for triu") return Array._new(np.triu(x._array, k=k)) def zeros( shape: Union[int, Tuple[int, ...]], *, dtype: Optional[Dtype] = None, device: Optional[Device] = None, ) -> Array: """ Array API compatible wrapper for :py:func:`np.zeros <numpy.zeros>`. See its docstring for more information. """ from ._array_object import Array _check_valid_dtype(dtype) if device not in ["cpu", None]: raise ValueError(f"Unsupported device {device!r}") return Array._new(np.zeros(shape, dtype=dtype)) def zeros_like( x: Array, /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None ) -> Array: """ Array API compatible wrapper for :py:func:`np.zeros_like <numpy.zeros_like>`. See its docstring for more information. """ from ._array_object import Array _check_valid_dtype(dtype) if device not in ["cpu", None]: raise ValueError(f"Unsupported device {device!r}") return Array._new(np.zeros_like(x._array, dtype=dtype))
10,050
Python
27.553977
86
0.628358
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/_array_object.py
""" Wrapper class around the ndarray object for the array API standard. The array API standard defines some behaviors differently than ndarray, in particular, type promotion rules are different (the standard has no value-based casting). The standard also specifies a more limited subset of array methods and functionalities than are implemented on ndarray. Since the goal of the array_api namespace is to be a minimal implementation of the array API standard, we need to define a separate wrapper class for the array_api namespace. The standard compliant class is only a wrapper class. It is *not* a subclass of ndarray. """ from __future__ import annotations import operator from enum import IntEnum from ._creation_functions import asarray from ._dtypes import ( _all_dtypes, _boolean_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _floating_dtypes, _numeric_dtypes, _result_type, _dtype_categories, ) from typing import TYPE_CHECKING, Optional, Tuple, Union, Any, SupportsIndex import types if TYPE_CHECKING: from ._typing import Any, PyCapsule, Device, Dtype import numpy.typing as npt import numpy as np from numpy import array_api class Array: """ n-d array object for the array API namespace. See the docstring of :py:obj:`np.ndarray <numpy.ndarray>` for more information. This is a wrapper around numpy.ndarray that restricts the usage to only those things that are required by the array API namespace. Note, attributes on this object that start with a single underscore are not part of the API specification and should only be used internally. This object should not be constructed directly. Rather, use one of the creation functions, such as asarray(). """ _array: np.ndarray # Use a custom constructor instead of __init__, as manually initializing # this class is not supported API. @classmethod def _new(cls, x, /): """ This is a private method for initializing the array API Array object. Functions outside of the array_api submodule should not use this method. Use one of the creation functions instead, such as ``asarray``. """ obj = super().__new__(cls) # Note: The spec does not have array scalars, only 0-D arrays. if isinstance(x, np.generic): # Convert the array scalar to a 0-D array x = np.asarray(x) if x.dtype not in _all_dtypes: raise TypeError( f"The array_api namespace does not support the dtype '{x.dtype}'" ) obj._array = x return obj # Prevent Array() from working def __new__(cls, *args, **kwargs): raise TypeError( "The array_api Array object should not be instantiated directly. Use an array creation function, such as asarray(), instead." ) # These functions are not required by the spec, but are implemented for # the sake of usability. def __str__(self: Array, /) -> str: """ Performs the operation __str__. """ return self._array.__str__().replace("array", "Array") def __repr__(self: Array, /) -> str: """ Performs the operation __repr__. """ suffix = f", dtype={self.dtype.name})" if 0 in self.shape: prefix = "empty(" mid = str(self.shape) else: prefix = "Array(" mid = np.array2string(self._array, separator=', ', prefix=prefix, suffix=suffix) return prefix + mid + suffix # This function is not required by the spec, but we implement it here for # convenience so that np.asarray(np.array_api.Array) will work. def __array__(self, dtype: None | np.dtype[Any] = None) -> npt.NDArray[Any]: """ Warning: this method is NOT part of the array API spec. Implementers of other libraries need not include it, and users should not assume it will be present in other implementations. """ return np.asarray(self._array, dtype=dtype) # These are various helper functions to make the array behavior match the # spec in places where it either deviates from or is more strict than # NumPy behavior def _check_allowed_dtypes(self, other: bool | int | float | Array, dtype_category: str, op: str) -> Array: """ Helper function for operators to only allow specific input dtypes Use like other = self._check_allowed_dtypes(other, 'numeric', '__add__') if other is NotImplemented: return other """ if self.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") if isinstance(other, (int, float, bool)): other = self._promote_scalar(other) elif isinstance(other, Array): if other.dtype not in _dtype_categories[dtype_category]: raise TypeError(f"Only {dtype_category} dtypes are allowed in {op}") else: return NotImplemented # This will raise TypeError for type combinations that are not allowed # to promote in the spec (even if the NumPy array operator would # promote them). res_dtype = _result_type(self.dtype, other.dtype) if op.startswith("__i"): # Note: NumPy will allow in-place operators in some cases where # the type promoted operator does not match the left-hand side # operand. For example, # >>> a = np.array(1, dtype=np.int8) # >>> a += np.array(1, dtype=np.int16) # The spec explicitly disallows this. if res_dtype != self.dtype: raise TypeError( f"Cannot perform {op} with dtypes {self.dtype} and {other.dtype}" ) return other # Helper function to match the type promotion rules in the spec def _promote_scalar(self, scalar): """ Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompatible with the dtype of self. """ # Note: Only Python scalar types that match the array dtype are # allowed. if isinstance(scalar, bool): if self.dtype not in _boolean_dtypes: raise TypeError( "Python bool scalars can only be promoted with bool arrays" ) elif isinstance(scalar, int): if self.dtype in _boolean_dtypes: raise TypeError( "Python int scalars cannot be promoted with bool arrays" ) elif isinstance(scalar, float): if self.dtype not in _floating_dtypes: raise TypeError( "Python float scalars can only be promoted with floating-point arrays." ) else: raise TypeError("'scalar' must be a Python scalar") # Note: scalars are unconditionally cast to the same dtype as the # array. # Note: the spec only specifies integer-dtype/int promotion # behavior for integers within the bounds of the integer dtype. # Outside of those bounds we use the default NumPy behavior (either # cast or raise OverflowError). return Array._new(np.array(scalar, self.dtype)) @staticmethod def _normalize_two_args(x1, x2) -> Tuple[Array, Array]: """ Normalize inputs to two arg functions to fix type promotion rules NumPy deviates from the spec type promotion rules in cases where one argument is 0-dimensional and the other is not. For example: >>> import numpy as np >>> a = np.array([1.0], dtype=np.float32) >>> b = np.array(1.0, dtype=np.float64) >>> np.add(a, b) # The spec says this should be float64 array([2.], dtype=float32) To fix this, we add a dimension to the 0-dimension array before passing it through. This works because a dimension would be added anyway from broadcasting, so the resulting shape is the same, but this prevents NumPy from not promoting the dtype. """ # Another option would be to use signature=(x1.dtype, x2.dtype, None), # but that only works for ufuncs, so we would have to call the ufuncs # directly in the operator methods. One should also note that this # sort of trick wouldn't work for functions like searchsorted, which # don't do normal broadcasting, but there aren't any functions like # that in the array API namespace. if x1.ndim == 0 and x2.ndim != 0: # The _array[None] workaround was chosen because it is relatively # performant. broadcast_to(x1._array, x2.shape) is much slower. We # could also manually type promote x2, but that is more complicated # and about the same performance as this. x1 = Array._new(x1._array[None]) elif x2.ndim == 0 and x1.ndim != 0: x2 = Array._new(x2._array[None]) return (x1, x2) # Note: A large fraction of allowed indices are disallowed here (see the # docstring below) def _validate_index(self, key): """ Validate an index according to the array API. The array API specification only requires a subset of indices that are supported by NumPy. This function will reject any index that is allowed by NumPy but not required by the array API specification. We always raise ``IndexError`` on such indices (the spec does not require any specific behavior on them, but this makes the NumPy array API namespace a minimal implementation of the spec). See https://data-apis.org/array-api/latest/API_specification/indexing.html for the full list of required indexing behavior This function raises IndexError if the index ``key`` is invalid. It only raises ``IndexError`` on indices that are not already rejected by NumPy, as NumPy will already raise the appropriate error on such indices. ``shape`` may be None, in which case, only cases that are independent of the array shape are checked. The following cases are allowed by NumPy, but not specified by the array API specification: - Indices to not include an implicit ellipsis at the end. That is, every axis of an array must be explicitly indexed or an ellipsis included. This behaviour is sometimes referred to as flat indexing. - The start and stop of a slice may not be out of bounds. In particular, for a slice ``i:j:k`` on an axis of size ``n``, only the following are allowed: - ``i`` or ``j`` omitted (``None``). - ``-n <= i <= max(0, n - 1)``. - For ``k > 0`` or ``k`` omitted (``None``), ``-n <= j <= n``. - For ``k < 0``, ``-n - 1 <= j <= max(0, n - 1)``. - Boolean array indices are not allowed as part of a larger tuple index. - Integer array indices are not allowed (with the exception of 0-D arrays, which are treated the same as scalars). Additionally, it should be noted that indices that would return a scalar in NumPy will return a 0-D array. Array scalars are not allowed in the specification, only 0-D arrays. This is done in the ``Array._new`` constructor, not this function. """ _key = key if isinstance(key, tuple) else (key,) for i in _key: if isinstance(i, bool) or not ( isinstance(i, SupportsIndex) # i.e. ints or isinstance(i, slice) or i == Ellipsis or i is None or isinstance(i, Array) or isinstance(i, np.ndarray) ): raise IndexError( f"Single-axes index {i} has {type(i)=}, but only " "integers, slices (:), ellipsis (...), newaxis (None), " "zero-dimensional integer arrays and boolean arrays " "are specified in the Array API." ) nonexpanding_key = [] single_axes = [] n_ellipsis = 0 key_has_mask = False for i in _key: if i is not None: nonexpanding_key.append(i) if isinstance(i, Array) or isinstance(i, np.ndarray): if i.dtype in _boolean_dtypes: key_has_mask = True single_axes.append(i) else: # i must not be an array here, to avoid elementwise equals if i == Ellipsis: n_ellipsis += 1 else: single_axes.append(i) n_single_axes = len(single_axes) if n_ellipsis > 1: return # handled by ndarray elif n_ellipsis == 0: # Note boolean masks must be the sole index, which we check for # later on. if not key_has_mask and n_single_axes < self.ndim: raise IndexError( f"{self.ndim=}, but the multi-axes index only specifies " f"{n_single_axes} dimensions. If this was intentional, " "add a trailing ellipsis (...) which expands into as many " "slices (:) as necessary - this is what np.ndarray arrays " "implicitly do, but such flat indexing behaviour is not " "specified in the Array API." ) if n_ellipsis == 0: indexed_shape = self.shape else: ellipsis_start = None for pos, i in enumerate(nonexpanding_key): if not (isinstance(i, Array) or isinstance(i, np.ndarray)): if i == Ellipsis: ellipsis_start = pos break assert ellipsis_start is not None # sanity check ellipsis_end = self.ndim - (n_single_axes - ellipsis_start) indexed_shape = ( self.shape[:ellipsis_start] + self.shape[ellipsis_end:] ) for i, side in zip(single_axes, indexed_shape): if isinstance(i, slice): if side == 0: f_range = "0 (or None)" else: f_range = f"between -{side} and {side - 1} (or None)" if i.start is not None: try: start = operator.index(i.start) except TypeError: pass # handled by ndarray else: if not (-side <= start <= side): raise IndexError( f"Slice {i} contains {start=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds starts are not specified in " "the Array API)" ) if i.stop is not None: try: stop = operator.index(i.stop) except TypeError: pass # handled by ndarray else: if not (-side <= stop <= side): raise IndexError( f"Slice {i} contains {stop=}, but should be " f"{f_range} for an axis of size {side} " "(out-of-bounds stops are not specified in " "the Array API)" ) elif isinstance(i, Array): if i.dtype in _boolean_dtypes and len(_key) != 1: assert isinstance(key, tuple) # sanity check raise IndexError( f"Single-axes index {i} is a boolean array and " f"{len(key)=}, but masking is only specified in the " "Array API when the array is the sole index." ) elif i.dtype in _integer_dtypes and i.ndim != 0: raise IndexError( f"Single-axes index {i} is a non-zero-dimensional " "integer array, but advanced integer indexing is not " "specified in the Array API." ) elif isinstance(i, tuple): raise IndexError( f"Single-axes index {i} is a tuple, but nested tuple " "indices are not specified in the Array API." ) # Everything below this line is required by the spec. def __abs__(self: Array, /) -> Array: """ Performs the operation __abs__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __abs__") res = self._array.__abs__() return self.__class__._new(res) def __add__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __add__. """ other = self._check_allowed_dtypes(other, "numeric", "__add__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__add__(other._array) return self.__class__._new(res) def __and__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __and__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__and__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__and__(other._array) return self.__class__._new(res) def __array_namespace__( self: Array, /, *, api_version: Optional[str] = None ) -> types.ModuleType: if api_version is not None and not api_version.startswith("2021."): raise ValueError(f"Unrecognized array API version: {api_version!r}") return array_api def __bool__(self: Array, /) -> bool: """ Performs the operation __bool__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("bool is only allowed on arrays with 0 dimensions") if self.dtype not in _boolean_dtypes: raise ValueError("bool is only allowed on boolean arrays") res = self._array.__bool__() return res def __dlpack__(self: Array, /, *, stream: None = None) -> PyCapsule: """ Performs the operation __dlpack__. """ return self._array.__dlpack__(stream=stream) def __dlpack_device__(self: Array, /) -> Tuple[IntEnum, int]: """ Performs the operation __dlpack_device__. """ # Note: device support is required for this return self._array.__dlpack_device__() def __eq__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __eq__. """ # Even though "all" dtypes are allowed, we still require them to be # promotable with each other. other = self._check_allowed_dtypes(other, "all", "__eq__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__eq__(other._array) return self.__class__._new(res) def __float__(self: Array, /) -> float: """ Performs the operation __float__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("float is only allowed on arrays with 0 dimensions") if self.dtype not in _floating_dtypes: raise ValueError("float is only allowed on floating-point arrays") res = self._array.__float__() return res def __floordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __floordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__floordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__floordiv__(other._array) return self.__class__._new(res) def __ge__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ge__. """ other = self._check_allowed_dtypes(other, "numeric", "__ge__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ge__(other._array) return self.__class__._new(res) def __getitem__( self: Array, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], /, ) -> Array: """ Performs the operation __getitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array res = self._array.__getitem__(key) return self._new(res) def __gt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __gt__. """ other = self._check_allowed_dtypes(other, "numeric", "__gt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__gt__(other._array) return self.__class__._new(res) def __int__(self: Array, /) -> int: """ Performs the operation __int__. """ # Note: This is an error here. if self._array.ndim != 0: raise TypeError("int is only allowed on arrays with 0 dimensions") if self.dtype not in _integer_dtypes: raise ValueError("int is only allowed on integer arrays") res = self._array.__int__() return res def __index__(self: Array, /) -> int: """ Performs the operation __index__. """ res = self._array.__index__() return res def __invert__(self: Array, /) -> Array: """ Performs the operation __invert__. """ if self.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in __invert__") res = self._array.__invert__() return self.__class__._new(res) def __le__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __le__. """ other = self._check_allowed_dtypes(other, "numeric", "__le__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__le__(other._array) return self.__class__._new(res) def __lshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __lshift__. """ other = self._check_allowed_dtypes(other, "integer", "__lshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lshift__(other._array) return self.__class__._new(res) def __lt__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __lt__. """ other = self._check_allowed_dtypes(other, "numeric", "__lt__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__lt__(other._array) return self.__class__._new(res) def __matmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __matmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__matmul__") if other is NotImplemented: return other res = self._array.__matmul__(other._array) return self.__class__._new(res) def __mod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mod__. """ other = self._check_allowed_dtypes(other, "numeric", "__mod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mod__(other._array) return self.__class__._new(res) def __mul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __mul__. """ other = self._check_allowed_dtypes(other, "numeric", "__mul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__mul__(other._array) return self.__class__._new(res) def __ne__(self: Array, other: Union[int, float, bool, Array], /) -> Array: """ Performs the operation __ne__. """ other = self._check_allowed_dtypes(other, "all", "__ne__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ne__(other._array) return self.__class__._new(res) def __neg__(self: Array, /) -> Array: """ Performs the operation __neg__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __neg__") res = self._array.__neg__() return self.__class__._new(res) def __or__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __or__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__or__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__or__(other._array) return self.__class__._new(res) def __pos__(self: Array, /) -> Array: """ Performs the operation __pos__. """ if self.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in __pos__") res = self._array.__pos__() return self.__class__._new(res) def __pow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __pow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__pow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow type promotion rules for 0-d # arrays, so we use pow() here instead. return pow(self, other) def __rshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rshift__(other._array) return self.__class__._new(res) def __setitem__( self, key: Union[ int, slice, ellipsis, Tuple[Union[int, slice, ellipsis], ...], Array ], value: Union[int, float, bool, Array], /, ) -> None: """ Performs the operation __setitem__. """ # Note: Only indices required by the spec are allowed. See the # docstring of _validate_index self._validate_index(key) if isinstance(key, Array): # Indexing self._array with array_api arrays can be erroneous key = key._array self._array.__setitem__(key, asarray(value)._array) def __sub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __sub__. """ other = self._check_allowed_dtypes(other, "numeric", "__sub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__sub__(other._array) return self.__class__._new(res) # PEP 484 requires int to be a subtype of float, but __truediv__ should # not accept int. def __truediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __truediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__truediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__truediv__(other._array) return self.__class__._new(res) def __xor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __xor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__xor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__xor__(other._array) return self.__class__._new(res) def __iadd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __iadd__. """ other = self._check_allowed_dtypes(other, "numeric", "__iadd__") if other is NotImplemented: return other self._array.__iadd__(other._array) return self def __radd__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __radd__. """ other = self._check_allowed_dtypes(other, "numeric", "__radd__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__radd__(other._array) return self.__class__._new(res) def __iand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __iand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__iand__") if other is NotImplemented: return other self._array.__iand__(other._array) return self def __rand__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rand__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rand__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rand__(other._array) return self.__class__._new(res) def __ifloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ifloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__ifloordiv__") if other is NotImplemented: return other self._array.__ifloordiv__(other._array) return self def __rfloordiv__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rfloordiv__. """ other = self._check_allowed_dtypes(other, "numeric", "__rfloordiv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rfloordiv__(other._array) return self.__class__._new(res) def __ilshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __ilshift__. """ other = self._check_allowed_dtypes(other, "integer", "__ilshift__") if other is NotImplemented: return other self._array.__ilshift__(other._array) return self def __rlshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rlshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rlshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rlshift__(other._array) return self.__class__._new(res) def __imatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __imatmul__. """ # Note: NumPy does not implement __imatmul__. # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__imatmul__") if other is NotImplemented: return other # __imatmul__ can only be allowed when it would not change the shape # of self. other_shape = other.shape if self.shape == () or other_shape == (): raise ValueError("@= requires at least one dimension") if len(other_shape) == 1 or other_shape[-1] != other_shape[-2]: raise ValueError("@= cannot change the shape of the input array") self._array[:] = self._array.__matmul__(other._array) return self def __rmatmul__(self: Array, other: Array, /) -> Array: """ Performs the operation __rmatmul__. """ # matmul is not defined for scalars, but without this, we may get # the wrong error message from asarray. other = self._check_allowed_dtypes(other, "numeric", "__rmatmul__") if other is NotImplemented: return other res = self._array.__rmatmul__(other._array) return self.__class__._new(res) def __imod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imod__. """ other = self._check_allowed_dtypes(other, "numeric", "__imod__") if other is NotImplemented: return other self._array.__imod__(other._array) return self def __rmod__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmod__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmod__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmod__(other._array) return self.__class__._new(res) def __imul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __imul__. """ other = self._check_allowed_dtypes(other, "numeric", "__imul__") if other is NotImplemented: return other self._array.__imul__(other._array) return self def __rmul__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rmul__. """ other = self._check_allowed_dtypes(other, "numeric", "__rmul__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rmul__(other._array) return self.__class__._new(res) def __ior__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ior__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ior__") if other is NotImplemented: return other self._array.__ior__(other._array) return self def __ror__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ror__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ror__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__ror__(other._array) return self.__class__._new(res) def __ipow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __ipow__. """ other = self._check_allowed_dtypes(other, "numeric", "__ipow__") if other is NotImplemented: return other self._array.__ipow__(other._array) return self def __rpow__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rpow__. """ from ._elementwise_functions import pow other = self._check_allowed_dtypes(other, "numeric", "__rpow__") if other is NotImplemented: return other # Note: NumPy's __pow__ does not follow the spec type promotion rules # for 0-d arrays, so we use pow() here instead. return pow(other, self) def __irshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __irshift__. """ other = self._check_allowed_dtypes(other, "integer", "__irshift__") if other is NotImplemented: return other self._array.__irshift__(other._array) return self def __rrshift__(self: Array, other: Union[int, Array], /) -> Array: """ Performs the operation __rrshift__. """ other = self._check_allowed_dtypes(other, "integer", "__rrshift__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rrshift__(other._array) return self.__class__._new(res) def __isub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __isub__. """ other = self._check_allowed_dtypes(other, "numeric", "__isub__") if other is NotImplemented: return other self._array.__isub__(other._array) return self def __rsub__(self: Array, other: Union[int, float, Array], /) -> Array: """ Performs the operation __rsub__. """ other = self._check_allowed_dtypes(other, "numeric", "__rsub__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rsub__(other._array) return self.__class__._new(res) def __itruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __itruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__itruediv__") if other is NotImplemented: return other self._array.__itruediv__(other._array) return self def __rtruediv__(self: Array, other: Union[float, Array], /) -> Array: """ Performs the operation __rtruediv__. """ other = self._check_allowed_dtypes(other, "floating-point", "__rtruediv__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rtruediv__(other._array) return self.__class__._new(res) def __ixor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __ixor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__ixor__") if other is NotImplemented: return other self._array.__ixor__(other._array) return self def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array: """ Performs the operation __rxor__. """ other = self._check_allowed_dtypes(other, "integer or boolean", "__rxor__") if other is NotImplemented: return other self, other = self._normalize_two_args(self, other) res = self._array.__rxor__(other._array) return self.__class__._new(res) def to_device(self: Array, device: Device, /, stream: None = None) -> Array: if stream is not None: raise ValueError("The stream argument to to_device() is not supported") if device == 'cpu': return self raise ValueError(f"Unsupported device {device!r}") @property def dtype(self) -> Dtype: """ Array API compatible wrapper for :py:meth:`np.ndarray.dtype <numpy.ndarray.dtype>`. See its docstring for more information. """ return self._array.dtype @property def device(self) -> Device: return "cpu" # Note: mT is new in array API spec (see matrix_transpose) @property def mT(self) -> Array: from .linalg import matrix_transpose return matrix_transpose(self) @property def ndim(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.ndim <numpy.ndarray.ndim>`. See its docstring for more information. """ return self._array.ndim @property def shape(self) -> Tuple[int, ...]: """ Array API compatible wrapper for :py:meth:`np.ndarray.shape <numpy.ndarray.shape>`. See its docstring for more information. """ return self._array.shape @property def size(self) -> int: """ Array API compatible wrapper for :py:meth:`np.ndarray.size <numpy.ndarray.size>`. See its docstring for more information. """ return self._array.size @property def T(self) -> Array: """ Array API compatible wrapper for :py:meth:`np.ndarray.T <numpy.ndarray.T>`. See its docstring for more information. """ # Note: T only works on 2-dimensional arrays. See the corresponding # note in the specification: # https://data-apis.org/array-api/latest/API_specification/array_object.html#t if self.ndim != 2: raise ValueError("x.T requires x to have 2 dimensions. Use x.mT to transpose stacks of matrices and permute_dims() to permute dimensions.") return self.__class__._new(self._array.T)
43,226
Python
37.630027
151
0.556262
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/linalg.py
from __future__ import annotations from ._dtypes import _floating_dtypes, _numeric_dtypes from ._array_object import Array from typing import TYPE_CHECKING if TYPE_CHECKING: from ._typing import Literal, Optional, Sequence, Tuple, Union from typing import NamedTuple import numpy.linalg import numpy as np class EighResult(NamedTuple): eigenvalues: Array eigenvectors: Array class QRResult(NamedTuple): Q: Array R: Array class SlogdetResult(NamedTuple): sign: Array logabsdet: Array class SVDResult(NamedTuple): U: Array S: Array Vh: Array # Note: the inclusion of the upper keyword is different from # np.linalg.cholesky, which does not have it. def cholesky(x: Array, /, *, upper: bool = False) -> Array: """ Array API compatible wrapper for :py:func:`np.linalg.cholesky <numpy.linalg.cholesky>`. See its docstring for more information. """ # Note: the restriction to floating-point dtypes only is different from # np.linalg.cholesky. if x.dtype not in _floating_dtypes: raise TypeError('Only floating-point dtypes are allowed in cholesky') L = np.linalg.cholesky(x._array) if upper: return Array._new(L).mT return Array._new(L) # Note: cross is the numpy top-level namespace, not np.linalg def cross(x1: Array, x2: Array, /, *, axis: int = -1) -> Array: """ Array API compatible wrapper for :py:func:`np.cross <numpy.cross>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError('Only numeric dtypes are allowed in cross') # Note: this is different from np.cross(), which broadcasts if x1.shape != x2.shape: raise ValueError('x1 and x2 must have the same shape') if x1.ndim == 0: raise ValueError('cross() requires arrays of dimension at least 1') # Note: this is different from np.cross(), which allows dimension 2 if x1.shape[axis] != 3: raise ValueError('cross() dimension must equal 3') return Array._new(np.cross(x1._array, x2._array, axis=axis)) def det(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.linalg.det <numpy.linalg.det>`. See its docstring for more information. """ # Note: the restriction to floating-point dtypes only is different from # np.linalg.det. if x.dtype not in _floating_dtypes: raise TypeError('Only floating-point dtypes are allowed in det') return Array._new(np.linalg.det(x._array)) # Note: diagonal is the numpy top-level namespace, not np.linalg def diagonal(x: Array, /, *, offset: int = 0) -> Array: """ Array API compatible wrapper for :py:func:`np.diagonal <numpy.diagonal>`. See its docstring for more information. """ # Note: diagonal always operates on the last two axes, whereas np.diagonal # operates on the first two axes by default return Array._new(np.diagonal(x._array, offset=offset, axis1=-2, axis2=-1)) def eigh(x: Array, /) -> EighResult: """ Array API compatible wrapper for :py:func:`np.linalg.eigh <numpy.linalg.eigh>`. See its docstring for more information. """ # Note: the restriction to floating-point dtypes only is different from # np.linalg.eigh. if x.dtype not in _floating_dtypes: raise TypeError('Only floating-point dtypes are allowed in eigh') # Note: the return type here is a namedtuple, which is different from # np.eigh, which only returns a tuple. return EighResult(*map(Array._new, np.linalg.eigh(x._array))) def eigvalsh(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.linalg.eigvalsh <numpy.linalg.eigvalsh>`. See its docstring for more information. """ # Note: the restriction to floating-point dtypes only is different from # np.linalg.eigvalsh. if x.dtype not in _floating_dtypes: raise TypeError('Only floating-point dtypes are allowed in eigvalsh') return Array._new(np.linalg.eigvalsh(x._array)) def inv(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.linalg.inv <numpy.linalg.inv>`. See its docstring for more information. """ # Note: the restriction to floating-point dtypes only is different from # np.linalg.inv. if x.dtype not in _floating_dtypes: raise TypeError('Only floating-point dtypes are allowed in inv') return Array._new(np.linalg.inv(x._array)) # Note: matmul is the numpy top-level namespace but not in np.linalg def matmul(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.matmul <numpy.matmul>`. See its docstring for more information. """ # Note: the restriction to numeric dtypes only is different from # np.matmul. if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError('Only numeric dtypes are allowed in matmul') return Array._new(np.matmul(x1._array, x2._array)) # Note: the name here is different from norm(). The array API norm is split # into matrix_norm and vector_norm(). # The type for ord should be Optional[Union[int, float, Literal[np.inf, # -np.inf, 'fro', 'nuc']]], but Literal does not support floating-point # literals. def matrix_norm(x: Array, /, *, keepdims: bool = False, ord: Optional[Union[int, float, Literal['fro', 'nuc']]] = 'fro') -> Array: """ Array API compatible wrapper for :py:func:`np.linalg.norm <numpy.linalg.norm>`. See its docstring for more information. """ # Note: the restriction to floating-point dtypes only is different from # np.linalg.norm. if x.dtype not in _floating_dtypes: raise TypeError('Only floating-point dtypes are allowed in matrix_norm') return Array._new(np.linalg.norm(x._array, axis=(-2, -1), keepdims=keepdims, ord=ord)) def matrix_power(x: Array, n: int, /) -> Array: """ Array API compatible wrapper for :py:func:`np.matrix_power <numpy.matrix_power>`. See its docstring for more information. """ # Note: the restriction to floating-point dtypes only is different from # np.linalg.matrix_power. if x.dtype not in _floating_dtypes: raise TypeError('Only floating-point dtypes are allowed for the first argument of matrix_power') # np.matrix_power already checks if n is an integer return Array._new(np.linalg.matrix_power(x._array, n)) # Note: the keyword argument name rtol is different from np.linalg.matrix_rank def matrix_rank(x: Array, /, *, rtol: Optional[Union[float, Array]] = None) -> Array: """ Array API compatible wrapper for :py:func:`np.matrix_rank <numpy.matrix_rank>`. See its docstring for more information. """ # Note: this is different from np.linalg.matrix_rank, which supports 1 # dimensional arrays. if x.ndim < 2: raise np.linalg.LinAlgError("1-dimensional array given. Array must be at least two-dimensional") S = np.linalg.svd(x._array, compute_uv=False) if rtol is None: tol = S.max(axis=-1, keepdims=True) * max(x.shape[-2:]) * np.finfo(S.dtype).eps else: if isinstance(rtol, Array): rtol = rtol._array # Note: this is different from np.linalg.matrix_rank, which does not multiply # the tolerance by the largest singular value. tol = S.max(axis=-1, keepdims=True)*np.asarray(rtol)[..., np.newaxis] return Array._new(np.count_nonzero(S > tol, axis=-1)) # Note: this function is new in the array API spec. Unlike transpose, it only # transposes the last two axes. def matrix_transpose(x: Array, /) -> Array: if x.ndim < 2: raise ValueError("x must be at least 2-dimensional for matrix_transpose") return Array._new(np.swapaxes(x._array, -1, -2)) # Note: outer is the numpy top-level namespace, not np.linalg def outer(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.outer <numpy.outer>`. See its docstring for more information. """ # Note: the restriction to numeric dtypes only is different from # np.outer. if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError('Only numeric dtypes are allowed in outer') # Note: the restriction to only 1-dim arrays is different from np.outer if x1.ndim != 1 or x2.ndim != 1: raise ValueError('The input arrays to outer must be 1-dimensional') return Array._new(np.outer(x1._array, x2._array)) # Note: the keyword argument name rtol is different from np.linalg.pinv def pinv(x: Array, /, *, rtol: Optional[Union[float, Array]] = None) -> Array: """ Array API compatible wrapper for :py:func:`np.linalg.pinv <numpy.linalg.pinv>`. See its docstring for more information. """ # Note: the restriction to floating-point dtypes only is different from # np.linalg.pinv. if x.dtype not in _floating_dtypes: raise TypeError('Only floating-point dtypes are allowed in pinv') # Note: this is different from np.linalg.pinv, which does not multiply the # default tolerance by max(M, N). if rtol is None: rtol = max(x.shape[-2:]) * np.finfo(x.dtype).eps return Array._new(np.linalg.pinv(x._array, rcond=rtol)) def qr(x: Array, /, *, mode: Literal['reduced', 'complete'] = 'reduced') -> QRResult: """ Array API compatible wrapper for :py:func:`np.linalg.qr <numpy.linalg.qr>`. See its docstring for more information. """ # Note: the restriction to floating-point dtypes only is different from # np.linalg.qr. if x.dtype not in _floating_dtypes: raise TypeError('Only floating-point dtypes are allowed in qr') # Note: the return type here is a namedtuple, which is different from # np.linalg.qr, which only returns a tuple. return QRResult(*map(Array._new, np.linalg.qr(x._array, mode=mode))) def slogdet(x: Array, /) -> SlogdetResult: """ Array API compatible wrapper for :py:func:`np.linalg.slogdet <numpy.linalg.slogdet>`. See its docstring for more information. """ # Note: the restriction to floating-point dtypes only is different from # np.linalg.slogdet. if x.dtype not in _floating_dtypes: raise TypeError('Only floating-point dtypes are allowed in slogdet') # Note: the return type here is a namedtuple, which is different from # np.linalg.slogdet, which only returns a tuple. return SlogdetResult(*map(Array._new, np.linalg.slogdet(x._array))) # Note: unlike np.linalg.solve, the array API solve() only accepts x2 as a # vector when it is exactly 1-dimensional. All other cases treat x2 as a stack # of matrices. The np.linalg.solve behavior of allowing stacks of both # matrices and vectors is ambiguous c.f. # https://github.com/numpy/numpy/issues/15349 and # https://github.com/data-apis/array-api/issues/285. # To workaround this, the below is the code from np.linalg.solve except # only calling solve1 in the exactly 1D case. def _solve(a, b): from ..linalg.linalg import (_makearray, _assert_stacked_2d, _assert_stacked_square, _commonType, isComplexType, get_linalg_error_extobj, _raise_linalgerror_singular) from ..linalg import _umath_linalg a, _ = _makearray(a) _assert_stacked_2d(a) _assert_stacked_square(a) b, wrap = _makearray(b) t, result_t = _commonType(a, b) # This part is different from np.linalg.solve if b.ndim == 1: gufunc = _umath_linalg.solve1 else: gufunc = _umath_linalg.solve # This does nothing currently but is left in because it will be relevant # when complex dtype support is added to the spec in 2022. signature = 'DD->D' if isComplexType(t) else 'dd->d' extobj = get_linalg_error_extobj(_raise_linalgerror_singular) r = gufunc(a, b, signature=signature, extobj=extobj) return wrap(r.astype(result_t, copy=False)) def solve(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.linalg.solve <numpy.linalg.solve>`. See its docstring for more information. """ # Note: the restriction to floating-point dtypes only is different from # np.linalg.solve. if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes: raise TypeError('Only floating-point dtypes are allowed in solve') return Array._new(_solve(x1._array, x2._array)) def svd(x: Array, /, *, full_matrices: bool = True) -> SVDResult: """ Array API compatible wrapper for :py:func:`np.linalg.svd <numpy.linalg.svd>`. See its docstring for more information. """ # Note: the restriction to floating-point dtypes only is different from # np.linalg.svd. if x.dtype not in _floating_dtypes: raise TypeError('Only floating-point dtypes are allowed in svd') # Note: the return type here is a namedtuple, which is different from # np.svd, which only returns a tuple. return SVDResult(*map(Array._new, np.linalg.svd(x._array, full_matrices=full_matrices))) # Note: svdvals is not in NumPy (but it is in SciPy). It is equivalent to # np.linalg.svd(compute_uv=False). def svdvals(x: Array, /) -> Union[Array, Tuple[Array, ...]]: if x.dtype not in _floating_dtypes: raise TypeError('Only floating-point dtypes are allowed in svdvals') return Array._new(np.linalg.svd(x._array, compute_uv=False)) # Note: tensordot is the numpy top-level namespace but not in np.linalg # Note: axes must be a tuple, unlike np.tensordot where it can be an array or array-like. def tensordot(x1: Array, x2: Array, /, *, axes: Union[int, Tuple[Sequence[int], Sequence[int]]] = 2) -> Array: # Note: the restriction to numeric dtypes only is different from # np.tensordot. if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError('Only numeric dtypes are allowed in tensordot') return Array._new(np.tensordot(x1._array, x2._array, axes=axes)) # Note: trace is the numpy top-level namespace, not np.linalg def trace(x: Array, /, *, offset: int = 0) -> Array: """ Array API compatible wrapper for :py:func:`np.trace <numpy.trace>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError('Only numeric dtypes are allowed in trace') # Note: trace always operates on the last two axes, whereas np.trace # operates on the first two axes by default return Array._new(np.asarray(np.trace(x._array, offset=offset, axis1=-2, axis2=-1))) # Note: vecdot is not in NumPy def vecdot(x1: Array, x2: Array, /, *, axis: int = -1) -> Array: if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError('Only numeric dtypes are allowed in vecdot') ndim = max(x1.ndim, x2.ndim) x1_shape = (1,)*(ndim - x1.ndim) + tuple(x1.shape) x2_shape = (1,)*(ndim - x2.ndim) + tuple(x2.shape) if x1_shape[axis] != x2_shape[axis]: raise ValueError("x1 and x2 must have the same size along the given axis") x1_, x2_ = np.broadcast_arrays(x1._array, x2._array) x1_ = np.moveaxis(x1_, axis, -1) x2_ = np.moveaxis(x2_, axis, -1) res = x1_[..., None, :] @ x2_[..., None] return Array._new(res[..., 0, 0]) # Note: the name here is different from norm(). The array API norm is split # into matrix_norm and vector_norm(). # The type for ord should be Optional[Union[int, float, Literal[np.inf, # -np.inf]]] but Literal does not support floating-point literals. def vector_norm(x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ord: Optional[Union[int, float]] = 2) -> Array: """ Array API compatible wrapper for :py:func:`np.linalg.norm <numpy.linalg.norm>`. See its docstring for more information. """ # Note: the restriction to floating-point dtypes only is different from # np.linalg.norm. if x.dtype not in _floating_dtypes: raise TypeError('Only floating-point dtypes are allowed in norm') a = x._array if axis is None: a = a.flatten() axis = 0 elif isinstance(axis, tuple): # Note: The axis argument supports any number of axes, whereas norm() # only supports a single axis for vector norm. rest = tuple(i for i in range(a.ndim) if i not in axis) newshape = axis + rest a = np.transpose(a, newshape).reshape((np.prod([a.shape[i] for i in axis]), *[a.shape[i] for i in rest])) axis = 0 return Array._new(np.linalg.norm(a, axis=axis, keepdims=keepdims, ord=ord)) __all__ = ['cholesky', 'cross', 'det', 'diagonal', 'eigh', 'eigvalsh', 'inv', 'matmul', 'matrix_norm', 'matrix_power', 'matrix_rank', 'matrix_transpose', 'outer', 'pinv', 'qr', 'slogdet', 'solve', 'svd', 'svdvals', 'tensordot', 'trace', 'vecdot', 'vector_norm']
16,964
Python
39.011792
261
0.669359
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/__init__.py
""" A NumPy sub-namespace that conforms to the Python array API standard. This submodule accompanies NEP 47, which proposes its inclusion in NumPy. It is still considered experimental, and will issue a warning when imported. This is a proof-of-concept namespace that wraps the corresponding NumPy functions to give a conforming implementation of the Python array API standard (https://data-apis.github.io/array-api/latest/). The standard is currently in an RFC phase and comments on it are both welcome and encouraged. Comments should be made either at https://github.com/data-apis/array-api or at https://github.com/data-apis/consortium-feedback/discussions. NumPy already follows the proposed spec for the most part, so this module serves mostly as a thin wrapper around it. However, NumPy also implements a lot of behavior that is not included in the spec, so this serves as a restricted subset of the API. Only those functions that are part of the spec are included in this namespace, and all functions are given with the exact signature given in the spec, including the use of position-only arguments, and omitting any extra keyword arguments implemented by NumPy but not part of the spec. The behavior of some functions is also modified from the NumPy behavior to conform to the standard. Note that the underlying array object itself is wrapped in a wrapper Array() class, but is otherwise unchanged. This submodule is implemented in pure Python with no C extensions. The array API spec is designed as a "minimal API subset" and explicitly allows libraries to include behaviors not specified by it. But users of this module that intend to write portable code should be aware that only those behaviors that are listed in the spec are guaranteed to be implemented across libraries. Consequently, the NumPy implementation was chosen to be both conforming and minimal, so that users can use this implementation of the array API namespace and be sure that behaviors that it defines will be available in conforming namespaces from other libraries. A few notes about the current state of this submodule: - There is a test suite that tests modules against the array API standard at https://github.com/data-apis/array-api-tests. The test suite is still a work in progress, but the existing tests pass on this module, with a few exceptions: - DLPack support (see https://github.com/data-apis/array-api/pull/106) is not included here, as it requires a full implementation in NumPy proper first. The test suite is not yet complete, and even the tests that exist are not guaranteed to give a comprehensive coverage of the spec. Therefore, when reviewing and using this submodule, you should refer to the standard documents themselves. There are some tests in numpy.array_api.tests, but they primarily focus on things that are not tested by the official array API test suite. - There is a custom array object, numpy.array_api.Array, which is returned by all functions in this module. All functions in the array API namespace implicitly assume that they will only receive this object as input. The only way to create instances of this object is to use one of the array creation functions. It does not have a public constructor on the object itself. The object is a small wrapper class around numpy.ndarray. The main purpose of it is to restrict the namespace of the array object to only those dtypes and only those methods that are required by the spec, as well as to limit/change certain behavior that differs in the spec. In particular: - The array API namespace does not have scalar objects, only 0-D arrays. Operations on Array that would create a scalar in NumPy create a 0-D array. - Indexing: Only a subset of indices supported by NumPy are required by the spec. The Array object restricts indexing to only allow those types of indices that are required by the spec. See the docstring of the numpy.array_api.Array._validate_indices helper function for more information. - Type promotion: Some type promotion rules are different in the spec. In particular, the spec does not have any value-based casting. The spec also does not require cross-kind casting, like integer -> floating-point. Only those promotions that are explicitly required by the array API specification are allowed in this module. See NEP 47 for more info. - Functions do not automatically call asarray() on their input, and will not work if the input type is not Array. The exception is array creation functions, and Python operators on the Array object, which accept Python scalars of the same type as the array dtype. - All functions include type annotations, corresponding to those given in the spec (see _typing.py for definitions of some custom types). These do not currently fully pass mypy due to some limitations in mypy. - Dtype objects are just the NumPy dtype objects, e.g., float64 = np.dtype('float64'). The spec does not require any behavior on these dtype objects other than that they be accessible by name and be comparable by equality, but it was considered too much extra complexity to create custom objects to represent dtypes. - All places where the implementations in this submodule are known to deviate from their corresponding functions in NumPy are marked with "# Note:" comments. Still TODO in this module are: - DLPack support for numpy.ndarray is still in progress. See https://github.com/numpy/numpy/pull/19083. - The copy=False keyword argument to asarray() is not yet implemented. This requires support in numpy.asarray() first. - Some functions are not yet fully tested in the array API test suite, and may require updates that are not yet known until the tests are written. - The spec is still in an RFC phase and may still have minor updates, which will need to be reflected here. - Complex number support in array API spec is planned but not yet finalized, as are the fft extension and certain linear algebra functions such as eig that require complex dtypes. """ import warnings warnings.warn( "The numpy.array_api submodule is still experimental. See NEP 47.", stacklevel=2 ) __array_api_version__ = "2021.12" __all__ = ["__array_api_version__"] from ._constants import e, inf, nan, pi __all__ += ["e", "inf", "nan", "pi"] from ._creation_functions import ( asarray, arange, empty, empty_like, eye, from_dlpack, full, full_like, linspace, meshgrid, ones, ones_like, tril, triu, zeros, zeros_like, ) __all__ += [ "asarray", "arange", "empty", "empty_like", "eye", "from_dlpack", "full", "full_like", "linspace", "meshgrid", "ones", "ones_like", "tril", "triu", "zeros", "zeros_like", ] from ._data_type_functions import ( astype, broadcast_arrays, broadcast_to, can_cast, finfo, iinfo, result_type, ) __all__ += [ "astype", "broadcast_arrays", "broadcast_to", "can_cast", "finfo", "iinfo", "result_type", ] from ._dtypes import ( int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, bool, ) __all__ += [ "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", "float32", "float64", "bool", ] from ._elementwise_functions import ( abs, acos, acosh, add, asin, asinh, atan, atan2, atanh, bitwise_and, bitwise_left_shift, bitwise_invert, bitwise_or, bitwise_right_shift, bitwise_xor, ceil, cos, cosh, divide, equal, exp, expm1, floor, floor_divide, greater, greater_equal, isfinite, isinf, isnan, less, less_equal, log, log1p, log2, log10, logaddexp, logical_and, logical_not, logical_or, logical_xor, multiply, negative, not_equal, positive, pow, remainder, round, sign, sin, sinh, square, sqrt, subtract, tan, tanh, trunc, ) __all__ += [ "abs", "acos", "acosh", "add", "asin", "asinh", "atan", "atan2", "atanh", "bitwise_and", "bitwise_left_shift", "bitwise_invert", "bitwise_or", "bitwise_right_shift", "bitwise_xor", "ceil", "cos", "cosh", "divide", "equal", "exp", "expm1", "floor", "floor_divide", "greater", "greater_equal", "isfinite", "isinf", "isnan", "less", "less_equal", "log", "log1p", "log2", "log10", "logaddexp", "logical_and", "logical_not", "logical_or", "logical_xor", "multiply", "negative", "not_equal", "positive", "pow", "remainder", "round", "sign", "sin", "sinh", "square", "sqrt", "subtract", "tan", "tanh", "trunc", ] # linalg is an extension in the array API spec, which is a sub-namespace. Only # a subset of functions in it are imported into the top-level namespace. from . import linalg __all__ += ["linalg"] from .linalg import matmul, tensordot, matrix_transpose, vecdot __all__ += ["matmul", "tensordot", "matrix_transpose", "vecdot"] from ._manipulation_functions import ( concat, expand_dims, flip, permute_dims, reshape, roll, squeeze, stack, ) __all__ += ["concat", "expand_dims", "flip", "permute_dims", "reshape", "roll", "squeeze", "stack"] from ._searching_functions import argmax, argmin, nonzero, where __all__ += ["argmax", "argmin", "nonzero", "where"] from ._set_functions import unique_all, unique_counts, unique_inverse, unique_values __all__ += ["unique_all", "unique_counts", "unique_inverse", "unique_values"] from ._sorting_functions import argsort, sort __all__ += ["argsort", "sort"] from ._statistical_functions import max, mean, min, prod, std, sum, var __all__ += ["max", "mean", "min", "prod", "std", "sum", "var"] from ._utility_functions import all, any __all__ += ["all", "any"]
10,221
Python
26.042328
99
0.681832
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/_data_type_functions.py
from __future__ import annotations from ._array_object import Array from ._dtypes import _all_dtypes, _result_type from dataclasses import dataclass from typing import TYPE_CHECKING, List, Tuple, Union if TYPE_CHECKING: from ._typing import Dtype from collections.abc import Sequence import numpy as np # Note: astype is a function, not an array method as in NumPy. def astype(x: Array, dtype: Dtype, /, *, copy: bool = True) -> Array: if not copy and dtype == x.dtype: return x return Array._new(x._array.astype(dtype=dtype, copy=copy)) def broadcast_arrays(*arrays: Array) -> List[Array]: """ Array API compatible wrapper for :py:func:`np.broadcast_arrays <numpy.broadcast_arrays>`. See its docstring for more information. """ from ._array_object import Array return [ Array._new(array) for array in np.broadcast_arrays(*[a._array for a in arrays]) ] def broadcast_to(x: Array, /, shape: Tuple[int, ...]) -> Array: """ Array API compatible wrapper for :py:func:`np.broadcast_to <numpy.broadcast_to>`. See its docstring for more information. """ from ._array_object import Array return Array._new(np.broadcast_to(x._array, shape)) def can_cast(from_: Union[Dtype, Array], to: Dtype, /) -> bool: """ Array API compatible wrapper for :py:func:`np.can_cast <numpy.can_cast>`. See its docstring for more information. """ if isinstance(from_, Array): from_ = from_.dtype elif from_ not in _all_dtypes: raise TypeError(f"{from_=}, but should be an array_api array or dtype") if to not in _all_dtypes: raise TypeError(f"{to=}, but should be a dtype") # Note: We avoid np.can_cast() as it has discrepancies with the array API, # since NumPy allows cross-kind casting (e.g., NumPy allows bool -> int8). # See https://github.com/numpy/numpy/issues/20870 try: # We promote `from_` and `to` together. We then check if the promoted # dtype is `to`, which indicates if `from_` can (up)cast to `to`. dtype = _result_type(from_, to) return to == dtype except TypeError: # _result_type() raises if the dtypes don't promote together return False # These are internal objects for the return types of finfo and iinfo, since # the NumPy versions contain extra data that isn't part of the spec. @dataclass class finfo_object: bits: int # Note: The types of the float data here are float, whereas in NumPy they # are scalars of the corresponding float dtype. eps: float max: float min: float smallest_normal: float @dataclass class iinfo_object: bits: int max: int min: int def finfo(type: Union[Dtype, Array], /) -> finfo_object: """ Array API compatible wrapper for :py:func:`np.finfo <numpy.finfo>`. See its docstring for more information. """ fi = np.finfo(type) # Note: The types of the float data here are float, whereas in NumPy they # are scalars of the corresponding float dtype. return finfo_object( fi.bits, float(fi.eps), float(fi.max), float(fi.min), float(fi.smallest_normal), ) def iinfo(type: Union[Dtype, Array], /) -> iinfo_object: """ Array API compatible wrapper for :py:func:`np.iinfo <numpy.iinfo>`. See its docstring for more information. """ ii = np.iinfo(type) return iinfo_object(ii.bits, ii.max, ii.min) def result_type(*arrays_and_dtypes: Union[Array, Dtype]) -> Dtype: """ Array API compatible wrapper for :py:func:`np.result_type <numpy.result_type>`. See its docstring for more information. """ # Note: we use a custom implementation that gives only the type promotions # required by the spec rather than using np.result_type. NumPy implements # too many extra type promotions like int64 + uint64 -> float64, and does # value-based casting on scalar arrays. A = [] for a in arrays_and_dtypes: if isinstance(a, Array): a = a.dtype elif isinstance(a, np.ndarray) or a not in _all_dtypes: raise TypeError("result_type() inputs must be array_api arrays or dtypes") A.append(a) if len(A) == 0: raise ValueError("at least one array or dtype is required") elif len(A) == 1: return A[0] else: t = A[0] for t2 in A[1:]: t = _result_type(t, t2) return t
4,480
Python
29.482993
93
0.641741
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/_searching_functions.py
from __future__ import annotations from ._array_object import Array from ._dtypes import _result_type from typing import Optional, Tuple import numpy as np def argmax(x: Array, /, *, axis: Optional[int] = None, keepdims: bool = False) -> Array: """ Array API compatible wrapper for :py:func:`np.argmax <numpy.argmax>`. See its docstring for more information. """ return Array._new(np.asarray(np.argmax(x._array, axis=axis, keepdims=keepdims))) def argmin(x: Array, /, *, axis: Optional[int] = None, keepdims: bool = False) -> Array: """ Array API compatible wrapper for :py:func:`np.argmin <numpy.argmin>`. See its docstring for more information. """ return Array._new(np.asarray(np.argmin(x._array, axis=axis, keepdims=keepdims))) def nonzero(x: Array, /) -> Tuple[Array, ...]: """ Array API compatible wrapper for :py:func:`np.nonzero <numpy.nonzero>`. See its docstring for more information. """ return tuple(Array._new(i) for i in np.nonzero(x._array)) def where(condition: Array, x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.where <numpy.where>`. See its docstring for more information. """ # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.where(condition._array, x1._array, x2._array))
1,457
Python
29.374999
88
0.664379
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/_constants.py
import numpy as np e = np.e inf = np.inf nan = np.nan pi = np.pi
66
Python
8.571427
18
0.621212
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/_typing.py
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ from __future__ import annotations __all__ = [ "Array", "Device", "Dtype", "SupportsDLPack", "SupportsBufferProtocol", "PyCapsule", ] import sys from typing import ( Any, Literal, Sequence, Type, Union, TYPE_CHECKING, TypeVar, Protocol, ) from ._array_object import Array from numpy import ( dtype, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, ) _T_co = TypeVar("_T_co", covariant=True) class NestedSequence(Protocol[_T_co]): def __getitem__(self, key: int, /) -> _T_co | NestedSequence[_T_co]: ... def __len__(self, /) -> int: ... Device = Literal["cpu"] if TYPE_CHECKING or sys.version_info >= (3, 9): Dtype = dtype[Union[ int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, ]] else: Dtype = dtype SupportsBufferProtocol = Any PyCapsule = Any class SupportsDLPack(Protocol): def __dlpack__(self, /, *, stream: None = ...) -> PyCapsule: ...
1,376
Python
17.36
76
0.595203
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/_statistical_functions.py
from __future__ import annotations from ._dtypes import ( _floating_dtypes, _numeric_dtypes, ) from ._array_object import Array from ._creation_functions import asarray from ._dtypes import float32, float64 from typing import TYPE_CHECKING, Optional, Tuple, Union if TYPE_CHECKING: from ._typing import Dtype import numpy as np def max( x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ) -> Array: if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in max") return Array._new(np.max(x._array, axis=axis, keepdims=keepdims)) def mean( x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ) -> Array: if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in mean") return Array._new(np.mean(x._array, axis=axis, keepdims=keepdims)) def min( x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ) -> Array: if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in min") return Array._new(np.min(x._array, axis=axis, keepdims=keepdims)) def prod( x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype: Optional[Dtype] = None, keepdims: bool = False, ) -> Array: if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in prod") # Note: sum() and prod() always upcast float32 to float64 for dtype=None # We need to do so here before computing the product to avoid overflow if dtype is None and x.dtype == float32: dtype = float64 return Array._new(np.prod(x._array, dtype=dtype, axis=axis, keepdims=keepdims)) def std( x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, correction: Union[int, float] = 0.0, keepdims: bool = False, ) -> Array: # Note: the keyword argument correction is different here if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in std") return Array._new(np.std(x._array, axis=axis, ddof=correction, keepdims=keepdims)) def sum( x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, dtype: Optional[Dtype] = None, keepdims: bool = False, ) -> Array: if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in sum") # Note: sum() and prod() always upcast integers to (u)int64 and float32 to # float64 for dtype=None. `np.sum` does that too for integers, but not for # float32, so we need to special-case it here if dtype is None and x.dtype == float32: dtype = float64 return Array._new(np.sum(x._array, axis=axis, dtype=dtype, keepdims=keepdims)) def var( x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, correction: Union[int, float] = 0.0, keepdims: bool = False, ) -> Array: # Note: the keyword argument correction is different here if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in var") return Array._new(np.var(x._array, axis=axis, ddof=correction, keepdims=keepdims))
3,378
Python
28.12931
86
0.64032
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/_manipulation_functions.py
from __future__ import annotations from ._array_object import Array from ._data_type_functions import result_type from typing import List, Optional, Tuple, Union import numpy as np # Note: the function name is different here def concat( arrays: Union[Tuple[Array, ...], List[Array]], /, *, axis: Optional[int] = 0 ) -> Array: """ Array API compatible wrapper for :py:func:`np.concatenate <numpy.concatenate>`. See its docstring for more information. """ # Note: Casting rules here are different from the np.concatenate default # (no for scalars with axis=None, no cross-kind casting) dtype = result_type(*arrays) arrays = tuple(a._array for a in arrays) return Array._new(np.concatenate(arrays, axis=axis, dtype=dtype)) def expand_dims(x: Array, /, *, axis: int) -> Array: """ Array API compatible wrapper for :py:func:`np.expand_dims <numpy.expand_dims>`. See its docstring for more information. """ return Array._new(np.expand_dims(x._array, axis)) def flip(x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None) -> Array: """ Array API compatible wrapper for :py:func:`np.flip <numpy.flip>`. See its docstring for more information. """ return Array._new(np.flip(x._array, axis=axis)) # Note: The function name is different here (see also matrix_transpose). # Unlike transpose(), the axes argument is required. def permute_dims(x: Array, /, axes: Tuple[int, ...]) -> Array: """ Array API compatible wrapper for :py:func:`np.transpose <numpy.transpose>`. See its docstring for more information. """ return Array._new(np.transpose(x._array, axes)) def reshape(x: Array, /, shape: Tuple[int, ...]) -> Array: """ Array API compatible wrapper for :py:func:`np.reshape <numpy.reshape>`. See its docstring for more information. """ return Array._new(np.reshape(x._array, shape)) def roll( x: Array, /, shift: Union[int, Tuple[int, ...]], *, axis: Optional[Union[int, Tuple[int, ...]]] = None, ) -> Array: """ Array API compatible wrapper for :py:func:`np.roll <numpy.roll>`. See its docstring for more information. """ return Array._new(np.roll(x._array, shift, axis=axis)) def squeeze(x: Array, /, axis: Union[int, Tuple[int, ...]]) -> Array: """ Array API compatible wrapper for :py:func:`np.squeeze <numpy.squeeze>`. See its docstring for more information. """ return Array._new(np.squeeze(x._array, axis=axis)) def stack(arrays: Union[Tuple[Array, ...], List[Array]], /, *, axis: int = 0) -> Array: """ Array API compatible wrapper for :py:func:`np.stack <numpy.stack>`. See its docstring for more information. """ # Call result type here just to raise on disallowed type combinations result_type(*arrays) arrays = tuple(a._array for a in arrays) return Array._new(np.stack(arrays, axis=axis))
2,944
Python
29.05102
87
0.648098
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/_set_functions.py
from __future__ import annotations from ._array_object import Array from typing import NamedTuple import numpy as np # Note: np.unique() is split into four functions in the array API: # unique_all, unique_counts, unique_inverse, and unique_values (this is done # to remove polymorphic return types). # Note: The various unique() functions are supposed to return multiple NaNs. # This does not match the NumPy behavior, however, this is currently left as a # TODO in this implementation as this behavior may be reverted in np.unique(). # See https://github.com/numpy/numpy/issues/20326. # Note: The functions here return a namedtuple (np.unique() returns a normal # tuple). class UniqueAllResult(NamedTuple): values: Array indices: Array inverse_indices: Array counts: Array class UniqueCountsResult(NamedTuple): values: Array counts: Array class UniqueInverseResult(NamedTuple): values: Array inverse_indices: Array def unique_all(x: Array, /) -> UniqueAllResult: """ Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`. See its docstring for more information. """ values, indices, inverse_indices, counts = np.unique( x._array, return_counts=True, return_index=True, return_inverse=True, ) # np.unique() flattens inverse indices, but they need to share x's shape # See https://github.com/numpy/numpy/issues/20638 inverse_indices = inverse_indices.reshape(x.shape) return UniqueAllResult( Array._new(values), Array._new(indices), Array._new(inverse_indices), Array._new(counts), ) def unique_counts(x: Array, /) -> UniqueCountsResult: res = np.unique( x._array, return_counts=True, return_index=False, return_inverse=False, ) return UniqueCountsResult(*[Array._new(i) for i in res]) def unique_inverse(x: Array, /) -> UniqueInverseResult: """ Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`. See its docstring for more information. """ values, inverse_indices = np.unique( x._array, return_counts=False, return_index=False, return_inverse=True, ) # np.unique() flattens inverse indices, but they need to share x's shape # See https://github.com/numpy/numpy/issues/20638 inverse_indices = inverse_indices.reshape(x.shape) return UniqueInverseResult(Array._new(values), Array._new(inverse_indices)) def unique_values(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`. See its docstring for more information. """ res = np.unique( x._array, return_counts=False, return_index=False, return_inverse=False, ) return Array._new(res)
2,848
Python
26.660194
79
0.668188
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/_elementwise_functions.py
from __future__ import annotations from ._dtypes import ( _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, _result_type, ) from ._array_object import Array import numpy as np def abs(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.abs <numpy.abs>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in abs") return Array._new(np.abs(x._array)) # Note: the function name is different here def acos(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.arccos <numpy.arccos>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in acos") return Array._new(np.arccos(x._array)) # Note: the function name is different here def acosh(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.arccosh <numpy.arccosh>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in acosh") return Array._new(np.arccosh(x._array)) def add(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.add <numpy.add>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in add") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.add(x1._array, x2._array)) # Note: the function name is different here def asin(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.arcsin <numpy.arcsin>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in asin") return Array._new(np.arcsin(x._array)) # Note: the function name is different here def asinh(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.arcsinh <numpy.arcsinh>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in asinh") return Array._new(np.arcsinh(x._array)) # Note: the function name is different here def atan(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.arctan <numpy.arctan>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in atan") return Array._new(np.arctan(x._array)) # Note: the function name is different here def atan2(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.arctan2 <numpy.arctan2>`. See its docstring for more information. """ if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in atan2") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.arctan2(x1._array, x2._array)) # Note: the function name is different here def atanh(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.arctanh <numpy.arctanh>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in atanh") return Array._new(np.arctanh(x._array)) def bitwise_and(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.bitwise_and <numpy.bitwise_and>`. See its docstring for more information. """ if ( x1.dtype not in _integer_or_boolean_dtypes or x2.dtype not in _integer_or_boolean_dtypes ): raise TypeError("Only integer or boolean dtypes are allowed in bitwise_and") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.bitwise_and(x1._array, x2._array)) # Note: the function name is different here def bitwise_left_shift(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.left_shift <numpy.left_shift>`. See its docstring for more information. """ if x1.dtype not in _integer_dtypes or x2.dtype not in _integer_dtypes: raise TypeError("Only integer dtypes are allowed in bitwise_left_shift") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) # Note: bitwise_left_shift is only defined for x2 nonnegative. if np.any(x2._array < 0): raise ValueError("bitwise_left_shift(x1, x2) is only defined for x2 >= 0") return Array._new(np.left_shift(x1._array, x2._array)) # Note: the function name is different here def bitwise_invert(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.invert <numpy.invert>`. See its docstring for more information. """ if x.dtype not in _integer_or_boolean_dtypes: raise TypeError("Only integer or boolean dtypes are allowed in bitwise_invert") return Array._new(np.invert(x._array)) def bitwise_or(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.bitwise_or <numpy.bitwise_or>`. See its docstring for more information. """ if ( x1.dtype not in _integer_or_boolean_dtypes or x2.dtype not in _integer_or_boolean_dtypes ): raise TypeError("Only integer or boolean dtypes are allowed in bitwise_or") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.bitwise_or(x1._array, x2._array)) # Note: the function name is different here def bitwise_right_shift(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.right_shift <numpy.right_shift>`. See its docstring for more information. """ if x1.dtype not in _integer_dtypes or x2.dtype not in _integer_dtypes: raise TypeError("Only integer dtypes are allowed in bitwise_right_shift") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) # Note: bitwise_right_shift is only defined for x2 nonnegative. if np.any(x2._array < 0): raise ValueError("bitwise_right_shift(x1, x2) is only defined for x2 >= 0") return Array._new(np.right_shift(x1._array, x2._array)) def bitwise_xor(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.bitwise_xor <numpy.bitwise_xor>`. See its docstring for more information. """ if ( x1.dtype not in _integer_or_boolean_dtypes or x2.dtype not in _integer_or_boolean_dtypes ): raise TypeError("Only integer or boolean dtypes are allowed in bitwise_xor") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.bitwise_xor(x1._array, x2._array)) def ceil(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.ceil <numpy.ceil>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in ceil") if x.dtype in _integer_dtypes: # Note: The return dtype of ceil is the same as the input return x return Array._new(np.ceil(x._array)) def cos(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.cos <numpy.cos>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in cos") return Array._new(np.cos(x._array)) def cosh(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.cosh <numpy.cosh>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in cosh") return Array._new(np.cosh(x._array)) def divide(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.divide <numpy.divide>`. See its docstring for more information. """ if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in divide") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.divide(x1._array, x2._array)) def equal(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.equal <numpy.equal>`. See its docstring for more information. """ # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.equal(x1._array, x2._array)) def exp(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.exp <numpy.exp>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in exp") return Array._new(np.exp(x._array)) def expm1(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.expm1 <numpy.expm1>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in expm1") return Array._new(np.expm1(x._array)) def floor(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.floor <numpy.floor>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in floor") if x.dtype in _integer_dtypes: # Note: The return dtype of floor is the same as the input return x return Array._new(np.floor(x._array)) def floor_divide(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.floor_divide <numpy.floor_divide>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in floor_divide") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.floor_divide(x1._array, x2._array)) def greater(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.greater <numpy.greater>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in greater") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.greater(x1._array, x2._array)) def greater_equal(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.greater_equal <numpy.greater_equal>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in greater_equal") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.greater_equal(x1._array, x2._array)) def isfinite(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.isfinite <numpy.isfinite>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in isfinite") return Array._new(np.isfinite(x._array)) def isinf(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.isinf <numpy.isinf>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in isinf") return Array._new(np.isinf(x._array)) def isnan(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.isnan <numpy.isnan>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in isnan") return Array._new(np.isnan(x._array)) def less(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.less <numpy.less>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in less") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.less(x1._array, x2._array)) def less_equal(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.less_equal <numpy.less_equal>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in less_equal") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.less_equal(x1._array, x2._array)) def log(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.log <numpy.log>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in log") return Array._new(np.log(x._array)) def log1p(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.log1p <numpy.log1p>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in log1p") return Array._new(np.log1p(x._array)) def log2(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.log2 <numpy.log2>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in log2") return Array._new(np.log2(x._array)) def log10(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.log10 <numpy.log10>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in log10") return Array._new(np.log10(x._array)) def logaddexp(x1: Array, x2: Array) -> Array: """ Array API compatible wrapper for :py:func:`np.logaddexp <numpy.logaddexp>`. See its docstring for more information. """ if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in logaddexp") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.logaddexp(x1._array, x2._array)) def logical_and(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.logical_and <numpy.logical_and>`. See its docstring for more information. """ if x1.dtype not in _boolean_dtypes or x2.dtype not in _boolean_dtypes: raise TypeError("Only boolean dtypes are allowed in logical_and") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.logical_and(x1._array, x2._array)) def logical_not(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.logical_not <numpy.logical_not>`. See its docstring for more information. """ if x.dtype not in _boolean_dtypes: raise TypeError("Only boolean dtypes are allowed in logical_not") return Array._new(np.logical_not(x._array)) def logical_or(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.logical_or <numpy.logical_or>`. See its docstring for more information. """ if x1.dtype not in _boolean_dtypes or x2.dtype not in _boolean_dtypes: raise TypeError("Only boolean dtypes are allowed in logical_or") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.logical_or(x1._array, x2._array)) def logical_xor(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.logical_xor <numpy.logical_xor>`. See its docstring for more information. """ if x1.dtype not in _boolean_dtypes or x2.dtype not in _boolean_dtypes: raise TypeError("Only boolean dtypes are allowed in logical_xor") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.logical_xor(x1._array, x2._array)) def multiply(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.multiply <numpy.multiply>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in multiply") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.multiply(x1._array, x2._array)) def negative(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.negative <numpy.negative>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in negative") return Array._new(np.negative(x._array)) def not_equal(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.not_equal <numpy.not_equal>`. See its docstring for more information. """ # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.not_equal(x1._array, x2._array)) def positive(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.positive <numpy.positive>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in positive") return Array._new(np.positive(x._array)) # Note: the function name is different here def pow(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.power <numpy.power>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in pow") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.power(x1._array, x2._array)) def remainder(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.remainder <numpy.remainder>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in remainder") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.remainder(x1._array, x2._array)) def round(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.round <numpy.round>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in round") return Array._new(np.round(x._array)) def sign(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.sign <numpy.sign>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in sign") return Array._new(np.sign(x._array)) def sin(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.sin <numpy.sin>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in sin") return Array._new(np.sin(x._array)) def sinh(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.sinh <numpy.sinh>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in sinh") return Array._new(np.sinh(x._array)) def square(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.square <numpy.square>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in square") return Array._new(np.square(x._array)) def sqrt(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.sqrt <numpy.sqrt>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in sqrt") return Array._new(np.sqrt(x._array)) def subtract(x1: Array, x2: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.subtract <numpy.subtract>`. See its docstring for more information. """ if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in subtract") # Call result type here just to raise on disallowed type combinations _result_type(x1.dtype, x2.dtype) x1, x2 = Array._normalize_two_args(x1, x2) return Array._new(np.subtract(x1._array, x2._array)) def tan(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.tan <numpy.tan>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in tan") return Array._new(np.tan(x._array)) def tanh(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.tanh <numpy.tanh>`. See its docstring for more information. """ if x.dtype not in _floating_dtypes: raise TypeError("Only floating-point dtypes are allowed in tanh") return Array._new(np.tanh(x._array)) def trunc(x: Array, /) -> Array: """ Array API compatible wrapper for :py:func:`np.trunc <numpy.trunc>`. See its docstring for more information. """ if x.dtype not in _numeric_dtypes: raise TypeError("Only numeric dtypes are allowed in trunc") if x.dtype in _integer_dtypes: # Note: The return dtype of trunc is the same as the input return x return Array._new(np.trunc(x._array))
24,772
Python
32.935616
87
0.662926
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/_dtypes.py
import numpy as np # Note: we use dtype objects instead of dtype classes. The spec does not # require any behavior on dtypes other than equality. int8 = np.dtype("int8") int16 = np.dtype("int16") int32 = np.dtype("int32") int64 = np.dtype("int64") uint8 = np.dtype("uint8") uint16 = np.dtype("uint16") uint32 = np.dtype("uint32") uint64 = np.dtype("uint64") float32 = np.dtype("float32") float64 = np.dtype("float64") # Note: This name is changed bool = np.dtype("bool") _all_dtypes = ( int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, bool, ) _boolean_dtypes = (bool,) _floating_dtypes = (float32, float64) _integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64) _integer_or_boolean_dtypes = ( bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) _numeric_dtypes = ( float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64, ) _dtype_categories = { "all": _all_dtypes, "numeric": _numeric_dtypes, "integer": _integer_dtypes, "integer or boolean": _integer_or_boolean_dtypes, "boolean": _boolean_dtypes, "floating-point": _floating_dtypes, } # Note: the spec defines a restricted type promotion table compared to NumPy. # In particular, cross-kind promotions like integer + float or boolean + # integer are not allowed, even for functions that accept both kinds. # Additionally, NumPy promotes signed integer + uint64 to float64, but this # promotion is not allowed here. To be clear, Python scalar int objects are # allowed to promote to floating-point dtypes, but only in array operators # (see Array._promote_scalar) method in _array_object.py. _promotion_table = { (int8, int8): int8, (int8, int16): int16, (int8, int32): int32, (int8, int64): int64, (int16, int8): int16, (int16, int16): int16, (int16, int32): int32, (int16, int64): int64, (int32, int8): int32, (int32, int16): int32, (int32, int32): int32, (int32, int64): int64, (int64, int8): int64, (int64, int16): int64, (int64, int32): int64, (int64, int64): int64, (uint8, uint8): uint8, (uint8, uint16): uint16, (uint8, uint32): uint32, (uint8, uint64): uint64, (uint16, uint8): uint16, (uint16, uint16): uint16, (uint16, uint32): uint32, (uint16, uint64): uint64, (uint32, uint8): uint32, (uint32, uint16): uint32, (uint32, uint32): uint32, (uint32, uint64): uint64, (uint64, uint8): uint64, (uint64, uint16): uint64, (uint64, uint32): uint64, (uint64, uint64): uint64, (int8, uint8): int16, (int8, uint16): int32, (int8, uint32): int64, (int16, uint8): int16, (int16, uint16): int32, (int16, uint32): int64, (int32, uint8): int32, (int32, uint16): int32, (int32, uint32): int64, (int64, uint8): int64, (int64, uint16): int64, (int64, uint32): int64, (uint8, int8): int16, (uint16, int8): int32, (uint32, int8): int64, (uint8, int16): int16, (uint16, int16): int32, (uint32, int16): int64, (uint8, int32): int32, (uint16, int32): int32, (uint32, int32): int64, (uint8, int64): int64, (uint16, int64): int64, (uint32, int64): int64, (float32, float32): float32, (float32, float64): float64, (float64, float32): float64, (float64, float64): float64, (bool, bool): bool, } def _result_type(type1, type2): if (type1, type2) in _promotion_table: return _promotion_table[type1, type2] raise TypeError(f"{type1} and {type2} cannot be type promoted together")
3,707
Python
24.75
77
0.623415
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/tests/test_elementwise_functions.py
from inspect import getfullargspec from numpy.testing import assert_raises from .. import asarray, _elementwise_functions from .._elementwise_functions import bitwise_left_shift, bitwise_right_shift from .._dtypes import ( _dtype_categories, _boolean_dtypes, _floating_dtypes, _integer_dtypes, ) def nargs(func): return len(getfullargspec(func).args) def test_function_types(): # Test that every function accepts only the required input types. We only # test the negative cases here (error). The positive cases are tested in # the array API test suite. elementwise_function_input_types = { "abs": "numeric", "acos": "floating-point", "acosh": "floating-point", "add": "numeric", "asin": "floating-point", "asinh": "floating-point", "atan": "floating-point", "atan2": "floating-point", "atanh": "floating-point", "bitwise_and": "integer or boolean", "bitwise_invert": "integer or boolean", "bitwise_left_shift": "integer", "bitwise_or": "integer or boolean", "bitwise_right_shift": "integer", "bitwise_xor": "integer or boolean", "ceil": "numeric", "cos": "floating-point", "cosh": "floating-point", "divide": "floating-point", "equal": "all", "exp": "floating-point", "expm1": "floating-point", "floor": "numeric", "floor_divide": "numeric", "greater": "numeric", "greater_equal": "numeric", "isfinite": "numeric", "isinf": "numeric", "isnan": "numeric", "less": "numeric", "less_equal": "numeric", "log": "floating-point", "logaddexp": "floating-point", "log10": "floating-point", "log1p": "floating-point", "log2": "floating-point", "logical_and": "boolean", "logical_not": "boolean", "logical_or": "boolean", "logical_xor": "boolean", "multiply": "numeric", "negative": "numeric", "not_equal": "all", "positive": "numeric", "pow": "numeric", "remainder": "numeric", "round": "numeric", "sign": "numeric", "sin": "floating-point", "sinh": "floating-point", "sqrt": "floating-point", "square": "numeric", "subtract": "numeric", "tan": "floating-point", "tanh": "floating-point", "trunc": "numeric", } def _array_vals(): for d in _integer_dtypes: yield asarray(1, dtype=d) for d in _boolean_dtypes: yield asarray(False, dtype=d) for d in _floating_dtypes: yield asarray(1.0, dtype=d) for x in _array_vals(): for func_name, types in elementwise_function_input_types.items(): dtypes = _dtype_categories[types] func = getattr(_elementwise_functions, func_name) if nargs(func) == 2: for y in _array_vals(): if x.dtype not in dtypes or y.dtype not in dtypes: assert_raises(TypeError, lambda: func(x, y)) else: if x.dtype not in dtypes: assert_raises(TypeError, lambda: func(x)) def test_bitwise_shift_error(): # bitwise shift functions should raise when the second argument is negative assert_raises( ValueError, lambda: bitwise_left_shift(asarray([1, 1]), asarray([1, -1])) ) assert_raises( ValueError, lambda: bitwise_right_shift(asarray([1, 1]), asarray([1, -1])) )
3,619
Python
31.321428
82
0.554849
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/tests/test_array_object.py
import operator from numpy.testing import assert_raises import numpy as np import pytest from .. import ones, asarray, reshape, result_type, all, equal from .._array_object import Array from .._dtypes import ( _all_dtypes, _boolean_dtypes, _floating_dtypes, _integer_dtypes, _integer_or_boolean_dtypes, _numeric_dtypes, int8, int16, int32, int64, uint64, bool as bool_, ) def test_validate_index(): # The indexing tests in the official array API test suite test that the # array object correctly handles the subset of indices that are required # by the spec. But the NumPy array API implementation specifically # disallows any index not required by the spec, via Array._validate_index. # This test focuses on testing that non-valid indices are correctly # rejected. See # https://data-apis.org/array-api/latest/API_specification/indexing.html # and the docstring of Array._validate_index for the exact indexing # behavior that should be allowed. This does not test indices that are # already invalid in NumPy itself because Array will generally just pass # such indices directly to the underlying np.ndarray. a = ones((3, 4)) # Out of bounds slices are not allowed assert_raises(IndexError, lambda: a[:4]) assert_raises(IndexError, lambda: a[:-4]) assert_raises(IndexError, lambda: a[:3:-1]) assert_raises(IndexError, lambda: a[:-5:-1]) assert_raises(IndexError, lambda: a[4:]) assert_raises(IndexError, lambda: a[-4:]) assert_raises(IndexError, lambda: a[4::-1]) assert_raises(IndexError, lambda: a[-4::-1]) assert_raises(IndexError, lambda: a[...,:5]) assert_raises(IndexError, lambda: a[...,:-5]) assert_raises(IndexError, lambda: a[...,:5:-1]) assert_raises(IndexError, lambda: a[...,:-6:-1]) assert_raises(IndexError, lambda: a[...,5:]) assert_raises(IndexError, lambda: a[...,-5:]) assert_raises(IndexError, lambda: a[...,5::-1]) assert_raises(IndexError, lambda: a[...,-5::-1]) # Boolean indices cannot be part of a larger tuple index assert_raises(IndexError, lambda: a[a[:,0]==1,0]) assert_raises(IndexError, lambda: a[a[:,0]==1,...]) assert_raises(IndexError, lambda: a[..., a[0]==1]) assert_raises(IndexError, lambda: a[[True, True, True]]) assert_raises(IndexError, lambda: a[(True, True, True),]) # Integer array indices are not allowed (except for 0-D) idx = asarray([[0, 1]]) assert_raises(IndexError, lambda: a[idx]) assert_raises(IndexError, lambda: a[idx,]) assert_raises(IndexError, lambda: a[[0, 1]]) assert_raises(IndexError, lambda: a[(0, 1), (0, 1)]) assert_raises(IndexError, lambda: a[[0, 1]]) assert_raises(IndexError, lambda: a[np.array([[0, 1]])]) # Multiaxis indices must contain exactly as many indices as dimensions assert_raises(IndexError, lambda: a[()]) assert_raises(IndexError, lambda: a[0,]) assert_raises(IndexError, lambda: a[0]) assert_raises(IndexError, lambda: a[:]) def test_operators(): # For every operator, we test that it works for the required type # combinations and raises TypeError otherwise binary_op_dtypes = { "__add__": "numeric", "__and__": "integer_or_boolean", "__eq__": "all", "__floordiv__": "numeric", "__ge__": "numeric", "__gt__": "numeric", "__le__": "numeric", "__lshift__": "integer", "__lt__": "numeric", "__mod__": "numeric", "__mul__": "numeric", "__ne__": "all", "__or__": "integer_or_boolean", "__pow__": "numeric", "__rshift__": "integer", "__sub__": "numeric", "__truediv__": "floating", "__xor__": "integer_or_boolean", } # Recompute each time because of in-place ops def _array_vals(): for d in _integer_dtypes: yield asarray(1, dtype=d) for d in _boolean_dtypes: yield asarray(False, dtype=d) for d in _floating_dtypes: yield asarray(1.0, dtype=d) for op, dtypes in binary_op_dtypes.items(): ops = [op] if op not in ["__eq__", "__ne__", "__le__", "__ge__", "__lt__", "__gt__"]: rop = "__r" + op[2:] iop = "__i" + op[2:] ops += [rop, iop] for s in [1, 1.0, False]: for _op in ops: for a in _array_vals(): # Test array op scalar. From the spec, the following combinations # are supported: # - Python bool for a bool array dtype, # - a Python int within the bounds of the given dtype for integer array dtypes, # - a Python int or float for floating-point array dtypes # We do not do bounds checking for int scalars, but rather use the default # NumPy behavior for casting in that case. if ((dtypes == "all" or dtypes == "numeric" and a.dtype in _numeric_dtypes or dtypes == "integer" and a.dtype in _integer_dtypes or dtypes == "integer_or_boolean" and a.dtype in _integer_or_boolean_dtypes or dtypes == "boolean" and a.dtype in _boolean_dtypes or dtypes == "floating" and a.dtype in _floating_dtypes ) # bool is a subtype of int, which is why we avoid # isinstance here. and (a.dtype in _boolean_dtypes and type(s) == bool or a.dtype in _integer_dtypes and type(s) == int or a.dtype in _floating_dtypes and type(s) in [float, int] )): # Only test for no error getattr(a, _op)(s) else: assert_raises(TypeError, lambda: getattr(a, _op)(s)) # Test array op array. for _op in ops: for x in _array_vals(): for y in _array_vals(): # See the promotion table in NEP 47 or the array # API spec page on type promotion. Mixed kind # promotion is not defined. if (x.dtype == uint64 and y.dtype in [int8, int16, int32, int64] or y.dtype == uint64 and x.dtype in [int8, int16, int32, int64] or x.dtype in _integer_dtypes and y.dtype not in _integer_dtypes or y.dtype in _integer_dtypes and x.dtype not in _integer_dtypes or x.dtype in _boolean_dtypes and y.dtype not in _boolean_dtypes or y.dtype in _boolean_dtypes and x.dtype not in _boolean_dtypes or x.dtype in _floating_dtypes and y.dtype not in _floating_dtypes or y.dtype in _floating_dtypes and x.dtype not in _floating_dtypes ): assert_raises(TypeError, lambda: getattr(x, _op)(y)) # Ensure in-place operators only promote to the same dtype as the left operand. elif ( _op.startswith("__i") and result_type(x.dtype, y.dtype) != x.dtype ): assert_raises(TypeError, lambda: getattr(x, _op)(y)) # Ensure only those dtypes that are required for every operator are allowed. elif (dtypes == "all" and (x.dtype in _boolean_dtypes and y.dtype in _boolean_dtypes or x.dtype in _numeric_dtypes and y.dtype in _numeric_dtypes) or (dtypes == "numeric" and x.dtype in _numeric_dtypes and y.dtype in _numeric_dtypes) or dtypes == "integer" and x.dtype in _integer_dtypes and y.dtype in _numeric_dtypes or dtypes == "integer_or_boolean" and (x.dtype in _integer_dtypes and y.dtype in _integer_dtypes or x.dtype in _boolean_dtypes and y.dtype in _boolean_dtypes) or dtypes == "boolean" and x.dtype in _boolean_dtypes and y.dtype in _boolean_dtypes or dtypes == "floating" and x.dtype in _floating_dtypes and y.dtype in _floating_dtypes ): getattr(x, _op)(y) else: assert_raises(TypeError, lambda: getattr(x, _op)(y)) unary_op_dtypes = { "__abs__": "numeric", "__invert__": "integer_or_boolean", "__neg__": "numeric", "__pos__": "numeric", } for op, dtypes in unary_op_dtypes.items(): for a in _array_vals(): if ( dtypes == "numeric" and a.dtype in _numeric_dtypes or dtypes == "integer_or_boolean" and a.dtype in _integer_or_boolean_dtypes ): # Only test for no error getattr(a, op)() else: assert_raises(TypeError, lambda: getattr(a, op)()) # Finally, matmul() must be tested separately, because it works a bit # different from the other operations. def _matmul_array_vals(): for a in _array_vals(): yield a for d in _all_dtypes: yield ones((3, 4), dtype=d) yield ones((4, 2), dtype=d) yield ones((4, 4), dtype=d) # Scalars always error for _op in ["__matmul__", "__rmatmul__", "__imatmul__"]: for s in [1, 1.0, False]: for a in _matmul_array_vals(): if (type(s) in [float, int] and a.dtype in _floating_dtypes or type(s) == int and a.dtype in _integer_dtypes): # Type promotion is valid, but @ is not allowed on 0-D # inputs, so the error is a ValueError assert_raises(ValueError, lambda: getattr(a, _op)(s)) else: assert_raises(TypeError, lambda: getattr(a, _op)(s)) for x in _matmul_array_vals(): for y in _matmul_array_vals(): if (x.dtype == uint64 and y.dtype in [int8, int16, int32, int64] or y.dtype == uint64 and x.dtype in [int8, int16, int32, int64] or x.dtype in _integer_dtypes and y.dtype not in _integer_dtypes or y.dtype in _integer_dtypes and x.dtype not in _integer_dtypes or x.dtype in _floating_dtypes and y.dtype not in _floating_dtypes or y.dtype in _floating_dtypes and x.dtype not in _floating_dtypes or x.dtype in _boolean_dtypes or y.dtype in _boolean_dtypes ): assert_raises(TypeError, lambda: x.__matmul__(y)) assert_raises(TypeError, lambda: y.__rmatmul__(x)) assert_raises(TypeError, lambda: x.__imatmul__(y)) elif x.shape == () or y.shape == () or x.shape[1] != y.shape[0]: assert_raises(ValueError, lambda: x.__matmul__(y)) assert_raises(ValueError, lambda: y.__rmatmul__(x)) if result_type(x.dtype, y.dtype) != x.dtype: assert_raises(TypeError, lambda: x.__imatmul__(y)) else: assert_raises(ValueError, lambda: x.__imatmul__(y)) else: x.__matmul__(y) y.__rmatmul__(x) if result_type(x.dtype, y.dtype) != x.dtype: assert_raises(TypeError, lambda: x.__imatmul__(y)) elif y.shape[0] != y.shape[1]: # This one fails because x @ y has a different shape from x assert_raises(ValueError, lambda: x.__imatmul__(y)) else: x.__imatmul__(y) def test_python_scalar_construtors(): b = asarray(False) i = asarray(0) f = asarray(0.0) assert bool(b) == False assert int(i) == 0 assert float(f) == 0.0 assert operator.index(i) == 0 # bool/int/float should only be allowed on 0-D arrays. assert_raises(TypeError, lambda: bool(asarray([False]))) assert_raises(TypeError, lambda: int(asarray([0]))) assert_raises(TypeError, lambda: float(asarray([0.0]))) assert_raises(TypeError, lambda: operator.index(asarray([0]))) # bool/int/float should only be allowed on arrays of the corresponding # dtype assert_raises(ValueError, lambda: bool(i)) assert_raises(ValueError, lambda: bool(f)) assert_raises(ValueError, lambda: int(b)) assert_raises(ValueError, lambda: int(f)) assert_raises(ValueError, lambda: float(b)) assert_raises(ValueError, lambda: float(i)) assert_raises(TypeError, lambda: operator.index(b)) assert_raises(TypeError, lambda: operator.index(f)) def test_device_property(): a = ones((3, 4)) assert a.device == 'cpu' assert all(equal(a.to_device('cpu'), a)) assert_raises(ValueError, lambda: a.to_device('gpu')) assert all(equal(asarray(a, device='cpu'), a)) assert_raises(ValueError, lambda: asarray(a, device='gpu')) def test_array_properties(): a = ones((1, 2, 3)) b = ones((2, 3)) assert_raises(ValueError, lambda: a.T) assert isinstance(b.T, Array) assert b.T.shape == (3, 2) assert isinstance(a.mT, Array) assert a.mT.shape == (1, 3, 2) assert isinstance(b.mT, Array) assert b.mT.shape == (3, 2) def test___array__(): a = ones((2, 3), dtype=int16) assert np.asarray(a) is a._array b = np.asarray(a, dtype=np.float64) assert np.all(np.equal(b, np.ones((2, 3), dtype=np.float64))) assert b.dtype == np.float64 def test_allow_newaxis(): a = ones(5) indexed_a = a[None, :] assert indexed_a.shape == (1, 5) def test_disallow_flat_indexing_with_newaxis(): a = ones((3, 3, 3)) with pytest.raises(IndexError): a[None, 0, 0] def test_disallow_mask_with_newaxis(): a = ones((3, 3, 3)) with pytest.raises(IndexError): a[None, asarray(True)] @pytest.mark.parametrize("shape", [(), (5,), (3, 3, 3)]) @pytest.mark.parametrize("index", ["string", False, True]) def test_error_on_invalid_index(shape, index): a = ones(shape) with pytest.raises(IndexError): a[index] def test_mask_0d_array_without_errors(): a = ones(()) a[asarray(True)] @pytest.mark.parametrize( "i", [slice(5), slice(5, 0), asarray(True), asarray([0, 1])] ) def test_error_on_invalid_index_with_ellipsis(i): a = ones((3, 3, 3)) with pytest.raises(IndexError): a[..., i] with pytest.raises(IndexError): a[i, ...] def test_array_keys_use_private_array(): """ Indexing operations convert array keys before indexing the internal array Fails when array_api array keys are not converted into NumPy-proper arrays in __getitem__(). This is achieved by passing array_api arrays with 0-sized dimensions, which NumPy-proper treats erroneously - not sure why! TODO: Find and use appropiate __setitem__() case. """ a = ones((0, 0), dtype=bool_) assert a[a].shape == (0,) a = ones((0,), dtype=bool_) key = ones((0, 0), dtype=bool_) with pytest.raises(IndexError): a[key]
15,770
Python
40.944149
132
0.54293
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/tests/test_sorting_functions.py
import pytest from numpy import array_api as xp @pytest.mark.parametrize( "obj, axis, expected", [ ([0, 0], -1, [0, 1]), ([0, 1, 0], -1, [1, 0, 2]), ([[0, 1], [1, 1]], 0, [[1, 0], [0, 1]]), ([[0, 1], [1, 1]], 1, [[1, 0], [0, 1]]), ], ) def test_stable_desc_argsort(obj, axis, expected): """ Indices respect relative order of a descending stable-sort See https://github.com/numpy/numpy/issues/20778 """ x = xp.asarray(obj) out = xp.argsort(x, axis=axis, stable=True, descending=True) assert xp.all(out == xp.asarray(expected))
602
Python
24.124999
64
0.533223
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/tests/__init__.py
""" Tests for the array API namespace. Note, full compliance with the array API can be tested with the official array API test suite https://github.com/data-apis/array-api-tests. This test suite primarily focuses on those things that are not tested by the official test suite. """
282
Python
34.374996
87
0.776596
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/tests/test_validation.py
from typing import Callable import pytest from numpy import array_api as xp def p(func: Callable, *args, **kwargs): f_sig = ", ".join( [str(a) for a in args] + [f"{k}={v}" for k, v in kwargs.items()] ) id_ = f"{func.__name__}({f_sig})" return pytest.param(func, args, kwargs, id=id_) @pytest.mark.parametrize( "func, args, kwargs", [ p(xp.can_cast, 42, xp.int8), p(xp.can_cast, xp.int8, 42), p(xp.result_type, 42), ], ) def test_raises_on_invalid_types(func, args, kwargs): """Function raises TypeError when passed invalidly-typed inputs""" with pytest.raises(TypeError): func(*args, **kwargs)
676
Python
23.178571
72
0.593195
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/tests/test_data_type_functions.py
import pytest from numpy import array_api as xp @pytest.mark.parametrize( "from_, to, expected", [ (xp.int8, xp.int16, True), (xp.int16, xp.int8, False), (xp.bool, xp.int8, False), (xp.asarray(0, dtype=xp.uint8), xp.int8, False), ], ) def test_can_cast(from_, to, expected): """ can_cast() returns correct result """ assert xp.can_cast(from_, to) == expected
422
Python
20.149999
56
0.575829
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/tests/test_creation_functions.py
from numpy.testing import assert_raises import numpy as np from .. import all from .._creation_functions import ( asarray, arange, empty, empty_like, eye, full, full_like, linspace, meshgrid, ones, ones_like, zeros, zeros_like, ) from .._dtypes import float32, float64 from .._array_object import Array def test_asarray_errors(): # Test various protections against incorrect usage assert_raises(TypeError, lambda: Array([1])) assert_raises(TypeError, lambda: asarray(["a"])) assert_raises(ValueError, lambda: asarray([1.0], dtype=np.float16)) assert_raises(OverflowError, lambda: asarray(2**100)) # Preferably this would be OverflowError # assert_raises(OverflowError, lambda: asarray([2**100])) assert_raises(TypeError, lambda: asarray([2**100])) asarray([1], device="cpu") # Doesn't error assert_raises(ValueError, lambda: asarray([1], device="gpu")) assert_raises(ValueError, lambda: asarray([1], dtype=int)) assert_raises(ValueError, lambda: asarray([1], dtype="i")) def test_asarray_copy(): a = asarray([1]) b = asarray(a, copy=True) a[0] = 0 assert all(b[0] == 1) assert all(a[0] == 0) a = asarray([1]) b = asarray(a, copy=np._CopyMode.ALWAYS) a[0] = 0 assert all(b[0] == 1) assert all(a[0] == 0) a = asarray([1]) b = asarray(a, copy=np._CopyMode.NEVER) a[0] = 0 assert all(b[0] == 0) assert_raises(NotImplementedError, lambda: asarray(a, copy=False)) assert_raises(NotImplementedError, lambda: asarray(a, copy=np._CopyMode.IF_NEEDED)) def test_arange_errors(): arange(1, device="cpu") # Doesn't error assert_raises(ValueError, lambda: arange(1, device="gpu")) assert_raises(ValueError, lambda: arange(1, dtype=int)) assert_raises(ValueError, lambda: arange(1, dtype="i")) def test_empty_errors(): empty((1,), device="cpu") # Doesn't error assert_raises(ValueError, lambda: empty((1,), device="gpu")) assert_raises(ValueError, lambda: empty((1,), dtype=int)) assert_raises(ValueError, lambda: empty((1,), dtype="i")) def test_empty_like_errors(): empty_like(asarray(1), device="cpu") # Doesn't error assert_raises(ValueError, lambda: empty_like(asarray(1), device="gpu")) assert_raises(ValueError, lambda: empty_like(asarray(1), dtype=int)) assert_raises(ValueError, lambda: empty_like(asarray(1), dtype="i")) def test_eye_errors(): eye(1, device="cpu") # Doesn't error assert_raises(ValueError, lambda: eye(1, device="gpu")) assert_raises(ValueError, lambda: eye(1, dtype=int)) assert_raises(ValueError, lambda: eye(1, dtype="i")) def test_full_errors(): full((1,), 0, device="cpu") # Doesn't error assert_raises(ValueError, lambda: full((1,), 0, device="gpu")) assert_raises(ValueError, lambda: full((1,), 0, dtype=int)) assert_raises(ValueError, lambda: full((1,), 0, dtype="i")) def test_full_like_errors(): full_like(asarray(1), 0, device="cpu") # Doesn't error assert_raises(ValueError, lambda: full_like(asarray(1), 0, device="gpu")) assert_raises(ValueError, lambda: full_like(asarray(1), 0, dtype=int)) assert_raises(ValueError, lambda: full_like(asarray(1), 0, dtype="i")) def test_linspace_errors(): linspace(0, 1, 10, device="cpu") # Doesn't error assert_raises(ValueError, lambda: linspace(0, 1, 10, device="gpu")) assert_raises(ValueError, lambda: linspace(0, 1, 10, dtype=float)) assert_raises(ValueError, lambda: linspace(0, 1, 10, dtype="f")) def test_ones_errors(): ones((1,), device="cpu") # Doesn't error assert_raises(ValueError, lambda: ones((1,), device="gpu")) assert_raises(ValueError, lambda: ones((1,), dtype=int)) assert_raises(ValueError, lambda: ones((1,), dtype="i")) def test_ones_like_errors(): ones_like(asarray(1), device="cpu") # Doesn't error assert_raises(ValueError, lambda: ones_like(asarray(1), device="gpu")) assert_raises(ValueError, lambda: ones_like(asarray(1), dtype=int)) assert_raises(ValueError, lambda: ones_like(asarray(1), dtype="i")) def test_zeros_errors(): zeros((1,), device="cpu") # Doesn't error assert_raises(ValueError, lambda: zeros((1,), device="gpu")) assert_raises(ValueError, lambda: zeros((1,), dtype=int)) assert_raises(ValueError, lambda: zeros((1,), dtype="i")) def test_zeros_like_errors(): zeros_like(asarray(1), device="cpu") # Doesn't error assert_raises(ValueError, lambda: zeros_like(asarray(1), device="gpu")) assert_raises(ValueError, lambda: zeros_like(asarray(1), dtype=int)) assert_raises(ValueError, lambda: zeros_like(asarray(1), dtype="i")) def test_meshgrid_dtype_errors(): # Doesn't raise meshgrid() meshgrid(asarray([1.], dtype=float32)) meshgrid(asarray([1.], dtype=float32), asarray([1.], dtype=float32)) assert_raises(ValueError, lambda: meshgrid(asarray([1.], dtype=float32), asarray([1.], dtype=float64)))
5,023
Python
34.132867
107
0.655982
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/numpy/array_api/tests/test_set_functions.py
import pytest from hypothesis import given from hypothesis.extra.array_api import make_strategies_namespace from numpy import array_api as xp xps = make_strategies_namespace(xp) @pytest.mark.parametrize("func", [xp.unique_all, xp.unique_inverse]) @given(xps.arrays(dtype=xps.scalar_dtypes(), shape=xps.array_shapes())) def test_inverse_indices_shape(func, x): """ Inverse indices share shape of input array See https://github.com/numpy/numpy/issues/20638 """ out = func(x) assert out.inverse_indices.shape == x.shape
546
Python
26.349999
71
0.730769
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/idna/intranges.py
""" Given a list of integers, made up of (hopefully) a small number of long runs of consecutive integers, compute a representation of the form ((start1, end1), (start2, end2) ...). Then answer the question "was x present in the original list?" in time O(log(# runs)). """ import bisect from typing import List, Tuple def intranges_from_list(list_: List[int]) -> Tuple[int, ...]: """Represent a list of integers as a sequence of ranges: ((start_0, end_0), (start_1, end_1), ...), such that the original integers are exactly those x such that start_i <= x < end_i for some i. Ranges are encoded as single integers (start << 32 | end), not as tuples. """ sorted_list = sorted(list_) ranges = [] last_write = -1 for i in range(len(sorted_list)): if i+1 < len(sorted_list): if sorted_list[i] == sorted_list[i+1]-1: continue current_range = sorted_list[last_write+1:i+1] ranges.append(_encode_range(current_range[0], current_range[-1] + 1)) last_write = i return tuple(ranges) def _encode_range(start: int, end: int) -> int: return (start << 32) | end def _decode_range(r: int) -> Tuple[int, int]: return (r >> 32), (r & ((1 << 32) - 1)) def intranges_contain(int_: int, ranges: Tuple[int, ...]) -> bool: """Determine if `int_` falls into one of the ranges in `ranges`.""" tuple_ = _encode_range(int_, 0) pos = bisect.bisect_left(ranges, tuple_) # we could be immediately ahead of a tuple (start, end) # with start < int_ <= end if pos > 0: left, right = _decode_range(ranges[pos-1]) if left <= int_ < right: return True # or we could be immediately behind a tuple (int_, end) if pos < len(ranges): left, _ = _decode_range(ranges[pos]) if left == int_: return True return False
1,881
Python
33.218181
77
0.600744
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/idna/__init__.py
from .package_data import __version__ from .core import ( IDNABidiError, IDNAError, InvalidCodepoint, InvalidCodepointContext, alabel, check_bidi, check_hyphen_ok, check_initial_combiner, check_label, check_nfc, decode, encode, ulabel, uts46_remap, valid_contextj, valid_contexto, valid_label_length, valid_string_length, ) from .intranges import intranges_contain __all__ = [ "IDNABidiError", "IDNAError", "InvalidCodepoint", "InvalidCodepointContext", "alabel", "check_bidi", "check_hyphen_ok", "check_initial_combiner", "check_label", "check_nfc", "decode", "encode", "intranges_contain", "ulabel", "uts46_remap", "valid_contextj", "valid_contexto", "valid_label_length", "valid_string_length", ]
849
Python
17.888888
40
0.617197
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/idna/core.py
from . import idnadata import bisect import unicodedata import re from typing import Union, Optional from .intranges import intranges_contain _virama_combining_class = 9 _alabel_prefix = b'xn--' _unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]') class IDNAError(UnicodeError): """ Base exception for all IDNA-encoding related problems """ pass class IDNABidiError(IDNAError): """ Exception when bidirectional requirements are not satisfied """ pass class InvalidCodepoint(IDNAError): """ Exception when a disallowed or unallocated codepoint is used """ pass class InvalidCodepointContext(IDNAError): """ Exception when the codepoint is not valid in the context it is used """ pass def _combining_class(cp: int) -> int: v = unicodedata.combining(chr(cp)) if v == 0: if not unicodedata.name(chr(cp)): raise ValueError('Unknown character in unicodedata') return v def _is_script(cp: str, script: str) -> bool: return intranges_contain(ord(cp), idnadata.scripts[script]) def _punycode(s: str) -> bytes: return s.encode('punycode') def _unot(s: int) -> str: return 'U+{:04X}'.format(s) def valid_label_length(label: Union[bytes, str]) -> bool: if len(label) > 63: return False return True def valid_string_length(label: Union[bytes, str], trailing_dot: bool) -> bool: if len(label) > (254 if trailing_dot else 253): return False return True def check_bidi(label: str, check_ltr: bool = False) -> bool: # Bidi rules should only be applied if string contains RTL characters bidi_label = False for (idx, cp) in enumerate(label, 1): direction = unicodedata.bidirectional(cp) if direction == '': # String likely comes from a newer version of Unicode raise IDNABidiError('Unknown directionality in label {} at position {}'.format(repr(label), idx)) if direction in ['R', 'AL', 'AN']: bidi_label = True if not bidi_label and not check_ltr: return True # Bidi rule 1 direction = unicodedata.bidirectional(label[0]) if direction in ['R', 'AL']: rtl = True elif direction == 'L': rtl = False else: raise IDNABidiError('First codepoint in label {} must be directionality L, R or AL'.format(repr(label))) valid_ending = False number_type = None # type: Optional[str] for (idx, cp) in enumerate(label, 1): direction = unicodedata.bidirectional(cp) if rtl: # Bidi rule 2 if not direction in ['R', 'AL', 'AN', 'EN', 'ES', 'CS', 'ET', 'ON', 'BN', 'NSM']: raise IDNABidiError('Invalid direction for codepoint at position {} in a right-to-left label'.format(idx)) # Bidi rule 3 if direction in ['R', 'AL', 'EN', 'AN']: valid_ending = True elif direction != 'NSM': valid_ending = False # Bidi rule 4 if direction in ['AN', 'EN']: if not number_type: number_type = direction else: if number_type != direction: raise IDNABidiError('Can not mix numeral types in a right-to-left label') else: # Bidi rule 5 if not direction in ['L', 'EN', 'ES', 'CS', 'ET', 'ON', 'BN', 'NSM']: raise IDNABidiError('Invalid direction for codepoint at position {} in a left-to-right label'.format(idx)) # Bidi rule 6 if direction in ['L', 'EN']: valid_ending = True elif direction != 'NSM': valid_ending = False if not valid_ending: raise IDNABidiError('Label ends with illegal codepoint directionality') return True def check_initial_combiner(label: str) -> bool: if unicodedata.category(label[0])[0] == 'M': raise IDNAError('Label begins with an illegal combining character') return True def check_hyphen_ok(label: str) -> bool: if label[2:4] == '--': raise IDNAError('Label has disallowed hyphens in 3rd and 4th position') if label[0] == '-' or label[-1] == '-': raise IDNAError('Label must not start or end with a hyphen') return True def check_nfc(label: str) -> None: if unicodedata.normalize('NFC', label) != label: raise IDNAError('Label must be in Normalization Form C') def valid_contextj(label: str, pos: int) -> bool: cp_value = ord(label[pos]) if cp_value == 0x200c: if pos > 0: if _combining_class(ord(label[pos - 1])) == _virama_combining_class: return True ok = False for i in range(pos-1, -1, -1): joining_type = idnadata.joining_types.get(ord(label[i])) if joining_type == ord('T'): continue if joining_type in [ord('L'), ord('D')]: ok = True break if not ok: return False ok = False for i in range(pos+1, len(label)): joining_type = idnadata.joining_types.get(ord(label[i])) if joining_type == ord('T'): continue if joining_type in [ord('R'), ord('D')]: ok = True break return ok if cp_value == 0x200d: if pos > 0: if _combining_class(ord(label[pos - 1])) == _virama_combining_class: return True return False else: return False def valid_contexto(label: str, pos: int, exception: bool = False) -> bool: cp_value = ord(label[pos]) if cp_value == 0x00b7: if 0 < pos < len(label)-1: if ord(label[pos - 1]) == 0x006c and ord(label[pos + 1]) == 0x006c: return True return False elif cp_value == 0x0375: if pos < len(label)-1 and len(label) > 1: return _is_script(label[pos + 1], 'Greek') return False elif cp_value == 0x05f3 or cp_value == 0x05f4: if pos > 0: return _is_script(label[pos - 1], 'Hebrew') return False elif cp_value == 0x30fb: for cp in label: if cp == '\u30fb': continue if _is_script(cp, 'Hiragana') or _is_script(cp, 'Katakana') or _is_script(cp, 'Han'): return True return False elif 0x660 <= cp_value <= 0x669: for cp in label: if 0x6f0 <= ord(cp) <= 0x06f9: return False return True elif 0x6f0 <= cp_value <= 0x6f9: for cp in label: if 0x660 <= ord(cp) <= 0x0669: return False return True return False def check_label(label: Union[str, bytes, bytearray]) -> None: if isinstance(label, (bytes, bytearray)): label = label.decode('utf-8') if len(label) == 0: raise IDNAError('Empty Label') check_nfc(label) check_hyphen_ok(label) check_initial_combiner(label) for (pos, cp) in enumerate(label): cp_value = ord(cp) if intranges_contain(cp_value, idnadata.codepoint_classes['PVALID']): continue elif intranges_contain(cp_value, idnadata.codepoint_classes['CONTEXTJ']): try: if not valid_contextj(label, pos): raise InvalidCodepointContext('Joiner {} not allowed at position {} in {}'.format( _unot(cp_value), pos+1, repr(label))) except ValueError: raise IDNAError('Unknown codepoint adjacent to joiner {} at position {} in {}'.format( _unot(cp_value), pos+1, repr(label))) elif intranges_contain(cp_value, idnadata.codepoint_classes['CONTEXTO']): if not valid_contexto(label, pos): raise InvalidCodepointContext('Codepoint {} not allowed at position {} in {}'.format(_unot(cp_value), pos+1, repr(label))) else: raise InvalidCodepoint('Codepoint {} at position {} of {} not allowed'.format(_unot(cp_value), pos+1, repr(label))) check_bidi(label) def alabel(label: str) -> bytes: try: label_bytes = label.encode('ascii') ulabel(label_bytes) if not valid_label_length(label_bytes): raise IDNAError('Label too long') return label_bytes except UnicodeEncodeError: pass if not label: raise IDNAError('No Input') label = str(label) check_label(label) label_bytes = _punycode(label) label_bytes = _alabel_prefix + label_bytes if not valid_label_length(label_bytes): raise IDNAError('Label too long') return label_bytes def ulabel(label: Union[str, bytes, bytearray]) -> str: if not isinstance(label, (bytes, bytearray)): try: label_bytes = label.encode('ascii') except UnicodeEncodeError: check_label(label) return label else: label_bytes = label label_bytes = label_bytes.lower() if label_bytes.startswith(_alabel_prefix): label_bytes = label_bytes[len(_alabel_prefix):] if not label_bytes: raise IDNAError('Malformed A-label, no Punycode eligible content found') if label_bytes.decode('ascii')[-1] == '-': raise IDNAError('A-label must not end with a hyphen') else: check_label(label_bytes) return label_bytes.decode('ascii') try: label = label_bytes.decode('punycode') except UnicodeError: raise IDNAError('Invalid A-label') check_label(label) return label def uts46_remap(domain: str, std3_rules: bool = True, transitional: bool = False) -> str: """Re-map the characters in the string according to UTS46 processing.""" from .uts46data import uts46data output = '' for pos, char in enumerate(domain): code_point = ord(char) try: uts46row = uts46data[code_point if code_point < 256 else bisect.bisect_left(uts46data, (code_point, 'Z')) - 1] status = uts46row[1] replacement = None # type: Optional[str] if len(uts46row) == 3: replacement = uts46row[2] # type: ignore if (status == 'V' or (status == 'D' and not transitional) or (status == '3' and not std3_rules and replacement is None)): output += char elif replacement is not None and (status == 'M' or (status == '3' and not std3_rules) or (status == 'D' and transitional)): output += replacement elif status != 'I': raise IndexError() except IndexError: raise InvalidCodepoint( 'Codepoint {} not allowed at position {} in {}'.format( _unot(code_point), pos + 1, repr(domain))) return unicodedata.normalize('NFC', output) def encode(s: Union[str, bytes, bytearray], strict: bool = False, uts46: bool = False, std3_rules: bool = False, transitional: bool = False) -> bytes: if isinstance(s, (bytes, bytearray)): try: s = s.decode('ascii') except UnicodeDecodeError: raise IDNAError('should pass a unicode string to the function rather than a byte string.') if uts46: s = uts46_remap(s, std3_rules, transitional) trailing_dot = False result = [] if strict: labels = s.split('.') else: labels = _unicode_dots_re.split(s) if not labels or labels == ['']: raise IDNAError('Empty domain') if labels[-1] == '': del labels[-1] trailing_dot = True for label in labels: s = alabel(label) if s: result.append(s) else: raise IDNAError('Empty label') if trailing_dot: result.append(b'') s = b'.'.join(result) if not valid_string_length(s, trailing_dot): raise IDNAError('Domain too long') return s def decode(s: Union[str, bytes, bytearray], strict: bool = False, uts46: bool = False, std3_rules: bool = False) -> str: try: if isinstance(s, (bytes, bytearray)): s = s.decode('ascii') except UnicodeDecodeError: raise IDNAError('Invalid ASCII in A-label') if uts46: s = uts46_remap(s, std3_rules, False) trailing_dot = False result = [] if not strict: labels = _unicode_dots_re.split(s) else: labels = s.split('.') if not labels or labels == ['']: raise IDNAError('Empty domain') if not labels[-1]: del labels[-1] trailing_dot = True for label in labels: s = ulabel(label) if s: result.append(s) else: raise IDNAError('Empty label') if trailing_dot: result.append('') return '.'.join(result)
12,950
Python
31.296758
150
0.569807
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/idna/codec.py
from .core import encode, decode, alabel, ulabel, IDNAError import codecs import re from typing import Tuple, Optional _unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]') class Codec(codecs.Codec): def encode(self, data: str, errors: str = 'strict') -> Tuple[bytes, int]: if errors != 'strict': raise IDNAError('Unsupported error handling \"{}\"'.format(errors)) if not data: return b"", 0 return encode(data), len(data) def decode(self, data: bytes, errors: str = 'strict') -> Tuple[str, int]: if errors != 'strict': raise IDNAError('Unsupported error handling \"{}\"'.format(errors)) if not data: return '', 0 return decode(data), len(data) class IncrementalEncoder(codecs.BufferedIncrementalEncoder): def _buffer_encode(self, data: str, errors: str, final: bool) -> Tuple[str, int]: # type: ignore if errors != 'strict': raise IDNAError('Unsupported error handling \"{}\"'.format(errors)) if not data: return "", 0 labels = _unicode_dots_re.split(data) trailing_dot = '' if labels: if not labels[-1]: trailing_dot = '.' del labels[-1] elif not final: # Keep potentially unfinished label until the next call del labels[-1] if labels: trailing_dot = '.' result = [] size = 0 for label in labels: result.append(alabel(label)) if size: size += 1 size += len(label) # Join with U+002E result_str = '.'.join(result) + trailing_dot # type: ignore size += len(trailing_dot) return result_str, size class IncrementalDecoder(codecs.BufferedIncrementalDecoder): def _buffer_decode(self, data: str, errors: str, final: bool) -> Tuple[str, int]: # type: ignore if errors != 'strict': raise IDNAError('Unsupported error handling \"{}\"'.format(errors)) if not data: return ('', 0) labels = _unicode_dots_re.split(data) trailing_dot = '' if labels: if not labels[-1]: trailing_dot = '.' del labels[-1] elif not final: # Keep potentially unfinished label until the next call del labels[-1] if labels: trailing_dot = '.' result = [] size = 0 for label in labels: result.append(ulabel(label)) if size: size += 1 size += len(label) result_str = '.'.join(result) + trailing_dot size += len(trailing_dot) return (result_str, size) class StreamWriter(Codec, codecs.StreamWriter): pass class StreamReader(Codec, codecs.StreamReader): pass def getregentry() -> codecs.CodecInfo: # Compatibility as a search_function for codecs.register() return codecs.CodecInfo( name='idna', encode=Codec().encode, # type: ignore decode=Codec().decode, # type: ignore incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamwriter=StreamWriter, streamreader=StreamReader, )
3,374
Python
28.867256
101
0.553053
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/idna/package_data.py
__version__ = '3.4'
21
Python
6.333331
19
0.428571
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/idna/idnadata.py
# This file is automatically generated by tools/idna-data __version__ = '15.0.0' scripts = { 'Greek': ( 0x37000000374, 0x37500000378, 0x37a0000037e, 0x37f00000380, 0x38400000385, 0x38600000387, 0x3880000038b, 0x38c0000038d, 0x38e000003a2, 0x3a3000003e2, 0x3f000000400, 0x1d2600001d2b, 0x1d5d00001d62, 0x1d6600001d6b, 0x1dbf00001dc0, 0x1f0000001f16, 0x1f1800001f1e, 0x1f2000001f46, 0x1f4800001f4e, 0x1f5000001f58, 0x1f5900001f5a, 0x1f5b00001f5c, 0x1f5d00001f5e, 0x1f5f00001f7e, 0x1f8000001fb5, 0x1fb600001fc5, 0x1fc600001fd4, 0x1fd600001fdc, 0x1fdd00001ff0, 0x1ff200001ff5, 0x1ff600001fff, 0x212600002127, 0xab650000ab66, 0x101400001018f, 0x101a0000101a1, 0x1d2000001d246, ), 'Han': ( 0x2e8000002e9a, 0x2e9b00002ef4, 0x2f0000002fd6, 0x300500003006, 0x300700003008, 0x30210000302a, 0x30380000303c, 0x340000004dc0, 0x4e000000a000, 0xf9000000fa6e, 0xfa700000fada, 0x16fe200016fe4, 0x16ff000016ff2, 0x200000002a6e0, 0x2a7000002b73a, 0x2b7400002b81e, 0x2b8200002cea2, 0x2ceb00002ebe1, 0x2f8000002fa1e, 0x300000003134b, 0x31350000323b0, ), 'Hebrew': ( 0x591000005c8, 0x5d0000005eb, 0x5ef000005f5, 0xfb1d0000fb37, 0xfb380000fb3d, 0xfb3e0000fb3f, 0xfb400000fb42, 0xfb430000fb45, 0xfb460000fb50, ), 'Hiragana': ( 0x304100003097, 0x309d000030a0, 0x1b0010001b120, 0x1b1320001b133, 0x1b1500001b153, 0x1f2000001f201, ), 'Katakana': ( 0x30a1000030fb, 0x30fd00003100, 0x31f000003200, 0x32d0000032ff, 0x330000003358, 0xff660000ff70, 0xff710000ff9e, 0x1aff00001aff4, 0x1aff50001affc, 0x1affd0001afff, 0x1b0000001b001, 0x1b1200001b123, 0x1b1550001b156, 0x1b1640001b168, ), } joining_types = { 0x600: 85, 0x601: 85, 0x602: 85, 0x603: 85, 0x604: 85, 0x605: 85, 0x608: 85, 0x60b: 85, 0x620: 68, 0x621: 85, 0x622: 82, 0x623: 82, 0x624: 82, 0x625: 82, 0x626: 68, 0x627: 82, 0x628: 68, 0x629: 82, 0x62a: 68, 0x62b: 68, 0x62c: 68, 0x62d: 68, 0x62e: 68, 0x62f: 82, 0x630: 82, 0x631: 82, 0x632: 82, 0x633: 68, 0x634: 68, 0x635: 68, 0x636: 68, 0x637: 68, 0x638: 68, 0x639: 68, 0x63a: 68, 0x63b: 68, 0x63c: 68, 0x63d: 68, 0x63e: 68, 0x63f: 68, 0x640: 67, 0x641: 68, 0x642: 68, 0x643: 68, 0x644: 68, 0x645: 68, 0x646: 68, 0x647: 68, 0x648: 82, 0x649: 68, 0x64a: 68, 0x66e: 68, 0x66f: 68, 0x671: 82, 0x672: 82, 0x673: 82, 0x674: 85, 0x675: 82, 0x676: 82, 0x677: 82, 0x678: 68, 0x679: 68, 0x67a: 68, 0x67b: 68, 0x67c: 68, 0x67d: 68, 0x67e: 68, 0x67f: 68, 0x680: 68, 0x681: 68, 0x682: 68, 0x683: 68, 0x684: 68, 0x685: 68, 0x686: 68, 0x687: 68, 0x688: 82, 0x689: 82, 0x68a: 82, 0x68b: 82, 0x68c: 82, 0x68d: 82, 0x68e: 82, 0x68f: 82, 0x690: 82, 0x691: 82, 0x692: 82, 0x693: 82, 0x694: 82, 0x695: 82, 0x696: 82, 0x697: 82, 0x698: 82, 0x699: 82, 0x69a: 68, 0x69b: 68, 0x69c: 68, 0x69d: 68, 0x69e: 68, 0x69f: 68, 0x6a0: 68, 0x6a1: 68, 0x6a2: 68, 0x6a3: 68, 0x6a4: 68, 0x6a5: 68, 0x6a6: 68, 0x6a7: 68, 0x6a8: 68, 0x6a9: 68, 0x6aa: 68, 0x6ab: 68, 0x6ac: 68, 0x6ad: 68, 0x6ae: 68, 0x6af: 68, 0x6b0: 68, 0x6b1: 68, 0x6b2: 68, 0x6b3: 68, 0x6b4: 68, 0x6b5: 68, 0x6b6: 68, 0x6b7: 68, 0x6b8: 68, 0x6b9: 68, 0x6ba: 68, 0x6bb: 68, 0x6bc: 68, 0x6bd: 68, 0x6be: 68, 0x6bf: 68, 0x6c0: 82, 0x6c1: 68, 0x6c2: 68, 0x6c3: 82, 0x6c4: 82, 0x6c5: 82, 0x6c6: 82, 0x6c7: 82, 0x6c8: 82, 0x6c9: 82, 0x6ca: 82, 0x6cb: 82, 0x6cc: 68, 0x6cd: 82, 0x6ce: 68, 0x6cf: 82, 0x6d0: 68, 0x6d1: 68, 0x6d2: 82, 0x6d3: 82, 0x6d5: 82, 0x6dd: 85, 0x6ee: 82, 0x6ef: 82, 0x6fa: 68, 0x6fb: 68, 0x6fc: 68, 0x6ff: 68, 0x70f: 84, 0x710: 82, 0x712: 68, 0x713: 68, 0x714: 68, 0x715: 82, 0x716: 82, 0x717: 82, 0x718: 82, 0x719: 82, 0x71a: 68, 0x71b: 68, 0x71c: 68, 0x71d: 68, 0x71e: 82, 0x71f: 68, 0x720: 68, 0x721: 68, 0x722: 68, 0x723: 68, 0x724: 68, 0x725: 68, 0x726: 68, 0x727: 68, 0x728: 82, 0x729: 68, 0x72a: 82, 0x72b: 68, 0x72c: 82, 0x72d: 68, 0x72e: 68, 0x72f: 82, 0x74d: 82, 0x74e: 68, 0x74f: 68, 0x750: 68, 0x751: 68, 0x752: 68, 0x753: 68, 0x754: 68, 0x755: 68, 0x756: 68, 0x757: 68, 0x758: 68, 0x759: 82, 0x75a: 82, 0x75b: 82, 0x75c: 68, 0x75d: 68, 0x75e: 68, 0x75f: 68, 0x760: 68, 0x761: 68, 0x762: 68, 0x763: 68, 0x764: 68, 0x765: 68, 0x766: 68, 0x767: 68, 0x768: 68, 0x769: 68, 0x76a: 68, 0x76b: 82, 0x76c: 82, 0x76d: 68, 0x76e: 68, 0x76f: 68, 0x770: 68, 0x771: 82, 0x772: 68, 0x773: 82, 0x774: 82, 0x775: 68, 0x776: 68, 0x777: 68, 0x778: 82, 0x779: 82, 0x77a: 68, 0x77b: 68, 0x77c: 68, 0x77d: 68, 0x77e: 68, 0x77f: 68, 0x7ca: 68, 0x7cb: 68, 0x7cc: 68, 0x7cd: 68, 0x7ce: 68, 0x7cf: 68, 0x7d0: 68, 0x7d1: 68, 0x7d2: 68, 0x7d3: 68, 0x7d4: 68, 0x7d5: 68, 0x7d6: 68, 0x7d7: 68, 0x7d8: 68, 0x7d9: 68, 0x7da: 68, 0x7db: 68, 0x7dc: 68, 0x7dd: 68, 0x7de: 68, 0x7df: 68, 0x7e0: 68, 0x7e1: 68, 0x7e2: 68, 0x7e3: 68, 0x7e4: 68, 0x7e5: 68, 0x7e6: 68, 0x7e7: 68, 0x7e8: 68, 0x7e9: 68, 0x7ea: 68, 0x7fa: 67, 0x840: 82, 0x841: 68, 0x842: 68, 0x843: 68, 0x844: 68, 0x845: 68, 0x846: 82, 0x847: 82, 0x848: 68, 0x849: 82, 0x84a: 68, 0x84b: 68, 0x84c: 68, 0x84d: 68, 0x84e: 68, 0x84f: 68, 0x850: 68, 0x851: 68, 0x852: 68, 0x853: 68, 0x854: 82, 0x855: 68, 0x856: 82, 0x857: 82, 0x858: 82, 0x860: 68, 0x861: 85, 0x862: 68, 0x863: 68, 0x864: 68, 0x865: 68, 0x866: 85, 0x867: 82, 0x868: 68, 0x869: 82, 0x86a: 82, 0x870: 82, 0x871: 82, 0x872: 82, 0x873: 82, 0x874: 82, 0x875: 82, 0x876: 82, 0x877: 82, 0x878: 82, 0x879: 82, 0x87a: 82, 0x87b: 82, 0x87c: 82, 0x87d: 82, 0x87e: 82, 0x87f: 82, 0x880: 82, 0x881: 82, 0x882: 82, 0x883: 67, 0x884: 67, 0x885: 67, 0x886: 68, 0x887: 85, 0x888: 85, 0x889: 68, 0x88a: 68, 0x88b: 68, 0x88c: 68, 0x88d: 68, 0x88e: 82, 0x890: 85, 0x891: 85, 0x8a0: 68, 0x8a1: 68, 0x8a2: 68, 0x8a3: 68, 0x8a4: 68, 0x8a5: 68, 0x8a6: 68, 0x8a7: 68, 0x8a8: 68, 0x8a9: 68, 0x8aa: 82, 0x8ab: 82, 0x8ac: 82, 0x8ad: 85, 0x8ae: 82, 0x8af: 68, 0x8b0: 68, 0x8b1: 82, 0x8b2: 82, 0x8b3: 68, 0x8b4: 68, 0x8b5: 68, 0x8b6: 68, 0x8b7: 68, 0x8b8: 68, 0x8b9: 82, 0x8ba: 68, 0x8bb: 68, 0x8bc: 68, 0x8bd: 68, 0x8be: 68, 0x8bf: 68, 0x8c0: 68, 0x8c1: 68, 0x8c2: 68, 0x8c3: 68, 0x8c4: 68, 0x8c5: 68, 0x8c6: 68, 0x8c7: 68, 0x8c8: 68, 0x8e2: 85, 0x1806: 85, 0x1807: 68, 0x180a: 67, 0x180e: 85, 0x1820: 68, 0x1821: 68, 0x1822: 68, 0x1823: 68, 0x1824: 68, 0x1825: 68, 0x1826: 68, 0x1827: 68, 0x1828: 68, 0x1829: 68, 0x182a: 68, 0x182b: 68, 0x182c: 68, 0x182d: 68, 0x182e: 68, 0x182f: 68, 0x1830: 68, 0x1831: 68, 0x1832: 68, 0x1833: 68, 0x1834: 68, 0x1835: 68, 0x1836: 68, 0x1837: 68, 0x1838: 68, 0x1839: 68, 0x183a: 68, 0x183b: 68, 0x183c: 68, 0x183d: 68, 0x183e: 68, 0x183f: 68, 0x1840: 68, 0x1841: 68, 0x1842: 68, 0x1843: 68, 0x1844: 68, 0x1845: 68, 0x1846: 68, 0x1847: 68, 0x1848: 68, 0x1849: 68, 0x184a: 68, 0x184b: 68, 0x184c: 68, 0x184d: 68, 0x184e: 68, 0x184f: 68, 0x1850: 68, 0x1851: 68, 0x1852: 68, 0x1853: 68, 0x1854: 68, 0x1855: 68, 0x1856: 68, 0x1857: 68, 0x1858: 68, 0x1859: 68, 0x185a: 68, 0x185b: 68, 0x185c: 68, 0x185d: 68, 0x185e: 68, 0x185f: 68, 0x1860: 68, 0x1861: 68, 0x1862: 68, 0x1863: 68, 0x1864: 68, 0x1865: 68, 0x1866: 68, 0x1867: 68, 0x1868: 68, 0x1869: 68, 0x186a: 68, 0x186b: 68, 0x186c: 68, 0x186d: 68, 0x186e: 68, 0x186f: 68, 0x1870: 68, 0x1871: 68, 0x1872: 68, 0x1873: 68, 0x1874: 68, 0x1875: 68, 0x1876: 68, 0x1877: 68, 0x1878: 68, 0x1880: 85, 0x1881: 85, 0x1882: 85, 0x1883: 85, 0x1884: 85, 0x1885: 84, 0x1886: 84, 0x1887: 68, 0x1888: 68, 0x1889: 68, 0x188a: 68, 0x188b: 68, 0x188c: 68, 0x188d: 68, 0x188e: 68, 0x188f: 68, 0x1890: 68, 0x1891: 68, 0x1892: 68, 0x1893: 68, 0x1894: 68, 0x1895: 68, 0x1896: 68, 0x1897: 68, 0x1898: 68, 0x1899: 68, 0x189a: 68, 0x189b: 68, 0x189c: 68, 0x189d: 68, 0x189e: 68, 0x189f: 68, 0x18a0: 68, 0x18a1: 68, 0x18a2: 68, 0x18a3: 68, 0x18a4: 68, 0x18a5: 68, 0x18a6: 68, 0x18a7: 68, 0x18a8: 68, 0x18aa: 68, 0x200c: 85, 0x200d: 67, 0x202f: 85, 0x2066: 85, 0x2067: 85, 0x2068: 85, 0x2069: 85, 0xa840: 68, 0xa841: 68, 0xa842: 68, 0xa843: 68, 0xa844: 68, 0xa845: 68, 0xa846: 68, 0xa847: 68, 0xa848: 68, 0xa849: 68, 0xa84a: 68, 0xa84b: 68, 0xa84c: 68, 0xa84d: 68, 0xa84e: 68, 0xa84f: 68, 0xa850: 68, 0xa851: 68, 0xa852: 68, 0xa853: 68, 0xa854: 68, 0xa855: 68, 0xa856: 68, 0xa857: 68, 0xa858: 68, 0xa859: 68, 0xa85a: 68, 0xa85b: 68, 0xa85c: 68, 0xa85d: 68, 0xa85e: 68, 0xa85f: 68, 0xa860: 68, 0xa861: 68, 0xa862: 68, 0xa863: 68, 0xa864: 68, 0xa865: 68, 0xa866: 68, 0xa867: 68, 0xa868: 68, 0xa869: 68, 0xa86a: 68, 0xa86b: 68, 0xa86c: 68, 0xa86d: 68, 0xa86e: 68, 0xa86f: 68, 0xa870: 68, 0xa871: 68, 0xa872: 76, 0xa873: 85, 0x10ac0: 68, 0x10ac1: 68, 0x10ac2: 68, 0x10ac3: 68, 0x10ac4: 68, 0x10ac5: 82, 0x10ac6: 85, 0x10ac7: 82, 0x10ac8: 85, 0x10ac9: 82, 0x10aca: 82, 0x10acb: 85, 0x10acc: 85, 0x10acd: 76, 0x10ace: 82, 0x10acf: 82, 0x10ad0: 82, 0x10ad1: 82, 0x10ad2: 82, 0x10ad3: 68, 0x10ad4: 68, 0x10ad5: 68, 0x10ad6: 68, 0x10ad7: 76, 0x10ad8: 68, 0x10ad9: 68, 0x10ada: 68, 0x10adb: 68, 0x10adc: 68, 0x10add: 82, 0x10ade: 68, 0x10adf: 68, 0x10ae0: 68, 0x10ae1: 82, 0x10ae2: 85, 0x10ae3: 85, 0x10ae4: 82, 0x10aeb: 68, 0x10aec: 68, 0x10aed: 68, 0x10aee: 68, 0x10aef: 82, 0x10b80: 68, 0x10b81: 82, 0x10b82: 68, 0x10b83: 82, 0x10b84: 82, 0x10b85: 82, 0x10b86: 68, 0x10b87: 68, 0x10b88: 68, 0x10b89: 82, 0x10b8a: 68, 0x10b8b: 68, 0x10b8c: 82, 0x10b8d: 68, 0x10b8e: 82, 0x10b8f: 82, 0x10b90: 68, 0x10b91: 82, 0x10ba9: 82, 0x10baa: 82, 0x10bab: 82, 0x10bac: 82, 0x10bad: 68, 0x10bae: 68, 0x10baf: 85, 0x10d00: 76, 0x10d01: 68, 0x10d02: 68, 0x10d03: 68, 0x10d04: 68, 0x10d05: 68, 0x10d06: 68, 0x10d07: 68, 0x10d08: 68, 0x10d09: 68, 0x10d0a: 68, 0x10d0b: 68, 0x10d0c: 68, 0x10d0d: 68, 0x10d0e: 68, 0x10d0f: 68, 0x10d10: 68, 0x10d11: 68, 0x10d12: 68, 0x10d13: 68, 0x10d14: 68, 0x10d15: 68, 0x10d16: 68, 0x10d17: 68, 0x10d18: 68, 0x10d19: 68, 0x10d1a: 68, 0x10d1b: 68, 0x10d1c: 68, 0x10d1d: 68, 0x10d1e: 68, 0x10d1f: 68, 0x10d20: 68, 0x10d21: 68, 0x10d22: 82, 0x10d23: 68, 0x10f30: 68, 0x10f31: 68, 0x10f32: 68, 0x10f33: 82, 0x10f34: 68, 0x10f35: 68, 0x10f36: 68, 0x10f37: 68, 0x10f38: 68, 0x10f39: 68, 0x10f3a: 68, 0x10f3b: 68, 0x10f3c: 68, 0x10f3d: 68, 0x10f3e: 68, 0x10f3f: 68, 0x10f40: 68, 0x10f41: 68, 0x10f42: 68, 0x10f43: 68, 0x10f44: 68, 0x10f45: 85, 0x10f51: 68, 0x10f52: 68, 0x10f53: 68, 0x10f54: 82, 0x10f70: 68, 0x10f71: 68, 0x10f72: 68, 0x10f73: 68, 0x10f74: 82, 0x10f75: 82, 0x10f76: 68, 0x10f77: 68, 0x10f78: 68, 0x10f79: 68, 0x10f7a: 68, 0x10f7b: 68, 0x10f7c: 68, 0x10f7d: 68, 0x10f7e: 68, 0x10f7f: 68, 0x10f80: 68, 0x10f81: 68, 0x10fb0: 68, 0x10fb1: 85, 0x10fb2: 68, 0x10fb3: 68, 0x10fb4: 82, 0x10fb5: 82, 0x10fb6: 82, 0x10fb7: 85, 0x10fb8: 68, 0x10fb9: 82, 0x10fba: 82, 0x10fbb: 68, 0x10fbc: 68, 0x10fbd: 82, 0x10fbe: 68, 0x10fbf: 68, 0x10fc0: 85, 0x10fc1: 68, 0x10fc2: 82, 0x10fc3: 82, 0x10fc4: 68, 0x10fc5: 85, 0x10fc6: 85, 0x10fc7: 85, 0x10fc8: 85, 0x10fc9: 82, 0x10fca: 68, 0x10fcb: 76, 0x110bd: 85, 0x110cd: 85, 0x1e900: 68, 0x1e901: 68, 0x1e902: 68, 0x1e903: 68, 0x1e904: 68, 0x1e905: 68, 0x1e906: 68, 0x1e907: 68, 0x1e908: 68, 0x1e909: 68, 0x1e90a: 68, 0x1e90b: 68, 0x1e90c: 68, 0x1e90d: 68, 0x1e90e: 68, 0x1e90f: 68, 0x1e910: 68, 0x1e911: 68, 0x1e912: 68, 0x1e913: 68, 0x1e914: 68, 0x1e915: 68, 0x1e916: 68, 0x1e917: 68, 0x1e918: 68, 0x1e919: 68, 0x1e91a: 68, 0x1e91b: 68, 0x1e91c: 68, 0x1e91d: 68, 0x1e91e: 68, 0x1e91f: 68, 0x1e920: 68, 0x1e921: 68, 0x1e922: 68, 0x1e923: 68, 0x1e924: 68, 0x1e925: 68, 0x1e926: 68, 0x1e927: 68, 0x1e928: 68, 0x1e929: 68, 0x1e92a: 68, 0x1e92b: 68, 0x1e92c: 68, 0x1e92d: 68, 0x1e92e: 68, 0x1e92f: 68, 0x1e930: 68, 0x1e931: 68, 0x1e932: 68, 0x1e933: 68, 0x1e934: 68, 0x1e935: 68, 0x1e936: 68, 0x1e937: 68, 0x1e938: 68, 0x1e939: 68, 0x1e93a: 68, 0x1e93b: 68, 0x1e93c: 68, 0x1e93d: 68, 0x1e93e: 68, 0x1e93f: 68, 0x1e940: 68, 0x1e941: 68, 0x1e942: 68, 0x1e943: 68, 0x1e94b: 84, } codepoint_classes = { 'PVALID': ( 0x2d0000002e, 0x300000003a, 0x610000007b, 0xdf000000f7, 0xf800000100, 0x10100000102, 0x10300000104, 0x10500000106, 0x10700000108, 0x1090000010a, 0x10b0000010c, 0x10d0000010e, 0x10f00000110, 0x11100000112, 0x11300000114, 0x11500000116, 0x11700000118, 0x1190000011a, 0x11b0000011c, 0x11d0000011e, 0x11f00000120, 0x12100000122, 0x12300000124, 0x12500000126, 0x12700000128, 0x1290000012a, 0x12b0000012c, 0x12d0000012e, 0x12f00000130, 0x13100000132, 0x13500000136, 0x13700000139, 0x13a0000013b, 0x13c0000013d, 0x13e0000013f, 0x14200000143, 0x14400000145, 0x14600000147, 0x14800000149, 0x14b0000014c, 0x14d0000014e, 0x14f00000150, 0x15100000152, 0x15300000154, 0x15500000156, 0x15700000158, 0x1590000015a, 0x15b0000015c, 0x15d0000015e, 0x15f00000160, 0x16100000162, 0x16300000164, 0x16500000166, 0x16700000168, 0x1690000016a, 0x16b0000016c, 0x16d0000016e, 0x16f00000170, 0x17100000172, 0x17300000174, 0x17500000176, 0x17700000178, 0x17a0000017b, 0x17c0000017d, 0x17e0000017f, 0x18000000181, 0x18300000184, 0x18500000186, 0x18800000189, 0x18c0000018e, 0x19200000193, 0x19500000196, 0x1990000019c, 0x19e0000019f, 0x1a1000001a2, 0x1a3000001a4, 0x1a5000001a6, 0x1a8000001a9, 0x1aa000001ac, 0x1ad000001ae, 0x1b0000001b1, 0x1b4000001b5, 0x1b6000001b7, 0x1b9000001bc, 0x1bd000001c4, 0x1ce000001cf, 0x1d0000001d1, 0x1d2000001d3, 0x1d4000001d5, 0x1d6000001d7, 0x1d8000001d9, 0x1da000001db, 0x1dc000001de, 0x1df000001e0, 0x1e1000001e2, 0x1e3000001e4, 0x1e5000001e6, 0x1e7000001e8, 0x1e9000001ea, 0x1eb000001ec, 0x1ed000001ee, 0x1ef000001f1, 0x1f5000001f6, 0x1f9000001fa, 0x1fb000001fc, 0x1fd000001fe, 0x1ff00000200, 0x20100000202, 0x20300000204, 0x20500000206, 0x20700000208, 0x2090000020a, 0x20b0000020c, 0x20d0000020e, 0x20f00000210, 0x21100000212, 0x21300000214, 0x21500000216, 0x21700000218, 0x2190000021a, 0x21b0000021c, 0x21d0000021e, 0x21f00000220, 0x22100000222, 0x22300000224, 0x22500000226, 0x22700000228, 0x2290000022a, 0x22b0000022c, 0x22d0000022e, 0x22f00000230, 0x23100000232, 0x2330000023a, 0x23c0000023d, 0x23f00000241, 0x24200000243, 0x24700000248, 0x2490000024a, 0x24b0000024c, 0x24d0000024e, 0x24f000002b0, 0x2b9000002c2, 0x2c6000002d2, 0x2ec000002ed, 0x2ee000002ef, 0x30000000340, 0x34200000343, 0x3460000034f, 0x35000000370, 0x37100000372, 0x37300000374, 0x37700000378, 0x37b0000037e, 0x39000000391, 0x3ac000003cf, 0x3d7000003d8, 0x3d9000003da, 0x3db000003dc, 0x3dd000003de, 0x3df000003e0, 0x3e1000003e2, 0x3e3000003e4, 0x3e5000003e6, 0x3e7000003e8, 0x3e9000003ea, 0x3eb000003ec, 0x3ed000003ee, 0x3ef000003f0, 0x3f3000003f4, 0x3f8000003f9, 0x3fb000003fd, 0x43000000460, 0x46100000462, 0x46300000464, 0x46500000466, 0x46700000468, 0x4690000046a, 0x46b0000046c, 0x46d0000046e, 0x46f00000470, 0x47100000472, 0x47300000474, 0x47500000476, 0x47700000478, 0x4790000047a, 0x47b0000047c, 0x47d0000047e, 0x47f00000480, 0x48100000482, 0x48300000488, 0x48b0000048c, 0x48d0000048e, 0x48f00000490, 0x49100000492, 0x49300000494, 0x49500000496, 0x49700000498, 0x4990000049a, 0x49b0000049c, 0x49d0000049e, 0x49f000004a0, 0x4a1000004a2, 0x4a3000004a4, 0x4a5000004a6, 0x4a7000004a8, 0x4a9000004aa, 0x4ab000004ac, 0x4ad000004ae, 0x4af000004b0, 0x4b1000004b2, 0x4b3000004b4, 0x4b5000004b6, 0x4b7000004b8, 0x4b9000004ba, 0x4bb000004bc, 0x4bd000004be, 0x4bf000004c0, 0x4c2000004c3, 0x4c4000004c5, 0x4c6000004c7, 0x4c8000004c9, 0x4ca000004cb, 0x4cc000004cd, 0x4ce000004d0, 0x4d1000004d2, 0x4d3000004d4, 0x4d5000004d6, 0x4d7000004d8, 0x4d9000004da, 0x4db000004dc, 0x4dd000004de, 0x4df000004e0, 0x4e1000004e2, 0x4e3000004e4, 0x4e5000004e6, 0x4e7000004e8, 0x4e9000004ea, 0x4eb000004ec, 0x4ed000004ee, 0x4ef000004f0, 0x4f1000004f2, 0x4f3000004f4, 0x4f5000004f6, 0x4f7000004f8, 0x4f9000004fa, 0x4fb000004fc, 0x4fd000004fe, 0x4ff00000500, 0x50100000502, 0x50300000504, 0x50500000506, 0x50700000508, 0x5090000050a, 0x50b0000050c, 0x50d0000050e, 0x50f00000510, 0x51100000512, 0x51300000514, 0x51500000516, 0x51700000518, 0x5190000051a, 0x51b0000051c, 0x51d0000051e, 0x51f00000520, 0x52100000522, 0x52300000524, 0x52500000526, 0x52700000528, 0x5290000052a, 0x52b0000052c, 0x52d0000052e, 0x52f00000530, 0x5590000055a, 0x56000000587, 0x58800000589, 0x591000005be, 0x5bf000005c0, 0x5c1000005c3, 0x5c4000005c6, 0x5c7000005c8, 0x5d0000005eb, 0x5ef000005f3, 0x6100000061b, 0x62000000640, 0x64100000660, 0x66e00000675, 0x679000006d4, 0x6d5000006dd, 0x6df000006e9, 0x6ea000006f0, 0x6fa00000700, 0x7100000074b, 0x74d000007b2, 0x7c0000007f6, 0x7fd000007fe, 0x8000000082e, 0x8400000085c, 0x8600000086b, 0x87000000888, 0x8890000088f, 0x898000008e2, 0x8e300000958, 0x96000000964, 0x96600000970, 0x97100000984, 0x9850000098d, 0x98f00000991, 0x993000009a9, 0x9aa000009b1, 0x9b2000009b3, 0x9b6000009ba, 0x9bc000009c5, 0x9c7000009c9, 0x9cb000009cf, 0x9d7000009d8, 0x9e0000009e4, 0x9e6000009f2, 0x9fc000009fd, 0x9fe000009ff, 0xa0100000a04, 0xa0500000a0b, 0xa0f00000a11, 0xa1300000a29, 0xa2a00000a31, 0xa3200000a33, 0xa3500000a36, 0xa3800000a3a, 0xa3c00000a3d, 0xa3e00000a43, 0xa4700000a49, 0xa4b00000a4e, 0xa5100000a52, 0xa5c00000a5d, 0xa6600000a76, 0xa8100000a84, 0xa8500000a8e, 0xa8f00000a92, 0xa9300000aa9, 0xaaa00000ab1, 0xab200000ab4, 0xab500000aba, 0xabc00000ac6, 0xac700000aca, 0xacb00000ace, 0xad000000ad1, 0xae000000ae4, 0xae600000af0, 0xaf900000b00, 0xb0100000b04, 0xb0500000b0d, 0xb0f00000b11, 0xb1300000b29, 0xb2a00000b31, 0xb3200000b34, 0xb3500000b3a, 0xb3c00000b45, 0xb4700000b49, 0xb4b00000b4e, 0xb5500000b58, 0xb5f00000b64, 0xb6600000b70, 0xb7100000b72, 0xb8200000b84, 0xb8500000b8b, 0xb8e00000b91, 0xb9200000b96, 0xb9900000b9b, 0xb9c00000b9d, 0xb9e00000ba0, 0xba300000ba5, 0xba800000bab, 0xbae00000bba, 0xbbe00000bc3, 0xbc600000bc9, 0xbca00000bce, 0xbd000000bd1, 0xbd700000bd8, 0xbe600000bf0, 0xc0000000c0d, 0xc0e00000c11, 0xc1200000c29, 0xc2a00000c3a, 0xc3c00000c45, 0xc4600000c49, 0xc4a00000c4e, 0xc5500000c57, 0xc5800000c5b, 0xc5d00000c5e, 0xc6000000c64, 0xc6600000c70, 0xc8000000c84, 0xc8500000c8d, 0xc8e00000c91, 0xc9200000ca9, 0xcaa00000cb4, 0xcb500000cba, 0xcbc00000cc5, 0xcc600000cc9, 0xcca00000cce, 0xcd500000cd7, 0xcdd00000cdf, 0xce000000ce4, 0xce600000cf0, 0xcf100000cf4, 0xd0000000d0d, 0xd0e00000d11, 0xd1200000d45, 0xd4600000d49, 0xd4a00000d4f, 0xd5400000d58, 0xd5f00000d64, 0xd6600000d70, 0xd7a00000d80, 0xd8100000d84, 0xd8500000d97, 0xd9a00000db2, 0xdb300000dbc, 0xdbd00000dbe, 0xdc000000dc7, 0xdca00000dcb, 0xdcf00000dd5, 0xdd600000dd7, 0xdd800000de0, 0xde600000df0, 0xdf200000df4, 0xe0100000e33, 0xe3400000e3b, 0xe4000000e4f, 0xe5000000e5a, 0xe8100000e83, 0xe8400000e85, 0xe8600000e8b, 0xe8c00000ea4, 0xea500000ea6, 0xea700000eb3, 0xeb400000ebe, 0xec000000ec5, 0xec600000ec7, 0xec800000ecf, 0xed000000eda, 0xede00000ee0, 0xf0000000f01, 0xf0b00000f0c, 0xf1800000f1a, 0xf2000000f2a, 0xf3500000f36, 0xf3700000f38, 0xf3900000f3a, 0xf3e00000f43, 0xf4400000f48, 0xf4900000f4d, 0xf4e00000f52, 0xf5300000f57, 0xf5800000f5c, 0xf5d00000f69, 0xf6a00000f6d, 0xf7100000f73, 0xf7400000f75, 0xf7a00000f81, 0xf8200000f85, 0xf8600000f93, 0xf9400000f98, 0xf9900000f9d, 0xf9e00000fa2, 0xfa300000fa7, 0xfa800000fac, 0xfad00000fb9, 0xfba00000fbd, 0xfc600000fc7, 0x10000000104a, 0x10500000109e, 0x10d0000010fb, 0x10fd00001100, 0x120000001249, 0x124a0000124e, 0x125000001257, 0x125800001259, 0x125a0000125e, 0x126000001289, 0x128a0000128e, 0x1290000012b1, 0x12b2000012b6, 0x12b8000012bf, 0x12c0000012c1, 0x12c2000012c6, 0x12c8000012d7, 0x12d800001311, 0x131200001316, 0x13180000135b, 0x135d00001360, 0x138000001390, 0x13a0000013f6, 0x14010000166d, 0x166f00001680, 0x16810000169b, 0x16a0000016eb, 0x16f1000016f9, 0x170000001716, 0x171f00001735, 0x174000001754, 0x17600000176d, 0x176e00001771, 0x177200001774, 0x1780000017b4, 0x17b6000017d4, 0x17d7000017d8, 0x17dc000017de, 0x17e0000017ea, 0x18100000181a, 0x182000001879, 0x1880000018ab, 0x18b0000018f6, 0x19000000191f, 0x19200000192c, 0x19300000193c, 0x19460000196e, 0x197000001975, 0x1980000019ac, 0x19b0000019ca, 0x19d0000019da, 0x1a0000001a1c, 0x1a2000001a5f, 0x1a6000001a7d, 0x1a7f00001a8a, 0x1a9000001a9a, 0x1aa700001aa8, 0x1ab000001abe, 0x1abf00001acf, 0x1b0000001b4d, 0x1b5000001b5a, 0x1b6b00001b74, 0x1b8000001bf4, 0x1c0000001c38, 0x1c4000001c4a, 0x1c4d00001c7e, 0x1cd000001cd3, 0x1cd400001cfb, 0x1d0000001d2c, 0x1d2f00001d30, 0x1d3b00001d3c, 0x1d4e00001d4f, 0x1d6b00001d78, 0x1d7900001d9b, 0x1dc000001e00, 0x1e0100001e02, 0x1e0300001e04, 0x1e0500001e06, 0x1e0700001e08, 0x1e0900001e0a, 0x1e0b00001e0c, 0x1e0d00001e0e, 0x1e0f00001e10, 0x1e1100001e12, 0x1e1300001e14, 0x1e1500001e16, 0x1e1700001e18, 0x1e1900001e1a, 0x1e1b00001e1c, 0x1e1d00001e1e, 0x1e1f00001e20, 0x1e2100001e22, 0x1e2300001e24, 0x1e2500001e26, 0x1e2700001e28, 0x1e2900001e2a, 0x1e2b00001e2c, 0x1e2d00001e2e, 0x1e2f00001e30, 0x1e3100001e32, 0x1e3300001e34, 0x1e3500001e36, 0x1e3700001e38, 0x1e3900001e3a, 0x1e3b00001e3c, 0x1e3d00001e3e, 0x1e3f00001e40, 0x1e4100001e42, 0x1e4300001e44, 0x1e4500001e46, 0x1e4700001e48, 0x1e4900001e4a, 0x1e4b00001e4c, 0x1e4d00001e4e, 0x1e4f00001e50, 0x1e5100001e52, 0x1e5300001e54, 0x1e5500001e56, 0x1e5700001e58, 0x1e5900001e5a, 0x1e5b00001e5c, 0x1e5d00001e5e, 0x1e5f00001e60, 0x1e6100001e62, 0x1e6300001e64, 0x1e6500001e66, 0x1e6700001e68, 0x1e6900001e6a, 0x1e6b00001e6c, 0x1e6d00001e6e, 0x1e6f00001e70, 0x1e7100001e72, 0x1e7300001e74, 0x1e7500001e76, 0x1e7700001e78, 0x1e7900001e7a, 0x1e7b00001e7c, 0x1e7d00001e7e, 0x1e7f00001e80, 0x1e8100001e82, 0x1e8300001e84, 0x1e8500001e86, 0x1e8700001e88, 0x1e8900001e8a, 0x1e8b00001e8c, 0x1e8d00001e8e, 0x1e8f00001e90, 0x1e9100001e92, 0x1e9300001e94, 0x1e9500001e9a, 0x1e9c00001e9e, 0x1e9f00001ea0, 0x1ea100001ea2, 0x1ea300001ea4, 0x1ea500001ea6, 0x1ea700001ea8, 0x1ea900001eaa, 0x1eab00001eac, 0x1ead00001eae, 0x1eaf00001eb0, 0x1eb100001eb2, 0x1eb300001eb4, 0x1eb500001eb6, 0x1eb700001eb8, 0x1eb900001eba, 0x1ebb00001ebc, 0x1ebd00001ebe, 0x1ebf00001ec0, 0x1ec100001ec2, 0x1ec300001ec4, 0x1ec500001ec6, 0x1ec700001ec8, 0x1ec900001eca, 0x1ecb00001ecc, 0x1ecd00001ece, 0x1ecf00001ed0, 0x1ed100001ed2, 0x1ed300001ed4, 0x1ed500001ed6, 0x1ed700001ed8, 0x1ed900001eda, 0x1edb00001edc, 0x1edd00001ede, 0x1edf00001ee0, 0x1ee100001ee2, 0x1ee300001ee4, 0x1ee500001ee6, 0x1ee700001ee8, 0x1ee900001eea, 0x1eeb00001eec, 0x1eed00001eee, 0x1eef00001ef0, 0x1ef100001ef2, 0x1ef300001ef4, 0x1ef500001ef6, 0x1ef700001ef8, 0x1ef900001efa, 0x1efb00001efc, 0x1efd00001efe, 0x1eff00001f08, 0x1f1000001f16, 0x1f2000001f28, 0x1f3000001f38, 0x1f4000001f46, 0x1f5000001f58, 0x1f6000001f68, 0x1f7000001f71, 0x1f7200001f73, 0x1f7400001f75, 0x1f7600001f77, 0x1f7800001f79, 0x1f7a00001f7b, 0x1f7c00001f7d, 0x1fb000001fb2, 0x1fb600001fb7, 0x1fc600001fc7, 0x1fd000001fd3, 0x1fd600001fd8, 0x1fe000001fe3, 0x1fe400001fe8, 0x1ff600001ff7, 0x214e0000214f, 0x218400002185, 0x2c3000002c60, 0x2c6100002c62, 0x2c6500002c67, 0x2c6800002c69, 0x2c6a00002c6b, 0x2c6c00002c6d, 0x2c7100002c72, 0x2c7300002c75, 0x2c7600002c7c, 0x2c8100002c82, 0x2c8300002c84, 0x2c8500002c86, 0x2c8700002c88, 0x2c8900002c8a, 0x2c8b00002c8c, 0x2c8d00002c8e, 0x2c8f00002c90, 0x2c9100002c92, 0x2c9300002c94, 0x2c9500002c96, 0x2c9700002c98, 0x2c9900002c9a, 0x2c9b00002c9c, 0x2c9d00002c9e, 0x2c9f00002ca0, 0x2ca100002ca2, 0x2ca300002ca4, 0x2ca500002ca6, 0x2ca700002ca8, 0x2ca900002caa, 0x2cab00002cac, 0x2cad00002cae, 0x2caf00002cb0, 0x2cb100002cb2, 0x2cb300002cb4, 0x2cb500002cb6, 0x2cb700002cb8, 0x2cb900002cba, 0x2cbb00002cbc, 0x2cbd00002cbe, 0x2cbf00002cc0, 0x2cc100002cc2, 0x2cc300002cc4, 0x2cc500002cc6, 0x2cc700002cc8, 0x2cc900002cca, 0x2ccb00002ccc, 0x2ccd00002cce, 0x2ccf00002cd0, 0x2cd100002cd2, 0x2cd300002cd4, 0x2cd500002cd6, 0x2cd700002cd8, 0x2cd900002cda, 0x2cdb00002cdc, 0x2cdd00002cde, 0x2cdf00002ce0, 0x2ce100002ce2, 0x2ce300002ce5, 0x2cec00002ced, 0x2cee00002cf2, 0x2cf300002cf4, 0x2d0000002d26, 0x2d2700002d28, 0x2d2d00002d2e, 0x2d3000002d68, 0x2d7f00002d97, 0x2da000002da7, 0x2da800002daf, 0x2db000002db7, 0x2db800002dbf, 0x2dc000002dc7, 0x2dc800002dcf, 0x2dd000002dd7, 0x2dd800002ddf, 0x2de000002e00, 0x2e2f00002e30, 0x300500003008, 0x302a0000302e, 0x303c0000303d, 0x304100003097, 0x30990000309b, 0x309d0000309f, 0x30a1000030fb, 0x30fc000030ff, 0x310500003130, 0x31a0000031c0, 0x31f000003200, 0x340000004dc0, 0x4e000000a48d, 0xa4d00000a4fe, 0xa5000000a60d, 0xa6100000a62c, 0xa6410000a642, 0xa6430000a644, 0xa6450000a646, 0xa6470000a648, 0xa6490000a64a, 0xa64b0000a64c, 0xa64d0000a64e, 0xa64f0000a650, 0xa6510000a652, 0xa6530000a654, 0xa6550000a656, 0xa6570000a658, 0xa6590000a65a, 0xa65b0000a65c, 0xa65d0000a65e, 0xa65f0000a660, 0xa6610000a662, 0xa6630000a664, 0xa6650000a666, 0xa6670000a668, 0xa6690000a66a, 0xa66b0000a66c, 0xa66d0000a670, 0xa6740000a67e, 0xa67f0000a680, 0xa6810000a682, 0xa6830000a684, 0xa6850000a686, 0xa6870000a688, 0xa6890000a68a, 0xa68b0000a68c, 0xa68d0000a68e, 0xa68f0000a690, 0xa6910000a692, 0xa6930000a694, 0xa6950000a696, 0xa6970000a698, 0xa6990000a69a, 0xa69b0000a69c, 0xa69e0000a6e6, 0xa6f00000a6f2, 0xa7170000a720, 0xa7230000a724, 0xa7250000a726, 0xa7270000a728, 0xa7290000a72a, 0xa72b0000a72c, 0xa72d0000a72e, 0xa72f0000a732, 0xa7330000a734, 0xa7350000a736, 0xa7370000a738, 0xa7390000a73a, 0xa73b0000a73c, 0xa73d0000a73e, 0xa73f0000a740, 0xa7410000a742, 0xa7430000a744, 0xa7450000a746, 0xa7470000a748, 0xa7490000a74a, 0xa74b0000a74c, 0xa74d0000a74e, 0xa74f0000a750, 0xa7510000a752, 0xa7530000a754, 0xa7550000a756, 0xa7570000a758, 0xa7590000a75a, 0xa75b0000a75c, 0xa75d0000a75e, 0xa75f0000a760, 0xa7610000a762, 0xa7630000a764, 0xa7650000a766, 0xa7670000a768, 0xa7690000a76a, 0xa76b0000a76c, 0xa76d0000a76e, 0xa76f0000a770, 0xa7710000a779, 0xa77a0000a77b, 0xa77c0000a77d, 0xa77f0000a780, 0xa7810000a782, 0xa7830000a784, 0xa7850000a786, 0xa7870000a789, 0xa78c0000a78d, 0xa78e0000a790, 0xa7910000a792, 0xa7930000a796, 0xa7970000a798, 0xa7990000a79a, 0xa79b0000a79c, 0xa79d0000a79e, 0xa79f0000a7a0, 0xa7a10000a7a2, 0xa7a30000a7a4, 0xa7a50000a7a6, 0xa7a70000a7a8, 0xa7a90000a7aa, 0xa7af0000a7b0, 0xa7b50000a7b6, 0xa7b70000a7b8, 0xa7b90000a7ba, 0xa7bb0000a7bc, 0xa7bd0000a7be, 0xa7bf0000a7c0, 0xa7c10000a7c2, 0xa7c30000a7c4, 0xa7c80000a7c9, 0xa7ca0000a7cb, 0xa7d10000a7d2, 0xa7d30000a7d4, 0xa7d50000a7d6, 0xa7d70000a7d8, 0xa7d90000a7da, 0xa7f20000a7f5, 0xa7f60000a7f8, 0xa7fa0000a828, 0xa82c0000a82d, 0xa8400000a874, 0xa8800000a8c6, 0xa8d00000a8da, 0xa8e00000a8f8, 0xa8fb0000a8fc, 0xa8fd0000a92e, 0xa9300000a954, 0xa9800000a9c1, 0xa9cf0000a9da, 0xa9e00000a9ff, 0xaa000000aa37, 0xaa400000aa4e, 0xaa500000aa5a, 0xaa600000aa77, 0xaa7a0000aac3, 0xaadb0000aade, 0xaae00000aaf0, 0xaaf20000aaf7, 0xab010000ab07, 0xab090000ab0f, 0xab110000ab17, 0xab200000ab27, 0xab280000ab2f, 0xab300000ab5b, 0xab600000ab69, 0xabc00000abeb, 0xabec0000abee, 0xabf00000abfa, 0xac000000d7a4, 0xfa0e0000fa10, 0xfa110000fa12, 0xfa130000fa15, 0xfa1f0000fa20, 0xfa210000fa22, 0xfa230000fa25, 0xfa270000fa2a, 0xfb1e0000fb1f, 0xfe200000fe30, 0xfe730000fe74, 0x100000001000c, 0x1000d00010027, 0x100280001003b, 0x1003c0001003e, 0x1003f0001004e, 0x100500001005e, 0x10080000100fb, 0x101fd000101fe, 0x102800001029d, 0x102a0000102d1, 0x102e0000102e1, 0x1030000010320, 0x1032d00010341, 0x103420001034a, 0x103500001037b, 0x103800001039e, 0x103a0000103c4, 0x103c8000103d0, 0x104280001049e, 0x104a0000104aa, 0x104d8000104fc, 0x1050000010528, 0x1053000010564, 0x10597000105a2, 0x105a3000105b2, 0x105b3000105ba, 0x105bb000105bd, 0x1060000010737, 0x1074000010756, 0x1076000010768, 0x1078000010786, 0x10787000107b1, 0x107b2000107bb, 0x1080000010806, 0x1080800010809, 0x1080a00010836, 0x1083700010839, 0x1083c0001083d, 0x1083f00010856, 0x1086000010877, 0x108800001089f, 0x108e0000108f3, 0x108f4000108f6, 0x1090000010916, 0x109200001093a, 0x10980000109b8, 0x109be000109c0, 0x10a0000010a04, 0x10a0500010a07, 0x10a0c00010a14, 0x10a1500010a18, 0x10a1900010a36, 0x10a3800010a3b, 0x10a3f00010a40, 0x10a6000010a7d, 0x10a8000010a9d, 0x10ac000010ac8, 0x10ac900010ae7, 0x10b0000010b36, 0x10b4000010b56, 0x10b6000010b73, 0x10b8000010b92, 0x10c0000010c49, 0x10cc000010cf3, 0x10d0000010d28, 0x10d3000010d3a, 0x10e8000010eaa, 0x10eab00010ead, 0x10eb000010eb2, 0x10efd00010f1d, 0x10f2700010f28, 0x10f3000010f51, 0x10f7000010f86, 0x10fb000010fc5, 0x10fe000010ff7, 0x1100000011047, 0x1106600011076, 0x1107f000110bb, 0x110c2000110c3, 0x110d0000110e9, 0x110f0000110fa, 0x1110000011135, 0x1113600011140, 0x1114400011148, 0x1115000011174, 0x1117600011177, 0x11180000111c5, 0x111c9000111cd, 0x111ce000111db, 0x111dc000111dd, 0x1120000011212, 0x1121300011238, 0x1123e00011242, 0x1128000011287, 0x1128800011289, 0x1128a0001128e, 0x1128f0001129e, 0x1129f000112a9, 0x112b0000112eb, 0x112f0000112fa, 0x1130000011304, 0x113050001130d, 0x1130f00011311, 0x1131300011329, 0x1132a00011331, 0x1133200011334, 0x113350001133a, 0x1133b00011345, 0x1134700011349, 0x1134b0001134e, 0x1135000011351, 0x1135700011358, 0x1135d00011364, 0x113660001136d, 0x1137000011375, 0x114000001144b, 0x114500001145a, 0x1145e00011462, 0x11480000114c6, 0x114c7000114c8, 0x114d0000114da, 0x11580000115b6, 0x115b8000115c1, 0x115d8000115de, 0x1160000011641, 0x1164400011645, 0x116500001165a, 0x11680000116b9, 0x116c0000116ca, 0x117000001171b, 0x1171d0001172c, 0x117300001173a, 0x1174000011747, 0x118000001183b, 0x118c0000118ea, 0x118ff00011907, 0x119090001190a, 0x1190c00011914, 0x1191500011917, 0x1191800011936, 0x1193700011939, 0x1193b00011944, 0x119500001195a, 0x119a0000119a8, 0x119aa000119d8, 0x119da000119e2, 0x119e3000119e5, 0x11a0000011a3f, 0x11a4700011a48, 0x11a5000011a9a, 0x11a9d00011a9e, 0x11ab000011af9, 0x11c0000011c09, 0x11c0a00011c37, 0x11c3800011c41, 0x11c5000011c5a, 0x11c7200011c90, 0x11c9200011ca8, 0x11ca900011cb7, 0x11d0000011d07, 0x11d0800011d0a, 0x11d0b00011d37, 0x11d3a00011d3b, 0x11d3c00011d3e, 0x11d3f00011d48, 0x11d5000011d5a, 0x11d6000011d66, 0x11d6700011d69, 0x11d6a00011d8f, 0x11d9000011d92, 0x11d9300011d99, 0x11da000011daa, 0x11ee000011ef7, 0x11f0000011f11, 0x11f1200011f3b, 0x11f3e00011f43, 0x11f5000011f5a, 0x11fb000011fb1, 0x120000001239a, 0x1248000012544, 0x12f9000012ff1, 0x1300000013430, 0x1344000013456, 0x1440000014647, 0x1680000016a39, 0x16a4000016a5f, 0x16a6000016a6a, 0x16a7000016abf, 0x16ac000016aca, 0x16ad000016aee, 0x16af000016af5, 0x16b0000016b37, 0x16b4000016b44, 0x16b5000016b5a, 0x16b6300016b78, 0x16b7d00016b90, 0x16e6000016e80, 0x16f0000016f4b, 0x16f4f00016f88, 0x16f8f00016fa0, 0x16fe000016fe2, 0x16fe300016fe5, 0x16ff000016ff2, 0x17000000187f8, 0x1880000018cd6, 0x18d0000018d09, 0x1aff00001aff4, 0x1aff50001affc, 0x1affd0001afff, 0x1b0000001b123, 0x1b1320001b133, 0x1b1500001b153, 0x1b1550001b156, 0x1b1640001b168, 0x1b1700001b2fc, 0x1bc000001bc6b, 0x1bc700001bc7d, 0x1bc800001bc89, 0x1bc900001bc9a, 0x1bc9d0001bc9f, 0x1cf000001cf2e, 0x1cf300001cf47, 0x1da000001da37, 0x1da3b0001da6d, 0x1da750001da76, 0x1da840001da85, 0x1da9b0001daa0, 0x1daa10001dab0, 0x1df000001df1f, 0x1df250001df2b, 0x1e0000001e007, 0x1e0080001e019, 0x1e01b0001e022, 0x1e0230001e025, 0x1e0260001e02b, 0x1e0300001e06e, 0x1e08f0001e090, 0x1e1000001e12d, 0x1e1300001e13e, 0x1e1400001e14a, 0x1e14e0001e14f, 0x1e2900001e2af, 0x1e2c00001e2fa, 0x1e4d00001e4fa, 0x1e7e00001e7e7, 0x1e7e80001e7ec, 0x1e7ed0001e7ef, 0x1e7f00001e7ff, 0x1e8000001e8c5, 0x1e8d00001e8d7, 0x1e9220001e94c, 0x1e9500001e95a, 0x200000002a6e0, 0x2a7000002b73a, 0x2b7400002b81e, 0x2b8200002cea2, 0x2ceb00002ebe1, 0x300000003134b, 0x31350000323b0, ), 'CONTEXTJ': ( 0x200c0000200e, ), 'CONTEXTO': ( 0xb7000000b8, 0x37500000376, 0x5f3000005f5, 0x6600000066a, 0x6f0000006fa, 0x30fb000030fc, ), }
44,375
Python
19.620818
57
0.554096
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/idna/uts46data.py
# This file is automatically generated by tools/idna-data # vim: set fileencoding=utf-8 : from typing import List, Tuple, Union """IDNA Mapping Table from UTS46.""" __version__ = '15.0.0' def _seg_0() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x0, '3'), (0x1, '3'), (0x2, '3'), (0x3, '3'), (0x4, '3'), (0x5, '3'), (0x6, '3'), (0x7, '3'), (0x8, '3'), (0x9, '3'), (0xA, '3'), (0xB, '3'), (0xC, '3'), (0xD, '3'), (0xE, '3'), (0xF, '3'), (0x10, '3'), (0x11, '3'), (0x12, '3'), (0x13, '3'), (0x14, '3'), (0x15, '3'), (0x16, '3'), (0x17, '3'), (0x18, '3'), (0x19, '3'), (0x1A, '3'), (0x1B, '3'), (0x1C, '3'), (0x1D, '3'), (0x1E, '3'), (0x1F, '3'), (0x20, '3'), (0x21, '3'), (0x22, '3'), (0x23, '3'), (0x24, '3'), (0x25, '3'), (0x26, '3'), (0x27, '3'), (0x28, '3'), (0x29, '3'), (0x2A, '3'), (0x2B, '3'), (0x2C, '3'), (0x2D, 'V'), (0x2E, 'V'), (0x2F, '3'), (0x30, 'V'), (0x31, 'V'), (0x32, 'V'), (0x33, 'V'), (0x34, 'V'), (0x35, 'V'), (0x36, 'V'), (0x37, 'V'), (0x38, 'V'), (0x39, 'V'), (0x3A, '3'), (0x3B, '3'), (0x3C, '3'), (0x3D, '3'), (0x3E, '3'), (0x3F, '3'), (0x40, '3'), (0x41, 'M', 'a'), (0x42, 'M', 'b'), (0x43, 'M', 'c'), (0x44, 'M', 'd'), (0x45, 'M', 'e'), (0x46, 'M', 'f'), (0x47, 'M', 'g'), (0x48, 'M', 'h'), (0x49, 'M', 'i'), (0x4A, 'M', 'j'), (0x4B, 'M', 'k'), (0x4C, 'M', 'l'), (0x4D, 'M', 'm'), (0x4E, 'M', 'n'), (0x4F, 'M', 'o'), (0x50, 'M', 'p'), (0x51, 'M', 'q'), (0x52, 'M', 'r'), (0x53, 'M', 's'), (0x54, 'M', 't'), (0x55, 'M', 'u'), (0x56, 'M', 'v'), (0x57, 'M', 'w'), (0x58, 'M', 'x'), (0x59, 'M', 'y'), (0x5A, 'M', 'z'), (0x5B, '3'), (0x5C, '3'), (0x5D, '3'), (0x5E, '3'), (0x5F, '3'), (0x60, '3'), (0x61, 'V'), (0x62, 'V'), (0x63, 'V'), ] def _seg_1() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x64, 'V'), (0x65, 'V'), (0x66, 'V'), (0x67, 'V'), (0x68, 'V'), (0x69, 'V'), (0x6A, 'V'), (0x6B, 'V'), (0x6C, 'V'), (0x6D, 'V'), (0x6E, 'V'), (0x6F, 'V'), (0x70, 'V'), (0x71, 'V'), (0x72, 'V'), (0x73, 'V'), (0x74, 'V'), (0x75, 'V'), (0x76, 'V'), (0x77, 'V'), (0x78, 'V'), (0x79, 'V'), (0x7A, 'V'), (0x7B, '3'), (0x7C, '3'), (0x7D, '3'), (0x7E, '3'), (0x7F, '3'), (0x80, 'X'), (0x81, 'X'), (0x82, 'X'), (0x83, 'X'), (0x84, 'X'), (0x85, 'X'), (0x86, 'X'), (0x87, 'X'), (0x88, 'X'), (0x89, 'X'), (0x8A, 'X'), (0x8B, 'X'), (0x8C, 'X'), (0x8D, 'X'), (0x8E, 'X'), (0x8F, 'X'), (0x90, 'X'), (0x91, 'X'), (0x92, 'X'), (0x93, 'X'), (0x94, 'X'), (0x95, 'X'), (0x96, 'X'), (0x97, 'X'), (0x98, 'X'), (0x99, 'X'), (0x9A, 'X'), (0x9B, 'X'), (0x9C, 'X'), (0x9D, 'X'), (0x9E, 'X'), (0x9F, 'X'), (0xA0, '3', ' '), (0xA1, 'V'), (0xA2, 'V'), (0xA3, 'V'), (0xA4, 'V'), (0xA5, 'V'), (0xA6, 'V'), (0xA7, 'V'), (0xA8, '3', ' ̈'), (0xA9, 'V'), (0xAA, 'M', 'a'), (0xAB, 'V'), (0xAC, 'V'), (0xAD, 'I'), (0xAE, 'V'), (0xAF, '3', ' ̄'), (0xB0, 'V'), (0xB1, 'V'), (0xB2, 'M', '2'), (0xB3, 'M', '3'), (0xB4, '3', ' ́'), (0xB5, 'M', 'μ'), (0xB6, 'V'), (0xB7, 'V'), (0xB8, '3', ' ̧'), (0xB9, 'M', '1'), (0xBA, 'M', 'o'), (0xBB, 'V'), (0xBC, 'M', '1⁄4'), (0xBD, 'M', '1⁄2'), (0xBE, 'M', '3⁄4'), (0xBF, 'V'), (0xC0, 'M', 'à'), (0xC1, 'M', 'á'), (0xC2, 'M', 'â'), (0xC3, 'M', 'ã'), (0xC4, 'M', 'ä'), (0xC5, 'M', 'å'), (0xC6, 'M', 'æ'), (0xC7, 'M', 'ç'), ] def _seg_2() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xC8, 'M', 'è'), (0xC9, 'M', 'é'), (0xCA, 'M', 'ê'), (0xCB, 'M', 'ë'), (0xCC, 'M', 'ì'), (0xCD, 'M', 'í'), (0xCE, 'M', 'î'), (0xCF, 'M', 'ï'), (0xD0, 'M', 'ð'), (0xD1, 'M', 'ñ'), (0xD2, 'M', 'ò'), (0xD3, 'M', 'ó'), (0xD4, 'M', 'ô'), (0xD5, 'M', 'õ'), (0xD6, 'M', 'ö'), (0xD7, 'V'), (0xD8, 'M', 'ø'), (0xD9, 'M', 'ù'), (0xDA, 'M', 'ú'), (0xDB, 'M', 'û'), (0xDC, 'M', 'ü'), (0xDD, 'M', 'ý'), (0xDE, 'M', 'þ'), (0xDF, 'D', 'ss'), (0xE0, 'V'), (0xE1, 'V'), (0xE2, 'V'), (0xE3, 'V'), (0xE4, 'V'), (0xE5, 'V'), (0xE6, 'V'), (0xE7, 'V'), (0xE8, 'V'), (0xE9, 'V'), (0xEA, 'V'), (0xEB, 'V'), (0xEC, 'V'), (0xED, 'V'), (0xEE, 'V'), (0xEF, 'V'), (0xF0, 'V'), (0xF1, 'V'), (0xF2, 'V'), (0xF3, 'V'), (0xF4, 'V'), (0xF5, 'V'), (0xF6, 'V'), (0xF7, 'V'), (0xF8, 'V'), (0xF9, 'V'), (0xFA, 'V'), (0xFB, 'V'), (0xFC, 'V'), (0xFD, 'V'), (0xFE, 'V'), (0xFF, 'V'), (0x100, 'M', 'ā'), (0x101, 'V'), (0x102, 'M', 'ă'), (0x103, 'V'), (0x104, 'M', 'ą'), (0x105, 'V'), (0x106, 'M', 'ć'), (0x107, 'V'), (0x108, 'M', 'ĉ'), (0x109, 'V'), (0x10A, 'M', 'ċ'), (0x10B, 'V'), (0x10C, 'M', 'č'), (0x10D, 'V'), (0x10E, 'M', 'ď'), (0x10F, 'V'), (0x110, 'M', 'đ'), (0x111, 'V'), (0x112, 'M', 'ē'), (0x113, 'V'), (0x114, 'M', 'ĕ'), (0x115, 'V'), (0x116, 'M', 'ė'), (0x117, 'V'), (0x118, 'M', 'ę'), (0x119, 'V'), (0x11A, 'M', 'ě'), (0x11B, 'V'), (0x11C, 'M', 'ĝ'), (0x11D, 'V'), (0x11E, 'M', 'ğ'), (0x11F, 'V'), (0x120, 'M', 'ġ'), (0x121, 'V'), (0x122, 'M', 'ģ'), (0x123, 'V'), (0x124, 'M', 'ĥ'), (0x125, 'V'), (0x126, 'M', 'ħ'), (0x127, 'V'), (0x128, 'M', 'ĩ'), (0x129, 'V'), (0x12A, 'M', 'ī'), (0x12B, 'V'), ] def _seg_3() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x12C, 'M', 'ĭ'), (0x12D, 'V'), (0x12E, 'M', 'į'), (0x12F, 'V'), (0x130, 'M', 'i̇'), (0x131, 'V'), (0x132, 'M', 'ij'), (0x134, 'M', 'ĵ'), (0x135, 'V'), (0x136, 'M', 'ķ'), (0x137, 'V'), (0x139, 'M', 'ĺ'), (0x13A, 'V'), (0x13B, 'M', 'ļ'), (0x13C, 'V'), (0x13D, 'M', 'ľ'), (0x13E, 'V'), (0x13F, 'M', 'l·'), (0x141, 'M', 'ł'), (0x142, 'V'), (0x143, 'M', 'ń'), (0x144, 'V'), (0x145, 'M', 'ņ'), (0x146, 'V'), (0x147, 'M', 'ň'), (0x148, 'V'), (0x149, 'M', 'ʼn'), (0x14A, 'M', 'ŋ'), (0x14B, 'V'), (0x14C, 'M', 'ō'), (0x14D, 'V'), (0x14E, 'M', 'ŏ'), (0x14F, 'V'), (0x150, 'M', 'ő'), (0x151, 'V'), (0x152, 'M', 'œ'), (0x153, 'V'), (0x154, 'M', 'ŕ'), (0x155, 'V'), (0x156, 'M', 'ŗ'), (0x157, 'V'), (0x158, 'M', 'ř'), (0x159, 'V'), (0x15A, 'M', 'ś'), (0x15B, 'V'), (0x15C, 'M', 'ŝ'), (0x15D, 'V'), (0x15E, 'M', 'ş'), (0x15F, 'V'), (0x160, 'M', 'š'), (0x161, 'V'), (0x162, 'M', 'ţ'), (0x163, 'V'), (0x164, 'M', 'ť'), (0x165, 'V'), (0x166, 'M', 'ŧ'), (0x167, 'V'), (0x168, 'M', 'ũ'), (0x169, 'V'), (0x16A, 'M', 'ū'), (0x16B, 'V'), (0x16C, 'M', 'ŭ'), (0x16D, 'V'), (0x16E, 'M', 'ů'), (0x16F, 'V'), (0x170, 'M', 'ű'), (0x171, 'V'), (0x172, 'M', 'ų'), (0x173, 'V'), (0x174, 'M', 'ŵ'), (0x175, 'V'), (0x176, 'M', 'ŷ'), (0x177, 'V'), (0x178, 'M', 'ÿ'), (0x179, 'M', 'ź'), (0x17A, 'V'), (0x17B, 'M', 'ż'), (0x17C, 'V'), (0x17D, 'M', 'ž'), (0x17E, 'V'), (0x17F, 'M', 's'), (0x180, 'V'), (0x181, 'M', 'ɓ'), (0x182, 'M', 'ƃ'), (0x183, 'V'), (0x184, 'M', 'ƅ'), (0x185, 'V'), (0x186, 'M', 'ɔ'), (0x187, 'M', 'ƈ'), (0x188, 'V'), (0x189, 'M', 'ɖ'), (0x18A, 'M', 'ɗ'), (0x18B, 'M', 'ƌ'), (0x18C, 'V'), (0x18E, 'M', 'ǝ'), (0x18F, 'M', 'ə'), (0x190, 'M', 'ɛ'), (0x191, 'M', 'ƒ'), (0x192, 'V'), (0x193, 'M', 'ɠ'), ] def _seg_4() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x194, 'M', 'ɣ'), (0x195, 'V'), (0x196, 'M', 'ɩ'), (0x197, 'M', 'ɨ'), (0x198, 'M', 'ƙ'), (0x199, 'V'), (0x19C, 'M', 'ɯ'), (0x19D, 'M', 'ɲ'), (0x19E, 'V'), (0x19F, 'M', 'ɵ'), (0x1A0, 'M', 'ơ'), (0x1A1, 'V'), (0x1A2, 'M', 'ƣ'), (0x1A3, 'V'), (0x1A4, 'M', 'ƥ'), (0x1A5, 'V'), (0x1A6, 'M', 'ʀ'), (0x1A7, 'M', 'ƨ'), (0x1A8, 'V'), (0x1A9, 'M', 'ʃ'), (0x1AA, 'V'), (0x1AC, 'M', 'ƭ'), (0x1AD, 'V'), (0x1AE, 'M', 'ʈ'), (0x1AF, 'M', 'ư'), (0x1B0, 'V'), (0x1B1, 'M', 'ʊ'), (0x1B2, 'M', 'ʋ'), (0x1B3, 'M', 'ƴ'), (0x1B4, 'V'), (0x1B5, 'M', 'ƶ'), (0x1B6, 'V'), (0x1B7, 'M', 'ʒ'), (0x1B8, 'M', 'ƹ'), (0x1B9, 'V'), (0x1BC, 'M', 'ƽ'), (0x1BD, 'V'), (0x1C4, 'M', 'dž'), (0x1C7, 'M', 'lj'), (0x1CA, 'M', 'nj'), (0x1CD, 'M', 'ǎ'), (0x1CE, 'V'), (0x1CF, 'M', 'ǐ'), (0x1D0, 'V'), (0x1D1, 'M', 'ǒ'), (0x1D2, 'V'), (0x1D3, 'M', 'ǔ'), (0x1D4, 'V'), (0x1D5, 'M', 'ǖ'), (0x1D6, 'V'), (0x1D7, 'M', 'ǘ'), (0x1D8, 'V'), (0x1D9, 'M', 'ǚ'), (0x1DA, 'V'), (0x1DB, 'M', 'ǜ'), (0x1DC, 'V'), (0x1DE, 'M', 'ǟ'), (0x1DF, 'V'), (0x1E0, 'M', 'ǡ'), (0x1E1, 'V'), (0x1E2, 'M', 'ǣ'), (0x1E3, 'V'), (0x1E4, 'M', 'ǥ'), (0x1E5, 'V'), (0x1E6, 'M', 'ǧ'), (0x1E7, 'V'), (0x1E8, 'M', 'ǩ'), (0x1E9, 'V'), (0x1EA, 'M', 'ǫ'), (0x1EB, 'V'), (0x1EC, 'M', 'ǭ'), (0x1ED, 'V'), (0x1EE, 'M', 'ǯ'), (0x1EF, 'V'), (0x1F1, 'M', 'dz'), (0x1F4, 'M', 'ǵ'), (0x1F5, 'V'), (0x1F6, 'M', 'ƕ'), (0x1F7, 'M', 'ƿ'), (0x1F8, 'M', 'ǹ'), (0x1F9, 'V'), (0x1FA, 'M', 'ǻ'), (0x1FB, 'V'), (0x1FC, 'M', 'ǽ'), (0x1FD, 'V'), (0x1FE, 'M', 'ǿ'), (0x1FF, 'V'), (0x200, 'M', 'ȁ'), (0x201, 'V'), (0x202, 'M', 'ȃ'), (0x203, 'V'), (0x204, 'M', 'ȅ'), (0x205, 'V'), (0x206, 'M', 'ȇ'), (0x207, 'V'), (0x208, 'M', 'ȉ'), (0x209, 'V'), (0x20A, 'M', 'ȋ'), (0x20B, 'V'), (0x20C, 'M', 'ȍ'), ] def _seg_5() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x20D, 'V'), (0x20E, 'M', 'ȏ'), (0x20F, 'V'), (0x210, 'M', 'ȑ'), (0x211, 'V'), (0x212, 'M', 'ȓ'), (0x213, 'V'), (0x214, 'M', 'ȕ'), (0x215, 'V'), (0x216, 'M', 'ȗ'), (0x217, 'V'), (0x218, 'M', 'ș'), (0x219, 'V'), (0x21A, 'M', 'ț'), (0x21B, 'V'), (0x21C, 'M', 'ȝ'), (0x21D, 'V'), (0x21E, 'M', 'ȟ'), (0x21F, 'V'), (0x220, 'M', 'ƞ'), (0x221, 'V'), (0x222, 'M', 'ȣ'), (0x223, 'V'), (0x224, 'M', 'ȥ'), (0x225, 'V'), (0x226, 'M', 'ȧ'), (0x227, 'V'), (0x228, 'M', 'ȩ'), (0x229, 'V'), (0x22A, 'M', 'ȫ'), (0x22B, 'V'), (0x22C, 'M', 'ȭ'), (0x22D, 'V'), (0x22E, 'M', 'ȯ'), (0x22F, 'V'), (0x230, 'M', 'ȱ'), (0x231, 'V'), (0x232, 'M', 'ȳ'), (0x233, 'V'), (0x23A, 'M', 'ⱥ'), (0x23B, 'M', 'ȼ'), (0x23C, 'V'), (0x23D, 'M', 'ƚ'), (0x23E, 'M', 'ⱦ'), (0x23F, 'V'), (0x241, 'M', 'ɂ'), (0x242, 'V'), (0x243, 'M', 'ƀ'), (0x244, 'M', 'ʉ'), (0x245, 'M', 'ʌ'), (0x246, 'M', 'ɇ'), (0x247, 'V'), (0x248, 'M', 'ɉ'), (0x249, 'V'), (0x24A, 'M', 'ɋ'), (0x24B, 'V'), (0x24C, 'M', 'ɍ'), (0x24D, 'V'), (0x24E, 'M', 'ɏ'), (0x24F, 'V'), (0x2B0, 'M', 'h'), (0x2B1, 'M', 'ɦ'), (0x2B2, 'M', 'j'), (0x2B3, 'M', 'r'), (0x2B4, 'M', 'ɹ'), (0x2B5, 'M', 'ɻ'), (0x2B6, 'M', 'ʁ'), (0x2B7, 'M', 'w'), (0x2B8, 'M', 'y'), (0x2B9, 'V'), (0x2D8, '3', ' ̆'), (0x2D9, '3', ' ̇'), (0x2DA, '3', ' ̊'), (0x2DB, '3', ' ̨'), (0x2DC, '3', ' ̃'), (0x2DD, '3', ' ̋'), (0x2DE, 'V'), (0x2E0, 'M', 'ɣ'), (0x2E1, 'M', 'l'), (0x2E2, 'M', 's'), (0x2E3, 'M', 'x'), (0x2E4, 'M', 'ʕ'), (0x2E5, 'V'), (0x340, 'M', '̀'), (0x341, 'M', '́'), (0x342, 'V'), (0x343, 'M', '̓'), (0x344, 'M', '̈́'), (0x345, 'M', 'ι'), (0x346, 'V'), (0x34F, 'I'), (0x350, 'V'), (0x370, 'M', 'ͱ'), (0x371, 'V'), (0x372, 'M', 'ͳ'), (0x373, 'V'), (0x374, 'M', 'ʹ'), (0x375, 'V'), (0x376, 'M', 'ͷ'), (0x377, 'V'), ] def _seg_6() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x378, 'X'), (0x37A, '3', ' ι'), (0x37B, 'V'), (0x37E, '3', ';'), (0x37F, 'M', 'ϳ'), (0x380, 'X'), (0x384, '3', ' ́'), (0x385, '3', ' ̈́'), (0x386, 'M', 'ά'), (0x387, 'M', '·'), (0x388, 'M', 'έ'), (0x389, 'M', 'ή'), (0x38A, 'M', 'ί'), (0x38B, 'X'), (0x38C, 'M', 'ό'), (0x38D, 'X'), (0x38E, 'M', 'ύ'), (0x38F, 'M', 'ώ'), (0x390, 'V'), (0x391, 'M', 'α'), (0x392, 'M', 'β'), (0x393, 'M', 'γ'), (0x394, 'M', 'δ'), (0x395, 'M', 'ε'), (0x396, 'M', 'ζ'), (0x397, 'M', 'η'), (0x398, 'M', 'θ'), (0x399, 'M', 'ι'), (0x39A, 'M', 'κ'), (0x39B, 'M', 'λ'), (0x39C, 'M', 'μ'), (0x39D, 'M', 'ν'), (0x39E, 'M', 'ξ'), (0x39F, 'M', 'ο'), (0x3A0, 'M', 'π'), (0x3A1, 'M', 'ρ'), (0x3A2, 'X'), (0x3A3, 'M', 'σ'), (0x3A4, 'M', 'τ'), (0x3A5, 'M', 'υ'), (0x3A6, 'M', 'φ'), (0x3A7, 'M', 'χ'), (0x3A8, 'M', 'ψ'), (0x3A9, 'M', 'ω'), (0x3AA, 'M', 'ϊ'), (0x3AB, 'M', 'ϋ'), (0x3AC, 'V'), (0x3C2, 'D', 'σ'), (0x3C3, 'V'), (0x3CF, 'M', 'ϗ'), (0x3D0, 'M', 'β'), (0x3D1, 'M', 'θ'), (0x3D2, 'M', 'υ'), (0x3D3, 'M', 'ύ'), (0x3D4, 'M', 'ϋ'), (0x3D5, 'M', 'φ'), (0x3D6, 'M', 'π'), (0x3D7, 'V'), (0x3D8, 'M', 'ϙ'), (0x3D9, 'V'), (0x3DA, 'M', 'ϛ'), (0x3DB, 'V'), (0x3DC, 'M', 'ϝ'), (0x3DD, 'V'), (0x3DE, 'M', 'ϟ'), (0x3DF, 'V'), (0x3E0, 'M', 'ϡ'), (0x3E1, 'V'), (0x3E2, 'M', 'ϣ'), (0x3E3, 'V'), (0x3E4, 'M', 'ϥ'), (0x3E5, 'V'), (0x3E6, 'M', 'ϧ'), (0x3E7, 'V'), (0x3E8, 'M', 'ϩ'), (0x3E9, 'V'), (0x3EA, 'M', 'ϫ'), (0x3EB, 'V'), (0x3EC, 'M', 'ϭ'), (0x3ED, 'V'), (0x3EE, 'M', 'ϯ'), (0x3EF, 'V'), (0x3F0, 'M', 'κ'), (0x3F1, 'M', 'ρ'), (0x3F2, 'M', 'σ'), (0x3F3, 'V'), (0x3F4, 'M', 'θ'), (0x3F5, 'M', 'ε'), (0x3F6, 'V'), (0x3F7, 'M', 'ϸ'), (0x3F8, 'V'), (0x3F9, 'M', 'σ'), (0x3FA, 'M', 'ϻ'), (0x3FB, 'V'), (0x3FD, 'M', 'ͻ'), (0x3FE, 'M', 'ͼ'), (0x3FF, 'M', 'ͽ'), (0x400, 'M', 'ѐ'), (0x401, 'M', 'ё'), (0x402, 'M', 'ђ'), ] def _seg_7() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x403, 'M', 'ѓ'), (0x404, 'M', 'є'), (0x405, 'M', 'ѕ'), (0x406, 'M', 'і'), (0x407, 'M', 'ї'), (0x408, 'M', 'ј'), (0x409, 'M', 'љ'), (0x40A, 'M', 'њ'), (0x40B, 'M', 'ћ'), (0x40C, 'M', 'ќ'), (0x40D, 'M', 'ѝ'), (0x40E, 'M', 'ў'), (0x40F, 'M', 'џ'), (0x410, 'M', 'а'), (0x411, 'M', 'б'), (0x412, 'M', 'в'), (0x413, 'M', 'г'), (0x414, 'M', 'д'), (0x415, 'M', 'е'), (0x416, 'M', 'ж'), (0x417, 'M', 'з'), (0x418, 'M', 'и'), (0x419, 'M', 'й'), (0x41A, 'M', 'к'), (0x41B, 'M', 'л'), (0x41C, 'M', 'м'), (0x41D, 'M', 'н'), (0x41E, 'M', 'о'), (0x41F, 'M', 'п'), (0x420, 'M', 'р'), (0x421, 'M', 'с'), (0x422, 'M', 'т'), (0x423, 'M', 'у'), (0x424, 'M', 'ф'), (0x425, 'M', 'х'), (0x426, 'M', 'ц'), (0x427, 'M', 'ч'), (0x428, 'M', 'ш'), (0x429, 'M', 'щ'), (0x42A, 'M', 'ъ'), (0x42B, 'M', 'ы'), (0x42C, 'M', 'ь'), (0x42D, 'M', 'э'), (0x42E, 'M', 'ю'), (0x42F, 'M', 'я'), (0x430, 'V'), (0x460, 'M', 'ѡ'), (0x461, 'V'), (0x462, 'M', 'ѣ'), (0x463, 'V'), (0x464, 'M', 'ѥ'), (0x465, 'V'), (0x466, 'M', 'ѧ'), (0x467, 'V'), (0x468, 'M', 'ѩ'), (0x469, 'V'), (0x46A, 'M', 'ѫ'), (0x46B, 'V'), (0x46C, 'M', 'ѭ'), (0x46D, 'V'), (0x46E, 'M', 'ѯ'), (0x46F, 'V'), (0x470, 'M', 'ѱ'), (0x471, 'V'), (0x472, 'M', 'ѳ'), (0x473, 'V'), (0x474, 'M', 'ѵ'), (0x475, 'V'), (0x476, 'M', 'ѷ'), (0x477, 'V'), (0x478, 'M', 'ѹ'), (0x479, 'V'), (0x47A, 'M', 'ѻ'), (0x47B, 'V'), (0x47C, 'M', 'ѽ'), (0x47D, 'V'), (0x47E, 'M', 'ѿ'), (0x47F, 'V'), (0x480, 'M', 'ҁ'), (0x481, 'V'), (0x48A, 'M', 'ҋ'), (0x48B, 'V'), (0x48C, 'M', 'ҍ'), (0x48D, 'V'), (0x48E, 'M', 'ҏ'), (0x48F, 'V'), (0x490, 'M', 'ґ'), (0x491, 'V'), (0x492, 'M', 'ғ'), (0x493, 'V'), (0x494, 'M', 'ҕ'), (0x495, 'V'), (0x496, 'M', 'җ'), (0x497, 'V'), (0x498, 'M', 'ҙ'), (0x499, 'V'), (0x49A, 'M', 'қ'), (0x49B, 'V'), (0x49C, 'M', 'ҝ'), (0x49D, 'V'), ] def _seg_8() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x49E, 'M', 'ҟ'), (0x49F, 'V'), (0x4A0, 'M', 'ҡ'), (0x4A1, 'V'), (0x4A2, 'M', 'ң'), (0x4A3, 'V'), (0x4A4, 'M', 'ҥ'), (0x4A5, 'V'), (0x4A6, 'M', 'ҧ'), (0x4A7, 'V'), (0x4A8, 'M', 'ҩ'), (0x4A9, 'V'), (0x4AA, 'M', 'ҫ'), (0x4AB, 'V'), (0x4AC, 'M', 'ҭ'), (0x4AD, 'V'), (0x4AE, 'M', 'ү'), (0x4AF, 'V'), (0x4B0, 'M', 'ұ'), (0x4B1, 'V'), (0x4B2, 'M', 'ҳ'), (0x4B3, 'V'), (0x4B4, 'M', 'ҵ'), (0x4B5, 'V'), (0x4B6, 'M', 'ҷ'), (0x4B7, 'V'), (0x4B8, 'M', 'ҹ'), (0x4B9, 'V'), (0x4BA, 'M', 'һ'), (0x4BB, 'V'), (0x4BC, 'M', 'ҽ'), (0x4BD, 'V'), (0x4BE, 'M', 'ҿ'), (0x4BF, 'V'), (0x4C0, 'X'), (0x4C1, 'M', 'ӂ'), (0x4C2, 'V'), (0x4C3, 'M', 'ӄ'), (0x4C4, 'V'), (0x4C5, 'M', 'ӆ'), (0x4C6, 'V'), (0x4C7, 'M', 'ӈ'), (0x4C8, 'V'), (0x4C9, 'M', 'ӊ'), (0x4CA, 'V'), (0x4CB, 'M', 'ӌ'), (0x4CC, 'V'), (0x4CD, 'M', 'ӎ'), (0x4CE, 'V'), (0x4D0, 'M', 'ӑ'), (0x4D1, 'V'), (0x4D2, 'M', 'ӓ'), (0x4D3, 'V'), (0x4D4, 'M', 'ӕ'), (0x4D5, 'V'), (0x4D6, 'M', 'ӗ'), (0x4D7, 'V'), (0x4D8, 'M', 'ә'), (0x4D9, 'V'), (0x4DA, 'M', 'ӛ'), (0x4DB, 'V'), (0x4DC, 'M', 'ӝ'), (0x4DD, 'V'), (0x4DE, 'M', 'ӟ'), (0x4DF, 'V'), (0x4E0, 'M', 'ӡ'), (0x4E1, 'V'), (0x4E2, 'M', 'ӣ'), (0x4E3, 'V'), (0x4E4, 'M', 'ӥ'), (0x4E5, 'V'), (0x4E6, 'M', 'ӧ'), (0x4E7, 'V'), (0x4E8, 'M', 'ө'), (0x4E9, 'V'), (0x4EA, 'M', 'ӫ'), (0x4EB, 'V'), (0x4EC, 'M', 'ӭ'), (0x4ED, 'V'), (0x4EE, 'M', 'ӯ'), (0x4EF, 'V'), (0x4F0, 'M', 'ӱ'), (0x4F1, 'V'), (0x4F2, 'M', 'ӳ'), (0x4F3, 'V'), (0x4F4, 'M', 'ӵ'), (0x4F5, 'V'), (0x4F6, 'M', 'ӷ'), (0x4F7, 'V'), (0x4F8, 'M', 'ӹ'), (0x4F9, 'V'), (0x4FA, 'M', 'ӻ'), (0x4FB, 'V'), (0x4FC, 'M', 'ӽ'), (0x4FD, 'V'), (0x4FE, 'M', 'ӿ'), (0x4FF, 'V'), (0x500, 'M', 'ԁ'), (0x501, 'V'), (0x502, 'M', 'ԃ'), ] def _seg_9() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x503, 'V'), (0x504, 'M', 'ԅ'), (0x505, 'V'), (0x506, 'M', 'ԇ'), (0x507, 'V'), (0x508, 'M', 'ԉ'), (0x509, 'V'), (0x50A, 'M', 'ԋ'), (0x50B, 'V'), (0x50C, 'M', 'ԍ'), (0x50D, 'V'), (0x50E, 'M', 'ԏ'), (0x50F, 'V'), (0x510, 'M', 'ԑ'), (0x511, 'V'), (0x512, 'M', 'ԓ'), (0x513, 'V'), (0x514, 'M', 'ԕ'), (0x515, 'V'), (0x516, 'M', 'ԗ'), (0x517, 'V'), (0x518, 'M', 'ԙ'), (0x519, 'V'), (0x51A, 'M', 'ԛ'), (0x51B, 'V'), (0x51C, 'M', 'ԝ'), (0x51D, 'V'), (0x51E, 'M', 'ԟ'), (0x51F, 'V'), (0x520, 'M', 'ԡ'), (0x521, 'V'), (0x522, 'M', 'ԣ'), (0x523, 'V'), (0x524, 'M', 'ԥ'), (0x525, 'V'), (0x526, 'M', 'ԧ'), (0x527, 'V'), (0x528, 'M', 'ԩ'), (0x529, 'V'), (0x52A, 'M', 'ԫ'), (0x52B, 'V'), (0x52C, 'M', 'ԭ'), (0x52D, 'V'), (0x52E, 'M', 'ԯ'), (0x52F, 'V'), (0x530, 'X'), (0x531, 'M', 'ա'), (0x532, 'M', 'բ'), (0x533, 'M', 'գ'), (0x534, 'M', 'դ'), (0x535, 'M', 'ե'), (0x536, 'M', 'զ'), (0x537, 'M', 'է'), (0x538, 'M', 'ը'), (0x539, 'M', 'թ'), (0x53A, 'M', 'ժ'), (0x53B, 'M', 'ի'), (0x53C, 'M', 'լ'), (0x53D, 'M', 'խ'), (0x53E, 'M', 'ծ'), (0x53F, 'M', 'կ'), (0x540, 'M', 'հ'), (0x541, 'M', 'ձ'), (0x542, 'M', 'ղ'), (0x543, 'M', 'ճ'), (0x544, 'M', 'մ'), (0x545, 'M', 'յ'), (0x546, 'M', 'ն'), (0x547, 'M', 'շ'), (0x548, 'M', 'ո'), (0x549, 'M', 'չ'), (0x54A, 'M', 'պ'), (0x54B, 'M', 'ջ'), (0x54C, 'M', 'ռ'), (0x54D, 'M', 'ս'), (0x54E, 'M', 'վ'), (0x54F, 'M', 'տ'), (0x550, 'M', 'ր'), (0x551, 'M', 'ց'), (0x552, 'M', 'ւ'), (0x553, 'M', 'փ'), (0x554, 'M', 'ք'), (0x555, 'M', 'օ'), (0x556, 'M', 'ֆ'), (0x557, 'X'), (0x559, 'V'), (0x587, 'M', 'եւ'), (0x588, 'V'), (0x58B, 'X'), (0x58D, 'V'), (0x590, 'X'), (0x591, 'V'), (0x5C8, 'X'), (0x5D0, 'V'), (0x5EB, 'X'), (0x5EF, 'V'), (0x5F5, 'X'), (0x606, 'V'), (0x61C, 'X'), (0x61D, 'V'), ] def _seg_10() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x675, 'M', 'اٴ'), (0x676, 'M', 'وٴ'), (0x677, 'M', 'ۇٴ'), (0x678, 'M', 'يٴ'), (0x679, 'V'), (0x6DD, 'X'), (0x6DE, 'V'), (0x70E, 'X'), (0x710, 'V'), (0x74B, 'X'), (0x74D, 'V'), (0x7B2, 'X'), (0x7C0, 'V'), (0x7FB, 'X'), (0x7FD, 'V'), (0x82E, 'X'), (0x830, 'V'), (0x83F, 'X'), (0x840, 'V'), (0x85C, 'X'), (0x85E, 'V'), (0x85F, 'X'), (0x860, 'V'), (0x86B, 'X'), (0x870, 'V'), (0x88F, 'X'), (0x898, 'V'), (0x8E2, 'X'), (0x8E3, 'V'), (0x958, 'M', 'क़'), (0x959, 'M', 'ख़'), (0x95A, 'M', 'ग़'), (0x95B, 'M', 'ज़'), (0x95C, 'M', 'ड़'), (0x95D, 'M', 'ढ़'), (0x95E, 'M', 'फ़'), (0x95F, 'M', 'य़'), (0x960, 'V'), (0x984, 'X'), (0x985, 'V'), (0x98D, 'X'), (0x98F, 'V'), (0x991, 'X'), (0x993, 'V'), (0x9A9, 'X'), (0x9AA, 'V'), (0x9B1, 'X'), (0x9B2, 'V'), (0x9B3, 'X'), (0x9B6, 'V'), (0x9BA, 'X'), (0x9BC, 'V'), (0x9C5, 'X'), (0x9C7, 'V'), (0x9C9, 'X'), (0x9CB, 'V'), (0x9CF, 'X'), (0x9D7, 'V'), (0x9D8, 'X'), (0x9DC, 'M', 'ড়'), (0x9DD, 'M', 'ঢ়'), (0x9DE, 'X'), (0x9DF, 'M', 'য়'), (0x9E0, 'V'), (0x9E4, 'X'), (0x9E6, 'V'), (0x9FF, 'X'), (0xA01, 'V'), (0xA04, 'X'), (0xA05, 'V'), (0xA0B, 'X'), (0xA0F, 'V'), (0xA11, 'X'), (0xA13, 'V'), (0xA29, 'X'), (0xA2A, 'V'), (0xA31, 'X'), (0xA32, 'V'), (0xA33, 'M', 'ਲ਼'), (0xA34, 'X'), (0xA35, 'V'), (0xA36, 'M', 'ਸ਼'), (0xA37, 'X'), (0xA38, 'V'), (0xA3A, 'X'), (0xA3C, 'V'), (0xA3D, 'X'), (0xA3E, 'V'), (0xA43, 'X'), (0xA47, 'V'), (0xA49, 'X'), (0xA4B, 'V'), (0xA4E, 'X'), (0xA51, 'V'), (0xA52, 'X'), (0xA59, 'M', 'ਖ਼'), (0xA5A, 'M', 'ਗ਼'), (0xA5B, 'M', 'ਜ਼'), (0xA5C, 'V'), (0xA5D, 'X'), ] def _seg_11() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xA5E, 'M', 'ਫ਼'), (0xA5F, 'X'), (0xA66, 'V'), (0xA77, 'X'), (0xA81, 'V'), (0xA84, 'X'), (0xA85, 'V'), (0xA8E, 'X'), (0xA8F, 'V'), (0xA92, 'X'), (0xA93, 'V'), (0xAA9, 'X'), (0xAAA, 'V'), (0xAB1, 'X'), (0xAB2, 'V'), (0xAB4, 'X'), (0xAB5, 'V'), (0xABA, 'X'), (0xABC, 'V'), (0xAC6, 'X'), (0xAC7, 'V'), (0xACA, 'X'), (0xACB, 'V'), (0xACE, 'X'), (0xAD0, 'V'), (0xAD1, 'X'), (0xAE0, 'V'), (0xAE4, 'X'), (0xAE6, 'V'), (0xAF2, 'X'), (0xAF9, 'V'), (0xB00, 'X'), (0xB01, 'V'), (0xB04, 'X'), (0xB05, 'V'), (0xB0D, 'X'), (0xB0F, 'V'), (0xB11, 'X'), (0xB13, 'V'), (0xB29, 'X'), (0xB2A, 'V'), (0xB31, 'X'), (0xB32, 'V'), (0xB34, 'X'), (0xB35, 'V'), (0xB3A, 'X'), (0xB3C, 'V'), (0xB45, 'X'), (0xB47, 'V'), (0xB49, 'X'), (0xB4B, 'V'), (0xB4E, 'X'), (0xB55, 'V'), (0xB58, 'X'), (0xB5C, 'M', 'ଡ଼'), (0xB5D, 'M', 'ଢ଼'), (0xB5E, 'X'), (0xB5F, 'V'), (0xB64, 'X'), (0xB66, 'V'), (0xB78, 'X'), (0xB82, 'V'), (0xB84, 'X'), (0xB85, 'V'), (0xB8B, 'X'), (0xB8E, 'V'), (0xB91, 'X'), (0xB92, 'V'), (0xB96, 'X'), (0xB99, 'V'), (0xB9B, 'X'), (0xB9C, 'V'), (0xB9D, 'X'), (0xB9E, 'V'), (0xBA0, 'X'), (0xBA3, 'V'), (0xBA5, 'X'), (0xBA8, 'V'), (0xBAB, 'X'), (0xBAE, 'V'), (0xBBA, 'X'), (0xBBE, 'V'), (0xBC3, 'X'), (0xBC6, 'V'), (0xBC9, 'X'), (0xBCA, 'V'), (0xBCE, 'X'), (0xBD0, 'V'), (0xBD1, 'X'), (0xBD7, 'V'), (0xBD8, 'X'), (0xBE6, 'V'), (0xBFB, 'X'), (0xC00, 'V'), (0xC0D, 'X'), (0xC0E, 'V'), (0xC11, 'X'), (0xC12, 'V'), (0xC29, 'X'), (0xC2A, 'V'), ] def _seg_12() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xC3A, 'X'), (0xC3C, 'V'), (0xC45, 'X'), (0xC46, 'V'), (0xC49, 'X'), (0xC4A, 'V'), (0xC4E, 'X'), (0xC55, 'V'), (0xC57, 'X'), (0xC58, 'V'), (0xC5B, 'X'), (0xC5D, 'V'), (0xC5E, 'X'), (0xC60, 'V'), (0xC64, 'X'), (0xC66, 'V'), (0xC70, 'X'), (0xC77, 'V'), (0xC8D, 'X'), (0xC8E, 'V'), (0xC91, 'X'), (0xC92, 'V'), (0xCA9, 'X'), (0xCAA, 'V'), (0xCB4, 'X'), (0xCB5, 'V'), (0xCBA, 'X'), (0xCBC, 'V'), (0xCC5, 'X'), (0xCC6, 'V'), (0xCC9, 'X'), (0xCCA, 'V'), (0xCCE, 'X'), (0xCD5, 'V'), (0xCD7, 'X'), (0xCDD, 'V'), (0xCDF, 'X'), (0xCE0, 'V'), (0xCE4, 'X'), (0xCE6, 'V'), (0xCF0, 'X'), (0xCF1, 'V'), (0xCF4, 'X'), (0xD00, 'V'), (0xD0D, 'X'), (0xD0E, 'V'), (0xD11, 'X'), (0xD12, 'V'), (0xD45, 'X'), (0xD46, 'V'), (0xD49, 'X'), (0xD4A, 'V'), (0xD50, 'X'), (0xD54, 'V'), (0xD64, 'X'), (0xD66, 'V'), (0xD80, 'X'), (0xD81, 'V'), (0xD84, 'X'), (0xD85, 'V'), (0xD97, 'X'), (0xD9A, 'V'), (0xDB2, 'X'), (0xDB3, 'V'), (0xDBC, 'X'), (0xDBD, 'V'), (0xDBE, 'X'), (0xDC0, 'V'), (0xDC7, 'X'), (0xDCA, 'V'), (0xDCB, 'X'), (0xDCF, 'V'), (0xDD5, 'X'), (0xDD6, 'V'), (0xDD7, 'X'), (0xDD8, 'V'), (0xDE0, 'X'), (0xDE6, 'V'), (0xDF0, 'X'), (0xDF2, 'V'), (0xDF5, 'X'), (0xE01, 'V'), (0xE33, 'M', 'ํา'), (0xE34, 'V'), (0xE3B, 'X'), (0xE3F, 'V'), (0xE5C, 'X'), (0xE81, 'V'), (0xE83, 'X'), (0xE84, 'V'), (0xE85, 'X'), (0xE86, 'V'), (0xE8B, 'X'), (0xE8C, 'V'), (0xEA4, 'X'), (0xEA5, 'V'), (0xEA6, 'X'), (0xEA7, 'V'), (0xEB3, 'M', 'ໍາ'), (0xEB4, 'V'), ] def _seg_13() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xEBE, 'X'), (0xEC0, 'V'), (0xEC5, 'X'), (0xEC6, 'V'), (0xEC7, 'X'), (0xEC8, 'V'), (0xECF, 'X'), (0xED0, 'V'), (0xEDA, 'X'), (0xEDC, 'M', 'ຫນ'), (0xEDD, 'M', 'ຫມ'), (0xEDE, 'V'), (0xEE0, 'X'), (0xF00, 'V'), (0xF0C, 'M', '་'), (0xF0D, 'V'), (0xF43, 'M', 'གྷ'), (0xF44, 'V'), (0xF48, 'X'), (0xF49, 'V'), (0xF4D, 'M', 'ཌྷ'), (0xF4E, 'V'), (0xF52, 'M', 'དྷ'), (0xF53, 'V'), (0xF57, 'M', 'བྷ'), (0xF58, 'V'), (0xF5C, 'M', 'ཛྷ'), (0xF5D, 'V'), (0xF69, 'M', 'ཀྵ'), (0xF6A, 'V'), (0xF6D, 'X'), (0xF71, 'V'), (0xF73, 'M', 'ཱི'), (0xF74, 'V'), (0xF75, 'M', 'ཱུ'), (0xF76, 'M', 'ྲྀ'), (0xF77, 'M', 'ྲཱྀ'), (0xF78, 'M', 'ླྀ'), (0xF79, 'M', 'ླཱྀ'), (0xF7A, 'V'), (0xF81, 'M', 'ཱྀ'), (0xF82, 'V'), (0xF93, 'M', 'ྒྷ'), (0xF94, 'V'), (0xF98, 'X'), (0xF99, 'V'), (0xF9D, 'M', 'ྜྷ'), (0xF9E, 'V'), (0xFA2, 'M', 'ྡྷ'), (0xFA3, 'V'), (0xFA7, 'M', 'ྦྷ'), (0xFA8, 'V'), (0xFAC, 'M', 'ྫྷ'), (0xFAD, 'V'), (0xFB9, 'M', 'ྐྵ'), (0xFBA, 'V'), (0xFBD, 'X'), (0xFBE, 'V'), (0xFCD, 'X'), (0xFCE, 'V'), (0xFDB, 'X'), (0x1000, 'V'), (0x10A0, 'X'), (0x10C7, 'M', 'ⴧ'), (0x10C8, 'X'), (0x10CD, 'M', 'ⴭ'), (0x10CE, 'X'), (0x10D0, 'V'), (0x10FC, 'M', 'ნ'), (0x10FD, 'V'), (0x115F, 'X'), (0x1161, 'V'), (0x1249, 'X'), (0x124A, 'V'), (0x124E, 'X'), (0x1250, 'V'), (0x1257, 'X'), (0x1258, 'V'), (0x1259, 'X'), (0x125A, 'V'), (0x125E, 'X'), (0x1260, 'V'), (0x1289, 'X'), (0x128A, 'V'), (0x128E, 'X'), (0x1290, 'V'), (0x12B1, 'X'), (0x12B2, 'V'), (0x12B6, 'X'), (0x12B8, 'V'), (0x12BF, 'X'), (0x12C0, 'V'), (0x12C1, 'X'), (0x12C2, 'V'), (0x12C6, 'X'), (0x12C8, 'V'), (0x12D7, 'X'), (0x12D8, 'V'), (0x1311, 'X'), (0x1312, 'V'), ] def _seg_14() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1316, 'X'), (0x1318, 'V'), (0x135B, 'X'), (0x135D, 'V'), (0x137D, 'X'), (0x1380, 'V'), (0x139A, 'X'), (0x13A0, 'V'), (0x13F6, 'X'), (0x13F8, 'M', 'Ᏸ'), (0x13F9, 'M', 'Ᏹ'), (0x13FA, 'M', 'Ᏺ'), (0x13FB, 'M', 'Ᏻ'), (0x13FC, 'M', 'Ᏼ'), (0x13FD, 'M', 'Ᏽ'), (0x13FE, 'X'), (0x1400, 'V'), (0x1680, 'X'), (0x1681, 'V'), (0x169D, 'X'), (0x16A0, 'V'), (0x16F9, 'X'), (0x1700, 'V'), (0x1716, 'X'), (0x171F, 'V'), (0x1737, 'X'), (0x1740, 'V'), (0x1754, 'X'), (0x1760, 'V'), (0x176D, 'X'), (0x176E, 'V'), (0x1771, 'X'), (0x1772, 'V'), (0x1774, 'X'), (0x1780, 'V'), (0x17B4, 'X'), (0x17B6, 'V'), (0x17DE, 'X'), (0x17E0, 'V'), (0x17EA, 'X'), (0x17F0, 'V'), (0x17FA, 'X'), (0x1800, 'V'), (0x1806, 'X'), (0x1807, 'V'), (0x180B, 'I'), (0x180E, 'X'), (0x180F, 'I'), (0x1810, 'V'), (0x181A, 'X'), (0x1820, 'V'), (0x1879, 'X'), (0x1880, 'V'), (0x18AB, 'X'), (0x18B0, 'V'), (0x18F6, 'X'), (0x1900, 'V'), (0x191F, 'X'), (0x1920, 'V'), (0x192C, 'X'), (0x1930, 'V'), (0x193C, 'X'), (0x1940, 'V'), (0x1941, 'X'), (0x1944, 'V'), (0x196E, 'X'), (0x1970, 'V'), (0x1975, 'X'), (0x1980, 'V'), (0x19AC, 'X'), (0x19B0, 'V'), (0x19CA, 'X'), (0x19D0, 'V'), (0x19DB, 'X'), (0x19DE, 'V'), (0x1A1C, 'X'), (0x1A1E, 'V'), (0x1A5F, 'X'), (0x1A60, 'V'), (0x1A7D, 'X'), (0x1A7F, 'V'), (0x1A8A, 'X'), (0x1A90, 'V'), (0x1A9A, 'X'), (0x1AA0, 'V'), (0x1AAE, 'X'), (0x1AB0, 'V'), (0x1ACF, 'X'), (0x1B00, 'V'), (0x1B4D, 'X'), (0x1B50, 'V'), (0x1B7F, 'X'), (0x1B80, 'V'), (0x1BF4, 'X'), (0x1BFC, 'V'), (0x1C38, 'X'), (0x1C3B, 'V'), (0x1C4A, 'X'), (0x1C4D, 'V'), (0x1C80, 'M', 'в'), ] def _seg_15() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1C81, 'M', 'д'), (0x1C82, 'M', 'о'), (0x1C83, 'M', 'с'), (0x1C84, 'M', 'т'), (0x1C86, 'M', 'ъ'), (0x1C87, 'M', 'ѣ'), (0x1C88, 'M', 'ꙋ'), (0x1C89, 'X'), (0x1C90, 'M', 'ა'), (0x1C91, 'M', 'ბ'), (0x1C92, 'M', 'გ'), (0x1C93, 'M', 'დ'), (0x1C94, 'M', 'ე'), (0x1C95, 'M', 'ვ'), (0x1C96, 'M', 'ზ'), (0x1C97, 'M', 'თ'), (0x1C98, 'M', 'ი'), (0x1C99, 'M', 'კ'), (0x1C9A, 'M', 'ლ'), (0x1C9B, 'M', 'მ'), (0x1C9C, 'M', 'ნ'), (0x1C9D, 'M', 'ო'), (0x1C9E, 'M', 'პ'), (0x1C9F, 'M', 'ჟ'), (0x1CA0, 'M', 'რ'), (0x1CA1, 'M', 'ს'), (0x1CA2, 'M', 'ტ'), (0x1CA3, 'M', 'უ'), (0x1CA4, 'M', 'ფ'), (0x1CA5, 'M', 'ქ'), (0x1CA6, 'M', 'ღ'), (0x1CA7, 'M', 'ყ'), (0x1CA8, 'M', 'შ'), (0x1CA9, 'M', 'ჩ'), (0x1CAA, 'M', 'ც'), (0x1CAB, 'M', 'ძ'), (0x1CAC, 'M', 'წ'), (0x1CAD, 'M', 'ჭ'), (0x1CAE, 'M', 'ხ'), (0x1CAF, 'M', 'ჯ'), (0x1CB0, 'M', 'ჰ'), (0x1CB1, 'M', 'ჱ'), (0x1CB2, 'M', 'ჲ'), (0x1CB3, 'M', 'ჳ'), (0x1CB4, 'M', 'ჴ'), (0x1CB5, 'M', 'ჵ'), (0x1CB6, 'M', 'ჶ'), (0x1CB7, 'M', 'ჷ'), (0x1CB8, 'M', 'ჸ'), (0x1CB9, 'M', 'ჹ'), (0x1CBA, 'M', 'ჺ'), (0x1CBB, 'X'), (0x1CBD, 'M', 'ჽ'), (0x1CBE, 'M', 'ჾ'), (0x1CBF, 'M', 'ჿ'), (0x1CC0, 'V'), (0x1CC8, 'X'), (0x1CD0, 'V'), (0x1CFB, 'X'), (0x1D00, 'V'), (0x1D2C, 'M', 'a'), (0x1D2D, 'M', 'æ'), (0x1D2E, 'M', 'b'), (0x1D2F, 'V'), (0x1D30, 'M', 'd'), (0x1D31, 'M', 'e'), (0x1D32, 'M', 'ǝ'), (0x1D33, 'M', 'g'), (0x1D34, 'M', 'h'), (0x1D35, 'M', 'i'), (0x1D36, 'M', 'j'), (0x1D37, 'M', 'k'), (0x1D38, 'M', 'l'), (0x1D39, 'M', 'm'), (0x1D3A, 'M', 'n'), (0x1D3B, 'V'), (0x1D3C, 'M', 'o'), (0x1D3D, 'M', 'ȣ'), (0x1D3E, 'M', 'p'), (0x1D3F, 'M', 'r'), (0x1D40, 'M', 't'), (0x1D41, 'M', 'u'), (0x1D42, 'M', 'w'), (0x1D43, 'M', 'a'), (0x1D44, 'M', 'ɐ'), (0x1D45, 'M', 'ɑ'), (0x1D46, 'M', 'ᴂ'), (0x1D47, 'M', 'b'), (0x1D48, 'M', 'd'), (0x1D49, 'M', 'e'), (0x1D4A, 'M', 'ə'), (0x1D4B, 'M', 'ɛ'), (0x1D4C, 'M', 'ɜ'), (0x1D4D, 'M', 'g'), (0x1D4E, 'V'), (0x1D4F, 'M', 'k'), (0x1D50, 'M', 'm'), (0x1D51, 'M', 'ŋ'), (0x1D52, 'M', 'o'), (0x1D53, 'M', 'ɔ'), ] def _seg_16() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D54, 'M', 'ᴖ'), (0x1D55, 'M', 'ᴗ'), (0x1D56, 'M', 'p'), (0x1D57, 'M', 't'), (0x1D58, 'M', 'u'), (0x1D59, 'M', 'ᴝ'), (0x1D5A, 'M', 'ɯ'), (0x1D5B, 'M', 'v'), (0x1D5C, 'M', 'ᴥ'), (0x1D5D, 'M', 'β'), (0x1D5E, 'M', 'γ'), (0x1D5F, 'M', 'δ'), (0x1D60, 'M', 'φ'), (0x1D61, 'M', 'χ'), (0x1D62, 'M', 'i'), (0x1D63, 'M', 'r'), (0x1D64, 'M', 'u'), (0x1D65, 'M', 'v'), (0x1D66, 'M', 'β'), (0x1D67, 'M', 'γ'), (0x1D68, 'M', 'ρ'), (0x1D69, 'M', 'φ'), (0x1D6A, 'M', 'χ'), (0x1D6B, 'V'), (0x1D78, 'M', 'н'), (0x1D79, 'V'), (0x1D9B, 'M', 'ɒ'), (0x1D9C, 'M', 'c'), (0x1D9D, 'M', 'ɕ'), (0x1D9E, 'M', 'ð'), (0x1D9F, 'M', 'ɜ'), (0x1DA0, 'M', 'f'), (0x1DA1, 'M', 'ɟ'), (0x1DA2, 'M', 'ɡ'), (0x1DA3, 'M', 'ɥ'), (0x1DA4, 'M', 'ɨ'), (0x1DA5, 'M', 'ɩ'), (0x1DA6, 'M', 'ɪ'), (0x1DA7, 'M', 'ᵻ'), (0x1DA8, 'M', 'ʝ'), (0x1DA9, 'M', 'ɭ'), (0x1DAA, 'M', 'ᶅ'), (0x1DAB, 'M', 'ʟ'), (0x1DAC, 'M', 'ɱ'), (0x1DAD, 'M', 'ɰ'), (0x1DAE, 'M', 'ɲ'), (0x1DAF, 'M', 'ɳ'), (0x1DB0, 'M', 'ɴ'), (0x1DB1, 'M', 'ɵ'), (0x1DB2, 'M', 'ɸ'), (0x1DB3, 'M', 'ʂ'), (0x1DB4, 'M', 'ʃ'), (0x1DB5, 'M', 'ƫ'), (0x1DB6, 'M', 'ʉ'), (0x1DB7, 'M', 'ʊ'), (0x1DB8, 'M', 'ᴜ'), (0x1DB9, 'M', 'ʋ'), (0x1DBA, 'M', 'ʌ'), (0x1DBB, 'M', 'z'), (0x1DBC, 'M', 'ʐ'), (0x1DBD, 'M', 'ʑ'), (0x1DBE, 'M', 'ʒ'), (0x1DBF, 'M', 'θ'), (0x1DC0, 'V'), (0x1E00, 'M', 'ḁ'), (0x1E01, 'V'), (0x1E02, 'M', 'ḃ'), (0x1E03, 'V'), (0x1E04, 'M', 'ḅ'), (0x1E05, 'V'), (0x1E06, 'M', 'ḇ'), (0x1E07, 'V'), (0x1E08, 'M', 'ḉ'), (0x1E09, 'V'), (0x1E0A, 'M', 'ḋ'), (0x1E0B, 'V'), (0x1E0C, 'M', 'ḍ'), (0x1E0D, 'V'), (0x1E0E, 'M', 'ḏ'), (0x1E0F, 'V'), (0x1E10, 'M', 'ḑ'), (0x1E11, 'V'), (0x1E12, 'M', 'ḓ'), (0x1E13, 'V'), (0x1E14, 'M', 'ḕ'), (0x1E15, 'V'), (0x1E16, 'M', 'ḗ'), (0x1E17, 'V'), (0x1E18, 'M', 'ḙ'), (0x1E19, 'V'), (0x1E1A, 'M', 'ḛ'), (0x1E1B, 'V'), (0x1E1C, 'M', 'ḝ'), (0x1E1D, 'V'), (0x1E1E, 'M', 'ḟ'), (0x1E1F, 'V'), (0x1E20, 'M', 'ḡ'), (0x1E21, 'V'), (0x1E22, 'M', 'ḣ'), (0x1E23, 'V'), ] def _seg_17() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1E24, 'M', 'ḥ'), (0x1E25, 'V'), (0x1E26, 'M', 'ḧ'), (0x1E27, 'V'), (0x1E28, 'M', 'ḩ'), (0x1E29, 'V'), (0x1E2A, 'M', 'ḫ'), (0x1E2B, 'V'), (0x1E2C, 'M', 'ḭ'), (0x1E2D, 'V'), (0x1E2E, 'M', 'ḯ'), (0x1E2F, 'V'), (0x1E30, 'M', 'ḱ'), (0x1E31, 'V'), (0x1E32, 'M', 'ḳ'), (0x1E33, 'V'), (0x1E34, 'M', 'ḵ'), (0x1E35, 'V'), (0x1E36, 'M', 'ḷ'), (0x1E37, 'V'), (0x1E38, 'M', 'ḹ'), (0x1E39, 'V'), (0x1E3A, 'M', 'ḻ'), (0x1E3B, 'V'), (0x1E3C, 'M', 'ḽ'), (0x1E3D, 'V'), (0x1E3E, 'M', 'ḿ'), (0x1E3F, 'V'), (0x1E40, 'M', 'ṁ'), (0x1E41, 'V'), (0x1E42, 'M', 'ṃ'), (0x1E43, 'V'), (0x1E44, 'M', 'ṅ'), (0x1E45, 'V'), (0x1E46, 'M', 'ṇ'), (0x1E47, 'V'), (0x1E48, 'M', 'ṉ'), (0x1E49, 'V'), (0x1E4A, 'M', 'ṋ'), (0x1E4B, 'V'), (0x1E4C, 'M', 'ṍ'), (0x1E4D, 'V'), (0x1E4E, 'M', 'ṏ'), (0x1E4F, 'V'), (0x1E50, 'M', 'ṑ'), (0x1E51, 'V'), (0x1E52, 'M', 'ṓ'), (0x1E53, 'V'), (0x1E54, 'M', 'ṕ'), (0x1E55, 'V'), (0x1E56, 'M', 'ṗ'), (0x1E57, 'V'), (0x1E58, 'M', 'ṙ'), (0x1E59, 'V'), (0x1E5A, 'M', 'ṛ'), (0x1E5B, 'V'), (0x1E5C, 'M', 'ṝ'), (0x1E5D, 'V'), (0x1E5E, 'M', 'ṟ'), (0x1E5F, 'V'), (0x1E60, 'M', 'ṡ'), (0x1E61, 'V'), (0x1E62, 'M', 'ṣ'), (0x1E63, 'V'), (0x1E64, 'M', 'ṥ'), (0x1E65, 'V'), (0x1E66, 'M', 'ṧ'), (0x1E67, 'V'), (0x1E68, 'M', 'ṩ'), (0x1E69, 'V'), (0x1E6A, 'M', 'ṫ'), (0x1E6B, 'V'), (0x1E6C, 'M', 'ṭ'), (0x1E6D, 'V'), (0x1E6E, 'M', 'ṯ'), (0x1E6F, 'V'), (0x1E70, 'M', 'ṱ'), (0x1E71, 'V'), (0x1E72, 'M', 'ṳ'), (0x1E73, 'V'), (0x1E74, 'M', 'ṵ'), (0x1E75, 'V'), (0x1E76, 'M', 'ṷ'), (0x1E77, 'V'), (0x1E78, 'M', 'ṹ'), (0x1E79, 'V'), (0x1E7A, 'M', 'ṻ'), (0x1E7B, 'V'), (0x1E7C, 'M', 'ṽ'), (0x1E7D, 'V'), (0x1E7E, 'M', 'ṿ'), (0x1E7F, 'V'), (0x1E80, 'M', 'ẁ'), (0x1E81, 'V'), (0x1E82, 'M', 'ẃ'), (0x1E83, 'V'), (0x1E84, 'M', 'ẅ'), (0x1E85, 'V'), (0x1E86, 'M', 'ẇ'), (0x1E87, 'V'), ] def _seg_18() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1E88, 'M', 'ẉ'), (0x1E89, 'V'), (0x1E8A, 'M', 'ẋ'), (0x1E8B, 'V'), (0x1E8C, 'M', 'ẍ'), (0x1E8D, 'V'), (0x1E8E, 'M', 'ẏ'), (0x1E8F, 'V'), (0x1E90, 'M', 'ẑ'), (0x1E91, 'V'), (0x1E92, 'M', 'ẓ'), (0x1E93, 'V'), (0x1E94, 'M', 'ẕ'), (0x1E95, 'V'), (0x1E9A, 'M', 'aʾ'), (0x1E9B, 'M', 'ṡ'), (0x1E9C, 'V'), (0x1E9E, 'M', 'ss'), (0x1E9F, 'V'), (0x1EA0, 'M', 'ạ'), (0x1EA1, 'V'), (0x1EA2, 'M', 'ả'), (0x1EA3, 'V'), (0x1EA4, 'M', 'ấ'), (0x1EA5, 'V'), (0x1EA6, 'M', 'ầ'), (0x1EA7, 'V'), (0x1EA8, 'M', 'ẩ'), (0x1EA9, 'V'), (0x1EAA, 'M', 'ẫ'), (0x1EAB, 'V'), (0x1EAC, 'M', 'ậ'), (0x1EAD, 'V'), (0x1EAE, 'M', 'ắ'), (0x1EAF, 'V'), (0x1EB0, 'M', 'ằ'), (0x1EB1, 'V'), (0x1EB2, 'M', 'ẳ'), (0x1EB3, 'V'), (0x1EB4, 'M', 'ẵ'), (0x1EB5, 'V'), (0x1EB6, 'M', 'ặ'), (0x1EB7, 'V'), (0x1EB8, 'M', 'ẹ'), (0x1EB9, 'V'), (0x1EBA, 'M', 'ẻ'), (0x1EBB, 'V'), (0x1EBC, 'M', 'ẽ'), (0x1EBD, 'V'), (0x1EBE, 'M', 'ế'), (0x1EBF, 'V'), (0x1EC0, 'M', 'ề'), (0x1EC1, 'V'), (0x1EC2, 'M', 'ể'), (0x1EC3, 'V'), (0x1EC4, 'M', 'ễ'), (0x1EC5, 'V'), (0x1EC6, 'M', 'ệ'), (0x1EC7, 'V'), (0x1EC8, 'M', 'ỉ'), (0x1EC9, 'V'), (0x1ECA, 'M', 'ị'), (0x1ECB, 'V'), (0x1ECC, 'M', 'ọ'), (0x1ECD, 'V'), (0x1ECE, 'M', 'ỏ'), (0x1ECF, 'V'), (0x1ED0, 'M', 'ố'), (0x1ED1, 'V'), (0x1ED2, 'M', 'ồ'), (0x1ED3, 'V'), (0x1ED4, 'M', 'ổ'), (0x1ED5, 'V'), (0x1ED6, 'M', 'ỗ'), (0x1ED7, 'V'), (0x1ED8, 'M', 'ộ'), (0x1ED9, 'V'), (0x1EDA, 'M', 'ớ'), (0x1EDB, 'V'), (0x1EDC, 'M', 'ờ'), (0x1EDD, 'V'), (0x1EDE, 'M', 'ở'), (0x1EDF, 'V'), (0x1EE0, 'M', 'ỡ'), (0x1EE1, 'V'), (0x1EE2, 'M', 'ợ'), (0x1EE3, 'V'), (0x1EE4, 'M', 'ụ'), (0x1EE5, 'V'), (0x1EE6, 'M', 'ủ'), (0x1EE7, 'V'), (0x1EE8, 'M', 'ứ'), (0x1EE9, 'V'), (0x1EEA, 'M', 'ừ'), (0x1EEB, 'V'), (0x1EEC, 'M', 'ử'), (0x1EED, 'V'), (0x1EEE, 'M', 'ữ'), (0x1EEF, 'V'), (0x1EF0, 'M', 'ự'), ] def _seg_19() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1EF1, 'V'), (0x1EF2, 'M', 'ỳ'), (0x1EF3, 'V'), (0x1EF4, 'M', 'ỵ'), (0x1EF5, 'V'), (0x1EF6, 'M', 'ỷ'), (0x1EF7, 'V'), (0x1EF8, 'M', 'ỹ'), (0x1EF9, 'V'), (0x1EFA, 'M', 'ỻ'), (0x1EFB, 'V'), (0x1EFC, 'M', 'ỽ'), (0x1EFD, 'V'), (0x1EFE, 'M', 'ỿ'), (0x1EFF, 'V'), (0x1F08, 'M', 'ἀ'), (0x1F09, 'M', 'ἁ'), (0x1F0A, 'M', 'ἂ'), (0x1F0B, 'M', 'ἃ'), (0x1F0C, 'M', 'ἄ'), (0x1F0D, 'M', 'ἅ'), (0x1F0E, 'M', 'ἆ'), (0x1F0F, 'M', 'ἇ'), (0x1F10, 'V'), (0x1F16, 'X'), (0x1F18, 'M', 'ἐ'), (0x1F19, 'M', 'ἑ'), (0x1F1A, 'M', 'ἒ'), (0x1F1B, 'M', 'ἓ'), (0x1F1C, 'M', 'ἔ'), (0x1F1D, 'M', 'ἕ'), (0x1F1E, 'X'), (0x1F20, 'V'), (0x1F28, 'M', 'ἠ'), (0x1F29, 'M', 'ἡ'), (0x1F2A, 'M', 'ἢ'), (0x1F2B, 'M', 'ἣ'), (0x1F2C, 'M', 'ἤ'), (0x1F2D, 'M', 'ἥ'), (0x1F2E, 'M', 'ἦ'), (0x1F2F, 'M', 'ἧ'), (0x1F30, 'V'), (0x1F38, 'M', 'ἰ'), (0x1F39, 'M', 'ἱ'), (0x1F3A, 'M', 'ἲ'), (0x1F3B, 'M', 'ἳ'), (0x1F3C, 'M', 'ἴ'), (0x1F3D, 'M', 'ἵ'), (0x1F3E, 'M', 'ἶ'), (0x1F3F, 'M', 'ἷ'), (0x1F40, 'V'), (0x1F46, 'X'), (0x1F48, 'M', 'ὀ'), (0x1F49, 'M', 'ὁ'), (0x1F4A, 'M', 'ὂ'), (0x1F4B, 'M', 'ὃ'), (0x1F4C, 'M', 'ὄ'), (0x1F4D, 'M', 'ὅ'), (0x1F4E, 'X'), (0x1F50, 'V'), (0x1F58, 'X'), (0x1F59, 'M', 'ὑ'), (0x1F5A, 'X'), (0x1F5B, 'M', 'ὓ'), (0x1F5C, 'X'), (0x1F5D, 'M', 'ὕ'), (0x1F5E, 'X'), (0x1F5F, 'M', 'ὗ'), (0x1F60, 'V'), (0x1F68, 'M', 'ὠ'), (0x1F69, 'M', 'ὡ'), (0x1F6A, 'M', 'ὢ'), (0x1F6B, 'M', 'ὣ'), (0x1F6C, 'M', 'ὤ'), (0x1F6D, 'M', 'ὥ'), (0x1F6E, 'M', 'ὦ'), (0x1F6F, 'M', 'ὧ'), (0x1F70, 'V'), (0x1F71, 'M', 'ά'), (0x1F72, 'V'), (0x1F73, 'M', 'έ'), (0x1F74, 'V'), (0x1F75, 'M', 'ή'), (0x1F76, 'V'), (0x1F77, 'M', 'ί'), (0x1F78, 'V'), (0x1F79, 'M', 'ό'), (0x1F7A, 'V'), (0x1F7B, 'M', 'ύ'), (0x1F7C, 'V'), (0x1F7D, 'M', 'ώ'), (0x1F7E, 'X'), (0x1F80, 'M', 'ἀι'), (0x1F81, 'M', 'ἁι'), (0x1F82, 'M', 'ἂι'), (0x1F83, 'M', 'ἃι'), (0x1F84, 'M', 'ἄι'), (0x1F85, 'M', 'ἅι'), (0x1F86, 'M', 'ἆι'), (0x1F87, 'M', 'ἇι'), ] def _seg_20() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1F88, 'M', 'ἀι'), (0x1F89, 'M', 'ἁι'), (0x1F8A, 'M', 'ἂι'), (0x1F8B, 'M', 'ἃι'), (0x1F8C, 'M', 'ἄι'), (0x1F8D, 'M', 'ἅι'), (0x1F8E, 'M', 'ἆι'), (0x1F8F, 'M', 'ἇι'), (0x1F90, 'M', 'ἠι'), (0x1F91, 'M', 'ἡι'), (0x1F92, 'M', 'ἢι'), (0x1F93, 'M', 'ἣι'), (0x1F94, 'M', 'ἤι'), (0x1F95, 'M', 'ἥι'), (0x1F96, 'M', 'ἦι'), (0x1F97, 'M', 'ἧι'), (0x1F98, 'M', 'ἠι'), (0x1F99, 'M', 'ἡι'), (0x1F9A, 'M', 'ἢι'), (0x1F9B, 'M', 'ἣι'), (0x1F9C, 'M', 'ἤι'), (0x1F9D, 'M', 'ἥι'), (0x1F9E, 'M', 'ἦι'), (0x1F9F, 'M', 'ἧι'), (0x1FA0, 'M', 'ὠι'), (0x1FA1, 'M', 'ὡι'), (0x1FA2, 'M', 'ὢι'), (0x1FA3, 'M', 'ὣι'), (0x1FA4, 'M', 'ὤι'), (0x1FA5, 'M', 'ὥι'), (0x1FA6, 'M', 'ὦι'), (0x1FA7, 'M', 'ὧι'), (0x1FA8, 'M', 'ὠι'), (0x1FA9, 'M', 'ὡι'), (0x1FAA, 'M', 'ὢι'), (0x1FAB, 'M', 'ὣι'), (0x1FAC, 'M', 'ὤι'), (0x1FAD, 'M', 'ὥι'), (0x1FAE, 'M', 'ὦι'), (0x1FAF, 'M', 'ὧι'), (0x1FB0, 'V'), (0x1FB2, 'M', 'ὰι'), (0x1FB3, 'M', 'αι'), (0x1FB4, 'M', 'άι'), (0x1FB5, 'X'), (0x1FB6, 'V'), (0x1FB7, 'M', 'ᾶι'), (0x1FB8, 'M', 'ᾰ'), (0x1FB9, 'M', 'ᾱ'), (0x1FBA, 'M', 'ὰ'), (0x1FBB, 'M', 'ά'), (0x1FBC, 'M', 'αι'), (0x1FBD, '3', ' ̓'), (0x1FBE, 'M', 'ι'), (0x1FBF, '3', ' ̓'), (0x1FC0, '3', ' ͂'), (0x1FC1, '3', ' ̈͂'), (0x1FC2, 'M', 'ὴι'), (0x1FC3, 'M', 'ηι'), (0x1FC4, 'M', 'ήι'), (0x1FC5, 'X'), (0x1FC6, 'V'), (0x1FC7, 'M', 'ῆι'), (0x1FC8, 'M', 'ὲ'), (0x1FC9, 'M', 'έ'), (0x1FCA, 'M', 'ὴ'), (0x1FCB, 'M', 'ή'), (0x1FCC, 'M', 'ηι'), (0x1FCD, '3', ' ̓̀'), (0x1FCE, '3', ' ̓́'), (0x1FCF, '3', ' ̓͂'), (0x1FD0, 'V'), (0x1FD3, 'M', 'ΐ'), (0x1FD4, 'X'), (0x1FD6, 'V'), (0x1FD8, 'M', 'ῐ'), (0x1FD9, 'M', 'ῑ'), (0x1FDA, 'M', 'ὶ'), (0x1FDB, 'M', 'ί'), (0x1FDC, 'X'), (0x1FDD, '3', ' ̔̀'), (0x1FDE, '3', ' ̔́'), (0x1FDF, '3', ' ̔͂'), (0x1FE0, 'V'), (0x1FE3, 'M', 'ΰ'), (0x1FE4, 'V'), (0x1FE8, 'M', 'ῠ'), (0x1FE9, 'M', 'ῡ'), (0x1FEA, 'M', 'ὺ'), (0x1FEB, 'M', 'ύ'), (0x1FEC, 'M', 'ῥ'), (0x1FED, '3', ' ̈̀'), (0x1FEE, '3', ' ̈́'), (0x1FEF, '3', '`'), (0x1FF0, 'X'), (0x1FF2, 'M', 'ὼι'), (0x1FF3, 'M', 'ωι'), (0x1FF4, 'M', 'ώι'), (0x1FF5, 'X'), (0x1FF6, 'V'), ] def _seg_21() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1FF7, 'M', 'ῶι'), (0x1FF8, 'M', 'ὸ'), (0x1FF9, 'M', 'ό'), (0x1FFA, 'M', 'ὼ'), (0x1FFB, 'M', 'ώ'), (0x1FFC, 'M', 'ωι'), (0x1FFD, '3', ' ́'), (0x1FFE, '3', ' ̔'), (0x1FFF, 'X'), (0x2000, '3', ' '), (0x200B, 'I'), (0x200C, 'D', ''), (0x200E, 'X'), (0x2010, 'V'), (0x2011, 'M', '‐'), (0x2012, 'V'), (0x2017, '3', ' ̳'), (0x2018, 'V'), (0x2024, 'X'), (0x2027, 'V'), (0x2028, 'X'), (0x202F, '3', ' '), (0x2030, 'V'), (0x2033, 'M', '′′'), (0x2034, 'M', '′′′'), (0x2035, 'V'), (0x2036, 'M', '‵‵'), (0x2037, 'M', '‵‵‵'), (0x2038, 'V'), (0x203C, '3', '!!'), (0x203D, 'V'), (0x203E, '3', ' ̅'), (0x203F, 'V'), (0x2047, '3', '??'), (0x2048, '3', '?!'), (0x2049, '3', '!?'), (0x204A, 'V'), (0x2057, 'M', '′′′′'), (0x2058, 'V'), (0x205F, '3', ' '), (0x2060, 'I'), (0x2061, 'X'), (0x2064, 'I'), (0x2065, 'X'), (0x2070, 'M', '0'), (0x2071, 'M', 'i'), (0x2072, 'X'), (0x2074, 'M', '4'), (0x2075, 'M', '5'), (0x2076, 'M', '6'), (0x2077, 'M', '7'), (0x2078, 'M', '8'), (0x2079, 'M', '9'), (0x207A, '3', '+'), (0x207B, 'M', '−'), (0x207C, '3', '='), (0x207D, '3', '('), (0x207E, '3', ')'), (0x207F, 'M', 'n'), (0x2080, 'M', '0'), (0x2081, 'M', '1'), (0x2082, 'M', '2'), (0x2083, 'M', '3'), (0x2084, 'M', '4'), (0x2085, 'M', '5'), (0x2086, 'M', '6'), (0x2087, 'M', '7'), (0x2088, 'M', '8'), (0x2089, 'M', '9'), (0x208A, '3', '+'), (0x208B, 'M', '−'), (0x208C, '3', '='), (0x208D, '3', '('), (0x208E, '3', ')'), (0x208F, 'X'), (0x2090, 'M', 'a'), (0x2091, 'M', 'e'), (0x2092, 'M', 'o'), (0x2093, 'M', 'x'), (0x2094, 'M', 'ə'), (0x2095, 'M', 'h'), (0x2096, 'M', 'k'), (0x2097, 'M', 'l'), (0x2098, 'M', 'm'), (0x2099, 'M', 'n'), (0x209A, 'M', 'p'), (0x209B, 'M', 's'), (0x209C, 'M', 't'), (0x209D, 'X'), (0x20A0, 'V'), (0x20A8, 'M', 'rs'), (0x20A9, 'V'), (0x20C1, 'X'), (0x20D0, 'V'), (0x20F1, 'X'), (0x2100, '3', 'a/c'), (0x2101, '3', 'a/s'), (0x2102, 'M', 'c'), (0x2103, 'M', '°c'), (0x2104, 'V'), ] def _seg_22() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2105, '3', 'c/o'), (0x2106, '3', 'c/u'), (0x2107, 'M', 'ɛ'), (0x2108, 'V'), (0x2109, 'M', '°f'), (0x210A, 'M', 'g'), (0x210B, 'M', 'h'), (0x210F, 'M', 'ħ'), (0x2110, 'M', 'i'), (0x2112, 'M', 'l'), (0x2114, 'V'), (0x2115, 'M', 'n'), (0x2116, 'M', 'no'), (0x2117, 'V'), (0x2119, 'M', 'p'), (0x211A, 'M', 'q'), (0x211B, 'M', 'r'), (0x211E, 'V'), (0x2120, 'M', 'sm'), (0x2121, 'M', 'tel'), (0x2122, 'M', 'tm'), (0x2123, 'V'), (0x2124, 'M', 'z'), (0x2125, 'V'), (0x2126, 'M', 'ω'), (0x2127, 'V'), (0x2128, 'M', 'z'), (0x2129, 'V'), (0x212A, 'M', 'k'), (0x212B, 'M', 'å'), (0x212C, 'M', 'b'), (0x212D, 'M', 'c'), (0x212E, 'V'), (0x212F, 'M', 'e'), (0x2131, 'M', 'f'), (0x2132, 'X'), (0x2133, 'M', 'm'), (0x2134, 'M', 'o'), (0x2135, 'M', 'א'), (0x2136, 'M', 'ב'), (0x2137, 'M', 'ג'), (0x2138, 'M', 'ד'), (0x2139, 'M', 'i'), (0x213A, 'V'), (0x213B, 'M', 'fax'), (0x213C, 'M', 'π'), (0x213D, 'M', 'γ'), (0x213F, 'M', 'π'), (0x2140, 'M', '∑'), (0x2141, 'V'), (0x2145, 'M', 'd'), (0x2147, 'M', 'e'), (0x2148, 'M', 'i'), (0x2149, 'M', 'j'), (0x214A, 'V'), (0x2150, 'M', '1⁄7'), (0x2151, 'M', '1⁄9'), (0x2152, 'M', '1⁄10'), (0x2153, 'M', '1⁄3'), (0x2154, 'M', '2⁄3'), (0x2155, 'M', '1⁄5'), (0x2156, 'M', '2⁄5'), (0x2157, 'M', '3⁄5'), (0x2158, 'M', '4⁄5'), (0x2159, 'M', '1⁄6'), (0x215A, 'M', '5⁄6'), (0x215B, 'M', '1⁄8'), (0x215C, 'M', '3⁄8'), (0x215D, 'M', '5⁄8'), (0x215E, 'M', '7⁄8'), (0x215F, 'M', '1⁄'), (0x2160, 'M', 'i'), (0x2161, 'M', 'ii'), (0x2162, 'M', 'iii'), (0x2163, 'M', 'iv'), (0x2164, 'M', 'v'), (0x2165, 'M', 'vi'), (0x2166, 'M', 'vii'), (0x2167, 'M', 'viii'), (0x2168, 'M', 'ix'), (0x2169, 'M', 'x'), (0x216A, 'M', 'xi'), (0x216B, 'M', 'xii'), (0x216C, 'M', 'l'), (0x216D, 'M', 'c'), (0x216E, 'M', 'd'), (0x216F, 'M', 'm'), (0x2170, 'M', 'i'), (0x2171, 'M', 'ii'), (0x2172, 'M', 'iii'), (0x2173, 'M', 'iv'), (0x2174, 'M', 'v'), (0x2175, 'M', 'vi'), (0x2176, 'M', 'vii'), (0x2177, 'M', 'viii'), (0x2178, 'M', 'ix'), (0x2179, 'M', 'x'), (0x217A, 'M', 'xi'), (0x217B, 'M', 'xii'), (0x217C, 'M', 'l'), ] def _seg_23() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x217D, 'M', 'c'), (0x217E, 'M', 'd'), (0x217F, 'M', 'm'), (0x2180, 'V'), (0x2183, 'X'), (0x2184, 'V'), (0x2189, 'M', '0⁄3'), (0x218A, 'V'), (0x218C, 'X'), (0x2190, 'V'), (0x222C, 'M', '∫∫'), (0x222D, 'M', '∫∫∫'), (0x222E, 'V'), (0x222F, 'M', '∮∮'), (0x2230, 'M', '∮∮∮'), (0x2231, 'V'), (0x2260, '3'), (0x2261, 'V'), (0x226E, '3'), (0x2270, 'V'), (0x2329, 'M', '〈'), (0x232A, 'M', '〉'), (0x232B, 'V'), (0x2427, 'X'), (0x2440, 'V'), (0x244B, 'X'), (0x2460, 'M', '1'), (0x2461, 'M', '2'), (0x2462, 'M', '3'), (0x2463, 'M', '4'), (0x2464, 'M', '5'), (0x2465, 'M', '6'), (0x2466, 'M', '7'), (0x2467, 'M', '8'), (0x2468, 'M', '9'), (0x2469, 'M', '10'), (0x246A, 'M', '11'), (0x246B, 'M', '12'), (0x246C, 'M', '13'), (0x246D, 'M', '14'), (0x246E, 'M', '15'), (0x246F, 'M', '16'), (0x2470, 'M', '17'), (0x2471, 'M', '18'), (0x2472, 'M', '19'), (0x2473, 'M', '20'), (0x2474, '3', '(1)'), (0x2475, '3', '(2)'), (0x2476, '3', '(3)'), (0x2477, '3', '(4)'), (0x2478, '3', '(5)'), (0x2479, '3', '(6)'), (0x247A, '3', '(7)'), (0x247B, '3', '(8)'), (0x247C, '3', '(9)'), (0x247D, '3', '(10)'), (0x247E, '3', '(11)'), (0x247F, '3', '(12)'), (0x2480, '3', '(13)'), (0x2481, '3', '(14)'), (0x2482, '3', '(15)'), (0x2483, '3', '(16)'), (0x2484, '3', '(17)'), (0x2485, '3', '(18)'), (0x2486, '3', '(19)'), (0x2487, '3', '(20)'), (0x2488, 'X'), (0x249C, '3', '(a)'), (0x249D, '3', '(b)'), (0x249E, '3', '(c)'), (0x249F, '3', '(d)'), (0x24A0, '3', '(e)'), (0x24A1, '3', '(f)'), (0x24A2, '3', '(g)'), (0x24A3, '3', '(h)'), (0x24A4, '3', '(i)'), (0x24A5, '3', '(j)'), (0x24A6, '3', '(k)'), (0x24A7, '3', '(l)'), (0x24A8, '3', '(m)'), (0x24A9, '3', '(n)'), (0x24AA, '3', '(o)'), (0x24AB, '3', '(p)'), (0x24AC, '3', '(q)'), (0x24AD, '3', '(r)'), (0x24AE, '3', '(s)'), (0x24AF, '3', '(t)'), (0x24B0, '3', '(u)'), (0x24B1, '3', '(v)'), (0x24B2, '3', '(w)'), (0x24B3, '3', '(x)'), (0x24B4, '3', '(y)'), (0x24B5, '3', '(z)'), (0x24B6, 'M', 'a'), (0x24B7, 'M', 'b'), (0x24B8, 'M', 'c'), (0x24B9, 'M', 'd'), (0x24BA, 'M', 'e'), (0x24BB, 'M', 'f'), (0x24BC, 'M', 'g'), ] def _seg_24() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x24BD, 'M', 'h'), (0x24BE, 'M', 'i'), (0x24BF, 'M', 'j'), (0x24C0, 'M', 'k'), (0x24C1, 'M', 'l'), (0x24C2, 'M', 'm'), (0x24C3, 'M', 'n'), (0x24C4, 'M', 'o'), (0x24C5, 'M', 'p'), (0x24C6, 'M', 'q'), (0x24C7, 'M', 'r'), (0x24C8, 'M', 's'), (0x24C9, 'M', 't'), (0x24CA, 'M', 'u'), (0x24CB, 'M', 'v'), (0x24CC, 'M', 'w'), (0x24CD, 'M', 'x'), (0x24CE, 'M', 'y'), (0x24CF, 'M', 'z'), (0x24D0, 'M', 'a'), (0x24D1, 'M', 'b'), (0x24D2, 'M', 'c'), (0x24D3, 'M', 'd'), (0x24D4, 'M', 'e'), (0x24D5, 'M', 'f'), (0x24D6, 'M', 'g'), (0x24D7, 'M', 'h'), (0x24D8, 'M', 'i'), (0x24D9, 'M', 'j'), (0x24DA, 'M', 'k'), (0x24DB, 'M', 'l'), (0x24DC, 'M', 'm'), (0x24DD, 'M', 'n'), (0x24DE, 'M', 'o'), (0x24DF, 'M', 'p'), (0x24E0, 'M', 'q'), (0x24E1, 'M', 'r'), (0x24E2, 'M', 's'), (0x24E3, 'M', 't'), (0x24E4, 'M', 'u'), (0x24E5, 'M', 'v'), (0x24E6, 'M', 'w'), (0x24E7, 'M', 'x'), (0x24E8, 'M', 'y'), (0x24E9, 'M', 'z'), (0x24EA, 'M', '0'), (0x24EB, 'V'), (0x2A0C, 'M', '∫∫∫∫'), (0x2A0D, 'V'), (0x2A74, '3', '::='), (0x2A75, '3', '=='), (0x2A76, '3', '==='), (0x2A77, 'V'), (0x2ADC, 'M', '⫝̸'), (0x2ADD, 'V'), (0x2B74, 'X'), (0x2B76, 'V'), (0x2B96, 'X'), (0x2B97, 'V'), (0x2C00, 'M', 'ⰰ'), (0x2C01, 'M', 'ⰱ'), (0x2C02, 'M', 'ⰲ'), (0x2C03, 'M', 'ⰳ'), (0x2C04, 'M', 'ⰴ'), (0x2C05, 'M', 'ⰵ'), (0x2C06, 'M', 'ⰶ'), (0x2C07, 'M', 'ⰷ'), (0x2C08, 'M', 'ⰸ'), (0x2C09, 'M', 'ⰹ'), (0x2C0A, 'M', 'ⰺ'), (0x2C0B, 'M', 'ⰻ'), (0x2C0C, 'M', 'ⰼ'), (0x2C0D, 'M', 'ⰽ'), (0x2C0E, 'M', 'ⰾ'), (0x2C0F, 'M', 'ⰿ'), (0x2C10, 'M', 'ⱀ'), (0x2C11, 'M', 'ⱁ'), (0x2C12, 'M', 'ⱂ'), (0x2C13, 'M', 'ⱃ'), (0x2C14, 'M', 'ⱄ'), (0x2C15, 'M', 'ⱅ'), (0x2C16, 'M', 'ⱆ'), (0x2C17, 'M', 'ⱇ'), (0x2C18, 'M', 'ⱈ'), (0x2C19, 'M', 'ⱉ'), (0x2C1A, 'M', 'ⱊ'), (0x2C1B, 'M', 'ⱋ'), (0x2C1C, 'M', 'ⱌ'), (0x2C1D, 'M', 'ⱍ'), (0x2C1E, 'M', 'ⱎ'), (0x2C1F, 'M', 'ⱏ'), (0x2C20, 'M', 'ⱐ'), (0x2C21, 'M', 'ⱑ'), (0x2C22, 'M', 'ⱒ'), (0x2C23, 'M', 'ⱓ'), (0x2C24, 'M', 'ⱔ'), (0x2C25, 'M', 'ⱕ'), (0x2C26, 'M', 'ⱖ'), (0x2C27, 'M', 'ⱗ'), (0x2C28, 'M', 'ⱘ'), ] def _seg_25() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2C29, 'M', 'ⱙ'), (0x2C2A, 'M', 'ⱚ'), (0x2C2B, 'M', 'ⱛ'), (0x2C2C, 'M', 'ⱜ'), (0x2C2D, 'M', 'ⱝ'), (0x2C2E, 'M', 'ⱞ'), (0x2C2F, 'M', 'ⱟ'), (0x2C30, 'V'), (0x2C60, 'M', 'ⱡ'), (0x2C61, 'V'), (0x2C62, 'M', 'ɫ'), (0x2C63, 'M', 'ᵽ'), (0x2C64, 'M', 'ɽ'), (0x2C65, 'V'), (0x2C67, 'M', 'ⱨ'), (0x2C68, 'V'), (0x2C69, 'M', 'ⱪ'), (0x2C6A, 'V'), (0x2C6B, 'M', 'ⱬ'), (0x2C6C, 'V'), (0x2C6D, 'M', 'ɑ'), (0x2C6E, 'M', 'ɱ'), (0x2C6F, 'M', 'ɐ'), (0x2C70, 'M', 'ɒ'), (0x2C71, 'V'), (0x2C72, 'M', 'ⱳ'), (0x2C73, 'V'), (0x2C75, 'M', 'ⱶ'), (0x2C76, 'V'), (0x2C7C, 'M', 'j'), (0x2C7D, 'M', 'v'), (0x2C7E, 'M', 'ȿ'), (0x2C7F, 'M', 'ɀ'), (0x2C80, 'M', 'ⲁ'), (0x2C81, 'V'), (0x2C82, 'M', 'ⲃ'), (0x2C83, 'V'), (0x2C84, 'M', 'ⲅ'), (0x2C85, 'V'), (0x2C86, 'M', 'ⲇ'), (0x2C87, 'V'), (0x2C88, 'M', 'ⲉ'), (0x2C89, 'V'), (0x2C8A, 'M', 'ⲋ'), (0x2C8B, 'V'), (0x2C8C, 'M', 'ⲍ'), (0x2C8D, 'V'), (0x2C8E, 'M', 'ⲏ'), (0x2C8F, 'V'), (0x2C90, 'M', 'ⲑ'), (0x2C91, 'V'), (0x2C92, 'M', 'ⲓ'), (0x2C93, 'V'), (0x2C94, 'M', 'ⲕ'), (0x2C95, 'V'), (0x2C96, 'M', 'ⲗ'), (0x2C97, 'V'), (0x2C98, 'M', 'ⲙ'), (0x2C99, 'V'), (0x2C9A, 'M', 'ⲛ'), (0x2C9B, 'V'), (0x2C9C, 'M', 'ⲝ'), (0x2C9D, 'V'), (0x2C9E, 'M', 'ⲟ'), (0x2C9F, 'V'), (0x2CA0, 'M', 'ⲡ'), (0x2CA1, 'V'), (0x2CA2, 'M', 'ⲣ'), (0x2CA3, 'V'), (0x2CA4, 'M', 'ⲥ'), (0x2CA5, 'V'), (0x2CA6, 'M', 'ⲧ'), (0x2CA7, 'V'), (0x2CA8, 'M', 'ⲩ'), (0x2CA9, 'V'), (0x2CAA, 'M', 'ⲫ'), (0x2CAB, 'V'), (0x2CAC, 'M', 'ⲭ'), (0x2CAD, 'V'), (0x2CAE, 'M', 'ⲯ'), (0x2CAF, 'V'), (0x2CB0, 'M', 'ⲱ'), (0x2CB1, 'V'), (0x2CB2, 'M', 'ⲳ'), (0x2CB3, 'V'), (0x2CB4, 'M', 'ⲵ'), (0x2CB5, 'V'), (0x2CB6, 'M', 'ⲷ'), (0x2CB7, 'V'), (0x2CB8, 'M', 'ⲹ'), (0x2CB9, 'V'), (0x2CBA, 'M', 'ⲻ'), (0x2CBB, 'V'), (0x2CBC, 'M', 'ⲽ'), (0x2CBD, 'V'), (0x2CBE, 'M', 'ⲿ'), (0x2CBF, 'V'), (0x2CC0, 'M', 'ⳁ'), (0x2CC1, 'V'), (0x2CC2, 'M', 'ⳃ'), ] def _seg_26() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2CC3, 'V'), (0x2CC4, 'M', 'ⳅ'), (0x2CC5, 'V'), (0x2CC6, 'M', 'ⳇ'), (0x2CC7, 'V'), (0x2CC8, 'M', 'ⳉ'), (0x2CC9, 'V'), (0x2CCA, 'M', 'ⳋ'), (0x2CCB, 'V'), (0x2CCC, 'M', 'ⳍ'), (0x2CCD, 'V'), (0x2CCE, 'M', 'ⳏ'), (0x2CCF, 'V'), (0x2CD0, 'M', 'ⳑ'), (0x2CD1, 'V'), (0x2CD2, 'M', 'ⳓ'), (0x2CD3, 'V'), (0x2CD4, 'M', 'ⳕ'), (0x2CD5, 'V'), (0x2CD6, 'M', 'ⳗ'), (0x2CD7, 'V'), (0x2CD8, 'M', 'ⳙ'), (0x2CD9, 'V'), (0x2CDA, 'M', 'ⳛ'), (0x2CDB, 'V'), (0x2CDC, 'M', 'ⳝ'), (0x2CDD, 'V'), (0x2CDE, 'M', 'ⳟ'), (0x2CDF, 'V'), (0x2CE0, 'M', 'ⳡ'), (0x2CE1, 'V'), (0x2CE2, 'M', 'ⳣ'), (0x2CE3, 'V'), (0x2CEB, 'M', 'ⳬ'), (0x2CEC, 'V'), (0x2CED, 'M', 'ⳮ'), (0x2CEE, 'V'), (0x2CF2, 'M', 'ⳳ'), (0x2CF3, 'V'), (0x2CF4, 'X'), (0x2CF9, 'V'), (0x2D26, 'X'), (0x2D27, 'V'), (0x2D28, 'X'), (0x2D2D, 'V'), (0x2D2E, 'X'), (0x2D30, 'V'), (0x2D68, 'X'), (0x2D6F, 'M', 'ⵡ'), (0x2D70, 'V'), (0x2D71, 'X'), (0x2D7F, 'V'), (0x2D97, 'X'), (0x2DA0, 'V'), (0x2DA7, 'X'), (0x2DA8, 'V'), (0x2DAF, 'X'), (0x2DB0, 'V'), (0x2DB7, 'X'), (0x2DB8, 'V'), (0x2DBF, 'X'), (0x2DC0, 'V'), (0x2DC7, 'X'), (0x2DC8, 'V'), (0x2DCF, 'X'), (0x2DD0, 'V'), (0x2DD7, 'X'), (0x2DD8, 'V'), (0x2DDF, 'X'), (0x2DE0, 'V'), (0x2E5E, 'X'), (0x2E80, 'V'), (0x2E9A, 'X'), (0x2E9B, 'V'), (0x2E9F, 'M', '母'), (0x2EA0, 'V'), (0x2EF3, 'M', '龟'), (0x2EF4, 'X'), (0x2F00, 'M', '一'), (0x2F01, 'M', '丨'), (0x2F02, 'M', '丶'), (0x2F03, 'M', '丿'), (0x2F04, 'M', '乙'), (0x2F05, 'M', '亅'), (0x2F06, 'M', '二'), (0x2F07, 'M', '亠'), (0x2F08, 'M', '人'), (0x2F09, 'M', '儿'), (0x2F0A, 'M', '入'), (0x2F0B, 'M', '八'), (0x2F0C, 'M', '冂'), (0x2F0D, 'M', '冖'), (0x2F0E, 'M', '冫'), (0x2F0F, 'M', '几'), (0x2F10, 'M', '凵'), (0x2F11, 'M', '刀'), (0x2F12, 'M', '力'), (0x2F13, 'M', '勹'), (0x2F14, 'M', '匕'), (0x2F15, 'M', '匚'), ] def _seg_27() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2F16, 'M', '匸'), (0x2F17, 'M', '十'), (0x2F18, 'M', '卜'), (0x2F19, 'M', '卩'), (0x2F1A, 'M', '厂'), (0x2F1B, 'M', '厶'), (0x2F1C, 'M', '又'), (0x2F1D, 'M', '口'), (0x2F1E, 'M', '囗'), (0x2F1F, 'M', '土'), (0x2F20, 'M', '士'), (0x2F21, 'M', '夂'), (0x2F22, 'M', '夊'), (0x2F23, 'M', '夕'), (0x2F24, 'M', '大'), (0x2F25, 'M', '女'), (0x2F26, 'M', '子'), (0x2F27, 'M', '宀'), (0x2F28, 'M', '寸'), (0x2F29, 'M', '小'), (0x2F2A, 'M', '尢'), (0x2F2B, 'M', '尸'), (0x2F2C, 'M', '屮'), (0x2F2D, 'M', '山'), (0x2F2E, 'M', '巛'), (0x2F2F, 'M', '工'), (0x2F30, 'M', '己'), (0x2F31, 'M', '巾'), (0x2F32, 'M', '干'), (0x2F33, 'M', '幺'), (0x2F34, 'M', '广'), (0x2F35, 'M', '廴'), (0x2F36, 'M', '廾'), (0x2F37, 'M', '弋'), (0x2F38, 'M', '弓'), (0x2F39, 'M', '彐'), (0x2F3A, 'M', '彡'), (0x2F3B, 'M', '彳'), (0x2F3C, 'M', '心'), (0x2F3D, 'M', '戈'), (0x2F3E, 'M', '戶'), (0x2F3F, 'M', '手'), (0x2F40, 'M', '支'), (0x2F41, 'M', '攴'), (0x2F42, 'M', '文'), (0x2F43, 'M', '斗'), (0x2F44, 'M', '斤'), (0x2F45, 'M', '方'), (0x2F46, 'M', '无'), (0x2F47, 'M', '日'), (0x2F48, 'M', '曰'), (0x2F49, 'M', '月'), (0x2F4A, 'M', '木'), (0x2F4B, 'M', '欠'), (0x2F4C, 'M', '止'), (0x2F4D, 'M', '歹'), (0x2F4E, 'M', '殳'), (0x2F4F, 'M', '毋'), (0x2F50, 'M', '比'), (0x2F51, 'M', '毛'), (0x2F52, 'M', '氏'), (0x2F53, 'M', '气'), (0x2F54, 'M', '水'), (0x2F55, 'M', '火'), (0x2F56, 'M', '爪'), (0x2F57, 'M', '父'), (0x2F58, 'M', '爻'), (0x2F59, 'M', '爿'), (0x2F5A, 'M', '片'), (0x2F5B, 'M', '牙'), (0x2F5C, 'M', '牛'), (0x2F5D, 'M', '犬'), (0x2F5E, 'M', '玄'), (0x2F5F, 'M', '玉'), (0x2F60, 'M', '瓜'), (0x2F61, 'M', '瓦'), (0x2F62, 'M', '甘'), (0x2F63, 'M', '生'), (0x2F64, 'M', '用'), (0x2F65, 'M', '田'), (0x2F66, 'M', '疋'), (0x2F67, 'M', '疒'), (0x2F68, 'M', '癶'), (0x2F69, 'M', '白'), (0x2F6A, 'M', '皮'), (0x2F6B, 'M', '皿'), (0x2F6C, 'M', '目'), (0x2F6D, 'M', '矛'), (0x2F6E, 'M', '矢'), (0x2F6F, 'M', '石'), (0x2F70, 'M', '示'), (0x2F71, 'M', '禸'), (0x2F72, 'M', '禾'), (0x2F73, 'M', '穴'), (0x2F74, 'M', '立'), (0x2F75, 'M', '竹'), (0x2F76, 'M', '米'), (0x2F77, 'M', '糸'), (0x2F78, 'M', '缶'), (0x2F79, 'M', '网'), ] def _seg_28() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2F7A, 'M', '羊'), (0x2F7B, 'M', '羽'), (0x2F7C, 'M', '老'), (0x2F7D, 'M', '而'), (0x2F7E, 'M', '耒'), (0x2F7F, 'M', '耳'), (0x2F80, 'M', '聿'), (0x2F81, 'M', '肉'), (0x2F82, 'M', '臣'), (0x2F83, 'M', '自'), (0x2F84, 'M', '至'), (0x2F85, 'M', '臼'), (0x2F86, 'M', '舌'), (0x2F87, 'M', '舛'), (0x2F88, 'M', '舟'), (0x2F89, 'M', '艮'), (0x2F8A, 'M', '色'), (0x2F8B, 'M', '艸'), (0x2F8C, 'M', '虍'), (0x2F8D, 'M', '虫'), (0x2F8E, 'M', '血'), (0x2F8F, 'M', '行'), (0x2F90, 'M', '衣'), (0x2F91, 'M', '襾'), (0x2F92, 'M', '見'), (0x2F93, 'M', '角'), (0x2F94, 'M', '言'), (0x2F95, 'M', '谷'), (0x2F96, 'M', '豆'), (0x2F97, 'M', '豕'), (0x2F98, 'M', '豸'), (0x2F99, 'M', '貝'), (0x2F9A, 'M', '赤'), (0x2F9B, 'M', '走'), (0x2F9C, 'M', '足'), (0x2F9D, 'M', '身'), (0x2F9E, 'M', '車'), (0x2F9F, 'M', '辛'), (0x2FA0, 'M', '辰'), (0x2FA1, 'M', '辵'), (0x2FA2, 'M', '邑'), (0x2FA3, 'M', '酉'), (0x2FA4, 'M', '釆'), (0x2FA5, 'M', '里'), (0x2FA6, 'M', '金'), (0x2FA7, 'M', '長'), (0x2FA8, 'M', '門'), (0x2FA9, 'M', '阜'), (0x2FAA, 'M', '隶'), (0x2FAB, 'M', '隹'), (0x2FAC, 'M', '雨'), (0x2FAD, 'M', '靑'), (0x2FAE, 'M', '非'), (0x2FAF, 'M', '面'), (0x2FB0, 'M', '革'), (0x2FB1, 'M', '韋'), (0x2FB2, 'M', '韭'), (0x2FB3, 'M', '音'), (0x2FB4, 'M', '頁'), (0x2FB5, 'M', '風'), (0x2FB6, 'M', '飛'), (0x2FB7, 'M', '食'), (0x2FB8, 'M', '首'), (0x2FB9, 'M', '香'), (0x2FBA, 'M', '馬'), (0x2FBB, 'M', '骨'), (0x2FBC, 'M', '高'), (0x2FBD, 'M', '髟'), (0x2FBE, 'M', '鬥'), (0x2FBF, 'M', '鬯'), (0x2FC0, 'M', '鬲'), (0x2FC1, 'M', '鬼'), (0x2FC2, 'M', '魚'), (0x2FC3, 'M', '鳥'), (0x2FC4, 'M', '鹵'), (0x2FC5, 'M', '鹿'), (0x2FC6, 'M', '麥'), (0x2FC7, 'M', '麻'), (0x2FC8, 'M', '黃'), (0x2FC9, 'M', '黍'), (0x2FCA, 'M', '黑'), (0x2FCB, 'M', '黹'), (0x2FCC, 'M', '黽'), (0x2FCD, 'M', '鼎'), (0x2FCE, 'M', '鼓'), (0x2FCF, 'M', '鼠'), (0x2FD0, 'M', '鼻'), (0x2FD1, 'M', '齊'), (0x2FD2, 'M', '齒'), (0x2FD3, 'M', '龍'), (0x2FD4, 'M', '龜'), (0x2FD5, 'M', '龠'), (0x2FD6, 'X'), (0x3000, '3', ' '), (0x3001, 'V'), (0x3002, 'M', '.'), (0x3003, 'V'), (0x3036, 'M', '〒'), (0x3037, 'V'), (0x3038, 'M', '十'), ] def _seg_29() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x3039, 'M', '卄'), (0x303A, 'M', '卅'), (0x303B, 'V'), (0x3040, 'X'), (0x3041, 'V'), (0x3097, 'X'), (0x3099, 'V'), (0x309B, '3', ' ゙'), (0x309C, '3', ' ゚'), (0x309D, 'V'), (0x309F, 'M', 'より'), (0x30A0, 'V'), (0x30FF, 'M', 'コト'), (0x3100, 'X'), (0x3105, 'V'), (0x3130, 'X'), (0x3131, 'M', 'ᄀ'), (0x3132, 'M', 'ᄁ'), (0x3133, 'M', 'ᆪ'), (0x3134, 'M', 'ᄂ'), (0x3135, 'M', 'ᆬ'), (0x3136, 'M', 'ᆭ'), (0x3137, 'M', 'ᄃ'), (0x3138, 'M', 'ᄄ'), (0x3139, 'M', 'ᄅ'), (0x313A, 'M', 'ᆰ'), (0x313B, 'M', 'ᆱ'), (0x313C, 'M', 'ᆲ'), (0x313D, 'M', 'ᆳ'), (0x313E, 'M', 'ᆴ'), (0x313F, 'M', 'ᆵ'), (0x3140, 'M', 'ᄚ'), (0x3141, 'M', 'ᄆ'), (0x3142, 'M', 'ᄇ'), (0x3143, 'M', 'ᄈ'), (0x3144, 'M', 'ᄡ'), (0x3145, 'M', 'ᄉ'), (0x3146, 'M', 'ᄊ'), (0x3147, 'M', 'ᄋ'), (0x3148, 'M', 'ᄌ'), (0x3149, 'M', 'ᄍ'), (0x314A, 'M', 'ᄎ'), (0x314B, 'M', 'ᄏ'), (0x314C, 'M', 'ᄐ'), (0x314D, 'M', 'ᄑ'), (0x314E, 'M', 'ᄒ'), (0x314F, 'M', 'ᅡ'), (0x3150, 'M', 'ᅢ'), (0x3151, 'M', 'ᅣ'), (0x3152, 'M', 'ᅤ'), (0x3153, 'M', 'ᅥ'), (0x3154, 'M', 'ᅦ'), (0x3155, 'M', 'ᅧ'), (0x3156, 'M', 'ᅨ'), (0x3157, 'M', 'ᅩ'), (0x3158, 'M', 'ᅪ'), (0x3159, 'M', 'ᅫ'), (0x315A, 'M', 'ᅬ'), (0x315B, 'M', 'ᅭ'), (0x315C, 'M', 'ᅮ'), (0x315D, 'M', 'ᅯ'), (0x315E, 'M', 'ᅰ'), (0x315F, 'M', 'ᅱ'), (0x3160, 'M', 'ᅲ'), (0x3161, 'M', 'ᅳ'), (0x3162, 'M', 'ᅴ'), (0x3163, 'M', 'ᅵ'), (0x3164, 'X'), (0x3165, 'M', 'ᄔ'), (0x3166, 'M', 'ᄕ'), (0x3167, 'M', 'ᇇ'), (0x3168, 'M', 'ᇈ'), (0x3169, 'M', 'ᇌ'), (0x316A, 'M', 'ᇎ'), (0x316B, 'M', 'ᇓ'), (0x316C, 'M', 'ᇗ'), (0x316D, 'M', 'ᇙ'), (0x316E, 'M', 'ᄜ'), (0x316F, 'M', 'ᇝ'), (0x3170, 'M', 'ᇟ'), (0x3171, 'M', 'ᄝ'), (0x3172, 'M', 'ᄞ'), (0x3173, 'M', 'ᄠ'), (0x3174, 'M', 'ᄢ'), (0x3175, 'M', 'ᄣ'), (0x3176, 'M', 'ᄧ'), (0x3177, 'M', 'ᄩ'), (0x3178, 'M', 'ᄫ'), (0x3179, 'M', 'ᄬ'), (0x317A, 'M', 'ᄭ'), (0x317B, 'M', 'ᄮ'), (0x317C, 'M', 'ᄯ'), (0x317D, 'M', 'ᄲ'), (0x317E, 'M', 'ᄶ'), (0x317F, 'M', 'ᅀ'), (0x3180, 'M', 'ᅇ'), (0x3181, 'M', 'ᅌ'), (0x3182, 'M', 'ᇱ'), (0x3183, 'M', 'ᇲ'), (0x3184, 'M', 'ᅗ'), ] def _seg_30() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x3185, 'M', 'ᅘ'), (0x3186, 'M', 'ᅙ'), (0x3187, 'M', 'ᆄ'), (0x3188, 'M', 'ᆅ'), (0x3189, 'M', 'ᆈ'), (0x318A, 'M', 'ᆑ'), (0x318B, 'M', 'ᆒ'), (0x318C, 'M', 'ᆔ'), (0x318D, 'M', 'ᆞ'), (0x318E, 'M', 'ᆡ'), (0x318F, 'X'), (0x3190, 'V'), (0x3192, 'M', '一'), (0x3193, 'M', '二'), (0x3194, 'M', '三'), (0x3195, 'M', '四'), (0x3196, 'M', '上'), (0x3197, 'M', '中'), (0x3198, 'M', '下'), (0x3199, 'M', '甲'), (0x319A, 'M', '乙'), (0x319B, 'M', '丙'), (0x319C, 'M', '丁'), (0x319D, 'M', '天'), (0x319E, 'M', '地'), (0x319F, 'M', '人'), (0x31A0, 'V'), (0x31E4, 'X'), (0x31F0, 'V'), (0x3200, '3', '(ᄀ)'), (0x3201, '3', '(ᄂ)'), (0x3202, '3', '(ᄃ)'), (0x3203, '3', '(ᄅ)'), (0x3204, '3', '(ᄆ)'), (0x3205, '3', '(ᄇ)'), (0x3206, '3', '(ᄉ)'), (0x3207, '3', '(ᄋ)'), (0x3208, '3', '(ᄌ)'), (0x3209, '3', '(ᄎ)'), (0x320A, '3', '(ᄏ)'), (0x320B, '3', '(ᄐ)'), (0x320C, '3', '(ᄑ)'), (0x320D, '3', '(ᄒ)'), (0x320E, '3', '(가)'), (0x320F, '3', '(나)'), (0x3210, '3', '(다)'), (0x3211, '3', '(라)'), (0x3212, '3', '(마)'), (0x3213, '3', '(바)'), (0x3214, '3', '(사)'), (0x3215, '3', '(아)'), (0x3216, '3', '(자)'), (0x3217, '3', '(차)'), (0x3218, '3', '(카)'), (0x3219, '3', '(타)'), (0x321A, '3', '(파)'), (0x321B, '3', '(하)'), (0x321C, '3', '(주)'), (0x321D, '3', '(오전)'), (0x321E, '3', '(오후)'), (0x321F, 'X'), (0x3220, '3', '(一)'), (0x3221, '3', '(二)'), (0x3222, '3', '(三)'), (0x3223, '3', '(四)'), (0x3224, '3', '(五)'), (0x3225, '3', '(六)'), (0x3226, '3', '(七)'), (0x3227, '3', '(八)'), (0x3228, '3', '(九)'), (0x3229, '3', '(十)'), (0x322A, '3', '(月)'), (0x322B, '3', '(火)'), (0x322C, '3', '(水)'), (0x322D, '3', '(木)'), (0x322E, '3', '(金)'), (0x322F, '3', '(土)'), (0x3230, '3', '(日)'), (0x3231, '3', '(株)'), (0x3232, '3', '(有)'), (0x3233, '3', '(社)'), (0x3234, '3', '(名)'), (0x3235, '3', '(特)'), (0x3236, '3', '(財)'), (0x3237, '3', '(祝)'), (0x3238, '3', '(労)'), (0x3239, '3', '(代)'), (0x323A, '3', '(呼)'), (0x323B, '3', '(学)'), (0x323C, '3', '(監)'), (0x323D, '3', '(企)'), (0x323E, '3', '(資)'), (0x323F, '3', '(協)'), (0x3240, '3', '(祭)'), (0x3241, '3', '(休)'), (0x3242, '3', '(自)'), (0x3243, '3', '(至)'), (0x3244, 'M', '問'), (0x3245, 'M', '幼'), (0x3246, 'M', '文'), ] def _seg_31() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x3247, 'M', '箏'), (0x3248, 'V'), (0x3250, 'M', 'pte'), (0x3251, 'M', '21'), (0x3252, 'M', '22'), (0x3253, 'M', '23'), (0x3254, 'M', '24'), (0x3255, 'M', '25'), (0x3256, 'M', '26'), (0x3257, 'M', '27'), (0x3258, 'M', '28'), (0x3259, 'M', '29'), (0x325A, 'M', '30'), (0x325B, 'M', '31'), (0x325C, 'M', '32'), (0x325D, 'M', '33'), (0x325E, 'M', '34'), (0x325F, 'M', '35'), (0x3260, 'M', 'ᄀ'), (0x3261, 'M', 'ᄂ'), (0x3262, 'M', 'ᄃ'), (0x3263, 'M', 'ᄅ'), (0x3264, 'M', 'ᄆ'), (0x3265, 'M', 'ᄇ'), (0x3266, 'M', 'ᄉ'), (0x3267, 'M', 'ᄋ'), (0x3268, 'M', 'ᄌ'), (0x3269, 'M', 'ᄎ'), (0x326A, 'M', 'ᄏ'), (0x326B, 'M', 'ᄐ'), (0x326C, 'M', 'ᄑ'), (0x326D, 'M', 'ᄒ'), (0x326E, 'M', '가'), (0x326F, 'M', '나'), (0x3270, 'M', '다'), (0x3271, 'M', '라'), (0x3272, 'M', '마'), (0x3273, 'M', '바'), (0x3274, 'M', '사'), (0x3275, 'M', '아'), (0x3276, 'M', '자'), (0x3277, 'M', '차'), (0x3278, 'M', '카'), (0x3279, 'M', '타'), (0x327A, 'M', '파'), (0x327B, 'M', '하'), (0x327C, 'M', '참고'), (0x327D, 'M', '주의'), (0x327E, 'M', '우'), (0x327F, 'V'), (0x3280, 'M', '一'), (0x3281, 'M', '二'), (0x3282, 'M', '三'), (0x3283, 'M', '四'), (0x3284, 'M', '五'), (0x3285, 'M', '六'), (0x3286, 'M', '七'), (0x3287, 'M', '八'), (0x3288, 'M', '九'), (0x3289, 'M', '十'), (0x328A, 'M', '月'), (0x328B, 'M', '火'), (0x328C, 'M', '水'), (0x328D, 'M', '木'), (0x328E, 'M', '金'), (0x328F, 'M', '土'), (0x3290, 'M', '日'), (0x3291, 'M', '株'), (0x3292, 'M', '有'), (0x3293, 'M', '社'), (0x3294, 'M', '名'), (0x3295, 'M', '特'), (0x3296, 'M', '財'), (0x3297, 'M', '祝'), (0x3298, 'M', '労'), (0x3299, 'M', '秘'), (0x329A, 'M', '男'), (0x329B, 'M', '女'), (0x329C, 'M', '適'), (0x329D, 'M', '優'), (0x329E, 'M', '印'), (0x329F, 'M', '注'), (0x32A0, 'M', '項'), (0x32A1, 'M', '休'), (0x32A2, 'M', '写'), (0x32A3, 'M', '正'), (0x32A4, 'M', '上'), (0x32A5, 'M', '中'), (0x32A6, 'M', '下'), (0x32A7, 'M', '左'), (0x32A8, 'M', '右'), (0x32A9, 'M', '医'), (0x32AA, 'M', '宗'), (0x32AB, 'M', '学'), (0x32AC, 'M', '監'), (0x32AD, 'M', '企'), (0x32AE, 'M', '資'), (0x32AF, 'M', '協'), (0x32B0, 'M', '夜'), (0x32B1, 'M', '36'), ] def _seg_32() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x32B2, 'M', '37'), (0x32B3, 'M', '38'), (0x32B4, 'M', '39'), (0x32B5, 'M', '40'), (0x32B6, 'M', '41'), (0x32B7, 'M', '42'), (0x32B8, 'M', '43'), (0x32B9, 'M', '44'), (0x32BA, 'M', '45'), (0x32BB, 'M', '46'), (0x32BC, 'M', '47'), (0x32BD, 'M', '48'), (0x32BE, 'M', '49'), (0x32BF, 'M', '50'), (0x32C0, 'M', '1月'), (0x32C1, 'M', '2月'), (0x32C2, 'M', '3月'), (0x32C3, 'M', '4月'), (0x32C4, 'M', '5月'), (0x32C5, 'M', '6月'), (0x32C6, 'M', '7月'), (0x32C7, 'M', '8月'), (0x32C8, 'M', '9月'), (0x32C9, 'M', '10月'), (0x32CA, 'M', '11月'), (0x32CB, 'M', '12月'), (0x32CC, 'M', 'hg'), (0x32CD, 'M', 'erg'), (0x32CE, 'M', 'ev'), (0x32CF, 'M', 'ltd'), (0x32D0, 'M', 'ア'), (0x32D1, 'M', 'イ'), (0x32D2, 'M', 'ウ'), (0x32D3, 'M', 'エ'), (0x32D4, 'M', 'オ'), (0x32D5, 'M', 'カ'), (0x32D6, 'M', 'キ'), (0x32D7, 'M', 'ク'), (0x32D8, 'M', 'ケ'), (0x32D9, 'M', 'コ'), (0x32DA, 'M', 'サ'), (0x32DB, 'M', 'シ'), (0x32DC, 'M', 'ス'), (0x32DD, 'M', 'セ'), (0x32DE, 'M', 'ソ'), (0x32DF, 'M', 'タ'), (0x32E0, 'M', 'チ'), (0x32E1, 'M', 'ツ'), (0x32E2, 'M', 'テ'), (0x32E3, 'M', 'ト'), (0x32E4, 'M', 'ナ'), (0x32E5, 'M', 'ニ'), (0x32E6, 'M', 'ヌ'), (0x32E7, 'M', 'ネ'), (0x32E8, 'M', 'ノ'), (0x32E9, 'M', 'ハ'), (0x32EA, 'M', 'ヒ'), (0x32EB, 'M', 'フ'), (0x32EC, 'M', 'ヘ'), (0x32ED, 'M', 'ホ'), (0x32EE, 'M', 'マ'), (0x32EF, 'M', 'ミ'), (0x32F0, 'M', 'ム'), (0x32F1, 'M', 'メ'), (0x32F2, 'M', 'モ'), (0x32F3, 'M', 'ヤ'), (0x32F4, 'M', 'ユ'), (0x32F5, 'M', 'ヨ'), (0x32F6, 'M', 'ラ'), (0x32F7, 'M', 'リ'), (0x32F8, 'M', 'ル'), (0x32F9, 'M', 'レ'), (0x32FA, 'M', 'ロ'), (0x32FB, 'M', 'ワ'), (0x32FC, 'M', 'ヰ'), (0x32FD, 'M', 'ヱ'), (0x32FE, 'M', 'ヲ'), (0x32FF, 'M', '令和'), (0x3300, 'M', 'アパート'), (0x3301, 'M', 'アルファ'), (0x3302, 'M', 'アンペア'), (0x3303, 'M', 'アール'), (0x3304, 'M', 'イニング'), (0x3305, 'M', 'インチ'), (0x3306, 'M', 'ウォン'), (0x3307, 'M', 'エスクード'), (0x3308, 'M', 'エーカー'), (0x3309, 'M', 'オンス'), (0x330A, 'M', 'オーム'), (0x330B, 'M', 'カイリ'), (0x330C, 'M', 'カラット'), (0x330D, 'M', 'カロリー'), (0x330E, 'M', 'ガロン'), (0x330F, 'M', 'ガンマ'), (0x3310, 'M', 'ギガ'), (0x3311, 'M', 'ギニー'), (0x3312, 'M', 'キュリー'), (0x3313, 'M', 'ギルダー'), (0x3314, 'M', 'キロ'), (0x3315, 'M', 'キログラム'), ] def _seg_33() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x3316, 'M', 'キロメートル'), (0x3317, 'M', 'キロワット'), (0x3318, 'M', 'グラム'), (0x3319, 'M', 'グラムトン'), (0x331A, 'M', 'クルゼイロ'), (0x331B, 'M', 'クローネ'), (0x331C, 'M', 'ケース'), (0x331D, 'M', 'コルナ'), (0x331E, 'M', 'コーポ'), (0x331F, 'M', 'サイクル'), (0x3320, 'M', 'サンチーム'), (0x3321, 'M', 'シリング'), (0x3322, 'M', 'センチ'), (0x3323, 'M', 'セント'), (0x3324, 'M', 'ダース'), (0x3325, 'M', 'デシ'), (0x3326, 'M', 'ドル'), (0x3327, 'M', 'トン'), (0x3328, 'M', 'ナノ'), (0x3329, 'M', 'ノット'), (0x332A, 'M', 'ハイツ'), (0x332B, 'M', 'パーセント'), (0x332C, 'M', 'パーツ'), (0x332D, 'M', 'バーレル'), (0x332E, 'M', 'ピアストル'), (0x332F, 'M', 'ピクル'), (0x3330, 'M', 'ピコ'), (0x3331, 'M', 'ビル'), (0x3332, 'M', 'ファラッド'), (0x3333, 'M', 'フィート'), (0x3334, 'M', 'ブッシェル'), (0x3335, 'M', 'フラン'), (0x3336, 'M', 'ヘクタール'), (0x3337, 'M', 'ペソ'), (0x3338, 'M', 'ペニヒ'), (0x3339, 'M', 'ヘルツ'), (0x333A, 'M', 'ペンス'), (0x333B, 'M', 'ページ'), (0x333C, 'M', 'ベータ'), (0x333D, 'M', 'ポイント'), (0x333E, 'M', 'ボルト'), (0x333F, 'M', 'ホン'), (0x3340, 'M', 'ポンド'), (0x3341, 'M', 'ホール'), (0x3342, 'M', 'ホーン'), (0x3343, 'M', 'マイクロ'), (0x3344, 'M', 'マイル'), (0x3345, 'M', 'マッハ'), (0x3346, 'M', 'マルク'), (0x3347, 'M', 'マンション'), (0x3348, 'M', 'ミクロン'), (0x3349, 'M', 'ミリ'), (0x334A, 'M', 'ミリバール'), (0x334B, 'M', 'メガ'), (0x334C, 'M', 'メガトン'), (0x334D, 'M', 'メートル'), (0x334E, 'M', 'ヤード'), (0x334F, 'M', 'ヤール'), (0x3350, 'M', 'ユアン'), (0x3351, 'M', 'リットル'), (0x3352, 'M', 'リラ'), (0x3353, 'M', 'ルピー'), (0x3354, 'M', 'ルーブル'), (0x3355, 'M', 'レム'), (0x3356, 'M', 'レントゲン'), (0x3357, 'M', 'ワット'), (0x3358, 'M', '0点'), (0x3359, 'M', '1点'), (0x335A, 'M', '2点'), (0x335B, 'M', '3点'), (0x335C, 'M', '4点'), (0x335D, 'M', '5点'), (0x335E, 'M', '6点'), (0x335F, 'M', '7点'), (0x3360, 'M', '8点'), (0x3361, 'M', '9点'), (0x3362, 'M', '10点'), (0x3363, 'M', '11点'), (0x3364, 'M', '12点'), (0x3365, 'M', '13点'), (0x3366, 'M', '14点'), (0x3367, 'M', '15点'), (0x3368, 'M', '16点'), (0x3369, 'M', '17点'), (0x336A, 'M', '18点'), (0x336B, 'M', '19点'), (0x336C, 'M', '20点'), (0x336D, 'M', '21点'), (0x336E, 'M', '22点'), (0x336F, 'M', '23点'), (0x3370, 'M', '24点'), (0x3371, 'M', 'hpa'), (0x3372, 'M', 'da'), (0x3373, 'M', 'au'), (0x3374, 'M', 'bar'), (0x3375, 'M', 'ov'), (0x3376, 'M', 'pc'), (0x3377, 'M', 'dm'), (0x3378, 'M', 'dm2'), (0x3379, 'M', 'dm3'), ] def _seg_34() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x337A, 'M', 'iu'), (0x337B, 'M', '平成'), (0x337C, 'M', '昭和'), (0x337D, 'M', '大正'), (0x337E, 'M', '明治'), (0x337F, 'M', '株式会社'), (0x3380, 'M', 'pa'), (0x3381, 'M', 'na'), (0x3382, 'M', 'μa'), (0x3383, 'M', 'ma'), (0x3384, 'M', 'ka'), (0x3385, 'M', 'kb'), (0x3386, 'M', 'mb'), (0x3387, 'M', 'gb'), (0x3388, 'M', 'cal'), (0x3389, 'M', 'kcal'), (0x338A, 'M', 'pf'), (0x338B, 'M', 'nf'), (0x338C, 'M', 'μf'), (0x338D, 'M', 'μg'), (0x338E, 'M', 'mg'), (0x338F, 'M', 'kg'), (0x3390, 'M', 'hz'), (0x3391, 'M', 'khz'), (0x3392, 'M', 'mhz'), (0x3393, 'M', 'ghz'), (0x3394, 'M', 'thz'), (0x3395, 'M', 'μl'), (0x3396, 'M', 'ml'), (0x3397, 'M', 'dl'), (0x3398, 'M', 'kl'), (0x3399, 'M', 'fm'), (0x339A, 'M', 'nm'), (0x339B, 'M', 'μm'), (0x339C, 'M', 'mm'), (0x339D, 'M', 'cm'), (0x339E, 'M', 'km'), (0x339F, 'M', 'mm2'), (0x33A0, 'M', 'cm2'), (0x33A1, 'M', 'm2'), (0x33A2, 'M', 'km2'), (0x33A3, 'M', 'mm3'), (0x33A4, 'M', 'cm3'), (0x33A5, 'M', 'm3'), (0x33A6, 'M', 'km3'), (0x33A7, 'M', 'm∕s'), (0x33A8, 'M', 'm∕s2'), (0x33A9, 'M', 'pa'), (0x33AA, 'M', 'kpa'), (0x33AB, 'M', 'mpa'), (0x33AC, 'M', 'gpa'), (0x33AD, 'M', 'rad'), (0x33AE, 'M', 'rad∕s'), (0x33AF, 'M', 'rad∕s2'), (0x33B0, 'M', 'ps'), (0x33B1, 'M', 'ns'), (0x33B2, 'M', 'μs'), (0x33B3, 'M', 'ms'), (0x33B4, 'M', 'pv'), (0x33B5, 'M', 'nv'), (0x33B6, 'M', 'μv'), (0x33B7, 'M', 'mv'), (0x33B8, 'M', 'kv'), (0x33B9, 'M', 'mv'), (0x33BA, 'M', 'pw'), (0x33BB, 'M', 'nw'), (0x33BC, 'M', 'μw'), (0x33BD, 'M', 'mw'), (0x33BE, 'M', 'kw'), (0x33BF, 'M', 'mw'), (0x33C0, 'M', 'kω'), (0x33C1, 'M', 'mω'), (0x33C2, 'X'), (0x33C3, 'M', 'bq'), (0x33C4, 'M', 'cc'), (0x33C5, 'M', 'cd'), (0x33C6, 'M', 'c∕kg'), (0x33C7, 'X'), (0x33C8, 'M', 'db'), (0x33C9, 'M', 'gy'), (0x33CA, 'M', 'ha'), (0x33CB, 'M', 'hp'), (0x33CC, 'M', 'in'), (0x33CD, 'M', 'kk'), (0x33CE, 'M', 'km'), (0x33CF, 'M', 'kt'), (0x33D0, 'M', 'lm'), (0x33D1, 'M', 'ln'), (0x33D2, 'M', 'log'), (0x33D3, 'M', 'lx'), (0x33D4, 'M', 'mb'), (0x33D5, 'M', 'mil'), (0x33D6, 'M', 'mol'), (0x33D7, 'M', 'ph'), (0x33D8, 'X'), (0x33D9, 'M', 'ppm'), (0x33DA, 'M', 'pr'), (0x33DB, 'M', 'sr'), (0x33DC, 'M', 'sv'), (0x33DD, 'M', 'wb'), ] def _seg_35() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x33DE, 'M', 'v∕m'), (0x33DF, 'M', 'a∕m'), (0x33E0, 'M', '1日'), (0x33E1, 'M', '2日'), (0x33E2, 'M', '3日'), (0x33E3, 'M', '4日'), (0x33E4, 'M', '5日'), (0x33E5, 'M', '6日'), (0x33E6, 'M', '7日'), (0x33E7, 'M', '8日'), (0x33E8, 'M', '9日'), (0x33E9, 'M', '10日'), (0x33EA, 'M', '11日'), (0x33EB, 'M', '12日'), (0x33EC, 'M', '13日'), (0x33ED, 'M', '14日'), (0x33EE, 'M', '15日'), (0x33EF, 'M', '16日'), (0x33F0, 'M', '17日'), (0x33F1, 'M', '18日'), (0x33F2, 'M', '19日'), (0x33F3, 'M', '20日'), (0x33F4, 'M', '21日'), (0x33F5, 'M', '22日'), (0x33F6, 'M', '23日'), (0x33F7, 'M', '24日'), (0x33F8, 'M', '25日'), (0x33F9, 'M', '26日'), (0x33FA, 'M', '27日'), (0x33FB, 'M', '28日'), (0x33FC, 'M', '29日'), (0x33FD, 'M', '30日'), (0x33FE, 'M', '31日'), (0x33FF, 'M', 'gal'), (0x3400, 'V'), (0xA48D, 'X'), (0xA490, 'V'), (0xA4C7, 'X'), (0xA4D0, 'V'), (0xA62C, 'X'), (0xA640, 'M', 'ꙁ'), (0xA641, 'V'), (0xA642, 'M', 'ꙃ'), (0xA643, 'V'), (0xA644, 'M', 'ꙅ'), (0xA645, 'V'), (0xA646, 'M', 'ꙇ'), (0xA647, 'V'), (0xA648, 'M', 'ꙉ'), (0xA649, 'V'), (0xA64A, 'M', 'ꙋ'), (0xA64B, 'V'), (0xA64C, 'M', 'ꙍ'), (0xA64D, 'V'), (0xA64E, 'M', 'ꙏ'), (0xA64F, 'V'), (0xA650, 'M', 'ꙑ'), (0xA651, 'V'), (0xA652, 'M', 'ꙓ'), (0xA653, 'V'), (0xA654, 'M', 'ꙕ'), (0xA655, 'V'), (0xA656, 'M', 'ꙗ'), (0xA657, 'V'), (0xA658, 'M', 'ꙙ'), (0xA659, 'V'), (0xA65A, 'M', 'ꙛ'), (0xA65B, 'V'), (0xA65C, 'M', 'ꙝ'), (0xA65D, 'V'), (0xA65E, 'M', 'ꙟ'), (0xA65F, 'V'), (0xA660, 'M', 'ꙡ'), (0xA661, 'V'), (0xA662, 'M', 'ꙣ'), (0xA663, 'V'), (0xA664, 'M', 'ꙥ'), (0xA665, 'V'), (0xA666, 'M', 'ꙧ'), (0xA667, 'V'), (0xA668, 'M', 'ꙩ'), (0xA669, 'V'), (0xA66A, 'M', 'ꙫ'), (0xA66B, 'V'), (0xA66C, 'M', 'ꙭ'), (0xA66D, 'V'), (0xA680, 'M', 'ꚁ'), (0xA681, 'V'), (0xA682, 'M', 'ꚃ'), (0xA683, 'V'), (0xA684, 'M', 'ꚅ'), (0xA685, 'V'), (0xA686, 'M', 'ꚇ'), (0xA687, 'V'), (0xA688, 'M', 'ꚉ'), (0xA689, 'V'), (0xA68A, 'M', 'ꚋ'), (0xA68B, 'V'), (0xA68C, 'M', 'ꚍ'), (0xA68D, 'V'), ] def _seg_36() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xA68E, 'M', 'ꚏ'), (0xA68F, 'V'), (0xA690, 'M', 'ꚑ'), (0xA691, 'V'), (0xA692, 'M', 'ꚓ'), (0xA693, 'V'), (0xA694, 'M', 'ꚕ'), (0xA695, 'V'), (0xA696, 'M', 'ꚗ'), (0xA697, 'V'), (0xA698, 'M', 'ꚙ'), (0xA699, 'V'), (0xA69A, 'M', 'ꚛ'), (0xA69B, 'V'), (0xA69C, 'M', 'ъ'), (0xA69D, 'M', 'ь'), (0xA69E, 'V'), (0xA6F8, 'X'), (0xA700, 'V'), (0xA722, 'M', 'ꜣ'), (0xA723, 'V'), (0xA724, 'M', 'ꜥ'), (0xA725, 'V'), (0xA726, 'M', 'ꜧ'), (0xA727, 'V'), (0xA728, 'M', 'ꜩ'), (0xA729, 'V'), (0xA72A, 'M', 'ꜫ'), (0xA72B, 'V'), (0xA72C, 'M', 'ꜭ'), (0xA72D, 'V'), (0xA72E, 'M', 'ꜯ'), (0xA72F, 'V'), (0xA732, 'M', 'ꜳ'), (0xA733, 'V'), (0xA734, 'M', 'ꜵ'), (0xA735, 'V'), (0xA736, 'M', 'ꜷ'), (0xA737, 'V'), (0xA738, 'M', 'ꜹ'), (0xA739, 'V'), (0xA73A, 'M', 'ꜻ'), (0xA73B, 'V'), (0xA73C, 'M', 'ꜽ'), (0xA73D, 'V'), (0xA73E, 'M', 'ꜿ'), (0xA73F, 'V'), (0xA740, 'M', 'ꝁ'), (0xA741, 'V'), (0xA742, 'M', 'ꝃ'), (0xA743, 'V'), (0xA744, 'M', 'ꝅ'), (0xA745, 'V'), (0xA746, 'M', 'ꝇ'), (0xA747, 'V'), (0xA748, 'M', 'ꝉ'), (0xA749, 'V'), (0xA74A, 'M', 'ꝋ'), (0xA74B, 'V'), (0xA74C, 'M', 'ꝍ'), (0xA74D, 'V'), (0xA74E, 'M', 'ꝏ'), (0xA74F, 'V'), (0xA750, 'M', 'ꝑ'), (0xA751, 'V'), (0xA752, 'M', 'ꝓ'), (0xA753, 'V'), (0xA754, 'M', 'ꝕ'), (0xA755, 'V'), (0xA756, 'M', 'ꝗ'), (0xA757, 'V'), (0xA758, 'M', 'ꝙ'), (0xA759, 'V'), (0xA75A, 'M', 'ꝛ'), (0xA75B, 'V'), (0xA75C, 'M', 'ꝝ'), (0xA75D, 'V'), (0xA75E, 'M', 'ꝟ'), (0xA75F, 'V'), (0xA760, 'M', 'ꝡ'), (0xA761, 'V'), (0xA762, 'M', 'ꝣ'), (0xA763, 'V'), (0xA764, 'M', 'ꝥ'), (0xA765, 'V'), (0xA766, 'M', 'ꝧ'), (0xA767, 'V'), (0xA768, 'M', 'ꝩ'), (0xA769, 'V'), (0xA76A, 'M', 'ꝫ'), (0xA76B, 'V'), (0xA76C, 'M', 'ꝭ'), (0xA76D, 'V'), (0xA76E, 'M', 'ꝯ'), (0xA76F, 'V'), (0xA770, 'M', 'ꝯ'), (0xA771, 'V'), (0xA779, 'M', 'ꝺ'), (0xA77A, 'V'), (0xA77B, 'M', 'ꝼ'), ] def _seg_37() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xA77C, 'V'), (0xA77D, 'M', 'ᵹ'), (0xA77E, 'M', 'ꝿ'), (0xA77F, 'V'), (0xA780, 'M', 'ꞁ'), (0xA781, 'V'), (0xA782, 'M', 'ꞃ'), (0xA783, 'V'), (0xA784, 'M', 'ꞅ'), (0xA785, 'V'), (0xA786, 'M', 'ꞇ'), (0xA787, 'V'), (0xA78B, 'M', 'ꞌ'), (0xA78C, 'V'), (0xA78D, 'M', 'ɥ'), (0xA78E, 'V'), (0xA790, 'M', 'ꞑ'), (0xA791, 'V'), (0xA792, 'M', 'ꞓ'), (0xA793, 'V'), (0xA796, 'M', 'ꞗ'), (0xA797, 'V'), (0xA798, 'M', 'ꞙ'), (0xA799, 'V'), (0xA79A, 'M', 'ꞛ'), (0xA79B, 'V'), (0xA79C, 'M', 'ꞝ'), (0xA79D, 'V'), (0xA79E, 'M', 'ꞟ'), (0xA79F, 'V'), (0xA7A0, 'M', 'ꞡ'), (0xA7A1, 'V'), (0xA7A2, 'M', 'ꞣ'), (0xA7A3, 'V'), (0xA7A4, 'M', 'ꞥ'), (0xA7A5, 'V'), (0xA7A6, 'M', 'ꞧ'), (0xA7A7, 'V'), (0xA7A8, 'M', 'ꞩ'), (0xA7A9, 'V'), (0xA7AA, 'M', 'ɦ'), (0xA7AB, 'M', 'ɜ'), (0xA7AC, 'M', 'ɡ'), (0xA7AD, 'M', 'ɬ'), (0xA7AE, 'M', 'ɪ'), (0xA7AF, 'V'), (0xA7B0, 'M', 'ʞ'), (0xA7B1, 'M', 'ʇ'), (0xA7B2, 'M', 'ʝ'), (0xA7B3, 'M', 'ꭓ'), (0xA7B4, 'M', 'ꞵ'), (0xA7B5, 'V'), (0xA7B6, 'M', 'ꞷ'), (0xA7B7, 'V'), (0xA7B8, 'M', 'ꞹ'), (0xA7B9, 'V'), (0xA7BA, 'M', 'ꞻ'), (0xA7BB, 'V'), (0xA7BC, 'M', 'ꞽ'), (0xA7BD, 'V'), (0xA7BE, 'M', 'ꞿ'), (0xA7BF, 'V'), (0xA7C0, 'M', 'ꟁ'), (0xA7C1, 'V'), (0xA7C2, 'M', 'ꟃ'), (0xA7C3, 'V'), (0xA7C4, 'M', 'ꞔ'), (0xA7C5, 'M', 'ʂ'), (0xA7C6, 'M', 'ᶎ'), (0xA7C7, 'M', 'ꟈ'), (0xA7C8, 'V'), (0xA7C9, 'M', 'ꟊ'), (0xA7CA, 'V'), (0xA7CB, 'X'), (0xA7D0, 'M', 'ꟑ'), (0xA7D1, 'V'), (0xA7D2, 'X'), (0xA7D3, 'V'), (0xA7D4, 'X'), (0xA7D5, 'V'), (0xA7D6, 'M', 'ꟗ'), (0xA7D7, 'V'), (0xA7D8, 'M', 'ꟙ'), (0xA7D9, 'V'), (0xA7DA, 'X'), (0xA7F2, 'M', 'c'), (0xA7F3, 'M', 'f'), (0xA7F4, 'M', 'q'), (0xA7F5, 'M', 'ꟶ'), (0xA7F6, 'V'), (0xA7F8, 'M', 'ħ'), (0xA7F9, 'M', 'œ'), (0xA7FA, 'V'), (0xA82D, 'X'), (0xA830, 'V'), (0xA83A, 'X'), (0xA840, 'V'), (0xA878, 'X'), (0xA880, 'V'), (0xA8C6, 'X'), ] def _seg_38() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xA8CE, 'V'), (0xA8DA, 'X'), (0xA8E0, 'V'), (0xA954, 'X'), (0xA95F, 'V'), (0xA97D, 'X'), (0xA980, 'V'), (0xA9CE, 'X'), (0xA9CF, 'V'), (0xA9DA, 'X'), (0xA9DE, 'V'), (0xA9FF, 'X'), (0xAA00, 'V'), (0xAA37, 'X'), (0xAA40, 'V'), (0xAA4E, 'X'), (0xAA50, 'V'), (0xAA5A, 'X'), (0xAA5C, 'V'), (0xAAC3, 'X'), (0xAADB, 'V'), (0xAAF7, 'X'), (0xAB01, 'V'), (0xAB07, 'X'), (0xAB09, 'V'), (0xAB0F, 'X'), (0xAB11, 'V'), (0xAB17, 'X'), (0xAB20, 'V'), (0xAB27, 'X'), (0xAB28, 'V'), (0xAB2F, 'X'), (0xAB30, 'V'), (0xAB5C, 'M', 'ꜧ'), (0xAB5D, 'M', 'ꬷ'), (0xAB5E, 'M', 'ɫ'), (0xAB5F, 'M', 'ꭒ'), (0xAB60, 'V'), (0xAB69, 'M', 'ʍ'), (0xAB6A, 'V'), (0xAB6C, 'X'), (0xAB70, 'M', 'Ꭰ'), (0xAB71, 'M', 'Ꭱ'), (0xAB72, 'M', 'Ꭲ'), (0xAB73, 'M', 'Ꭳ'), (0xAB74, 'M', 'Ꭴ'), (0xAB75, 'M', 'Ꭵ'), (0xAB76, 'M', 'Ꭶ'), (0xAB77, 'M', 'Ꭷ'), (0xAB78, 'M', 'Ꭸ'), (0xAB79, 'M', 'Ꭹ'), (0xAB7A, 'M', 'Ꭺ'), (0xAB7B, 'M', 'Ꭻ'), (0xAB7C, 'M', 'Ꭼ'), (0xAB7D, 'M', 'Ꭽ'), (0xAB7E, 'M', 'Ꭾ'), (0xAB7F, 'M', 'Ꭿ'), (0xAB80, 'M', 'Ꮀ'), (0xAB81, 'M', 'Ꮁ'), (0xAB82, 'M', 'Ꮂ'), (0xAB83, 'M', 'Ꮃ'), (0xAB84, 'M', 'Ꮄ'), (0xAB85, 'M', 'Ꮅ'), (0xAB86, 'M', 'Ꮆ'), (0xAB87, 'M', 'Ꮇ'), (0xAB88, 'M', 'Ꮈ'), (0xAB89, 'M', 'Ꮉ'), (0xAB8A, 'M', 'Ꮊ'), (0xAB8B, 'M', 'Ꮋ'), (0xAB8C, 'M', 'Ꮌ'), (0xAB8D, 'M', 'Ꮍ'), (0xAB8E, 'M', 'Ꮎ'), (0xAB8F, 'M', 'Ꮏ'), (0xAB90, 'M', 'Ꮐ'), (0xAB91, 'M', 'Ꮑ'), (0xAB92, 'M', 'Ꮒ'), (0xAB93, 'M', 'Ꮓ'), (0xAB94, 'M', 'Ꮔ'), (0xAB95, 'M', 'Ꮕ'), (0xAB96, 'M', 'Ꮖ'), (0xAB97, 'M', 'Ꮗ'), (0xAB98, 'M', 'Ꮘ'), (0xAB99, 'M', 'Ꮙ'), (0xAB9A, 'M', 'Ꮚ'), (0xAB9B, 'M', 'Ꮛ'), (0xAB9C, 'M', 'Ꮜ'), (0xAB9D, 'M', 'Ꮝ'), (0xAB9E, 'M', 'Ꮞ'), (0xAB9F, 'M', 'Ꮟ'), (0xABA0, 'M', 'Ꮠ'), (0xABA1, 'M', 'Ꮡ'), (0xABA2, 'M', 'Ꮢ'), (0xABA3, 'M', 'Ꮣ'), (0xABA4, 'M', 'Ꮤ'), (0xABA5, 'M', 'Ꮥ'), (0xABA6, 'M', 'Ꮦ'), (0xABA7, 'M', 'Ꮧ'), (0xABA8, 'M', 'Ꮨ'), (0xABA9, 'M', 'Ꮩ'), (0xABAA, 'M', 'Ꮪ'), ] def _seg_39() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xABAB, 'M', 'Ꮫ'), (0xABAC, 'M', 'Ꮬ'), (0xABAD, 'M', 'Ꮭ'), (0xABAE, 'M', 'Ꮮ'), (0xABAF, 'M', 'Ꮯ'), (0xABB0, 'M', 'Ꮰ'), (0xABB1, 'M', 'Ꮱ'), (0xABB2, 'M', 'Ꮲ'), (0xABB3, 'M', 'Ꮳ'), (0xABB4, 'M', 'Ꮴ'), (0xABB5, 'M', 'Ꮵ'), (0xABB6, 'M', 'Ꮶ'), (0xABB7, 'M', 'Ꮷ'), (0xABB8, 'M', 'Ꮸ'), (0xABB9, 'M', 'Ꮹ'), (0xABBA, 'M', 'Ꮺ'), (0xABBB, 'M', 'Ꮻ'), (0xABBC, 'M', 'Ꮼ'), (0xABBD, 'M', 'Ꮽ'), (0xABBE, 'M', 'Ꮾ'), (0xABBF, 'M', 'Ꮿ'), (0xABC0, 'V'), (0xABEE, 'X'), (0xABF0, 'V'), (0xABFA, 'X'), (0xAC00, 'V'), (0xD7A4, 'X'), (0xD7B0, 'V'), (0xD7C7, 'X'), (0xD7CB, 'V'), (0xD7FC, 'X'), (0xF900, 'M', '豈'), (0xF901, 'M', '更'), (0xF902, 'M', '車'), (0xF903, 'M', '賈'), (0xF904, 'M', '滑'), (0xF905, 'M', '串'), (0xF906, 'M', '句'), (0xF907, 'M', '龜'), (0xF909, 'M', '契'), (0xF90A, 'M', '金'), (0xF90B, 'M', '喇'), (0xF90C, 'M', '奈'), (0xF90D, 'M', '懶'), (0xF90E, 'M', '癩'), (0xF90F, 'M', '羅'), (0xF910, 'M', '蘿'), (0xF911, 'M', '螺'), (0xF912, 'M', '裸'), (0xF913, 'M', '邏'), (0xF914, 'M', '樂'), (0xF915, 'M', '洛'), (0xF916, 'M', '烙'), (0xF917, 'M', '珞'), (0xF918, 'M', '落'), (0xF919, 'M', '酪'), (0xF91A, 'M', '駱'), (0xF91B, 'M', '亂'), (0xF91C, 'M', '卵'), (0xF91D, 'M', '欄'), (0xF91E, 'M', '爛'), (0xF91F, 'M', '蘭'), (0xF920, 'M', '鸞'), (0xF921, 'M', '嵐'), (0xF922, 'M', '濫'), (0xF923, 'M', '藍'), (0xF924, 'M', '襤'), (0xF925, 'M', '拉'), (0xF926, 'M', '臘'), (0xF927, 'M', '蠟'), (0xF928, 'M', '廊'), (0xF929, 'M', '朗'), (0xF92A, 'M', '浪'), (0xF92B, 'M', '狼'), (0xF92C, 'M', '郎'), (0xF92D, 'M', '來'), (0xF92E, 'M', '冷'), (0xF92F, 'M', '勞'), (0xF930, 'M', '擄'), (0xF931, 'M', '櫓'), (0xF932, 'M', '爐'), (0xF933, 'M', '盧'), (0xF934, 'M', '老'), (0xF935, 'M', '蘆'), (0xF936, 'M', '虜'), (0xF937, 'M', '路'), (0xF938, 'M', '露'), (0xF939, 'M', '魯'), (0xF93A, 'M', '鷺'), (0xF93B, 'M', '碌'), (0xF93C, 'M', '祿'), (0xF93D, 'M', '綠'), (0xF93E, 'M', '菉'), (0xF93F, 'M', '錄'), (0xF940, 'M', '鹿'), (0xF941, 'M', '論'), (0xF942, 'M', '壟'), (0xF943, 'M', '弄'), (0xF944, 'M', '籠'), (0xF945, 'M', '聾'), ] def _seg_40() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xF946, 'M', '牢'), (0xF947, 'M', '磊'), (0xF948, 'M', '賂'), (0xF949, 'M', '雷'), (0xF94A, 'M', '壘'), (0xF94B, 'M', '屢'), (0xF94C, 'M', '樓'), (0xF94D, 'M', '淚'), (0xF94E, 'M', '漏'), (0xF94F, 'M', '累'), (0xF950, 'M', '縷'), (0xF951, 'M', '陋'), (0xF952, 'M', '勒'), (0xF953, 'M', '肋'), (0xF954, 'M', '凜'), (0xF955, 'M', '凌'), (0xF956, 'M', '稜'), (0xF957, 'M', '綾'), (0xF958, 'M', '菱'), (0xF959, 'M', '陵'), (0xF95A, 'M', '讀'), (0xF95B, 'M', '拏'), (0xF95C, 'M', '樂'), (0xF95D, 'M', '諾'), (0xF95E, 'M', '丹'), (0xF95F, 'M', '寧'), (0xF960, 'M', '怒'), (0xF961, 'M', '率'), (0xF962, 'M', '異'), (0xF963, 'M', '北'), (0xF964, 'M', '磻'), (0xF965, 'M', '便'), (0xF966, 'M', '復'), (0xF967, 'M', '不'), (0xF968, 'M', '泌'), (0xF969, 'M', '數'), (0xF96A, 'M', '索'), (0xF96B, 'M', '參'), (0xF96C, 'M', '塞'), (0xF96D, 'M', '省'), (0xF96E, 'M', '葉'), (0xF96F, 'M', '說'), (0xF970, 'M', '殺'), (0xF971, 'M', '辰'), (0xF972, 'M', '沈'), (0xF973, 'M', '拾'), (0xF974, 'M', '若'), (0xF975, 'M', '掠'), (0xF976, 'M', '略'), (0xF977, 'M', '亮'), (0xF978, 'M', '兩'), (0xF979, 'M', '凉'), (0xF97A, 'M', '梁'), (0xF97B, 'M', '糧'), (0xF97C, 'M', '良'), (0xF97D, 'M', '諒'), (0xF97E, 'M', '量'), (0xF97F, 'M', '勵'), (0xF980, 'M', '呂'), (0xF981, 'M', '女'), (0xF982, 'M', '廬'), (0xF983, 'M', '旅'), (0xF984, 'M', '濾'), (0xF985, 'M', '礪'), (0xF986, 'M', '閭'), (0xF987, 'M', '驪'), (0xF988, 'M', '麗'), (0xF989, 'M', '黎'), (0xF98A, 'M', '力'), (0xF98B, 'M', '曆'), (0xF98C, 'M', '歷'), (0xF98D, 'M', '轢'), (0xF98E, 'M', '年'), (0xF98F, 'M', '憐'), (0xF990, 'M', '戀'), (0xF991, 'M', '撚'), (0xF992, 'M', '漣'), (0xF993, 'M', '煉'), (0xF994, 'M', '璉'), (0xF995, 'M', '秊'), (0xF996, 'M', '練'), (0xF997, 'M', '聯'), (0xF998, 'M', '輦'), (0xF999, 'M', '蓮'), (0xF99A, 'M', '連'), (0xF99B, 'M', '鍊'), (0xF99C, 'M', '列'), (0xF99D, 'M', '劣'), (0xF99E, 'M', '咽'), (0xF99F, 'M', '烈'), (0xF9A0, 'M', '裂'), (0xF9A1, 'M', '說'), (0xF9A2, 'M', '廉'), (0xF9A3, 'M', '念'), (0xF9A4, 'M', '捻'), (0xF9A5, 'M', '殮'), (0xF9A6, 'M', '簾'), (0xF9A7, 'M', '獵'), (0xF9A8, 'M', '令'), (0xF9A9, 'M', '囹'), ] def _seg_41() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xF9AA, 'M', '寧'), (0xF9AB, 'M', '嶺'), (0xF9AC, 'M', '怜'), (0xF9AD, 'M', '玲'), (0xF9AE, 'M', '瑩'), (0xF9AF, 'M', '羚'), (0xF9B0, 'M', '聆'), (0xF9B1, 'M', '鈴'), (0xF9B2, 'M', '零'), (0xF9B3, 'M', '靈'), (0xF9B4, 'M', '領'), (0xF9B5, 'M', '例'), (0xF9B6, 'M', '禮'), (0xF9B7, 'M', '醴'), (0xF9B8, 'M', '隸'), (0xF9B9, 'M', '惡'), (0xF9BA, 'M', '了'), (0xF9BB, 'M', '僚'), (0xF9BC, 'M', '寮'), (0xF9BD, 'M', '尿'), (0xF9BE, 'M', '料'), (0xF9BF, 'M', '樂'), (0xF9C0, 'M', '燎'), (0xF9C1, 'M', '療'), (0xF9C2, 'M', '蓼'), (0xF9C3, 'M', '遼'), (0xF9C4, 'M', '龍'), (0xF9C5, 'M', '暈'), (0xF9C6, 'M', '阮'), (0xF9C7, 'M', '劉'), (0xF9C8, 'M', '杻'), (0xF9C9, 'M', '柳'), (0xF9CA, 'M', '流'), (0xF9CB, 'M', '溜'), (0xF9CC, 'M', '琉'), (0xF9CD, 'M', '留'), (0xF9CE, 'M', '硫'), (0xF9CF, 'M', '紐'), (0xF9D0, 'M', '類'), (0xF9D1, 'M', '六'), (0xF9D2, 'M', '戮'), (0xF9D3, 'M', '陸'), (0xF9D4, 'M', '倫'), (0xF9D5, 'M', '崙'), (0xF9D6, 'M', '淪'), (0xF9D7, 'M', '輪'), (0xF9D8, 'M', '律'), (0xF9D9, 'M', '慄'), (0xF9DA, 'M', '栗'), (0xF9DB, 'M', '率'), (0xF9DC, 'M', '隆'), (0xF9DD, 'M', '利'), (0xF9DE, 'M', '吏'), (0xF9DF, 'M', '履'), (0xF9E0, 'M', '易'), (0xF9E1, 'M', '李'), (0xF9E2, 'M', '梨'), (0xF9E3, 'M', '泥'), (0xF9E4, 'M', '理'), (0xF9E5, 'M', '痢'), (0xF9E6, 'M', '罹'), (0xF9E7, 'M', '裏'), (0xF9E8, 'M', '裡'), (0xF9E9, 'M', '里'), (0xF9EA, 'M', '離'), (0xF9EB, 'M', '匿'), (0xF9EC, 'M', '溺'), (0xF9ED, 'M', '吝'), (0xF9EE, 'M', '燐'), (0xF9EF, 'M', '璘'), (0xF9F0, 'M', '藺'), (0xF9F1, 'M', '隣'), (0xF9F2, 'M', '鱗'), (0xF9F3, 'M', '麟'), (0xF9F4, 'M', '林'), (0xF9F5, 'M', '淋'), (0xF9F6, 'M', '臨'), (0xF9F7, 'M', '立'), (0xF9F8, 'M', '笠'), (0xF9F9, 'M', '粒'), (0xF9FA, 'M', '狀'), (0xF9FB, 'M', '炙'), (0xF9FC, 'M', '識'), (0xF9FD, 'M', '什'), (0xF9FE, 'M', '茶'), (0xF9FF, 'M', '刺'), (0xFA00, 'M', '切'), (0xFA01, 'M', '度'), (0xFA02, 'M', '拓'), (0xFA03, 'M', '糖'), (0xFA04, 'M', '宅'), (0xFA05, 'M', '洞'), (0xFA06, 'M', '暴'), (0xFA07, 'M', '輻'), (0xFA08, 'M', '行'), (0xFA09, 'M', '降'), (0xFA0A, 'M', '見'), (0xFA0B, 'M', '廓'), (0xFA0C, 'M', '兀'), (0xFA0D, 'M', '嗀'), ] def _seg_42() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFA0E, 'V'), (0xFA10, 'M', '塚'), (0xFA11, 'V'), (0xFA12, 'M', '晴'), (0xFA13, 'V'), (0xFA15, 'M', '凞'), (0xFA16, 'M', '猪'), (0xFA17, 'M', '益'), (0xFA18, 'M', '礼'), (0xFA19, 'M', '神'), (0xFA1A, 'M', '祥'), (0xFA1B, 'M', '福'), (0xFA1C, 'M', '靖'), (0xFA1D, 'M', '精'), (0xFA1E, 'M', '羽'), (0xFA1F, 'V'), (0xFA20, 'M', '蘒'), (0xFA21, 'V'), (0xFA22, 'M', '諸'), (0xFA23, 'V'), (0xFA25, 'M', '逸'), (0xFA26, 'M', '都'), (0xFA27, 'V'), (0xFA2A, 'M', '飯'), (0xFA2B, 'M', '飼'), (0xFA2C, 'M', '館'), (0xFA2D, 'M', '鶴'), (0xFA2E, 'M', '郞'), (0xFA2F, 'M', '隷'), (0xFA30, 'M', '侮'), (0xFA31, 'M', '僧'), (0xFA32, 'M', '免'), (0xFA33, 'M', '勉'), (0xFA34, 'M', '勤'), (0xFA35, 'M', '卑'), (0xFA36, 'M', '喝'), (0xFA37, 'M', '嘆'), (0xFA38, 'M', '器'), (0xFA39, 'M', '塀'), (0xFA3A, 'M', '墨'), (0xFA3B, 'M', '層'), (0xFA3C, 'M', '屮'), (0xFA3D, 'M', '悔'), (0xFA3E, 'M', '慨'), (0xFA3F, 'M', '憎'), (0xFA40, 'M', '懲'), (0xFA41, 'M', '敏'), (0xFA42, 'M', '既'), (0xFA43, 'M', '暑'), (0xFA44, 'M', '梅'), (0xFA45, 'M', '海'), (0xFA46, 'M', '渚'), (0xFA47, 'M', '漢'), (0xFA48, 'M', '煮'), (0xFA49, 'M', '爫'), (0xFA4A, 'M', '琢'), (0xFA4B, 'M', '碑'), (0xFA4C, 'M', '社'), (0xFA4D, 'M', '祉'), (0xFA4E, 'M', '祈'), (0xFA4F, 'M', '祐'), (0xFA50, 'M', '祖'), (0xFA51, 'M', '祝'), (0xFA52, 'M', '禍'), (0xFA53, 'M', '禎'), (0xFA54, 'M', '穀'), (0xFA55, 'M', '突'), (0xFA56, 'M', '節'), (0xFA57, 'M', '練'), (0xFA58, 'M', '縉'), (0xFA59, 'M', '繁'), (0xFA5A, 'M', '署'), (0xFA5B, 'M', '者'), (0xFA5C, 'M', '臭'), (0xFA5D, 'M', '艹'), (0xFA5F, 'M', '著'), (0xFA60, 'M', '褐'), (0xFA61, 'M', '視'), (0xFA62, 'M', '謁'), (0xFA63, 'M', '謹'), (0xFA64, 'M', '賓'), (0xFA65, 'M', '贈'), (0xFA66, 'M', '辶'), (0xFA67, 'M', '逸'), (0xFA68, 'M', '難'), (0xFA69, 'M', '響'), (0xFA6A, 'M', '頻'), (0xFA6B, 'M', '恵'), (0xFA6C, 'M', '𤋮'), (0xFA6D, 'M', '舘'), (0xFA6E, 'X'), (0xFA70, 'M', '並'), (0xFA71, 'M', '况'), (0xFA72, 'M', '全'), (0xFA73, 'M', '侀'), (0xFA74, 'M', '充'), (0xFA75, 'M', '冀'), (0xFA76, 'M', '勇'), (0xFA77, 'M', '勺'), (0xFA78, 'M', '喝'), ] def _seg_43() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFA79, 'M', '啕'), (0xFA7A, 'M', '喙'), (0xFA7B, 'M', '嗢'), (0xFA7C, 'M', '塚'), (0xFA7D, 'M', '墳'), (0xFA7E, 'M', '奄'), (0xFA7F, 'M', '奔'), (0xFA80, 'M', '婢'), (0xFA81, 'M', '嬨'), (0xFA82, 'M', '廒'), (0xFA83, 'M', '廙'), (0xFA84, 'M', '彩'), (0xFA85, 'M', '徭'), (0xFA86, 'M', '惘'), (0xFA87, 'M', '慎'), (0xFA88, 'M', '愈'), (0xFA89, 'M', '憎'), (0xFA8A, 'M', '慠'), (0xFA8B, 'M', '懲'), (0xFA8C, 'M', '戴'), (0xFA8D, 'M', '揄'), (0xFA8E, 'M', '搜'), (0xFA8F, 'M', '摒'), (0xFA90, 'M', '敖'), (0xFA91, 'M', '晴'), (0xFA92, 'M', '朗'), (0xFA93, 'M', '望'), (0xFA94, 'M', '杖'), (0xFA95, 'M', '歹'), (0xFA96, 'M', '殺'), (0xFA97, 'M', '流'), (0xFA98, 'M', '滛'), (0xFA99, 'M', '滋'), (0xFA9A, 'M', '漢'), (0xFA9B, 'M', '瀞'), (0xFA9C, 'M', '煮'), (0xFA9D, 'M', '瞧'), (0xFA9E, 'M', '爵'), (0xFA9F, 'M', '犯'), (0xFAA0, 'M', '猪'), (0xFAA1, 'M', '瑱'), (0xFAA2, 'M', '甆'), (0xFAA3, 'M', '画'), (0xFAA4, 'M', '瘝'), (0xFAA5, 'M', '瘟'), (0xFAA6, 'M', '益'), (0xFAA7, 'M', '盛'), (0xFAA8, 'M', '直'), (0xFAA9, 'M', '睊'), (0xFAAA, 'M', '着'), (0xFAAB, 'M', '磌'), (0xFAAC, 'M', '窱'), (0xFAAD, 'M', '節'), (0xFAAE, 'M', '类'), (0xFAAF, 'M', '絛'), (0xFAB0, 'M', '練'), (0xFAB1, 'M', '缾'), (0xFAB2, 'M', '者'), (0xFAB3, 'M', '荒'), (0xFAB4, 'M', '華'), (0xFAB5, 'M', '蝹'), (0xFAB6, 'M', '襁'), (0xFAB7, 'M', '覆'), (0xFAB8, 'M', '視'), (0xFAB9, 'M', '調'), (0xFABA, 'M', '諸'), (0xFABB, 'M', '請'), (0xFABC, 'M', '謁'), (0xFABD, 'M', '諾'), (0xFABE, 'M', '諭'), (0xFABF, 'M', '謹'), (0xFAC0, 'M', '變'), (0xFAC1, 'M', '贈'), (0xFAC2, 'M', '輸'), (0xFAC3, 'M', '遲'), (0xFAC4, 'M', '醙'), (0xFAC5, 'M', '鉶'), (0xFAC6, 'M', '陼'), (0xFAC7, 'M', '難'), (0xFAC8, 'M', '靖'), (0xFAC9, 'M', '韛'), (0xFACA, 'M', '響'), (0xFACB, 'M', '頋'), (0xFACC, 'M', '頻'), (0xFACD, 'M', '鬒'), (0xFACE, 'M', '龜'), (0xFACF, 'M', '𢡊'), (0xFAD0, 'M', '𢡄'), (0xFAD1, 'M', '𣏕'), (0xFAD2, 'M', '㮝'), (0xFAD3, 'M', '䀘'), (0xFAD4, 'M', '䀹'), (0xFAD5, 'M', '𥉉'), (0xFAD6, 'M', '𥳐'), (0xFAD7, 'M', '𧻓'), (0xFAD8, 'M', '齃'), (0xFAD9, 'M', '龎'), (0xFADA, 'X'), (0xFB00, 'M', 'ff'), (0xFB01, 'M', 'fi'), ] def _seg_44() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFB02, 'M', 'fl'), (0xFB03, 'M', 'ffi'), (0xFB04, 'M', 'ffl'), (0xFB05, 'M', 'st'), (0xFB07, 'X'), (0xFB13, 'M', 'մն'), (0xFB14, 'M', 'մե'), (0xFB15, 'M', 'մի'), (0xFB16, 'M', 'վն'), (0xFB17, 'M', 'մխ'), (0xFB18, 'X'), (0xFB1D, 'M', 'יִ'), (0xFB1E, 'V'), (0xFB1F, 'M', 'ײַ'), (0xFB20, 'M', 'ע'), (0xFB21, 'M', 'א'), (0xFB22, 'M', 'ד'), (0xFB23, 'M', 'ה'), (0xFB24, 'M', 'כ'), (0xFB25, 'M', 'ל'), (0xFB26, 'M', 'ם'), (0xFB27, 'M', 'ר'), (0xFB28, 'M', 'ת'), (0xFB29, '3', '+'), (0xFB2A, 'M', 'שׁ'), (0xFB2B, 'M', 'שׂ'), (0xFB2C, 'M', 'שּׁ'), (0xFB2D, 'M', 'שּׂ'), (0xFB2E, 'M', 'אַ'), (0xFB2F, 'M', 'אָ'), (0xFB30, 'M', 'אּ'), (0xFB31, 'M', 'בּ'), (0xFB32, 'M', 'גּ'), (0xFB33, 'M', 'דּ'), (0xFB34, 'M', 'הּ'), (0xFB35, 'M', 'וּ'), (0xFB36, 'M', 'זּ'), (0xFB37, 'X'), (0xFB38, 'M', 'טּ'), (0xFB39, 'M', 'יּ'), (0xFB3A, 'M', 'ךּ'), (0xFB3B, 'M', 'כּ'), (0xFB3C, 'M', 'לּ'), (0xFB3D, 'X'), (0xFB3E, 'M', 'מּ'), (0xFB3F, 'X'), (0xFB40, 'M', 'נּ'), (0xFB41, 'M', 'סּ'), (0xFB42, 'X'), (0xFB43, 'M', 'ףּ'), (0xFB44, 'M', 'פּ'), (0xFB45, 'X'), (0xFB46, 'M', 'צּ'), (0xFB47, 'M', 'קּ'), (0xFB48, 'M', 'רּ'), (0xFB49, 'M', 'שּ'), (0xFB4A, 'M', 'תּ'), (0xFB4B, 'M', 'וֹ'), (0xFB4C, 'M', 'בֿ'), (0xFB4D, 'M', 'כֿ'), (0xFB4E, 'M', 'פֿ'), (0xFB4F, 'M', 'אל'), (0xFB50, 'M', 'ٱ'), (0xFB52, 'M', 'ٻ'), (0xFB56, 'M', 'پ'), (0xFB5A, 'M', 'ڀ'), (0xFB5E, 'M', 'ٺ'), (0xFB62, 'M', 'ٿ'), (0xFB66, 'M', 'ٹ'), (0xFB6A, 'M', 'ڤ'), (0xFB6E, 'M', 'ڦ'), (0xFB72, 'M', 'ڄ'), (0xFB76, 'M', 'ڃ'), (0xFB7A, 'M', 'چ'), (0xFB7E, 'M', 'ڇ'), (0xFB82, 'M', 'ڍ'), (0xFB84, 'M', 'ڌ'), (0xFB86, 'M', 'ڎ'), (0xFB88, 'M', 'ڈ'), (0xFB8A, 'M', 'ژ'), (0xFB8C, 'M', 'ڑ'), (0xFB8E, 'M', 'ک'), (0xFB92, 'M', 'گ'), (0xFB96, 'M', 'ڳ'), (0xFB9A, 'M', 'ڱ'), (0xFB9E, 'M', 'ں'), (0xFBA0, 'M', 'ڻ'), (0xFBA4, 'M', 'ۀ'), (0xFBA6, 'M', 'ہ'), (0xFBAA, 'M', 'ھ'), (0xFBAE, 'M', 'ے'), (0xFBB0, 'M', 'ۓ'), (0xFBB2, 'V'), (0xFBC3, 'X'), (0xFBD3, 'M', 'ڭ'), (0xFBD7, 'M', 'ۇ'), (0xFBD9, 'M', 'ۆ'), (0xFBDB, 'M', 'ۈ'), (0xFBDD, 'M', 'ۇٴ'), (0xFBDE, 'M', 'ۋ'), ] def _seg_45() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFBE0, 'M', 'ۅ'), (0xFBE2, 'M', 'ۉ'), (0xFBE4, 'M', 'ې'), (0xFBE8, 'M', 'ى'), (0xFBEA, 'M', 'ئا'), (0xFBEC, 'M', 'ئە'), (0xFBEE, 'M', 'ئو'), (0xFBF0, 'M', 'ئۇ'), (0xFBF2, 'M', 'ئۆ'), (0xFBF4, 'M', 'ئۈ'), (0xFBF6, 'M', 'ئې'), (0xFBF9, 'M', 'ئى'), (0xFBFC, 'M', 'ی'), (0xFC00, 'M', 'ئج'), (0xFC01, 'M', 'ئح'), (0xFC02, 'M', 'ئم'), (0xFC03, 'M', 'ئى'), (0xFC04, 'M', 'ئي'), (0xFC05, 'M', 'بج'), (0xFC06, 'M', 'بح'), (0xFC07, 'M', 'بخ'), (0xFC08, 'M', 'بم'), (0xFC09, 'M', 'بى'), (0xFC0A, 'M', 'بي'), (0xFC0B, 'M', 'تج'), (0xFC0C, 'M', 'تح'), (0xFC0D, 'M', 'تخ'), (0xFC0E, 'M', 'تم'), (0xFC0F, 'M', 'تى'), (0xFC10, 'M', 'تي'), (0xFC11, 'M', 'ثج'), (0xFC12, 'M', 'ثم'), (0xFC13, 'M', 'ثى'), (0xFC14, 'M', 'ثي'), (0xFC15, 'M', 'جح'), (0xFC16, 'M', 'جم'), (0xFC17, 'M', 'حج'), (0xFC18, 'M', 'حم'), (0xFC19, 'M', 'خج'), (0xFC1A, 'M', 'خح'), (0xFC1B, 'M', 'خم'), (0xFC1C, 'M', 'سج'), (0xFC1D, 'M', 'سح'), (0xFC1E, 'M', 'سخ'), (0xFC1F, 'M', 'سم'), (0xFC20, 'M', 'صح'), (0xFC21, 'M', 'صم'), (0xFC22, 'M', 'ضج'), (0xFC23, 'M', 'ضح'), (0xFC24, 'M', 'ضخ'), (0xFC25, 'M', 'ضم'), (0xFC26, 'M', 'طح'), (0xFC27, 'M', 'طم'), (0xFC28, 'M', 'ظم'), (0xFC29, 'M', 'عج'), (0xFC2A, 'M', 'عم'), (0xFC2B, 'M', 'غج'), (0xFC2C, 'M', 'غم'), (0xFC2D, 'M', 'فج'), (0xFC2E, 'M', 'فح'), (0xFC2F, 'M', 'فخ'), (0xFC30, 'M', 'فم'), (0xFC31, 'M', 'فى'), (0xFC32, 'M', 'في'), (0xFC33, 'M', 'قح'), (0xFC34, 'M', 'قم'), (0xFC35, 'M', 'قى'), (0xFC36, 'M', 'قي'), (0xFC37, 'M', 'كا'), (0xFC38, 'M', 'كج'), (0xFC39, 'M', 'كح'), (0xFC3A, 'M', 'كخ'), (0xFC3B, 'M', 'كل'), (0xFC3C, 'M', 'كم'), (0xFC3D, 'M', 'كى'), (0xFC3E, 'M', 'كي'), (0xFC3F, 'M', 'لج'), (0xFC40, 'M', 'لح'), (0xFC41, 'M', 'لخ'), (0xFC42, 'M', 'لم'), (0xFC43, 'M', 'لى'), (0xFC44, 'M', 'لي'), (0xFC45, 'M', 'مج'), (0xFC46, 'M', 'مح'), (0xFC47, 'M', 'مخ'), (0xFC48, 'M', 'مم'), (0xFC49, 'M', 'مى'), (0xFC4A, 'M', 'مي'), (0xFC4B, 'M', 'نج'), (0xFC4C, 'M', 'نح'), (0xFC4D, 'M', 'نخ'), (0xFC4E, 'M', 'نم'), (0xFC4F, 'M', 'نى'), (0xFC50, 'M', 'ني'), (0xFC51, 'M', 'هج'), (0xFC52, 'M', 'هم'), (0xFC53, 'M', 'هى'), (0xFC54, 'M', 'هي'), (0xFC55, 'M', 'يج'), (0xFC56, 'M', 'يح'), ] def _seg_46() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFC57, 'M', 'يخ'), (0xFC58, 'M', 'يم'), (0xFC59, 'M', 'يى'), (0xFC5A, 'M', 'يي'), (0xFC5B, 'M', 'ذٰ'), (0xFC5C, 'M', 'رٰ'), (0xFC5D, 'M', 'ىٰ'), (0xFC5E, '3', ' ٌّ'), (0xFC5F, '3', ' ٍّ'), (0xFC60, '3', ' َّ'), (0xFC61, '3', ' ُّ'), (0xFC62, '3', ' ِّ'), (0xFC63, '3', ' ّٰ'), (0xFC64, 'M', 'ئر'), (0xFC65, 'M', 'ئز'), (0xFC66, 'M', 'ئم'), (0xFC67, 'M', 'ئن'), (0xFC68, 'M', 'ئى'), (0xFC69, 'M', 'ئي'), (0xFC6A, 'M', 'بر'), (0xFC6B, 'M', 'بز'), (0xFC6C, 'M', 'بم'), (0xFC6D, 'M', 'بن'), (0xFC6E, 'M', 'بى'), (0xFC6F, 'M', 'بي'), (0xFC70, 'M', 'تر'), (0xFC71, 'M', 'تز'), (0xFC72, 'M', 'تم'), (0xFC73, 'M', 'تن'), (0xFC74, 'M', 'تى'), (0xFC75, 'M', 'تي'), (0xFC76, 'M', 'ثر'), (0xFC77, 'M', 'ثز'), (0xFC78, 'M', 'ثم'), (0xFC79, 'M', 'ثن'), (0xFC7A, 'M', 'ثى'), (0xFC7B, 'M', 'ثي'), (0xFC7C, 'M', 'فى'), (0xFC7D, 'M', 'في'), (0xFC7E, 'M', 'قى'), (0xFC7F, 'M', 'قي'), (0xFC80, 'M', 'كا'), (0xFC81, 'M', 'كل'), (0xFC82, 'M', 'كم'), (0xFC83, 'M', 'كى'), (0xFC84, 'M', 'كي'), (0xFC85, 'M', 'لم'), (0xFC86, 'M', 'لى'), (0xFC87, 'M', 'لي'), (0xFC88, 'M', 'ما'), (0xFC89, 'M', 'مم'), (0xFC8A, 'M', 'نر'), (0xFC8B, 'M', 'نز'), (0xFC8C, 'M', 'نم'), (0xFC8D, 'M', 'نن'), (0xFC8E, 'M', 'نى'), (0xFC8F, 'M', 'ني'), (0xFC90, 'M', 'ىٰ'), (0xFC91, 'M', 'ير'), (0xFC92, 'M', 'يز'), (0xFC93, 'M', 'يم'), (0xFC94, 'M', 'ين'), (0xFC95, 'M', 'يى'), (0xFC96, 'M', 'يي'), (0xFC97, 'M', 'ئج'), (0xFC98, 'M', 'ئح'), (0xFC99, 'M', 'ئخ'), (0xFC9A, 'M', 'ئم'), (0xFC9B, 'M', 'ئه'), (0xFC9C, 'M', 'بج'), (0xFC9D, 'M', 'بح'), (0xFC9E, 'M', 'بخ'), (0xFC9F, 'M', 'بم'), (0xFCA0, 'M', 'به'), (0xFCA1, 'M', 'تج'), (0xFCA2, 'M', 'تح'), (0xFCA3, 'M', 'تخ'), (0xFCA4, 'M', 'تم'), (0xFCA5, 'M', 'ته'), (0xFCA6, 'M', 'ثم'), (0xFCA7, 'M', 'جح'), (0xFCA8, 'M', 'جم'), (0xFCA9, 'M', 'حج'), (0xFCAA, 'M', 'حم'), (0xFCAB, 'M', 'خج'), (0xFCAC, 'M', 'خم'), (0xFCAD, 'M', 'سج'), (0xFCAE, 'M', 'سح'), (0xFCAF, 'M', 'سخ'), (0xFCB0, 'M', 'سم'), (0xFCB1, 'M', 'صح'), (0xFCB2, 'M', 'صخ'), (0xFCB3, 'M', 'صم'), (0xFCB4, 'M', 'ضج'), (0xFCB5, 'M', 'ضح'), (0xFCB6, 'M', 'ضخ'), (0xFCB7, 'M', 'ضم'), (0xFCB8, 'M', 'طح'), (0xFCB9, 'M', 'ظم'), (0xFCBA, 'M', 'عج'), ] def _seg_47() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFCBB, 'M', 'عم'), (0xFCBC, 'M', 'غج'), (0xFCBD, 'M', 'غم'), (0xFCBE, 'M', 'فج'), (0xFCBF, 'M', 'فح'), (0xFCC0, 'M', 'فخ'), (0xFCC1, 'M', 'فم'), (0xFCC2, 'M', 'قح'), (0xFCC3, 'M', 'قم'), (0xFCC4, 'M', 'كج'), (0xFCC5, 'M', 'كح'), (0xFCC6, 'M', 'كخ'), (0xFCC7, 'M', 'كل'), (0xFCC8, 'M', 'كم'), (0xFCC9, 'M', 'لج'), (0xFCCA, 'M', 'لح'), (0xFCCB, 'M', 'لخ'), (0xFCCC, 'M', 'لم'), (0xFCCD, 'M', 'له'), (0xFCCE, 'M', 'مج'), (0xFCCF, 'M', 'مح'), (0xFCD0, 'M', 'مخ'), (0xFCD1, 'M', 'مم'), (0xFCD2, 'M', 'نج'), (0xFCD3, 'M', 'نح'), (0xFCD4, 'M', 'نخ'), (0xFCD5, 'M', 'نم'), (0xFCD6, 'M', 'نه'), (0xFCD7, 'M', 'هج'), (0xFCD8, 'M', 'هم'), (0xFCD9, 'M', 'هٰ'), (0xFCDA, 'M', 'يج'), (0xFCDB, 'M', 'يح'), (0xFCDC, 'M', 'يخ'), (0xFCDD, 'M', 'يم'), (0xFCDE, 'M', 'يه'), (0xFCDF, 'M', 'ئم'), (0xFCE0, 'M', 'ئه'), (0xFCE1, 'M', 'بم'), (0xFCE2, 'M', 'به'), (0xFCE3, 'M', 'تم'), (0xFCE4, 'M', 'ته'), (0xFCE5, 'M', 'ثم'), (0xFCE6, 'M', 'ثه'), (0xFCE7, 'M', 'سم'), (0xFCE8, 'M', 'سه'), (0xFCE9, 'M', 'شم'), (0xFCEA, 'M', 'شه'), (0xFCEB, 'M', 'كل'), (0xFCEC, 'M', 'كم'), (0xFCED, 'M', 'لم'), (0xFCEE, 'M', 'نم'), (0xFCEF, 'M', 'نه'), (0xFCF0, 'M', 'يم'), (0xFCF1, 'M', 'يه'), (0xFCF2, 'M', 'ـَّ'), (0xFCF3, 'M', 'ـُّ'), (0xFCF4, 'M', 'ـِّ'), (0xFCF5, 'M', 'طى'), (0xFCF6, 'M', 'طي'), (0xFCF7, 'M', 'عى'), (0xFCF8, 'M', 'عي'), (0xFCF9, 'M', 'غى'), (0xFCFA, 'M', 'غي'), (0xFCFB, 'M', 'سى'), (0xFCFC, 'M', 'سي'), (0xFCFD, 'M', 'شى'), (0xFCFE, 'M', 'شي'), (0xFCFF, 'M', 'حى'), (0xFD00, 'M', 'حي'), (0xFD01, 'M', 'جى'), (0xFD02, 'M', 'جي'), (0xFD03, 'M', 'خى'), (0xFD04, 'M', 'خي'), (0xFD05, 'M', 'صى'), (0xFD06, 'M', 'صي'), (0xFD07, 'M', 'ضى'), (0xFD08, 'M', 'ضي'), (0xFD09, 'M', 'شج'), (0xFD0A, 'M', 'شح'), (0xFD0B, 'M', 'شخ'), (0xFD0C, 'M', 'شم'), (0xFD0D, 'M', 'شر'), (0xFD0E, 'M', 'سر'), (0xFD0F, 'M', 'صر'), (0xFD10, 'M', 'ضر'), (0xFD11, 'M', 'طى'), (0xFD12, 'M', 'طي'), (0xFD13, 'M', 'عى'), (0xFD14, 'M', 'عي'), (0xFD15, 'M', 'غى'), (0xFD16, 'M', 'غي'), (0xFD17, 'M', 'سى'), (0xFD18, 'M', 'سي'), (0xFD19, 'M', 'شى'), (0xFD1A, 'M', 'شي'), (0xFD1B, 'M', 'حى'), (0xFD1C, 'M', 'حي'), (0xFD1D, 'M', 'جى'), (0xFD1E, 'M', 'جي'), ] def _seg_48() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFD1F, 'M', 'خى'), (0xFD20, 'M', 'خي'), (0xFD21, 'M', 'صى'), (0xFD22, 'M', 'صي'), (0xFD23, 'M', 'ضى'), (0xFD24, 'M', 'ضي'), (0xFD25, 'M', 'شج'), (0xFD26, 'M', 'شح'), (0xFD27, 'M', 'شخ'), (0xFD28, 'M', 'شم'), (0xFD29, 'M', 'شر'), (0xFD2A, 'M', 'سر'), (0xFD2B, 'M', 'صر'), (0xFD2C, 'M', 'ضر'), (0xFD2D, 'M', 'شج'), (0xFD2E, 'M', 'شح'), (0xFD2F, 'M', 'شخ'), (0xFD30, 'M', 'شم'), (0xFD31, 'M', 'سه'), (0xFD32, 'M', 'شه'), (0xFD33, 'M', 'طم'), (0xFD34, 'M', 'سج'), (0xFD35, 'M', 'سح'), (0xFD36, 'M', 'سخ'), (0xFD37, 'M', 'شج'), (0xFD38, 'M', 'شح'), (0xFD39, 'M', 'شخ'), (0xFD3A, 'M', 'طم'), (0xFD3B, 'M', 'ظم'), (0xFD3C, 'M', 'اً'), (0xFD3E, 'V'), (0xFD50, 'M', 'تجم'), (0xFD51, 'M', 'تحج'), (0xFD53, 'M', 'تحم'), (0xFD54, 'M', 'تخم'), (0xFD55, 'M', 'تمج'), (0xFD56, 'M', 'تمح'), (0xFD57, 'M', 'تمخ'), (0xFD58, 'M', 'جمح'), (0xFD5A, 'M', 'حمي'), (0xFD5B, 'M', 'حمى'), (0xFD5C, 'M', 'سحج'), (0xFD5D, 'M', 'سجح'), (0xFD5E, 'M', 'سجى'), (0xFD5F, 'M', 'سمح'), (0xFD61, 'M', 'سمج'), (0xFD62, 'M', 'سمم'), (0xFD64, 'M', 'صحح'), (0xFD66, 'M', 'صمم'), (0xFD67, 'M', 'شحم'), (0xFD69, 'M', 'شجي'), (0xFD6A, 'M', 'شمخ'), (0xFD6C, 'M', 'شمم'), (0xFD6E, 'M', 'ضحى'), (0xFD6F, 'M', 'ضخم'), (0xFD71, 'M', 'طمح'), (0xFD73, 'M', 'طمم'), (0xFD74, 'M', 'طمي'), (0xFD75, 'M', 'عجم'), (0xFD76, 'M', 'عمم'), (0xFD78, 'M', 'عمى'), (0xFD79, 'M', 'غمم'), (0xFD7A, 'M', 'غمي'), (0xFD7B, 'M', 'غمى'), (0xFD7C, 'M', 'فخم'), (0xFD7E, 'M', 'قمح'), (0xFD7F, 'M', 'قمم'), (0xFD80, 'M', 'لحم'), (0xFD81, 'M', 'لحي'), (0xFD82, 'M', 'لحى'), (0xFD83, 'M', 'لجج'), (0xFD85, 'M', 'لخم'), (0xFD87, 'M', 'لمح'), (0xFD89, 'M', 'محج'), (0xFD8A, 'M', 'محم'), (0xFD8B, 'M', 'محي'), (0xFD8C, 'M', 'مجح'), (0xFD8D, 'M', 'مجم'), (0xFD8E, 'M', 'مخج'), (0xFD8F, 'M', 'مخم'), (0xFD90, 'X'), (0xFD92, 'M', 'مجخ'), (0xFD93, 'M', 'همج'), (0xFD94, 'M', 'همم'), (0xFD95, 'M', 'نحم'), (0xFD96, 'M', 'نحى'), (0xFD97, 'M', 'نجم'), (0xFD99, 'M', 'نجى'), (0xFD9A, 'M', 'نمي'), (0xFD9B, 'M', 'نمى'), (0xFD9C, 'M', 'يمم'), (0xFD9E, 'M', 'بخي'), (0xFD9F, 'M', 'تجي'), (0xFDA0, 'M', 'تجى'), (0xFDA1, 'M', 'تخي'), (0xFDA2, 'M', 'تخى'), (0xFDA3, 'M', 'تمي'), (0xFDA4, 'M', 'تمى'), (0xFDA5, 'M', 'جمي'), (0xFDA6, 'M', 'جحى'), ] def _seg_49() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFDA7, 'M', 'جمى'), (0xFDA8, 'M', 'سخى'), (0xFDA9, 'M', 'صحي'), (0xFDAA, 'M', 'شحي'), (0xFDAB, 'M', 'ضحي'), (0xFDAC, 'M', 'لجي'), (0xFDAD, 'M', 'لمي'), (0xFDAE, 'M', 'يحي'), (0xFDAF, 'M', 'يجي'), (0xFDB0, 'M', 'يمي'), (0xFDB1, 'M', 'ممي'), (0xFDB2, 'M', 'قمي'), (0xFDB3, 'M', 'نحي'), (0xFDB4, 'M', 'قمح'), (0xFDB5, 'M', 'لحم'), (0xFDB6, 'M', 'عمي'), (0xFDB7, 'M', 'كمي'), (0xFDB8, 'M', 'نجح'), (0xFDB9, 'M', 'مخي'), (0xFDBA, 'M', 'لجم'), (0xFDBB, 'M', 'كمم'), (0xFDBC, 'M', 'لجم'), (0xFDBD, 'M', 'نجح'), (0xFDBE, 'M', 'جحي'), (0xFDBF, 'M', 'حجي'), (0xFDC0, 'M', 'مجي'), (0xFDC1, 'M', 'فمي'), (0xFDC2, 'M', 'بحي'), (0xFDC3, 'M', 'كمم'), (0xFDC4, 'M', 'عجم'), (0xFDC5, 'M', 'صمم'), (0xFDC6, 'M', 'سخي'), (0xFDC7, 'M', 'نجي'), (0xFDC8, 'X'), (0xFDCF, 'V'), (0xFDD0, 'X'), (0xFDF0, 'M', 'صلے'), (0xFDF1, 'M', 'قلے'), (0xFDF2, 'M', 'الله'), (0xFDF3, 'M', 'اكبر'), (0xFDF4, 'M', 'محمد'), (0xFDF5, 'M', 'صلعم'), (0xFDF6, 'M', 'رسول'), (0xFDF7, 'M', 'عليه'), (0xFDF8, 'M', 'وسلم'), (0xFDF9, 'M', 'صلى'), (0xFDFA, '3', 'صلى الله عليه وسلم'), (0xFDFB, '3', 'جل جلاله'), (0xFDFC, 'M', 'ریال'), (0xFDFD, 'V'), (0xFE00, 'I'), (0xFE10, '3', ','), (0xFE11, 'M', '、'), (0xFE12, 'X'), (0xFE13, '3', ':'), (0xFE14, '3', ';'), (0xFE15, '3', '!'), (0xFE16, '3', '?'), (0xFE17, 'M', '〖'), (0xFE18, 'M', '〗'), (0xFE19, 'X'), (0xFE20, 'V'), (0xFE30, 'X'), (0xFE31, 'M', '—'), (0xFE32, 'M', '–'), (0xFE33, '3', '_'), (0xFE35, '3', '('), (0xFE36, '3', ')'), (0xFE37, '3', '{'), (0xFE38, '3', '}'), (0xFE39, 'M', '〔'), (0xFE3A, 'M', '〕'), (0xFE3B, 'M', '【'), (0xFE3C, 'M', '】'), (0xFE3D, 'M', '《'), (0xFE3E, 'M', '》'), (0xFE3F, 'M', '〈'), (0xFE40, 'M', '〉'), (0xFE41, 'M', '「'), (0xFE42, 'M', '」'), (0xFE43, 'M', '『'), (0xFE44, 'M', '』'), (0xFE45, 'V'), (0xFE47, '3', '['), (0xFE48, '3', ']'), (0xFE49, '3', ' ̅'), (0xFE4D, '3', '_'), (0xFE50, '3', ','), (0xFE51, 'M', '、'), (0xFE52, 'X'), (0xFE54, '3', ';'), (0xFE55, '3', ':'), (0xFE56, '3', '?'), (0xFE57, '3', '!'), (0xFE58, 'M', '—'), (0xFE59, '3', '('), (0xFE5A, '3', ')'), (0xFE5B, '3', '{'), (0xFE5C, '3', '}'), (0xFE5D, 'M', '〔'), ] def _seg_50() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFE5E, 'M', '〕'), (0xFE5F, '3', '#'), (0xFE60, '3', '&'), (0xFE61, '3', '*'), (0xFE62, '3', '+'), (0xFE63, 'M', '-'), (0xFE64, '3', '<'), (0xFE65, '3', '>'), (0xFE66, '3', '='), (0xFE67, 'X'), (0xFE68, '3', '\\'), (0xFE69, '3', '$'), (0xFE6A, '3', '%'), (0xFE6B, '3', '@'), (0xFE6C, 'X'), (0xFE70, '3', ' ً'), (0xFE71, 'M', 'ـً'), (0xFE72, '3', ' ٌ'), (0xFE73, 'V'), (0xFE74, '3', ' ٍ'), (0xFE75, 'X'), (0xFE76, '3', ' َ'), (0xFE77, 'M', 'ـَ'), (0xFE78, '3', ' ُ'), (0xFE79, 'M', 'ـُ'), (0xFE7A, '3', ' ِ'), (0xFE7B, 'M', 'ـِ'), (0xFE7C, '3', ' ّ'), (0xFE7D, 'M', 'ـّ'), (0xFE7E, '3', ' ْ'), (0xFE7F, 'M', 'ـْ'), (0xFE80, 'M', 'ء'), (0xFE81, 'M', 'آ'), (0xFE83, 'M', 'أ'), (0xFE85, 'M', 'ؤ'), (0xFE87, 'M', 'إ'), (0xFE89, 'M', 'ئ'), (0xFE8D, 'M', 'ا'), (0xFE8F, 'M', 'ب'), (0xFE93, 'M', 'ة'), (0xFE95, 'M', 'ت'), (0xFE99, 'M', 'ث'), (0xFE9D, 'M', 'ج'), (0xFEA1, 'M', 'ح'), (0xFEA5, 'M', 'خ'), (0xFEA9, 'M', 'د'), (0xFEAB, 'M', 'ذ'), (0xFEAD, 'M', 'ر'), (0xFEAF, 'M', 'ز'), (0xFEB1, 'M', 'س'), (0xFEB5, 'M', 'ش'), (0xFEB9, 'M', 'ص'), (0xFEBD, 'M', 'ض'), (0xFEC1, 'M', 'ط'), (0xFEC5, 'M', 'ظ'), (0xFEC9, 'M', 'ع'), (0xFECD, 'M', 'غ'), (0xFED1, 'M', 'ف'), (0xFED5, 'M', 'ق'), (0xFED9, 'M', 'ك'), (0xFEDD, 'M', 'ل'), (0xFEE1, 'M', 'م'), (0xFEE5, 'M', 'ن'), (0xFEE9, 'M', 'ه'), (0xFEED, 'M', 'و'), (0xFEEF, 'M', 'ى'), (0xFEF1, 'M', 'ي'), (0xFEF5, 'M', 'لآ'), (0xFEF7, 'M', 'لأ'), (0xFEF9, 'M', 'لإ'), (0xFEFB, 'M', 'لا'), (0xFEFD, 'X'), (0xFEFF, 'I'), (0xFF00, 'X'), (0xFF01, '3', '!'), (0xFF02, '3', '"'), (0xFF03, '3', '#'), (0xFF04, '3', '$'), (0xFF05, '3', '%'), (0xFF06, '3', '&'), (0xFF07, '3', '\''), (0xFF08, '3', '('), (0xFF09, '3', ')'), (0xFF0A, '3', '*'), (0xFF0B, '3', '+'), (0xFF0C, '3', ','), (0xFF0D, 'M', '-'), (0xFF0E, 'M', '.'), (0xFF0F, '3', '/'), (0xFF10, 'M', '0'), (0xFF11, 'M', '1'), (0xFF12, 'M', '2'), (0xFF13, 'M', '3'), (0xFF14, 'M', '4'), (0xFF15, 'M', '5'), (0xFF16, 'M', '6'), (0xFF17, 'M', '7'), (0xFF18, 'M', '8'), (0xFF19, 'M', '9'), (0xFF1A, '3', ':'), ] def _seg_51() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFF1B, '3', ';'), (0xFF1C, '3', '<'), (0xFF1D, '3', '='), (0xFF1E, '3', '>'), (0xFF1F, '3', '?'), (0xFF20, '3', '@'), (0xFF21, 'M', 'a'), (0xFF22, 'M', 'b'), (0xFF23, 'M', 'c'), (0xFF24, 'M', 'd'), (0xFF25, 'M', 'e'), (0xFF26, 'M', 'f'), (0xFF27, 'M', 'g'), (0xFF28, 'M', 'h'), (0xFF29, 'M', 'i'), (0xFF2A, 'M', 'j'), (0xFF2B, 'M', 'k'), (0xFF2C, 'M', 'l'), (0xFF2D, 'M', 'm'), (0xFF2E, 'M', 'n'), (0xFF2F, 'M', 'o'), (0xFF30, 'M', 'p'), (0xFF31, 'M', 'q'), (0xFF32, 'M', 'r'), (0xFF33, 'M', 's'), (0xFF34, 'M', 't'), (0xFF35, 'M', 'u'), (0xFF36, 'M', 'v'), (0xFF37, 'M', 'w'), (0xFF38, 'M', 'x'), (0xFF39, 'M', 'y'), (0xFF3A, 'M', 'z'), (0xFF3B, '3', '['), (0xFF3C, '3', '\\'), (0xFF3D, '3', ']'), (0xFF3E, '3', '^'), (0xFF3F, '3', '_'), (0xFF40, '3', '`'), (0xFF41, 'M', 'a'), (0xFF42, 'M', 'b'), (0xFF43, 'M', 'c'), (0xFF44, 'M', 'd'), (0xFF45, 'M', 'e'), (0xFF46, 'M', 'f'), (0xFF47, 'M', 'g'), (0xFF48, 'M', 'h'), (0xFF49, 'M', 'i'), (0xFF4A, 'M', 'j'), (0xFF4B, 'M', 'k'), (0xFF4C, 'M', 'l'), (0xFF4D, 'M', 'm'), (0xFF4E, 'M', 'n'), (0xFF4F, 'M', 'o'), (0xFF50, 'M', 'p'), (0xFF51, 'M', 'q'), (0xFF52, 'M', 'r'), (0xFF53, 'M', 's'), (0xFF54, 'M', 't'), (0xFF55, 'M', 'u'), (0xFF56, 'M', 'v'), (0xFF57, 'M', 'w'), (0xFF58, 'M', 'x'), (0xFF59, 'M', 'y'), (0xFF5A, 'M', 'z'), (0xFF5B, '3', '{'), (0xFF5C, '3', '|'), (0xFF5D, '3', '}'), (0xFF5E, '3', '~'), (0xFF5F, 'M', '⦅'), (0xFF60, 'M', '⦆'), (0xFF61, 'M', '.'), (0xFF62, 'M', '「'), (0xFF63, 'M', '」'), (0xFF64, 'M', '、'), (0xFF65, 'M', '・'), (0xFF66, 'M', 'ヲ'), (0xFF67, 'M', 'ァ'), (0xFF68, 'M', 'ィ'), (0xFF69, 'M', 'ゥ'), (0xFF6A, 'M', 'ェ'), (0xFF6B, 'M', 'ォ'), (0xFF6C, 'M', 'ャ'), (0xFF6D, 'M', 'ュ'), (0xFF6E, 'M', 'ョ'), (0xFF6F, 'M', 'ッ'), (0xFF70, 'M', 'ー'), (0xFF71, 'M', 'ア'), (0xFF72, 'M', 'イ'), (0xFF73, 'M', 'ウ'), (0xFF74, 'M', 'エ'), (0xFF75, 'M', 'オ'), (0xFF76, 'M', 'カ'), (0xFF77, 'M', 'キ'), (0xFF78, 'M', 'ク'), (0xFF79, 'M', 'ケ'), (0xFF7A, 'M', 'コ'), (0xFF7B, 'M', 'サ'), (0xFF7C, 'M', 'シ'), (0xFF7D, 'M', 'ス'), (0xFF7E, 'M', 'セ'), ] def _seg_52() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFF7F, 'M', 'ソ'), (0xFF80, 'M', 'タ'), (0xFF81, 'M', 'チ'), (0xFF82, 'M', 'ツ'), (0xFF83, 'M', 'テ'), (0xFF84, 'M', 'ト'), (0xFF85, 'M', 'ナ'), (0xFF86, 'M', 'ニ'), (0xFF87, 'M', 'ヌ'), (0xFF88, 'M', 'ネ'), (0xFF89, 'M', 'ノ'), (0xFF8A, 'M', 'ハ'), (0xFF8B, 'M', 'ヒ'), (0xFF8C, 'M', 'フ'), (0xFF8D, 'M', 'ヘ'), (0xFF8E, 'M', 'ホ'), (0xFF8F, 'M', 'マ'), (0xFF90, 'M', 'ミ'), (0xFF91, 'M', 'ム'), (0xFF92, 'M', 'メ'), (0xFF93, 'M', 'モ'), (0xFF94, 'M', 'ヤ'), (0xFF95, 'M', 'ユ'), (0xFF96, 'M', 'ヨ'), (0xFF97, 'M', 'ラ'), (0xFF98, 'M', 'リ'), (0xFF99, 'M', 'ル'), (0xFF9A, 'M', 'レ'), (0xFF9B, 'M', 'ロ'), (0xFF9C, 'M', 'ワ'), (0xFF9D, 'M', 'ン'), (0xFF9E, 'M', '゙'), (0xFF9F, 'M', '゚'), (0xFFA0, 'X'), (0xFFA1, 'M', 'ᄀ'), (0xFFA2, 'M', 'ᄁ'), (0xFFA3, 'M', 'ᆪ'), (0xFFA4, 'M', 'ᄂ'), (0xFFA5, 'M', 'ᆬ'), (0xFFA6, 'M', 'ᆭ'), (0xFFA7, 'M', 'ᄃ'), (0xFFA8, 'M', 'ᄄ'), (0xFFA9, 'M', 'ᄅ'), (0xFFAA, 'M', 'ᆰ'), (0xFFAB, 'M', 'ᆱ'), (0xFFAC, 'M', 'ᆲ'), (0xFFAD, 'M', 'ᆳ'), (0xFFAE, 'M', 'ᆴ'), (0xFFAF, 'M', 'ᆵ'), (0xFFB0, 'M', 'ᄚ'), (0xFFB1, 'M', 'ᄆ'), (0xFFB2, 'M', 'ᄇ'), (0xFFB3, 'M', 'ᄈ'), (0xFFB4, 'M', 'ᄡ'), (0xFFB5, 'M', 'ᄉ'), (0xFFB6, 'M', 'ᄊ'), (0xFFB7, 'M', 'ᄋ'), (0xFFB8, 'M', 'ᄌ'), (0xFFB9, 'M', 'ᄍ'), (0xFFBA, 'M', 'ᄎ'), (0xFFBB, 'M', 'ᄏ'), (0xFFBC, 'M', 'ᄐ'), (0xFFBD, 'M', 'ᄑ'), (0xFFBE, 'M', 'ᄒ'), (0xFFBF, 'X'), (0xFFC2, 'M', 'ᅡ'), (0xFFC3, 'M', 'ᅢ'), (0xFFC4, 'M', 'ᅣ'), (0xFFC5, 'M', 'ᅤ'), (0xFFC6, 'M', 'ᅥ'), (0xFFC7, 'M', 'ᅦ'), (0xFFC8, 'X'), (0xFFCA, 'M', 'ᅧ'), (0xFFCB, 'M', 'ᅨ'), (0xFFCC, 'M', 'ᅩ'), (0xFFCD, 'M', 'ᅪ'), (0xFFCE, 'M', 'ᅫ'), (0xFFCF, 'M', 'ᅬ'), (0xFFD0, 'X'), (0xFFD2, 'M', 'ᅭ'), (0xFFD3, 'M', 'ᅮ'), (0xFFD4, 'M', 'ᅯ'), (0xFFD5, 'M', 'ᅰ'), (0xFFD6, 'M', 'ᅱ'), (0xFFD7, 'M', 'ᅲ'), (0xFFD8, 'X'), (0xFFDA, 'M', 'ᅳ'), (0xFFDB, 'M', 'ᅴ'), (0xFFDC, 'M', 'ᅵ'), (0xFFDD, 'X'), (0xFFE0, 'M', '¢'), (0xFFE1, 'M', '£'), (0xFFE2, 'M', '¬'), (0xFFE3, '3', ' ̄'), (0xFFE4, 'M', '¦'), (0xFFE5, 'M', '¥'), (0xFFE6, 'M', '₩'), (0xFFE7, 'X'), (0xFFE8, 'M', '│'), (0xFFE9, 'M', '←'), ] def _seg_53() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0xFFEA, 'M', '↑'), (0xFFEB, 'M', '→'), (0xFFEC, 'M', '↓'), (0xFFED, 'M', '■'), (0xFFEE, 'M', '○'), (0xFFEF, 'X'), (0x10000, 'V'), (0x1000C, 'X'), (0x1000D, 'V'), (0x10027, 'X'), (0x10028, 'V'), (0x1003B, 'X'), (0x1003C, 'V'), (0x1003E, 'X'), (0x1003F, 'V'), (0x1004E, 'X'), (0x10050, 'V'), (0x1005E, 'X'), (0x10080, 'V'), (0x100FB, 'X'), (0x10100, 'V'), (0x10103, 'X'), (0x10107, 'V'), (0x10134, 'X'), (0x10137, 'V'), (0x1018F, 'X'), (0x10190, 'V'), (0x1019D, 'X'), (0x101A0, 'V'), (0x101A1, 'X'), (0x101D0, 'V'), (0x101FE, 'X'), (0x10280, 'V'), (0x1029D, 'X'), (0x102A0, 'V'), (0x102D1, 'X'), (0x102E0, 'V'), (0x102FC, 'X'), (0x10300, 'V'), (0x10324, 'X'), (0x1032D, 'V'), (0x1034B, 'X'), (0x10350, 'V'), (0x1037B, 'X'), (0x10380, 'V'), (0x1039E, 'X'), (0x1039F, 'V'), (0x103C4, 'X'), (0x103C8, 'V'), (0x103D6, 'X'), (0x10400, 'M', '𐐨'), (0x10401, 'M', '𐐩'), (0x10402, 'M', '𐐪'), (0x10403, 'M', '𐐫'), (0x10404, 'M', '𐐬'), (0x10405, 'M', '𐐭'), (0x10406, 'M', '𐐮'), (0x10407, 'M', '𐐯'), (0x10408, 'M', '𐐰'), (0x10409, 'M', '𐐱'), (0x1040A, 'M', '𐐲'), (0x1040B, 'M', '𐐳'), (0x1040C, 'M', '𐐴'), (0x1040D, 'M', '𐐵'), (0x1040E, 'M', '𐐶'), (0x1040F, 'M', '𐐷'), (0x10410, 'M', '𐐸'), (0x10411, 'M', '𐐹'), (0x10412, 'M', '𐐺'), (0x10413, 'M', '𐐻'), (0x10414, 'M', '𐐼'), (0x10415, 'M', '𐐽'), (0x10416, 'M', '𐐾'), (0x10417, 'M', '𐐿'), (0x10418, 'M', '𐑀'), (0x10419, 'M', '𐑁'), (0x1041A, 'M', '𐑂'), (0x1041B, 'M', '𐑃'), (0x1041C, 'M', '𐑄'), (0x1041D, 'M', '𐑅'), (0x1041E, 'M', '𐑆'), (0x1041F, 'M', '𐑇'), (0x10420, 'M', '𐑈'), (0x10421, 'M', '𐑉'), (0x10422, 'M', '𐑊'), (0x10423, 'M', '𐑋'), (0x10424, 'M', '𐑌'), (0x10425, 'M', '𐑍'), (0x10426, 'M', '𐑎'), (0x10427, 'M', '𐑏'), (0x10428, 'V'), (0x1049E, 'X'), (0x104A0, 'V'), (0x104AA, 'X'), (0x104B0, 'M', '𐓘'), (0x104B1, 'M', '𐓙'), (0x104B2, 'M', '𐓚'), (0x104B3, 'M', '𐓛'), (0x104B4, 'M', '𐓜'), (0x104B5, 'M', '𐓝'), ] def _seg_54() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x104B6, 'M', '𐓞'), (0x104B7, 'M', '𐓟'), (0x104B8, 'M', '𐓠'), (0x104B9, 'M', '𐓡'), (0x104BA, 'M', '𐓢'), (0x104BB, 'M', '𐓣'), (0x104BC, 'M', '𐓤'), (0x104BD, 'M', '𐓥'), (0x104BE, 'M', '𐓦'), (0x104BF, 'M', '𐓧'), (0x104C0, 'M', '𐓨'), (0x104C1, 'M', '𐓩'), (0x104C2, 'M', '𐓪'), (0x104C3, 'M', '𐓫'), (0x104C4, 'M', '𐓬'), (0x104C5, 'M', '𐓭'), (0x104C6, 'M', '𐓮'), (0x104C7, 'M', '𐓯'), (0x104C8, 'M', '𐓰'), (0x104C9, 'M', '𐓱'), (0x104CA, 'M', '𐓲'), (0x104CB, 'M', '𐓳'), (0x104CC, 'M', '𐓴'), (0x104CD, 'M', '𐓵'), (0x104CE, 'M', '𐓶'), (0x104CF, 'M', '𐓷'), (0x104D0, 'M', '𐓸'), (0x104D1, 'M', '𐓹'), (0x104D2, 'M', '𐓺'), (0x104D3, 'M', '𐓻'), (0x104D4, 'X'), (0x104D8, 'V'), (0x104FC, 'X'), (0x10500, 'V'), (0x10528, 'X'), (0x10530, 'V'), (0x10564, 'X'), (0x1056F, 'V'), (0x10570, 'M', '𐖗'), (0x10571, 'M', '𐖘'), (0x10572, 'M', '𐖙'), (0x10573, 'M', '𐖚'), (0x10574, 'M', '𐖛'), (0x10575, 'M', '𐖜'), (0x10576, 'M', '𐖝'), (0x10577, 'M', '𐖞'), (0x10578, 'M', '𐖟'), (0x10579, 'M', '𐖠'), (0x1057A, 'M', '𐖡'), (0x1057B, 'X'), (0x1057C, 'M', '𐖣'), (0x1057D, 'M', '𐖤'), (0x1057E, 'M', '𐖥'), (0x1057F, 'M', '𐖦'), (0x10580, 'M', '𐖧'), (0x10581, 'M', '𐖨'), (0x10582, 'M', '𐖩'), (0x10583, 'M', '𐖪'), (0x10584, 'M', '𐖫'), (0x10585, 'M', '𐖬'), (0x10586, 'M', '𐖭'), (0x10587, 'M', '𐖮'), (0x10588, 'M', '𐖯'), (0x10589, 'M', '𐖰'), (0x1058A, 'M', '𐖱'), (0x1058B, 'X'), (0x1058C, 'M', '𐖳'), (0x1058D, 'M', '𐖴'), (0x1058E, 'M', '𐖵'), (0x1058F, 'M', '𐖶'), (0x10590, 'M', '𐖷'), (0x10591, 'M', '𐖸'), (0x10592, 'M', '𐖹'), (0x10593, 'X'), (0x10594, 'M', '𐖻'), (0x10595, 'M', '𐖼'), (0x10596, 'X'), (0x10597, 'V'), (0x105A2, 'X'), (0x105A3, 'V'), (0x105B2, 'X'), (0x105B3, 'V'), (0x105BA, 'X'), (0x105BB, 'V'), (0x105BD, 'X'), (0x10600, 'V'), (0x10737, 'X'), (0x10740, 'V'), (0x10756, 'X'), (0x10760, 'V'), (0x10768, 'X'), (0x10780, 'V'), (0x10781, 'M', 'ː'), (0x10782, 'M', 'ˑ'), (0x10783, 'M', 'æ'), (0x10784, 'M', 'ʙ'), (0x10785, 'M', 'ɓ'), (0x10786, 'X'), (0x10787, 'M', 'ʣ'), (0x10788, 'M', 'ꭦ'), ] def _seg_55() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x10789, 'M', 'ʥ'), (0x1078A, 'M', 'ʤ'), (0x1078B, 'M', 'ɖ'), (0x1078C, 'M', 'ɗ'), (0x1078D, 'M', 'ᶑ'), (0x1078E, 'M', 'ɘ'), (0x1078F, 'M', 'ɞ'), (0x10790, 'M', 'ʩ'), (0x10791, 'M', 'ɤ'), (0x10792, 'M', 'ɢ'), (0x10793, 'M', 'ɠ'), (0x10794, 'M', 'ʛ'), (0x10795, 'M', 'ħ'), (0x10796, 'M', 'ʜ'), (0x10797, 'M', 'ɧ'), (0x10798, 'M', 'ʄ'), (0x10799, 'M', 'ʪ'), (0x1079A, 'M', 'ʫ'), (0x1079B, 'M', 'ɬ'), (0x1079C, 'M', '𝼄'), (0x1079D, 'M', 'ꞎ'), (0x1079E, 'M', 'ɮ'), (0x1079F, 'M', '𝼅'), (0x107A0, 'M', 'ʎ'), (0x107A1, 'M', '𝼆'), (0x107A2, 'M', 'ø'), (0x107A3, 'M', 'ɶ'), (0x107A4, 'M', 'ɷ'), (0x107A5, 'M', 'q'), (0x107A6, 'M', 'ɺ'), (0x107A7, 'M', '𝼈'), (0x107A8, 'M', 'ɽ'), (0x107A9, 'M', 'ɾ'), (0x107AA, 'M', 'ʀ'), (0x107AB, 'M', 'ʨ'), (0x107AC, 'M', 'ʦ'), (0x107AD, 'M', 'ꭧ'), (0x107AE, 'M', 'ʧ'), (0x107AF, 'M', 'ʈ'), (0x107B0, 'M', 'ⱱ'), (0x107B1, 'X'), (0x107B2, 'M', 'ʏ'), (0x107B3, 'M', 'ʡ'), (0x107B4, 'M', 'ʢ'), (0x107B5, 'M', 'ʘ'), (0x107B6, 'M', 'ǀ'), (0x107B7, 'M', 'ǁ'), (0x107B8, 'M', 'ǂ'), (0x107B9, 'M', '𝼊'), (0x107BA, 'M', '𝼞'), (0x107BB, 'X'), (0x10800, 'V'), (0x10806, 'X'), (0x10808, 'V'), (0x10809, 'X'), (0x1080A, 'V'), (0x10836, 'X'), (0x10837, 'V'), (0x10839, 'X'), (0x1083C, 'V'), (0x1083D, 'X'), (0x1083F, 'V'), (0x10856, 'X'), (0x10857, 'V'), (0x1089F, 'X'), (0x108A7, 'V'), (0x108B0, 'X'), (0x108E0, 'V'), (0x108F3, 'X'), (0x108F4, 'V'), (0x108F6, 'X'), (0x108FB, 'V'), (0x1091C, 'X'), (0x1091F, 'V'), (0x1093A, 'X'), (0x1093F, 'V'), (0x10940, 'X'), (0x10980, 'V'), (0x109B8, 'X'), (0x109BC, 'V'), (0x109D0, 'X'), (0x109D2, 'V'), (0x10A04, 'X'), (0x10A05, 'V'), (0x10A07, 'X'), (0x10A0C, 'V'), (0x10A14, 'X'), (0x10A15, 'V'), (0x10A18, 'X'), (0x10A19, 'V'), (0x10A36, 'X'), (0x10A38, 'V'), (0x10A3B, 'X'), (0x10A3F, 'V'), (0x10A49, 'X'), (0x10A50, 'V'), (0x10A59, 'X'), (0x10A60, 'V'), (0x10AA0, 'X'), (0x10AC0, 'V'), ] def _seg_56() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x10AE7, 'X'), (0x10AEB, 'V'), (0x10AF7, 'X'), (0x10B00, 'V'), (0x10B36, 'X'), (0x10B39, 'V'), (0x10B56, 'X'), (0x10B58, 'V'), (0x10B73, 'X'), (0x10B78, 'V'), (0x10B92, 'X'), (0x10B99, 'V'), (0x10B9D, 'X'), (0x10BA9, 'V'), (0x10BB0, 'X'), (0x10C00, 'V'), (0x10C49, 'X'), (0x10C80, 'M', '𐳀'), (0x10C81, 'M', '𐳁'), (0x10C82, 'M', '𐳂'), (0x10C83, 'M', '𐳃'), (0x10C84, 'M', '𐳄'), (0x10C85, 'M', '𐳅'), (0x10C86, 'M', '𐳆'), (0x10C87, 'M', '𐳇'), (0x10C88, 'M', '𐳈'), (0x10C89, 'M', '𐳉'), (0x10C8A, 'M', '𐳊'), (0x10C8B, 'M', '𐳋'), (0x10C8C, 'M', '𐳌'), (0x10C8D, 'M', '𐳍'), (0x10C8E, 'M', '𐳎'), (0x10C8F, 'M', '𐳏'), (0x10C90, 'M', '𐳐'), (0x10C91, 'M', '𐳑'), (0x10C92, 'M', '𐳒'), (0x10C93, 'M', '𐳓'), (0x10C94, 'M', '𐳔'), (0x10C95, 'M', '𐳕'), (0x10C96, 'M', '𐳖'), (0x10C97, 'M', '𐳗'), (0x10C98, 'M', '𐳘'), (0x10C99, 'M', '𐳙'), (0x10C9A, 'M', '𐳚'), (0x10C9B, 'M', '𐳛'), (0x10C9C, 'M', '𐳜'), (0x10C9D, 'M', '𐳝'), (0x10C9E, 'M', '𐳞'), (0x10C9F, 'M', '𐳟'), (0x10CA0, 'M', '𐳠'), (0x10CA1, 'M', '𐳡'), (0x10CA2, 'M', '𐳢'), (0x10CA3, 'M', '𐳣'), (0x10CA4, 'M', '𐳤'), (0x10CA5, 'M', '𐳥'), (0x10CA6, 'M', '𐳦'), (0x10CA7, 'M', '𐳧'), (0x10CA8, 'M', '𐳨'), (0x10CA9, 'M', '𐳩'), (0x10CAA, 'M', '𐳪'), (0x10CAB, 'M', '𐳫'), (0x10CAC, 'M', '𐳬'), (0x10CAD, 'M', '𐳭'), (0x10CAE, 'M', '𐳮'), (0x10CAF, 'M', '𐳯'), (0x10CB0, 'M', '𐳰'), (0x10CB1, 'M', '𐳱'), (0x10CB2, 'M', '𐳲'), (0x10CB3, 'X'), (0x10CC0, 'V'), (0x10CF3, 'X'), (0x10CFA, 'V'), (0x10D28, 'X'), (0x10D30, 'V'), (0x10D3A, 'X'), (0x10E60, 'V'), (0x10E7F, 'X'), (0x10E80, 'V'), (0x10EAA, 'X'), (0x10EAB, 'V'), (0x10EAE, 'X'), (0x10EB0, 'V'), (0x10EB2, 'X'), (0x10EFD, 'V'), (0x10F28, 'X'), (0x10F30, 'V'), (0x10F5A, 'X'), (0x10F70, 'V'), (0x10F8A, 'X'), (0x10FB0, 'V'), (0x10FCC, 'X'), (0x10FE0, 'V'), (0x10FF7, 'X'), (0x11000, 'V'), (0x1104E, 'X'), (0x11052, 'V'), (0x11076, 'X'), (0x1107F, 'V'), (0x110BD, 'X'), (0x110BE, 'V'), ] def _seg_57() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x110C3, 'X'), (0x110D0, 'V'), (0x110E9, 'X'), (0x110F0, 'V'), (0x110FA, 'X'), (0x11100, 'V'), (0x11135, 'X'), (0x11136, 'V'), (0x11148, 'X'), (0x11150, 'V'), (0x11177, 'X'), (0x11180, 'V'), (0x111E0, 'X'), (0x111E1, 'V'), (0x111F5, 'X'), (0x11200, 'V'), (0x11212, 'X'), (0x11213, 'V'), (0x11242, 'X'), (0x11280, 'V'), (0x11287, 'X'), (0x11288, 'V'), (0x11289, 'X'), (0x1128A, 'V'), (0x1128E, 'X'), (0x1128F, 'V'), (0x1129E, 'X'), (0x1129F, 'V'), (0x112AA, 'X'), (0x112B0, 'V'), (0x112EB, 'X'), (0x112F0, 'V'), (0x112FA, 'X'), (0x11300, 'V'), (0x11304, 'X'), (0x11305, 'V'), (0x1130D, 'X'), (0x1130F, 'V'), (0x11311, 'X'), (0x11313, 'V'), (0x11329, 'X'), (0x1132A, 'V'), (0x11331, 'X'), (0x11332, 'V'), (0x11334, 'X'), (0x11335, 'V'), (0x1133A, 'X'), (0x1133B, 'V'), (0x11345, 'X'), (0x11347, 'V'), (0x11349, 'X'), (0x1134B, 'V'), (0x1134E, 'X'), (0x11350, 'V'), (0x11351, 'X'), (0x11357, 'V'), (0x11358, 'X'), (0x1135D, 'V'), (0x11364, 'X'), (0x11366, 'V'), (0x1136D, 'X'), (0x11370, 'V'), (0x11375, 'X'), (0x11400, 'V'), (0x1145C, 'X'), (0x1145D, 'V'), (0x11462, 'X'), (0x11480, 'V'), (0x114C8, 'X'), (0x114D0, 'V'), (0x114DA, 'X'), (0x11580, 'V'), (0x115B6, 'X'), (0x115B8, 'V'), (0x115DE, 'X'), (0x11600, 'V'), (0x11645, 'X'), (0x11650, 'V'), (0x1165A, 'X'), (0x11660, 'V'), (0x1166D, 'X'), (0x11680, 'V'), (0x116BA, 'X'), (0x116C0, 'V'), (0x116CA, 'X'), (0x11700, 'V'), (0x1171B, 'X'), (0x1171D, 'V'), (0x1172C, 'X'), (0x11730, 'V'), (0x11747, 'X'), (0x11800, 'V'), (0x1183C, 'X'), (0x118A0, 'M', '𑣀'), (0x118A1, 'M', '𑣁'), (0x118A2, 'M', '𑣂'), (0x118A3, 'M', '𑣃'), (0x118A4, 'M', '𑣄'), (0x118A5, 'M', '𑣅'), (0x118A6, 'M', '𑣆'), ] def _seg_58() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x118A7, 'M', '𑣇'), (0x118A8, 'M', '𑣈'), (0x118A9, 'M', '𑣉'), (0x118AA, 'M', '𑣊'), (0x118AB, 'M', '𑣋'), (0x118AC, 'M', '𑣌'), (0x118AD, 'M', '𑣍'), (0x118AE, 'M', '𑣎'), (0x118AF, 'M', '𑣏'), (0x118B0, 'M', '𑣐'), (0x118B1, 'M', '𑣑'), (0x118B2, 'M', '𑣒'), (0x118B3, 'M', '𑣓'), (0x118B4, 'M', '𑣔'), (0x118B5, 'M', '𑣕'), (0x118B6, 'M', '𑣖'), (0x118B7, 'M', '𑣗'), (0x118B8, 'M', '𑣘'), (0x118B9, 'M', '𑣙'), (0x118BA, 'M', '𑣚'), (0x118BB, 'M', '𑣛'), (0x118BC, 'M', '𑣜'), (0x118BD, 'M', '𑣝'), (0x118BE, 'M', '𑣞'), (0x118BF, 'M', '𑣟'), (0x118C0, 'V'), (0x118F3, 'X'), (0x118FF, 'V'), (0x11907, 'X'), (0x11909, 'V'), (0x1190A, 'X'), (0x1190C, 'V'), (0x11914, 'X'), (0x11915, 'V'), (0x11917, 'X'), (0x11918, 'V'), (0x11936, 'X'), (0x11937, 'V'), (0x11939, 'X'), (0x1193B, 'V'), (0x11947, 'X'), (0x11950, 'V'), (0x1195A, 'X'), (0x119A0, 'V'), (0x119A8, 'X'), (0x119AA, 'V'), (0x119D8, 'X'), (0x119DA, 'V'), (0x119E5, 'X'), (0x11A00, 'V'), (0x11A48, 'X'), (0x11A50, 'V'), (0x11AA3, 'X'), (0x11AB0, 'V'), (0x11AF9, 'X'), (0x11B00, 'V'), (0x11B0A, 'X'), (0x11C00, 'V'), (0x11C09, 'X'), (0x11C0A, 'V'), (0x11C37, 'X'), (0x11C38, 'V'), (0x11C46, 'X'), (0x11C50, 'V'), (0x11C6D, 'X'), (0x11C70, 'V'), (0x11C90, 'X'), (0x11C92, 'V'), (0x11CA8, 'X'), (0x11CA9, 'V'), (0x11CB7, 'X'), (0x11D00, 'V'), (0x11D07, 'X'), (0x11D08, 'V'), (0x11D0A, 'X'), (0x11D0B, 'V'), (0x11D37, 'X'), (0x11D3A, 'V'), (0x11D3B, 'X'), (0x11D3C, 'V'), (0x11D3E, 'X'), (0x11D3F, 'V'), (0x11D48, 'X'), (0x11D50, 'V'), (0x11D5A, 'X'), (0x11D60, 'V'), (0x11D66, 'X'), (0x11D67, 'V'), (0x11D69, 'X'), (0x11D6A, 'V'), (0x11D8F, 'X'), (0x11D90, 'V'), (0x11D92, 'X'), (0x11D93, 'V'), (0x11D99, 'X'), (0x11DA0, 'V'), (0x11DAA, 'X'), (0x11EE0, 'V'), (0x11EF9, 'X'), (0x11F00, 'V'), ] def _seg_59() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x11F11, 'X'), (0x11F12, 'V'), (0x11F3B, 'X'), (0x11F3E, 'V'), (0x11F5A, 'X'), (0x11FB0, 'V'), (0x11FB1, 'X'), (0x11FC0, 'V'), (0x11FF2, 'X'), (0x11FFF, 'V'), (0x1239A, 'X'), (0x12400, 'V'), (0x1246F, 'X'), (0x12470, 'V'), (0x12475, 'X'), (0x12480, 'V'), (0x12544, 'X'), (0x12F90, 'V'), (0x12FF3, 'X'), (0x13000, 'V'), (0x13430, 'X'), (0x13440, 'V'), (0x13456, 'X'), (0x14400, 'V'), (0x14647, 'X'), (0x16800, 'V'), (0x16A39, 'X'), (0x16A40, 'V'), (0x16A5F, 'X'), (0x16A60, 'V'), (0x16A6A, 'X'), (0x16A6E, 'V'), (0x16ABF, 'X'), (0x16AC0, 'V'), (0x16ACA, 'X'), (0x16AD0, 'V'), (0x16AEE, 'X'), (0x16AF0, 'V'), (0x16AF6, 'X'), (0x16B00, 'V'), (0x16B46, 'X'), (0x16B50, 'V'), (0x16B5A, 'X'), (0x16B5B, 'V'), (0x16B62, 'X'), (0x16B63, 'V'), (0x16B78, 'X'), (0x16B7D, 'V'), (0x16B90, 'X'), (0x16E40, 'M', '𖹠'), (0x16E41, 'M', '𖹡'), (0x16E42, 'M', '𖹢'), (0x16E43, 'M', '𖹣'), (0x16E44, 'M', '𖹤'), (0x16E45, 'M', '𖹥'), (0x16E46, 'M', '𖹦'), (0x16E47, 'M', '𖹧'), (0x16E48, 'M', '𖹨'), (0x16E49, 'M', '𖹩'), (0x16E4A, 'M', '𖹪'), (0x16E4B, 'M', '𖹫'), (0x16E4C, 'M', '𖹬'), (0x16E4D, 'M', '𖹭'), (0x16E4E, 'M', '𖹮'), (0x16E4F, 'M', '𖹯'), (0x16E50, 'M', '𖹰'), (0x16E51, 'M', '𖹱'), (0x16E52, 'M', '𖹲'), (0x16E53, 'M', '𖹳'), (0x16E54, 'M', '𖹴'), (0x16E55, 'M', '𖹵'), (0x16E56, 'M', '𖹶'), (0x16E57, 'M', '𖹷'), (0x16E58, 'M', '𖹸'), (0x16E59, 'M', '𖹹'), (0x16E5A, 'M', '𖹺'), (0x16E5B, 'M', '𖹻'), (0x16E5C, 'M', '𖹼'), (0x16E5D, 'M', '𖹽'), (0x16E5E, 'M', '𖹾'), (0x16E5F, 'M', '𖹿'), (0x16E60, 'V'), (0x16E9B, 'X'), (0x16F00, 'V'), (0x16F4B, 'X'), (0x16F4F, 'V'), (0x16F88, 'X'), (0x16F8F, 'V'), (0x16FA0, 'X'), (0x16FE0, 'V'), (0x16FE5, 'X'), (0x16FF0, 'V'), (0x16FF2, 'X'), (0x17000, 'V'), (0x187F8, 'X'), (0x18800, 'V'), (0x18CD6, 'X'), (0x18D00, 'V'), (0x18D09, 'X'), (0x1AFF0, 'V'), ] def _seg_60() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1AFF4, 'X'), (0x1AFF5, 'V'), (0x1AFFC, 'X'), (0x1AFFD, 'V'), (0x1AFFF, 'X'), (0x1B000, 'V'), (0x1B123, 'X'), (0x1B132, 'V'), (0x1B133, 'X'), (0x1B150, 'V'), (0x1B153, 'X'), (0x1B155, 'V'), (0x1B156, 'X'), (0x1B164, 'V'), (0x1B168, 'X'), (0x1B170, 'V'), (0x1B2FC, 'X'), (0x1BC00, 'V'), (0x1BC6B, 'X'), (0x1BC70, 'V'), (0x1BC7D, 'X'), (0x1BC80, 'V'), (0x1BC89, 'X'), (0x1BC90, 'V'), (0x1BC9A, 'X'), (0x1BC9C, 'V'), (0x1BCA0, 'I'), (0x1BCA4, 'X'), (0x1CF00, 'V'), (0x1CF2E, 'X'), (0x1CF30, 'V'), (0x1CF47, 'X'), (0x1CF50, 'V'), (0x1CFC4, 'X'), (0x1D000, 'V'), (0x1D0F6, 'X'), (0x1D100, 'V'), (0x1D127, 'X'), (0x1D129, 'V'), (0x1D15E, 'M', '𝅗𝅥'), (0x1D15F, 'M', '𝅘𝅥'), (0x1D160, 'M', '𝅘𝅥𝅮'), (0x1D161, 'M', '𝅘𝅥𝅯'), (0x1D162, 'M', '𝅘𝅥𝅰'), (0x1D163, 'M', '𝅘𝅥𝅱'), (0x1D164, 'M', '𝅘𝅥𝅲'), (0x1D165, 'V'), (0x1D173, 'X'), (0x1D17B, 'V'), (0x1D1BB, 'M', '𝆹𝅥'), (0x1D1BC, 'M', '𝆺𝅥'), (0x1D1BD, 'M', '𝆹𝅥𝅮'), (0x1D1BE, 'M', '𝆺𝅥𝅮'), (0x1D1BF, 'M', '𝆹𝅥𝅯'), (0x1D1C0, 'M', '𝆺𝅥𝅯'), (0x1D1C1, 'V'), (0x1D1EB, 'X'), (0x1D200, 'V'), (0x1D246, 'X'), (0x1D2C0, 'V'), (0x1D2D4, 'X'), (0x1D2E0, 'V'), (0x1D2F4, 'X'), (0x1D300, 'V'), (0x1D357, 'X'), (0x1D360, 'V'), (0x1D379, 'X'), (0x1D400, 'M', 'a'), (0x1D401, 'M', 'b'), (0x1D402, 'M', 'c'), (0x1D403, 'M', 'd'), (0x1D404, 'M', 'e'), (0x1D405, 'M', 'f'), (0x1D406, 'M', 'g'), (0x1D407, 'M', 'h'), (0x1D408, 'M', 'i'), (0x1D409, 'M', 'j'), (0x1D40A, 'M', 'k'), (0x1D40B, 'M', 'l'), (0x1D40C, 'M', 'm'), (0x1D40D, 'M', 'n'), (0x1D40E, 'M', 'o'), (0x1D40F, 'M', 'p'), (0x1D410, 'M', 'q'), (0x1D411, 'M', 'r'), (0x1D412, 'M', 's'), (0x1D413, 'M', 't'), (0x1D414, 'M', 'u'), (0x1D415, 'M', 'v'), (0x1D416, 'M', 'w'), (0x1D417, 'M', 'x'), (0x1D418, 'M', 'y'), (0x1D419, 'M', 'z'), (0x1D41A, 'M', 'a'), (0x1D41B, 'M', 'b'), (0x1D41C, 'M', 'c'), (0x1D41D, 'M', 'd'), (0x1D41E, 'M', 'e'), (0x1D41F, 'M', 'f'), (0x1D420, 'M', 'g'), ] def _seg_61() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D421, 'M', 'h'), (0x1D422, 'M', 'i'), (0x1D423, 'M', 'j'), (0x1D424, 'M', 'k'), (0x1D425, 'M', 'l'), (0x1D426, 'M', 'm'), (0x1D427, 'M', 'n'), (0x1D428, 'M', 'o'), (0x1D429, 'M', 'p'), (0x1D42A, 'M', 'q'), (0x1D42B, 'M', 'r'), (0x1D42C, 'M', 's'), (0x1D42D, 'M', 't'), (0x1D42E, 'M', 'u'), (0x1D42F, 'M', 'v'), (0x1D430, 'M', 'w'), (0x1D431, 'M', 'x'), (0x1D432, 'M', 'y'), (0x1D433, 'M', 'z'), (0x1D434, 'M', 'a'), (0x1D435, 'M', 'b'), (0x1D436, 'M', 'c'), (0x1D437, 'M', 'd'), (0x1D438, 'M', 'e'), (0x1D439, 'M', 'f'), (0x1D43A, 'M', 'g'), (0x1D43B, 'M', 'h'), (0x1D43C, 'M', 'i'), (0x1D43D, 'M', 'j'), (0x1D43E, 'M', 'k'), (0x1D43F, 'M', 'l'), (0x1D440, 'M', 'm'), (0x1D441, 'M', 'n'), (0x1D442, 'M', 'o'), (0x1D443, 'M', 'p'), (0x1D444, 'M', 'q'), (0x1D445, 'M', 'r'), (0x1D446, 'M', 's'), (0x1D447, 'M', 't'), (0x1D448, 'M', 'u'), (0x1D449, 'M', 'v'), (0x1D44A, 'M', 'w'), (0x1D44B, 'M', 'x'), (0x1D44C, 'M', 'y'), (0x1D44D, 'M', 'z'), (0x1D44E, 'M', 'a'), (0x1D44F, 'M', 'b'), (0x1D450, 'M', 'c'), (0x1D451, 'M', 'd'), (0x1D452, 'M', 'e'), (0x1D453, 'M', 'f'), (0x1D454, 'M', 'g'), (0x1D455, 'X'), (0x1D456, 'M', 'i'), (0x1D457, 'M', 'j'), (0x1D458, 'M', 'k'), (0x1D459, 'M', 'l'), (0x1D45A, 'M', 'm'), (0x1D45B, 'M', 'n'), (0x1D45C, 'M', 'o'), (0x1D45D, 'M', 'p'), (0x1D45E, 'M', 'q'), (0x1D45F, 'M', 'r'), (0x1D460, 'M', 's'), (0x1D461, 'M', 't'), (0x1D462, 'M', 'u'), (0x1D463, 'M', 'v'), (0x1D464, 'M', 'w'), (0x1D465, 'M', 'x'), (0x1D466, 'M', 'y'), (0x1D467, 'M', 'z'), (0x1D468, 'M', 'a'), (0x1D469, 'M', 'b'), (0x1D46A, 'M', 'c'), (0x1D46B, 'M', 'd'), (0x1D46C, 'M', 'e'), (0x1D46D, 'M', 'f'), (0x1D46E, 'M', 'g'), (0x1D46F, 'M', 'h'), (0x1D470, 'M', 'i'), (0x1D471, 'M', 'j'), (0x1D472, 'M', 'k'), (0x1D473, 'M', 'l'), (0x1D474, 'M', 'm'), (0x1D475, 'M', 'n'), (0x1D476, 'M', 'o'), (0x1D477, 'M', 'p'), (0x1D478, 'M', 'q'), (0x1D479, 'M', 'r'), (0x1D47A, 'M', 's'), (0x1D47B, 'M', 't'), (0x1D47C, 'M', 'u'), (0x1D47D, 'M', 'v'), (0x1D47E, 'M', 'w'), (0x1D47F, 'M', 'x'), (0x1D480, 'M', 'y'), (0x1D481, 'M', 'z'), (0x1D482, 'M', 'a'), (0x1D483, 'M', 'b'), (0x1D484, 'M', 'c'), ] def _seg_62() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D485, 'M', 'd'), (0x1D486, 'M', 'e'), (0x1D487, 'M', 'f'), (0x1D488, 'M', 'g'), (0x1D489, 'M', 'h'), (0x1D48A, 'M', 'i'), (0x1D48B, 'M', 'j'), (0x1D48C, 'M', 'k'), (0x1D48D, 'M', 'l'), (0x1D48E, 'M', 'm'), (0x1D48F, 'M', 'n'), (0x1D490, 'M', 'o'), (0x1D491, 'M', 'p'), (0x1D492, 'M', 'q'), (0x1D493, 'M', 'r'), (0x1D494, 'M', 's'), (0x1D495, 'M', 't'), (0x1D496, 'M', 'u'), (0x1D497, 'M', 'v'), (0x1D498, 'M', 'w'), (0x1D499, 'M', 'x'), (0x1D49A, 'M', 'y'), (0x1D49B, 'M', 'z'), (0x1D49C, 'M', 'a'), (0x1D49D, 'X'), (0x1D49E, 'M', 'c'), (0x1D49F, 'M', 'd'), (0x1D4A0, 'X'), (0x1D4A2, 'M', 'g'), (0x1D4A3, 'X'), (0x1D4A5, 'M', 'j'), (0x1D4A6, 'M', 'k'), (0x1D4A7, 'X'), (0x1D4A9, 'M', 'n'), (0x1D4AA, 'M', 'o'), (0x1D4AB, 'M', 'p'), (0x1D4AC, 'M', 'q'), (0x1D4AD, 'X'), (0x1D4AE, 'M', 's'), (0x1D4AF, 'M', 't'), (0x1D4B0, 'M', 'u'), (0x1D4B1, 'M', 'v'), (0x1D4B2, 'M', 'w'), (0x1D4B3, 'M', 'x'), (0x1D4B4, 'M', 'y'), (0x1D4B5, 'M', 'z'), (0x1D4B6, 'M', 'a'), (0x1D4B7, 'M', 'b'), (0x1D4B8, 'M', 'c'), (0x1D4B9, 'M', 'd'), (0x1D4BA, 'X'), (0x1D4BB, 'M', 'f'), (0x1D4BC, 'X'), (0x1D4BD, 'M', 'h'), (0x1D4BE, 'M', 'i'), (0x1D4BF, 'M', 'j'), (0x1D4C0, 'M', 'k'), (0x1D4C1, 'M', 'l'), (0x1D4C2, 'M', 'm'), (0x1D4C3, 'M', 'n'), (0x1D4C4, 'X'), (0x1D4C5, 'M', 'p'), (0x1D4C6, 'M', 'q'), (0x1D4C7, 'M', 'r'), (0x1D4C8, 'M', 's'), (0x1D4C9, 'M', 't'), (0x1D4CA, 'M', 'u'), (0x1D4CB, 'M', 'v'), (0x1D4CC, 'M', 'w'), (0x1D4CD, 'M', 'x'), (0x1D4CE, 'M', 'y'), (0x1D4CF, 'M', 'z'), (0x1D4D0, 'M', 'a'), (0x1D4D1, 'M', 'b'), (0x1D4D2, 'M', 'c'), (0x1D4D3, 'M', 'd'), (0x1D4D4, 'M', 'e'), (0x1D4D5, 'M', 'f'), (0x1D4D6, 'M', 'g'), (0x1D4D7, 'M', 'h'), (0x1D4D8, 'M', 'i'), (0x1D4D9, 'M', 'j'), (0x1D4DA, 'M', 'k'), (0x1D4DB, 'M', 'l'), (0x1D4DC, 'M', 'm'), (0x1D4DD, 'M', 'n'), (0x1D4DE, 'M', 'o'), (0x1D4DF, 'M', 'p'), (0x1D4E0, 'M', 'q'), (0x1D4E1, 'M', 'r'), (0x1D4E2, 'M', 's'), (0x1D4E3, 'M', 't'), (0x1D4E4, 'M', 'u'), (0x1D4E5, 'M', 'v'), (0x1D4E6, 'M', 'w'), (0x1D4E7, 'M', 'x'), (0x1D4E8, 'M', 'y'), (0x1D4E9, 'M', 'z'), (0x1D4EA, 'M', 'a'), (0x1D4EB, 'M', 'b'), ] def _seg_63() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D4EC, 'M', 'c'), (0x1D4ED, 'M', 'd'), (0x1D4EE, 'M', 'e'), (0x1D4EF, 'M', 'f'), (0x1D4F0, 'M', 'g'), (0x1D4F1, 'M', 'h'), (0x1D4F2, 'M', 'i'), (0x1D4F3, 'M', 'j'), (0x1D4F4, 'M', 'k'), (0x1D4F5, 'M', 'l'), (0x1D4F6, 'M', 'm'), (0x1D4F7, 'M', 'n'), (0x1D4F8, 'M', 'o'), (0x1D4F9, 'M', 'p'), (0x1D4FA, 'M', 'q'), (0x1D4FB, 'M', 'r'), (0x1D4FC, 'M', 's'), (0x1D4FD, 'M', 't'), (0x1D4FE, 'M', 'u'), (0x1D4FF, 'M', 'v'), (0x1D500, 'M', 'w'), (0x1D501, 'M', 'x'), (0x1D502, 'M', 'y'), (0x1D503, 'M', 'z'), (0x1D504, 'M', 'a'), (0x1D505, 'M', 'b'), (0x1D506, 'X'), (0x1D507, 'M', 'd'), (0x1D508, 'M', 'e'), (0x1D509, 'M', 'f'), (0x1D50A, 'M', 'g'), (0x1D50B, 'X'), (0x1D50D, 'M', 'j'), (0x1D50E, 'M', 'k'), (0x1D50F, 'M', 'l'), (0x1D510, 'M', 'm'), (0x1D511, 'M', 'n'), (0x1D512, 'M', 'o'), (0x1D513, 'M', 'p'), (0x1D514, 'M', 'q'), (0x1D515, 'X'), (0x1D516, 'M', 's'), (0x1D517, 'M', 't'), (0x1D518, 'M', 'u'), (0x1D519, 'M', 'v'), (0x1D51A, 'M', 'w'), (0x1D51B, 'M', 'x'), (0x1D51C, 'M', 'y'), (0x1D51D, 'X'), (0x1D51E, 'M', 'a'), (0x1D51F, 'M', 'b'), (0x1D520, 'M', 'c'), (0x1D521, 'M', 'd'), (0x1D522, 'M', 'e'), (0x1D523, 'M', 'f'), (0x1D524, 'M', 'g'), (0x1D525, 'M', 'h'), (0x1D526, 'M', 'i'), (0x1D527, 'M', 'j'), (0x1D528, 'M', 'k'), (0x1D529, 'M', 'l'), (0x1D52A, 'M', 'm'), (0x1D52B, 'M', 'n'), (0x1D52C, 'M', 'o'), (0x1D52D, 'M', 'p'), (0x1D52E, 'M', 'q'), (0x1D52F, 'M', 'r'), (0x1D530, 'M', 's'), (0x1D531, 'M', 't'), (0x1D532, 'M', 'u'), (0x1D533, 'M', 'v'), (0x1D534, 'M', 'w'), (0x1D535, 'M', 'x'), (0x1D536, 'M', 'y'), (0x1D537, 'M', 'z'), (0x1D538, 'M', 'a'), (0x1D539, 'M', 'b'), (0x1D53A, 'X'), (0x1D53B, 'M', 'd'), (0x1D53C, 'M', 'e'), (0x1D53D, 'M', 'f'), (0x1D53E, 'M', 'g'), (0x1D53F, 'X'), (0x1D540, 'M', 'i'), (0x1D541, 'M', 'j'), (0x1D542, 'M', 'k'), (0x1D543, 'M', 'l'), (0x1D544, 'M', 'm'), (0x1D545, 'X'), (0x1D546, 'M', 'o'), (0x1D547, 'X'), (0x1D54A, 'M', 's'), (0x1D54B, 'M', 't'), (0x1D54C, 'M', 'u'), (0x1D54D, 'M', 'v'), (0x1D54E, 'M', 'w'), (0x1D54F, 'M', 'x'), (0x1D550, 'M', 'y'), (0x1D551, 'X'), (0x1D552, 'M', 'a'), ] def _seg_64() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D553, 'M', 'b'), (0x1D554, 'M', 'c'), (0x1D555, 'M', 'd'), (0x1D556, 'M', 'e'), (0x1D557, 'M', 'f'), (0x1D558, 'M', 'g'), (0x1D559, 'M', 'h'), (0x1D55A, 'M', 'i'), (0x1D55B, 'M', 'j'), (0x1D55C, 'M', 'k'), (0x1D55D, 'M', 'l'), (0x1D55E, 'M', 'm'), (0x1D55F, 'M', 'n'), (0x1D560, 'M', 'o'), (0x1D561, 'M', 'p'), (0x1D562, 'M', 'q'), (0x1D563, 'M', 'r'), (0x1D564, 'M', 's'), (0x1D565, 'M', 't'), (0x1D566, 'M', 'u'), (0x1D567, 'M', 'v'), (0x1D568, 'M', 'w'), (0x1D569, 'M', 'x'), (0x1D56A, 'M', 'y'), (0x1D56B, 'M', 'z'), (0x1D56C, 'M', 'a'), (0x1D56D, 'M', 'b'), (0x1D56E, 'M', 'c'), (0x1D56F, 'M', 'd'), (0x1D570, 'M', 'e'), (0x1D571, 'M', 'f'), (0x1D572, 'M', 'g'), (0x1D573, 'M', 'h'), (0x1D574, 'M', 'i'), (0x1D575, 'M', 'j'), (0x1D576, 'M', 'k'), (0x1D577, 'M', 'l'), (0x1D578, 'M', 'm'), (0x1D579, 'M', 'n'), (0x1D57A, 'M', 'o'), (0x1D57B, 'M', 'p'), (0x1D57C, 'M', 'q'), (0x1D57D, 'M', 'r'), (0x1D57E, 'M', 's'), (0x1D57F, 'M', 't'), (0x1D580, 'M', 'u'), (0x1D581, 'M', 'v'), (0x1D582, 'M', 'w'), (0x1D583, 'M', 'x'), (0x1D584, 'M', 'y'), (0x1D585, 'M', 'z'), (0x1D586, 'M', 'a'), (0x1D587, 'M', 'b'), (0x1D588, 'M', 'c'), (0x1D589, 'M', 'd'), (0x1D58A, 'M', 'e'), (0x1D58B, 'M', 'f'), (0x1D58C, 'M', 'g'), (0x1D58D, 'M', 'h'), (0x1D58E, 'M', 'i'), (0x1D58F, 'M', 'j'), (0x1D590, 'M', 'k'), (0x1D591, 'M', 'l'), (0x1D592, 'M', 'm'), (0x1D593, 'M', 'n'), (0x1D594, 'M', 'o'), (0x1D595, 'M', 'p'), (0x1D596, 'M', 'q'), (0x1D597, 'M', 'r'), (0x1D598, 'M', 's'), (0x1D599, 'M', 't'), (0x1D59A, 'M', 'u'), (0x1D59B, 'M', 'v'), (0x1D59C, 'M', 'w'), (0x1D59D, 'M', 'x'), (0x1D59E, 'M', 'y'), (0x1D59F, 'M', 'z'), (0x1D5A0, 'M', 'a'), (0x1D5A1, 'M', 'b'), (0x1D5A2, 'M', 'c'), (0x1D5A3, 'M', 'd'), (0x1D5A4, 'M', 'e'), (0x1D5A5, 'M', 'f'), (0x1D5A6, 'M', 'g'), (0x1D5A7, 'M', 'h'), (0x1D5A8, 'M', 'i'), (0x1D5A9, 'M', 'j'), (0x1D5AA, 'M', 'k'), (0x1D5AB, 'M', 'l'), (0x1D5AC, 'M', 'm'), (0x1D5AD, 'M', 'n'), (0x1D5AE, 'M', 'o'), (0x1D5AF, 'M', 'p'), (0x1D5B0, 'M', 'q'), (0x1D5B1, 'M', 'r'), (0x1D5B2, 'M', 's'), (0x1D5B3, 'M', 't'), (0x1D5B4, 'M', 'u'), (0x1D5B5, 'M', 'v'), (0x1D5B6, 'M', 'w'), ] def _seg_65() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D5B7, 'M', 'x'), (0x1D5B8, 'M', 'y'), (0x1D5B9, 'M', 'z'), (0x1D5BA, 'M', 'a'), (0x1D5BB, 'M', 'b'), (0x1D5BC, 'M', 'c'), (0x1D5BD, 'M', 'd'), (0x1D5BE, 'M', 'e'), (0x1D5BF, 'M', 'f'), (0x1D5C0, 'M', 'g'), (0x1D5C1, 'M', 'h'), (0x1D5C2, 'M', 'i'), (0x1D5C3, 'M', 'j'), (0x1D5C4, 'M', 'k'), (0x1D5C5, 'M', 'l'), (0x1D5C6, 'M', 'm'), (0x1D5C7, 'M', 'n'), (0x1D5C8, 'M', 'o'), (0x1D5C9, 'M', 'p'), (0x1D5CA, 'M', 'q'), (0x1D5CB, 'M', 'r'), (0x1D5CC, 'M', 's'), (0x1D5CD, 'M', 't'), (0x1D5CE, 'M', 'u'), (0x1D5CF, 'M', 'v'), (0x1D5D0, 'M', 'w'), (0x1D5D1, 'M', 'x'), (0x1D5D2, 'M', 'y'), (0x1D5D3, 'M', 'z'), (0x1D5D4, 'M', 'a'), (0x1D5D5, 'M', 'b'), (0x1D5D6, 'M', 'c'), (0x1D5D7, 'M', 'd'), (0x1D5D8, 'M', 'e'), (0x1D5D9, 'M', 'f'), (0x1D5DA, 'M', 'g'), (0x1D5DB, 'M', 'h'), (0x1D5DC, 'M', 'i'), (0x1D5DD, 'M', 'j'), (0x1D5DE, 'M', 'k'), (0x1D5DF, 'M', 'l'), (0x1D5E0, 'M', 'm'), (0x1D5E1, 'M', 'n'), (0x1D5E2, 'M', 'o'), (0x1D5E3, 'M', 'p'), (0x1D5E4, 'M', 'q'), (0x1D5E5, 'M', 'r'), (0x1D5E6, 'M', 's'), (0x1D5E7, 'M', 't'), (0x1D5E8, 'M', 'u'), (0x1D5E9, 'M', 'v'), (0x1D5EA, 'M', 'w'), (0x1D5EB, 'M', 'x'), (0x1D5EC, 'M', 'y'), (0x1D5ED, 'M', 'z'), (0x1D5EE, 'M', 'a'), (0x1D5EF, 'M', 'b'), (0x1D5F0, 'M', 'c'), (0x1D5F1, 'M', 'd'), (0x1D5F2, 'M', 'e'), (0x1D5F3, 'M', 'f'), (0x1D5F4, 'M', 'g'), (0x1D5F5, 'M', 'h'), (0x1D5F6, 'M', 'i'), (0x1D5F7, 'M', 'j'), (0x1D5F8, 'M', 'k'), (0x1D5F9, 'M', 'l'), (0x1D5FA, 'M', 'm'), (0x1D5FB, 'M', 'n'), (0x1D5FC, 'M', 'o'), (0x1D5FD, 'M', 'p'), (0x1D5FE, 'M', 'q'), (0x1D5FF, 'M', 'r'), (0x1D600, 'M', 's'), (0x1D601, 'M', 't'), (0x1D602, 'M', 'u'), (0x1D603, 'M', 'v'), (0x1D604, 'M', 'w'), (0x1D605, 'M', 'x'), (0x1D606, 'M', 'y'), (0x1D607, 'M', 'z'), (0x1D608, 'M', 'a'), (0x1D609, 'M', 'b'), (0x1D60A, 'M', 'c'), (0x1D60B, 'M', 'd'), (0x1D60C, 'M', 'e'), (0x1D60D, 'M', 'f'), (0x1D60E, 'M', 'g'), (0x1D60F, 'M', 'h'), (0x1D610, 'M', 'i'), (0x1D611, 'M', 'j'), (0x1D612, 'M', 'k'), (0x1D613, 'M', 'l'), (0x1D614, 'M', 'm'), (0x1D615, 'M', 'n'), (0x1D616, 'M', 'o'), (0x1D617, 'M', 'p'), (0x1D618, 'M', 'q'), (0x1D619, 'M', 'r'), (0x1D61A, 'M', 's'), ] def _seg_66() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D61B, 'M', 't'), (0x1D61C, 'M', 'u'), (0x1D61D, 'M', 'v'), (0x1D61E, 'M', 'w'), (0x1D61F, 'M', 'x'), (0x1D620, 'M', 'y'), (0x1D621, 'M', 'z'), (0x1D622, 'M', 'a'), (0x1D623, 'M', 'b'), (0x1D624, 'M', 'c'), (0x1D625, 'M', 'd'), (0x1D626, 'M', 'e'), (0x1D627, 'M', 'f'), (0x1D628, 'M', 'g'), (0x1D629, 'M', 'h'), (0x1D62A, 'M', 'i'), (0x1D62B, 'M', 'j'), (0x1D62C, 'M', 'k'), (0x1D62D, 'M', 'l'), (0x1D62E, 'M', 'm'), (0x1D62F, 'M', 'n'), (0x1D630, 'M', 'o'), (0x1D631, 'M', 'p'), (0x1D632, 'M', 'q'), (0x1D633, 'M', 'r'), (0x1D634, 'M', 's'), (0x1D635, 'M', 't'), (0x1D636, 'M', 'u'), (0x1D637, 'M', 'v'), (0x1D638, 'M', 'w'), (0x1D639, 'M', 'x'), (0x1D63A, 'M', 'y'), (0x1D63B, 'M', 'z'), (0x1D63C, 'M', 'a'), (0x1D63D, 'M', 'b'), (0x1D63E, 'M', 'c'), (0x1D63F, 'M', 'd'), (0x1D640, 'M', 'e'), (0x1D641, 'M', 'f'), (0x1D642, 'M', 'g'), (0x1D643, 'M', 'h'), (0x1D644, 'M', 'i'), (0x1D645, 'M', 'j'), (0x1D646, 'M', 'k'), (0x1D647, 'M', 'l'), (0x1D648, 'M', 'm'), (0x1D649, 'M', 'n'), (0x1D64A, 'M', 'o'), (0x1D64B, 'M', 'p'), (0x1D64C, 'M', 'q'), (0x1D64D, 'M', 'r'), (0x1D64E, 'M', 's'), (0x1D64F, 'M', 't'), (0x1D650, 'M', 'u'), (0x1D651, 'M', 'v'), (0x1D652, 'M', 'w'), (0x1D653, 'M', 'x'), (0x1D654, 'M', 'y'), (0x1D655, 'M', 'z'), (0x1D656, 'M', 'a'), (0x1D657, 'M', 'b'), (0x1D658, 'M', 'c'), (0x1D659, 'M', 'd'), (0x1D65A, 'M', 'e'), (0x1D65B, 'M', 'f'), (0x1D65C, 'M', 'g'), (0x1D65D, 'M', 'h'), (0x1D65E, 'M', 'i'), (0x1D65F, 'M', 'j'), (0x1D660, 'M', 'k'), (0x1D661, 'M', 'l'), (0x1D662, 'M', 'm'), (0x1D663, 'M', 'n'), (0x1D664, 'M', 'o'), (0x1D665, 'M', 'p'), (0x1D666, 'M', 'q'), (0x1D667, 'M', 'r'), (0x1D668, 'M', 's'), (0x1D669, 'M', 't'), (0x1D66A, 'M', 'u'), (0x1D66B, 'M', 'v'), (0x1D66C, 'M', 'w'), (0x1D66D, 'M', 'x'), (0x1D66E, 'M', 'y'), (0x1D66F, 'M', 'z'), (0x1D670, 'M', 'a'), (0x1D671, 'M', 'b'), (0x1D672, 'M', 'c'), (0x1D673, 'M', 'd'), (0x1D674, 'M', 'e'), (0x1D675, 'M', 'f'), (0x1D676, 'M', 'g'), (0x1D677, 'M', 'h'), (0x1D678, 'M', 'i'), (0x1D679, 'M', 'j'), (0x1D67A, 'M', 'k'), (0x1D67B, 'M', 'l'), (0x1D67C, 'M', 'm'), (0x1D67D, 'M', 'n'), (0x1D67E, 'M', 'o'), ] def _seg_67() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D67F, 'M', 'p'), (0x1D680, 'M', 'q'), (0x1D681, 'M', 'r'), (0x1D682, 'M', 's'), (0x1D683, 'M', 't'), (0x1D684, 'M', 'u'), (0x1D685, 'M', 'v'), (0x1D686, 'M', 'w'), (0x1D687, 'M', 'x'), (0x1D688, 'M', 'y'), (0x1D689, 'M', 'z'), (0x1D68A, 'M', 'a'), (0x1D68B, 'M', 'b'), (0x1D68C, 'M', 'c'), (0x1D68D, 'M', 'd'), (0x1D68E, 'M', 'e'), (0x1D68F, 'M', 'f'), (0x1D690, 'M', 'g'), (0x1D691, 'M', 'h'), (0x1D692, 'M', 'i'), (0x1D693, 'M', 'j'), (0x1D694, 'M', 'k'), (0x1D695, 'M', 'l'), (0x1D696, 'M', 'm'), (0x1D697, 'M', 'n'), (0x1D698, 'M', 'o'), (0x1D699, 'M', 'p'), (0x1D69A, 'M', 'q'), (0x1D69B, 'M', 'r'), (0x1D69C, 'M', 's'), (0x1D69D, 'M', 't'), (0x1D69E, 'M', 'u'), (0x1D69F, 'M', 'v'), (0x1D6A0, 'M', 'w'), (0x1D6A1, 'M', 'x'), (0x1D6A2, 'M', 'y'), (0x1D6A3, 'M', 'z'), (0x1D6A4, 'M', 'ı'), (0x1D6A5, 'M', 'ȷ'), (0x1D6A6, 'X'), (0x1D6A8, 'M', 'α'), (0x1D6A9, 'M', 'β'), (0x1D6AA, 'M', 'γ'), (0x1D6AB, 'M', 'δ'), (0x1D6AC, 'M', 'ε'), (0x1D6AD, 'M', 'ζ'), (0x1D6AE, 'M', 'η'), (0x1D6AF, 'M', 'θ'), (0x1D6B0, 'M', 'ι'), (0x1D6B1, 'M', 'κ'), (0x1D6B2, 'M', 'λ'), (0x1D6B3, 'M', 'μ'), (0x1D6B4, 'M', 'ν'), (0x1D6B5, 'M', 'ξ'), (0x1D6B6, 'M', 'ο'), (0x1D6B7, 'M', 'π'), (0x1D6B8, 'M', 'ρ'), (0x1D6B9, 'M', 'θ'), (0x1D6BA, 'M', 'σ'), (0x1D6BB, 'M', 'τ'), (0x1D6BC, 'M', 'υ'), (0x1D6BD, 'M', 'φ'), (0x1D6BE, 'M', 'χ'), (0x1D6BF, 'M', 'ψ'), (0x1D6C0, 'M', 'ω'), (0x1D6C1, 'M', '∇'), (0x1D6C2, 'M', 'α'), (0x1D6C3, 'M', 'β'), (0x1D6C4, 'M', 'γ'), (0x1D6C5, 'M', 'δ'), (0x1D6C6, 'M', 'ε'), (0x1D6C7, 'M', 'ζ'), (0x1D6C8, 'M', 'η'), (0x1D6C9, 'M', 'θ'), (0x1D6CA, 'M', 'ι'), (0x1D6CB, 'M', 'κ'), (0x1D6CC, 'M', 'λ'), (0x1D6CD, 'M', 'μ'), (0x1D6CE, 'M', 'ν'), (0x1D6CF, 'M', 'ξ'), (0x1D6D0, 'M', 'ο'), (0x1D6D1, 'M', 'π'), (0x1D6D2, 'M', 'ρ'), (0x1D6D3, 'M', 'σ'), (0x1D6D5, 'M', 'τ'), (0x1D6D6, 'M', 'υ'), (0x1D6D7, 'M', 'φ'), (0x1D6D8, 'M', 'χ'), (0x1D6D9, 'M', 'ψ'), (0x1D6DA, 'M', 'ω'), (0x1D6DB, 'M', '∂'), (0x1D6DC, 'M', 'ε'), (0x1D6DD, 'M', 'θ'), (0x1D6DE, 'M', 'κ'), (0x1D6DF, 'M', 'φ'), (0x1D6E0, 'M', 'ρ'), (0x1D6E1, 'M', 'π'), (0x1D6E2, 'M', 'α'), (0x1D6E3, 'M', 'β'), (0x1D6E4, 'M', 'γ'), ] def _seg_68() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D6E5, 'M', 'δ'), (0x1D6E6, 'M', 'ε'), (0x1D6E7, 'M', 'ζ'), (0x1D6E8, 'M', 'η'), (0x1D6E9, 'M', 'θ'), (0x1D6EA, 'M', 'ι'), (0x1D6EB, 'M', 'κ'), (0x1D6EC, 'M', 'λ'), (0x1D6ED, 'M', 'μ'), (0x1D6EE, 'M', 'ν'), (0x1D6EF, 'M', 'ξ'), (0x1D6F0, 'M', 'ο'), (0x1D6F1, 'M', 'π'), (0x1D6F2, 'M', 'ρ'), (0x1D6F3, 'M', 'θ'), (0x1D6F4, 'M', 'σ'), (0x1D6F5, 'M', 'τ'), (0x1D6F6, 'M', 'υ'), (0x1D6F7, 'M', 'φ'), (0x1D6F8, 'M', 'χ'), (0x1D6F9, 'M', 'ψ'), (0x1D6FA, 'M', 'ω'), (0x1D6FB, 'M', '∇'), (0x1D6FC, 'M', 'α'), (0x1D6FD, 'M', 'β'), (0x1D6FE, 'M', 'γ'), (0x1D6FF, 'M', 'δ'), (0x1D700, 'M', 'ε'), (0x1D701, 'M', 'ζ'), (0x1D702, 'M', 'η'), (0x1D703, 'M', 'θ'), (0x1D704, 'M', 'ι'), (0x1D705, 'M', 'κ'), (0x1D706, 'M', 'λ'), (0x1D707, 'M', 'μ'), (0x1D708, 'M', 'ν'), (0x1D709, 'M', 'ξ'), (0x1D70A, 'M', 'ο'), (0x1D70B, 'M', 'π'), (0x1D70C, 'M', 'ρ'), (0x1D70D, 'M', 'σ'), (0x1D70F, 'M', 'τ'), (0x1D710, 'M', 'υ'), (0x1D711, 'M', 'φ'), (0x1D712, 'M', 'χ'), (0x1D713, 'M', 'ψ'), (0x1D714, 'M', 'ω'), (0x1D715, 'M', '∂'), (0x1D716, 'M', 'ε'), (0x1D717, 'M', 'θ'), (0x1D718, 'M', 'κ'), (0x1D719, 'M', 'φ'), (0x1D71A, 'M', 'ρ'), (0x1D71B, 'M', 'π'), (0x1D71C, 'M', 'α'), (0x1D71D, 'M', 'β'), (0x1D71E, 'M', 'γ'), (0x1D71F, 'M', 'δ'), (0x1D720, 'M', 'ε'), (0x1D721, 'M', 'ζ'), (0x1D722, 'M', 'η'), (0x1D723, 'M', 'θ'), (0x1D724, 'M', 'ι'), (0x1D725, 'M', 'κ'), (0x1D726, 'M', 'λ'), (0x1D727, 'M', 'μ'), (0x1D728, 'M', 'ν'), (0x1D729, 'M', 'ξ'), (0x1D72A, 'M', 'ο'), (0x1D72B, 'M', 'π'), (0x1D72C, 'M', 'ρ'), (0x1D72D, 'M', 'θ'), (0x1D72E, 'M', 'σ'), (0x1D72F, 'M', 'τ'), (0x1D730, 'M', 'υ'), (0x1D731, 'M', 'φ'), (0x1D732, 'M', 'χ'), (0x1D733, 'M', 'ψ'), (0x1D734, 'M', 'ω'), (0x1D735, 'M', '∇'), (0x1D736, 'M', 'α'), (0x1D737, 'M', 'β'), (0x1D738, 'M', 'γ'), (0x1D739, 'M', 'δ'), (0x1D73A, 'M', 'ε'), (0x1D73B, 'M', 'ζ'), (0x1D73C, 'M', 'η'), (0x1D73D, 'M', 'θ'), (0x1D73E, 'M', 'ι'), (0x1D73F, 'M', 'κ'), (0x1D740, 'M', 'λ'), (0x1D741, 'M', 'μ'), (0x1D742, 'M', 'ν'), (0x1D743, 'M', 'ξ'), (0x1D744, 'M', 'ο'), (0x1D745, 'M', 'π'), (0x1D746, 'M', 'ρ'), (0x1D747, 'M', 'σ'), (0x1D749, 'M', 'τ'), (0x1D74A, 'M', 'υ'), ] def _seg_69() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D74B, 'M', 'φ'), (0x1D74C, 'M', 'χ'), (0x1D74D, 'M', 'ψ'), (0x1D74E, 'M', 'ω'), (0x1D74F, 'M', '∂'), (0x1D750, 'M', 'ε'), (0x1D751, 'M', 'θ'), (0x1D752, 'M', 'κ'), (0x1D753, 'M', 'φ'), (0x1D754, 'M', 'ρ'), (0x1D755, 'M', 'π'), (0x1D756, 'M', 'α'), (0x1D757, 'M', 'β'), (0x1D758, 'M', 'γ'), (0x1D759, 'M', 'δ'), (0x1D75A, 'M', 'ε'), (0x1D75B, 'M', 'ζ'), (0x1D75C, 'M', 'η'), (0x1D75D, 'M', 'θ'), (0x1D75E, 'M', 'ι'), (0x1D75F, 'M', 'κ'), (0x1D760, 'M', 'λ'), (0x1D761, 'M', 'μ'), (0x1D762, 'M', 'ν'), (0x1D763, 'M', 'ξ'), (0x1D764, 'M', 'ο'), (0x1D765, 'M', 'π'), (0x1D766, 'M', 'ρ'), (0x1D767, 'M', 'θ'), (0x1D768, 'M', 'σ'), (0x1D769, 'M', 'τ'), (0x1D76A, 'M', 'υ'), (0x1D76B, 'M', 'φ'), (0x1D76C, 'M', 'χ'), (0x1D76D, 'M', 'ψ'), (0x1D76E, 'M', 'ω'), (0x1D76F, 'M', '∇'), (0x1D770, 'M', 'α'), (0x1D771, 'M', 'β'), (0x1D772, 'M', 'γ'), (0x1D773, 'M', 'δ'), (0x1D774, 'M', 'ε'), (0x1D775, 'M', 'ζ'), (0x1D776, 'M', 'η'), (0x1D777, 'M', 'θ'), (0x1D778, 'M', 'ι'), (0x1D779, 'M', 'κ'), (0x1D77A, 'M', 'λ'), (0x1D77B, 'M', 'μ'), (0x1D77C, 'M', 'ν'), (0x1D77D, 'M', 'ξ'), (0x1D77E, 'M', 'ο'), (0x1D77F, 'M', 'π'), (0x1D780, 'M', 'ρ'), (0x1D781, 'M', 'σ'), (0x1D783, 'M', 'τ'), (0x1D784, 'M', 'υ'), (0x1D785, 'M', 'φ'), (0x1D786, 'M', 'χ'), (0x1D787, 'M', 'ψ'), (0x1D788, 'M', 'ω'), (0x1D789, 'M', '∂'), (0x1D78A, 'M', 'ε'), (0x1D78B, 'M', 'θ'), (0x1D78C, 'M', 'κ'), (0x1D78D, 'M', 'φ'), (0x1D78E, 'M', 'ρ'), (0x1D78F, 'M', 'π'), (0x1D790, 'M', 'α'), (0x1D791, 'M', 'β'), (0x1D792, 'M', 'γ'), (0x1D793, 'M', 'δ'), (0x1D794, 'M', 'ε'), (0x1D795, 'M', 'ζ'), (0x1D796, 'M', 'η'), (0x1D797, 'M', 'θ'), (0x1D798, 'M', 'ι'), (0x1D799, 'M', 'κ'), (0x1D79A, 'M', 'λ'), (0x1D79B, 'M', 'μ'), (0x1D79C, 'M', 'ν'), (0x1D79D, 'M', 'ξ'), (0x1D79E, 'M', 'ο'), (0x1D79F, 'M', 'π'), (0x1D7A0, 'M', 'ρ'), (0x1D7A1, 'M', 'θ'), (0x1D7A2, 'M', 'σ'), (0x1D7A3, 'M', 'τ'), (0x1D7A4, 'M', 'υ'), (0x1D7A5, 'M', 'φ'), (0x1D7A6, 'M', 'χ'), (0x1D7A7, 'M', 'ψ'), (0x1D7A8, 'M', 'ω'), (0x1D7A9, 'M', '∇'), (0x1D7AA, 'M', 'α'), (0x1D7AB, 'M', 'β'), (0x1D7AC, 'M', 'γ'), (0x1D7AD, 'M', 'δ'), (0x1D7AE, 'M', 'ε'), (0x1D7AF, 'M', 'ζ'), ] def _seg_70() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1D7B0, 'M', 'η'), (0x1D7B1, 'M', 'θ'), (0x1D7B2, 'M', 'ι'), (0x1D7B3, 'M', 'κ'), (0x1D7B4, 'M', 'λ'), (0x1D7B5, 'M', 'μ'), (0x1D7B6, 'M', 'ν'), (0x1D7B7, 'M', 'ξ'), (0x1D7B8, 'M', 'ο'), (0x1D7B9, 'M', 'π'), (0x1D7BA, 'M', 'ρ'), (0x1D7BB, 'M', 'σ'), (0x1D7BD, 'M', 'τ'), (0x1D7BE, 'M', 'υ'), (0x1D7BF, 'M', 'φ'), (0x1D7C0, 'M', 'χ'), (0x1D7C1, 'M', 'ψ'), (0x1D7C2, 'M', 'ω'), (0x1D7C3, 'M', '∂'), (0x1D7C4, 'M', 'ε'), (0x1D7C5, 'M', 'θ'), (0x1D7C6, 'M', 'κ'), (0x1D7C7, 'M', 'φ'), (0x1D7C8, 'M', 'ρ'), (0x1D7C9, 'M', 'π'), (0x1D7CA, 'M', 'ϝ'), (0x1D7CC, 'X'), (0x1D7CE, 'M', '0'), (0x1D7CF, 'M', '1'), (0x1D7D0, 'M', '2'), (0x1D7D1, 'M', '3'), (0x1D7D2, 'M', '4'), (0x1D7D3, 'M', '5'), (0x1D7D4, 'M', '6'), (0x1D7D5, 'M', '7'), (0x1D7D6, 'M', '8'), (0x1D7D7, 'M', '9'), (0x1D7D8, 'M', '0'), (0x1D7D9, 'M', '1'), (0x1D7DA, 'M', '2'), (0x1D7DB, 'M', '3'), (0x1D7DC, 'M', '4'), (0x1D7DD, 'M', '5'), (0x1D7DE, 'M', '6'), (0x1D7DF, 'M', '7'), (0x1D7E0, 'M', '8'), (0x1D7E1, 'M', '9'), (0x1D7E2, 'M', '0'), (0x1D7E3, 'M', '1'), (0x1D7E4, 'M', '2'), (0x1D7E5, 'M', '3'), (0x1D7E6, 'M', '4'), (0x1D7E7, 'M', '5'), (0x1D7E8, 'M', '6'), (0x1D7E9, 'M', '7'), (0x1D7EA, 'M', '8'), (0x1D7EB, 'M', '9'), (0x1D7EC, 'M', '0'), (0x1D7ED, 'M', '1'), (0x1D7EE, 'M', '2'), (0x1D7EF, 'M', '3'), (0x1D7F0, 'M', '4'), (0x1D7F1, 'M', '5'), (0x1D7F2, 'M', '6'), (0x1D7F3, 'M', '7'), (0x1D7F4, 'M', '8'), (0x1D7F5, 'M', '9'), (0x1D7F6, 'M', '0'), (0x1D7F7, 'M', '1'), (0x1D7F8, 'M', '2'), (0x1D7F9, 'M', '3'), (0x1D7FA, 'M', '4'), (0x1D7FB, 'M', '5'), (0x1D7FC, 'M', '6'), (0x1D7FD, 'M', '7'), (0x1D7FE, 'M', '8'), (0x1D7FF, 'M', '9'), (0x1D800, 'V'), (0x1DA8C, 'X'), (0x1DA9B, 'V'), (0x1DAA0, 'X'), (0x1DAA1, 'V'), (0x1DAB0, 'X'), (0x1DF00, 'V'), (0x1DF1F, 'X'), (0x1DF25, 'V'), (0x1DF2B, 'X'), (0x1E000, 'V'), (0x1E007, 'X'), (0x1E008, 'V'), (0x1E019, 'X'), (0x1E01B, 'V'), (0x1E022, 'X'), (0x1E023, 'V'), (0x1E025, 'X'), (0x1E026, 'V'), (0x1E02B, 'X'), (0x1E030, 'M', 'а'), (0x1E031, 'M', 'б'), (0x1E032, 'M', 'в'), ] def _seg_71() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1E033, 'M', 'г'), (0x1E034, 'M', 'д'), (0x1E035, 'M', 'е'), (0x1E036, 'M', 'ж'), (0x1E037, 'M', 'з'), (0x1E038, 'M', 'и'), (0x1E039, 'M', 'к'), (0x1E03A, 'M', 'л'), (0x1E03B, 'M', 'м'), (0x1E03C, 'M', 'о'), (0x1E03D, 'M', 'п'), (0x1E03E, 'M', 'р'), (0x1E03F, 'M', 'с'), (0x1E040, 'M', 'т'), (0x1E041, 'M', 'у'), (0x1E042, 'M', 'ф'), (0x1E043, 'M', 'х'), (0x1E044, 'M', 'ц'), (0x1E045, 'M', 'ч'), (0x1E046, 'M', 'ш'), (0x1E047, 'M', 'ы'), (0x1E048, 'M', 'э'), (0x1E049, 'M', 'ю'), (0x1E04A, 'M', 'ꚉ'), (0x1E04B, 'M', 'ә'), (0x1E04C, 'M', 'і'), (0x1E04D, 'M', 'ј'), (0x1E04E, 'M', 'ө'), (0x1E04F, 'M', 'ү'), (0x1E050, 'M', 'ӏ'), (0x1E051, 'M', 'а'), (0x1E052, 'M', 'б'), (0x1E053, 'M', 'в'), (0x1E054, 'M', 'г'), (0x1E055, 'M', 'д'), (0x1E056, 'M', 'е'), (0x1E057, 'M', 'ж'), (0x1E058, 'M', 'з'), (0x1E059, 'M', 'и'), (0x1E05A, 'M', 'к'), (0x1E05B, 'M', 'л'), (0x1E05C, 'M', 'о'), (0x1E05D, 'M', 'п'), (0x1E05E, 'M', 'с'), (0x1E05F, 'M', 'у'), (0x1E060, 'M', 'ф'), (0x1E061, 'M', 'х'), (0x1E062, 'M', 'ц'), (0x1E063, 'M', 'ч'), (0x1E064, 'M', 'ш'), (0x1E065, 'M', 'ъ'), (0x1E066, 'M', 'ы'), (0x1E067, 'M', 'ґ'), (0x1E068, 'M', 'і'), (0x1E069, 'M', 'ѕ'), (0x1E06A, 'M', 'џ'), (0x1E06B, 'M', 'ҫ'), (0x1E06C, 'M', 'ꙑ'), (0x1E06D, 'M', 'ұ'), (0x1E06E, 'X'), (0x1E08F, 'V'), (0x1E090, 'X'), (0x1E100, 'V'), (0x1E12D, 'X'), (0x1E130, 'V'), (0x1E13E, 'X'), (0x1E140, 'V'), (0x1E14A, 'X'), (0x1E14E, 'V'), (0x1E150, 'X'), (0x1E290, 'V'), (0x1E2AF, 'X'), (0x1E2C0, 'V'), (0x1E2FA, 'X'), (0x1E2FF, 'V'), (0x1E300, 'X'), (0x1E4D0, 'V'), (0x1E4FA, 'X'), (0x1E7E0, 'V'), (0x1E7E7, 'X'), (0x1E7E8, 'V'), (0x1E7EC, 'X'), (0x1E7ED, 'V'), (0x1E7EF, 'X'), (0x1E7F0, 'V'), (0x1E7FF, 'X'), (0x1E800, 'V'), (0x1E8C5, 'X'), (0x1E8C7, 'V'), (0x1E8D7, 'X'), (0x1E900, 'M', '𞤢'), (0x1E901, 'M', '𞤣'), (0x1E902, 'M', '𞤤'), (0x1E903, 'M', '𞤥'), (0x1E904, 'M', '𞤦'), (0x1E905, 'M', '𞤧'), (0x1E906, 'M', '𞤨'), (0x1E907, 'M', '𞤩'), (0x1E908, 'M', '𞤪'), (0x1E909, 'M', '𞤫'), ] def _seg_72() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1E90A, 'M', '𞤬'), (0x1E90B, 'M', '𞤭'), (0x1E90C, 'M', '𞤮'), (0x1E90D, 'M', '𞤯'), (0x1E90E, 'M', '𞤰'), (0x1E90F, 'M', '𞤱'), (0x1E910, 'M', '𞤲'), (0x1E911, 'M', '𞤳'), (0x1E912, 'M', '𞤴'), (0x1E913, 'M', '𞤵'), (0x1E914, 'M', '𞤶'), (0x1E915, 'M', '𞤷'), (0x1E916, 'M', '𞤸'), (0x1E917, 'M', '𞤹'), (0x1E918, 'M', '𞤺'), (0x1E919, 'M', '𞤻'), (0x1E91A, 'M', '𞤼'), (0x1E91B, 'M', '𞤽'), (0x1E91C, 'M', '𞤾'), (0x1E91D, 'M', '𞤿'), (0x1E91E, 'M', '𞥀'), (0x1E91F, 'M', '𞥁'), (0x1E920, 'M', '𞥂'), (0x1E921, 'M', '𞥃'), (0x1E922, 'V'), (0x1E94C, 'X'), (0x1E950, 'V'), (0x1E95A, 'X'), (0x1E95E, 'V'), (0x1E960, 'X'), (0x1EC71, 'V'), (0x1ECB5, 'X'), (0x1ED01, 'V'), (0x1ED3E, 'X'), (0x1EE00, 'M', 'ا'), (0x1EE01, 'M', 'ب'), (0x1EE02, 'M', 'ج'), (0x1EE03, 'M', 'د'), (0x1EE04, 'X'), (0x1EE05, 'M', 'و'), (0x1EE06, 'M', 'ز'), (0x1EE07, 'M', 'ح'), (0x1EE08, 'M', 'ط'), (0x1EE09, 'M', 'ي'), (0x1EE0A, 'M', 'ك'), (0x1EE0B, 'M', 'ل'), (0x1EE0C, 'M', 'م'), (0x1EE0D, 'M', 'ن'), (0x1EE0E, 'M', 'س'), (0x1EE0F, 'M', 'ع'), (0x1EE10, 'M', 'ف'), (0x1EE11, 'M', 'ص'), (0x1EE12, 'M', 'ق'), (0x1EE13, 'M', 'ر'), (0x1EE14, 'M', 'ش'), (0x1EE15, 'M', 'ت'), (0x1EE16, 'M', 'ث'), (0x1EE17, 'M', 'خ'), (0x1EE18, 'M', 'ذ'), (0x1EE19, 'M', 'ض'), (0x1EE1A, 'M', 'ظ'), (0x1EE1B, 'M', 'غ'), (0x1EE1C, 'M', 'ٮ'), (0x1EE1D, 'M', 'ں'), (0x1EE1E, 'M', 'ڡ'), (0x1EE1F, 'M', 'ٯ'), (0x1EE20, 'X'), (0x1EE21, 'M', 'ب'), (0x1EE22, 'M', 'ج'), (0x1EE23, 'X'), (0x1EE24, 'M', 'ه'), (0x1EE25, 'X'), (0x1EE27, 'M', 'ح'), (0x1EE28, 'X'), (0x1EE29, 'M', 'ي'), (0x1EE2A, 'M', 'ك'), (0x1EE2B, 'M', 'ل'), (0x1EE2C, 'M', 'م'), (0x1EE2D, 'M', 'ن'), (0x1EE2E, 'M', 'س'), (0x1EE2F, 'M', 'ع'), (0x1EE30, 'M', 'ف'), (0x1EE31, 'M', 'ص'), (0x1EE32, 'M', 'ق'), (0x1EE33, 'X'), (0x1EE34, 'M', 'ش'), (0x1EE35, 'M', 'ت'), (0x1EE36, 'M', 'ث'), (0x1EE37, 'M', 'خ'), (0x1EE38, 'X'), (0x1EE39, 'M', 'ض'), (0x1EE3A, 'X'), (0x1EE3B, 'M', 'غ'), (0x1EE3C, 'X'), (0x1EE42, 'M', 'ج'), (0x1EE43, 'X'), (0x1EE47, 'M', 'ح'), (0x1EE48, 'X'), (0x1EE49, 'M', 'ي'), (0x1EE4A, 'X'), ] def _seg_73() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1EE4B, 'M', 'ل'), (0x1EE4C, 'X'), (0x1EE4D, 'M', 'ن'), (0x1EE4E, 'M', 'س'), (0x1EE4F, 'M', 'ع'), (0x1EE50, 'X'), (0x1EE51, 'M', 'ص'), (0x1EE52, 'M', 'ق'), (0x1EE53, 'X'), (0x1EE54, 'M', 'ش'), (0x1EE55, 'X'), (0x1EE57, 'M', 'خ'), (0x1EE58, 'X'), (0x1EE59, 'M', 'ض'), (0x1EE5A, 'X'), (0x1EE5B, 'M', 'غ'), (0x1EE5C, 'X'), (0x1EE5D, 'M', 'ں'), (0x1EE5E, 'X'), (0x1EE5F, 'M', 'ٯ'), (0x1EE60, 'X'), (0x1EE61, 'M', 'ب'), (0x1EE62, 'M', 'ج'), (0x1EE63, 'X'), (0x1EE64, 'M', 'ه'), (0x1EE65, 'X'), (0x1EE67, 'M', 'ح'), (0x1EE68, 'M', 'ط'), (0x1EE69, 'M', 'ي'), (0x1EE6A, 'M', 'ك'), (0x1EE6B, 'X'), (0x1EE6C, 'M', 'م'), (0x1EE6D, 'M', 'ن'), (0x1EE6E, 'M', 'س'), (0x1EE6F, 'M', 'ع'), (0x1EE70, 'M', 'ف'), (0x1EE71, 'M', 'ص'), (0x1EE72, 'M', 'ق'), (0x1EE73, 'X'), (0x1EE74, 'M', 'ش'), (0x1EE75, 'M', 'ت'), (0x1EE76, 'M', 'ث'), (0x1EE77, 'M', 'خ'), (0x1EE78, 'X'), (0x1EE79, 'M', 'ض'), (0x1EE7A, 'M', 'ظ'), (0x1EE7B, 'M', 'غ'), (0x1EE7C, 'M', 'ٮ'), (0x1EE7D, 'X'), (0x1EE7E, 'M', 'ڡ'), (0x1EE7F, 'X'), (0x1EE80, 'M', 'ا'), (0x1EE81, 'M', 'ب'), (0x1EE82, 'M', 'ج'), (0x1EE83, 'M', 'د'), (0x1EE84, 'M', 'ه'), (0x1EE85, 'M', 'و'), (0x1EE86, 'M', 'ز'), (0x1EE87, 'M', 'ح'), (0x1EE88, 'M', 'ط'), (0x1EE89, 'M', 'ي'), (0x1EE8A, 'X'), (0x1EE8B, 'M', 'ل'), (0x1EE8C, 'M', 'م'), (0x1EE8D, 'M', 'ن'), (0x1EE8E, 'M', 'س'), (0x1EE8F, 'M', 'ع'), (0x1EE90, 'M', 'ف'), (0x1EE91, 'M', 'ص'), (0x1EE92, 'M', 'ق'), (0x1EE93, 'M', 'ر'), (0x1EE94, 'M', 'ش'), (0x1EE95, 'M', 'ت'), (0x1EE96, 'M', 'ث'), (0x1EE97, 'M', 'خ'), (0x1EE98, 'M', 'ذ'), (0x1EE99, 'M', 'ض'), (0x1EE9A, 'M', 'ظ'), (0x1EE9B, 'M', 'غ'), (0x1EE9C, 'X'), (0x1EEA1, 'M', 'ب'), (0x1EEA2, 'M', 'ج'), (0x1EEA3, 'M', 'د'), (0x1EEA4, 'X'), (0x1EEA5, 'M', 'و'), (0x1EEA6, 'M', 'ز'), (0x1EEA7, 'M', 'ح'), (0x1EEA8, 'M', 'ط'), (0x1EEA9, 'M', 'ي'), (0x1EEAA, 'X'), (0x1EEAB, 'M', 'ل'), (0x1EEAC, 'M', 'م'), (0x1EEAD, 'M', 'ن'), (0x1EEAE, 'M', 'س'), (0x1EEAF, 'M', 'ع'), (0x1EEB0, 'M', 'ف'), (0x1EEB1, 'M', 'ص'), (0x1EEB2, 'M', 'ق'), (0x1EEB3, 'M', 'ر'), (0x1EEB4, 'M', 'ش'), ] def _seg_74() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1EEB5, 'M', 'ت'), (0x1EEB6, 'M', 'ث'), (0x1EEB7, 'M', 'خ'), (0x1EEB8, 'M', 'ذ'), (0x1EEB9, 'M', 'ض'), (0x1EEBA, 'M', 'ظ'), (0x1EEBB, 'M', 'غ'), (0x1EEBC, 'X'), (0x1EEF0, 'V'), (0x1EEF2, 'X'), (0x1F000, 'V'), (0x1F02C, 'X'), (0x1F030, 'V'), (0x1F094, 'X'), (0x1F0A0, 'V'), (0x1F0AF, 'X'), (0x1F0B1, 'V'), (0x1F0C0, 'X'), (0x1F0C1, 'V'), (0x1F0D0, 'X'), (0x1F0D1, 'V'), (0x1F0F6, 'X'), (0x1F101, '3', '0,'), (0x1F102, '3', '1,'), (0x1F103, '3', '2,'), (0x1F104, '3', '3,'), (0x1F105, '3', '4,'), (0x1F106, '3', '5,'), (0x1F107, '3', '6,'), (0x1F108, '3', '7,'), (0x1F109, '3', '8,'), (0x1F10A, '3', '9,'), (0x1F10B, 'V'), (0x1F110, '3', '(a)'), (0x1F111, '3', '(b)'), (0x1F112, '3', '(c)'), (0x1F113, '3', '(d)'), (0x1F114, '3', '(e)'), (0x1F115, '3', '(f)'), (0x1F116, '3', '(g)'), (0x1F117, '3', '(h)'), (0x1F118, '3', '(i)'), (0x1F119, '3', '(j)'), (0x1F11A, '3', '(k)'), (0x1F11B, '3', '(l)'), (0x1F11C, '3', '(m)'), (0x1F11D, '3', '(n)'), (0x1F11E, '3', '(o)'), (0x1F11F, '3', '(p)'), (0x1F120, '3', '(q)'), (0x1F121, '3', '(r)'), (0x1F122, '3', '(s)'), (0x1F123, '3', '(t)'), (0x1F124, '3', '(u)'), (0x1F125, '3', '(v)'), (0x1F126, '3', '(w)'), (0x1F127, '3', '(x)'), (0x1F128, '3', '(y)'), (0x1F129, '3', '(z)'), (0x1F12A, 'M', '〔s〕'), (0x1F12B, 'M', 'c'), (0x1F12C, 'M', 'r'), (0x1F12D, 'M', 'cd'), (0x1F12E, 'M', 'wz'), (0x1F12F, 'V'), (0x1F130, 'M', 'a'), (0x1F131, 'M', 'b'), (0x1F132, 'M', 'c'), (0x1F133, 'M', 'd'), (0x1F134, 'M', 'e'), (0x1F135, 'M', 'f'), (0x1F136, 'M', 'g'), (0x1F137, 'M', 'h'), (0x1F138, 'M', 'i'), (0x1F139, 'M', 'j'), (0x1F13A, 'M', 'k'), (0x1F13B, 'M', 'l'), (0x1F13C, 'M', 'm'), (0x1F13D, 'M', 'n'), (0x1F13E, 'M', 'o'), (0x1F13F, 'M', 'p'), (0x1F140, 'M', 'q'), (0x1F141, 'M', 'r'), (0x1F142, 'M', 's'), (0x1F143, 'M', 't'), (0x1F144, 'M', 'u'), (0x1F145, 'M', 'v'), (0x1F146, 'M', 'w'), (0x1F147, 'M', 'x'), (0x1F148, 'M', 'y'), (0x1F149, 'M', 'z'), (0x1F14A, 'M', 'hv'), (0x1F14B, 'M', 'mv'), (0x1F14C, 'M', 'sd'), (0x1F14D, 'M', 'ss'), (0x1F14E, 'M', 'ppv'), (0x1F14F, 'M', 'wc'), (0x1F150, 'V'), (0x1F16A, 'M', 'mc'), (0x1F16B, 'M', 'md'), ] def _seg_75() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1F16C, 'M', 'mr'), (0x1F16D, 'V'), (0x1F190, 'M', 'dj'), (0x1F191, 'V'), (0x1F1AE, 'X'), (0x1F1E6, 'V'), (0x1F200, 'M', 'ほか'), (0x1F201, 'M', 'ココ'), (0x1F202, 'M', 'サ'), (0x1F203, 'X'), (0x1F210, 'M', '手'), (0x1F211, 'M', '字'), (0x1F212, 'M', '双'), (0x1F213, 'M', 'デ'), (0x1F214, 'M', '二'), (0x1F215, 'M', '多'), (0x1F216, 'M', '解'), (0x1F217, 'M', '天'), (0x1F218, 'M', '交'), (0x1F219, 'M', '映'), (0x1F21A, 'M', '無'), (0x1F21B, 'M', '料'), (0x1F21C, 'M', '前'), (0x1F21D, 'M', '後'), (0x1F21E, 'M', '再'), (0x1F21F, 'M', '新'), (0x1F220, 'M', '初'), (0x1F221, 'M', '終'), (0x1F222, 'M', '生'), (0x1F223, 'M', '販'), (0x1F224, 'M', '声'), (0x1F225, 'M', '吹'), (0x1F226, 'M', '演'), (0x1F227, 'M', '投'), (0x1F228, 'M', '捕'), (0x1F229, 'M', '一'), (0x1F22A, 'M', '三'), (0x1F22B, 'M', '遊'), (0x1F22C, 'M', '左'), (0x1F22D, 'M', '中'), (0x1F22E, 'M', '右'), (0x1F22F, 'M', '指'), (0x1F230, 'M', '走'), (0x1F231, 'M', '打'), (0x1F232, 'M', '禁'), (0x1F233, 'M', '空'), (0x1F234, 'M', '合'), (0x1F235, 'M', '満'), (0x1F236, 'M', '有'), (0x1F237, 'M', '月'), (0x1F238, 'M', '申'), (0x1F239, 'M', '割'), (0x1F23A, 'M', '営'), (0x1F23B, 'M', '配'), (0x1F23C, 'X'), (0x1F240, 'M', '〔本〕'), (0x1F241, 'M', '〔三〕'), (0x1F242, 'M', '〔二〕'), (0x1F243, 'M', '〔安〕'), (0x1F244, 'M', '〔点〕'), (0x1F245, 'M', '〔打〕'), (0x1F246, 'M', '〔盗〕'), (0x1F247, 'M', '〔勝〕'), (0x1F248, 'M', '〔敗〕'), (0x1F249, 'X'), (0x1F250, 'M', '得'), (0x1F251, 'M', '可'), (0x1F252, 'X'), (0x1F260, 'V'), (0x1F266, 'X'), (0x1F300, 'V'), (0x1F6D8, 'X'), (0x1F6DC, 'V'), (0x1F6ED, 'X'), (0x1F6F0, 'V'), (0x1F6FD, 'X'), (0x1F700, 'V'), (0x1F777, 'X'), (0x1F77B, 'V'), (0x1F7DA, 'X'), (0x1F7E0, 'V'), (0x1F7EC, 'X'), (0x1F7F0, 'V'), (0x1F7F1, 'X'), (0x1F800, 'V'), (0x1F80C, 'X'), (0x1F810, 'V'), (0x1F848, 'X'), (0x1F850, 'V'), (0x1F85A, 'X'), (0x1F860, 'V'), (0x1F888, 'X'), (0x1F890, 'V'), (0x1F8AE, 'X'), (0x1F8B0, 'V'), (0x1F8B2, 'X'), (0x1F900, 'V'), (0x1FA54, 'X'), (0x1FA60, 'V'), (0x1FA6E, 'X'), ] def _seg_76() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x1FA70, 'V'), (0x1FA7D, 'X'), (0x1FA80, 'V'), (0x1FA89, 'X'), (0x1FA90, 'V'), (0x1FABE, 'X'), (0x1FABF, 'V'), (0x1FAC6, 'X'), (0x1FACE, 'V'), (0x1FADC, 'X'), (0x1FAE0, 'V'), (0x1FAE9, 'X'), (0x1FAF0, 'V'), (0x1FAF9, 'X'), (0x1FB00, 'V'), (0x1FB93, 'X'), (0x1FB94, 'V'), (0x1FBCB, 'X'), (0x1FBF0, 'M', '0'), (0x1FBF1, 'M', '1'), (0x1FBF2, 'M', '2'), (0x1FBF3, 'M', '3'), (0x1FBF4, 'M', '4'), (0x1FBF5, 'M', '5'), (0x1FBF6, 'M', '6'), (0x1FBF7, 'M', '7'), (0x1FBF8, 'M', '8'), (0x1FBF9, 'M', '9'), (0x1FBFA, 'X'), (0x20000, 'V'), (0x2A6E0, 'X'), (0x2A700, 'V'), (0x2B73A, 'X'), (0x2B740, 'V'), (0x2B81E, 'X'), (0x2B820, 'V'), (0x2CEA2, 'X'), (0x2CEB0, 'V'), (0x2EBE1, 'X'), (0x2F800, 'M', '丽'), (0x2F801, 'M', '丸'), (0x2F802, 'M', '乁'), (0x2F803, 'M', '𠄢'), (0x2F804, 'M', '你'), (0x2F805, 'M', '侮'), (0x2F806, 'M', '侻'), (0x2F807, 'M', '倂'), (0x2F808, 'M', '偺'), (0x2F809, 'M', '備'), (0x2F80A, 'M', '僧'), (0x2F80B, 'M', '像'), (0x2F80C, 'M', '㒞'), (0x2F80D, 'M', '𠘺'), (0x2F80E, 'M', '免'), (0x2F80F, 'M', '兔'), (0x2F810, 'M', '兤'), (0x2F811, 'M', '具'), (0x2F812, 'M', '𠔜'), (0x2F813, 'M', '㒹'), (0x2F814, 'M', '內'), (0x2F815, 'M', '再'), (0x2F816, 'M', '𠕋'), (0x2F817, 'M', '冗'), (0x2F818, 'M', '冤'), (0x2F819, 'M', '仌'), (0x2F81A, 'M', '冬'), (0x2F81B, 'M', '况'), (0x2F81C, 'M', '𩇟'), (0x2F81D, 'M', '凵'), (0x2F81E, 'M', '刃'), (0x2F81F, 'M', '㓟'), (0x2F820, 'M', '刻'), (0x2F821, 'M', '剆'), (0x2F822, 'M', '割'), (0x2F823, 'M', '剷'), (0x2F824, 'M', '㔕'), (0x2F825, 'M', '勇'), (0x2F826, 'M', '勉'), (0x2F827, 'M', '勤'), (0x2F828, 'M', '勺'), (0x2F829, 'M', '包'), (0x2F82A, 'M', '匆'), (0x2F82B, 'M', '北'), (0x2F82C, 'M', '卉'), (0x2F82D, 'M', '卑'), (0x2F82E, 'M', '博'), (0x2F82F, 'M', '即'), (0x2F830, 'M', '卽'), (0x2F831, 'M', '卿'), (0x2F834, 'M', '𠨬'), (0x2F835, 'M', '灰'), (0x2F836, 'M', '及'), (0x2F837, 'M', '叟'), (0x2F838, 'M', '𠭣'), (0x2F839, 'M', '叫'), (0x2F83A, 'M', '叱'), (0x2F83B, 'M', '吆'), (0x2F83C, 'M', '咞'), (0x2F83D, 'M', '吸'), (0x2F83E, 'M', '呈'), ] def _seg_77() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2F83F, 'M', '周'), (0x2F840, 'M', '咢'), (0x2F841, 'M', '哶'), (0x2F842, 'M', '唐'), (0x2F843, 'M', '啓'), (0x2F844, 'M', '啣'), (0x2F845, 'M', '善'), (0x2F847, 'M', '喙'), (0x2F848, 'M', '喫'), (0x2F849, 'M', '喳'), (0x2F84A, 'M', '嗂'), (0x2F84B, 'M', '圖'), (0x2F84C, 'M', '嘆'), (0x2F84D, 'M', '圗'), (0x2F84E, 'M', '噑'), (0x2F84F, 'M', '噴'), (0x2F850, 'M', '切'), (0x2F851, 'M', '壮'), (0x2F852, 'M', '城'), (0x2F853, 'M', '埴'), (0x2F854, 'M', '堍'), (0x2F855, 'M', '型'), (0x2F856, 'M', '堲'), (0x2F857, 'M', '報'), (0x2F858, 'M', '墬'), (0x2F859, 'M', '𡓤'), (0x2F85A, 'M', '売'), (0x2F85B, 'M', '壷'), (0x2F85C, 'M', '夆'), (0x2F85D, 'M', '多'), (0x2F85E, 'M', '夢'), (0x2F85F, 'M', '奢'), (0x2F860, 'M', '𡚨'), (0x2F861, 'M', '𡛪'), (0x2F862, 'M', '姬'), (0x2F863, 'M', '娛'), (0x2F864, 'M', '娧'), (0x2F865, 'M', '姘'), (0x2F866, 'M', '婦'), (0x2F867, 'M', '㛮'), (0x2F868, 'X'), (0x2F869, 'M', '嬈'), (0x2F86A, 'M', '嬾'), (0x2F86C, 'M', '𡧈'), (0x2F86D, 'M', '寃'), (0x2F86E, 'M', '寘'), (0x2F86F, 'M', '寧'), (0x2F870, 'M', '寳'), (0x2F871, 'M', '𡬘'), (0x2F872, 'M', '寿'), (0x2F873, 'M', '将'), (0x2F874, 'X'), (0x2F875, 'M', '尢'), (0x2F876, 'M', '㞁'), (0x2F877, 'M', '屠'), (0x2F878, 'M', '屮'), (0x2F879, 'M', '峀'), (0x2F87A, 'M', '岍'), (0x2F87B, 'M', '𡷤'), (0x2F87C, 'M', '嵃'), (0x2F87D, 'M', '𡷦'), (0x2F87E, 'M', '嵮'), (0x2F87F, 'M', '嵫'), (0x2F880, 'M', '嵼'), (0x2F881, 'M', '巡'), (0x2F882, 'M', '巢'), (0x2F883, 'M', '㠯'), (0x2F884, 'M', '巽'), (0x2F885, 'M', '帨'), (0x2F886, 'M', '帽'), (0x2F887, 'M', '幩'), (0x2F888, 'M', '㡢'), (0x2F889, 'M', '𢆃'), (0x2F88A, 'M', '㡼'), (0x2F88B, 'M', '庰'), (0x2F88C, 'M', '庳'), (0x2F88D, 'M', '庶'), (0x2F88E, 'M', '廊'), (0x2F88F, 'M', '𪎒'), (0x2F890, 'M', '廾'), (0x2F891, 'M', '𢌱'), (0x2F893, 'M', '舁'), (0x2F894, 'M', '弢'), (0x2F896, 'M', '㣇'), (0x2F897, 'M', '𣊸'), (0x2F898, 'M', '𦇚'), (0x2F899, 'M', '形'), (0x2F89A, 'M', '彫'), (0x2F89B, 'M', '㣣'), (0x2F89C, 'M', '徚'), (0x2F89D, 'M', '忍'), (0x2F89E, 'M', '志'), (0x2F89F, 'M', '忹'), (0x2F8A0, 'M', '悁'), (0x2F8A1, 'M', '㤺'), (0x2F8A2, 'M', '㤜'), (0x2F8A3, 'M', '悔'), (0x2F8A4, 'M', '𢛔'), (0x2F8A5, 'M', '惇'), (0x2F8A6, 'M', '慈'), ] def _seg_78() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2F8A7, 'M', '慌'), (0x2F8A8, 'M', '慎'), (0x2F8A9, 'M', '慌'), (0x2F8AA, 'M', '慺'), (0x2F8AB, 'M', '憎'), (0x2F8AC, 'M', '憲'), (0x2F8AD, 'M', '憤'), (0x2F8AE, 'M', '憯'), (0x2F8AF, 'M', '懞'), (0x2F8B0, 'M', '懲'), (0x2F8B1, 'M', '懶'), (0x2F8B2, 'M', '成'), (0x2F8B3, 'M', '戛'), (0x2F8B4, 'M', '扝'), (0x2F8B5, 'M', '抱'), (0x2F8B6, 'M', '拔'), (0x2F8B7, 'M', '捐'), (0x2F8B8, 'M', '𢬌'), (0x2F8B9, 'M', '挽'), (0x2F8BA, 'M', '拼'), (0x2F8BB, 'M', '捨'), (0x2F8BC, 'M', '掃'), (0x2F8BD, 'M', '揤'), (0x2F8BE, 'M', '𢯱'), (0x2F8BF, 'M', '搢'), (0x2F8C0, 'M', '揅'), (0x2F8C1, 'M', '掩'), (0x2F8C2, 'M', '㨮'), (0x2F8C3, 'M', '摩'), (0x2F8C4, 'M', '摾'), (0x2F8C5, 'M', '撝'), (0x2F8C6, 'M', '摷'), (0x2F8C7, 'M', '㩬'), (0x2F8C8, 'M', '敏'), (0x2F8C9, 'M', '敬'), (0x2F8CA, 'M', '𣀊'), (0x2F8CB, 'M', '旣'), (0x2F8CC, 'M', '書'), (0x2F8CD, 'M', '晉'), (0x2F8CE, 'M', '㬙'), (0x2F8CF, 'M', '暑'), (0x2F8D0, 'M', '㬈'), (0x2F8D1, 'M', '㫤'), (0x2F8D2, 'M', '冒'), (0x2F8D3, 'M', '冕'), (0x2F8D4, 'M', '最'), (0x2F8D5, 'M', '暜'), (0x2F8D6, 'M', '肭'), (0x2F8D7, 'M', '䏙'), (0x2F8D8, 'M', '朗'), (0x2F8D9, 'M', '望'), (0x2F8DA, 'M', '朡'), (0x2F8DB, 'M', '杞'), (0x2F8DC, 'M', '杓'), (0x2F8DD, 'M', '𣏃'), (0x2F8DE, 'M', '㭉'), (0x2F8DF, 'M', '柺'), (0x2F8E0, 'M', '枅'), (0x2F8E1, 'M', '桒'), (0x2F8E2, 'M', '梅'), (0x2F8E3, 'M', '𣑭'), (0x2F8E4, 'M', '梎'), (0x2F8E5, 'M', '栟'), (0x2F8E6, 'M', '椔'), (0x2F8E7, 'M', '㮝'), (0x2F8E8, 'M', '楂'), (0x2F8E9, 'M', '榣'), (0x2F8EA, 'M', '槪'), (0x2F8EB, 'M', '檨'), (0x2F8EC, 'M', '𣚣'), (0x2F8ED, 'M', '櫛'), (0x2F8EE, 'M', '㰘'), (0x2F8EF, 'M', '次'), (0x2F8F0, 'M', '𣢧'), (0x2F8F1, 'M', '歔'), (0x2F8F2, 'M', '㱎'), (0x2F8F3, 'M', '歲'), (0x2F8F4, 'M', '殟'), (0x2F8F5, 'M', '殺'), (0x2F8F6, 'M', '殻'), (0x2F8F7, 'M', '𣪍'), (0x2F8F8, 'M', '𡴋'), (0x2F8F9, 'M', '𣫺'), (0x2F8FA, 'M', '汎'), (0x2F8FB, 'M', '𣲼'), (0x2F8FC, 'M', '沿'), (0x2F8FD, 'M', '泍'), (0x2F8FE, 'M', '汧'), (0x2F8FF, 'M', '洖'), (0x2F900, 'M', '派'), (0x2F901, 'M', '海'), (0x2F902, 'M', '流'), (0x2F903, 'M', '浩'), (0x2F904, 'M', '浸'), (0x2F905, 'M', '涅'), (0x2F906, 'M', '𣴞'), (0x2F907, 'M', '洴'), (0x2F908, 'M', '港'), (0x2F909, 'M', '湮'), (0x2F90A, 'M', '㴳'), ] def _seg_79() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2F90B, 'M', '滋'), (0x2F90C, 'M', '滇'), (0x2F90D, 'M', '𣻑'), (0x2F90E, 'M', '淹'), (0x2F90F, 'M', '潮'), (0x2F910, 'M', '𣽞'), (0x2F911, 'M', '𣾎'), (0x2F912, 'M', '濆'), (0x2F913, 'M', '瀹'), (0x2F914, 'M', '瀞'), (0x2F915, 'M', '瀛'), (0x2F916, 'M', '㶖'), (0x2F917, 'M', '灊'), (0x2F918, 'M', '災'), (0x2F919, 'M', '灷'), (0x2F91A, 'M', '炭'), (0x2F91B, 'M', '𠔥'), (0x2F91C, 'M', '煅'), (0x2F91D, 'M', '𤉣'), (0x2F91E, 'M', '熜'), (0x2F91F, 'X'), (0x2F920, 'M', '爨'), (0x2F921, 'M', '爵'), (0x2F922, 'M', '牐'), (0x2F923, 'M', '𤘈'), (0x2F924, 'M', '犀'), (0x2F925, 'M', '犕'), (0x2F926, 'M', '𤜵'), (0x2F927, 'M', '𤠔'), (0x2F928, 'M', '獺'), (0x2F929, 'M', '王'), (0x2F92A, 'M', '㺬'), (0x2F92B, 'M', '玥'), (0x2F92C, 'M', '㺸'), (0x2F92E, 'M', '瑇'), (0x2F92F, 'M', '瑜'), (0x2F930, 'M', '瑱'), (0x2F931, 'M', '璅'), (0x2F932, 'M', '瓊'), (0x2F933, 'M', '㼛'), (0x2F934, 'M', '甤'), (0x2F935, 'M', '𤰶'), (0x2F936, 'M', '甾'), (0x2F937, 'M', '𤲒'), (0x2F938, 'M', '異'), (0x2F939, 'M', '𢆟'), (0x2F93A, 'M', '瘐'), (0x2F93B, 'M', '𤾡'), (0x2F93C, 'M', '𤾸'), (0x2F93D, 'M', '𥁄'), (0x2F93E, 'M', '㿼'), (0x2F93F, 'M', '䀈'), (0x2F940, 'M', '直'), (0x2F941, 'M', '𥃳'), (0x2F942, 'M', '𥃲'), (0x2F943, 'M', '𥄙'), (0x2F944, 'M', '𥄳'), (0x2F945, 'M', '眞'), (0x2F946, 'M', '真'), (0x2F948, 'M', '睊'), (0x2F949, 'M', '䀹'), (0x2F94A, 'M', '瞋'), (0x2F94B, 'M', '䁆'), (0x2F94C, 'M', '䂖'), (0x2F94D, 'M', '𥐝'), (0x2F94E, 'M', '硎'), (0x2F94F, 'M', '碌'), (0x2F950, 'M', '磌'), (0x2F951, 'M', '䃣'), (0x2F952, 'M', '𥘦'), (0x2F953, 'M', '祖'), (0x2F954, 'M', '𥚚'), (0x2F955, 'M', '𥛅'), (0x2F956, 'M', '福'), (0x2F957, 'M', '秫'), (0x2F958, 'M', '䄯'), (0x2F959, 'M', '穀'), (0x2F95A, 'M', '穊'), (0x2F95B, 'M', '穏'), (0x2F95C, 'M', '𥥼'), (0x2F95D, 'M', '𥪧'), (0x2F95F, 'X'), (0x2F960, 'M', '䈂'), (0x2F961, 'M', '𥮫'), (0x2F962, 'M', '篆'), (0x2F963, 'M', '築'), (0x2F964, 'M', '䈧'), (0x2F965, 'M', '𥲀'), (0x2F966, 'M', '糒'), (0x2F967, 'M', '䊠'), (0x2F968, 'M', '糨'), (0x2F969, 'M', '糣'), (0x2F96A, 'M', '紀'), (0x2F96B, 'M', '𥾆'), (0x2F96C, 'M', '絣'), (0x2F96D, 'M', '䌁'), (0x2F96E, 'M', '緇'), (0x2F96F, 'M', '縂'), (0x2F970, 'M', '繅'), (0x2F971, 'M', '䌴'), ] def _seg_80() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2F972, 'M', '𦈨'), (0x2F973, 'M', '𦉇'), (0x2F974, 'M', '䍙'), (0x2F975, 'M', '𦋙'), (0x2F976, 'M', '罺'), (0x2F977, 'M', '𦌾'), (0x2F978, 'M', '羕'), (0x2F979, 'M', '翺'), (0x2F97A, 'M', '者'), (0x2F97B, 'M', '𦓚'), (0x2F97C, 'M', '𦔣'), (0x2F97D, 'M', '聠'), (0x2F97E, 'M', '𦖨'), (0x2F97F, 'M', '聰'), (0x2F980, 'M', '𣍟'), (0x2F981, 'M', '䏕'), (0x2F982, 'M', '育'), (0x2F983, 'M', '脃'), (0x2F984, 'M', '䐋'), (0x2F985, 'M', '脾'), (0x2F986, 'M', '媵'), (0x2F987, 'M', '𦞧'), (0x2F988, 'M', '𦞵'), (0x2F989, 'M', '𣎓'), (0x2F98A, 'M', '𣎜'), (0x2F98B, 'M', '舁'), (0x2F98C, 'M', '舄'), (0x2F98D, 'M', '辞'), (0x2F98E, 'M', '䑫'), (0x2F98F, 'M', '芑'), (0x2F990, 'M', '芋'), (0x2F991, 'M', '芝'), (0x2F992, 'M', '劳'), (0x2F993, 'M', '花'), (0x2F994, 'M', '芳'), (0x2F995, 'M', '芽'), (0x2F996, 'M', '苦'), (0x2F997, 'M', '𦬼'), (0x2F998, 'M', '若'), (0x2F999, 'M', '茝'), (0x2F99A, 'M', '荣'), (0x2F99B, 'M', '莭'), (0x2F99C, 'M', '茣'), (0x2F99D, 'M', '莽'), (0x2F99E, 'M', '菧'), (0x2F99F, 'M', '著'), (0x2F9A0, 'M', '荓'), (0x2F9A1, 'M', '菊'), (0x2F9A2, 'M', '菌'), (0x2F9A3, 'M', '菜'), (0x2F9A4, 'M', '𦰶'), (0x2F9A5, 'M', '𦵫'), (0x2F9A6, 'M', '𦳕'), (0x2F9A7, 'M', '䔫'), (0x2F9A8, 'M', '蓱'), (0x2F9A9, 'M', '蓳'), (0x2F9AA, 'M', '蔖'), (0x2F9AB, 'M', '𧏊'), (0x2F9AC, 'M', '蕤'), (0x2F9AD, 'M', '𦼬'), (0x2F9AE, 'M', '䕝'), (0x2F9AF, 'M', '䕡'), (0x2F9B0, 'M', '𦾱'), (0x2F9B1, 'M', '𧃒'), (0x2F9B2, 'M', '䕫'), (0x2F9B3, 'M', '虐'), (0x2F9B4, 'M', '虜'), (0x2F9B5, 'M', '虧'), (0x2F9B6, 'M', '虩'), (0x2F9B7, 'M', '蚩'), (0x2F9B8, 'M', '蚈'), (0x2F9B9, 'M', '蜎'), (0x2F9BA, 'M', '蛢'), (0x2F9BB, 'M', '蝹'), (0x2F9BC, 'M', '蜨'), (0x2F9BD, 'M', '蝫'), (0x2F9BE, 'M', '螆'), (0x2F9BF, 'X'), (0x2F9C0, 'M', '蟡'), (0x2F9C1, 'M', '蠁'), (0x2F9C2, 'M', '䗹'), (0x2F9C3, 'M', '衠'), (0x2F9C4, 'M', '衣'), (0x2F9C5, 'M', '𧙧'), (0x2F9C6, 'M', '裗'), (0x2F9C7, 'M', '裞'), (0x2F9C8, 'M', '䘵'), (0x2F9C9, 'M', '裺'), (0x2F9CA, 'M', '㒻'), (0x2F9CB, 'M', '𧢮'), (0x2F9CC, 'M', '𧥦'), (0x2F9CD, 'M', '䚾'), (0x2F9CE, 'M', '䛇'), (0x2F9CF, 'M', '誠'), (0x2F9D0, 'M', '諭'), (0x2F9D1, 'M', '變'), (0x2F9D2, 'M', '豕'), (0x2F9D3, 'M', '𧲨'), (0x2F9D4, 'M', '貫'), (0x2F9D5, 'M', '賁'), ] def _seg_81() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]: return [ (0x2F9D6, 'M', '贛'), (0x2F9D7, 'M', '起'), (0x2F9D8, 'M', '𧼯'), (0x2F9D9, 'M', '𠠄'), (0x2F9DA, 'M', '跋'), (0x2F9DB, 'M', '趼'), (0x2F9DC, 'M', '跰'), (0x2F9DD, 'M', '𠣞'), (0x2F9DE, 'M', '軔'), (0x2F9DF, 'M', '輸'), (0x2F9E0, 'M', '𨗒'), (0x2F9E1, 'M', '𨗭'), (0x2F9E2, 'M', '邔'), (0x2F9E3, 'M', '郱'), (0x2F9E4, 'M', '鄑'), (0x2F9E5, 'M', '𨜮'), (0x2F9E6, 'M', '鄛'), (0x2F9E7, 'M', '鈸'), (0x2F9E8, 'M', '鋗'), (0x2F9E9, 'M', '鋘'), (0x2F9EA, 'M', '鉼'), (0x2F9EB, 'M', '鏹'), (0x2F9EC, 'M', '鐕'), (0x2F9ED, 'M', '𨯺'), (0x2F9EE, 'M', '開'), (0x2F9EF, 'M', '䦕'), (0x2F9F0, 'M', '閷'), (0x2F9F1, 'M', '𨵷'), (0x2F9F2, 'M', '䧦'), (0x2F9F3, 'M', '雃'), (0x2F9F4, 'M', '嶲'), (0x2F9F5, 'M', '霣'), (0x2F9F6, 'M', '𩅅'), (0x2F9F7, 'M', '𩈚'), (0x2F9F8, 'M', '䩮'), (0x2F9F9, 'M', '䩶'), (0x2F9FA, 'M', '韠'), (0x2F9FB, 'M', '𩐊'), (0x2F9FC, 'M', '䪲'), (0x2F9FD, 'M', '𩒖'), (0x2F9FE, 'M', '頋'), (0x2FA00, 'M', '頩'), (0x2FA01, 'M', '𩖶'), (0x2FA02, 'M', '飢'), (0x2FA03, 'M', '䬳'), (0x2FA04, 'M', '餩'), (0x2FA05, 'M', '馧'), (0x2FA06, 'M', '駂'), (0x2FA07, 'M', '駾'), (0x2FA08, 'M', '䯎'), (0x2FA09, 'M', '𩬰'), (0x2FA0A, 'M', '鬒'), (0x2FA0B, 'M', '鱀'), (0x2FA0C, 'M', '鳽'), (0x2FA0D, 'M', '䳎'), (0x2FA0E, 'M', '䳭'), (0x2FA0F, 'M', '鵧'), (0x2FA10, 'M', '𪃎'), (0x2FA11, 'M', '䳸'), (0x2FA12, 'M', '𪄅'), (0x2FA13, 'M', '𪈎'), (0x2FA14, 'M', '𪊑'), (0x2FA15, 'M', '麻'), (0x2FA16, 'M', '䵖'), (0x2FA17, 'M', '黹'), (0x2FA18, 'M', '黾'), (0x2FA19, 'M', '鼅'), (0x2FA1A, 'M', '鼏'), (0x2FA1B, 'M', '鼖'), (0x2FA1C, 'M', '鼻'), (0x2FA1D, 'M', '𪘀'), (0x2FA1E, 'X'), (0x30000, 'V'), (0x3134B, 'X'), (0x31350, 'V'), (0x323B0, 'X'), (0xE0100, 'I'), (0xE01F0, 'X'), ] uts46data = tuple( _seg_0() + _seg_1() + _seg_2() + _seg_3() + _seg_4() + _seg_5() + _seg_6() + _seg_7() + _seg_8() + _seg_9() + _seg_10() + _seg_11() + _seg_12() + _seg_13() + _seg_14() + _seg_15() + _seg_16() + _seg_17() + _seg_18() + _seg_19() + _seg_20() + _seg_21() + _seg_22() + _seg_23() + _seg_24() + _seg_25() + _seg_26() + _seg_27() + _seg_28() + _seg_29() + _seg_30() + _seg_31() + _seg_32() + _seg_33() + _seg_34() + _seg_35() + _seg_36() + _seg_37() + _seg_38() + _seg_39() + _seg_40() + _seg_41() + _seg_42() + _seg_43() + _seg_44() + _seg_45() + _seg_46() + _seg_47() + _seg_48() + _seg_49() + _seg_50() + _seg_51() + _seg_52() + _seg_53() + _seg_54() + _seg_55() + _seg_56() + _seg_57() + _seg_58() + _seg_59() + _seg_60() + _seg_61() + _seg_62() + _seg_63() + _seg_64() + _seg_65() + _seg_66() + _seg_67() + _seg_68() + _seg_69() + _seg_70() + _seg_71() + _seg_72() + _seg_73() + _seg_74() + _seg_75() + _seg_76() + _seg_77() + _seg_78() + _seg_79() + _seg_80() + _seg_81() ) # type: Tuple[Union[Tuple[int, str], Tuple[int, str, str]], ...]
197,261
Python
21.934775
68
0.354708
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/idna/compat.py
from .core import * from .codec import * from typing import Any, Union def ToASCII(label: str) -> bytes: return encode(label) def ToUnicode(label: Union[bytes, bytearray]) -> str: return decode(label) def nameprep(s: Any) -> None: raise NotImplementedError('IDNA 2008 does not utilise nameprep protocol')
321
Python
21.999998
77
0.716511
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/envelope.py
import io import json import mimetypes from sentry_sdk._compat import text_type, PY2 from sentry_sdk._types import MYPY from sentry_sdk.session import Session from sentry_sdk.utils import json_dumps, capture_internal_exceptions if MYPY: from typing import Any from typing import Optional from typing import Union from typing import Dict from typing import List from typing import Iterator from sentry_sdk._types import Event, EventDataCategory def parse_json(data): # type: (Union[bytes, text_type]) -> Any # on some python 3 versions this needs to be bytes if not PY2 and isinstance(data, bytes): data = data.decode("utf-8", "replace") return json.loads(data) class Envelope(object): def __init__( self, headers=None, # type: Optional[Dict[str, Any]] items=None, # type: Optional[List[Item]] ): # type: (...) -> None if headers is not None: headers = dict(headers) self.headers = headers or {} if items is None: items = [] else: items = list(items) self.items = items @property def description(self): # type: (...) -> str return "envelope with %s items (%s)" % ( len(self.items), ", ".join(x.data_category for x in self.items), ) def add_event( self, event # type: Event ): # type: (...) -> None self.add_item(Item(payload=PayloadRef(json=event), type="event")) def add_transaction( self, transaction # type: Event ): # type: (...) -> None self.add_item(Item(payload=PayloadRef(json=transaction), type="transaction")) def add_profile( self, profile # type: Any ): # type: (...) -> None self.add_item(Item(payload=PayloadRef(json=profile), type="profile")) def add_session( self, session # type: Union[Session, Any] ): # type: (...) -> None if isinstance(session, Session): session = session.to_json() self.add_item(Item(payload=PayloadRef(json=session), type="session")) def add_sessions( self, sessions # type: Any ): # type: (...) -> None self.add_item(Item(payload=PayloadRef(json=sessions), type="sessions")) def add_item( self, item # type: Item ): # type: (...) -> None self.items.append(item) def get_event(self): # type: (...) -> Optional[Event] for items in self.items: event = items.get_event() if event is not None: return event return None def get_transaction_event(self): # type: (...) -> Optional[Event] for item in self.items: event = item.get_transaction_event() if event is not None: return event return None def __iter__(self): # type: (...) -> Iterator[Item] return iter(self.items) def serialize_into( self, f # type: Any ): # type: (...) -> None f.write(json_dumps(self.headers)) f.write(b"\n") for item in self.items: item.serialize_into(f) def serialize(self): # type: (...) -> bytes out = io.BytesIO() self.serialize_into(out) return out.getvalue() @classmethod def deserialize_from( cls, f # type: Any ): # type: (...) -> Envelope headers = parse_json(f.readline()) items = [] while 1: item = Item.deserialize_from(f) if item is None: break items.append(item) return cls(headers=headers, items=items) @classmethod def deserialize( cls, bytes # type: bytes ): # type: (...) -> Envelope return cls.deserialize_from(io.BytesIO(bytes)) def __repr__(self): # type: (...) -> str return "<Envelope headers=%r items=%r>" % (self.headers, self.items) class PayloadRef(object): def __init__( self, bytes=None, # type: Optional[bytes] path=None, # type: Optional[Union[bytes, text_type]] json=None, # type: Optional[Any] ): # type: (...) -> None self.json = json self.bytes = bytes self.path = path def get_bytes(self): # type: (...) -> bytes if self.bytes is None: if self.path is not None: with capture_internal_exceptions(): with open(self.path, "rb") as f: self.bytes = f.read() elif self.json is not None: self.bytes = json_dumps(self.json) else: self.bytes = b"" return self.bytes @property def inferred_content_type(self): # type: (...) -> str if self.json is not None: return "application/json" elif self.path is not None: path = self.path if isinstance(path, bytes): path = path.decode("utf-8", "replace") ty = mimetypes.guess_type(path)[0] if ty: return ty return "application/octet-stream" def __repr__(self): # type: (...) -> str return "<Payload %r>" % (self.inferred_content_type,) class Item(object): def __init__( self, payload, # type: Union[bytes, text_type, PayloadRef] headers=None, # type: Optional[Dict[str, Any]] type=None, # type: Optional[str] content_type=None, # type: Optional[str] filename=None, # type: Optional[str] ): if headers is not None: headers = dict(headers) elif headers is None: headers = {} self.headers = headers if isinstance(payload, bytes): payload = PayloadRef(bytes=payload) elif isinstance(payload, text_type): payload = PayloadRef(bytes=payload.encode("utf-8")) else: payload = payload if filename is not None: headers["filename"] = filename if type is not None: headers["type"] = type if content_type is not None: headers["content_type"] = content_type elif "content_type" not in headers: headers["content_type"] = payload.inferred_content_type self.payload = payload def __repr__(self): # type: (...) -> str return "<Item headers=%r payload=%r data_category=%r>" % ( self.headers, self.payload, self.data_category, ) @property def type(self): # type: (...) -> Optional[str] return self.headers.get("type") @property def data_category(self): # type: (...) -> EventDataCategory ty = self.headers.get("type") if ty == "session": return "session" elif ty == "attachment": return "attachment" elif ty == "transaction": return "transaction" elif ty == "event": return "error" elif ty == "client_report": return "internal" elif ty == "profile": return "profile" else: return "default" def get_bytes(self): # type: (...) -> bytes return self.payload.get_bytes() def get_event(self): # type: (...) -> Optional[Event] """ Returns an error event if there is one. """ if self.type == "event" and self.payload.json is not None: return self.payload.json return None def get_transaction_event(self): # type: (...) -> Optional[Event] if self.type == "transaction" and self.payload.json is not None: return self.payload.json return None def serialize_into( self, f # type: Any ): # type: (...) -> None headers = dict(self.headers) bytes = self.get_bytes() headers["length"] = len(bytes) f.write(json_dumps(headers)) f.write(b"\n") f.write(bytes) f.write(b"\n") def serialize(self): # type: (...) -> bytes out = io.BytesIO() self.serialize_into(out) return out.getvalue() @classmethod def deserialize_from( cls, f # type: Any ): # type: (...) -> Optional[Item] line = f.readline().rstrip() if not line: return None headers = parse_json(line) length = headers.get("length") if length is not None: payload = f.read(length) f.readline() else: # if no length was specified we need to read up to the end of line # and remove it (if it is present, i.e. not the very last char in an eof terminated envelope) payload = f.readline().rstrip(b"\n") if headers.get("type") in ("event", "transaction", "metric_buckets"): rv = cls(headers=headers, payload=PayloadRef(json=parse_json(payload))) else: rv = cls(headers=headers, payload=payload) return rv @classmethod def deserialize( cls, bytes # type: bytes ): # type: (...) -> Optional[Item] return cls.deserialize_from(io.BytesIO(bytes))
9,400
Python
27.837423
105
0.528936
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/tracing.py
import uuid import random import threading import time from datetime import datetime, timedelta import sentry_sdk from sentry_sdk.consts import INSTRUMENTER from sentry_sdk.utils import logger from sentry_sdk._types import MYPY if MYPY: import typing from typing import Optional from typing import Any from typing import Dict from typing import List from typing import Tuple from typing import Iterator import sentry_sdk.profiler from sentry_sdk._types import Event, SamplingContext, MeasurementUnit BAGGAGE_HEADER_NAME = "baggage" SENTRY_TRACE_HEADER_NAME = "sentry-trace" # Transaction source # see https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations TRANSACTION_SOURCE_CUSTOM = "custom" TRANSACTION_SOURCE_URL = "url" TRANSACTION_SOURCE_ROUTE = "route" TRANSACTION_SOURCE_VIEW = "view" TRANSACTION_SOURCE_COMPONENT = "component" TRANSACTION_SOURCE_TASK = "task" # These are typically high cardinality and the server hates them LOW_QUALITY_TRANSACTION_SOURCES = [ TRANSACTION_SOURCE_URL, ] SOURCE_FOR_STYLE = { "endpoint": TRANSACTION_SOURCE_COMPONENT, "function_name": TRANSACTION_SOURCE_COMPONENT, "handler_name": TRANSACTION_SOURCE_COMPONENT, "method_and_path_pattern": TRANSACTION_SOURCE_ROUTE, "path": TRANSACTION_SOURCE_URL, "route_name": TRANSACTION_SOURCE_COMPONENT, "route_pattern": TRANSACTION_SOURCE_ROUTE, "uri_template": TRANSACTION_SOURCE_ROUTE, "url": TRANSACTION_SOURCE_ROUTE, } class _SpanRecorder(object): """Limits the number of spans recorded in a transaction.""" __slots__ = ("maxlen", "spans") def __init__(self, maxlen): # type: (int) -> None # FIXME: this is `maxlen - 1` only to preserve historical behavior # enforced by tests. # Either this should be changed to `maxlen` or the JS SDK implementation # should be changed to match a consistent interpretation of what maxlen # limits: either transaction+spans or only child spans. self.maxlen = maxlen - 1 self.spans = [] # type: List[Span] def add(self, span): # type: (Span) -> None if len(self.spans) > self.maxlen: span._span_recorder = None else: self.spans.append(span) class Span(object): __slots__ = ( "trace_id", "span_id", "parent_span_id", "same_process_as_parent", "sampled", "op", "description", "start_timestamp", "_start_timestamp_monotonic", "status", "timestamp", "_tags", "_data", "_span_recorder", "hub", "_context_manager_state", "_containing_transaction", ) def __new__(cls, **kwargs): # type: (**Any) -> Any """ Backwards-compatible implementation of Span and Transaction creation. """ # TODO: consider removing this in a future release. # This is for backwards compatibility with releases before Transaction # existed, to allow for a smoother transition. if "transaction" in kwargs: return object.__new__(Transaction) return object.__new__(cls) def __init__( self, trace_id=None, # type: Optional[str] span_id=None, # type: Optional[str] parent_span_id=None, # type: Optional[str] same_process_as_parent=True, # type: bool sampled=None, # type: Optional[bool] op=None, # type: Optional[str] description=None, # type: Optional[str] hub=None, # type: Optional[sentry_sdk.Hub] status=None, # type: Optional[str] transaction=None, # type: Optional[str] # deprecated containing_transaction=None, # type: Optional[Transaction] start_timestamp=None, # type: Optional[datetime] ): # type: (...) -> None self.trace_id = trace_id or uuid.uuid4().hex self.span_id = span_id or uuid.uuid4().hex[16:] self.parent_span_id = parent_span_id self.same_process_as_parent = same_process_as_parent self.sampled = sampled self.op = op self.description = description self.status = status self.hub = hub self._tags = {} # type: Dict[str, str] self._data = {} # type: Dict[str, Any] self._containing_transaction = containing_transaction self.start_timestamp = start_timestamp or datetime.utcnow() try: # TODO: For Python 3.7+, we could use a clock with ns resolution: # self._start_timestamp_monotonic = time.perf_counter_ns() # Python 3.3+ self._start_timestamp_monotonic = time.perf_counter() except AttributeError: pass #: End timestamp of span self.timestamp = None # type: Optional[datetime] self._span_recorder = None # type: Optional[_SpanRecorder] # TODO this should really live on the Transaction class rather than the Span # class def init_span_recorder(self, maxlen): # type: (int) -> None if self._span_recorder is None: self._span_recorder = _SpanRecorder(maxlen) def __repr__(self): # type: () -> str return ( "<%s(op=%r, description:%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r)>" % ( self.__class__.__name__, self.op, self.description, self.trace_id, self.span_id, self.parent_span_id, self.sampled, ) ) def __enter__(self): # type: () -> Span hub = self.hub or sentry_sdk.Hub.current _, scope = hub._stack[-1] old_span = scope.span scope.span = self self._context_manager_state = (hub, scope, old_span) return self def __exit__(self, ty, value, tb): # type: (Optional[Any], Optional[Any], Optional[Any]) -> None if value is not None: self.set_status("internal_error") hub, scope, old_span = self._context_manager_state del self._context_manager_state self.finish(hub) scope.span = old_span @property def containing_transaction(self): # type: () -> Optional[Transaction] # this is a getter rather than a regular attribute so that transactions # can return `self` here instead (as a way to prevent them circularly # referencing themselves) return self._containing_transaction def start_child(self, instrumenter=INSTRUMENTER.SENTRY, **kwargs): # type: (str, **Any) -> Span """ Start a sub-span from the current span or transaction. Takes the same arguments as the initializer of :py:class:`Span`. The trace id, sampling decision, transaction pointer, and span recorder are inherited from the current span/transaction. """ hub = self.hub or sentry_sdk.Hub.current client = hub.client configuration_instrumenter = client and client.options["instrumenter"] if instrumenter != configuration_instrumenter: return NoOpSpan() kwargs.setdefault("sampled", self.sampled) child = Span( trace_id=self.trace_id, parent_span_id=self.span_id, containing_transaction=self.containing_transaction, **kwargs ) span_recorder = ( self.containing_transaction and self.containing_transaction._span_recorder ) if span_recorder: span_recorder.add(child) return child def new_span(self, **kwargs): # type: (**Any) -> Span """Deprecated: use start_child instead.""" logger.warning("Deprecated: use Span.start_child instead of Span.new_span.") return self.start_child(**kwargs) @classmethod def continue_from_environ( cls, environ, # type: typing.Mapping[str, str] **kwargs # type: Any ): # type: (...) -> Transaction """ Create a Transaction with the given params, then add in data pulled from the 'sentry-trace', 'baggage' and 'tracestate' headers from the environ (if any) before returning the Transaction. This is different from `continue_from_headers` in that it assumes header names in the form "HTTP_HEADER_NAME" - such as you would get from a wsgi environ - rather than the form "header-name". """ if cls is Span: logger.warning( "Deprecated: use Transaction.continue_from_environ " "instead of Span.continue_from_environ." ) return Transaction.continue_from_headers(EnvironHeaders(environ), **kwargs) @classmethod def continue_from_headers( cls, headers, # type: typing.Mapping[str, str] **kwargs # type: Any ): # type: (...) -> Transaction """ Create a transaction with the given params (including any data pulled from the 'sentry-trace', 'baggage' and 'tracestate' headers). """ # TODO move this to the Transaction class if cls is Span: logger.warning( "Deprecated: use Transaction.continue_from_headers " "instead of Span.continue_from_headers." ) # TODO-neel move away from this kwargs stuff, it's confusing and opaque # make more explicit baggage = Baggage.from_incoming_header(headers.get(BAGGAGE_HEADER_NAME)) kwargs.update({BAGGAGE_HEADER_NAME: baggage}) sentrytrace_kwargs = extract_sentrytrace_data( headers.get(SENTRY_TRACE_HEADER_NAME) ) if sentrytrace_kwargs is not None: kwargs.update(sentrytrace_kwargs) # If there's an incoming sentry-trace but no incoming baggage header, # for instance in traces coming from older SDKs, # baggage will be empty and immutable and won't be populated as head SDK. baggage.freeze() kwargs.update(extract_tracestate_data(headers.get("tracestate"))) transaction = Transaction(**kwargs) transaction.same_process_as_parent = False return transaction def iter_headers(self): # type: () -> Iterator[Tuple[str, str]] """ Creates a generator which returns the span's `sentry-trace`, `baggage` and `tracestate` headers. If the span's containing transaction doesn't yet have a `sentry_tracestate` value, this will cause one to be generated and stored. """ yield SENTRY_TRACE_HEADER_NAME, self.to_traceparent() tracestate = self.to_tracestate() if has_tracestate_enabled(self) else None # `tracestate` will only be `None` if there's no client or no DSN # TODO (kmclb) the above will be true once the feature is no longer # behind a flag if tracestate: yield "tracestate", tracestate if self.containing_transaction: baggage = self.containing_transaction.get_baggage().serialize() if baggage: yield BAGGAGE_HEADER_NAME, baggage @classmethod def from_traceparent( cls, traceparent, # type: Optional[str] **kwargs # type: Any ): # type: (...) -> Optional[Transaction] """ DEPRECATED: Use Transaction.continue_from_headers(headers, **kwargs) Create a Transaction with the given params, then add in data pulled from the given 'sentry-trace' header value before returning the Transaction. """ logger.warning( "Deprecated: Use Transaction.continue_from_headers(headers, **kwargs) " "instead of from_traceparent(traceparent, **kwargs)" ) if not traceparent: return None return cls.continue_from_headers( {SENTRY_TRACE_HEADER_NAME: traceparent}, **kwargs ) def to_traceparent(self): # type: () -> str sampled = "" if self.sampled is True: sampled = "1" if self.sampled is False: sampled = "0" return "%s-%s-%s" % (self.trace_id, self.span_id, sampled) def to_tracestate(self): # type: () -> Optional[str] """ Computes the `tracestate` header value using data from the containing transaction. If the containing transaction doesn't yet have a `sentry_tracestate` value, this will cause one to be generated and stored. If there is no containing transaction, a value will be generated but not stored. Returns None if there's no client and/or no DSN. """ sentry_tracestate = self.get_or_set_sentry_tracestate() third_party_tracestate = ( self.containing_transaction._third_party_tracestate if self.containing_transaction else None ) if not sentry_tracestate: return None header_value = sentry_tracestate if third_party_tracestate: header_value = header_value + "," + third_party_tracestate return header_value def get_or_set_sentry_tracestate(self): # type: (Span) -> Optional[str] """ Read sentry tracestate off of the span's containing transaction. If the transaction doesn't yet have a `_sentry_tracestate` value, compute one and store it. """ transaction = self.containing_transaction if transaction: if not transaction._sentry_tracestate: transaction._sentry_tracestate = compute_tracestate_entry(self) return transaction._sentry_tracestate # orphan span - nowhere to store the value, so just return it return compute_tracestate_entry(self) def set_tag(self, key, value): # type: (str, Any) -> None self._tags[key] = value def set_data(self, key, value): # type: (str, Any) -> None self._data[key] = value def set_status(self, value): # type: (str) -> None self.status = value def set_http_status(self, http_status): # type: (int) -> None self.set_tag("http.status_code", str(http_status)) if http_status < 400: self.set_status("ok") elif 400 <= http_status < 500: if http_status == 403: self.set_status("permission_denied") elif http_status == 404: self.set_status("not_found") elif http_status == 429: self.set_status("resource_exhausted") elif http_status == 413: self.set_status("failed_precondition") elif http_status == 401: self.set_status("unauthenticated") elif http_status == 409: self.set_status("already_exists") else: self.set_status("invalid_argument") elif 500 <= http_status < 600: if http_status == 504: self.set_status("deadline_exceeded") elif http_status == 501: self.set_status("unimplemented") elif http_status == 503: self.set_status("unavailable") else: self.set_status("internal_error") else: self.set_status("unknown_error") def is_success(self): # type: () -> bool return self.status == "ok" def finish(self, hub=None, end_timestamp=None): # type: (Optional[sentry_sdk.Hub], Optional[datetime]) -> Optional[str] # XXX: would be type: (Optional[sentry_sdk.Hub]) -> None, but that leads # to incompatible return types for Span.finish and Transaction.finish. if self.timestamp is not None: # This span is already finished, ignore. return None hub = hub or self.hub or sentry_sdk.Hub.current try: if end_timestamp: self.timestamp = end_timestamp else: duration_seconds = time.perf_counter() - self._start_timestamp_monotonic self.timestamp = self.start_timestamp + timedelta( seconds=duration_seconds ) except AttributeError: self.timestamp = datetime.utcnow() maybe_create_breadcrumbs_from_span(hub, self) return None def to_json(self): # type: () -> Dict[str, Any] rv = { "trace_id": self.trace_id, "span_id": self.span_id, "parent_span_id": self.parent_span_id, "same_process_as_parent": self.same_process_as_parent, "op": self.op, "description": self.description, "start_timestamp": self.start_timestamp, "timestamp": self.timestamp, } # type: Dict[str, Any] if self.status: self._tags["status"] = self.status tags = self._tags if tags: rv["tags"] = tags data = self._data if data: rv["data"] = data return rv def get_trace_context(self): # type: () -> Any rv = { "trace_id": self.trace_id, "span_id": self.span_id, "parent_span_id": self.parent_span_id, "op": self.op, "description": self.description, } # type: Dict[str, Any] if self.status: rv["status"] = self.status # if the transaction didn't inherit a tracestate value, and no outgoing # requests - whose need for headers would have caused a tracestate value # to be created - were made as part of the transaction, the transaction # still won't have a tracestate value, so compute one now sentry_tracestate = self.get_or_set_sentry_tracestate() if sentry_tracestate: rv["tracestate"] = sentry_tracestate if self.containing_transaction: rv[ "dynamic_sampling_context" ] = self.containing_transaction.get_baggage().dynamic_sampling_context() return rv class Transaction(Span): __slots__ = ( "name", "source", "parent_sampled", # used to create baggage value for head SDKs in dynamic sampling "sample_rate", # the sentry portion of the `tracestate` header used to transmit # correlation context for server-side dynamic sampling, of the form # `sentry=xxxxx`, where `xxxxx` is the base64-encoded json of the # correlation context data, missing trailing any = "_sentry_tracestate", # tracestate data from other vendors, of the form `dogs=yes,cats=maybe` "_third_party_tracestate", "_measurements", "_contexts", "_profile", "_baggage", "_active_thread_id", ) def __init__( self, name="", # type: str parent_sampled=None, # type: Optional[bool] sentry_tracestate=None, # type: Optional[str] third_party_tracestate=None, # type: Optional[str] baggage=None, # type: Optional[Baggage] source=TRANSACTION_SOURCE_CUSTOM, # type: str **kwargs # type: Any ): # type: (...) -> None # TODO: consider removing this in a future release. # This is for backwards compatibility with releases before Transaction # existed, to allow for a smoother transition. if not name and "transaction" in kwargs: logger.warning( "Deprecated: use Transaction(name=...) to create transactions " "instead of Span(transaction=...)." ) name = kwargs.pop("transaction") Span.__init__(self, **kwargs) self.name = name self.source = source self.sample_rate = None # type: Optional[float] self.parent_sampled = parent_sampled # if tracestate isn't inherited and set here, it will get set lazily, # either the first time an outgoing request needs it for a header or the # first time an event needs it for inclusion in the captured data self._sentry_tracestate = sentry_tracestate self._third_party_tracestate = third_party_tracestate self._measurements = {} # type: Dict[str, Any] self._contexts = {} # type: Dict[str, Any] self._profile = None # type: Optional[sentry_sdk.profiler.Profile] self._baggage = baggage # for profiling, we want to know on which thread a transaction is started # to accurately show the active thread in the UI self._active_thread_id = ( threading.current_thread().ident ) # used by profiling.py def __repr__(self): # type: () -> str return ( "<%s(name=%r, op=%r, trace_id=%r, span_id=%r, parent_span_id=%r, sampled=%r, source=%r)>" % ( self.__class__.__name__, self.name, self.op, self.trace_id, self.span_id, self.parent_span_id, self.sampled, self.source, ) ) @property def containing_transaction(self): # type: () -> Transaction # Transactions (as spans) belong to themselves (as transactions). This # is a getter rather than a regular attribute to avoid having a circular # reference. return self def finish(self, hub=None, end_timestamp=None): # type: (Optional[sentry_sdk.Hub], Optional[datetime]) -> Optional[str] if self.timestamp is not None: # This transaction is already finished, ignore. return None hub = hub or self.hub or sentry_sdk.Hub.current client = hub.client if client is None: # We have no client and therefore nowhere to send this transaction. return None # This is a de facto proxy for checking if sampled = False if self._span_recorder is None: logger.debug("Discarding transaction because sampled = False") # This is not entirely accurate because discards here are not # exclusively based on sample rate but also traces sampler, but # we handle this the same here. if client.transport and has_tracing_enabled(client.options): client.transport.record_lost_event( "sample_rate", data_category="transaction" ) return None if not self.name: logger.warning( "Transaction has no name, falling back to `<unlabeled transaction>`." ) self.name = "<unlabeled transaction>" Span.finish(self, hub, end_timestamp) if not self.sampled: # At this point a `sampled = None` should have already been resolved # to a concrete decision. if self.sampled is None: logger.warning("Discarding transaction without sampling decision.") return None finished_spans = [ span.to_json() for span in self._span_recorder.spans if span.timestamp is not None ] # we do this to break the circular reference of transaction -> span # recorder -> span -> containing transaction (which is where we started) # before either the spans or the transaction goes out of scope and has # to be garbage collected self._span_recorder = None contexts = {} contexts.update(self._contexts) contexts.update({"trace": self.get_trace_context()}) event = { "type": "transaction", "transaction": self.name, "transaction_info": {"source": self.source}, "contexts": contexts, "tags": self._tags, "timestamp": self.timestamp, "start_timestamp": self.start_timestamp, "spans": finished_spans, } # type: Event if hub.client is not None and self._profile is not None: event["profile"] = self._profile contexts.update({"profile": self._profile.get_profile_context()}) if has_custom_measurements_enabled(): event["measurements"] = self._measurements return hub.capture_event(event) def set_measurement(self, name, value, unit=""): # type: (str, float, MeasurementUnit) -> None if not has_custom_measurements_enabled(): logger.debug( "[Tracing] Experimental custom_measurements feature is disabled" ) return self._measurements[name] = {"value": value, "unit": unit} def set_context(self, key, value): # type: (str, Any) -> None self._contexts[key] = value def to_json(self): # type: () -> Dict[str, Any] rv = super(Transaction, self).to_json() rv["name"] = self.name rv["source"] = self.source rv["sampled"] = self.sampled return rv def get_baggage(self): # type: () -> Baggage """ The first time a new baggage with sentry items is made, it will be frozen. """ if not self._baggage or self._baggage.mutable: self._baggage = Baggage.populate_from_transaction(self) return self._baggage def _set_initial_sampling_decision(self, sampling_context): # type: (SamplingContext) -> None """ Sets the transaction's sampling decision, according to the following precedence rules: 1. If a sampling decision is passed to `start_transaction` (`start_transaction(name: "my transaction", sampled: True)`), that decision will be used, regardless of anything else 2. If `traces_sampler` is defined, its decision will be used. It can choose to keep or ignore any parent sampling decision, or use the sampling context data to make its own decision or to choose a sample rate for the transaction. 3. If `traces_sampler` is not defined, but there's a parent sampling decision, the parent sampling decision will be used. 4. If `traces_sampler` is not defined and there's no parent sampling decision, `traces_sample_rate` will be used. """ hub = self.hub or sentry_sdk.Hub.current client = hub.client options = (client and client.options) or {} transaction_description = "{op}transaction <{name}>".format( op=("<" + self.op + "> " if self.op else ""), name=self.name ) # nothing to do if there's no client or if tracing is disabled if not client or not has_tracing_enabled(options): self.sampled = False return # if the user has forced a sampling decision by passing a `sampled` # value when starting the transaction, go with that if self.sampled is not None: self.sample_rate = float(self.sampled) return # we would have bailed already if neither `traces_sampler` nor # `traces_sample_rate` were defined, so one of these should work; prefer # the hook if so sample_rate = ( options["traces_sampler"](sampling_context) if callable(options.get("traces_sampler")) else ( # default inheritance behavior sampling_context["parent_sampled"] if sampling_context["parent_sampled"] is not None else options["traces_sample_rate"] ) ) # Since this is coming from the user (or from a function provided by the # user), who knows what we might get. (The only valid values are # booleans or numbers between 0 and 1.) if not is_valid_sample_rate(sample_rate): logger.warning( "[Tracing] Discarding {transaction_description} because of invalid sample rate.".format( transaction_description=transaction_description, ) ) self.sampled = False return self.sample_rate = float(sample_rate) # if the function returned 0 (or false), or if `traces_sample_rate` is # 0, it's a sign the transaction should be dropped if not sample_rate: logger.debug( "[Tracing] Discarding {transaction_description} because {reason}".format( transaction_description=transaction_description, reason=( "traces_sampler returned 0 or False" if callable(options.get("traces_sampler")) else "traces_sample_rate is set to 0" ), ) ) self.sampled = False return # Now we roll the dice. random.random is inclusive of 0, but not of 1, # so strict < is safe here. In case sample_rate is a boolean, cast it # to a float (True becomes 1.0 and False becomes 0.0) self.sampled = random.random() < float(sample_rate) if self.sampled: logger.debug( "[Tracing] Starting {transaction_description}".format( transaction_description=transaction_description, ) ) else: logger.debug( "[Tracing] Discarding {transaction_description} because it's not included in the random sample (sampling rate = {sample_rate})".format( transaction_description=transaction_description, sample_rate=float(sample_rate), ) ) class NoOpSpan(Span): def __repr__(self): # type: () -> str return self.__class__.__name__ def start_child(self, instrumenter=INSTRUMENTER.SENTRY, **kwargs): # type: (str, **Any) -> NoOpSpan return NoOpSpan() def new_span(self, **kwargs): # type: (**Any) -> NoOpSpan pass def set_tag(self, key, value): # type: (str, Any) -> None pass def set_data(self, key, value): # type: (str, Any) -> None pass def set_status(self, value): # type: (str) -> None pass def set_http_status(self, http_status): # type: (int) -> None pass def finish(self, hub=None, end_timestamp=None): # type: (Optional[sentry_sdk.Hub], Optional[datetime]) -> Optional[str] pass # Circular imports from sentry_sdk.tracing_utils import ( Baggage, EnvironHeaders, compute_tracestate_entry, extract_sentrytrace_data, extract_tracestate_data, has_tracestate_enabled, has_tracing_enabled, is_valid_sample_rate, maybe_create_breadcrumbs_from_span, has_custom_measurements_enabled, )
31,209
Python
33.448124
151
0.581819
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/profiler.py
""" This file is originally based on code from https://github.com/nylas/nylas-perftools, which is published under the following license: The MIT License (MIT) Copyright (c) 2014 Nylas Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import atexit import os import platform import random import sys import threading import time import uuid from collections import deque from contextlib import contextmanager import sentry_sdk from sentry_sdk._compat import PY33, PY311 from sentry_sdk._types import MYPY from sentry_sdk.utils import ( filename_for_module, handle_in_app_impl, logger, nanosecond_time, ) if MYPY: from types import FrameType from typing import Any from typing import Callable from typing import Deque from typing import Dict from typing import Generator from typing import List from typing import Optional from typing import Set from typing import Sequence from typing import Tuple from typing_extensions import TypedDict import sentry_sdk.tracing ThreadId = str # The exact value of this id is not very meaningful. The purpose # of this id is to give us a compact and unique identifier for a # raw stack that can be used as a key to a dictionary so that it # can be used during the sampled format generation. RawStackId = Tuple[int, int] RawFrame = Tuple[ str, # abs_path Optional[str], # module Optional[str], # filename str, # function int, # lineno ] RawStack = Tuple[RawFrame, ...] RawSample = Sequence[Tuple[str, Tuple[RawStackId, RawStack]]] ProcessedSample = TypedDict( "ProcessedSample", { "elapsed_since_start_ns": str, "thread_id": ThreadId, "stack_id": int, }, ) ProcessedStack = List[int] ProcessedFrame = TypedDict( "ProcessedFrame", { "abs_path": str, "filename": Optional[str], "function": str, "lineno": int, "module": Optional[str], }, ) ProcessedThreadMetadata = TypedDict( "ProcessedThreadMetadata", {"name": str}, ) ProcessedProfile = TypedDict( "ProcessedProfile", { "frames": List[ProcessedFrame], "stacks": List[ProcessedStack], "samples": List[ProcessedSample], "thread_metadata": Dict[ThreadId, ProcessedThreadMetadata], }, ) ProfileContext = TypedDict( "ProfileContext", {"profile_id": str}, ) try: from gevent.monkey import is_module_patched # type: ignore except ImportError: def is_module_patched(*args, **kwargs): # type: (*Any, **Any) -> bool # unable to import from gevent means no modules have been patched return False _scheduler = None # type: Optional[Scheduler] def setup_profiler(options): # type: (Dict[str, Any]) -> None """ `buffer_secs` determines the max time a sample will be buffered for `frequency` determines the number of samples to take per second (Hz) """ global _scheduler if _scheduler is not None: logger.debug("profiling is already setup") return if not PY33: logger.warn("profiling is only supported on Python >= 3.3") return frequency = 101 if is_module_patched("threading") or is_module_patched("_thread"): # If gevent has patched the threading modules then we cannot rely on # them to spawn a native thread for sampling. # Instead we default to the GeventScheduler which is capable of # spawning native threads within gevent. default_profiler_mode = GeventScheduler.mode else: default_profiler_mode = ThreadScheduler.mode profiler_mode = options["_experiments"].get("profiler_mode", default_profiler_mode) if ( profiler_mode == ThreadScheduler.mode # for legacy reasons, we'll keep supporting sleep mode for this scheduler or profiler_mode == "sleep" ): _scheduler = ThreadScheduler(frequency=frequency) elif profiler_mode == GeventScheduler.mode: try: _scheduler = GeventScheduler(frequency=frequency) except ImportError: raise ValueError("Profiler mode: {} is not available".format(profiler_mode)) else: raise ValueError("Unknown profiler mode: {}".format(profiler_mode)) _scheduler.setup() atexit.register(teardown_profiler) def teardown_profiler(): # type: () -> None global _scheduler if _scheduler is not None: _scheduler.teardown() _scheduler = None # We want to impose a stack depth limit so that samples aren't too large. MAX_STACK_DEPTH = 128 def extract_stack( frame, # type: Optional[FrameType] cwd, # type: str prev_cache=None, # type: Optional[Tuple[RawStackId, RawStack, Deque[FrameType]]] max_stack_depth=MAX_STACK_DEPTH, # type: int ): # type: (...) -> Tuple[RawStackId, RawStack, Deque[FrameType]] """ Extracts the stack starting the specified frame. The extracted stack assumes the specified frame is the top of the stack, and works back to the bottom of the stack. In the event that the stack is more than `MAX_STACK_DEPTH` frames deep, only the first `MAX_STACK_DEPTH` frames will be returned. """ frames = deque(maxlen=max_stack_depth) # type: Deque[FrameType] while frame is not None: frames.append(frame) frame = frame.f_back if prev_cache is None: stack = tuple(extract_frame(frame, cwd) for frame in frames) else: _, prev_stack, prev_frames = prev_cache prev_depth = len(prev_frames) depth = len(frames) # We want to match the frame found in this sample to the frames found in the # previous sample. If they are the same (using the `is` operator), we can # skip the expensive work of extracting the frame information and reuse what # we extracted during the last sample. # # Make sure to keep in mind that the stack is ordered from the inner most # from to the outer most frame so be careful with the indexing. stack = tuple( prev_stack[i] if i >= 0 and frame is prev_frames[i] else extract_frame(frame, cwd) for i, frame in zip(range(prev_depth - depth, prev_depth), frames) ) # Instead of mapping the stack into frame ids and hashing # that as a tuple, we can directly hash the stack. # This saves us from having to generate yet another list. # Additionally, using the stack as the key directly is # costly because the stack can be large, so we pre-hash # the stack, and use the hash as the key as this will be # needed a few times to improve performance. # # To Reduce the likelihood of hash collisions, we include # the stack depth. This means that only stacks of the same # depth can suffer from hash collisions. stack_id = len(stack), hash(stack) return stack_id, stack, frames def extract_frame(frame, cwd): # type: (FrameType, str) -> RawFrame abs_path = frame.f_code.co_filename try: module = frame.f_globals["__name__"] except Exception: module = None # namedtuples can be many times slower when initialing # and accessing attribute so we opt to use a tuple here instead return ( # This originally was `os.path.abspath(abs_path)` but that had # a large performance overhead. # # According to docs, this is equivalent to # `os.path.normpath(os.path.join(os.getcwd(), path))`. # The `os.getcwd()` call is slow here, so we precompute it. # # Additionally, since we are using normalized path already, # we skip calling `os.path.normpath` entirely. os.path.join(cwd, abs_path), module, filename_for_module(module, abs_path) or None, get_frame_name(frame), frame.f_lineno, ) if PY311: def get_frame_name(frame): # type: (FrameType) -> str return frame.f_code.co_qualname # type: ignore else: def get_frame_name(frame): # type: (FrameType) -> str f_code = frame.f_code co_varnames = f_code.co_varnames # co_name only contains the frame name. If the frame was a method, # the class name will NOT be included. name = f_code.co_name # if it was a method, we can get the class name by inspecting # the f_locals for the `self` argument try: if ( # the co_varnames start with the frame's positional arguments # and we expect the first to be `self` if its an instance method co_varnames and co_varnames[0] == "self" and "self" in frame.f_locals ): for cls in frame.f_locals["self"].__class__.__mro__: if name in cls.__dict__: return "{}.{}".format(cls.__name__, name) except AttributeError: pass # if it was a class method, (decorated with `@classmethod`) # we can get the class name by inspecting the f_locals for the `cls` argument try: if ( # the co_varnames start with the frame's positional arguments # and we expect the first to be `cls` if its a class method co_varnames and co_varnames[0] == "cls" and "cls" in frame.f_locals ): for cls in frame.f_locals["cls"].__mro__: if name in cls.__dict__: return "{}.{}".format(cls.__name__, name) except AttributeError: pass # nothing we can do if it is a staticmethod (decorated with @staticmethod) # we've done all we can, time to give up and return what we have return name MAX_PROFILE_DURATION_NS = int(3e10) # 30 seconds class Profile(object): def __init__( self, scheduler, # type: Scheduler transaction, # type: sentry_sdk.tracing.Transaction hub=None, # type: Optional[sentry_sdk.Hub] ): # type: (...) -> None self.scheduler = scheduler self.transaction = transaction self.hub = hub self.active_thread_id = None # type: Optional[int] self.start_ns = 0 # type: int self.stop_ns = 0 # type: int self.active = False # type: bool self.event_id = uuid.uuid4().hex # type: str self.indexed_frames = {} # type: Dict[RawFrame, int] self.indexed_stacks = {} # type: Dict[RawStackId, int] self.frames = [] # type: List[ProcessedFrame] self.stacks = [] # type: List[ProcessedStack] self.samples = [] # type: List[ProcessedSample] transaction._profile = self def get_profile_context(self): # type: () -> ProfileContext return {"profile_id": self.event_id} def __enter__(self): # type: () -> None hub = self.hub or sentry_sdk.Hub.current _, scope = hub._stack[-1] old_profile = scope.profile scope.profile = self self._context_manager_state = (hub, scope, old_profile) self.start_ns = nanosecond_time() self.scheduler.start_profiling(self) def __exit__(self, ty, value, tb): # type: (Optional[Any], Optional[Any], Optional[Any]) -> None self.scheduler.stop_profiling(self) self.stop_ns = nanosecond_time() _, scope, old_profile = self._context_manager_state del self._context_manager_state scope.profile = old_profile def write(self, ts, sample): # type: (int, RawSample) -> None if ts < self.start_ns: return offset = ts - self.start_ns if offset > MAX_PROFILE_DURATION_NS: return elapsed_since_start_ns = str(offset) for tid, (stack_id, stack) in sample: # Check if the stack is indexed first, this lets us skip # indexing frames if it's not necessary if stack_id not in self.indexed_stacks: for frame in stack: if frame not in self.indexed_frames: self.indexed_frames[frame] = len(self.indexed_frames) self.frames.append( { "abs_path": frame[0], "module": frame[1], "filename": frame[2], "function": frame[3], "lineno": frame[4], } ) self.indexed_stacks[stack_id] = len(self.indexed_stacks) self.stacks.append([self.indexed_frames[frame] for frame in stack]) self.samples.append( { "elapsed_since_start_ns": elapsed_since_start_ns, "thread_id": tid, "stack_id": self.indexed_stacks[stack_id], } ) def process(self): # type: () -> ProcessedProfile # This collects the thread metadata at the end of a profile. Doing it # this way means that any threads that terminate before the profile ends # will not have any metadata associated with it. thread_metadata = { str(thread.ident): { "name": str(thread.name), } for thread in threading.enumerate() } # type: Dict[str, ProcessedThreadMetadata] return { "frames": self.frames, "stacks": self.stacks, "samples": self.samples, "thread_metadata": thread_metadata, } def to_json(self, event_opt, options): # type: (Any, Dict[str, Any]) -> Dict[str, Any] profile = self.process() handle_in_app_impl( profile["frames"], options["in_app_exclude"], options["in_app_include"] ) return { "environment": event_opt.get("environment"), "event_id": self.event_id, "platform": "python", "profile": profile, "release": event_opt.get("release", ""), "timestamp": event_opt["timestamp"], "version": "1", "device": { "architecture": platform.machine(), }, "os": { "name": platform.system(), "version": platform.release(), }, "runtime": { "name": platform.python_implementation(), "version": platform.python_version(), }, "transactions": [ { "id": event_opt["event_id"], "name": self.transaction.name, # we start the transaction before the profile and this is # the transaction start time relative to the profile, so we # hardcode it to 0 until we can start the profile before "relative_start_ns": "0", # use the duration of the profile instead of the transaction # because we end the transaction after the profile "relative_end_ns": str(self.stop_ns - self.start_ns), "trace_id": self.transaction.trace_id, "active_thread_id": str( self.transaction._active_thread_id if self.active_thread_id is None else self.active_thread_id ), } ], } class Scheduler(object): mode = "unknown" def __init__(self, frequency): # type: (int) -> None self.interval = 1.0 / frequency self.sampler = self.make_sampler() self.new_profiles = deque() # type: Deque[Profile] self.active_profiles = set() # type: Set[Profile] def __enter__(self): # type: () -> Scheduler self.setup() return self def __exit__(self, ty, value, tb): # type: (Optional[Any], Optional[Any], Optional[Any]) -> None self.teardown() def setup(self): # type: () -> None raise NotImplementedError def teardown(self): # type: () -> None raise NotImplementedError def start_profiling(self, profile): # type: (Profile) -> None profile.active = True self.new_profiles.append(profile) def stop_profiling(self, profile): # type: (Profile) -> None profile.active = False def make_sampler(self): # type: () -> Callable[..., None] cwd = os.getcwd() # In Python3+, we can use the `nonlocal` keyword to rebind the value, # but this is not possible in Python2. To get around this, we wrap # the value in a list to allow updating this value each sample. last_sample = [ {} ] # type: List[Dict[int, Tuple[RawStackId, RawStack, Deque[FrameType]]]] def _sample_stack(*args, **kwargs): # type: (*Any, **Any) -> None """ Take a sample of the stack on all the threads in the process. This should be called at a regular interval to collect samples. """ # no profiles taking place, so we can stop early if not self.new_profiles and not self.active_profiles: # make sure to clear the cache if we're not profiling so we dont # keep a reference to the last stack of frames around last_sample[0] = {} return # This is the number of profiles we want to pop off. # It's possible another thread adds a new profile to # the list and we spend longer than we want inside # the loop below. # # Also make sure to set this value before extracting # frames so we do not write to any new profiles that # were started after this point. new_profiles = len(self.new_profiles) now = nanosecond_time() raw_sample = { tid: extract_stack(frame, cwd, last_sample[0].get(tid)) for tid, frame in sys._current_frames().items() } # make sure to update the last sample so the cache has # the most recent stack for better cache hits last_sample[0] = raw_sample sample = [ (str(tid), (stack_id, stack)) for tid, (stack_id, stack, _) in raw_sample.items() ] # Move the new profiles into the active_profiles set. # # We cannot directly add the to active_profiles set # in `start_profiling` because it is called from other # threads which can cause a RuntimeError when it the # set sizes changes during iteration without a lock. # # We also want to avoid using a lock here so threads # that are starting profiles are not blocked until it # can acquire the lock. for _ in range(new_profiles): self.active_profiles.add(self.new_profiles.popleft()) inactive_profiles = [] for profile in self.active_profiles: if profile.active: profile.write(now, sample) else: # If a thread is marked inactive, we buffer it # to `inactive_profiles` so it can be removed. # We cannot remove it here as it would result # in a RuntimeError. inactive_profiles.append(profile) for profile in inactive_profiles: self.active_profiles.remove(profile) return _sample_stack class ThreadScheduler(Scheduler): """ This scheduler is based on running a daemon thread that will call the sampler at a regular interval. """ mode = "thread" name = "sentry.profiler.ThreadScheduler" def __init__(self, frequency): # type: (int) -> None super(ThreadScheduler, self).__init__(frequency=frequency) # used to signal to the thread that it should stop self.event = threading.Event() # make sure the thread is a daemon here otherwise this # can keep the application running after other threads # have exited self.thread = threading.Thread(name=self.name, target=self.run, daemon=True) def setup(self): # type: () -> None self.thread.start() def teardown(self): # type: () -> None self.event.set() self.thread.join() def run(self): # type: () -> None last = time.perf_counter() while True: if self.event.is_set(): break self.sampler() # some time may have elapsed since the last time # we sampled, so we need to account for that and # not sleep for too long elapsed = time.perf_counter() - last if elapsed < self.interval: time.sleep(self.interval - elapsed) # after sleeping, make sure to take the current # timestamp so we can use it next iteration last = time.perf_counter() class GeventScheduler(Scheduler): """ This scheduler is based on the thread scheduler but adapted to work with gevent. When using gevent, it may monkey patch the threading modules (`threading` and `_thread`). This results in the use of greenlets instead of native threads. This is an issue because the sampler CANNOT run in a greenlet because 1. Other greenlets doing sync work will prevent the sampler from running 2. The greenlet runs in the same thread as other greenlets so when taking a sample, other greenlets will have been evicted from the thread. This results in a sample containing only the sampler's code. """ mode = "gevent" name = "sentry.profiler.GeventScheduler" def __init__(self, frequency): # type: (int) -> None # This can throw an ImportError that must be caught if `gevent` is # not installed. from gevent.threadpool import ThreadPool # type: ignore super(GeventScheduler, self).__init__(frequency=frequency) # used to signal to the thread that it should stop self.event = threading.Event() # Using gevent's ThreadPool allows us to bypass greenlets and spawn # native threads. self.pool = ThreadPool(1) def setup(self): # type: () -> None self.pool.spawn(self.run) def teardown(self): # type: () -> None self.event.set() self.pool.join() def run(self): # type: () -> None last = time.perf_counter() while True: if self.event.is_set(): break self.sampler() # some time may have elapsed since the last time # we sampled, so we need to account for that and # not sleep for too long elapsed = time.perf_counter() - last if elapsed < self.interval: time.sleep(self.interval - elapsed) # after sleeping, make sure to take the current # timestamp so we can use it next iteration last = time.perf_counter() def _should_profile(transaction, hub): # type: (sentry_sdk.tracing.Transaction, sentry_sdk.Hub) -> bool # The corresponding transaction was not sampled, # so don't generate a profile for it. if not transaction.sampled: return False # The profiler hasn't been properly initialized. if _scheduler is None: return False client = hub.client # The client is None, so we can't get the sample rate. if client is None: return False options = client.options profiles_sample_rate = options["_experiments"].get("profiles_sample_rate") # The profiles_sample_rate option was not set, so profiling # was never enabled. if profiles_sample_rate is None: return False return random.random() < float(profiles_sample_rate) @contextmanager def start_profiling(transaction, hub=None): # type: (sentry_sdk.tracing.Transaction, Optional[sentry_sdk.Hub]) -> Generator[None, None, None] hub = hub or sentry_sdk.Hub.current # if profiling was not enabled, this should be a noop if _should_profile(transaction, hub): assert _scheduler is not None with Profile(_scheduler, transaction, hub): yield else: yield
26,041
Python
32.733161
460
0.585423
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/_queue.py
""" A fork of Python 3.6's stdlib queue with Lock swapped out for RLock to avoid a deadlock while garbage collecting. See https://codewithoutrules.com/2017/08/16/concurrency-python/ https://bugs.python.org/issue14976 https://github.com/sqlalchemy/sqlalchemy/blob/4eb747b61f0c1b1c25bdee3856d7195d10a0c227/lib/sqlalchemy/queue.py#L1 We also vendor the code to evade eventlet's broken monkeypatching, see https://github.com/getsentry/sentry-python/pull/484 """ import threading from collections import deque from time import time from sentry_sdk._types import MYPY if MYPY: from typing import Any __all__ = ["EmptyError", "FullError", "Queue"] class EmptyError(Exception): "Exception raised by Queue.get(block=0)/get_nowait()." pass class FullError(Exception): "Exception raised by Queue.put(block=0)/put_nowait()." pass class Queue(object): """Create a queue object with a given maximum size. If maxsize is <= 0, the queue size is infinite. """ def __init__(self, maxsize=0): self.maxsize = maxsize self._init(maxsize) # mutex must be held whenever the queue is mutating. All methods # that acquire mutex must release it before returning. mutex # is shared between the three conditions, so acquiring and # releasing the conditions also acquires and releases mutex. self.mutex = threading.RLock() # Notify not_empty whenever an item is added to the queue; a # thread waiting to get is notified then. self.not_empty = threading.Condition(self.mutex) # Notify not_full whenever an item is removed from the queue; # a thread waiting to put is notified then. self.not_full = threading.Condition(self.mutex) # Notify all_tasks_done whenever the number of unfinished tasks # drops to zero; thread waiting to join() is notified to resume self.all_tasks_done = threading.Condition(self.mutex) self.unfinished_tasks = 0 def task_done(self): """Indicate that a formerly enqueued task is complete. Used by Queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue). Raises a ValueError if called more times than there were items placed in the queue. """ with self.all_tasks_done: unfinished = self.unfinished_tasks - 1 if unfinished <= 0: if unfinished < 0: raise ValueError("task_done() called too many times") self.all_tasks_done.notify_all() self.unfinished_tasks = unfinished def join(self): """Blocks until all items in the Queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks. """ with self.all_tasks_done: while self.unfinished_tasks: self.all_tasks_done.wait() def qsize(self): """Return the approximate size of the queue (not reliable!).""" with self.mutex: return self._qsize() def empty(self): """Return True if the queue is empty, False otherwise (not reliable!). This method is likely to be removed at some point. Use qsize() == 0 as a direct substitute, but be aware that either approach risks a race condition where a queue can grow before the result of empty() or qsize() can be used. To create code that needs to wait for all queued tasks to be completed, the preferred technique is to use the join() method. """ with self.mutex: return not self._qsize() def full(self): """Return True if the queue is full, False otherwise (not reliable!). This method is likely to be removed at some point. Use qsize() >= n as a direct substitute, but be aware that either approach risks a race condition where a queue can shrink before the result of full() or qsize() can be used. """ with self.mutex: return 0 < self.maxsize <= self._qsize() def put(self, item, block=True, timeout=None): """Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the FullError exception if no free slot was available within that time. Otherwise ('block' is false), put an item on the queue if a free slot is immediately available, else raise the FullError exception ('timeout' is ignored in that case). """ with self.not_full: if self.maxsize > 0: if not block: if self._qsize() >= self.maxsize: raise FullError() elif timeout is None: while self._qsize() >= self.maxsize: self.not_full.wait() elif timeout < 0: raise ValueError("'timeout' must be a non-negative number") else: endtime = time() + timeout while self._qsize() >= self.maxsize: remaining = endtime - time() if remaining <= 0.0: raise FullError() self.not_full.wait(remaining) self._put(item) self.unfinished_tasks += 1 self.not_empty.notify() def get(self, block=True, timeout=None): """Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the EmptyError exception if no item was available within that time. Otherwise ('block' is false), return an item if one is immediately available, else raise the EmptyError exception ('timeout' is ignored in that case). """ with self.not_empty: if not block: if not self._qsize(): raise EmptyError() elif timeout is None: while not self._qsize(): self.not_empty.wait() elif timeout < 0: raise ValueError("'timeout' must be a non-negative number") else: endtime = time() + timeout while not self._qsize(): remaining = endtime - time() if remaining <= 0.0: raise EmptyError() self.not_empty.wait(remaining) item = self._get() self.not_full.notify() return item def put_nowait(self, item): """Put an item into the queue without blocking. Only enqueue the item if a free slot is immediately available. Otherwise raise the FullError exception. """ return self.put(item, block=False) def get_nowait(self): """Remove and return an item from the queue without blocking. Only get an item if one is immediately available. Otherwise raise the EmptyError exception. """ return self.get(block=False) # Override these methods to implement other queue organizations # (e.g. stack or priority queue). # These will only be called with appropriate locks held # Initialize the queue representation def _init(self, maxsize): self.queue = deque() # type: Any def _qsize(self): return len(self.queue) # Put a new item in the queue def _put(self, item): self.queue.append(item) # Get an item from the queue def _get(self): return self.queue.popleft()
8,475
Python
36.175438
113
0.609204
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/serializer.py
import sys import math from datetime import datetime from sentry_sdk.utils import ( AnnotatedValue, capture_internal_exception, disable_capture_event, format_timestamp, json_dumps, safe_repr, strip_string, ) import sentry_sdk.utils from sentry_sdk._compat import ( text_type, PY2, string_types, number_types, iteritems, binary_sequence_types, ) from sentry_sdk._types import MYPY if MYPY: from datetime import timedelta from types import TracebackType from typing import Any from typing import Callable from typing import ContextManager from typing import Dict from typing import List from typing import Optional from typing import Tuple from typing import Type from typing import Union from sentry_sdk._types import NotImplementedType, Event Span = Dict[str, Any] ReprProcessor = Callable[[Any, Dict[str, Any]], Union[NotImplementedType, str]] Segment = Union[str, int] if PY2: # Importing ABCs from collections is deprecated, and will stop working in 3.8 # https://github.com/python/cpython/blob/master/Lib/collections/__init__.py#L49 from collections import Mapping, Sequence, Set serializable_str_types = string_types + binary_sequence_types else: # New in 3.3 # https://docs.python.org/3/library/collections.abc.html from collections.abc import Mapping, Sequence, Set # Bytes are technically not strings in Python 3, but we can serialize them serializable_str_types = string_types + binary_sequence_types # Maximum length of JSON-serialized event payloads that can be safely sent # before the server may reject the event due to its size. This is not intended # to reflect actual values defined server-side, but rather only be an upper # bound for events sent by the SDK. # # Can be overwritten if wanting to send more bytes, e.g. with a custom server. # When changing this, keep in mind that events may be a little bit larger than # this value due to attached metadata, so keep the number conservative. MAX_EVENT_BYTES = 10**6 MAX_DATABAG_DEPTH = 5 MAX_DATABAG_BREADTH = 10 CYCLE_MARKER = "<cyclic>" global_repr_processors = [] # type: List[ReprProcessor] def add_global_repr_processor(processor): # type: (ReprProcessor) -> None global_repr_processors.append(processor) class Memo(object): __slots__ = ("_ids", "_objs") def __init__(self): # type: () -> None self._ids = {} # type: Dict[int, Any] self._objs = [] # type: List[Any] def memoize(self, obj): # type: (Any) -> ContextManager[bool] self._objs.append(obj) return self def __enter__(self): # type: () -> bool obj = self._objs[-1] if id(obj) in self._ids: return True else: self._ids[id(obj)] = obj return False def __exit__( self, ty, # type: Optional[Type[BaseException]] value, # type: Optional[BaseException] tb, # type: Optional[TracebackType] ): # type: (...) -> None self._ids.pop(id(self._objs.pop()), None) def serialize(event, smart_transaction_trimming=False, **kwargs): # type: (Event, bool, **Any) -> Event memo = Memo() path = [] # type: List[Segment] meta_stack = [] # type: List[Dict[str, Any]] span_description_bytes = [] # type: List[int] def _annotate(**meta): # type: (**Any) -> None while len(meta_stack) <= len(path): try: segment = path[len(meta_stack) - 1] node = meta_stack[-1].setdefault(text_type(segment), {}) except IndexError: node = {} meta_stack.append(node) meta_stack[-1].setdefault("", {}).update(meta) def _should_repr_strings(): # type: () -> Optional[bool] """ By default non-serializable objects are going through safe_repr(). For certain places in the event (local vars) we want to repr() even things that are JSON-serializable to make their type more apparent. For example, it's useful to see the difference between a unicode-string and a bytestring when viewing a stacktrace. For container-types we still don't do anything different. Generally we just try to make the Sentry UI present exactly what a pretty-printed repr would look like. :returns: `True` if we are somewhere in frame variables, and `False` if we are in a position where we will never encounter frame variables when recursing (for example, we're in `event.extra`). `None` if we are not (yet) in frame variables, but might encounter them when recursing (e.g. we're in `event.exception`) """ try: p0 = path[0] if p0 == "stacktrace" and path[1] == "frames" and path[3] == "vars": return True if ( p0 in ("threads", "exception") and path[1] == "values" and path[3] == "stacktrace" and path[4] == "frames" and path[6] == "vars" ): return True except IndexError: return None return False def _is_databag(): # type: () -> Optional[bool] """ A databag is any value that we need to trim. :returns: Works like `_should_repr_strings()`. `True` for "yes", `False` for :"no", `None` for "maybe soon". """ try: rv = _should_repr_strings() if rv in (True, None): return rv p0 = path[0] if p0 == "request" and path[1] == "data": return True if p0 == "breadcrumbs" and path[1] == "values": path[2] return True if p0 == "extra": return True except IndexError: return None return False def _serialize_node( obj, # type: Any is_databag=None, # type: Optional[bool] should_repr_strings=None, # type: Optional[bool] segment=None, # type: Optional[Segment] remaining_breadth=None, # type: Optional[int] remaining_depth=None, # type: Optional[int] ): # type: (...) -> Any if segment is not None: path.append(segment) try: with memo.memoize(obj) as result: if result: return CYCLE_MARKER return _serialize_node_impl( obj, is_databag=is_databag, should_repr_strings=should_repr_strings, remaining_depth=remaining_depth, remaining_breadth=remaining_breadth, ) except BaseException: capture_internal_exception(sys.exc_info()) if is_databag: return "<failed to serialize, use init(debug=True) to see error logs>" return None finally: if segment is not None: path.pop() del meta_stack[len(path) + 1 :] def _flatten_annotated(obj): # type: (Any) -> Any if isinstance(obj, AnnotatedValue): _annotate(**obj.metadata) obj = obj.value return obj def _serialize_node_impl( obj, is_databag, should_repr_strings, remaining_depth, remaining_breadth ): # type: (Any, Optional[bool], Optional[bool], Optional[int], Optional[int]) -> Any if should_repr_strings is None: should_repr_strings = _should_repr_strings() if is_databag is None: is_databag = _is_databag() if is_databag and remaining_depth is None: remaining_depth = MAX_DATABAG_DEPTH if is_databag and remaining_breadth is None: remaining_breadth = MAX_DATABAG_BREADTH obj = _flatten_annotated(obj) if remaining_depth is not None and remaining_depth <= 0: _annotate(rem=[["!limit", "x"]]) if is_databag: return _flatten_annotated(strip_string(safe_repr(obj))) return None if is_databag and global_repr_processors: hints = {"memo": memo, "remaining_depth": remaining_depth} for processor in global_repr_processors: result = processor(obj, hints) if result is not NotImplemented: return _flatten_annotated(result) sentry_repr = getattr(type(obj), "__sentry_repr__", None) if obj is None or isinstance(obj, (bool, number_types)): if should_repr_strings or ( isinstance(obj, float) and (math.isinf(obj) or math.isnan(obj)) ): return safe_repr(obj) else: return obj elif callable(sentry_repr): return sentry_repr(obj) elif isinstance(obj, datetime): return ( text_type(format_timestamp(obj)) if not should_repr_strings else safe_repr(obj) ) elif isinstance(obj, Mapping): # Create temporary copy here to avoid calling too much code that # might mutate our dictionary while we're still iterating over it. obj = dict(iteritems(obj)) rv_dict = {} # type: Dict[str, Any] i = 0 for k, v in iteritems(obj): if remaining_breadth is not None and i >= remaining_breadth: _annotate(len=len(obj)) break str_k = text_type(k) v = _serialize_node( v, segment=str_k, should_repr_strings=should_repr_strings, is_databag=is_databag, remaining_depth=remaining_depth - 1 if remaining_depth is not None else None, remaining_breadth=remaining_breadth, ) rv_dict[str_k] = v i += 1 return rv_dict elif not isinstance(obj, serializable_str_types) and isinstance( obj, (Set, Sequence) ): rv_list = [] for i, v in enumerate(obj): if remaining_breadth is not None and i >= remaining_breadth: _annotate(len=len(obj)) break rv_list.append( _serialize_node( v, segment=i, should_repr_strings=should_repr_strings, is_databag=is_databag, remaining_depth=remaining_depth - 1 if remaining_depth is not None else None, remaining_breadth=remaining_breadth, ) ) return rv_list if should_repr_strings: obj = safe_repr(obj) else: if isinstance(obj, bytes) or isinstance(obj, bytearray): obj = obj.decode("utf-8", "replace") if not isinstance(obj, string_types): obj = safe_repr(obj) # Allow span descriptions to be longer than other strings. # # For database auto-instrumented spans, the description contains # potentially long SQL queries that are most useful when not truncated. # Because arbitrarily large events may be discarded by the server as a # protection mechanism, we dynamically limit the description length # later in _truncate_span_descriptions. if ( smart_transaction_trimming and len(path) == 3 and path[0] == "spans" and path[-1] == "description" ): span_description_bytes.append(len(obj)) return obj return _flatten_annotated(strip_string(obj)) def _truncate_span_descriptions(serialized_event, event, excess_bytes): # type: (Event, Event, int) -> None """ Modifies serialized_event in-place trying to remove excess_bytes from span descriptions. The original event is used read-only to access the span timestamps (represented as RFC3399-formatted strings in serialized_event). It uses heuristics to prioritize preserving the description of spans that might be the most interesting ones in terms of understanding and optimizing performance. """ # When truncating a description, preserve a small prefix. min_length = 10 def shortest_duration_longest_description_first(args): # type: (Tuple[int, Span]) -> Tuple[timedelta, int] i, serialized_span = args span = event["spans"][i] now = datetime.utcnow() start = span.get("start_timestamp") or now end = span.get("timestamp") or now duration = end - start description = serialized_span.get("description") or "" return (duration, -len(description)) # Note: for simplicity we sort spans by exact duration and description # length. If ever needed, we could have a more involved heuristic, e.g. # replacing exact durations with "buckets" and/or looking at other span # properties. path.append("spans") for i, span in sorted( enumerate(serialized_event.get("spans") or []), key=shortest_duration_longest_description_first, ): description = span.get("description") or "" if len(description) <= min_length: continue excess_bytes -= len(description) - min_length path.extend([i, "description"]) # Note: the last time we call strip_string we could preserve a few # more bytes up to a total length of MAX_EVENT_BYTES. Since that's # not strictly required, we leave it out for now for simplicity. span["description"] = _flatten_annotated( strip_string(description, max_length=min_length) ) del path[-2:] del meta_stack[len(path) + 1 :] if excess_bytes <= 0: break path.pop() del meta_stack[len(path) + 1 :] disable_capture_event.set(True) try: rv = _serialize_node(event, **kwargs) if meta_stack and isinstance(rv, dict): rv["_meta"] = meta_stack[0] sum_span_description_bytes = sum(span_description_bytes) if smart_transaction_trimming and sum_span_description_bytes > 0: span_count = len(event.get("spans") or []) # This is an upper bound of how many bytes all descriptions would # consume if the usual string truncation in _serialize_node_impl # would have taken place, not accounting for the metadata attached # as event["_meta"]. descriptions_budget_bytes = span_count * sentry_sdk.utils.MAX_STRING_LENGTH # If by not truncating descriptions we ended up with more bytes than # per the usual string truncation, check if the event is too large # and we need to truncate some descriptions. # # This is guarded with an if statement to avoid JSON-encoding the # event unnecessarily. if sum_span_description_bytes > descriptions_budget_bytes: original_bytes = len(json_dumps(rv)) excess_bytes = original_bytes - MAX_EVENT_BYTES if excess_bytes > 0: # Event is too large, will likely be discarded by the # server. Trim it down before sending. _truncate_span_descriptions(rv, event, excess_bytes) # Span descriptions truncated, set or reset _meta. # # We run the same code earlier because we want to account # for _meta when calculating original_bytes, the number of # bytes in the JSON-encoded event. if meta_stack and isinstance(rv, dict): rv["_meta"] = meta_stack[0] return rv finally: disable_capture_event.set(False)
16,573
Python
33.819328
90
0.560792
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/_types.py
try: from typing import TYPE_CHECKING as MYPY except ImportError: MYPY = False if MYPY: from types import TracebackType from typing import Any from typing import Callable from typing import Dict from typing import Optional from typing import Tuple from typing import Type from typing import Union from typing_extensions import Literal ExcInfo = Tuple[ Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType] ] Event = Dict[str, Any] Hint = Dict[str, Any] Breadcrumb = Dict[str, Any] BreadcrumbHint = Dict[str, Any] SamplingContext = Dict[str, Any] EventProcessor = Callable[[Event, Hint], Optional[Event]] ErrorProcessor = Callable[[Event, ExcInfo], Optional[Event]] BreadcrumbProcessor = Callable[[Breadcrumb, BreadcrumbHint], Optional[Breadcrumb]] TransactionProcessor = Callable[[Event, Hint], Optional[Event]] TracesSampler = Callable[[SamplingContext], Union[float, int, bool]] # https://github.com/python/mypy/issues/5710 NotImplementedType = Any EventDataCategory = Literal[ "default", "error", "crash", "transaction", "security", "attachment", "session", "internal", "profile", ] SessionStatus = Literal["ok", "exited", "crashed", "abnormal"] EndpointType = Literal["store", "envelope"] DurationUnit = Literal[ "nanosecond", "microsecond", "millisecond", "second", "minute", "hour", "day", "week", ] InformationUnit = Literal[ "bit", "byte", "kilobyte", "kibibyte", "megabyte", "mebibyte", "gigabyte", "gibibyte", "terabyte", "tebibyte", "petabyte", "pebibyte", "exabyte", "exbibyte", ] FractionUnit = Literal["ratio", "percent"] MeasurementUnit = Union[DurationUnit, InformationUnit, FractionUnit, str]
2,045
Python
23.357143
87
0.602445
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/debug.py
import sys import logging from sentry_sdk import utils from sentry_sdk.hub import Hub from sentry_sdk.utils import logger from sentry_sdk.client import _client_init_debug from logging import LogRecord class _HubBasedClientFilter(logging.Filter): def filter(self, record): # type: (LogRecord) -> bool if _client_init_debug.get(False): return True hub = Hub.current if hub is not None and hub.client is not None: return hub.client.options["debug"] return False def init_debug_support(): # type: () -> None if not logger.handlers: configure_logger() configure_debug_hub() def configure_logger(): # type: () -> None _handler = logging.StreamHandler(sys.stderr) _handler.setFormatter(logging.Formatter(" [sentry] %(levelname)s: %(message)s")) logger.addHandler(_handler) logger.setLevel(logging.DEBUG) logger.addFilter(_HubBasedClientFilter()) def configure_debug_hub(): # type: () -> None def _get_debug_hub(): # type: () -> Hub return Hub.current utils._get_debug_hub = _get_debug_hub
1,132
Python
24.177777
84
0.65106
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/_compat.py
import sys from sentry_sdk._types import MYPY if MYPY: from typing import Optional from typing import Tuple from typing import Any from typing import Type from typing import TypeVar T = TypeVar("T") PY2 = sys.version_info[0] == 2 PY33 = sys.version_info[0] == 3 and sys.version_info[1] >= 3 PY37 = sys.version_info[0] == 3 and sys.version_info[1] >= 7 PY310 = sys.version_info[0] == 3 and sys.version_info[1] >= 10 PY311 = sys.version_info[0] == 3 and sys.version_info[1] >= 11 if PY2: import urlparse text_type = unicode # noqa string_types = (str, text_type) number_types = (int, long, float) # noqa int_types = (int, long) # noqa iteritems = lambda x: x.iteritems() # noqa: B301 binary_sequence_types = (bytearray, memoryview) def implements_str(cls): # type: (T) -> T cls.__unicode__ = cls.__str__ cls.__str__ = lambda x: unicode(x).encode("utf-8") # noqa return cls exec("def reraise(tp, value, tb=None):\n raise tp, value, tb") else: import urllib.parse as urlparse # noqa text_type = str string_types = (text_type,) # type: Tuple[type] number_types = (int, float) # type: Tuple[type, type] int_types = (int,) iteritems = lambda x: x.items() binary_sequence_types = (bytes, bytearray, memoryview) def implements_str(x): # type: (T) -> T return x def reraise(tp, value, tb=None): # type: (Optional[Type[BaseException]], Optional[BaseException], Optional[Any]) -> None assert value is not None if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value def with_metaclass(meta, *bases): # type: (Any, *Any) -> Any class MetaClass(type): def __new__(metacls, name, this_bases, d): # type: (Any, Any, Any, Any) -> Any return meta(name, bases, d) return type.__new__(MetaClass, "temporary_class", (), {}) def check_thread_support(): # type: () -> None try: from uwsgi import opt # type: ignore except ImportError: return # When `threads` is passed in as a uwsgi option, # `enable-threads` is implied on. if "threads" in opt: return if str(opt.get("enable-threads", "0")).lower() in ("false", "off", "no", "0"): from warnings import warn warn( Warning( "We detected the use of uwsgi with disabled threads. " "This will cause issues with the transport you are " "trying to use. Please enable threading for uwsgi. " '(Add the "enable-threads" flag).' ) )
2,702
Python
27.15625
95
0.581421
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/scope.py
from copy import copy from collections import deque from itertools import chain from sentry_sdk._functools import wraps from sentry_sdk._types import MYPY from sentry_sdk.utils import logger, capture_internal_exceptions from sentry_sdk.tracing import Transaction from sentry_sdk.attachments import Attachment if MYPY: from typing import Any from typing import Dict from typing import Optional from typing import Deque from typing import List from typing import Callable from typing import TypeVar from sentry_sdk._types import ( Breadcrumb, Event, EventProcessor, ErrorProcessor, ExcInfo, Hint, Type, ) from sentry_sdk.profiler import Profile from sentry_sdk.tracing import Span from sentry_sdk.session import Session F = TypeVar("F", bound=Callable[..., Any]) T = TypeVar("T") global_event_processors = [] # type: List[EventProcessor] def add_global_event_processor(processor): # type: (EventProcessor) -> None global_event_processors.append(processor) def _attr_setter(fn): # type: (Any) -> Any return property(fset=fn, doc=fn.__doc__) def _disable_capture(fn): # type: (F) -> F @wraps(fn) def wrapper(self, *args, **kwargs): # type: (Any, *Dict[str, Any], **Any) -> Any if not self._should_capture: return try: self._should_capture = False return fn(self, *args, **kwargs) finally: self._should_capture = True return wrapper # type: ignore class Scope(object): """The scope holds extra information that should be sent with all events that belong to it. """ # NOTE: Even though it should not happen, the scope needs to not crash when # accessed by multiple threads. It's fine if it's full of races, but those # races should never make the user application crash. # # The same needs to hold for any accesses of the scope the SDK makes. __slots__ = ( "_level", "_name", "_fingerprint", # note that for legacy reasons, _transaction is the transaction *name*, # not a Transaction object (the object is stored in _span) "_transaction", "_transaction_info", "_user", "_tags", "_contexts", "_extras", "_breadcrumbs", "_event_processors", "_error_processors", "_should_capture", "_span", "_session", "_attachments", "_force_auto_session_tracking", "_profile", ) def __init__(self): # type: () -> None self._event_processors = [] # type: List[EventProcessor] self._error_processors = [] # type: List[ErrorProcessor] self._name = None # type: Optional[str] self.clear() def clear(self): # type: () -> None """Clears the entire scope.""" self._level = None # type: Optional[str] self._fingerprint = None # type: Optional[List[str]] self._transaction = None # type: Optional[str] self._transaction_info = {} # type: Dict[str, str] self._user = None # type: Optional[Dict[str, Any]] self._tags = {} # type: Dict[str, Any] self._contexts = {} # type: Dict[str, Dict[str, Any]] self._extras = {} # type: Dict[str, Any] self._attachments = [] # type: List[Attachment] self.clear_breadcrumbs() self._should_capture = True self._span = None # type: Optional[Span] self._session = None # type: Optional[Session] self._force_auto_session_tracking = None # type: Optional[bool] self._profile = None # type: Optional[Profile] @_attr_setter def level(self, value): # type: (Optional[str]) -> None """When set this overrides the level. Deprecated in favor of set_level.""" self._level = value def set_level(self, value): # type: (Optional[str]) -> None """Sets the level for the scope.""" self._level = value @_attr_setter def fingerprint(self, value): # type: (Optional[List[str]]) -> None """When set this overrides the default fingerprint.""" self._fingerprint = value @property def transaction(self): # type: () -> Any # would be type: () -> Optional[Transaction], see https://github.com/python/mypy/issues/3004 """Return the transaction (root span) in the scope, if any.""" # there is no span/transaction on the scope if self._span is None: return None # there is an orphan span on the scope if self._span.containing_transaction is None: return None # there is either a transaction (which is its own containing # transaction) or a non-orphan span on the scope return self._span.containing_transaction @transaction.setter def transaction(self, value): # type: (Any) -> None # would be type: (Optional[str]) -> None, see https://github.com/python/mypy/issues/3004 """When set this forces a specific transaction name to be set. Deprecated: use set_transaction_name instead.""" # XXX: the docstring above is misleading. The implementation of # apply_to_event prefers an existing value of event.transaction over # anything set in the scope. # XXX: note that with the introduction of the Scope.transaction getter, # there is a semantic and type mismatch between getter and setter. The # getter returns a Transaction, the setter sets a transaction name. # Without breaking version compatibility, we could make the setter set a # transaction name or transaction (self._span) depending on the type of # the value argument. logger.warning( "Assigning to scope.transaction directly is deprecated: use scope.set_transaction_name() instead." ) self._transaction = value if self._span and self._span.containing_transaction: self._span.containing_transaction.name = value def set_transaction_name(self, name, source=None): # type: (str, Optional[str]) -> None """Set the transaction name and optionally the transaction source.""" self._transaction = name if self._span and self._span.containing_transaction: self._span.containing_transaction.name = name if source: self._span.containing_transaction.source = source if source: self._transaction_info["source"] = source @_attr_setter def user(self, value): # type: (Optional[Dict[str, Any]]) -> None """When set a specific user is bound to the scope. Deprecated in favor of set_user.""" self.set_user(value) def set_user(self, value): # type: (Optional[Dict[str, Any]]) -> None """Sets a user for the scope.""" self._user = value if self._session is not None: self._session.update(user=value) @property def span(self): # type: () -> Optional[Span] """Get/set current tracing span or transaction.""" return self._span @span.setter def span(self, span): # type: (Optional[Span]) -> None self._span = span # XXX: this differs from the implementation in JS, there Scope.setSpan # does not set Scope._transactionName. if isinstance(span, Transaction): transaction = span if transaction.name: self._transaction = transaction.name @property def profile(self): # type: () -> Optional[Profile] return self._profile @profile.setter def profile(self, profile): # type: (Optional[Profile]) -> None self._profile = profile def set_tag( self, key, # type: str value, # type: Any ): # type: (...) -> None """Sets a tag for a key to a specific value.""" self._tags[key] = value def remove_tag( self, key # type: str ): # type: (...) -> None """Removes a specific tag.""" self._tags.pop(key, None) def set_context( self, key, # type: str value, # type: Dict[str, Any] ): # type: (...) -> None """Binds a context at a certain key to a specific value.""" self._contexts[key] = value def remove_context( self, key # type: str ): # type: (...) -> None """Removes a context.""" self._contexts.pop(key, None) def set_extra( self, key, # type: str value, # type: Any ): # type: (...) -> None """Sets an extra key to a specific value.""" self._extras[key] = value def remove_extra( self, key # type: str ): # type: (...) -> None """Removes a specific extra key.""" self._extras.pop(key, None) def clear_breadcrumbs(self): # type: () -> None """Clears breadcrumb buffer.""" self._breadcrumbs = deque() # type: Deque[Breadcrumb] def add_attachment( self, bytes=None, # type: Optional[bytes] filename=None, # type: Optional[str] path=None, # type: Optional[str] content_type=None, # type: Optional[str] add_to_transactions=False, # type: bool ): # type: (...) -> None """Adds an attachment to future events sent.""" self._attachments.append( Attachment( bytes=bytes, path=path, filename=filename, content_type=content_type, add_to_transactions=add_to_transactions, ) ) def add_event_processor( self, func # type: EventProcessor ): # type: (...) -> None """Register a scope local event processor on the scope. :param func: This function behaves like `before_send.` """ if len(self._event_processors) > 20: logger.warning( "Too many event processors on scope! Clearing list to free up some memory: %r", self._event_processors, ) del self._event_processors[:] self._event_processors.append(func) def add_error_processor( self, func, # type: ErrorProcessor cls=None, # type: Optional[Type[BaseException]] ): # type: (...) -> None """Register a scope local error processor on the scope. :param func: A callback that works similar to an event processor but is invoked with the original exception info triple as second argument. :param cls: Optionally, only process exceptions of this type. """ if cls is not None: cls_ = cls # For mypy. real_func = func def func(event, exc_info): # type: (Event, ExcInfo) -> Optional[Event] try: is_inst = isinstance(exc_info[1], cls_) except Exception: is_inst = False if is_inst: return real_func(event, exc_info) return event self._error_processors.append(func) @_disable_capture def apply_to_event( self, event, # type: Event hint, # type: Hint ): # type: (...) -> Optional[Event] """Applies the information contained on the scope to the given event.""" def _drop(event, cause, ty): # type: (Dict[str, Any], Any, str) -> Optional[Any] logger.info("%s (%s) dropped event (%s)", ty, cause, event) return None is_transaction = event.get("type") == "transaction" # put all attachments into the hint. This lets callbacks play around # with attachments. We also later pull this out of the hint when we # create the envelope. attachments_to_send = hint.get("attachments") or [] for attachment in self._attachments: if not is_transaction or attachment.add_to_transactions: attachments_to_send.append(attachment) hint["attachments"] = attachments_to_send if self._level is not None: event["level"] = self._level if not is_transaction: event.setdefault("breadcrumbs", {}).setdefault("values", []).extend( self._breadcrumbs ) if event.get("user") is None and self._user is not None: event["user"] = self._user if event.get("transaction") is None and self._transaction is not None: event["transaction"] = self._transaction if event.get("transaction_info") is None and self._transaction_info is not None: event["transaction_info"] = self._transaction_info if event.get("fingerprint") is None and self._fingerprint is not None: event["fingerprint"] = self._fingerprint if self._extras: event.setdefault("extra", {}).update(self._extras) if self._tags: event.setdefault("tags", {}).update(self._tags) if self._contexts: event.setdefault("contexts", {}).update(self._contexts) if self._span is not None: contexts = event.setdefault("contexts", {}) if not contexts.get("trace"): contexts["trace"] = self._span.get_trace_context() exc_info = hint.get("exc_info") if exc_info is not None: for error_processor in self._error_processors: new_event = error_processor(event, exc_info) if new_event is None: return _drop(event, error_processor, "error processor") event = new_event for event_processor in chain(global_event_processors, self._event_processors): new_event = event with capture_internal_exceptions(): new_event = event_processor(event, hint) if new_event is None: return _drop(event, event_processor, "event processor") event = new_event return event def update_from_scope(self, scope): # type: (Scope) -> None if scope._level is not None: self._level = scope._level if scope._fingerprint is not None: self._fingerprint = scope._fingerprint if scope._transaction is not None: self._transaction = scope._transaction if scope._transaction_info is not None: self._transaction_info.update(scope._transaction_info) if scope._user is not None: self._user = scope._user if scope._tags: self._tags.update(scope._tags) if scope._contexts: self._contexts.update(scope._contexts) if scope._extras: self._extras.update(scope._extras) if scope._breadcrumbs: self._breadcrumbs.extend(scope._breadcrumbs) if scope._span: self._span = scope._span if scope._attachments: self._attachments.extend(scope._attachments) if scope._profile: self._profile = scope._profile def update_from_kwargs( self, user=None, # type: Optional[Any] level=None, # type: Optional[str] extras=None, # type: Optional[Dict[str, Any]] contexts=None, # type: Optional[Dict[str, Any]] tags=None, # type: Optional[Dict[str, str]] fingerprint=None, # type: Optional[List[str]] ): # type: (...) -> None if level is not None: self._level = level if user is not None: self._user = user if extras is not None: self._extras.update(extras) if contexts is not None: self._contexts.update(contexts) if tags is not None: self._tags.update(tags) if fingerprint is not None: self._fingerprint = fingerprint def __copy__(self): # type: () -> Scope rv = object.__new__(self.__class__) # type: Scope rv._level = self._level rv._name = self._name rv._fingerprint = self._fingerprint rv._transaction = self._transaction rv._transaction_info = dict(self._transaction_info) rv._user = self._user rv._tags = dict(self._tags) rv._contexts = dict(self._contexts) rv._extras = dict(self._extras) rv._breadcrumbs = copy(self._breadcrumbs) rv._event_processors = list(self._event_processors) rv._error_processors = list(self._error_processors) rv._should_capture = self._should_capture rv._span = self._span rv._session = self._session rv._force_auto_session_tracking = self._force_auto_session_tracking rv._attachments = list(self._attachments) rv._profile = self._profile return rv def __repr__(self): # type: () -> str return "<%s id=%s name=%s>" % ( self.__class__.__name__, hex(id(self)), self._name, )
17,318
Python
31.863378
147
0.568772
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/__init__.py
from sentry_sdk.hub import Hub, init from sentry_sdk.scope import Scope from sentry_sdk.transport import Transport, HttpTransport from sentry_sdk.client import Client from sentry_sdk.api import * # noqa from sentry_sdk.consts import VERSION # noqa __all__ = [ # noqa "Hub", "Scope", "Client", "Transport", "HttpTransport", "init", "integrations", # From sentry_sdk.api "capture_event", "capture_message", "capture_exception", "add_breadcrumb", "configure_scope", "push_scope", "flush", "last_event_id", "start_span", "start_transaction", "set_tag", "set_context", "set_extra", "set_user", "set_level", ] # Initialize the debug support after everything is loaded from sentry_sdk.debug import init_debug_support init_debug_support() del init_debug_support
854
Python
19.853658
57
0.652225
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/utils.py
import base64 import json import linecache import logging import os import re import subprocess import sys import threading import time from datetime import datetime from functools import partial try: from functools import partialmethod _PARTIALMETHOD_AVAILABLE = True except ImportError: _PARTIALMETHOD_AVAILABLE = False import sentry_sdk from sentry_sdk._compat import PY2, PY33, PY37, implements_str, text_type, urlparse from sentry_sdk._types import MYPY if MYPY: from types import FrameType, TracebackType from typing import ( Any, Callable, ContextManager, Dict, Iterator, List, Optional, Set, Tuple, Type, Union, ) from sentry_sdk._types import EndpointType, ExcInfo epoch = datetime(1970, 1, 1) # The logger is created here but initialized in the debug support module logger = logging.getLogger("sentry_sdk.errors") MAX_STRING_LENGTH = 1024 BASE64_ALPHABET = re.compile(r"^[a-zA-Z0-9/+=]*$") def json_dumps(data): # type: (Any) -> bytes """Serialize data into a compact JSON representation encoded as UTF-8.""" return json.dumps(data, allow_nan=False, separators=(",", ":")).encode("utf-8") def _get_debug_hub(): # type: () -> Optional[sentry_sdk.Hub] # This function is replaced by debug.py pass def get_default_release(): # type: () -> Optional[str] """Try to guess a default release.""" release = os.environ.get("SENTRY_RELEASE") if release: return release with open(os.path.devnull, "w+") as null: try: release = ( subprocess.Popen( ["git", "rev-parse", "HEAD"], stdout=subprocess.PIPE, stderr=null, stdin=null, ) .communicate()[0] .strip() .decode("utf-8") ) except (OSError, IOError): pass if release: return release for var in ( "HEROKU_SLUG_COMMIT", "SOURCE_VERSION", "CODEBUILD_RESOLVED_SOURCE_VERSION", "CIRCLE_SHA1", "GAE_DEPLOYMENT_ID", ): release = os.environ.get(var) if release: return release return None def get_sdk_name(installed_integrations): # type: (List[str]) -> str """Return the SDK name including the name of the used web framework.""" # Note: I can not use for example sentry_sdk.integrations.django.DjangoIntegration.identifier # here because if django is not installed the integration is not accessible. framework_integrations = [ "django", "flask", "fastapi", "bottle", "falcon", "quart", "sanic", "starlette", "chalice", "serverless", "pyramid", "tornado", "aiohttp", "aws_lambda", "gcp", "beam", "asgi", "wsgi", ] for integration in framework_integrations: if integration in installed_integrations: return "sentry.python.{}".format(integration) return "sentry.python" class CaptureInternalException(object): __slots__ = () def __enter__(self): # type: () -> ContextManager[Any] return self def __exit__(self, ty, value, tb): # type: (Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]) -> bool if ty is not None and value is not None: capture_internal_exception((ty, value, tb)) return True _CAPTURE_INTERNAL_EXCEPTION = CaptureInternalException() def capture_internal_exceptions(): # type: () -> ContextManager[Any] return _CAPTURE_INTERNAL_EXCEPTION def capture_internal_exception(exc_info): # type: (ExcInfo) -> None hub = _get_debug_hub() if hub is not None: hub._capture_internal_exception(exc_info) def to_timestamp(value): # type: (datetime) -> float return (value - epoch).total_seconds() def format_timestamp(value): # type: (datetime) -> str return value.strftime("%Y-%m-%dT%H:%M:%S.%fZ") def event_hint_with_exc_info(exc_info=None): # type: (Optional[ExcInfo]) -> Dict[str, Optional[ExcInfo]] """Creates a hint with the exc info filled in.""" if exc_info is None: exc_info = sys.exc_info() else: exc_info = exc_info_from_error(exc_info) if exc_info[0] is None: exc_info = None return {"exc_info": exc_info} class BadDsn(ValueError): """Raised on invalid DSNs.""" @implements_str class Dsn(object): """Represents a DSN.""" def __init__(self, value): # type: (Union[Dsn, str]) -> None if isinstance(value, Dsn): self.__dict__ = dict(value.__dict__) return parts = urlparse.urlsplit(text_type(value)) if parts.scheme not in ("http", "https"): raise BadDsn("Unsupported scheme %r" % parts.scheme) self.scheme = parts.scheme if parts.hostname is None: raise BadDsn("Missing hostname") self.host = parts.hostname if parts.port is None: self.port = self.scheme == "https" and 443 or 80 # type: int else: self.port = parts.port if not parts.username: raise BadDsn("Missing public key") self.public_key = parts.username self.secret_key = parts.password path = parts.path.rsplit("/", 1) try: self.project_id = text_type(int(path.pop())) except (ValueError, TypeError): raise BadDsn("Invalid project in DSN (%r)" % (parts.path or "")[1:]) self.path = "/".join(path) + "/" @property def netloc(self): # type: () -> str """The netloc part of a DSN.""" rv = self.host if (self.scheme, self.port) not in (("http", 80), ("https", 443)): rv = "%s:%s" % (rv, self.port) return rv def to_auth(self, client=None): # type: (Optional[Any]) -> Auth """Returns the auth info object for this dsn.""" return Auth( scheme=self.scheme, host=self.netloc, path=self.path, project_id=self.project_id, public_key=self.public_key, secret_key=self.secret_key, client=client, ) def __str__(self): # type: () -> str return "%s://%s%s@%s%s%s" % ( self.scheme, self.public_key, self.secret_key and "@" + self.secret_key or "", self.netloc, self.path, self.project_id, ) class Auth(object): """Helper object that represents the auth info.""" def __init__( self, scheme, host, project_id, public_key, secret_key=None, version=7, client=None, path="/", ): # type: (str, str, str, str, Optional[str], int, Optional[Any], str) -> None self.scheme = scheme self.host = host self.path = path self.project_id = project_id self.public_key = public_key self.secret_key = secret_key self.version = version self.client = client @property def store_api_url(self): # type: () -> str """Returns the API url for storing events. Deprecated: use get_api_url instead. """ return self.get_api_url(type="store") def get_api_url( self, type="store" # type: EndpointType ): # type: (...) -> str """Returns the API url for storing events.""" return "%s://%s%sapi/%s/%s/" % ( self.scheme, self.host, self.path, self.project_id, type, ) def to_header(self): # type: () -> str """Returns the auth header a string.""" rv = [("sentry_key", self.public_key), ("sentry_version", self.version)] if self.client is not None: rv.append(("sentry_client", self.client)) if self.secret_key is not None: rv.append(("sentry_secret", self.secret_key)) return "Sentry " + ", ".join("%s=%s" % (key, value) for key, value in rv) class AnnotatedValue(object): """ Meta information for a data field in the event payload. This is to tell Relay that we have tampered with the fields value. See: https://github.com/getsentry/relay/blob/be12cd49a0f06ea932ed9b9f93a655de5d6ad6d1/relay-general/src/types/meta.rs#L407-L423 """ __slots__ = ("value", "metadata") def __init__(self, value, metadata): # type: (Optional[Any], Dict[str, Any]) -> None self.value = value self.metadata = metadata @classmethod def removed_because_raw_data(cls): # type: () -> AnnotatedValue """The value was removed because it could not be parsed. This is done for request body values that are not json nor a form.""" return AnnotatedValue( value="", metadata={ "rem": [ # Remark [ "!raw", # Unparsable raw data "x", # The fields original value was removed ] ] }, ) @classmethod def removed_because_over_size_limit(cls): # type: () -> AnnotatedValue """The actual value was removed because the size of the field exceeded the configured maximum size (specified with the request_bodies sdk option)""" return AnnotatedValue( value="", metadata={ "rem": [ # Remark [ "!config", # Because of configured maximum size "x", # The fields original value was removed ] ] }, ) @classmethod def substituted_because_contains_sensitive_data(cls): # type: () -> AnnotatedValue """The actual value was removed because it contained sensitive information.""" from sentry_sdk.consts import SENSITIVE_DATA_SUBSTITUTE return AnnotatedValue( value=SENSITIVE_DATA_SUBSTITUTE, metadata={ "rem": [ # Remark [ "!config", # Because of SDK configuration (in this case the config is the hard coded removal of certain django cookies) "s", # The fields original value was substituted ] ] }, ) if MYPY: from typing import TypeVar T = TypeVar("T") Annotated = Union[AnnotatedValue, T] def get_type_name(cls): # type: (Optional[type]) -> Optional[str] return getattr(cls, "__qualname__", None) or getattr(cls, "__name__", None) def get_type_module(cls): # type: (Optional[type]) -> Optional[str] mod = getattr(cls, "__module__", None) if mod not in (None, "builtins", "__builtins__"): return mod return None def should_hide_frame(frame): # type: (FrameType) -> bool try: mod = frame.f_globals["__name__"] if mod.startswith("sentry_sdk."): return True except (AttributeError, KeyError): pass for flag_name in "__traceback_hide__", "__tracebackhide__": try: if frame.f_locals[flag_name]: return True except Exception: pass return False def iter_stacks(tb): # type: (Optional[TracebackType]) -> Iterator[TracebackType] tb_ = tb # type: Optional[TracebackType] while tb_ is not None: if not should_hide_frame(tb_.tb_frame): yield tb_ tb_ = tb_.tb_next def get_lines_from_file( filename, # type: str lineno, # type: int loader=None, # type: Optional[Any] module=None, # type: Optional[str] ): # type: (...) -> Tuple[List[Annotated[str]], Optional[Annotated[str]], List[Annotated[str]]] context_lines = 5 source = None if loader is not None and hasattr(loader, "get_source"): try: source_str = loader.get_source(module) # type: Optional[str] except (ImportError, IOError): source_str = None if source_str is not None: source = source_str.splitlines() if source is None: try: source = linecache.getlines(filename) except (OSError, IOError): return [], None, [] if not source: return [], None, [] lower_bound = max(0, lineno - context_lines) upper_bound = min(lineno + 1 + context_lines, len(source)) try: pre_context = [ strip_string(line.strip("\r\n")) for line in source[lower_bound:lineno] ] context_line = strip_string(source[lineno].strip("\r\n")) post_context = [ strip_string(line.strip("\r\n")) for line in source[(lineno + 1) : upper_bound] ] return pre_context, context_line, post_context except IndexError: # the file may have changed since it was loaded into memory return [], None, [] def get_source_context( frame, # type: FrameType tb_lineno, # type: int ): # type: (...) -> Tuple[List[Annotated[str]], Optional[Annotated[str]], List[Annotated[str]]] try: abs_path = frame.f_code.co_filename # type: Optional[str] except Exception: abs_path = None try: module = frame.f_globals["__name__"] except Exception: return [], None, [] try: loader = frame.f_globals["__loader__"] except Exception: loader = None lineno = tb_lineno - 1 if lineno is not None and abs_path: return get_lines_from_file(abs_path, lineno, loader, module) return [], None, [] def safe_str(value): # type: (Any) -> str try: return text_type(value) except Exception: return safe_repr(value) if PY2: def safe_repr(value): # type: (Any) -> str try: rv = repr(value).decode("utf-8", "replace") # At this point `rv` contains a bunch of literal escape codes, like # this (exaggerated example): # # u"\\x2f" # # But we want to show this string as: # # u"/" try: # unicode-escape does this job, but can only decode latin1. So we # attempt to encode in latin1. return rv.encode("latin1").decode("unicode-escape") except Exception: # Since usually strings aren't latin1 this can break. In those # cases we just give up. return rv except Exception: # If e.g. the call to `repr` already fails return "<broken repr>" else: def safe_repr(value): # type: (Any) -> str try: return repr(value) except Exception: return "<broken repr>" def filename_for_module(module, abs_path): # type: (Optional[str], Optional[str]) -> Optional[str] if not abs_path or not module: return abs_path try: if abs_path.endswith(".pyc"): abs_path = abs_path[:-1] base_module = module.split(".", 1)[0] if base_module == module: return os.path.basename(abs_path) base_module_path = sys.modules[base_module].__file__ if not base_module_path: return abs_path return abs_path.split(base_module_path.rsplit(os.sep, 2)[0], 1)[-1].lstrip( os.sep ) except Exception: return abs_path def serialize_frame(frame, tb_lineno=None, with_locals=True): # type: (FrameType, Optional[int], bool) -> Dict[str, Any] f_code = getattr(frame, "f_code", None) if not f_code: abs_path = None function = None else: abs_path = frame.f_code.co_filename function = frame.f_code.co_name try: module = frame.f_globals["__name__"] except Exception: module = None if tb_lineno is None: tb_lineno = frame.f_lineno pre_context, context_line, post_context = get_source_context(frame, tb_lineno) rv = { "filename": filename_for_module(module, abs_path) or None, "abs_path": os.path.abspath(abs_path) if abs_path else None, "function": function or "<unknown>", "module": module, "lineno": tb_lineno, "pre_context": pre_context, "context_line": context_line, "post_context": post_context, } # type: Dict[str, Any] if with_locals: rv["vars"] = frame.f_locals return rv def current_stacktrace(with_locals=True): # type: (bool) -> Any __tracebackhide__ = True frames = [] f = sys._getframe() # type: Optional[FrameType] while f is not None: if not should_hide_frame(f): frames.append(serialize_frame(f, with_locals=with_locals)) f = f.f_back frames.reverse() return {"frames": frames} def get_errno(exc_value): # type: (BaseException) -> Optional[Any] return getattr(exc_value, "errno", None) def single_exception_from_error_tuple( exc_type, # type: Optional[type] exc_value, # type: Optional[BaseException] tb, # type: Optional[TracebackType] client_options=None, # type: Optional[Dict[str, Any]] mechanism=None, # type: Optional[Dict[str, Any]] ): # type: (...) -> Dict[str, Any] if exc_value is not None: errno = get_errno(exc_value) else: errno = None if errno is not None: mechanism = mechanism or {"type": "generic"} mechanism.setdefault("meta", {}).setdefault("errno", {}).setdefault( "number", errno ) if client_options is None: with_locals = True else: with_locals = client_options["with_locals"] frames = [ serialize_frame(tb.tb_frame, tb_lineno=tb.tb_lineno, with_locals=with_locals) for tb in iter_stacks(tb) ] rv = { "module": get_type_module(exc_type), "type": get_type_name(exc_type), "value": safe_str(exc_value), "mechanism": mechanism, } if frames: rv["stacktrace"] = {"frames": frames} return rv HAS_CHAINED_EXCEPTIONS = hasattr(Exception, "__suppress_context__") if HAS_CHAINED_EXCEPTIONS: def walk_exception_chain(exc_info): # type: (ExcInfo) -> Iterator[ExcInfo] exc_type, exc_value, tb = exc_info seen_exceptions = [] seen_exception_ids = set() # type: Set[int] while ( exc_type is not None and exc_value is not None and id(exc_value) not in seen_exception_ids ): yield exc_type, exc_value, tb # Avoid hashing random types we don't know anything # about. Use the list to keep a ref so that the `id` is # not used for another object. seen_exceptions.append(exc_value) seen_exception_ids.add(id(exc_value)) if exc_value.__suppress_context__: cause = exc_value.__cause__ else: cause = exc_value.__context__ if cause is None: break exc_type = type(cause) exc_value = cause tb = getattr(cause, "__traceback__", None) else: def walk_exception_chain(exc_info): # type: (ExcInfo) -> Iterator[ExcInfo] yield exc_info def exceptions_from_error_tuple( exc_info, # type: ExcInfo client_options=None, # type: Optional[Dict[str, Any]] mechanism=None, # type: Optional[Dict[str, Any]] ): # type: (...) -> List[Dict[str, Any]] exc_type, exc_value, tb = exc_info rv = [] for exc_type, exc_value, tb in walk_exception_chain(exc_info): rv.append( single_exception_from_error_tuple( exc_type, exc_value, tb, client_options, mechanism ) ) rv.reverse() return rv def to_string(value): # type: (str) -> str try: return text_type(value) except UnicodeDecodeError: return repr(value)[1:-1] def iter_event_stacktraces(event): # type: (Dict[str, Any]) -> Iterator[Dict[str, Any]] if "stacktrace" in event: yield event["stacktrace"] if "threads" in event: for thread in event["threads"].get("values") or (): if "stacktrace" in thread: yield thread["stacktrace"] if "exception" in event: for exception in event["exception"].get("values") or (): if "stacktrace" in exception: yield exception["stacktrace"] def iter_event_frames(event): # type: (Dict[str, Any]) -> Iterator[Dict[str, Any]] for stacktrace in iter_event_stacktraces(event): for frame in stacktrace.get("frames") or (): yield frame def handle_in_app(event, in_app_exclude=None, in_app_include=None): # type: (Dict[str, Any], Optional[List[str]], Optional[List[str]]) -> Dict[str, Any] for stacktrace in iter_event_stacktraces(event): handle_in_app_impl( stacktrace.get("frames"), in_app_exclude=in_app_exclude, in_app_include=in_app_include, ) return event def handle_in_app_impl(frames, in_app_exclude, in_app_include): # type: (Any, Optional[List[str]], Optional[List[str]]) -> Optional[Any] if not frames: return None any_in_app = False for frame in frames: in_app = frame.get("in_app") if in_app is not None: if in_app: any_in_app = True continue module = frame.get("module") if not module: continue elif _module_in_set(module, in_app_include): frame["in_app"] = True any_in_app = True elif _module_in_set(module, in_app_exclude): frame["in_app"] = False if not any_in_app: for frame in frames: if frame.get("in_app") is None: frame["in_app"] = True return frames def exc_info_from_error(error): # type: (Union[BaseException, ExcInfo]) -> ExcInfo if isinstance(error, tuple) and len(error) == 3: exc_type, exc_value, tb = error elif isinstance(error, BaseException): tb = getattr(error, "__traceback__", None) if tb is not None: exc_type = type(error) exc_value = error else: exc_type, exc_value, tb = sys.exc_info() if exc_value is not error: tb = None exc_value = error exc_type = type(error) else: raise ValueError("Expected Exception object to report, got %s!" % type(error)) return exc_type, exc_value, tb def event_from_exception( exc_info, # type: Union[BaseException, ExcInfo] client_options=None, # type: Optional[Dict[str, Any]] mechanism=None, # type: Optional[Dict[str, Any]] ): # type: (...) -> Tuple[Dict[str, Any], Dict[str, Any]] exc_info = exc_info_from_error(exc_info) hint = event_hint_with_exc_info(exc_info) return ( { "level": "error", "exception": { "values": exceptions_from_error_tuple( exc_info, client_options, mechanism ) }, }, hint, ) def _module_in_set(name, set): # type: (str, Optional[List[str]]) -> bool if not set: return False for item in set or (): if item == name or name.startswith(item + "."): return True return False def strip_string(value, max_length=None): # type: (str, Optional[int]) -> Union[AnnotatedValue, str] # TODO: read max_length from config if not value: return value if max_length is None: # This is intentionally not just the default such that one can patch `MAX_STRING_LENGTH` and affect `strip_string`. max_length = MAX_STRING_LENGTH length = len(value.encode("utf-8")) if length > max_length: return AnnotatedValue( value=value[: max_length - 3] + "...", metadata={ "len": length, "rem": [["!limit", "x", max_length - 3, max_length]], }, ) return value def _is_contextvars_broken(): # type: () -> bool """ Returns whether gevent/eventlet have patched the stdlib in a way where thread locals are now more "correct" than contextvars. """ try: import gevent # type: ignore from gevent.monkey import is_object_patched # type: ignore # Get the MAJOR and MINOR version numbers of Gevent version_tuple = tuple( [int(part) for part in re.split(r"a|b|rc|\.", gevent.__version__)[:2]] ) if is_object_patched("threading", "local"): # Gevent 20.9.0 depends on Greenlet 0.4.17 which natively handles switching # context vars when greenlets are switched, so, Gevent 20.9.0+ is all fine. # Ref: https://github.com/gevent/gevent/blob/83c9e2ae5b0834b8f84233760aabe82c3ba065b4/src/gevent/monkey.py#L604-L609 # Gevent 20.5, that doesn't depend on Greenlet 0.4.17 with native support # for contextvars, is able to patch both thread locals and contextvars, in # that case, check if contextvars are effectively patched. if ( # Gevent 20.9.0+ (sys.version_info >= (3, 7) and version_tuple >= (20, 9)) # Gevent 20.5.0+ or Python < 3.7 or (is_object_patched("contextvars", "ContextVar")) ): return False return True except ImportError: pass try: from eventlet.patcher import is_monkey_patched # type: ignore if is_monkey_patched("thread"): return True except ImportError: pass return False def _make_threadlocal_contextvars(local): # type: (type) -> type class ContextVar(object): # Super-limited impl of ContextVar def __init__(self, name): # type: (str) -> None self._name = name self._local = local() def get(self, default): # type: (Any) -> Any return getattr(self._local, "value", default) def set(self, value): # type: (Any) -> None self._local.value = value return ContextVar def _get_contextvars(): # type: () -> Tuple[bool, type] """ Figure out the "right" contextvars installation to use. Returns a `contextvars.ContextVar`-like class with a limited API. See https://docs.sentry.io/platforms/python/contextvars/ for more information. """ if not _is_contextvars_broken(): # aiocontextvars is a PyPI package that ensures that the contextvars # backport (also a PyPI package) works with asyncio under Python 3.6 # # Import it if available. if sys.version_info < (3, 7): # `aiocontextvars` is absolutely required for functional # contextvars on Python 3.6. try: from aiocontextvars import ContextVar return True, ContextVar except ImportError: pass else: # On Python 3.7 contextvars are functional. try: from contextvars import ContextVar return True, ContextVar except ImportError: pass # Fall back to basic thread-local usage. from threading import local return False, _make_threadlocal_contextvars(local) HAS_REAL_CONTEXTVARS, ContextVar = _get_contextvars() CONTEXTVARS_ERROR_MESSAGE = """ With asyncio/ASGI applications, the Sentry SDK requires a functional installation of `contextvars` to avoid leaking scope/context data across requests. Please refer to https://docs.sentry.io/platforms/python/contextvars/ for more information. """ def qualname_from_function(func): # type: (Callable[..., Any]) -> Optional[str] """Return the qualified name of func. Works with regular function, lambda, partial and partialmethod.""" func_qualname = None # type: Optional[str] # Python 2 try: return "%s.%s.%s" % ( func.im_class.__module__, # type: ignore func.im_class.__name__, # type: ignore func.__name__, ) except Exception: pass prefix, suffix = "", "" if ( _PARTIALMETHOD_AVAILABLE and hasattr(func, "_partialmethod") and isinstance(func._partialmethod, partialmethod) # type: ignore ): prefix, suffix = "partialmethod(<function ", ">)" func = func._partialmethod.func # type: ignore elif isinstance(func, partial) and hasattr(func.func, "__name__"): prefix, suffix = "partial(<function ", ">)" func = func.func if hasattr(func, "__qualname__"): func_qualname = func.__qualname__ elif hasattr(func, "__name__"): # Python 2.7 has no __qualname__ func_qualname = func.__name__ # Python 3: methods, functions, classes if func_qualname is not None: if hasattr(func, "__module__"): func_qualname = func.__module__ + "." + func_qualname func_qualname = prefix + func_qualname + suffix return func_qualname def transaction_from_function(func): # type: (Callable[..., Any]) -> Optional[str] return qualname_from_function(func) disable_capture_event = ContextVar("disable_capture_event") class ServerlessTimeoutWarning(Exception): # noqa: N818 """Raised when a serverless method is about to reach its timeout.""" pass class TimeoutThread(threading.Thread): """Creates a Thread which runs (sleeps) for a time duration equal to waiting_time and raises a custom ServerlessTimeout exception. """ def __init__(self, waiting_time, configured_timeout): # type: (float, int) -> None threading.Thread.__init__(self) self.waiting_time = waiting_time self.configured_timeout = configured_timeout self._stop_event = threading.Event() def stop(self): # type: () -> None self._stop_event.set() def run(self): # type: () -> None self._stop_event.wait(self.waiting_time) if self._stop_event.is_set(): return integer_configured_timeout = int(self.configured_timeout) # Setting up the exact integer value of configured time(in seconds) if integer_configured_timeout < self.configured_timeout: integer_configured_timeout = integer_configured_timeout + 1 # Raising Exception after timeout duration is reached raise ServerlessTimeoutWarning( "WARNING : Function is expected to get timed out. Configured timeout duration = {} seconds.".format( integer_configured_timeout ) ) def to_base64(original): # type: (str) -> Optional[str] """ Convert a string to base64, via UTF-8. Returns None on invalid input. """ base64_string = None try: utf8_bytes = original.encode("UTF-8") base64_bytes = base64.b64encode(utf8_bytes) base64_string = base64_bytes.decode("UTF-8") except Exception as err: logger.warning("Unable to encode {orig} to base64:".format(orig=original), err) return base64_string def from_base64(base64_string): # type: (str) -> Optional[str] """ Convert a string from base64, via UTF-8. Returns None on invalid input. """ utf8_string = None try: only_valid_chars = BASE64_ALPHABET.match(base64_string) assert only_valid_chars base64_bytes = base64_string.encode("UTF-8") utf8_bytes = base64.b64decode(base64_bytes) utf8_string = utf8_bytes.decode("UTF-8") except Exception as err: logger.warning( "Unable to decode {b64} from base64:".format(b64=base64_string), err ) return utf8_string if PY37: def nanosecond_time(): # type: () -> int return time.perf_counter_ns() elif PY33: def nanosecond_time(): # type: () -> int return int(time.perf_counter() * 1e9) else: def nanosecond_time(): # type: () -> int raise AttributeError
32,694
Python
27.479965
156
0.566159
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/consts.py
from sentry_sdk._types import MYPY if MYPY: import sentry_sdk from typing import Optional from typing import Callable from typing import Union from typing import List from typing import Type from typing import Dict from typing import Any from typing import Sequence from typing_extensions import TypedDict from sentry_sdk.integrations import Integration from sentry_sdk._types import ( BreadcrumbProcessor, Event, EventProcessor, TracesSampler, TransactionProcessor, ) # Experiments are feature flags to enable and disable certain unstable SDK # functionality. Changing them from the defaults (`None`) in production # code is highly discouraged. They are not subject to any stability # guarantees such as the ones from semantic versioning. Experiments = TypedDict( "Experiments", { "max_spans": Optional[int], "record_sql_params": Optional[bool], "smart_transaction_trimming": Optional[bool], "propagate_tracestate": Optional[bool], "custom_measurements": Optional[bool], "profiles_sample_rate": Optional[float], "profiler_mode": Optional[str], }, total=False, ) DEFAULT_QUEUE_SIZE = 100 DEFAULT_MAX_BREADCRUMBS = 100 SENSITIVE_DATA_SUBSTITUTE = "[Filtered]" class INSTRUMENTER: SENTRY = "sentry" OTEL = "otel" class OP: DB = "db" DB_REDIS = "db.redis" EVENT_DJANGO = "event.django" FUNCTION = "function" FUNCTION_AWS = "function.aws" FUNCTION_GCP = "function.gcp" HTTP_CLIENT = "http.client" HTTP_CLIENT_STREAM = "http.client.stream" HTTP_SERVER = "http.server" MIDDLEWARE_DJANGO = "middleware.django" MIDDLEWARE_STARLETTE = "middleware.starlette" MIDDLEWARE_STARLETTE_RECEIVE = "middleware.starlette.receive" MIDDLEWARE_STARLETTE_SEND = "middleware.starlette.send" MIDDLEWARE_STARLITE = "middleware.starlite" MIDDLEWARE_STARLITE_RECEIVE = "middleware.starlite.receive" MIDDLEWARE_STARLITE_SEND = "middleware.starlite.send" QUEUE_SUBMIT_CELERY = "queue.submit.celery" QUEUE_TASK_CELERY = "queue.task.celery" QUEUE_TASK_RQ = "queue.task.rq" SUBPROCESS = "subprocess" SUBPROCESS_WAIT = "subprocess.wait" SUBPROCESS_COMMUNICATE = "subprocess.communicate" TEMPLATE_RENDER = "template.render" VIEW_RENDER = "view.render" VIEW_RESPONSE_RENDER = "view.response.render" WEBSOCKET_SERVER = "websocket.server" # This type exists to trick mypy and PyCharm into thinking `init` and `Client` # take these arguments (even though they take opaque **kwargs) class ClientConstructor(object): def __init__( self, dsn=None, # type: Optional[str] with_locals=True, # type: bool max_breadcrumbs=DEFAULT_MAX_BREADCRUMBS, # type: int release=None, # type: Optional[str] environment=None, # type: Optional[str] server_name=None, # type: Optional[str] shutdown_timeout=2, # type: float integrations=[], # type: Sequence[Integration] # noqa: B006 in_app_include=[], # type: List[str] # noqa: B006 in_app_exclude=[], # type: List[str] # noqa: B006 default_integrations=True, # type: bool dist=None, # type: Optional[str] transport=None, # type: Optional[Union[sentry_sdk.transport.Transport, Type[sentry_sdk.transport.Transport], Callable[[Event], None]]] transport_queue_size=DEFAULT_QUEUE_SIZE, # type: int sample_rate=1.0, # type: float send_default_pii=False, # type: bool http_proxy=None, # type: Optional[str] https_proxy=None, # type: Optional[str] ignore_errors=[], # type: List[Union[type, str]] # noqa: B006 request_bodies="medium", # type: str before_send=None, # type: Optional[EventProcessor] before_breadcrumb=None, # type: Optional[BreadcrumbProcessor] debug=False, # type: bool attach_stacktrace=False, # type: bool ca_certs=None, # type: Optional[str] propagate_traces=True, # type: bool traces_sample_rate=None, # type: Optional[float] traces_sampler=None, # type: Optional[TracesSampler] auto_enabling_integrations=True, # type: bool auto_session_tracking=True, # type: bool send_client_reports=True, # type: bool _experiments={}, # type: Experiments # noqa: B006 proxy_headers=None, # type: Optional[Dict[str, str]] instrumenter=INSTRUMENTER.SENTRY, # type: Optional[str] before_send_transaction=None, # type: Optional[TransactionProcessor] ): # type: (...) -> None pass def _get_default_options(): # type: () -> Dict[str, Any] import inspect if hasattr(inspect, "getfullargspec"): getargspec = inspect.getfullargspec else: getargspec = inspect.getargspec # type: ignore a = getargspec(ClientConstructor.__init__) defaults = a.defaults or () return dict(zip(a.args[-len(defaults) :], defaults)) DEFAULT_OPTIONS = _get_default_options() del _get_default_options VERSION = "1.14.0"
5,236
Python
34.385135
143
0.648587
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/attachments.py
import os import mimetypes from sentry_sdk._types import MYPY from sentry_sdk.envelope import Item, PayloadRef if MYPY: from typing import Optional, Union, Callable class Attachment(object): def __init__( self, bytes=None, # type: Union[None, bytes, Callable[[], bytes]] filename=None, # type: Optional[str] path=None, # type: Optional[str] content_type=None, # type: Optional[str] add_to_transactions=False, # type: bool ): # type: (...) -> None if bytes is None and path is None: raise TypeError("path or raw bytes required for attachment") if filename is None and path is not None: filename = os.path.basename(path) if filename is None: raise TypeError("filename is required for attachment") if content_type is None: content_type = mimetypes.guess_type(filename)[0] self.bytes = bytes self.filename = filename self.path = path self.content_type = content_type self.add_to_transactions = add_to_transactions def to_envelope_item(self): # type: () -> Item """Returns an envelope item for this attachment.""" payload = None # type: Union[None, PayloadRef, bytes] if self.bytes is not None: if callable(self.bytes): payload = self.bytes() else: payload = self.bytes else: payload = PayloadRef(path=self.path) return Item( payload=payload, type="attachment", content_type=self.content_type, filename=self.filename, ) def __repr__(self): # type: () -> str return "<Attachment %r>" % (self.filename,)
1,793
Python
31.035714
72
0.575014
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/tracing_utils.py
import re import contextlib import json import math from numbers import Real from decimal import Decimal import sentry_sdk from sentry_sdk.consts import OP from sentry_sdk.utils import ( capture_internal_exceptions, Dsn, logger, safe_str, to_base64, to_string, from_base64, ) from sentry_sdk._compat import PY2, iteritems from sentry_sdk._types import MYPY if PY2: from collections import Mapping from urllib import quote, unquote else: from collections.abc import Mapping from urllib.parse import quote, unquote if MYPY: import typing from typing import Generator from typing import Optional from typing import Any from typing import Dict from typing import Union SENTRY_TRACE_REGEX = re.compile( "^[ \t]*" # whitespace "([0-9a-f]{32})?" # trace_id "-?([0-9a-f]{16})?" # span_id "-?([01])?" # sampled "[ \t]*$" # whitespace ) # This is a normal base64 regex, modified to reflect that fact that we strip the # trailing = or == off base64_stripped = ( # any of the characters in the base64 "alphabet", in multiples of 4 "([a-zA-Z0-9+/]{4})*" # either nothing or 2 or 3 base64-alphabet characters (see # https://en.wikipedia.org/wiki/Base64#Decoding_Base64_without_padding for # why there's never only 1 extra character) "([a-zA-Z0-9+/]{2,3})?" ) # comma-delimited list of entries of the form `xxx=yyy` tracestate_entry = "[^=]+=[^=]+" TRACESTATE_ENTRIES_REGEX = re.compile( # one or more xxxxx=yyyy entries "^({te})+" # each entry except the last must be followed by a comma "(,|$)".format(te=tracestate_entry) ) # this doesn't check that the value is valid, just that there's something there # of the form `sentry=xxxx` SENTRY_TRACESTATE_ENTRY_REGEX = re.compile( # either sentry is the first entry or there's stuff immediately before it, # ending in a comma (this prevents matching something like `coolsentry=xxx`) "(?:^|.+,)" # sentry's part, not including the potential comma "(sentry=[^,]*)" # either there's a comma and another vendor's entry or we end "(?:,.+|$)" ) class EnvironHeaders(Mapping): # type: ignore def __init__( self, environ, # type: typing.Mapping[str, str] prefix="HTTP_", # type: str ): # type: (...) -> None self.environ = environ self.prefix = prefix def __getitem__(self, key): # type: (str) -> Optional[Any] return self.environ[self.prefix + key.replace("-", "_").upper()] def __len__(self): # type: () -> int return sum(1 for _ in iter(self)) def __iter__(self): # type: () -> Generator[str, None, None] for k in self.environ: if not isinstance(k, str): continue k = k.replace("-", "_").upper() if not k.startswith(self.prefix): continue yield k[len(self.prefix) :] def has_tracing_enabled(options): # type: (Dict[str, Any]) -> bool """ Returns True if either traces_sample_rate or traces_sampler is defined, False otherwise. """ return bool( options.get("traces_sample_rate") is not None or options.get("traces_sampler") is not None ) def is_valid_sample_rate(rate): # type: (Any) -> bool """ Checks the given sample rate to make sure it is valid type and value (a boolean or a number between 0 and 1, inclusive). """ # both booleans and NaN are instances of Real, so a) checking for Real # checks for the possibility of a boolean also, and b) we have to check # separately for NaN and Decimal does not derive from Real so need to check that too if not isinstance(rate, (Real, Decimal)) or math.isnan(rate): logger.warning( "[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got {rate} of type {type}.".format( rate=rate, type=type(rate) ) ) return False # in case rate is a boolean, it will get cast to 1 if it's True and 0 if it's False rate = float(rate) if rate < 0 or rate > 1: logger.warning( "[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got {rate}.".format( rate=rate ) ) return False return True @contextlib.contextmanager def record_sql_queries( hub, # type: sentry_sdk.Hub cursor, # type: Any query, # type: Any params_list, # type: Any paramstyle, # type: Optional[str] executemany, # type: bool ): # type: (...) -> Generator[Span, None, None] # TODO: Bring back capturing of params by default if hub.client and hub.client.options["_experiments"].get( "record_sql_params", False ): if not params_list or params_list == [None]: params_list = None if paramstyle == "pyformat": paramstyle = "format" else: params_list = None paramstyle = None query = _format_sql(cursor, query) data = {} if params_list is not None: data["db.params"] = params_list if paramstyle is not None: data["db.paramstyle"] = paramstyle if executemany: data["db.executemany"] = True with capture_internal_exceptions(): hub.add_breadcrumb(message=query, category="query", data=data) with hub.start_span(op=OP.DB, description=query) as span: for k, v in data.items(): span.set_data(k, v) yield span def maybe_create_breadcrumbs_from_span(hub, span): # type: (sentry_sdk.Hub, Span) -> None if span.op == OP.DB_REDIS: hub.add_breadcrumb( message=span.description, type="redis", category="redis", data=span._tags ) elif span.op == OP.HTTP_CLIENT: hub.add_breadcrumb(type="http", category="httplib", data=span._data) elif span.op == "subprocess": hub.add_breadcrumb( type="subprocess", category="subprocess", message=span.description, data=span._data, ) def extract_sentrytrace_data(header): # type: (Optional[str]) -> Optional[typing.Mapping[str, Union[str, bool, None]]] """ Given a `sentry-trace` header string, return a dictionary of data. """ if not header: return None if header.startswith("00-") and header.endswith("-00"): header = header[3:-3] match = SENTRY_TRACE_REGEX.match(header) if not match: return None trace_id, parent_span_id, sampled_str = match.groups() parent_sampled = None if trace_id: trace_id = "{:032x}".format(int(trace_id, 16)) if parent_span_id: parent_span_id = "{:016x}".format(int(parent_span_id, 16)) if sampled_str: parent_sampled = sampled_str != "0" return { "trace_id": trace_id, "parent_span_id": parent_span_id, "parent_sampled": parent_sampled, } def extract_tracestate_data(header): # type: (Optional[str]) -> typing.Mapping[str, Optional[str]] """ Extracts the sentry tracestate value and any third-party data from the given tracestate header, returning a dictionary of data. """ sentry_entry = third_party_entry = None before = after = "" if header: # find sentry's entry, if any sentry_match = SENTRY_TRACESTATE_ENTRY_REGEX.search(header) if sentry_match: sentry_entry = sentry_match.group(1) # remove the commas after the split so we don't end up with # `xxx=yyy,,zzz=qqq` (double commas) when we put them back together before, after = map(lambda s: s.strip(","), header.split(sentry_entry)) # extract sentry's value from its entry and test to make sure it's # valid; if it isn't, discard the entire entry so that a new one # will be created sentry_value = sentry_entry.replace("sentry=", "") if not re.search("^{b64}$".format(b64=base64_stripped), sentry_value): sentry_entry = None else: after = header # if either part is invalid or empty, remove it before gluing them together third_party_entry = ( ",".join(filter(TRACESTATE_ENTRIES_REGEX.search, [before, after])) or None ) return { "sentry_tracestate": sentry_entry, "third_party_tracestate": third_party_entry, } def compute_tracestate_value(data): # type: (typing.Mapping[str, str]) -> str """ Computes a new tracestate value using the given data. Note: Returns just the base64-encoded data, NOT the full `sentry=...` tracestate entry. """ tracestate_json = json.dumps(data, default=safe_str) # Base64-encoded strings always come out with a length which is a multiple # of 4. In order to achieve this, the end is padded with one or more `=` # signs. Because the tracestate standard calls for using `=` signs between # vendor name and value (`sentry=xxx,dogsaregreat=yyy`), to avoid confusion # we strip the `=` return (to_base64(tracestate_json) or "").rstrip("=") def compute_tracestate_entry(span): # type: (Span) -> Optional[str] """ Computes a new sentry tracestate for the span. Includes the `sentry=`. Will return `None` if there's no client and/or no DSN. """ data = {} hub = span.hub or sentry_sdk.Hub.current client = hub.client scope = hub.scope if client and client.options.get("dsn"): options = client.options user = scope._user data = { "trace_id": span.trace_id, "environment": options["environment"], "release": options.get("release"), "public_key": Dsn(options["dsn"]).public_key, } if user and (user.get("id") or user.get("segment")): user_data = {} if user.get("id"): user_data["id"] = user["id"] if user.get("segment"): user_data["segment"] = user["segment"] data["user"] = user_data if span.containing_transaction: data["transaction"] = span.containing_transaction.name return "sentry=" + compute_tracestate_value(data) return None def reinflate_tracestate(encoded_tracestate): # type: (str) -> typing.Optional[Mapping[str, str]] """ Given a sentry tracestate value in its encoded form, translate it back into a dictionary of data. """ inflated_tracestate = None if encoded_tracestate: # Base64-encoded strings always come out with a length which is a # multiple of 4. In order to achieve this, the end is padded with one or # more `=` signs. Because the tracestate standard calls for using `=` # signs between vendor name and value (`sentry=xxx,dogsaregreat=yyy`), # to avoid confusion we strip the `=` when the data is initially # encoded. Python's decoding function requires they be put back. # Fortunately, it doesn't complain if there are too many, so we just # attach two `=` on spec (there will never be more than 2, see # https://en.wikipedia.org/wiki/Base64#Decoding_Base64_without_padding). tracestate_json = from_base64(encoded_tracestate + "==") try: assert tracestate_json is not None inflated_tracestate = json.loads(tracestate_json) except Exception as err: logger.warning( ( "Unable to attach tracestate data to envelope header: {err}" + "\nTracestate value is {encoded_tracestate}" ).format(err=err, encoded_tracestate=encoded_tracestate), ) return inflated_tracestate def _format_sql(cursor, sql): # type: (Any, str) -> Optional[str] real_sql = None # If we're using psycopg2, it could be that we're # looking at a query that uses Composed objects. Use psycopg2's mogrify # function to format the query. We lose per-parameter trimming but gain # accuracy in formatting. try: if hasattr(cursor, "mogrify"): real_sql = cursor.mogrify(sql) if isinstance(real_sql, bytes): real_sql = real_sql.decode(cursor.connection.encoding) except Exception: real_sql = None return real_sql or to_string(sql) def has_tracestate_enabled(span=None): # type: (Optional[Span]) -> bool client = ((span and span.hub) or sentry_sdk.Hub.current).client options = client and client.options return bool(options and options["_experiments"].get("propagate_tracestate")) def has_custom_measurements_enabled(): # type: () -> bool client = sentry_sdk.Hub.current.client options = client and client.options return bool(options and options["_experiments"].get("custom_measurements")) class Baggage(object): __slots__ = ("sentry_items", "third_party_items", "mutable") SENTRY_PREFIX = "sentry-" SENTRY_PREFIX_REGEX = re.compile("^sentry-") # DynamicSamplingContext DSC_KEYS = [ "trace_id", "public_key", "sample_rate", "release", "environment", "transaction", "user_id", "user_segment", ] def __init__( self, sentry_items, # type: Dict[str, str] third_party_items="", # type: str mutable=True, # type: bool ): self.sentry_items = sentry_items self.third_party_items = third_party_items self.mutable = mutable @classmethod def from_incoming_header(cls, header): # type: (Optional[str]) -> Baggage """ freeze if incoming header already has sentry baggage """ sentry_items = {} third_party_items = "" mutable = True if header: for item in header.split(","): if "=" not in item: continue with capture_internal_exceptions(): item = item.strip() key, val = item.split("=") if Baggage.SENTRY_PREFIX_REGEX.match(key): baggage_key = unquote(key.split("-")[1]) sentry_items[baggage_key] = unquote(val) mutable = False else: third_party_items += ("," if third_party_items else "") + item return Baggage(sentry_items, third_party_items, mutable) @classmethod def populate_from_transaction(cls, transaction): # type: (Transaction) -> Baggage """ Populate fresh baggage entry with sentry_items and make it immutable if this is the head SDK which originates traces. """ hub = transaction.hub or sentry_sdk.Hub.current client = hub.client sentry_items = {} # type: Dict[str, str] if not client: return Baggage(sentry_items) options = client.options or {} user = (hub.scope and hub.scope._user) or {} sentry_items["trace_id"] = transaction.trace_id if options.get("environment"): sentry_items["environment"] = options["environment"] if options.get("release"): sentry_items["release"] = options["release"] if options.get("dsn"): sentry_items["public_key"] = Dsn(options["dsn"]).public_key if ( transaction.name and transaction.source not in LOW_QUALITY_TRANSACTION_SOURCES ): sentry_items["transaction"] = transaction.name if user.get("segment"): sentry_items["user_segment"] = user["segment"] if transaction.sample_rate is not None: sentry_items["sample_rate"] = str(transaction.sample_rate) # there's an existing baggage but it was mutable, # which is why we are creating this new baggage. # However, if by chance the user put some sentry items in there, give them precedence. if transaction._baggage and transaction._baggage.sentry_items: sentry_items.update(transaction._baggage.sentry_items) return Baggage(sentry_items, mutable=False) def freeze(self): # type: () -> None self.mutable = False def dynamic_sampling_context(self): # type: () -> Dict[str, str] header = {} for key in Baggage.DSC_KEYS: item = self.sentry_items.get(key) if item: header[key] = item return header def serialize(self, include_third_party=False): # type: (bool) -> str items = [] for key, val in iteritems(self.sentry_items): with capture_internal_exceptions(): item = Baggage.SENTRY_PREFIX + quote(key) + "=" + quote(str(val)) items.append(item) if include_third_party: items.append(self.third_party_items) return ",".join(items) # Circular imports from sentry_sdk.tracing import LOW_QUALITY_TRANSACTION_SOURCES if MYPY: from sentry_sdk.tracing import Span, Transaction
17,303
Python
29.9
147
0.597006
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/api.py
import inspect from sentry_sdk.hub import Hub from sentry_sdk.scope import Scope from sentry_sdk._types import MYPY from sentry_sdk.tracing import NoOpSpan if MYPY: from typing import Any from typing import Dict from typing import Optional from typing import overload from typing import Callable from typing import TypeVar from typing import ContextManager from typing import Union from sentry_sdk._types import Event, Hint, Breadcrumb, BreadcrumbHint, ExcInfo from sentry_sdk.tracing import Span, Transaction T = TypeVar("T") F = TypeVar("F", bound=Callable[..., Any]) else: def overload(x): # type: (T) -> T return x # When changing this, update __all__ in __init__.py too __all__ = [ "capture_event", "capture_message", "capture_exception", "add_breadcrumb", "configure_scope", "push_scope", "flush", "last_event_id", "start_span", "start_transaction", "set_tag", "set_context", "set_extra", "set_user", "set_level", ] def hubmethod(f): # type: (F) -> F f.__doc__ = "%s\n\n%s" % ( "Alias for :py:meth:`sentry_sdk.Hub.%s`" % f.__name__, inspect.getdoc(getattr(Hub, f.__name__)), ) return f def scopemethod(f): # type: (F) -> F f.__doc__ = "%s\n\n%s" % ( "Alias for :py:meth:`sentry_sdk.Scope.%s`" % f.__name__, inspect.getdoc(getattr(Scope, f.__name__)), ) return f @hubmethod def capture_event( event, # type: Event hint=None, # type: Optional[Hint] scope=None, # type: Optional[Any] **scope_args # type: Any ): # type: (...) -> Optional[str] return Hub.current.capture_event(event, hint, scope=scope, **scope_args) @hubmethod def capture_message( message, # type: str level=None, # type: Optional[str] scope=None, # type: Optional[Any] **scope_args # type: Any ): # type: (...) -> Optional[str] return Hub.current.capture_message(message, level, scope=scope, **scope_args) @hubmethod def capture_exception( error=None, # type: Optional[Union[BaseException, ExcInfo]] scope=None, # type: Optional[Any] **scope_args # type: Any ): # type: (...) -> Optional[str] return Hub.current.capture_exception(error, scope=scope, **scope_args) @hubmethod def add_breadcrumb( crumb=None, # type: Optional[Breadcrumb] hint=None, # type: Optional[BreadcrumbHint] **kwargs # type: Any ): # type: (...) -> None return Hub.current.add_breadcrumb(crumb, hint, **kwargs) @overload def configure_scope(): # type: () -> ContextManager[Scope] pass @overload def configure_scope( # noqa: F811 callback, # type: Callable[[Scope], None] ): # type: (...) -> None pass @hubmethod def configure_scope( # noqa: F811 callback=None, # type: Optional[Callable[[Scope], None]] ): # type: (...) -> Optional[ContextManager[Scope]] return Hub.current.configure_scope(callback) @overload def push_scope(): # type: () -> ContextManager[Scope] pass @overload def push_scope( # noqa: F811 callback, # type: Callable[[Scope], None] ): # type: (...) -> None pass @hubmethod def push_scope( # noqa: F811 callback=None, # type: Optional[Callable[[Scope], None]] ): # type: (...) -> Optional[ContextManager[Scope]] return Hub.current.push_scope(callback) @scopemethod def set_tag(key, value): # type: (str, Any) -> None return Hub.current.scope.set_tag(key, value) @scopemethod def set_context(key, value): # type: (str, Dict[str, Any]) -> None return Hub.current.scope.set_context(key, value) @scopemethod def set_extra(key, value): # type: (str, Any) -> None return Hub.current.scope.set_extra(key, value) @scopemethod def set_user(value): # type: (Optional[Dict[str, Any]]) -> None return Hub.current.scope.set_user(value) @scopemethod def set_level(value): # type: (str) -> None return Hub.current.scope.set_level(value) @hubmethod def flush( timeout=None, # type: Optional[float] callback=None, # type: Optional[Callable[[int, float], None]] ): # type: (...) -> None return Hub.current.flush(timeout=timeout, callback=callback) @hubmethod def last_event_id(): # type: () -> Optional[str] return Hub.current.last_event_id() @hubmethod def start_span( span=None, # type: Optional[Span] **kwargs # type: Any ): # type: (...) -> Span return Hub.current.start_span(span=span, **kwargs) @hubmethod def start_transaction( transaction=None, # type: Optional[Transaction] **kwargs # type: Any ): # type: (...) -> Union[Transaction, NoOpSpan] return Hub.current.start_transaction(transaction, **kwargs)
4,773
Python
21.101852
82
0.622879
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/transport.py
from __future__ import print_function import io import urllib3 # type: ignore import certifi import gzip import time from datetime import datetime, timedelta from collections import defaultdict from sentry_sdk.utils import Dsn, logger, capture_internal_exceptions, json_dumps from sentry_sdk.worker import BackgroundWorker from sentry_sdk.envelope import Envelope, Item, PayloadRef from sentry_sdk._types import MYPY if MYPY: from typing import Any from typing import Callable from typing import Dict from typing import Iterable from typing import Optional from typing import Tuple from typing import Type from typing import Union from typing import DefaultDict from urllib3.poolmanager import PoolManager # type: ignore from urllib3.poolmanager import ProxyManager from sentry_sdk._types import Event, EndpointType DataCategory = Optional[str] try: from urllib.request import getproxies except ImportError: from urllib import getproxies # type: ignore class Transport(object): """Baseclass for all transports. A transport is used to send an event to sentry. """ parsed_dsn = None # type: Optional[Dsn] def __init__( self, options=None # type: Optional[Dict[str, Any]] ): # type: (...) -> None self.options = options if options and options["dsn"] is not None and options["dsn"]: self.parsed_dsn = Dsn(options["dsn"]) else: self.parsed_dsn = None def capture_event( self, event # type: Event ): # type: (...) -> None """ This gets invoked with the event dictionary when an event should be sent to sentry. """ raise NotImplementedError() def capture_envelope( self, envelope # type: Envelope ): # type: (...) -> None """ Send an envelope to Sentry. Envelopes are a data container format that can hold any type of data submitted to Sentry. We use it for transactions and sessions, but regular "error" events should go through `capture_event` for backwards compat. """ raise NotImplementedError() def flush( self, timeout, # type: float callback=None, # type: Optional[Any] ): # type: (...) -> None """Wait `timeout` seconds for the current events to be sent out.""" pass def kill(self): # type: () -> None """Forcefully kills the transport.""" pass def record_lost_event( self, reason, # type: str data_category=None, # type: Optional[str] item=None, # type: Optional[Item] ): # type: (...) -> None """This increments a counter for event loss by reason and data category. """ return None def __del__(self): # type: () -> None try: self.kill() except Exception: pass def _parse_rate_limits(header, now=None): # type: (Any, Optional[datetime]) -> Iterable[Tuple[DataCategory, datetime]] if now is None: now = datetime.utcnow() for limit in header.split(","): try: retry_after, categories, _ = limit.strip().split(":", 2) retry_after = now + timedelta(seconds=int(retry_after)) for category in categories and categories.split(";") or (None,): yield category, retry_after except (LookupError, ValueError): continue class HttpTransport(Transport): """The default HTTP transport.""" def __init__( self, options # type: Dict[str, Any] ): # type: (...) -> None from sentry_sdk.consts import VERSION Transport.__init__(self, options) assert self.parsed_dsn is not None self.options = options # type: Dict[str, Any] self._worker = BackgroundWorker(queue_size=options["transport_queue_size"]) self._auth = self.parsed_dsn.to_auth("sentry.python/%s" % VERSION) self._disabled_until = {} # type: Dict[DataCategory, datetime] self._retry = urllib3.util.Retry() self._discarded_events = defaultdict( int ) # type: DefaultDict[Tuple[str, str], int] self._last_client_report_sent = time.time() self._pool = self._make_pool( self.parsed_dsn, http_proxy=options["http_proxy"], https_proxy=options["https_proxy"], ca_certs=options["ca_certs"], proxy_headers=options["proxy_headers"], ) from sentry_sdk import Hub self.hub_cls = Hub def record_lost_event( self, reason, # type: str data_category=None, # type: Optional[str] item=None, # type: Optional[Item] ): # type: (...) -> None if not self.options["send_client_reports"]: return quantity = 1 if item is not None: data_category = item.data_category if data_category == "attachment": # quantity of 0 is actually 1 as we do not want to count # empty attachments as actually empty. quantity = len(item.get_bytes()) or 1 elif data_category is None: raise TypeError("data category not provided") self._discarded_events[data_category, reason] += quantity def _update_rate_limits(self, response): # type: (urllib3.HTTPResponse) -> None # new sentries with more rate limit insights. We honor this header # no matter of the status code to update our internal rate limits. header = response.headers.get("x-sentry-rate-limits") if header: logger.warning("Rate-limited via x-sentry-rate-limits") self._disabled_until.update(_parse_rate_limits(header)) # old sentries only communicate global rate limit hits via the # retry-after header on 429. This header can also be emitted on new # sentries if a proxy in front wants to globally slow things down. elif response.status == 429: logger.warning("Rate-limited via 429") self._disabled_until[None] = datetime.utcnow() + timedelta( seconds=self._retry.get_retry_after(response) or 60 ) def _send_request( self, body, # type: bytes headers, # type: Dict[str, str] endpoint_type="store", # type: EndpointType envelope=None, # type: Optional[Envelope] ): # type: (...) -> None def record_loss(reason): # type: (str) -> None if envelope is None: self.record_lost_event(reason, data_category="error") else: for item in envelope.items: self.record_lost_event(reason, item=item) headers.update( { "User-Agent": str(self._auth.client), "X-Sentry-Auth": str(self._auth.to_header()), } ) try: response = self._pool.request( "POST", str(self._auth.get_api_url(endpoint_type)), body=body, headers=headers, ) except Exception: self.on_dropped_event("network") record_loss("network_error") raise try: self._update_rate_limits(response) if response.status == 429: # if we hit a 429. Something was rate limited but we already # acted on this in `self._update_rate_limits`. Note that we # do not want to record event loss here as we will have recorded # an outcome in relay already. self.on_dropped_event("status_429") pass elif response.status >= 300 or response.status < 200: logger.error( "Unexpected status code: %s (body: %s)", response.status, response.data, ) self.on_dropped_event("status_{}".format(response.status)) record_loss("network_error") finally: response.close() def on_dropped_event(self, reason): # type: (str) -> None return None def _fetch_pending_client_report(self, force=False, interval=60): # type: (bool, int) -> Optional[Item] if not self.options["send_client_reports"]: return None if not (force or self._last_client_report_sent < time.time() - interval): return None discarded_events = self._discarded_events self._discarded_events = defaultdict(int) self._last_client_report_sent = time.time() if not discarded_events: return None return Item( PayloadRef( json={ "timestamp": time.time(), "discarded_events": [ {"reason": reason, "category": category, "quantity": quantity} for ( (category, reason), quantity, ) in discarded_events.items() ], } ), type="client_report", ) def _flush_client_reports(self, force=False): # type: (bool) -> None client_report = self._fetch_pending_client_report(force=force, interval=60) if client_report is not None: self.capture_envelope(Envelope(items=[client_report])) def _check_disabled(self, category): # type: (str) -> bool def _disabled(bucket): # type: (Any) -> bool ts = self._disabled_until.get(bucket) return ts is not None and ts > datetime.utcnow() return _disabled(category) or _disabled(None) def _send_event( self, event # type: Event ): # type: (...) -> None if self._check_disabled("error"): self.on_dropped_event("self_rate_limits") self.record_lost_event("ratelimit_backoff", data_category="error") return None body = io.BytesIO() with gzip.GzipFile(fileobj=body, mode="w") as f: f.write(json_dumps(event)) assert self.parsed_dsn is not None logger.debug( "Sending event, type:%s level:%s event_id:%s project:%s host:%s" % ( event.get("type") or "null", event.get("level") or "null", event.get("event_id") or "null", self.parsed_dsn.project_id, self.parsed_dsn.host, ) ) self._send_request( body.getvalue(), headers={"Content-Type": "application/json", "Content-Encoding": "gzip"}, ) return None def _send_envelope( self, envelope # type: Envelope ): # type: (...) -> None # remove all items from the envelope which are over quota new_items = [] for item in envelope.items: if self._check_disabled(item.data_category): if item.data_category in ("transaction", "error", "default"): self.on_dropped_event("self_rate_limits") self.record_lost_event("ratelimit_backoff", item=item) else: new_items.append(item) # Since we're modifying the envelope here make a copy so that others # that hold references do not see their envelope modified. envelope = Envelope(headers=envelope.headers, items=new_items) if not envelope.items: return None # since we're already in the business of sending out an envelope here # check if we have one pending for the stats session envelopes so we # can attach it to this enveloped scheduled for sending. This will # currently typically attach the client report to the most recent # session update. client_report_item = self._fetch_pending_client_report(interval=30) if client_report_item is not None: envelope.items.append(client_report_item) body = io.BytesIO() with gzip.GzipFile(fileobj=body, mode="w") as f: envelope.serialize_into(f) assert self.parsed_dsn is not None logger.debug( "Sending envelope [%s] project:%s host:%s", envelope.description, self.parsed_dsn.project_id, self.parsed_dsn.host, ) self._send_request( body.getvalue(), headers={ "Content-Type": "application/x-sentry-envelope", "Content-Encoding": "gzip", }, endpoint_type="envelope", envelope=envelope, ) return None def _get_pool_options(self, ca_certs): # type: (Optional[Any]) -> Dict[str, Any] return { "num_pools": 2, "cert_reqs": "CERT_REQUIRED", "ca_certs": ca_certs or certifi.where(), } def _in_no_proxy(self, parsed_dsn): # type: (Dsn) -> bool no_proxy = getproxies().get("no") if not no_proxy: return False for host in no_proxy.split(","): host = host.strip() if parsed_dsn.host.endswith(host) or parsed_dsn.netloc.endswith(host): return True return False def _make_pool( self, parsed_dsn, # type: Dsn http_proxy, # type: Optional[str] https_proxy, # type: Optional[str] ca_certs, # type: Optional[Any] proxy_headers, # type: Optional[Dict[str, str]] ): # type: (...) -> Union[PoolManager, ProxyManager] proxy = None no_proxy = self._in_no_proxy(parsed_dsn) # try HTTPS first if parsed_dsn.scheme == "https" and (https_proxy != ""): proxy = https_proxy or (not no_proxy and getproxies().get("https")) # maybe fallback to HTTP proxy if not proxy and (http_proxy != ""): proxy = http_proxy or (not no_proxy and getproxies().get("http")) opts = self._get_pool_options(ca_certs) if proxy: if proxy_headers: opts["proxy_headers"] = proxy_headers return urllib3.ProxyManager(proxy, **opts) else: return urllib3.PoolManager(**opts) def capture_event( self, event # type: Event ): # type: (...) -> None hub = self.hub_cls.current def send_event_wrapper(): # type: () -> None with hub: with capture_internal_exceptions(): self._send_event(event) self._flush_client_reports() if not self._worker.submit(send_event_wrapper): self.on_dropped_event("full_queue") self.record_lost_event("queue_overflow", data_category="error") def capture_envelope( self, envelope # type: Envelope ): # type: (...) -> None hub = self.hub_cls.current def send_envelope_wrapper(): # type: () -> None with hub: with capture_internal_exceptions(): self._send_envelope(envelope) self._flush_client_reports() if not self._worker.submit(send_envelope_wrapper): self.on_dropped_event("full_queue") for item in envelope.items: self.record_lost_event("queue_overflow", item=item) def flush( self, timeout, # type: float callback=None, # type: Optional[Any] ): # type: (...) -> None logger.debug("Flushing HTTP transport") if timeout > 0: self._worker.submit(lambda: self._flush_client_reports(force=True)) self._worker.flush(timeout, callback) def kill(self): # type: () -> None logger.debug("Killing HTTP transport") self._worker.kill() class _FunctionTransport(Transport): def __init__( self, func # type: Callable[[Event], None] ): # type: (...) -> None Transport.__init__(self) self._func = func def capture_event( self, event # type: Event ): # type: (...) -> None self._func(event) return None def make_transport(options): # type: (Dict[str, Any]) -> Optional[Transport] ref_transport = options["transport"] # If no transport is given, we use the http transport class if ref_transport is None: transport_cls = HttpTransport # type: Type[Transport] elif isinstance(ref_transport, Transport): return ref_transport elif isinstance(ref_transport, type) and issubclass(ref_transport, Transport): transport_cls = ref_transport elif callable(ref_transport): return _FunctionTransport(ref_transport) # type: ignore # if a transport class is given only instantiate it if the dsn is not # empty or None if options["dsn"]: return transport_cls(options) return None
17,320
Python
31.255121
86
0.55537
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/client.py
import os import uuid import random from datetime import datetime import socket from sentry_sdk._compat import string_types, text_type, iteritems from sentry_sdk.utils import ( capture_internal_exceptions, current_stacktrace, disable_capture_event, format_timestamp, get_sdk_name, get_type_name, get_default_release, handle_in_app, logger, ) from sentry_sdk.serializer import serialize from sentry_sdk.transport import make_transport from sentry_sdk.consts import ( DEFAULT_OPTIONS, INSTRUMENTER, VERSION, ClientConstructor, ) from sentry_sdk.integrations import setup_integrations from sentry_sdk.utils import ContextVar from sentry_sdk.sessions import SessionFlusher from sentry_sdk.envelope import Envelope from sentry_sdk.profiler import setup_profiler from sentry_sdk.tracing_utils import has_tracestate_enabled, reinflate_tracestate from sentry_sdk._types import MYPY if MYPY: from typing import Any from typing import Callable from typing import Dict from typing import Optional from sentry_sdk.scope import Scope from sentry_sdk._types import Event, Hint from sentry_sdk.session import Session _client_init_debug = ContextVar("client_init_debug") SDK_INFO = { "name": "sentry.python", # SDK name will be overridden after integrations have been loaded with sentry_sdk.integrations.setup_integrations() "version": VERSION, "packages": [{"name": "pypi:sentry-sdk", "version": VERSION}], } def _get_options(*args, **kwargs): # type: (*Optional[str], **Any) -> Dict[str, Any] if args and (isinstance(args[0], (text_type, bytes, str)) or args[0] is None): dsn = args[0] # type: Optional[str] args = args[1:] else: dsn = None if len(args) > 1: raise TypeError("Only single positional argument is expected") rv = dict(DEFAULT_OPTIONS) options = dict(*args, **kwargs) if dsn is not None and options.get("dsn") is None: options["dsn"] = dsn for key, value in iteritems(options): if key not in rv: raise TypeError("Unknown option %r" % (key,)) rv[key] = value if rv["dsn"] is None: rv["dsn"] = os.environ.get("SENTRY_DSN") if rv["release"] is None: rv["release"] = get_default_release() if rv["environment"] is None: rv["environment"] = os.environ.get("SENTRY_ENVIRONMENT") or "production" if rv["server_name"] is None and hasattr(socket, "gethostname"): rv["server_name"] = socket.gethostname() if rv["instrumenter"] is None: rv["instrumenter"] = INSTRUMENTER.SENTRY return rv class _Client(object): """The client is internally responsible for capturing the events and forwarding them to sentry through the configured transport. It takes the client options as keyword arguments and optionally the DSN as first argument. """ def __init__(self, *args, **kwargs): # type: (*Any, **Any) -> None self.options = get_options(*args, **kwargs) # type: Dict[str, Any] self._init_impl() def __getstate__(self): # type: () -> Any return {"options": self.options} def __setstate__(self, state): # type: (Any) -> None self.options = state["options"] self._init_impl() def _init_impl(self): # type: () -> None old_debug = _client_init_debug.get(False) def _capture_envelope(envelope): # type: (Envelope) -> None if self.transport is not None: self.transport.capture_envelope(envelope) try: _client_init_debug.set(self.options["debug"]) self.transport = make_transport(self.options) self.session_flusher = SessionFlusher(capture_func=_capture_envelope) request_bodies = ("always", "never", "small", "medium") if self.options["request_bodies"] not in request_bodies: raise ValueError( "Invalid value for request_bodies. Must be one of {}".format( request_bodies ) ) self.integrations = setup_integrations( self.options["integrations"], with_defaults=self.options["default_integrations"], with_auto_enabling_integrations=self.options[ "auto_enabling_integrations" ], ) sdk_name = get_sdk_name(list(self.integrations.keys())) SDK_INFO["name"] = sdk_name logger.debug("Setting SDK name to '%s'", sdk_name) finally: _client_init_debug.set(old_debug) profiles_sample_rate = self.options["_experiments"].get("profiles_sample_rate") if profiles_sample_rate is not None and profiles_sample_rate > 0: try: setup_profiler(self.options) except ValueError as e: logger.debug(str(e)) @property def dsn(self): # type: () -> Optional[str] """Returns the configured DSN as string.""" return self.options["dsn"] def _prepare_event( self, event, # type: Event hint, # type: Hint scope, # type: Optional[Scope] ): # type: (...) -> Optional[Event] if event.get("timestamp") is None: event["timestamp"] = datetime.utcnow() if scope is not None: is_transaction = event.get("type") == "transaction" event_ = scope.apply_to_event(event, hint) # one of the event/error processors returned None if event_ is None: if self.transport: self.transport.record_lost_event( "event_processor", data_category=("transaction" if is_transaction else "error"), ) return None event = event_ if ( self.options["attach_stacktrace"] and "exception" not in event and "stacktrace" not in event and "threads" not in event ): with capture_internal_exceptions(): event["threads"] = { "values": [ { "stacktrace": current_stacktrace( self.options["with_locals"] ), "crashed": False, "current": True, } ] } for key in "release", "environment", "server_name", "dist": if event.get(key) is None and self.options[key] is not None: event[key] = text_type(self.options[key]).strip() if event.get("sdk") is None: sdk_info = dict(SDK_INFO) sdk_info["integrations"] = sorted(self.integrations.keys()) event["sdk"] = sdk_info if event.get("platform") is None: event["platform"] = "python" event = handle_in_app( event, self.options["in_app_exclude"], self.options["in_app_include"] ) # Postprocess the event here so that annotated types do # generally not surface in before_send if event is not None: event = serialize( event, smart_transaction_trimming=self.options["_experiments"].get( "smart_transaction_trimming" ), ) before_send = self.options["before_send"] if before_send is not None and event.get("type") != "transaction": new_event = None with capture_internal_exceptions(): new_event = before_send(event, hint or {}) if new_event is None: logger.info("before send dropped event (%s)", event) if self.transport: self.transport.record_lost_event( "before_send", data_category="error" ) event = new_event # type: ignore before_send_transaction = self.options["before_send_transaction"] if before_send_transaction is not None and event.get("type") == "transaction": new_event = None with capture_internal_exceptions(): new_event = before_send_transaction(event, hint or {}) if new_event is None: logger.info("before send transaction dropped event (%s)", event) if self.transport: self.transport.record_lost_event( "before_send", data_category="transaction" ) event = new_event # type: ignore return event def _is_ignored_error(self, event, hint): # type: (Event, Hint) -> bool exc_info = hint.get("exc_info") if exc_info is None: return False error = exc_info[0] error_type_name = get_type_name(exc_info[0]) error_full_name = "%s.%s" % (exc_info[0].__module__, error_type_name) for ignored_error in self.options["ignore_errors"]: # String types are matched against the type name in the # exception only if isinstance(ignored_error, string_types): if ignored_error == error_full_name or ignored_error == error_type_name: return True else: if issubclass(error, ignored_error): return True return False def _should_capture( self, event, # type: Event hint, # type: Hint scope=None, # type: Optional[Scope] ): # type: (...) -> bool # Transactions are sampled independent of error events. is_transaction = event.get("type") == "transaction" if is_transaction: return True ignoring_prevents_recursion = scope is not None and not scope._should_capture if ignoring_prevents_recursion: return False ignored_by_config_option = self._is_ignored_error(event, hint) if ignored_by_config_option: return False return True def _should_sample_error( self, event, # type: Event ): # type: (...) -> bool not_in_sample_rate = ( self.options["sample_rate"] < 1.0 and random.random() >= self.options["sample_rate"] ) if not_in_sample_rate: # because we will not sample this event, record a "lost event". if self.transport: self.transport.record_lost_event("sample_rate", data_category="error") return False return True def _update_session_from_event( self, session, # type: Session event, # type: Event ): # type: (...) -> None crashed = False errored = False user_agent = None exceptions = (event.get("exception") or {}).get("values") if exceptions: errored = True for error in exceptions: mechanism = error.get("mechanism") if mechanism and mechanism.get("handled") is False: crashed = True break user = event.get("user") if session.user_agent is None: headers = (event.get("request") or {}).get("headers") for (k, v) in iteritems(headers or {}): if k.lower() == "user-agent": user_agent = v break session.update( status="crashed" if crashed else None, user=user, user_agent=user_agent, errors=session.errors + (errored or crashed), ) def capture_event( self, event, # type: Event hint=None, # type: Optional[Hint] scope=None, # type: Optional[Scope] ): # type: (...) -> Optional[str] """Captures an event. :param event: A ready-made event that can be directly sent to Sentry. :param hint: Contains metadata about the event that can be read from `before_send`, such as the original exception object or a HTTP request object. :returns: An event ID. May be `None` if there is no DSN set or of if the SDK decided to discard the event for other reasons. In such situations setting `debug=True` on `init()` may help. """ if disable_capture_event.get(False): return None if self.transport is None: return None if hint is None: hint = {} event_id = event.get("event_id") hint = dict(hint or ()) # type: Hint if event_id is None: event["event_id"] = event_id = uuid.uuid4().hex if not self._should_capture(event, hint, scope): return None profile = event.pop("profile", None) event_opt = self._prepare_event(event, hint, scope) if event_opt is None: return None # whenever we capture an event we also check if the session needs # to be updated based on that information. session = scope._session if scope else None if session: self._update_session_from_event(session, event) is_transaction = event_opt.get("type") == "transaction" if not is_transaction and not self._should_sample_error(event): return None attachments = hint.get("attachments") # this is outside of the `if` immediately below because even if we don't # use the value, we want to make sure we remove it before the event is # sent raw_tracestate = ( event_opt.get("contexts", {}).get("trace", {}).pop("tracestate", "") ) dynamic_sampling_context = ( event_opt.get("contexts", {}) .get("trace", {}) .pop("dynamic_sampling_context", {}) ) # Transactions or events with attachments should go to the /envelope/ # endpoint. if is_transaction or attachments: headers = { "event_id": event_opt["event_id"], "sent_at": format_timestamp(datetime.utcnow()), } if has_tracestate_enabled(): tracestate_data = raw_tracestate and reinflate_tracestate( raw_tracestate.replace("sentry=", "") ) if tracestate_data: headers["trace"] = tracestate_data elif dynamic_sampling_context: headers["trace"] = dynamic_sampling_context envelope = Envelope(headers=headers) if is_transaction: if profile is not None: envelope.add_profile(profile.to_json(event_opt, self.options)) envelope.add_transaction(event_opt) else: envelope.add_event(event_opt) for attachment in attachments or (): envelope.add_item(attachment.to_envelope_item()) self.transport.capture_envelope(envelope) else: # All other events go to the /store/ endpoint. self.transport.capture_event(event_opt) return event_id def capture_session( self, session # type: Session ): # type: (...) -> None if not session.release: logger.info("Discarded session update because of missing release") else: self.session_flusher.add_session(session) def close( self, timeout=None, # type: Optional[float] callback=None, # type: Optional[Callable[[int, float], None]] ): # type: (...) -> None """ Close the client and shut down the transport. Arguments have the same semantics as :py:meth:`Client.flush`. """ if self.transport is not None: self.flush(timeout=timeout, callback=callback) self.session_flusher.kill() self.transport.kill() self.transport = None def flush( self, timeout=None, # type: Optional[float] callback=None, # type: Optional[Callable[[int, float], None]] ): # type: (...) -> None """ Wait for the current events to be sent. :param timeout: Wait for at most `timeout` seconds. If no `timeout` is provided, the `shutdown_timeout` option value is used. :param callback: Is invoked with the number of pending events and the configured timeout. """ if self.transport is not None: if timeout is None: timeout = self.options["shutdown_timeout"] self.session_flusher.flush() self.transport.flush(timeout=timeout, callback=callback) def __enter__(self): # type: () -> _Client return self def __exit__(self, exc_type, exc_value, tb): # type: (Any, Any, Any) -> None self.close() from sentry_sdk._types import MYPY if MYPY: # Make mypy, PyCharm and other static analyzers think `get_options` is a # type to have nicer autocompletion for params. # # Use `ClientConstructor` to define the argument types of `init` and # `Dict[str, Any]` to tell static analyzers about the return type. class get_options(ClientConstructor, Dict[str, Any]): # noqa: N801 pass class Client(ClientConstructor, _Client): pass else: # Alias `get_options` for actual usage. Go through the lambda indirection # to throw PyCharm off of the weakly typed signature (it would otherwise # discover both the weakly typed signature of `_init` and our faked `init` # type). get_options = (lambda: _get_options)() Client = (lambda: _Client)()
17,961
Python
32.386617
194
0.560325
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/_functools.py
""" A backport of Python 3 functools to Python 2/3. The only important change we rely upon is that `update_wrapper` handles AttributeError gracefully. """ from functools import partial from sentry_sdk._types import MYPY if MYPY: from typing import Any from typing import Callable WRAPPER_ASSIGNMENTS = ( "__module__", "__name__", "__qualname__", "__doc__", "__annotations__", ) WRAPPER_UPDATES = ("__dict__",) def update_wrapper( wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES ): # type: (Any, Any, Any, Any) -> Any """Update a wrapper function to look like the wrapped function wrapper is the function to be updated wrapped is the original function assigned is a tuple naming the attributes assigned directly from the wrapped function to the wrapper function (defaults to functools.WRAPPER_ASSIGNMENTS) updated is a tuple naming the attributes of the wrapper that are updated with the corresponding attribute from the wrapped function (defaults to functools.WRAPPER_UPDATES) """ for attr in assigned: try: value = getattr(wrapped, attr) except AttributeError: pass else: setattr(wrapper, attr, value) for attr in updated: getattr(wrapper, attr).update(getattr(wrapped, attr, {})) # Issue #17482: set __wrapped__ last so we don't inadvertently copy it # from the wrapped function when updating __dict__ wrapper.__wrapped__ = wrapped # Return the wrapper so this can be used as a decorator via partial() return wrapper def wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES): # type: (Callable[..., Any], Any, Any) -> Callable[[Callable[..., Any]], Callable[..., Any]] """Decorator factory to apply update_wrapper() to a wrapper function Returns a decorator that invokes update_wrapper() with the decorated function as the wrapper argument and the arguments to wraps() as the remaining arguments. Default arguments are as for update_wrapper(). This is a convenience function to simplify applying partial() to update_wrapper(). """ return partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)
2,276
Python
32.985074
96
0.688489
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/session.py
import uuid from datetime import datetime from sentry_sdk._types import MYPY from sentry_sdk.utils import format_timestamp if MYPY: from typing import Optional from typing import Union from typing import Any from typing import Dict from sentry_sdk._types import SessionStatus def _minute_trunc(ts): # type: (datetime) -> datetime return ts.replace(second=0, microsecond=0) def _make_uuid( val, # type: Union[str, uuid.UUID] ): # type: (...) -> uuid.UUID if isinstance(val, uuid.UUID): return val return uuid.UUID(val) class Session(object): def __init__( self, sid=None, # type: Optional[Union[str, uuid.UUID]] did=None, # type: Optional[str] timestamp=None, # type: Optional[datetime] started=None, # type: Optional[datetime] duration=None, # type: Optional[float] status=None, # type: Optional[SessionStatus] release=None, # type: Optional[str] environment=None, # type: Optional[str] user_agent=None, # type: Optional[str] ip_address=None, # type: Optional[str] errors=None, # type: Optional[int] user=None, # type: Optional[Any] session_mode="application", # type: str ): # type: (...) -> None if sid is None: sid = uuid.uuid4() if started is None: started = datetime.utcnow() if status is None: status = "ok" self.status = status self.did = None # type: Optional[str] self.started = started self.release = None # type: Optional[str] self.environment = None # type: Optional[str] self.duration = None # type: Optional[float] self.user_agent = None # type: Optional[str] self.ip_address = None # type: Optional[str] self.session_mode = session_mode # type: str self.errors = 0 self.update( sid=sid, did=did, timestamp=timestamp, duration=duration, release=release, environment=environment, user_agent=user_agent, ip_address=ip_address, errors=errors, user=user, ) @property def truncated_started(self): # type: (...) -> datetime return _minute_trunc(self.started) def update( self, sid=None, # type: Optional[Union[str, uuid.UUID]] did=None, # type: Optional[str] timestamp=None, # type: Optional[datetime] started=None, # type: Optional[datetime] duration=None, # type: Optional[float] status=None, # type: Optional[SessionStatus] release=None, # type: Optional[str] environment=None, # type: Optional[str] user_agent=None, # type: Optional[str] ip_address=None, # type: Optional[str] errors=None, # type: Optional[int] user=None, # type: Optional[Any] ): # type: (...) -> None # If a user is supplied we pull some data form it if user: if ip_address is None: ip_address = user.get("ip_address") if did is None: did = user.get("id") or user.get("email") or user.get("username") if sid is not None: self.sid = _make_uuid(sid) if did is not None: self.did = str(did) if timestamp is None: timestamp = datetime.utcnow() self.timestamp = timestamp if started is not None: self.started = started if duration is not None: self.duration = duration if release is not None: self.release = release if environment is not None: self.environment = environment if ip_address is not None: self.ip_address = ip_address if user_agent is not None: self.user_agent = user_agent if errors is not None: self.errors = errors if status is not None: self.status = status def close( self, status=None # type: Optional[SessionStatus] ): # type: (...) -> Any if status is None and self.status == "ok": status = "exited" if status is not None: self.update(status=status) def get_json_attrs( self, with_user_info=True # type: Optional[bool] ): # type: (...) -> Any attrs = {} if self.release is not None: attrs["release"] = self.release if self.environment is not None: attrs["environment"] = self.environment if with_user_info: if self.ip_address is not None: attrs["ip_address"] = self.ip_address if self.user_agent is not None: attrs["user_agent"] = self.user_agent return attrs def to_json(self): # type: (...) -> Any rv = { "sid": str(self.sid), "init": True, "started": format_timestamp(self.started), "timestamp": format_timestamp(self.timestamp), "status": self.status, } # type: Dict[str, Any] if self.errors: rv["errors"] = self.errors if self.did is not None: rv["did"] = self.did if self.duration is not None: rv["duration"] = self.duration attrs = self.get_json_attrs() if attrs: rv["attrs"] = attrs return rv
5,543
Python
30.68
81
0.546275
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/sessions.py
import os import time from threading import Thread, Lock from contextlib import contextmanager import sentry_sdk from sentry_sdk.envelope import Envelope from sentry_sdk.session import Session from sentry_sdk._types import MYPY from sentry_sdk.utils import format_timestamp if MYPY: from typing import Any from typing import Callable from typing import Dict from typing import Generator from typing import List from typing import Optional from typing import Union def is_auto_session_tracking_enabled(hub=None): # type: (Optional[sentry_sdk.Hub]) -> Union[Any, bool, None] """Utility function to find out if session tracking is enabled.""" if hub is None: hub = sentry_sdk.Hub.current should_track = hub.scope._force_auto_session_tracking if should_track is None: client_options = hub.client.options if hub.client else {} should_track = client_options.get("auto_session_tracking", False) return should_track @contextmanager def auto_session_tracking(hub=None, session_mode="application"): # type: (Optional[sentry_sdk.Hub], str) -> Generator[None, None, None] """Starts and stops a session automatically around a block.""" if hub is None: hub = sentry_sdk.Hub.current should_track = is_auto_session_tracking_enabled(hub) if should_track: hub.start_session(session_mode=session_mode) try: yield finally: if should_track: hub.end_session() TERMINAL_SESSION_STATES = ("exited", "abnormal", "crashed") MAX_ENVELOPE_ITEMS = 100 def make_aggregate_envelope(aggregate_states, attrs): # type: (Any, Any) -> Any return {"attrs": dict(attrs), "aggregates": list(aggregate_states.values())} class SessionFlusher(object): def __init__( self, capture_func, # type: Callable[[Envelope], None] flush_interval=60, # type: int ): # type: (...) -> None self.capture_func = capture_func self.flush_interval = flush_interval self.pending_sessions = [] # type: List[Any] self.pending_aggregates = {} # type: Dict[Any, Any] self._thread = None # type: Optional[Thread] self._thread_lock = Lock() self._aggregate_lock = Lock() self._thread_for_pid = None # type: Optional[int] self._running = True def flush(self): # type: (...) -> None pending_sessions = self.pending_sessions self.pending_sessions = [] with self._aggregate_lock: pending_aggregates = self.pending_aggregates self.pending_aggregates = {} envelope = Envelope() for session in pending_sessions: if len(envelope.items) == MAX_ENVELOPE_ITEMS: self.capture_func(envelope) envelope = Envelope() envelope.add_session(session) for (attrs, states) in pending_aggregates.items(): if len(envelope.items) == MAX_ENVELOPE_ITEMS: self.capture_func(envelope) envelope = Envelope() envelope.add_sessions(make_aggregate_envelope(states, attrs)) if len(envelope.items) > 0: self.capture_func(envelope) def _ensure_running(self): # type: (...) -> None if self._thread_for_pid == os.getpid() and self._thread is not None: return None with self._thread_lock: if self._thread_for_pid == os.getpid() and self._thread is not None: return None def _thread(): # type: (...) -> None while self._running: time.sleep(self.flush_interval) if self._running: self.flush() thread = Thread(target=_thread) thread.daemon = True thread.start() self._thread = thread self._thread_for_pid = os.getpid() return None def add_aggregate_session( self, session # type: Session ): # type: (...) -> None # NOTE on `session.did`: # the protocol can deal with buckets that have a distinct-id, however # in practice we expect the python SDK to have an extremely high cardinality # here, effectively making aggregation useless, therefore we do not # aggregate per-did. # For this part we can get away with using the global interpreter lock with self._aggregate_lock: attrs = session.get_json_attrs(with_user_info=False) primary_key = tuple(sorted(attrs.items())) secondary_key = session.truncated_started # (, session.did) states = self.pending_aggregates.setdefault(primary_key, {}) state = states.setdefault(secondary_key, {}) if "started" not in state: state["started"] = format_timestamp(session.truncated_started) # if session.did is not None: # state["did"] = session.did if session.status == "crashed": state["crashed"] = state.get("crashed", 0) + 1 elif session.status == "abnormal": state["abnormal"] = state.get("abnormal", 0) + 1 elif session.errors > 0: state["errored"] = state.get("errored", 0) + 1 else: state["exited"] = state.get("exited", 0) + 1 def add_session( self, session # type: Session ): # type: (...) -> None if session.session_mode == "request": self.add_aggregate_session(session) else: self.pending_sessions.append(session.to_json()) self._ensure_running() def kill(self): # type: (...) -> None self._running = False def __del__(self): # type: (...) -> None self.kill()
5,884
Python
32.4375
84
0.586506
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/hub.py
import copy import sys from datetime import datetime from contextlib import contextmanager from sentry_sdk._compat import with_metaclass from sentry_sdk.consts import INSTRUMENTER from sentry_sdk.scope import Scope from sentry_sdk.client import Client from sentry_sdk.tracing import NoOpSpan, Span, Transaction from sentry_sdk.session import Session from sentry_sdk.utils import ( exc_info_from_error, event_from_exception, logger, ContextVar, ) from sentry_sdk._types import MYPY if MYPY: from typing import Union from typing import Any from typing import Optional from typing import Tuple from typing import Dict from typing import List from typing import Callable from typing import Generator from typing import Type from typing import TypeVar from typing import overload from typing import ContextManager from sentry_sdk.integrations import Integration from sentry_sdk._types import ( Event, Hint, Breadcrumb, BreadcrumbHint, ExcInfo, ) from sentry_sdk.consts import ClientConstructor T = TypeVar("T") else: def overload(x): # type: (T) -> T return x _local = ContextVar("sentry_current_hub") def _update_scope(base, scope_change, scope_kwargs): # type: (Scope, Optional[Any], Dict[str, Any]) -> Scope if scope_change and scope_kwargs: raise TypeError("cannot provide scope and kwargs") if scope_change is not None: final_scope = copy.copy(base) if callable(scope_change): scope_change(final_scope) else: final_scope.update_from_scope(scope_change) elif scope_kwargs: final_scope = copy.copy(base) final_scope.update_from_kwargs(**scope_kwargs) else: final_scope = base return final_scope def _should_send_default_pii(): # type: () -> bool client = Hub.current.client if not client: return False return client.options["send_default_pii"] class _InitGuard(object): def __init__(self, client): # type: (Client) -> None self._client = client def __enter__(self): # type: () -> _InitGuard return self def __exit__(self, exc_type, exc_value, tb): # type: (Any, Any, Any) -> None c = self._client if c is not None: c.close() def _check_python_deprecations(): # type: () -> None version = sys.version_info[:2] if version == (3, 4) or version == (3, 5): logger.warning( "sentry-sdk 2.0.0 will drop support for Python %s.", "{}.{}".format(*version), ) logger.warning( "Please upgrade to the latest version to continue receiving upgrades and bugfixes." ) def _init(*args, **kwargs): # type: (*Optional[str], **Any) -> ContextManager[Any] """Initializes the SDK and optionally integrations. This takes the same arguments as the client constructor. """ client = Client(*args, **kwargs) # type: ignore Hub.current.bind_client(client) _check_python_deprecations() rv = _InitGuard(client) return rv from sentry_sdk._types import MYPY if MYPY: # Make mypy, PyCharm and other static analyzers think `init` is a type to # have nicer autocompletion for params. # # Use `ClientConstructor` to define the argument types of `init` and # `ContextManager[Any]` to tell static analyzers about the return type. class init(ClientConstructor, _InitGuard): # noqa: N801 pass else: # Alias `init` for actual usage. Go through the lambda indirection to throw # PyCharm off of the weakly typed signature (it would otherwise discover # both the weakly typed signature of `_init` and our faked `init` type). init = (lambda: _init)() class HubMeta(type): @property def current(cls): # type: () -> Hub """Returns the current instance of the hub.""" rv = _local.get(None) if rv is None: rv = Hub(GLOBAL_HUB) _local.set(rv) return rv @property def main(cls): # type: () -> Hub """Returns the main instance of the hub.""" return GLOBAL_HUB class _ScopeManager(object): def __init__(self, hub): # type: (Hub) -> None self._hub = hub self._original_len = len(hub._stack) self._layer = hub._stack[-1] def __enter__(self): # type: () -> Scope scope = self._layer[1] assert scope is not None return scope def __exit__(self, exc_type, exc_value, tb): # type: (Any, Any, Any) -> None current_len = len(self._hub._stack) if current_len < self._original_len: logger.error( "Scope popped too soon. Popped %s scopes too many.", self._original_len - current_len, ) return elif current_len > self._original_len: logger.warning( "Leaked %s scopes: %s", current_len - self._original_len, self._hub._stack[self._original_len :], ) layer = self._hub._stack[self._original_len - 1] del self._hub._stack[self._original_len - 1 :] if layer[1] != self._layer[1]: logger.error( "Wrong scope found. Meant to pop %s, but popped %s.", layer[1], self._layer[1], ) elif layer[0] != self._layer[0]: warning = ( "init() called inside of pushed scope. This might be entirely " "legitimate but usually occurs when initializing the SDK inside " "a request handler or task/job function. Try to initialize the " "SDK as early as possible instead." ) logger.warning(warning) class Hub(with_metaclass(HubMeta)): # type: ignore """The hub wraps the concurrency management of the SDK. Each thread has its own hub but the hub might transfer with the flow of execution if context vars are available. If the hub is used with a with statement it's temporarily activated. """ _stack = None # type: List[Tuple[Optional[Client], Scope]] # Mypy doesn't pick up on the metaclass. if MYPY: current = None # type: Hub main = None # type: Hub def __init__( self, client_or_hub=None, # type: Optional[Union[Hub, Client]] scope=None, # type: Optional[Any] ): # type: (...) -> None if isinstance(client_or_hub, Hub): hub = client_or_hub client, other_scope = hub._stack[-1] if scope is None: scope = copy.copy(other_scope) else: client = client_or_hub if scope is None: scope = Scope() self._stack = [(client, scope)] self._last_event_id = None # type: Optional[str] self._old_hubs = [] # type: List[Hub] def __enter__(self): # type: () -> Hub self._old_hubs.append(Hub.current) _local.set(self) return self def __exit__( self, exc_type, # type: Optional[type] exc_value, # type: Optional[BaseException] tb, # type: Optional[Any] ): # type: (...) -> None old = self._old_hubs.pop() _local.set(old) def run( self, callback # type: Callable[[], T] ): # type: (...) -> T """Runs a callback in the context of the hub. Alternatively the with statement can be used on the hub directly. """ with self: return callback() def get_integration( self, name_or_class # type: Union[str, Type[Integration]] ): # type: (...) -> Any """Returns the integration for this hub by name or class. If there is no client bound or the client does not have that integration then `None` is returned. If the return value is not `None` the hub is guaranteed to have a client attached. """ if isinstance(name_or_class, str): integration_name = name_or_class elif name_or_class.identifier is not None: integration_name = name_or_class.identifier else: raise ValueError("Integration has no name") client = self.client if client is not None: rv = client.integrations.get(integration_name) if rv is not None: return rv @property def client(self): # type: () -> Optional[Client] """Returns the current client on the hub.""" return self._stack[-1][0] @property def scope(self): # type: () -> Scope """Returns the current scope on the hub.""" return self._stack[-1][1] def last_event_id(self): # type: () -> Optional[str] """Returns the last event ID.""" return self._last_event_id def bind_client( self, new # type: Optional[Client] ): # type: (...) -> None """Binds a new client to the hub.""" top = self._stack[-1] self._stack[-1] = (new, top[1]) def capture_event( self, event, # type: Event hint=None, # type: Optional[Hint] scope=None, # type: Optional[Any] **scope_args # type: Any ): # type: (...) -> Optional[str] """Captures an event. Alias of :py:meth:`sentry_sdk.Client.capture_event`.""" client, top_scope = self._stack[-1] scope = _update_scope(top_scope, scope, scope_args) if client is not None: is_transaction = event.get("type") == "transaction" rv = client.capture_event(event, hint, scope) if rv is not None and not is_transaction: self._last_event_id = rv return rv return None def capture_message( self, message, # type: str level=None, # type: Optional[str] scope=None, # type: Optional[Any] **scope_args # type: Any ): # type: (...) -> Optional[str] """Captures a message. The message is just a string. If no level is provided the default level is `info`. :returns: An `event_id` if the SDK decided to send the event (see :py:meth:`sentry_sdk.Client.capture_event`). """ if self.client is None: return None if level is None: level = "info" return self.capture_event( {"message": message, "level": level}, scope=scope, **scope_args ) def capture_exception( self, error=None, # type: Optional[Union[BaseException, ExcInfo]] scope=None, # type: Optional[Any] **scope_args # type: Any ): # type: (...) -> Optional[str] """Captures an exception. :param error: An exception to catch. If `None`, `sys.exc_info()` will be used. :returns: An `event_id` if the SDK decided to send the event (see :py:meth:`sentry_sdk.Client.capture_event`). """ client = self.client if client is None: return None if error is not None: exc_info = exc_info_from_error(error) else: exc_info = sys.exc_info() event, hint = event_from_exception(exc_info, client_options=client.options) try: return self.capture_event(event, hint=hint, scope=scope, **scope_args) except Exception: self._capture_internal_exception(sys.exc_info()) return None def _capture_internal_exception( self, exc_info # type: Any ): # type: (...) -> Any """ Capture an exception that is likely caused by a bug in the SDK itself. These exceptions do not end up in Sentry and are just logged instead. """ logger.error("Internal error in sentry_sdk", exc_info=exc_info) def add_breadcrumb( self, crumb=None, # type: Optional[Breadcrumb] hint=None, # type: Optional[BreadcrumbHint] **kwargs # type: Any ): # type: (...) -> None """ Adds a breadcrumb. :param crumb: Dictionary with the data as the sentry v7/v8 protocol expects. :param hint: An optional value that can be used by `before_breadcrumb` to customize the breadcrumbs that are emitted. """ client, scope = self._stack[-1] if client is None: logger.info("Dropped breadcrumb because no client bound") return crumb = dict(crumb or ()) # type: Breadcrumb crumb.update(kwargs) if not crumb: return hint = dict(hint or ()) # type: Hint if crumb.get("timestamp") is None: crumb["timestamp"] = datetime.utcnow() if crumb.get("type") is None: crumb["type"] = "default" if client.options["before_breadcrumb"] is not None: new_crumb = client.options["before_breadcrumb"](crumb, hint) else: new_crumb = crumb if new_crumb is not None: scope._breadcrumbs.append(new_crumb) else: logger.info("before breadcrumb dropped breadcrumb (%s)", crumb) max_breadcrumbs = client.options["max_breadcrumbs"] # type: int while len(scope._breadcrumbs) > max_breadcrumbs: scope._breadcrumbs.popleft() def start_span( self, span=None, # type: Optional[Span] instrumenter=INSTRUMENTER.SENTRY, # type: str **kwargs # type: Any ): # type: (...) -> Span """ Create and start timing a new span whose parent is the currently active span or transaction, if any. The return value is a span instance, typically used as a context manager to start and stop timing in a `with` block. Only spans contained in a transaction are sent to Sentry. Most integrations start a transaction at the appropriate time, for example for every incoming HTTP request. Use `start_transaction` to start a new transaction when one is not already in progress. """ configuration_instrumenter = self.client and self.client.options["instrumenter"] if instrumenter != configuration_instrumenter: return NoOpSpan() # TODO: consider removing this in a future release. # This is for backwards compatibility with releases before # start_transaction existed, to allow for a smoother transition. if isinstance(span, Transaction) or "transaction" in kwargs: deprecation_msg = ( "Deprecated: use start_transaction to start transactions and " "Transaction.start_child to start spans." ) if isinstance(span, Transaction): logger.warning(deprecation_msg) return self.start_transaction(span) if "transaction" in kwargs: logger.warning(deprecation_msg) name = kwargs.pop("transaction") return self.start_transaction(name=name, **kwargs) if span is not None: return span kwargs.setdefault("hub", self) span = self.scope.span if span is not None: return span.start_child(**kwargs) return Span(**kwargs) def start_transaction( self, transaction=None, # type: Optional[Transaction] instrumenter=INSTRUMENTER.SENTRY, # type: str **kwargs # type: Any ): # type: (...) -> Union[Transaction, NoOpSpan] """ Start and return a transaction. Start an existing transaction if given, otherwise create and start a new transaction with kwargs. This is the entry point to manual tracing instrumentation. A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a new child span within the transaction or any span, call the respective `.start_child()` method. Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded. When used as context managers, spans and transactions are automatically finished at the end of the `with` block. If not using context managers, call the `.finish()` method. When the transaction is finished, it will be sent to Sentry with all its finished child spans. """ configuration_instrumenter = self.client and self.client.options["instrumenter"] if instrumenter != configuration_instrumenter: return NoOpSpan() custom_sampling_context = kwargs.pop("custom_sampling_context", {}) # if we haven't been given a transaction, make one if transaction is None: kwargs.setdefault("hub", self) transaction = Transaction(**kwargs) # use traces_sample_rate, traces_sampler, and/or inheritance to make a # sampling decision sampling_context = { "transaction_context": transaction.to_json(), "parent_sampled": transaction.parent_sampled, } sampling_context.update(custom_sampling_context) transaction._set_initial_sampling_decision(sampling_context=sampling_context) # we don't bother to keep spans if we already know we're not going to # send the transaction if transaction.sampled: max_spans = ( self.client and self.client.options["_experiments"].get("max_spans") ) or 1000 transaction.init_span_recorder(maxlen=max_spans) return transaction @overload def push_scope( self, callback=None # type: Optional[None] ): # type: (...) -> ContextManager[Scope] pass @overload def push_scope( # noqa: F811 self, callback # type: Callable[[Scope], None] ): # type: (...) -> None pass def push_scope( # noqa self, callback=None # type: Optional[Callable[[Scope], None]] ): # type: (...) -> Optional[ContextManager[Scope]] """ Pushes a new layer on the scope stack. :param callback: If provided, this method pushes a scope, calls `callback`, and pops the scope again. :returns: If no `callback` is provided, a context manager that should be used to pop the scope again. """ if callback is not None: with self.push_scope() as scope: callback(scope) return None client, scope = self._stack[-1] new_layer = (client, copy.copy(scope)) self._stack.append(new_layer) return _ScopeManager(self) def pop_scope_unsafe(self): # type: () -> Tuple[Optional[Client], Scope] """ Pops a scope layer from the stack. Try to use the context manager :py:meth:`push_scope` instead. """ rv = self._stack.pop() assert self._stack, "stack must have at least one layer" return rv @overload def configure_scope( self, callback=None # type: Optional[None] ): # type: (...) -> ContextManager[Scope] pass @overload def configure_scope( # noqa: F811 self, callback # type: Callable[[Scope], None] ): # type: (...) -> None pass def configure_scope( # noqa self, callback=None # type: Optional[Callable[[Scope], None]] ): # type: (...) -> Optional[ContextManager[Scope]] """ Reconfigures the scope. :param callback: If provided, call the callback with the current scope. :returns: If no callback is provided, returns a context manager that returns the scope. """ client, scope = self._stack[-1] if callback is not None: if client is not None: callback(scope) return None @contextmanager def inner(): # type: () -> Generator[Scope, None, None] if client is not None: yield scope else: yield Scope() return inner() def start_session( self, session_mode="application" # type: str ): # type: (...) -> None """Starts a new session.""" self.end_session() client, scope = self._stack[-1] scope._session = Session( release=client.options["release"] if client else None, environment=client.options["environment"] if client else None, user=scope._user, session_mode=session_mode, ) def end_session(self): # type: (...) -> None """Ends the current session if there is one.""" client, scope = self._stack[-1] session = scope._session self.scope._session = None if session is not None: session.close() if client is not None: client.capture_session(session) def stop_auto_session_tracking(self): # type: (...) -> None """Stops automatic session tracking. This temporarily session tracking for the current scope when called. To resume session tracking call `resume_auto_session_tracking`. """ self.end_session() client, scope = self._stack[-1] scope._force_auto_session_tracking = False def resume_auto_session_tracking(self): # type: (...) -> None """Resumes automatic session tracking for the current scope if disabled earlier. This requires that generally automatic session tracking is enabled. """ client, scope = self._stack[-1] scope._force_auto_session_tracking = None def flush( self, timeout=None, # type: Optional[float] callback=None, # type: Optional[Callable[[int, float], None]] ): # type: (...) -> None """ Alias for :py:meth:`sentry_sdk.Client.flush` """ client, scope = self._stack[-1] if client is not None: return client.flush(timeout=timeout, callback=callback) def iter_trace_propagation_headers(self, span=None): # type: (Optional[Span]) -> Generator[Tuple[str, str], None, None] """ Return HTTP headers which allow propagation of trace data. Data taken from the span representing the request, if available, or the current span on the scope if not. """ span = span or self.scope.span if not span: return client = self._stack[-1][0] propagate_traces = client and client.options["propagate_traces"] if not propagate_traces: return for header in span.iter_headers(): yield header def trace_propagation_meta(self, span=None): # type: (Optional[Span]) -> str """ Return meta tags which should be injected into the HTML template to allow propagation of trace data. """ meta = "" for name, content in self.iter_trace_propagation_headers(span): meta += '<meta name="%s" content="%s">' % (name, content) return meta GLOBAL_HUB = Hub() _local.set(GLOBAL_HUB)
23,584
Python
30.488651
118
0.576705
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/worker.py
import os import threading from time import sleep, time from sentry_sdk._compat import check_thread_support from sentry_sdk._queue import Queue, FullError from sentry_sdk.utils import logger from sentry_sdk.consts import DEFAULT_QUEUE_SIZE from sentry_sdk._types import MYPY if MYPY: from typing import Any from typing import Optional from typing import Callable _TERMINATOR = object() class BackgroundWorker(object): def __init__(self, queue_size=DEFAULT_QUEUE_SIZE): # type: (int) -> None check_thread_support() self._queue = Queue(queue_size) # type: Queue self._lock = threading.Lock() self._thread = None # type: Optional[threading.Thread] self._thread_for_pid = None # type: Optional[int] @property def is_alive(self): # type: () -> bool if self._thread_for_pid != os.getpid(): return False if not self._thread: return False return self._thread.is_alive() def _ensure_thread(self): # type: () -> None if not self.is_alive: self.start() def _timed_queue_join(self, timeout): # type: (float) -> bool deadline = time() + timeout queue = self._queue queue.all_tasks_done.acquire() try: while queue.unfinished_tasks: delay = deadline - time() if delay <= 0: return False queue.all_tasks_done.wait(timeout=delay) return True finally: queue.all_tasks_done.release() def start(self): # type: () -> None with self._lock: if not self.is_alive: self._thread = threading.Thread( target=self._target, name="raven-sentry.BackgroundWorker" ) self._thread.daemon = True self._thread.start() self._thread_for_pid = os.getpid() def kill(self): # type: () -> None """ Kill worker thread. Returns immediately. Not useful for waiting on shutdown for events, use `flush` for that. """ logger.debug("background worker got kill request") with self._lock: if self._thread: try: self._queue.put_nowait(_TERMINATOR) except FullError: logger.debug("background worker queue full, kill failed") self._thread = None self._thread_for_pid = None def flush(self, timeout, callback=None): # type: (float, Optional[Any]) -> None logger.debug("background worker got flush request") with self._lock: if self.is_alive and timeout > 0.0: self._wait_flush(timeout, callback) logger.debug("background worker flushed") def _wait_flush(self, timeout, callback): # type: (float, Optional[Any]) -> None initial_timeout = min(0.1, timeout) if not self._timed_queue_join(initial_timeout): pending = self._queue.qsize() + 1 logger.debug("%d event(s) pending on flush", pending) if callback is not None: callback(pending, timeout) if not self._timed_queue_join(timeout - initial_timeout): pending = self._queue.qsize() + 1 logger.error("flush timed out, dropped %s events", pending) def submit(self, callback): # type: (Callable[[], None]) -> bool self._ensure_thread() try: self._queue.put_nowait(callback) return True except FullError: return False def _target(self): # type: () -> None while True: callback = self._queue.get() try: if callback is _TERMINATOR: break try: callback() except Exception: logger.error("Failed processing job", exc_info=True) finally: self._queue.task_done() sleep(0)
4,154
Python
30.007462
77
0.539721
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/asgi.py
""" An ASGI middleware. Based on Tom Christie's `sentry-asgi <https://github.com/encode/sentry-asgi>`. """ import asyncio import inspect import urllib from sentry_sdk._functools import partial from sentry_sdk._types import MYPY from sentry_sdk.consts import OP from sentry_sdk.hub import Hub, _should_send_default_pii from sentry_sdk.integrations._wsgi_common import _filter_headers from sentry_sdk.integrations.modules import _get_installed_modules from sentry_sdk.profiler import start_profiling from sentry_sdk.sessions import auto_session_tracking from sentry_sdk.tracing import ( SOURCE_FOR_STYLE, TRANSACTION_SOURCE_ROUTE, ) from sentry_sdk.utils import ( ContextVar, event_from_exception, HAS_REAL_CONTEXTVARS, CONTEXTVARS_ERROR_MESSAGE, logger, transaction_from_function, ) from sentry_sdk.tracing import Transaction if MYPY: from typing import Dict from typing import Any from typing import Optional from typing import Callable from typing_extensions import Literal from sentry_sdk._types import Event, Hint _asgi_middleware_applied = ContextVar("sentry_asgi_middleware_applied") _DEFAULT_TRANSACTION_NAME = "generic ASGI request" TRANSACTION_STYLE_VALUES = ("endpoint", "url") def _capture_exception(hub, exc, mechanism_type="asgi"): # type: (Hub, Any, str) -> None # Check client here as it might have been unset while streaming response if hub.client is not None: event, hint = event_from_exception( exc, client_options=hub.client.options, mechanism={"type": mechanism_type, "handled": False}, ) hub.capture_event(event, hint=hint) def _looks_like_asgi3(app): # type: (Any) -> bool """ Try to figure out if an application object supports ASGI3. This is how uvicorn figures out the application version as well. """ if inspect.isclass(app): return hasattr(app, "__await__") elif inspect.isfunction(app): return asyncio.iscoroutinefunction(app) else: call = getattr(app, "__call__", None) # noqa return asyncio.iscoroutinefunction(call) class SentryAsgiMiddleware: __slots__ = ("app", "__call__", "transaction_style", "mechanism_type") def __init__( self, app, unsafe_context_data=False, transaction_style="endpoint", mechanism_type="asgi", ): # type: (Any, bool, str, str) -> None """ Instrument an ASGI application with Sentry. Provides HTTP/websocket data to sent events and basic handling for exceptions bubbling up through the middleware. :param unsafe_context_data: Disable errors when a proper contextvars installation could not be found. We do not recommend changing this from the default. """ if not unsafe_context_data and not HAS_REAL_CONTEXTVARS: # We better have contextvars or we're going to leak state between # requests. raise RuntimeError( "The ASGI middleware for Sentry requires Python 3.7+ " "or the aiocontextvars package." + CONTEXTVARS_ERROR_MESSAGE ) if transaction_style not in TRANSACTION_STYLE_VALUES: raise ValueError( "Invalid value for transaction_style: %s (must be in %s)" % (transaction_style, TRANSACTION_STYLE_VALUES) ) asgi_middleware_while_using_starlette_or_fastapi = ( mechanism_type == "asgi" and "starlette" in _get_installed_modules() ) if asgi_middleware_while_using_starlette_or_fastapi: logger.warning( "The Sentry Python SDK can now automatically support ASGI frameworks like Starlette and FastAPI. " "Please remove 'SentryAsgiMiddleware' from your project. " "See https://docs.sentry.io/platforms/python/guides/asgi/ for more information." ) self.transaction_style = transaction_style self.mechanism_type = mechanism_type self.app = app if _looks_like_asgi3(app): self.__call__ = self._run_asgi3 # type: Callable[..., Any] else: self.__call__ = self._run_asgi2 def _run_asgi2(self, scope): # type: (Any) -> Any async def inner(receive, send): # type: (Any, Any) -> Any return await self._run_app(scope, lambda: self.app(scope)(receive, send)) return inner async def _run_asgi3(self, scope, receive, send): # type: (Any, Any, Any) -> Any return await self._run_app(scope, lambda: self.app(scope, receive, send)) async def _run_app(self, scope, callback): # type: (Any, Any) -> Any is_recursive_asgi_middleware = _asgi_middleware_applied.get(False) if is_recursive_asgi_middleware: try: return await callback() except Exception as exc: _capture_exception(Hub.current, exc, mechanism_type=self.mechanism_type) raise exc from None _asgi_middleware_applied.set(True) try: hub = Hub(Hub.current) with auto_session_tracking(hub, session_mode="request"): with hub: with hub.configure_scope() as sentry_scope: sentry_scope.clear_breadcrumbs() sentry_scope._name = "asgi" processor = partial(self.event_processor, asgi_scope=scope) sentry_scope.add_event_processor(processor) ty = scope["type"] if ty in ("http", "websocket"): transaction = Transaction.continue_from_headers( self._get_headers(scope), op="{}.server".format(ty), ) else: transaction = Transaction(op=OP.HTTP_SERVER) transaction.name = _DEFAULT_TRANSACTION_NAME transaction.source = TRANSACTION_SOURCE_ROUTE transaction.set_tag("asgi.type", ty) with hub.start_transaction( transaction, custom_sampling_context={"asgi_scope": scope} ), start_profiling(transaction, hub): # XXX: Would be cool to have correct span status, but we # would have to wrap send(). That is a bit hard to do with # the current abstraction over ASGI 2/3. try: return await callback() except Exception as exc: _capture_exception( hub, exc, mechanism_type=self.mechanism_type ) raise exc from None finally: _asgi_middleware_applied.set(False) def event_processor(self, event, hint, asgi_scope): # type: (Event, Hint, Any) -> Optional[Event] request_info = event.get("request", {}) ty = asgi_scope["type"] if ty in ("http", "websocket"): request_info["method"] = asgi_scope.get("method") request_info["headers"] = headers = _filter_headers( self._get_headers(asgi_scope) ) request_info["query_string"] = self._get_query(asgi_scope) request_info["url"] = self._get_url( asgi_scope, "http" if ty == "http" else "ws", headers.get("host") ) client = asgi_scope.get("client") if client and _should_send_default_pii(): request_info["env"] = {"REMOTE_ADDR": self._get_ip(asgi_scope)} self._set_transaction_name_and_source(event, self.transaction_style, asgi_scope) event["request"] = request_info return event # Helper functions for extracting request data. # # Note: Those functions are not public API. If you want to mutate request # data to your liking it's recommended to use the `before_send` callback # for that. def _set_transaction_name_and_source(self, event, transaction_style, asgi_scope): # type: (Event, str, Any) -> None transaction_name_already_set = ( event.get("transaction", _DEFAULT_TRANSACTION_NAME) != _DEFAULT_TRANSACTION_NAME ) if transaction_name_already_set: return name = "" if transaction_style == "endpoint": endpoint = asgi_scope.get("endpoint") # Webframeworks like Starlette mutate the ASGI env once routing is # done, which is sometime after the request has started. If we have # an endpoint, overwrite our generic transaction name. if endpoint: name = transaction_from_function(endpoint) or "" elif transaction_style == "url": # FastAPI includes the route object in the scope to let Sentry extract the # path from it for the transaction name route = asgi_scope.get("route") if route: path = getattr(route, "path", None) if path is not None: name = path if not name: event["transaction"] = _DEFAULT_TRANSACTION_NAME event["transaction_info"] = {"source": TRANSACTION_SOURCE_ROUTE} return event["transaction"] = name event["transaction_info"] = {"source": SOURCE_FOR_STYLE[transaction_style]} def _get_url(self, scope, default_scheme, host): # type: (Dict[str, Any], Literal["ws", "http"], Optional[str]) -> str """ Extract URL from the ASGI scope, without also including the querystring. """ scheme = scope.get("scheme", default_scheme) server = scope.get("server", None) path = scope.get("root_path", "") + scope.get("path", "") if host: return "%s://%s%s" % (scheme, host, path) if server is not None: host, port = server default_port = {"http": 80, "https": 443, "ws": 80, "wss": 443}[scheme] if port != default_port: return "%s://%s:%s%s" % (scheme, host, port, path) return "%s://%s%s" % (scheme, host, path) return path def _get_query(self, scope): # type: (Any) -> Any """ Extract querystring from the ASGI scope, in the format that the Sentry protocol expects. """ qs = scope.get("query_string") if not qs: return None return urllib.parse.unquote(qs.decode("latin-1")) def _get_ip(self, scope): # type: (Any) -> str """ Extract IP Address from the ASGI scope based on request headers with fallback to scope client. """ headers = self._get_headers(scope) try: return headers["x-forwarded-for"].split(",")[0].strip() except (KeyError, IndexError): pass try: return headers["x-real-ip"] except KeyError: pass return scope.get("client")[0] def _get_headers(self, scope): # type: (Any) -> Dict[str, str] """ Extract headers from the ASGI scope, in the format that the Sentry protocol expects. """ headers = {} # type: Dict[str, str] for raw_key, raw_value in scope["headers"]: key = raw_key.decode("latin-1") value = raw_value.decode("latin-1") if key in headers: headers[key] = headers[key] + ", " + value else: headers[key] = value return headers
11,827
Python
35.506173
161
0.572673
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/pyramid.py
from __future__ import absolute_import import os import sys import weakref from sentry_sdk.hub import Hub, _should_send_default_pii from sentry_sdk.scope import Scope from sentry_sdk.tracing import SOURCE_FOR_STYLE from sentry_sdk.utils import ( capture_internal_exceptions, event_from_exception, ) from sentry_sdk._compat import reraise, iteritems from sentry_sdk.integrations import Integration, DidNotEnable from sentry_sdk.integrations._wsgi_common import RequestExtractor from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware try: from pyramid.httpexceptions import HTTPException from pyramid.request import Request except ImportError: raise DidNotEnable("Pyramid not installed") from sentry_sdk._types import MYPY if MYPY: from pyramid.response import Response from typing import Any from sentry_sdk.integrations.wsgi import _ScopedResponse from typing import Callable from typing import Dict from typing import Optional from webob.cookies import RequestCookies # type: ignore from webob.compat import cgi_FieldStorage # type: ignore from sentry_sdk.utils import ExcInfo from sentry_sdk._types import EventProcessor if getattr(Request, "authenticated_userid", None): def authenticated_userid(request): # type: (Request) -> Optional[Any] return request.authenticated_userid else: # bw-compat for pyramid < 1.5 from pyramid.security import authenticated_userid # type: ignore TRANSACTION_STYLE_VALUES = ("route_name", "route_pattern") class PyramidIntegration(Integration): identifier = "pyramid" transaction_style = "" def __init__(self, transaction_style="route_name"): # type: (str) -> None if transaction_style not in TRANSACTION_STYLE_VALUES: raise ValueError( "Invalid value for transaction_style: %s (must be in %s)" % (transaction_style, TRANSACTION_STYLE_VALUES) ) self.transaction_style = transaction_style @staticmethod def setup_once(): # type: () -> None from pyramid import router old_call_view = router._call_view def sentry_patched_call_view(registry, request, *args, **kwargs): # type: (Any, Request, *Any, **Any) -> Response hub = Hub.current integration = hub.get_integration(PyramidIntegration) if integration is not None: with hub.configure_scope() as scope: _set_transaction_name_and_source( scope, integration.transaction_style, request ) scope.add_event_processor( _make_event_processor(weakref.ref(request), integration) ) return old_call_view(registry, request, *args, **kwargs) router._call_view = sentry_patched_call_view if hasattr(Request, "invoke_exception_view"): old_invoke_exception_view = Request.invoke_exception_view def sentry_patched_invoke_exception_view(self, *args, **kwargs): # type: (Request, *Any, **Any) -> Any rv = old_invoke_exception_view(self, *args, **kwargs) if ( self.exc_info and all(self.exc_info) and rv.status_int == 500 and Hub.current.get_integration(PyramidIntegration) is not None ): _capture_exception(self.exc_info) return rv Request.invoke_exception_view = sentry_patched_invoke_exception_view old_wsgi_call = router.Router.__call__ def sentry_patched_wsgi_call(self, environ, start_response): # type: (Any, Dict[str, str], Callable[..., Any]) -> _ScopedResponse hub = Hub.current integration = hub.get_integration(PyramidIntegration) if integration is None: return old_wsgi_call(self, environ, start_response) def sentry_patched_inner_wsgi_call(environ, start_response): # type: (Dict[str, Any], Callable[..., Any]) -> Any try: return old_wsgi_call(self, environ, start_response) except Exception: einfo = sys.exc_info() _capture_exception(einfo) reraise(*einfo) return SentryWsgiMiddleware(sentry_patched_inner_wsgi_call)( environ, start_response ) router.Router.__call__ = sentry_patched_wsgi_call def _capture_exception(exc_info): # type: (ExcInfo) -> None if exc_info[0] is None or issubclass(exc_info[0], HTTPException): return hub = Hub.current if hub.get_integration(PyramidIntegration) is None: return # If an integration is there, a client has to be there. client = hub.client # type: Any event, hint = event_from_exception( exc_info, client_options=client.options, mechanism={"type": "pyramid", "handled": False}, ) hub.capture_event(event, hint=hint) def _set_transaction_name_and_source(scope, transaction_style, request): # type: (Scope, str, Request) -> None try: name_for_style = { "route_name": request.matched_route.name, "route_pattern": request.matched_route.pattern, } scope.set_transaction_name( name_for_style[transaction_style], source=SOURCE_FOR_STYLE[transaction_style], ) except Exception: pass class PyramidRequestExtractor(RequestExtractor): def url(self): # type: () -> str return self.request.path_url def env(self): # type: () -> Dict[str, str] return self.request.environ def cookies(self): # type: () -> RequestCookies return self.request.cookies def raw_data(self): # type: () -> str return self.request.text def form(self): # type: () -> Dict[str, str] return { key: value for key, value in iteritems(self.request.POST) if not getattr(value, "filename", None) } def files(self): # type: () -> Dict[str, cgi_FieldStorage] return { key: value for key, value in iteritems(self.request.POST) if getattr(value, "filename", None) } def size_of_file(self, postdata): # type: (cgi_FieldStorage) -> int file = postdata.file try: return os.fstat(file.fileno()).st_size except Exception: return 0 def _make_event_processor(weak_request, integration): # type: (Callable[[], Request], PyramidIntegration) -> EventProcessor def event_processor(event, hint): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] request = weak_request() if request is None: return event with capture_internal_exceptions(): PyramidRequestExtractor(request).extract_into_event(event) if _should_send_default_pii(): with capture_internal_exceptions(): user_info = event.setdefault("user", {}) user_info.setdefault("id", authenticated_userid(request)) return event return event_processor
7,424
Python
30.595745
83
0.603314
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/gnu_backtrace.py
import re from sentry_sdk.hub import Hub from sentry_sdk.integrations import Integration from sentry_sdk.scope import add_global_event_processor from sentry_sdk.utils import capture_internal_exceptions from sentry_sdk._types import MYPY if MYPY: from typing import Any from typing import Dict MODULE_RE = r"[a-zA-Z0-9/._:\\-]+" TYPE_RE = r"[a-zA-Z0-9._:<>,-]+" HEXVAL_RE = r"[A-Fa-f0-9]+" FRAME_RE = r""" ^(?P<index>\d+)\.\s (?P<package>{MODULE_RE})\( (?P<retval>{TYPE_RE}\ )? ((?P<function>{TYPE_RE}) (?P<args>\(.*\))? )? ((?P<constoffset>\ const)?\+0x(?P<offset>{HEXVAL_RE}))? \)\s \[0x(?P<retaddr>{HEXVAL_RE})\]$ """.format( MODULE_RE=MODULE_RE, HEXVAL_RE=HEXVAL_RE, TYPE_RE=TYPE_RE ) FRAME_RE = re.compile(FRAME_RE, re.MULTILINE | re.VERBOSE) class GnuBacktraceIntegration(Integration): identifier = "gnu_backtrace" @staticmethod def setup_once(): # type: () -> None @add_global_event_processor def process_gnu_backtrace(event, hint): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] with capture_internal_exceptions(): return _process_gnu_backtrace(event, hint) def _process_gnu_backtrace(event, hint): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] if Hub.current.get_integration(GnuBacktraceIntegration) is None: return event exc_info = hint.get("exc_info", None) if exc_info is None: return event exception = event.get("exception", None) if exception is None: return event values = exception.get("values", None) if values is None: return event for exception in values: frames = exception.get("stacktrace", {}).get("frames", []) if not frames: continue msg = exception.get("value", None) if not msg: continue additional_frames = [] new_msg = [] for line in msg.splitlines(): match = FRAME_RE.match(line) if match: additional_frames.append( ( int(match.group("index")), { "package": match.group("package") or None, "function": match.group("function") or None, "platform": "native", }, ) ) else: # Put garbage lines back into message, not sure what to do with them. new_msg.append(line) if additional_frames: additional_frames.sort(key=lambda x: -x[0]) for _, frame in additional_frames: frames.append(frame) new_msg.append("<stacktrace parsed and removed by GnuBacktraceIntegration>") exception["value"] = "\n".join(new_msg) return event
2,912
Python
25.972222
88
0.550824
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/argv.py
from __future__ import absolute_import import sys from sentry_sdk.hub import Hub from sentry_sdk.integrations import Integration from sentry_sdk.scope import add_global_event_processor from sentry_sdk._types import MYPY if MYPY: from typing import Optional from sentry_sdk._types import Event, Hint class ArgvIntegration(Integration): identifier = "argv" @staticmethod def setup_once(): # type: () -> None @add_global_event_processor def processor(event, hint): # type: (Event, Optional[Hint]) -> Optional[Event] if Hub.current.get_integration(ArgvIntegration) is not None: extra = event.setdefault("extra", {}) # If some event processor decided to set extra to e.g. an # `int`, don't crash. Not here. if isinstance(extra, dict): extra["sys.argv"] = sys.argv return event
945
Python
26.823529
73
0.621164
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/wsgi.py
import sys from sentry_sdk._functools import partial from sentry_sdk.consts import OP from sentry_sdk.hub import Hub, _should_send_default_pii from sentry_sdk.utils import ( ContextVar, capture_internal_exceptions, event_from_exception, ) from sentry_sdk._compat import PY2, reraise, iteritems from sentry_sdk.tracing import Transaction, TRANSACTION_SOURCE_ROUTE from sentry_sdk.sessions import auto_session_tracking from sentry_sdk.integrations._wsgi_common import _filter_headers from sentry_sdk.profiler import start_profiling from sentry_sdk._types import MYPY if MYPY: from typing import Callable from typing import Dict from typing import Iterator from typing import Any from typing import Tuple from typing import Optional from typing import TypeVar from typing import Protocol from sentry_sdk.utils import ExcInfo from sentry_sdk._types import EventProcessor WsgiResponseIter = TypeVar("WsgiResponseIter") WsgiResponseHeaders = TypeVar("WsgiResponseHeaders") WsgiExcInfo = TypeVar("WsgiExcInfo") class StartResponse(Protocol): def __call__(self, status, response_headers, exc_info=None): # type: (str, WsgiResponseHeaders, Optional[WsgiExcInfo]) -> WsgiResponseIter pass _wsgi_middleware_applied = ContextVar("sentry_wsgi_middleware_applied") if PY2: def wsgi_decoding_dance(s, charset="utf-8", errors="replace"): # type: (str, str, str) -> str return s.decode(charset, errors) else: def wsgi_decoding_dance(s, charset="utf-8", errors="replace"): # type: (str, str, str) -> str return s.encode("latin1").decode(charset, errors) def get_host(environ, use_x_forwarded_for=False): # type: (Dict[str, str], bool) -> str """Return the host for the given WSGI environment. Yanked from Werkzeug.""" if use_x_forwarded_for and "HTTP_X_FORWARDED_HOST" in environ: rv = environ["HTTP_X_FORWARDED_HOST"] if environ["wsgi.url_scheme"] == "http" and rv.endswith(":80"): rv = rv[:-3] elif environ["wsgi.url_scheme"] == "https" and rv.endswith(":443"): rv = rv[:-4] elif environ.get("HTTP_HOST"): rv = environ["HTTP_HOST"] if environ["wsgi.url_scheme"] == "http" and rv.endswith(":80"): rv = rv[:-3] elif environ["wsgi.url_scheme"] == "https" and rv.endswith(":443"): rv = rv[:-4] elif environ.get("SERVER_NAME"): rv = environ["SERVER_NAME"] if (environ["wsgi.url_scheme"], environ["SERVER_PORT"]) not in ( ("https", "443"), ("http", "80"), ): rv += ":" + environ["SERVER_PORT"] else: # In spite of the WSGI spec, SERVER_NAME might not be present. rv = "unknown" return rv def get_request_url(environ, use_x_forwarded_for=False): # type: (Dict[str, str], bool) -> str """Return the absolute URL without query string for the given WSGI environment.""" return "%s://%s/%s" % ( environ.get("wsgi.url_scheme"), get_host(environ, use_x_forwarded_for), wsgi_decoding_dance(environ.get("PATH_INFO") or "").lstrip("/"), ) class SentryWsgiMiddleware(object): __slots__ = ("app", "use_x_forwarded_for") def __init__(self, app, use_x_forwarded_for=False): # type: (Callable[[Dict[str, str], Callable[..., Any]], Any], bool) -> None self.app = app self.use_x_forwarded_for = use_x_forwarded_for def __call__(self, environ, start_response): # type: (Dict[str, str], Callable[..., Any]) -> _ScopedResponse if _wsgi_middleware_applied.get(False): return self.app(environ, start_response) _wsgi_middleware_applied.set(True) try: hub = Hub(Hub.current) with auto_session_tracking(hub, session_mode="request"): with hub: with capture_internal_exceptions(): with hub.configure_scope() as scope: scope.clear_breadcrumbs() scope._name = "wsgi" scope.add_event_processor( _make_wsgi_event_processor( environ, self.use_x_forwarded_for ) ) transaction = Transaction.continue_from_environ( environ, op=OP.HTTP_SERVER, name="generic WSGI request", source=TRANSACTION_SOURCE_ROUTE, ) with hub.start_transaction( transaction, custom_sampling_context={"wsgi_environ": environ} ), start_profiling(transaction, hub): try: rv = self.app( environ, partial( _sentry_start_response, start_response, transaction ), ) except BaseException: reraise(*_capture_exception(hub)) finally: _wsgi_middleware_applied.set(False) return _ScopedResponse(hub, rv) def _sentry_start_response( old_start_response, # type: StartResponse transaction, # type: Transaction status, # type: str response_headers, # type: WsgiResponseHeaders exc_info=None, # type: Optional[WsgiExcInfo] ): # type: (...) -> WsgiResponseIter with capture_internal_exceptions(): status_int = int(status.split(" ", 1)[0]) transaction.set_http_status(status_int) if exc_info is None: # The Django Rest Framework WSGI test client, and likely other # (incorrect) implementations, cannot deal with the exc_info argument # if one is present. Avoid providing a third argument if not necessary. return old_start_response(status, response_headers) else: return old_start_response(status, response_headers, exc_info) def _get_environ(environ): # type: (Dict[str, str]) -> Iterator[Tuple[str, str]] """ Returns our explicitly included environment variables we want to capture (server name, port and remote addr if pii is enabled). """ keys = ["SERVER_NAME", "SERVER_PORT"] if _should_send_default_pii(): # make debugging of proxy setup easier. Proxy headers are # in headers. keys += ["REMOTE_ADDR"] for key in keys: if key in environ: yield key, environ[key] # `get_headers` comes from `werkzeug.datastructures.EnvironHeaders` # # We need this function because Django does not give us a "pure" http header # dict. So we might as well use it for all WSGI integrations. def _get_headers(environ): # type: (Dict[str, str]) -> Iterator[Tuple[str, str]] """ Returns only proper HTTP headers. """ for key, value in iteritems(environ): key = str(key) if key.startswith("HTTP_") and key not in ( "HTTP_CONTENT_TYPE", "HTTP_CONTENT_LENGTH", ): yield key[5:].replace("_", "-").title(), value elif key in ("CONTENT_TYPE", "CONTENT_LENGTH"): yield key.replace("_", "-").title(), value def get_client_ip(environ): # type: (Dict[str, str]) -> Optional[Any] """ Infer the user IP address from various headers. This cannot be used in security sensitive situations since the value may be forged from a client, but it's good enough for the event payload. """ try: return environ["HTTP_X_FORWARDED_FOR"].split(",")[0].strip() except (KeyError, IndexError): pass try: return environ["HTTP_X_REAL_IP"] except KeyError: pass return environ.get("REMOTE_ADDR") def _capture_exception(hub): # type: (Hub) -> ExcInfo exc_info = sys.exc_info() # Check client here as it might have been unset while streaming response if hub.client is not None: e = exc_info[1] # SystemExit(0) is the only uncaught exception that is expected behavior should_skip_capture = isinstance(e, SystemExit) and e.code in (0, None) if not should_skip_capture: event, hint = event_from_exception( exc_info, client_options=hub.client.options, mechanism={"type": "wsgi", "handled": False}, ) hub.capture_event(event, hint=hint) return exc_info class _ScopedResponse(object): __slots__ = ("_response", "_hub") def __init__(self, hub, response): # type: (Hub, Iterator[bytes]) -> None self._hub = hub self._response = response def __iter__(self): # type: () -> Iterator[bytes] iterator = iter(self._response) while True: with self._hub: try: chunk = next(iterator) except StopIteration: break except BaseException: reraise(*_capture_exception(self._hub)) yield chunk def close(self): # type: () -> None with self._hub: try: self._response.close() # type: ignore except AttributeError: pass except BaseException: reraise(*_capture_exception(self._hub)) def _make_wsgi_event_processor(environ, use_x_forwarded_for): # type: (Dict[str, str], bool) -> EventProcessor # It's a bit unfortunate that we have to extract and parse the request data # from the environ so eagerly, but there are a few good reasons for this. # # We might be in a situation where the scope/hub never gets torn down # properly. In that case we will have an unnecessary strong reference to # all objects in the environ (some of which may take a lot of memory) when # we're really just interested in a few of them. # # Keeping the environment around for longer than the request lifecycle is # also not necessarily something uWSGI can deal with: # https://github.com/unbit/uwsgi/issues/1950 client_ip = get_client_ip(environ) request_url = get_request_url(environ, use_x_forwarded_for) query_string = environ.get("QUERY_STRING") method = environ.get("REQUEST_METHOD") env = dict(_get_environ(environ)) headers = _filter_headers(dict(_get_headers(environ))) def event_processor(event, hint): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] with capture_internal_exceptions(): # if the code below fails halfway through we at least have some data request_info = event.setdefault("request", {}) if _should_send_default_pii(): user_info = event.setdefault("user", {}) if client_ip: user_info.setdefault("ip_address", client_ip) request_info["url"] = request_url request_info["query_string"] = query_string request_info["method"] = method request_info["env"] = env request_info["headers"] = headers return event return event_processor
11,397
Python
33.96319
89
0.583224
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/aiohttp.py
import sys import weakref from sentry_sdk._compat import reraise from sentry_sdk.consts import OP from sentry_sdk.hub import Hub from sentry_sdk.integrations import Integration, DidNotEnable from sentry_sdk.integrations.logging import ignore_logger from sentry_sdk.sessions import auto_session_tracking from sentry_sdk.integrations._wsgi_common import ( _filter_headers, request_body_within_bounds, ) from sentry_sdk.tracing import SOURCE_FOR_STYLE, Transaction, TRANSACTION_SOURCE_ROUTE from sentry_sdk.utils import ( capture_internal_exceptions, event_from_exception, transaction_from_function, HAS_REAL_CONTEXTVARS, CONTEXTVARS_ERROR_MESSAGE, AnnotatedValue, ) try: import asyncio from aiohttp import __version__ as AIOHTTP_VERSION from aiohttp.web import Application, HTTPException, UrlDispatcher except ImportError: raise DidNotEnable("AIOHTTP not installed") from sentry_sdk._types import MYPY if MYPY: from aiohttp.web_request import Request from aiohttp.abc import AbstractMatchInfo from typing import Any from typing import Dict from typing import Optional from typing import Tuple from typing import Callable from typing import Union from sentry_sdk.utils import ExcInfo from sentry_sdk._types import EventProcessor TRANSACTION_STYLE_VALUES = ("handler_name", "method_and_path_pattern") class AioHttpIntegration(Integration): identifier = "aiohttp" def __init__(self, transaction_style="handler_name"): # type: (str) -> None if transaction_style not in TRANSACTION_STYLE_VALUES: raise ValueError( "Invalid value for transaction_style: %s (must be in %s)" % (transaction_style, TRANSACTION_STYLE_VALUES) ) self.transaction_style = transaction_style @staticmethod def setup_once(): # type: () -> None try: version = tuple(map(int, AIOHTTP_VERSION.split(".")[:2])) except (TypeError, ValueError): raise DidNotEnable("AIOHTTP version unparsable: {}".format(AIOHTTP_VERSION)) if version < (3, 4): raise DidNotEnable("AIOHTTP 3.4 or newer required.") if not HAS_REAL_CONTEXTVARS: # We better have contextvars or we're going to leak state between # requests. raise DidNotEnable( "The aiohttp integration for Sentry requires Python 3.7+ " " or aiocontextvars package." + CONTEXTVARS_ERROR_MESSAGE ) ignore_logger("aiohttp.server") old_handle = Application._handle async def sentry_app_handle(self, request, *args, **kwargs): # type: (Any, Request, *Any, **Any) -> Any hub = Hub.current if hub.get_integration(AioHttpIntegration) is None: return await old_handle(self, request, *args, **kwargs) weak_request = weakref.ref(request) with Hub(hub) as hub: with auto_session_tracking(hub, session_mode="request"): # Scope data will not leak between requests because aiohttp # create a task to wrap each request. with hub.configure_scope() as scope: scope.clear_breadcrumbs() scope.add_event_processor(_make_request_processor(weak_request)) transaction = Transaction.continue_from_headers( request.headers, op=OP.HTTP_SERVER, # If this transaction name makes it to the UI, AIOHTTP's # URL resolver did not find a route or died trying. name="generic AIOHTTP request", source=TRANSACTION_SOURCE_ROUTE, ) with hub.start_transaction( transaction, custom_sampling_context={"aiohttp_request": request}, ): try: response = await old_handle(self, request) except HTTPException as e: transaction.set_http_status(e.status_code) raise except (asyncio.CancelledError, ConnectionResetError): transaction.set_status("cancelled") raise except Exception: # This will probably map to a 500 but seems like we # have no way to tell. Do not set span status. reraise(*_capture_exception(hub)) transaction.set_http_status(response.status) return response Application._handle = sentry_app_handle old_urldispatcher_resolve = UrlDispatcher.resolve async def sentry_urldispatcher_resolve(self, request): # type: (UrlDispatcher, Request) -> AbstractMatchInfo rv = await old_urldispatcher_resolve(self, request) hub = Hub.current integration = hub.get_integration(AioHttpIntegration) name = None try: if integration.transaction_style == "handler_name": name = transaction_from_function(rv.handler) elif integration.transaction_style == "method_and_path_pattern": route_info = rv.get_info() pattern = route_info.get("path") or route_info.get("formatter") name = "{} {}".format(request.method, pattern) except Exception: pass if name is not None: with Hub.current.configure_scope() as scope: scope.set_transaction_name( name, source=SOURCE_FOR_STYLE[integration.transaction_style], ) return rv UrlDispatcher.resolve = sentry_urldispatcher_resolve def _make_request_processor(weak_request): # type: (Callable[[], Request]) -> EventProcessor def aiohttp_processor( event, # type: Dict[str, Any] hint, # type: Dict[str, Tuple[type, BaseException, Any]] ): # type: (...) -> Dict[str, Any] request = weak_request() if request is None: return event with capture_internal_exceptions(): request_info = event.setdefault("request", {}) request_info["url"] = "%s://%s%s" % ( request.scheme, request.host, request.path, ) request_info["query_string"] = request.query_string request_info["method"] = request.method request_info["env"] = {"REMOTE_ADDR": request.remote} hub = Hub.current request_info["headers"] = _filter_headers(dict(request.headers)) # Just attach raw data here if it is within bounds, if available. # Unfortunately there's no way to get structured data from aiohttp # without awaiting on some coroutine. request_info["data"] = get_aiohttp_request_data(hub, request) return event return aiohttp_processor def _capture_exception(hub): # type: (Hub) -> ExcInfo exc_info = sys.exc_info() event, hint = event_from_exception( exc_info, client_options=hub.client.options, # type: ignore mechanism={"type": "aiohttp", "handled": False}, ) hub.capture_event(event, hint=hint) return exc_info BODY_NOT_READ_MESSAGE = "[Can't show request body due to implementation details.]" def get_aiohttp_request_data(hub, request): # type: (Hub, Request) -> Union[Optional[str], AnnotatedValue] bytes_body = request._read_bytes if bytes_body is not None: # we have body to show if not request_body_within_bounds(hub.client, len(bytes_body)): return AnnotatedValue.removed_because_over_size_limit() encoding = request.charset or "utf-8" return bytes_body.decode(encoding, "replace") if request.can_read_body: # body exists but we can't show it return BODY_NOT_READ_MESSAGE # request has no body return None
8,393
Python
34.567796
88
0.583939
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/sqlalchemy.py
from __future__ import absolute_import import re from sentry_sdk._types import MYPY from sentry_sdk.hub import Hub from sentry_sdk.integrations import Integration, DidNotEnable from sentry_sdk.tracing_utils import record_sql_queries try: from sqlalchemy.engine import Engine # type: ignore from sqlalchemy.event import listen # type: ignore from sqlalchemy import __version__ as SQLALCHEMY_VERSION # type: ignore except ImportError: raise DidNotEnable("SQLAlchemy not installed.") if MYPY: from typing import Any from typing import ContextManager from typing import Optional from sentry_sdk.tracing import Span class SqlalchemyIntegration(Integration): identifier = "sqlalchemy" @staticmethod def setup_once(): # type: () -> None try: version = tuple( map(int, re.split("b|rc", SQLALCHEMY_VERSION)[0].split(".")) ) except (TypeError, ValueError): raise DidNotEnable( "Unparsable SQLAlchemy version: {}".format(SQLALCHEMY_VERSION) ) if version < (1, 2): raise DidNotEnable("SQLAlchemy 1.2 or newer required.") listen(Engine, "before_cursor_execute", _before_cursor_execute) listen(Engine, "after_cursor_execute", _after_cursor_execute) listen(Engine, "handle_error", _handle_error) def _before_cursor_execute( conn, cursor, statement, parameters, context, executemany, *args ): # type: (Any, Any, Any, Any, Any, bool, *Any) -> None hub = Hub.current if hub.get_integration(SqlalchemyIntegration) is None: return ctx_mgr = record_sql_queries( hub, cursor, statement, parameters, paramstyle=context and context.dialect and context.dialect.paramstyle or None, executemany=executemany, ) context._sentry_sql_span_manager = ctx_mgr span = ctx_mgr.__enter__() if span is not None: context._sentry_sql_span = span def _after_cursor_execute(conn, cursor, statement, parameters, context, *args): # type: (Any, Any, Any, Any, Any, *Any) -> None ctx_mgr = getattr( context, "_sentry_sql_span_manager", None ) # type: Optional[ContextManager[Any]] if ctx_mgr is not None: context._sentry_sql_span_manager = None ctx_mgr.__exit__(None, None, None) def _handle_error(context, *args): # type: (Any, *Any) -> None execution_context = context.execution_context if execution_context is None: return span = getattr(execution_context, "_sentry_sql_span", None) # type: Optional[Span] if span is not None: span.set_status("internal_error") # _after_cursor_execute does not get called for crashing SQL stmts. Judging # from SQLAlchemy codebase it does seem like any error coming into this # handler is going to be fatal. ctx_mgr = getattr( execution_context, "_sentry_sql_span_manager", None ) # type: Optional[ContextManager[Any]] if ctx_mgr is not None: execution_context._sentry_sql_span_manager = None ctx_mgr.__exit__(None, None, None)
3,165
Python
29.152381
87
0.649605
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/pymongo.py
from __future__ import absolute_import import copy from sentry_sdk import Hub from sentry_sdk.hub import _should_send_default_pii from sentry_sdk.integrations import DidNotEnable, Integration from sentry_sdk.tracing import Span from sentry_sdk.utils import capture_internal_exceptions from sentry_sdk._types import MYPY try: from pymongo import monitoring except ImportError: raise DidNotEnable("Pymongo not installed") if MYPY: from typing import Any, Dict, Union from pymongo.monitoring import ( CommandFailedEvent, CommandStartedEvent, CommandSucceededEvent, ) SAFE_COMMAND_ATTRIBUTES = [ "insert", "ordered", "find", "limit", "singleBatch", "aggregate", "createIndexes", "indexes", "delete", "findAndModify", "renameCollection", "to", "drop", ] def _strip_pii(command): # type: (Dict[str, Any]) -> Dict[str, Any] for key in command: is_safe_field = key in SAFE_COMMAND_ATTRIBUTES if is_safe_field: # Skip if safe key continue update_db_command = key == "update" and "findAndModify" not in command if update_db_command: # Also skip "update" db command because it is save. # There is also an "update" key in the "findAndModify" command, which is NOT safe! continue # Special stripping for documents is_document = key == "documents" if is_document: for doc in command[key]: for doc_key in doc: doc[doc_key] = "%s" continue # Special stripping for dict style fields is_dict_field = key in ["filter", "query", "update"] if is_dict_field: for item_key in command[key]: command[key][item_key] = "%s" continue # For pipeline fields strip the `$match` dict is_pipeline_field = key == "pipeline" if is_pipeline_field: for pipeline in command[key]: for match_key in pipeline["$match"] if "$match" in pipeline else []: pipeline["$match"][match_key] = "%s" continue # Default stripping command[key] = "%s" return command class CommandTracer(monitoring.CommandListener): def __init__(self): # type: () -> None self._ongoing_operations = {} # type: Dict[int, Span] def _operation_key(self, event): # type: (Union[CommandFailedEvent, CommandStartedEvent, CommandSucceededEvent]) -> int return event.request_id def started(self, event): # type: (CommandStartedEvent) -> None hub = Hub.current if hub.get_integration(PyMongoIntegration) is None: return with capture_internal_exceptions(): command = dict(copy.deepcopy(event.command)) command.pop("$db", None) command.pop("$clusterTime", None) command.pop("$signature", None) op = "db.query" tags = { "db.name": event.database_name, "db.system": "mongodb", "db.operation": event.command_name, } try: tags["net.peer.name"] = event.connection_id[0] tags["net.peer.port"] = str(event.connection_id[1]) except TypeError: pass data = {"operation_ids": {}} # type: Dict[str, Dict[str, Any]] data["operation_ids"]["operation"] = event.operation_id data["operation_ids"]["request"] = event.request_id try: lsid = command.pop("lsid")["id"] data["operation_ids"]["session"] = str(lsid) except KeyError: pass if not _should_send_default_pii(): command = _strip_pii(command) query = "{} {}".format(event.command_name, command) span = hub.start_span(op=op, description=query) for tag, value in tags.items(): span.set_tag(tag, value) for key, value in data.items(): span.set_data(key, value) with capture_internal_exceptions(): hub.add_breadcrumb(message=query, category="query", type=op, data=tags) self._ongoing_operations[self._operation_key(event)] = span.__enter__() def failed(self, event): # type: (CommandFailedEvent) -> None hub = Hub.current if hub.get_integration(PyMongoIntegration) is None: return try: span = self._ongoing_operations.pop(self._operation_key(event)) span.set_status("internal_error") span.__exit__(None, None, None) except KeyError: return def succeeded(self, event): # type: (CommandSucceededEvent) -> None hub = Hub.current if hub.get_integration(PyMongoIntegration) is None: return try: span = self._ongoing_operations.pop(self._operation_key(event)) span.set_status("ok") span.__exit__(None, None, None) except KeyError: pass class PyMongoIntegration(Integration): identifier = "pymongo" @staticmethod def setup_once(): # type: () -> None monitoring.register(CommandTracer())
5,404
Python
28.375
94
0.563101
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/gcp.py
from datetime import datetime, timedelta from os import environ import sys from sentry_sdk.consts import OP from sentry_sdk.hub import Hub, _should_send_default_pii from sentry_sdk.tracing import TRANSACTION_SOURCE_COMPONENT, Transaction from sentry_sdk._compat import reraise from sentry_sdk.utils import ( AnnotatedValue, capture_internal_exceptions, event_from_exception, logger, TimeoutThread, ) from sentry_sdk.integrations import Integration from sentry_sdk.integrations._wsgi_common import _filter_headers from sentry_sdk._types import MYPY # Constants TIMEOUT_WARNING_BUFFER = 1.5 # Buffer time required to send timeout warning to Sentry MILLIS_TO_SECONDS = 1000.0 if MYPY: from typing import Any from typing import TypeVar from typing import Callable from typing import Optional from sentry_sdk._types import EventProcessor, Event, Hint F = TypeVar("F", bound=Callable[..., Any]) def _wrap_func(func): # type: (F) -> F def sentry_func(functionhandler, gcp_event, *args, **kwargs): # type: (Any, Any, *Any, **Any) -> Any hub = Hub.current integration = hub.get_integration(GcpIntegration) if integration is None: return func(functionhandler, gcp_event, *args, **kwargs) # If an integration is there, a client has to be there. client = hub.client # type: Any configured_time = environ.get("FUNCTION_TIMEOUT_SEC") if not configured_time: logger.debug( "The configured timeout could not be fetched from Cloud Functions configuration." ) return func(functionhandler, gcp_event, *args, **kwargs) configured_time = int(configured_time) initial_time = datetime.utcnow() with hub.push_scope() as scope: with capture_internal_exceptions(): scope.clear_breadcrumbs() scope.add_event_processor( _make_request_event_processor( gcp_event, configured_time, initial_time ) ) scope.set_tag("gcp_region", environ.get("FUNCTION_REGION")) timeout_thread = None if ( integration.timeout_warning and configured_time > TIMEOUT_WARNING_BUFFER ): waiting_time = configured_time - TIMEOUT_WARNING_BUFFER timeout_thread = TimeoutThread(waiting_time, configured_time) # Starting the thread to raise timeout warning exception timeout_thread.start() headers = {} if hasattr(gcp_event, "headers"): headers = gcp_event.headers transaction = Transaction.continue_from_headers( headers, op=OP.FUNCTION_GCP, name=environ.get("FUNCTION_NAME", ""), source=TRANSACTION_SOURCE_COMPONENT, ) sampling_context = { "gcp_env": { "function_name": environ.get("FUNCTION_NAME"), "function_entry_point": environ.get("ENTRY_POINT"), "function_identity": environ.get("FUNCTION_IDENTITY"), "function_region": environ.get("FUNCTION_REGION"), "function_project": environ.get("GCP_PROJECT"), }, "gcp_event": gcp_event, } with hub.start_transaction( transaction, custom_sampling_context=sampling_context ): try: return func(functionhandler, gcp_event, *args, **kwargs) except Exception: exc_info = sys.exc_info() sentry_event, hint = event_from_exception( exc_info, client_options=client.options, mechanism={"type": "gcp", "handled": False}, ) hub.capture_event(sentry_event, hint=hint) reraise(*exc_info) finally: if timeout_thread: timeout_thread.stop() # Flush out the event queue hub.flush() return sentry_func # type: ignore class GcpIntegration(Integration): identifier = "gcp" def __init__(self, timeout_warning=False): # type: (bool) -> None self.timeout_warning = timeout_warning @staticmethod def setup_once(): # type: () -> None import __main__ as gcp_functions if not hasattr(gcp_functions, "worker_v1"): logger.warning( "GcpIntegration currently supports only Python 3.7 runtime environment." ) return worker1 = gcp_functions.worker_v1 worker1.FunctionHandler.invoke_user_function = _wrap_func( worker1.FunctionHandler.invoke_user_function ) def _make_request_event_processor(gcp_event, configured_timeout, initial_time): # type: (Any, Any, Any) -> EventProcessor def event_processor(event, hint): # type: (Event, Hint) -> Optional[Event] final_time = datetime.utcnow() time_diff = final_time - initial_time execution_duration_in_millis = time_diff.microseconds / MILLIS_TO_SECONDS extra = event.setdefault("extra", {}) extra["google cloud functions"] = { "function_name": environ.get("FUNCTION_NAME"), "function_entry_point": environ.get("ENTRY_POINT"), "function_identity": environ.get("FUNCTION_IDENTITY"), "function_region": environ.get("FUNCTION_REGION"), "function_project": environ.get("GCP_PROJECT"), "execution_duration_in_millis": execution_duration_in_millis, "configured_timeout_in_seconds": configured_timeout, } extra["google cloud logs"] = { "url": _get_google_cloud_logs_url(final_time), } request = event.get("request", {}) request["url"] = "gcp:///{}".format(environ.get("FUNCTION_NAME")) if hasattr(gcp_event, "method"): request["method"] = gcp_event.method if hasattr(gcp_event, "query_string"): request["query_string"] = gcp_event.query_string.decode("utf-8") if hasattr(gcp_event, "headers"): request["headers"] = _filter_headers(gcp_event.headers) if _should_send_default_pii(): if hasattr(gcp_event, "data"): request["data"] = gcp_event.data else: if hasattr(gcp_event, "data"): # Unfortunately couldn't find a way to get structured body from GCP # event. Meaning every body is unstructured to us. request["data"] = AnnotatedValue.removed_because_raw_data() event["request"] = request return event return event_processor def _get_google_cloud_logs_url(final_time): # type: (datetime) -> str """ Generates a Google Cloud Logs console URL based on the environment variables Arguments: final_time {datetime} -- Final time Returns: str -- Google Cloud Logs Console URL to logs. """ hour_ago = final_time - timedelta(hours=1) formatstring = "%Y-%m-%dT%H:%M:%SZ" url = ( "https://console.cloud.google.com/logs/viewer?project={project}&resource=cloud_function" "%2Ffunction_name%2F{function_name}%2Fregion%2F{region}&minLogLevel=0&expandAll=false" "&timestamp={timestamp_end}&customFacets=&limitCustomFacetWidth=true" "&dateRangeStart={timestamp_start}&dateRangeEnd={timestamp_end}" "&interval=PT1H&scrollTimestamp={timestamp_end}" ).format( project=environ.get("GCP_PROJECT"), function_name=environ.get("FUNCTION_NAME"), region=environ.get("FUNCTION_REGION"), timestamp_end=final_time.strftime(formatstring), timestamp_start=hour_ago.strftime(formatstring), ) return url
8,148
Python
34.430435
97
0.58137
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/executing.py
from __future__ import absolute_import from sentry_sdk import Hub from sentry_sdk._types import MYPY from sentry_sdk.integrations import Integration, DidNotEnable from sentry_sdk.scope import add_global_event_processor from sentry_sdk.utils import walk_exception_chain, iter_stacks if MYPY: from typing import Optional from sentry_sdk._types import Event, Hint try: import executing except ImportError: raise DidNotEnable("executing is not installed") class ExecutingIntegration(Integration): identifier = "executing" @staticmethod def setup_once(): # type: () -> None @add_global_event_processor def add_executing_info(event, hint): # type: (Event, Optional[Hint]) -> Optional[Event] if Hub.current.get_integration(ExecutingIntegration) is None: return event if hint is None: return event exc_info = hint.get("exc_info", None) if exc_info is None: return event exception = event.get("exception", None) if exception is None: return event values = exception.get("values", None) if values is None: return event for exception, (_exc_type, _exc_value, exc_tb) in zip( reversed(values), walk_exception_chain(exc_info) ): sentry_frames = [ frame for frame in exception.get("stacktrace", {}).get("frames", []) if frame.get("function") ] tbs = list(iter_stacks(exc_tb)) if len(sentry_frames) != len(tbs): continue for sentry_frame, tb in zip(sentry_frames, tbs): frame = tb.tb_frame source = executing.Source.for_frame(frame) sentry_frame["function"] = source.code_qualname(frame.f_code) return event
2,023
Python
28.333333
82
0.562531
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/modules.py
from __future__ import absolute_import from sentry_sdk.hub import Hub from sentry_sdk.integrations import Integration from sentry_sdk.scope import add_global_event_processor from sentry_sdk._types import MYPY if MYPY: from typing import Any from typing import Dict from typing import Tuple from typing import Iterator from sentry_sdk._types import Event _installed_modules = None def _generate_installed_modules(): # type: () -> Iterator[Tuple[str, str]] try: import pkg_resources except ImportError: return for info in pkg_resources.working_set: yield info.key, info.version def _get_installed_modules(): # type: () -> Dict[str, str] global _installed_modules if _installed_modules is None: _installed_modules = dict(_generate_installed_modules()) return _installed_modules class ModulesIntegration(Integration): identifier = "modules" @staticmethod def setup_once(): # type: () -> None @add_global_event_processor def processor(event, hint): # type: (Event, Any) -> Dict[str, Any] if event.get("type") == "transaction": return event if Hub.current.get_integration(ModulesIntegration) is None: return event event["modules"] = _get_installed_modules() return event
1,393
Python
23.45614
71
0.642498
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/trytond.py
import sentry_sdk.hub import sentry_sdk.utils import sentry_sdk.integrations import sentry_sdk.integrations.wsgi from sentry_sdk._types import MYPY from trytond.exceptions import TrytonException # type: ignore from trytond.wsgi import app # type: ignore if MYPY: from typing import Any # TODO: trytond-worker, trytond-cron and trytond-admin intergations class TrytondWSGIIntegration(sentry_sdk.integrations.Integration): identifier = "trytond_wsgi" def __init__(self): # type: () -> None pass @staticmethod def setup_once(): # type: () -> None app.wsgi_app = sentry_sdk.integrations.wsgi.SentryWsgiMiddleware(app.wsgi_app) def error_handler(e): # type: (Exception) -> None hub = sentry_sdk.hub.Hub.current if hub.get_integration(TrytondWSGIIntegration) is None: return elif isinstance(e, TrytonException): return else: # If an integration is there, a client has to be there. client = hub.client # type: Any event, hint = sentry_sdk.utils.event_from_exception( e, client_options=client.options, mechanism={"type": "trytond", "handled": False}, ) hub.capture_event(event, hint=hint) # Expected error handlers signature was changed # when the error_handler decorator was introduced # in Tryton-5.4 if hasattr(app, "error_handler"): @app.error_handler def _(app, request, e): # type: ignore error_handler(e) else: app.error_handlers.append(error_handler)
1,728
Python
29.874999
86
0.600116
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/httpx.py
from sentry_sdk import Hub from sentry_sdk.consts import OP from sentry_sdk.integrations import Integration, DidNotEnable from sentry_sdk.utils import logger from sentry_sdk._types import MYPY if MYPY: from typing import Any try: from httpx import AsyncClient, Client, Request, Response # type: ignore except ImportError: raise DidNotEnable("httpx is not installed") __all__ = ["HttpxIntegration"] class HttpxIntegration(Integration): identifier = "httpx" @staticmethod def setup_once(): # type: () -> None """ httpx has its own transport layer and can be customized when needed, so patch Client.send and AsyncClient.send to support both synchronous and async interfaces. """ _install_httpx_client() _install_httpx_async_client() def _install_httpx_client(): # type: () -> None real_send = Client.send def send(self, request, **kwargs): # type: (Client, Request, **Any) -> Response hub = Hub.current if hub.get_integration(HttpxIntegration) is None: return real_send(self, request, **kwargs) with hub.start_span( op=OP.HTTP_CLIENT, description="%s %s" % (request.method, request.url) ) as span: span.set_data("method", request.method) span.set_data("url", str(request.url)) for key, value in hub.iter_trace_propagation_headers(): logger.debug( "[Tracing] Adding `{key}` header {value} to outgoing request to {url}.".format( key=key, value=value, url=request.url ) ) request.headers[key] = value rv = real_send(self, request, **kwargs) span.set_data("status_code", rv.status_code) span.set_http_status(rv.status_code) span.set_data("reason", rv.reason_phrase) return rv Client.send = send def _install_httpx_async_client(): # type: () -> None real_send = AsyncClient.send async def send(self, request, **kwargs): # type: (AsyncClient, Request, **Any) -> Response hub = Hub.current if hub.get_integration(HttpxIntegration) is None: return await real_send(self, request, **kwargs) with hub.start_span( op=OP.HTTP_CLIENT, description="%s %s" % (request.method, request.url) ) as span: span.set_data("method", request.method) span.set_data("url", str(request.url)) for key, value in hub.iter_trace_propagation_headers(): logger.debug( "[Tracing] Adding `{key}` header {value} to outgoing request to {url}.".format( key=key, value=value, url=request.url ) ) request.headers[key] = value rv = await real_send(self, request, **kwargs) span.set_data("status_code", rv.status_code) span.set_http_status(rv.status_code) span.set_data("reason", rv.reason_phrase) return rv AsyncClient.send = send
3,162
Python
31.947916
99
0.580645
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/redis.py
from __future__ import absolute_import from sentry_sdk import Hub from sentry_sdk.consts import OP from sentry_sdk.utils import capture_internal_exceptions, logger from sentry_sdk.integrations import Integration, DidNotEnable from sentry_sdk._types import MYPY if MYPY: from typing import Any, Sequence _SINGLE_KEY_COMMANDS = frozenset( ["decr", "decrby", "get", "incr", "incrby", "pttl", "set", "setex", "setnx", "ttl"] ) _MULTI_KEY_COMMANDS = frozenset(["del", "touch", "unlink"]) #: Trim argument lists to this many values _MAX_NUM_ARGS = 10 def patch_redis_pipeline(pipeline_cls, is_cluster, get_command_args_fn): # type: (Any, bool, Any) -> None old_execute = pipeline_cls.execute def sentry_patched_execute(self, *args, **kwargs): # type: (Any, *Any, **Any) -> Any hub = Hub.current if hub.get_integration(RedisIntegration) is None: return old_execute(self, *args, **kwargs) with hub.start_span( op=OP.DB_REDIS, description="redis.pipeline.execute" ) as span: with capture_internal_exceptions(): span.set_tag("redis.is_cluster", is_cluster) transaction = self.transaction if not is_cluster else False span.set_tag("redis.transaction", transaction) commands = [] for i, arg in enumerate(self.command_stack): if i > _MAX_NUM_ARGS: break command_args = [] for j, command_arg in enumerate(get_command_args_fn(arg)): if j > 0: command_arg = repr(command_arg) command_args.append(command_arg) commands.append(" ".join(command_args)) span.set_data( "redis.commands", {"count": len(self.command_stack), "first_ten": commands}, ) return old_execute(self, *args, **kwargs) pipeline_cls.execute = sentry_patched_execute def _get_redis_command_args(command): # type: (Any) -> Sequence[Any] return command[0] def _parse_rediscluster_command(command): # type: (Any) -> Sequence[Any] return command.args def _patch_rediscluster(): # type: () -> None try: import rediscluster # type: ignore except ImportError: return patch_redis_client(rediscluster.RedisCluster, is_cluster=True) # up to v1.3.6, __version__ attribute is a tuple # from v2.0.0, __version__ is a string and VERSION a tuple version = getattr(rediscluster, "VERSION", rediscluster.__version__) # StrictRedisCluster was introduced in v0.2.0 and removed in v2.0.0 # https://github.com/Grokzen/redis-py-cluster/blob/master/docs/release-notes.rst if (0, 2, 0) < version < (2, 0, 0): pipeline_cls = rediscluster.pipeline.StrictClusterPipeline patch_redis_client(rediscluster.StrictRedisCluster, is_cluster=True) else: pipeline_cls = rediscluster.pipeline.ClusterPipeline patch_redis_pipeline(pipeline_cls, True, _parse_rediscluster_command) class RedisIntegration(Integration): identifier = "redis" @staticmethod def setup_once(): # type: () -> None try: import redis except ImportError: raise DidNotEnable("Redis client not installed") patch_redis_client(redis.StrictRedis, is_cluster=False) patch_redis_pipeline(redis.client.Pipeline, False, _get_redis_command_args) try: strict_pipeline = redis.client.StrictPipeline # type: ignore except AttributeError: pass else: patch_redis_pipeline(strict_pipeline, False, _get_redis_command_args) try: import rb.clients # type: ignore except ImportError: pass else: patch_redis_client(rb.clients.FanoutClient, is_cluster=False) patch_redis_client(rb.clients.MappingClient, is_cluster=False) patch_redis_client(rb.clients.RoutingClient, is_cluster=False) try: _patch_rediscluster() except Exception: logger.exception("Error occurred while patching `rediscluster` library") def patch_redis_client(cls, is_cluster): # type: (Any, bool) -> None """ This function can be used to instrument custom redis client classes or subclasses. """ old_execute_command = cls.execute_command def sentry_patched_execute_command(self, name, *args, **kwargs): # type: (Any, str, *Any, **Any) -> Any hub = Hub.current if hub.get_integration(RedisIntegration) is None: return old_execute_command(self, name, *args, **kwargs) description = name with capture_internal_exceptions(): description_parts = [name] for i, arg in enumerate(args): if i > _MAX_NUM_ARGS: break description_parts.append(repr(arg)) description = " ".join(description_parts) with hub.start_span(op=OP.DB_REDIS, description=description) as span: span.set_tag("redis.is_cluster", is_cluster) if name: span.set_tag("redis.command", name) if name and args: name_low = name.lower() if (name_low in _SINGLE_KEY_COMMANDS) or ( name_low in _MULTI_KEY_COMMANDS and len(args) == 1 ): span.set_tag("redis.key", args[0]) return old_execute_command(self, name, *args, **kwargs) cls.execute_command = sentry_patched_execute_command
5,740
Python
32.184971
87
0.59547
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/__init__.py
"""This package""" from __future__ import absolute_import from threading import Lock from sentry_sdk._compat import iteritems from sentry_sdk.utils import logger from sentry_sdk._types import MYPY if MYPY: from typing import Callable from typing import Dict from typing import Iterator from typing import List from typing import Set from typing import Tuple from typing import Type _installer_lock = Lock() _installed_integrations = set() # type: Set[str] def _generate_default_integrations_iterator(integrations, auto_enabling_integrations): # type: (Tuple[str, ...], Tuple[str, ...]) -> Callable[[bool], Iterator[Type[Integration]]] def iter_default_integrations(with_auto_enabling_integrations): # type: (bool) -> Iterator[Type[Integration]] """Returns an iterator of the default integration classes:""" from importlib import import_module if with_auto_enabling_integrations: all_import_strings = integrations + auto_enabling_integrations else: all_import_strings = integrations for import_string in all_import_strings: try: module, cls = import_string.rsplit(".", 1) yield getattr(import_module(module), cls) except (DidNotEnable, SyntaxError) as e: logger.debug( "Did not import default integration %s: %s", import_string, e ) if isinstance(iter_default_integrations.__doc__, str): for import_string in integrations: iter_default_integrations.__doc__ += "\n- `{}`".format(import_string) return iter_default_integrations _AUTO_ENABLING_INTEGRATIONS = ( "sentry_sdk.integrations.django.DjangoIntegration", "sentry_sdk.integrations.flask.FlaskIntegration", "sentry_sdk.integrations.starlette.StarletteIntegration", "sentry_sdk.integrations.fastapi.FastApiIntegration", "sentry_sdk.integrations.bottle.BottleIntegration", "sentry_sdk.integrations.falcon.FalconIntegration", "sentry_sdk.integrations.sanic.SanicIntegration", "sentry_sdk.integrations.celery.CeleryIntegration", "sentry_sdk.integrations.rq.RqIntegration", "sentry_sdk.integrations.aiohttp.AioHttpIntegration", "sentry_sdk.integrations.tornado.TornadoIntegration", "sentry_sdk.integrations.sqlalchemy.SqlalchemyIntegration", "sentry_sdk.integrations.redis.RedisIntegration", "sentry_sdk.integrations.pyramid.PyramidIntegration", "sentry_sdk.integrations.boto3.Boto3Integration", ) iter_default_integrations = _generate_default_integrations_iterator( integrations=( # stdlib/base runtime integrations "sentry_sdk.integrations.logging.LoggingIntegration", "sentry_sdk.integrations.stdlib.StdlibIntegration", "sentry_sdk.integrations.excepthook.ExcepthookIntegration", "sentry_sdk.integrations.dedupe.DedupeIntegration", "sentry_sdk.integrations.atexit.AtexitIntegration", "sentry_sdk.integrations.modules.ModulesIntegration", "sentry_sdk.integrations.argv.ArgvIntegration", "sentry_sdk.integrations.threading.ThreadingIntegration", ), auto_enabling_integrations=_AUTO_ENABLING_INTEGRATIONS, ) del _generate_default_integrations_iterator def setup_integrations( integrations, with_defaults=True, with_auto_enabling_integrations=False ): # type: (List[Integration], bool, bool) -> Dict[str, Integration] """Given a list of integration instances this installs them all. When `with_defaults` is set to `True` then all default integrations are added unless they were already provided before. """ integrations = dict( (integration.identifier, integration) for integration in integrations or () ) logger.debug("Setting up integrations (with default = %s)", with_defaults) # Integrations that are not explicitly set up by the user. used_as_default_integration = set() if with_defaults: for integration_cls in iter_default_integrations( with_auto_enabling_integrations ): if integration_cls.identifier not in integrations: instance = integration_cls() integrations[instance.identifier] = instance used_as_default_integration.add(instance.identifier) for identifier, integration in iteritems(integrations): with _installer_lock: if identifier not in _installed_integrations: logger.debug( "Setting up previously not enabled integration %s", identifier ) try: type(integration).setup_once() except NotImplementedError: if getattr(integration, "install", None) is not None: logger.warning( "Integration %s: The install method is " "deprecated. Use `setup_once`.", identifier, ) integration.install() else: raise except DidNotEnable as e: if identifier not in used_as_default_integration: raise logger.debug( "Did not enable default integration %s: %s", identifier, e ) _installed_integrations.add(identifier) for identifier in integrations: logger.debug("Enabling integration %s", identifier) return integrations class DidNotEnable(Exception): # noqa: N818 """ The integration could not be enabled due to a trivial user error like `flask` not being installed for the `FlaskIntegration`. This exception is silently swallowed for default integrations, but reraised for explicitly enabled integrations. """ class Integration(object): """Baseclass for all integrations. To accept options for an integration, implement your own constructor that saves those options on `self`. """ install = None """Legacy method, do not implement.""" identifier = None # type: str """String unique ID of integration type""" @staticmethod def setup_once(): # type: () -> None """ Initialize the integration. This function is only called once, ever. Configuration is not available at this point, so the only thing to do here is to hook into exception handlers, and perhaps do monkeypatches. Inside those hooks `Integration.current` can be used to access the instance again. """ raise NotImplementedError()
6,755
Python
34.93617
95
0.650777
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/celery.py
from __future__ import absolute_import import sys from sentry_sdk.consts import OP from sentry_sdk.hub import Hub from sentry_sdk.tracing import TRANSACTION_SOURCE_TASK from sentry_sdk.utils import ( capture_internal_exceptions, event_from_exception, ) from sentry_sdk.tracing import Transaction from sentry_sdk._compat import reraise from sentry_sdk.integrations import Integration, DidNotEnable from sentry_sdk.integrations.logging import ignore_logger from sentry_sdk._types import MYPY from sentry_sdk._functools import wraps if MYPY: from typing import Any from typing import TypeVar from typing import Callable from typing import Optional from sentry_sdk._types import EventProcessor, Event, Hint, ExcInfo F = TypeVar("F", bound=Callable[..., Any]) try: from celery import VERSION as CELERY_VERSION from celery.exceptions import ( # type: ignore SoftTimeLimitExceeded, Retry, Ignore, Reject, ) from celery.app.trace import task_has_custom except ImportError: raise DidNotEnable("Celery not installed") CELERY_CONTROL_FLOW_EXCEPTIONS = (Retry, Ignore, Reject) class CeleryIntegration(Integration): identifier = "celery" def __init__(self, propagate_traces=True): # type: (bool) -> None self.propagate_traces = propagate_traces @staticmethod def setup_once(): # type: () -> None if CELERY_VERSION < (3,): raise DidNotEnable("Celery 3 or newer required.") import celery.app.trace as trace # type: ignore old_build_tracer = trace.build_tracer def sentry_build_tracer(name, task, *args, **kwargs): # type: (Any, Any, *Any, **Any) -> Any if not getattr(task, "_sentry_is_patched", False): # determine whether Celery will use __call__ or run and patch # accordingly if task_has_custom(task, "__call__"): type(task).__call__ = _wrap_task_call(task, type(task).__call__) else: task.run = _wrap_task_call(task, task.run) # `build_tracer` is apparently called for every task # invocation. Can't wrap every celery task for every invocation # or we will get infinitely nested wrapper functions. task._sentry_is_patched = True return _wrap_tracer(task, old_build_tracer(name, task, *args, **kwargs)) trace.build_tracer = sentry_build_tracer from celery.app.task import Task # type: ignore Task.apply_async = _wrap_apply_async(Task.apply_async) _patch_worker_exit() # This logger logs every status of every task that ran on the worker. # Meaning that every task's breadcrumbs are full of stuff like "Task # <foo> raised unexpected <bar>". ignore_logger("celery.worker.job") ignore_logger("celery.app.trace") # This is stdout/err redirected to a logger, can't deal with this # (need event_level=logging.WARN to reproduce) ignore_logger("celery.redirected") def _wrap_apply_async(f): # type: (F) -> F @wraps(f) def apply_async(*args, **kwargs): # type: (*Any, **Any) -> Any hub = Hub.current integration = hub.get_integration(CeleryIntegration) if integration is not None and integration.propagate_traces: with hub.start_span( op=OP.QUEUE_SUBMIT_CELERY, description=args[0].name ) as span: with capture_internal_exceptions(): headers = dict(hub.iter_trace_propagation_headers(span)) if headers: # Note: kwargs can contain headers=None, so no setdefault! # Unsure which backend though. kwarg_headers = kwargs.get("headers") or {} kwarg_headers.update(headers) # https://github.com/celery/celery/issues/4875 # # Need to setdefault the inner headers too since other # tracing tools (dd-trace-py) also employ this exact # workaround and we don't want to break them. kwarg_headers.setdefault("headers", {}).update(headers) kwargs["headers"] = kwarg_headers return f(*args, **kwargs) else: return f(*args, **kwargs) return apply_async # type: ignore def _wrap_tracer(task, f): # type: (Any, F) -> F # Need to wrap tracer for pushing the scope before prerun is sent, and # popping it after postrun is sent. # # This is the reason we don't use signals for hooking in the first place. # Also because in Celery 3, signal dispatch returns early if one handler # crashes. @wraps(f) def _inner(*args, **kwargs): # type: (*Any, **Any) -> Any hub = Hub.current if hub.get_integration(CeleryIntegration) is None: return f(*args, **kwargs) with hub.push_scope() as scope: scope._name = "celery" scope.clear_breadcrumbs() scope.add_event_processor(_make_event_processor(task, *args, **kwargs)) transaction = None # Celery task objects are not a thing to be trusted. Even # something such as attribute access can fail. with capture_internal_exceptions(): transaction = Transaction.continue_from_headers( args[3].get("headers") or {}, op=OP.QUEUE_TASK_CELERY, name="unknown celery task", source=TRANSACTION_SOURCE_TASK, ) transaction.name = task.name transaction.set_status("ok") if transaction is None: return f(*args, **kwargs) with hub.start_transaction( transaction, custom_sampling_context={ "celery_job": { "task": task.name, # for some reason, args[1] is a list if non-empty but a # tuple if empty "args": list(args[1]), "kwargs": args[2], } }, ): return f(*args, **kwargs) return _inner # type: ignore def _wrap_task_call(task, f): # type: (Any, F) -> F # Need to wrap task call because the exception is caught before we get to # see it. Also celery's reported stacktrace is untrustworthy. # functools.wraps is important here because celery-once looks at this # method's name. # https://github.com/getsentry/sentry-python/issues/421 @wraps(f) def _inner(*args, **kwargs): # type: (*Any, **Any) -> Any try: return f(*args, **kwargs) except Exception: exc_info = sys.exc_info() with capture_internal_exceptions(): _capture_exception(task, exc_info) reraise(*exc_info) return _inner # type: ignore def _make_event_processor(task, uuid, args, kwargs, request=None): # type: (Any, Any, Any, Any, Optional[Any]) -> EventProcessor def event_processor(event, hint): # type: (Event, Hint) -> Optional[Event] with capture_internal_exceptions(): tags = event.setdefault("tags", {}) tags["celery_task_id"] = uuid extra = event.setdefault("extra", {}) extra["celery-job"] = { "task_name": task.name, "args": args, "kwargs": kwargs, } if "exc_info" in hint: with capture_internal_exceptions(): if issubclass(hint["exc_info"][0], SoftTimeLimitExceeded): event["fingerprint"] = [ "celery", "SoftTimeLimitExceeded", getattr(task, "name", task), ] return event return event_processor def _capture_exception(task, exc_info): # type: (Any, ExcInfo) -> None hub = Hub.current if hub.get_integration(CeleryIntegration) is None: return if isinstance(exc_info[1], CELERY_CONTROL_FLOW_EXCEPTIONS): # ??? Doesn't map to anything _set_status(hub, "aborted") return _set_status(hub, "internal_error") if hasattr(task, "throws") and isinstance(exc_info[1], task.throws): return # If an integration is there, a client has to be there. client = hub.client # type: Any event, hint = event_from_exception( exc_info, client_options=client.options, mechanism={"type": "celery", "handled": False}, ) hub.capture_event(event, hint=hint) def _set_status(hub, status): # type: (Hub, str) -> None with capture_internal_exceptions(): with hub.configure_scope() as scope: if scope.span is not None: scope.span.set_status(status) def _patch_worker_exit(): # type: () -> None # Need to flush queue before worker shutdown because a crashing worker will # call os._exit from billiard.pool import Worker # type: ignore old_workloop = Worker.workloop def sentry_workloop(*args, **kwargs): # type: (*Any, **Any) -> Any try: return old_workloop(*args, **kwargs) finally: with capture_internal_exceptions(): hub = Hub.current if hub.get_integration(CeleryIntegration) is not None: hub.flush() Worker.workloop = sentry_workloop
9,823
Python
32.077441
84
0.568462
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/dedupe.py
from sentry_sdk.hub import Hub from sentry_sdk.utils import ContextVar from sentry_sdk.integrations import Integration from sentry_sdk.scope import add_global_event_processor from sentry_sdk._types import MYPY if MYPY: from typing import Optional from sentry_sdk._types import Event, Hint class DedupeIntegration(Integration): identifier = "dedupe" def __init__(self): # type: () -> None self._last_seen = ContextVar("last-seen") @staticmethod def setup_once(): # type: () -> None @add_global_event_processor def processor(event, hint): # type: (Event, Optional[Hint]) -> Optional[Event] if hint is None: return event integration = Hub.current.get_integration(DedupeIntegration) if integration is None: return event exc_info = hint.get("exc_info", None) if exc_info is None: return event exc = exc_info[1] if integration._last_seen.get(None) is exc: return None integration._last_seen.set(exc) return event
1,166
Python
25.522727
72
0.59434
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/flask.py
from __future__ import absolute_import from sentry_sdk._types import MYPY from sentry_sdk.hub import Hub, _should_send_default_pii from sentry_sdk.integrations import DidNotEnable, Integration from sentry_sdk.integrations._wsgi_common import RequestExtractor from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware from sentry_sdk.scope import Scope from sentry_sdk.tracing import SENTRY_TRACE_HEADER_NAME, SOURCE_FOR_STYLE from sentry_sdk.utils import ( capture_internal_exceptions, event_from_exception, ) if MYPY: from typing import Any, Callable, Dict, Union from sentry_sdk._types import EventProcessor from sentry_sdk.integrations.wsgi import _ScopedResponse from werkzeug.datastructures import FileStorage, ImmutableMultiDict try: import flask_login # type: ignore except ImportError: flask_login = None try: from flask import Flask, Markup, Request # type: ignore from flask import __version__ as FLASK_VERSION from flask import request as flask_request from flask.signals import ( before_render_template, got_request_exception, request_started, ) except ImportError: raise DidNotEnable("Flask is not installed") try: import blinker # noqa except ImportError: raise DidNotEnable("blinker is not installed") TRANSACTION_STYLE_VALUES = ("endpoint", "url") class FlaskIntegration(Integration): identifier = "flask" transaction_style = "" def __init__(self, transaction_style="endpoint"): # type: (str) -> None if transaction_style not in TRANSACTION_STYLE_VALUES: raise ValueError( "Invalid value for transaction_style: %s (must be in %s)" % (transaction_style, TRANSACTION_STYLE_VALUES) ) self.transaction_style = transaction_style @staticmethod def setup_once(): # type: () -> None # This version parsing is absolutely naive but the alternative is to # import pkg_resources which slows down the SDK a lot. try: version = tuple(map(int, FLASK_VERSION.split(".")[:3])) except (ValueError, TypeError): # It's probably a release candidate, we assume it's fine. pass else: if version < (0, 10): raise DidNotEnable("Flask 0.10 or newer is required.") before_render_template.connect(_add_sentry_trace) request_started.connect(_request_started) got_request_exception.connect(_capture_exception) old_app = Flask.__call__ def sentry_patched_wsgi_app(self, environ, start_response): # type: (Any, Dict[str, str], Callable[..., Any]) -> _ScopedResponse if Hub.current.get_integration(FlaskIntegration) is None: return old_app(self, environ, start_response) return SentryWsgiMiddleware(lambda *a, **kw: old_app(self, *a, **kw))( environ, start_response ) Flask.__call__ = sentry_patched_wsgi_app def _add_sentry_trace(sender, template, context, **extra): # type: (Flask, Any, Dict[str, Any], **Any) -> None if "sentry_trace" in context: return sentry_span = Hub.current.scope.span context["sentry_trace"] = ( Markup( '<meta name="%s" content="%s" />' % ( SENTRY_TRACE_HEADER_NAME, sentry_span.to_traceparent(), ) ) if sentry_span else "" ) def _set_transaction_name_and_source(scope, transaction_style, request): # type: (Scope, str, Request) -> None try: name_for_style = { "url": request.url_rule.rule, "endpoint": request.url_rule.endpoint, } scope.set_transaction_name( name_for_style[transaction_style], source=SOURCE_FOR_STYLE[transaction_style], ) except Exception: pass def _request_started(app, **kwargs): # type: (Flask, **Any) -> None hub = Hub.current integration = hub.get_integration(FlaskIntegration) if integration is None: return with hub.configure_scope() as scope: # Set the transaction name and source here, # but rely on WSGI middleware to actually start the transaction request = flask_request._get_current_object() _set_transaction_name_and_source(scope, integration.transaction_style, request) evt_processor = _make_request_event_processor(app, request, integration) scope.add_event_processor(evt_processor) class FlaskRequestExtractor(RequestExtractor): def env(self): # type: () -> Dict[str, str] return self.request.environ def cookies(self): # type: () -> Dict[Any, Any] return { k: v[0] if isinstance(v, list) and len(v) == 1 else v for k, v in self.request.cookies.items() } def raw_data(self): # type: () -> bytes return self.request.get_data() def form(self): # type: () -> ImmutableMultiDict[str, Any] return self.request.form def files(self): # type: () -> ImmutableMultiDict[str, Any] return self.request.files def is_json(self): # type: () -> bool return self.request.is_json def json(self): # type: () -> Any return self.request.get_json() def size_of_file(self, file): # type: (FileStorage) -> int return file.content_length def _make_request_event_processor(app, request, integration): # type: (Flask, Callable[[], Request], FlaskIntegration) -> EventProcessor def inner(event, hint): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] # if the request is gone we are fine not logging the data from # it. This might happen if the processor is pushed away to # another thread. if request is None: return event with capture_internal_exceptions(): FlaskRequestExtractor(request).extract_into_event(event) if _should_send_default_pii(): with capture_internal_exceptions(): _add_user_to_event(event) return event return inner def _capture_exception(sender, exception, **kwargs): # type: (Flask, Union[ValueError, BaseException], **Any) -> None hub = Hub.current if hub.get_integration(FlaskIntegration) is None: return # If an integration is there, a client has to be there. client = hub.client # type: Any event, hint = event_from_exception( exception, client_options=client.options, mechanism={"type": "flask", "handled": False}, ) hub.capture_event(event, hint=hint) def _add_user_to_event(event): # type: (Dict[str, Any]) -> None if flask_login is None: return user = flask_login.current_user if user is None: return with capture_internal_exceptions(): # Access this object as late as possible as accessing the user # is relatively costly user_info = event.setdefault("user", {}) try: user_info.setdefault("id", user.get_id()) # TODO: more configurable user attrs here except AttributeError: # might happen if: # - flask_login could not be imported # - flask_login is not configured # - no user is logged in pass # The following attribute accesses are ineffective for the general # Flask-Login case, because the User interface of Flask-Login does not # care about anything but the ID. However, Flask-User (based on # Flask-Login) documents a few optional extra attributes. # # https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/docs/source/data_models.rst#fixed-data-model-property-names try: user_info.setdefault("email", user.email) except Exception: pass try: user_info.setdefault("username", user.username) user_info.setdefault("username", user.email) except Exception: pass
8,239
Python
29.861423
154
0.618886
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/pure_eval.py
from __future__ import absolute_import import ast from sentry_sdk import Hub, serializer from sentry_sdk._types import MYPY from sentry_sdk.integrations import Integration, DidNotEnable from sentry_sdk.scope import add_global_event_processor from sentry_sdk.utils import walk_exception_chain, iter_stacks if MYPY: from typing import Optional, Dict, Any, Tuple, List from types import FrameType from sentry_sdk._types import Event, Hint try: import executing except ImportError: raise DidNotEnable("executing is not installed") try: import pure_eval except ImportError: raise DidNotEnable("pure_eval is not installed") try: # Used implicitly, just testing it's available import asttokens # noqa except ImportError: raise DidNotEnable("asttokens is not installed") class PureEvalIntegration(Integration): identifier = "pure_eval" @staticmethod def setup_once(): # type: () -> None @add_global_event_processor def add_executing_info(event, hint): # type: (Event, Optional[Hint]) -> Optional[Event] if Hub.current.get_integration(PureEvalIntegration) is None: return event if hint is None: return event exc_info = hint.get("exc_info", None) if exc_info is None: return event exception = event.get("exception", None) if exception is None: return event values = exception.get("values", None) if values is None: return event for exception, (_exc_type, _exc_value, exc_tb) in zip( reversed(values), walk_exception_chain(exc_info) ): sentry_frames = [ frame for frame in exception.get("stacktrace", {}).get("frames", []) if frame.get("function") ] tbs = list(iter_stacks(exc_tb)) if len(sentry_frames) != len(tbs): continue for sentry_frame, tb in zip(sentry_frames, tbs): sentry_frame["vars"] = ( pure_eval_frame(tb.tb_frame) or sentry_frame["vars"] ) return event def pure_eval_frame(frame): # type: (FrameType) -> Dict[str, Any] source = executing.Source.for_frame(frame) if not source.tree: return {} statements = source.statements_at_line(frame.f_lineno) if not statements: return {} scope = stmt = list(statements)[0] while True: # Get the parent first in case the original statement is already # a function definition, e.g. if we're calling a decorator # In that case we still want the surrounding scope, not that function scope = scope.parent if isinstance(scope, (ast.FunctionDef, ast.ClassDef, ast.Module)): break evaluator = pure_eval.Evaluator.from_frame(frame) expressions = evaluator.interesting_expressions_grouped(scope) def closeness(expression): # type: (Tuple[List[Any], Any]) -> Tuple[int, int] # Prioritise expressions with a node closer to the statement executed # without being after that statement # A higher return value is better - the expression will appear # earlier in the list of values and is less likely to be trimmed nodes, _value = expression def start(n): # type: (ast.expr) -> Tuple[int, int] return (n.lineno, n.col_offset) nodes_before_stmt = [ node for node in nodes if start(node) < stmt.last_token.end # type: ignore ] if nodes_before_stmt: # The position of the last node before or in the statement return max(start(node) for node in nodes_before_stmt) else: # The position of the first node after the statement # Negative means it's always lower priority than nodes that come before # Less negative means closer to the statement and higher priority lineno, col_offset = min(start(node) for node in nodes) return (-lineno, -col_offset) # This adds the first_token and last_token attributes to nodes atok = source.asttokens() expressions.sort(key=closeness, reverse=True) return { atok.get_text(nodes[0]): value for nodes, value in expressions[: serializer.MAX_DATABAG_BREADTH] }
4,536
Python
31.640288
87
0.606702
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/quart.py
from __future__ import absolute_import from sentry_sdk.hub import _should_send_default_pii, Hub from sentry_sdk.integrations import DidNotEnable, Integration from sentry_sdk.integrations._wsgi_common import _filter_headers from sentry_sdk.integrations.asgi import SentryAsgiMiddleware from sentry_sdk.scope import Scope from sentry_sdk.tracing import SOURCE_FOR_STYLE from sentry_sdk.utils import ( capture_internal_exceptions, event_from_exception, ) from sentry_sdk._types import MYPY if MYPY: from typing import Any from typing import Dict from typing import Union from sentry_sdk._types import EventProcessor try: import quart_auth # type: ignore except ImportError: quart_auth = None try: from quart import ( # type: ignore has_request_context, has_websocket_context, Request, Quart, request, websocket, ) from quart.signals import ( # type: ignore got_background_exception, got_request_exception, got_websocket_exception, request_started, websocket_started, ) except ImportError: raise DidNotEnable("Quart is not installed") TRANSACTION_STYLE_VALUES = ("endpoint", "url") class QuartIntegration(Integration): identifier = "quart" transaction_style = "" def __init__(self, transaction_style="endpoint"): # type: (str) -> None if transaction_style not in TRANSACTION_STYLE_VALUES: raise ValueError( "Invalid value for transaction_style: %s (must be in %s)" % (transaction_style, TRANSACTION_STYLE_VALUES) ) self.transaction_style = transaction_style @staticmethod def setup_once(): # type: () -> None request_started.connect(_request_websocket_started) websocket_started.connect(_request_websocket_started) got_background_exception.connect(_capture_exception) got_request_exception.connect(_capture_exception) got_websocket_exception.connect(_capture_exception) old_app = Quart.__call__ async def sentry_patched_asgi_app(self, scope, receive, send): # type: (Any, Any, Any, Any) -> Any if Hub.current.get_integration(QuartIntegration) is None: return await old_app(self, scope, receive, send) middleware = SentryAsgiMiddleware(lambda *a, **kw: old_app(self, *a, **kw)) middleware.__call__ = middleware._run_asgi3 return await middleware(scope, receive, send) Quart.__call__ = sentry_patched_asgi_app def _set_transaction_name_and_source(scope, transaction_style, request): # type: (Scope, str, Request) -> None try: name_for_style = { "url": request.url_rule.rule, "endpoint": request.url_rule.endpoint, } scope.set_transaction_name( name_for_style[transaction_style], source=SOURCE_FOR_STYLE[transaction_style], ) except Exception: pass def _request_websocket_started(app, **kwargs): # type: (Quart, **Any) -> None hub = Hub.current integration = hub.get_integration(QuartIntegration) if integration is None: return with hub.configure_scope() as scope: if has_request_context(): request_websocket = request._get_current_object() if has_websocket_context(): request_websocket = websocket._get_current_object() # Set the transaction name here, but rely on ASGI middleware # to actually start the transaction _set_transaction_name_and_source( scope, integration.transaction_style, request_websocket ) evt_processor = _make_request_event_processor( app, request_websocket, integration ) scope.add_event_processor(evt_processor) def _make_request_event_processor(app, request, integration): # type: (Quart, Request, QuartIntegration) -> EventProcessor def inner(event, hint): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] # if the request is gone we are fine not logging the data from # it. This might happen if the processor is pushed away to # another thread. if request is None: return event with capture_internal_exceptions(): # TODO: Figure out what to do with request body. Methods on request # are async, but event processors are not. request_info = event.setdefault("request", {}) request_info["url"] = request.url request_info["query_string"] = request.query_string request_info["method"] = request.method request_info["headers"] = _filter_headers(dict(request.headers)) if _should_send_default_pii(): request_info["env"] = {"REMOTE_ADDR": request.access_route[0]} _add_user_to_event(event) return event return inner def _capture_exception(sender, exception, **kwargs): # type: (Quart, Union[ValueError, BaseException], **Any) -> None hub = Hub.current if hub.get_integration(QuartIntegration) is None: return # If an integration is there, a client has to be there. client = hub.client # type: Any event, hint = event_from_exception( exception, client_options=client.options, mechanism={"type": "quart", "handled": False}, ) hub.capture_event(event, hint=hint) def _add_user_to_event(event): # type: (Dict[str, Any]) -> None if quart_auth is None: return user = quart_auth.current_user if user is None: return with capture_internal_exceptions(): user_info = event.setdefault("user", {}) user_info["id"] = quart_auth.current_user._auth_id
5,867
Python
30.047619
87
0.631328
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/threading.py
from __future__ import absolute_import import sys from threading import Thread, current_thread from sentry_sdk import Hub from sentry_sdk._compat import reraise from sentry_sdk._types import MYPY from sentry_sdk.integrations import Integration from sentry_sdk.utils import event_from_exception, capture_internal_exceptions if MYPY: from typing import Any from typing import TypeVar from typing import Callable from typing import Optional from sentry_sdk._types import ExcInfo F = TypeVar("F", bound=Callable[..., Any]) class ThreadingIntegration(Integration): identifier = "threading" def __init__(self, propagate_hub=False): # type: (bool) -> None self.propagate_hub = propagate_hub @staticmethod def setup_once(): # type: () -> None old_start = Thread.start def sentry_start(self, *a, **kw): # type: (Thread, *Any, **Any) -> Any hub = Hub.current integration = hub.get_integration(ThreadingIntegration) if integration is not None: if not integration.propagate_hub: hub_ = None else: hub_ = Hub(hub) # Patching instance methods in `start()` creates a reference cycle if # done in a naive way. See # https://github.com/getsentry/sentry-python/pull/434 # # In threading module, using current_thread API will access current thread instance # without holding it to avoid a reference cycle in an easier way. with capture_internal_exceptions(): new_run = _wrap_run(hub_, getattr(self.run, "__func__", self.run)) self.run = new_run # type: ignore return old_start(self, *a, **kw) Thread.start = sentry_start # type: ignore def _wrap_run(parent_hub, old_run_func): # type: (Optional[Hub], F) -> F def run(*a, **kw): # type: (*Any, **Any) -> Any hub = parent_hub or Hub.current with hub: try: self = current_thread() return old_run_func(self, *a, **kw) except Exception: reraise(*_capture_exception()) return run # type: ignore def _capture_exception(): # type: () -> ExcInfo hub = Hub.current exc_info = sys.exc_info() if hub.get_integration(ThreadingIntegration) is not None: # If an integration is there, a client has to be there. client = hub.client # type: Any event, hint = event_from_exception( exc_info, client_options=client.options, mechanism={"type": "threading", "handled": False}, ) hub.capture_event(event, hint=hint) return exc_info
2,840
Python
30.21978
99
0.580986
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/boto3.py
from __future__ import absolute_import from sentry_sdk import Hub from sentry_sdk.consts import OP from sentry_sdk.integrations import Integration, DidNotEnable from sentry_sdk.tracing import Span from sentry_sdk._functools import partial from sentry_sdk._types import MYPY if MYPY: from typing import Any from typing import Dict from typing import Optional from typing import Type try: from botocore import __version__ as BOTOCORE_VERSION # type: ignore from botocore.client import BaseClient # type: ignore from botocore.response import StreamingBody # type: ignore from botocore.awsrequest import AWSRequest # type: ignore except ImportError: raise DidNotEnable("botocore is not installed") class Boto3Integration(Integration): identifier = "boto3" @staticmethod def setup_once(): # type: () -> None try: version = tuple(map(int, BOTOCORE_VERSION.split(".")[:3])) except (ValueError, TypeError): raise DidNotEnable( "Unparsable botocore version: {}".format(BOTOCORE_VERSION) ) if version < (1, 12): raise DidNotEnable("Botocore 1.12 or newer is required.") orig_init = BaseClient.__init__ def sentry_patched_init(self, *args, **kwargs): # type: (Type[BaseClient], *Any, **Any) -> None orig_init(self, *args, **kwargs) meta = self.meta service_id = meta.service_model.service_id.hyphenize() meta.events.register( "request-created", partial(_sentry_request_created, service_id=service_id), ) meta.events.register("after-call", _sentry_after_call) meta.events.register("after-call-error", _sentry_after_call_error) BaseClient.__init__ = sentry_patched_init def _sentry_request_created(service_id, request, operation_name, **kwargs): # type: (str, AWSRequest, str, **Any) -> None hub = Hub.current if hub.get_integration(Boto3Integration) is None: return description = "aws.%s.%s" % (service_id, operation_name) span = hub.start_span( hub=hub, op=OP.HTTP_CLIENT, description=description, ) span.set_tag("aws.service_id", service_id) span.set_tag("aws.operation_name", operation_name) span.set_data("aws.request.url", request.url) # We do it in order for subsequent http calls/retries be # attached to this span. span.__enter__() # request.context is an open-ended data-structure # where we can add anything useful in request life cycle. request.context["_sentrysdk_span"] = span def _sentry_after_call(context, parsed, **kwargs): # type: (Dict[str, Any], Dict[str, Any], **Any) -> None span = context.pop("_sentrysdk_span", None) # type: Optional[Span] # Span could be absent if the integration is disabled. if span is None: return span.__exit__(None, None, None) body = parsed.get("Body") if not isinstance(body, StreamingBody): return streaming_span = span.start_child( op=OP.HTTP_CLIENT_STREAM, description=span.description, ) orig_read = body.read orig_close = body.close def sentry_streaming_body_read(*args, **kwargs): # type: (*Any, **Any) -> bytes try: ret = orig_read(*args, **kwargs) if not ret: streaming_span.finish() return ret except Exception: streaming_span.finish() raise body.read = sentry_streaming_body_read def sentry_streaming_body_close(*args, **kwargs): # type: (*Any, **Any) -> None streaming_span.finish() orig_close(*args, **kwargs) body.close = sentry_streaming_body_close def _sentry_after_call_error(context, exception, **kwargs): # type: (Dict[str, Any], Type[BaseException], **Any) -> None span = context.pop("_sentrysdk_span", None) # type: Optional[Span] # Span could be absent if the integration is disabled. if span is None: return span.__exit__(type(exception), exception, None)
4,180
Python
30.674242
78
0.625359
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/aws_lambda.py
from datetime import datetime, timedelta from os import environ import sys from sentry_sdk.consts import OP from sentry_sdk.hub import Hub, _should_send_default_pii from sentry_sdk.tracing import TRANSACTION_SOURCE_COMPONENT, Transaction from sentry_sdk._compat import reraise from sentry_sdk.utils import ( AnnotatedValue, capture_internal_exceptions, event_from_exception, logger, TimeoutThread, ) from sentry_sdk.integrations import Integration from sentry_sdk.integrations._wsgi_common import _filter_headers from sentry_sdk._types import MYPY if MYPY: from typing import Any from typing import TypeVar from typing import Callable from typing import Optional from sentry_sdk._types import EventProcessor, Event, Hint F = TypeVar("F", bound=Callable[..., Any]) # Constants TIMEOUT_WARNING_BUFFER = 1500 # Buffer time required to send timeout warning to Sentry MILLIS_TO_SECONDS = 1000.0 def _wrap_init_error(init_error): # type: (F) -> F def sentry_init_error(*args, **kwargs): # type: (*Any, **Any) -> Any hub = Hub.current integration = hub.get_integration(AwsLambdaIntegration) if integration is None: return init_error(*args, **kwargs) # If an integration is there, a client has to be there. client = hub.client # type: Any with capture_internal_exceptions(): with hub.configure_scope() as scope: scope.clear_breadcrumbs() exc_info = sys.exc_info() if exc_info and all(exc_info): sentry_event, hint = event_from_exception( exc_info, client_options=client.options, mechanism={"type": "aws_lambda", "handled": False}, ) hub.capture_event(sentry_event, hint=hint) return init_error(*args, **kwargs) return sentry_init_error # type: ignore def _wrap_handler(handler): # type: (F) -> F def sentry_handler(aws_event, aws_context, *args, **kwargs): # type: (Any, Any, *Any, **Any) -> Any # Per https://docs.aws.amazon.com/lambda/latest/dg/python-handler.html, # `event` here is *likely* a dictionary, but also might be a number of # other types (str, int, float, None). # # In some cases, it is a list (if the user is batch-invoking their # function, for example), in which case we'll use the first entry as a # representative from which to try pulling request data. (Presumably it # will be the same for all events in the list, since they're all hitting # the lambda in the same request.) if isinstance(aws_event, list): request_data = aws_event[0] batch_size = len(aws_event) else: request_data = aws_event batch_size = 1 if not isinstance(request_data, dict): # If we're not dealing with a dictionary, we won't be able to get # headers, path, http method, etc in any case, so it's fine that # this is empty request_data = {} hub = Hub.current integration = hub.get_integration(AwsLambdaIntegration) if integration is None: return handler(aws_event, aws_context, *args, **kwargs) # If an integration is there, a client has to be there. client = hub.client # type: Any configured_time = aws_context.get_remaining_time_in_millis() with hub.push_scope() as scope: timeout_thread = None with capture_internal_exceptions(): scope.clear_breadcrumbs() scope.add_event_processor( _make_request_event_processor( request_data, aws_context, configured_time ) ) scope.set_tag( "aws_region", aws_context.invoked_function_arn.split(":")[3] ) if batch_size > 1: scope.set_tag("batch_request", True) scope.set_tag("batch_size", batch_size) # Starting the Timeout thread only if the configured time is greater than Timeout warning # buffer and timeout_warning parameter is set True. if ( integration.timeout_warning and configured_time > TIMEOUT_WARNING_BUFFER ): waiting_time = ( configured_time - TIMEOUT_WARNING_BUFFER ) / MILLIS_TO_SECONDS timeout_thread = TimeoutThread( waiting_time, configured_time / MILLIS_TO_SECONDS, ) # Starting the thread to raise timeout warning exception timeout_thread.start() headers = request_data.get("headers") # AWS Service may set an explicit `{headers: None}`, we can't rely on `.get()`'s default. if headers is None: headers = {} transaction = Transaction.continue_from_headers( headers, op=OP.FUNCTION_AWS, name=aws_context.function_name, source=TRANSACTION_SOURCE_COMPONENT, ) with hub.start_transaction( transaction, custom_sampling_context={ "aws_event": aws_event, "aws_context": aws_context, }, ): try: return handler(aws_event, aws_context, *args, **kwargs) except Exception: exc_info = sys.exc_info() sentry_event, hint = event_from_exception( exc_info, client_options=client.options, mechanism={"type": "aws_lambda", "handled": False}, ) hub.capture_event(sentry_event, hint=hint) reraise(*exc_info) finally: if timeout_thread: timeout_thread.stop() return sentry_handler # type: ignore def _drain_queue(): # type: () -> None with capture_internal_exceptions(): hub = Hub.current integration = hub.get_integration(AwsLambdaIntegration) if integration is not None: # Flush out the event queue before AWS kills the # process. hub.flush() class AwsLambdaIntegration(Integration): identifier = "aws_lambda" def __init__(self, timeout_warning=False): # type: (bool) -> None self.timeout_warning = timeout_warning @staticmethod def setup_once(): # type: () -> None lambda_bootstrap = get_lambda_bootstrap() if not lambda_bootstrap: logger.warning( "Not running in AWS Lambda environment, " "AwsLambdaIntegration disabled (could not find bootstrap module)" ) return if not hasattr(lambda_bootstrap, "handle_event_request"): logger.warning( "Not running in AWS Lambda environment, " "AwsLambdaIntegration disabled (could not find handle_event_request)" ) return pre_37 = hasattr(lambda_bootstrap, "handle_http_request") # Python 3.6 or 2.7 if pre_37: old_handle_event_request = lambda_bootstrap.handle_event_request def sentry_handle_event_request(request_handler, *args, **kwargs): # type: (Any, *Any, **Any) -> Any request_handler = _wrap_handler(request_handler) return old_handle_event_request(request_handler, *args, **kwargs) lambda_bootstrap.handle_event_request = sentry_handle_event_request old_handle_http_request = lambda_bootstrap.handle_http_request def sentry_handle_http_request(request_handler, *args, **kwargs): # type: (Any, *Any, **Any) -> Any request_handler = _wrap_handler(request_handler) return old_handle_http_request(request_handler, *args, **kwargs) lambda_bootstrap.handle_http_request = sentry_handle_http_request # Patch to_json to drain the queue. This should work even when the # SDK is initialized inside of the handler old_to_json = lambda_bootstrap.to_json def sentry_to_json(*args, **kwargs): # type: (*Any, **Any) -> Any _drain_queue() return old_to_json(*args, **kwargs) lambda_bootstrap.to_json = sentry_to_json else: lambda_bootstrap.LambdaRuntimeClient.post_init_error = _wrap_init_error( lambda_bootstrap.LambdaRuntimeClient.post_init_error ) old_handle_event_request = lambda_bootstrap.handle_event_request def sentry_handle_event_request( # type: ignore lambda_runtime_client, request_handler, *args, **kwargs ): request_handler = _wrap_handler(request_handler) return old_handle_event_request( lambda_runtime_client, request_handler, *args, **kwargs ) lambda_bootstrap.handle_event_request = sentry_handle_event_request # Patch the runtime client to drain the queue. This should work # even when the SDK is initialized inside of the handler def _wrap_post_function(f): # type: (F) -> F def inner(*args, **kwargs): # type: (*Any, **Any) -> Any _drain_queue() return f(*args, **kwargs) return inner # type: ignore lambda_bootstrap.LambdaRuntimeClient.post_invocation_result = ( _wrap_post_function( lambda_bootstrap.LambdaRuntimeClient.post_invocation_result ) ) lambda_bootstrap.LambdaRuntimeClient.post_invocation_error = ( _wrap_post_function( lambda_bootstrap.LambdaRuntimeClient.post_invocation_error ) ) def get_lambda_bootstrap(): # type: () -> Optional[Any] # Python 2.7: Everything is in `__main__`. # # Python 3.7: If the bootstrap module is *already imported*, it is the # one we actually want to use (no idea what's in __main__) # # Python 3.8: bootstrap is also importable, but will be the same file # as __main__ imported under a different name: # # sys.modules['__main__'].__file__ == sys.modules['bootstrap'].__file__ # sys.modules['__main__'] is not sys.modules['bootstrap'] # # Python 3.9: bootstrap is in __main__.awslambdaricmain # # On container builds using the `aws-lambda-python-runtime-interface-client` # (awslamdaric) module, bootstrap is located in sys.modules['__main__'].bootstrap # # Such a setup would then make all monkeypatches useless. if "bootstrap" in sys.modules: return sys.modules["bootstrap"] elif "__main__" in sys.modules: module = sys.modules["__main__"] # python3.9 runtime if hasattr(module, "awslambdaricmain") and hasattr( module.awslambdaricmain, "bootstrap" ): return module.awslambdaricmain.bootstrap elif hasattr(module, "bootstrap"): # awslambdaric python module in container builds return module.bootstrap # python3.8 runtime return module else: return None def _make_request_event_processor(aws_event, aws_context, configured_timeout): # type: (Any, Any, Any) -> EventProcessor start_time = datetime.utcnow() def event_processor(sentry_event, hint, start_time=start_time): # type: (Event, Hint, datetime) -> Optional[Event] remaining_time_in_milis = aws_context.get_remaining_time_in_millis() exec_duration = configured_timeout - remaining_time_in_milis extra = sentry_event.setdefault("extra", {}) extra["lambda"] = { "function_name": aws_context.function_name, "function_version": aws_context.function_version, "invoked_function_arn": aws_context.invoked_function_arn, "aws_request_id": aws_context.aws_request_id, "execution_duration_in_millis": exec_duration, "remaining_time_in_millis": remaining_time_in_milis, } extra["cloudwatch logs"] = { "url": _get_cloudwatch_logs_url(aws_context, start_time), "log_group": aws_context.log_group_name, "log_stream": aws_context.log_stream_name, } request = sentry_event.get("request", {}) if "httpMethod" in aws_event: request["method"] = aws_event["httpMethod"] request["url"] = _get_url(aws_event, aws_context) if "queryStringParameters" in aws_event: request["query_string"] = aws_event["queryStringParameters"] if "headers" in aws_event: request["headers"] = _filter_headers(aws_event["headers"]) if _should_send_default_pii(): user_info = sentry_event.setdefault("user", {}) identity = aws_event.get("identity") if identity is None: identity = {} id = identity.get("userArn") if id is not None: user_info.setdefault("id", id) ip = identity.get("sourceIp") if ip is not None: user_info.setdefault("ip_address", ip) if "body" in aws_event: request["data"] = aws_event.get("body", "") else: if aws_event.get("body", None): # Unfortunately couldn't find a way to get structured body from AWS # event. Meaning every body is unstructured to us. request["data"] = AnnotatedValue.removed_because_raw_data() sentry_event["request"] = request return sentry_event return event_processor def _get_url(aws_event, aws_context): # type: (Any, Any) -> str path = aws_event.get("path", None) headers = aws_event.get("headers") if headers is None: headers = {} host = headers.get("Host", None) proto = headers.get("X-Forwarded-Proto", None) if proto and host and path: return "{}://{}{}".format(proto, host, path) return "awslambda:///{}".format(aws_context.function_name) def _get_cloudwatch_logs_url(aws_context, start_time): # type: (Any, datetime) -> str """ Generates a CloudWatchLogs console URL based on the context object Arguments: aws_context {Any} -- context from lambda handler Returns: str -- AWS Console URL to logs. """ formatstring = "%Y-%m-%dT%H:%M:%SZ" region = environ.get("AWS_REGION", "") url = ( "https://console.{domain}/cloudwatch/home?region={region}" "#logEventViewer:group={log_group};stream={log_stream}" ";start={start_time};end={end_time}" ).format( domain="amazonaws.cn" if region.startswith("cn-") else "aws.amazon.com", region=region, log_group=aws_context.log_group_name, log_stream=aws_context.log_stream_name, start_time=(start_time - timedelta(seconds=1)).strftime(formatstring), end_time=(datetime.utcnow() + timedelta(seconds=2)).strftime(formatstring), ) return url
15,751
Python
35.378753
105
0.57044
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/serverless.py
import sys from sentry_sdk.hub import Hub from sentry_sdk.utils import event_from_exception from sentry_sdk._compat import reraise from sentry_sdk._functools import wraps from sentry_sdk._types import MYPY if MYPY: from typing import Any from typing import Callable from typing import TypeVar from typing import Union from typing import Optional from typing import overload F = TypeVar("F", bound=Callable[..., Any]) else: def overload(x): # type: (F) -> F return x @overload def serverless_function(f, flush=True): # type: (F, bool) -> F pass @overload def serverless_function(f=None, flush=True): # noqa: F811 # type: (None, bool) -> Callable[[F], F] pass def serverless_function(f=None, flush=True): # noqa # type: (Optional[F], bool) -> Union[F, Callable[[F], F]] def wrapper(f): # type: (F) -> F @wraps(f) def inner(*args, **kwargs): # type: (*Any, **Any) -> Any with Hub(Hub.current) as hub: with hub.configure_scope() as scope: scope.clear_breadcrumbs() try: return f(*args, **kwargs) except Exception: _capture_and_reraise() finally: if flush: _flush_client() return inner # type: ignore if f is None: return wrapper else: return wrapper(f) def _capture_and_reraise(): # type: () -> None exc_info = sys.exc_info() hub = Hub.current if hub.client is not None: event, hint = event_from_exception( exc_info, client_options=hub.client.options, mechanism={"type": "serverless", "handled": False}, ) hub.capture_event(event, hint=hint) reraise(*exc_info) def _flush_client(): # type: () -> None return Hub.current.flush()
1,957
Python
21.767442
63
0.556975
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/starlite.py
from typing import TYPE_CHECKING from pydantic import BaseModel # type: ignore from sentry_sdk.consts import OP from sentry_sdk.hub import Hub, _should_send_default_pii from sentry_sdk.integrations import DidNotEnable, Integration from sentry_sdk.integrations.asgi import SentryAsgiMiddleware from sentry_sdk.tracing import SOURCE_FOR_STYLE, TRANSACTION_SOURCE_ROUTE from sentry_sdk.utils import event_from_exception, transaction_from_function try: from starlite import Request, Starlite, State # type: ignore from starlite.handlers.base import BaseRouteHandler # type: ignore from starlite.middleware import DefineMiddleware # type: ignore from starlite.plugins.base import get_plugin_for_value # type: ignore from starlite.routes.http import HTTPRoute # type: ignore from starlite.utils import ConnectionDataExtractor, is_async_callable, Ref # type: ignore if TYPE_CHECKING: from typing import Any, Dict, List, Optional, Union from starlite.types import ( # type: ignore ASGIApp, HTTPReceiveMessage, HTTPScope, Message, Middleware, Receive, Scope, Send, WebSocketReceiveMessage, ) from starlite import MiddlewareProtocol from sentry_sdk._types import Event except ImportError: raise DidNotEnable("Starlite is not installed") _DEFAULT_TRANSACTION_NAME = "generic Starlite request" class SentryStarliteASGIMiddleware(SentryAsgiMiddleware): def __init__(self, app: "ASGIApp"): super().__init__( app=app, unsafe_context_data=False, transaction_style="endpoint", mechanism_type="asgi", ) class StarliteIntegration(Integration): identifier = "starlite" @staticmethod def setup_once() -> None: patch_app_init() patch_middlewares() patch_http_route_handle() def patch_app_init() -> None: """ Replaces the Starlite class's `__init__` function in order to inject `after_exception` handlers and set the `SentryStarliteASGIMiddleware` as the outmost middleware in the stack. See: - https://starlite-api.github.io/starlite/usage/0-the-starlite-app/5-application-hooks/#after-exception - https://starlite-api.github.io/starlite/usage/7-middleware/0-middleware-intro/ """ old__init__ = Starlite.__init__ def injection_wrapper(self: "Starlite", *args: "Any", **kwargs: "Any") -> None: after_exception = kwargs.pop("after_exception", []) kwargs.update( after_exception=[ exception_handler, *( after_exception if isinstance(after_exception, list) else [after_exception] ), ] ) SentryStarliteASGIMiddleware.__call__ = SentryStarliteASGIMiddleware._run_asgi3 middleware = kwargs.pop("middleware", None) or [] kwargs["middleware"] = [SentryStarliteASGIMiddleware, *middleware] old__init__(self, *args, **kwargs) Starlite.__init__ = injection_wrapper def patch_middlewares() -> None: old__resolve_middleware_stack = BaseRouteHandler.resolve_middleware def resolve_middleware_wrapper(self: "Any") -> "List[Middleware]": return [ enable_span_for_middleware(middleware) for middleware in old__resolve_middleware_stack(self) ] BaseRouteHandler.resolve_middleware = resolve_middleware_wrapper def enable_span_for_middleware(middleware: "Middleware") -> "Middleware": if ( not hasattr(middleware, "__call__") # noqa: B004 or middleware is SentryStarliteASGIMiddleware ): return middleware if isinstance(middleware, DefineMiddleware): old_call: "ASGIApp" = middleware.middleware.__call__ else: old_call = middleware.__call__ async def _create_span_call( self: "MiddlewareProtocol", scope: "Scope", receive: "Receive", send: "Send" ) -> None: hub = Hub.current integration = hub.get_integration(StarliteIntegration) if integration is not None: middleware_name = self.__class__.__name__ with hub.start_span( op=OP.MIDDLEWARE_STARLITE, description=middleware_name ) as middleware_span: middleware_span.set_tag("starlite.middleware_name", middleware_name) # Creating spans for the "receive" callback async def _sentry_receive( *args: "Any", **kwargs: "Any" ) -> "Union[HTTPReceiveMessage, WebSocketReceiveMessage]": hub = Hub.current with hub.start_span( op=OP.MIDDLEWARE_STARLITE_RECEIVE, description=getattr(receive, "__qualname__", str(receive)), ) as span: span.set_tag("starlite.middleware_name", middleware_name) return await receive(*args, **kwargs) receive_name = getattr(receive, "__name__", str(receive)) receive_patched = receive_name == "_sentry_receive" new_receive = _sentry_receive if not receive_patched else receive # Creating spans for the "send" callback async def _sentry_send(message: "Message") -> None: hub = Hub.current with hub.start_span( op=OP.MIDDLEWARE_STARLITE_SEND, description=getattr(send, "__qualname__", str(send)), ) as span: span.set_tag("starlite.middleware_name", middleware_name) return await send(message) send_name = getattr(send, "__name__", str(send)) send_patched = send_name == "_sentry_send" new_send = _sentry_send if not send_patched else send return await old_call(self, scope, new_receive, new_send) else: return await old_call(self, scope, receive, send) not_yet_patched = old_call.__name__ not in ["_create_span_call"] if not_yet_patched: if isinstance(middleware, DefineMiddleware): middleware.middleware.__call__ = _create_span_call else: middleware.__call__ = _create_span_call return middleware def patch_http_route_handle() -> None: old_handle = HTTPRoute.handle async def handle_wrapper( self: "HTTPRoute", scope: "HTTPScope", receive: "Receive", send: "Send" ) -> None: hub = Hub.current integration: StarliteIntegration = hub.get_integration(StarliteIntegration) if integration is None: return await old_handle(self, scope, receive, send) with hub.configure_scope() as sentry_scope: request: "Request[Any, Any]" = scope["app"].request_class( scope=scope, receive=receive, send=send ) extracted_request_data = ConnectionDataExtractor( parse_body=True, parse_query=True )(request) body = extracted_request_data.pop("body") request_data = await body def event_processor(event: "Event", _: "Dict[str, Any]") -> "Event": route_handler = scope.get("route_handler") request_info = event.get("request", {}) request_info["content_length"] = len(scope.get("_body", b"")) if _should_send_default_pii(): request_info["cookies"] = extracted_request_data["cookies"] if request_data is not None: request_info["data"] = request_data func = None if route_handler.name is not None: tx_name = route_handler.name elif isinstance(route_handler.fn, Ref): func = route_handler.fn.value else: func = route_handler.fn if func is not None: tx_name = transaction_from_function(func) tx_info = {"source": SOURCE_FOR_STYLE["endpoint"]} if not tx_name: tx_name = _DEFAULT_TRANSACTION_NAME tx_info = {"source": TRANSACTION_SOURCE_ROUTE} event.update( request=request_info, transaction=tx_name, transaction_info=tx_info ) return event sentry_scope._name = StarliteIntegration.identifier sentry_scope.add_event_processor(event_processor) return await old_handle(self, scope, receive, send) HTTPRoute.handle = handle_wrapper def retrieve_user_from_scope(scope: "Scope") -> "Optional[Dict[str, Any]]": scope_user = scope.get("user", {}) if not scope_user: return None if isinstance(scope_user, dict): return scope_user if isinstance(scope_user, BaseModel): return scope_user.dict() if hasattr(scope_user, "asdict"): # dataclasses return scope_user.asdict() plugin = get_plugin_for_value(scope_user) if plugin and not is_async_callable(plugin.to_dict): return plugin.to_dict(scope_user) return None def exception_handler(exc: Exception, scope: "Scope", _: "State") -> None: hub = Hub.current if hub.get_integration(StarliteIntegration) is None: return user_info: "Optional[Dict[str, Any]]" = None if _should_send_default_pii(): user_info = retrieve_user_from_scope(scope) if user_info and isinstance(user_info, dict): with hub.configure_scope() as sentry_scope: sentry_scope.set_user(user_info) event, hint = event_from_exception( exc, client_options=hub.client.options if hub.client else None, mechanism={"type": StarliteIntegration.identifier, "handled": False}, ) hub.capture_event(event, hint=hint)
10,090
Python
36.099265
111
0.595837
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/tornado.py
import weakref import contextlib from inspect import iscoroutinefunction from sentry_sdk.consts import OP from sentry_sdk.hub import Hub, _should_send_default_pii from sentry_sdk.tracing import ( TRANSACTION_SOURCE_COMPONENT, TRANSACTION_SOURCE_ROUTE, Transaction, ) from sentry_sdk.utils import ( HAS_REAL_CONTEXTVARS, CONTEXTVARS_ERROR_MESSAGE, event_from_exception, capture_internal_exceptions, transaction_from_function, ) from sentry_sdk.integrations import Integration, DidNotEnable from sentry_sdk.integrations._wsgi_common import ( RequestExtractor, _filter_headers, _is_json_content_type, ) from sentry_sdk.integrations.logging import ignore_logger from sentry_sdk._compat import iteritems try: from tornado import version_info as TORNADO_VERSION from tornado.web import RequestHandler, HTTPError from tornado.gen import coroutine except ImportError: raise DidNotEnable("Tornado not installed") from sentry_sdk._types import MYPY if MYPY: from typing import Any from typing import Optional from typing import Dict from typing import Callable from typing import Generator from sentry_sdk._types import EventProcessor class TornadoIntegration(Integration): identifier = "tornado" @staticmethod def setup_once(): # type: () -> None if TORNADO_VERSION < (5, 0): raise DidNotEnable("Tornado 5+ required") if not HAS_REAL_CONTEXTVARS: # Tornado is async. We better have contextvars or we're going to leak # state between requests. raise DidNotEnable( "The tornado integration for Sentry requires Python 3.7+ or the aiocontextvars package" + CONTEXTVARS_ERROR_MESSAGE ) ignore_logger("tornado.access") old_execute = RequestHandler._execute awaitable = iscoroutinefunction(old_execute) if awaitable: # Starting Tornado 6 RequestHandler._execute method is a standard Python coroutine (async/await) # In that case our method should be a coroutine function too async def sentry_execute_request_handler(self, *args, **kwargs): # type: (RequestHandler, *Any, **Any) -> Any with _handle_request_impl(self): return await old_execute(self, *args, **kwargs) else: @coroutine # type: ignore def sentry_execute_request_handler(self, *args, **kwargs): # type: ignore # type: (RequestHandler, *Any, **Any) -> Any with _handle_request_impl(self): result = yield from old_execute(self, *args, **kwargs) return result RequestHandler._execute = sentry_execute_request_handler old_log_exception = RequestHandler.log_exception def sentry_log_exception(self, ty, value, tb, *args, **kwargs): # type: (Any, type, BaseException, Any, *Any, **Any) -> Optional[Any] _capture_exception(ty, value, tb) return old_log_exception(self, ty, value, tb, *args, **kwargs) RequestHandler.log_exception = sentry_log_exception @contextlib.contextmanager def _handle_request_impl(self): # type: (RequestHandler) -> Generator[None, None, None] hub = Hub.current integration = hub.get_integration(TornadoIntegration) if integration is None: yield weak_handler = weakref.ref(self) with Hub(hub) as hub: with hub.configure_scope() as scope: scope.clear_breadcrumbs() processor = _make_event_processor(weak_handler) scope.add_event_processor(processor) transaction = Transaction.continue_from_headers( self.request.headers, op=OP.HTTP_SERVER, # Like with all other integrations, this is our # fallback transaction in case there is no route. # sentry_urldispatcher_resolve is responsible for # setting a transaction name later. name="generic Tornado request", source=TRANSACTION_SOURCE_ROUTE, ) with hub.start_transaction( transaction, custom_sampling_context={"tornado_request": self.request} ): yield def _capture_exception(ty, value, tb): # type: (type, BaseException, Any) -> None hub = Hub.current if hub.get_integration(TornadoIntegration) is None: return if isinstance(value, HTTPError): return # If an integration is there, a client has to be there. client = hub.client # type: Any event, hint = event_from_exception( (ty, value, tb), client_options=client.options, mechanism={"type": "tornado", "handled": False}, ) hub.capture_event(event, hint=hint) def _make_event_processor(weak_handler): # type: (Callable[[], RequestHandler]) -> EventProcessor def tornado_processor(event, hint): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] handler = weak_handler() if handler is None: return event request = handler.request with capture_internal_exceptions(): method = getattr(handler, handler.request.method.lower()) event["transaction"] = transaction_from_function(method) event["transaction_info"] = {"source": TRANSACTION_SOURCE_COMPONENT} with capture_internal_exceptions(): extractor = TornadoRequestExtractor(request) extractor.extract_into_event(event) request_info = event["request"] request_info["url"] = "%s://%s%s" % ( request.protocol, request.host, request.path, ) request_info["query_string"] = request.query request_info["method"] = request.method request_info["env"] = {"REMOTE_ADDR": request.remote_ip} request_info["headers"] = _filter_headers(dict(request.headers)) with capture_internal_exceptions(): if handler.current_user and _should_send_default_pii(): event.setdefault("user", {}).setdefault("is_authenticated", True) return event return tornado_processor class TornadoRequestExtractor(RequestExtractor): def content_length(self): # type: () -> int if self.request.body is None: return 0 return len(self.request.body) def cookies(self): # type: () -> Dict[str, str] return {k: v.value for k, v in iteritems(self.request.cookies)} def raw_data(self): # type: () -> bytes return self.request.body def form(self): # type: () -> Dict[str, Any] return { k: [v.decode("latin1", "replace") for v in vs] for k, vs in iteritems(self.request.body_arguments) } def is_json(self): # type: () -> bool return _is_json_content_type(self.request.headers.get("content-type")) def files(self): # type: () -> Dict[str, Any] return {k: v[0] for k, v in iteritems(self.request.files) if v} def size_of_file(self, file): # type: (Any) -> int return len(file.body or ())
7,307
Python
31.193832
108
0.619406
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/asyncio.py
from __future__ import absolute_import import sys from sentry_sdk._compat import reraise from sentry_sdk.consts import OP from sentry_sdk.hub import Hub from sentry_sdk.integrations import Integration, DidNotEnable from sentry_sdk._types import MYPY from sentry_sdk.utils import event_from_exception try: import asyncio from asyncio.tasks import Task except ImportError: raise DidNotEnable("asyncio not available") if MYPY: from typing import Any from sentry_sdk._types import ExcInfo def patch_asyncio(): # type: () -> None orig_task_factory = None try: loop = asyncio.get_running_loop() orig_task_factory = loop.get_task_factory() def _sentry_task_factory(loop, coro): # type: (Any, Any) -> Any async def _coro_creating_hub_and_span(): # type: () -> None hub = Hub(Hub.current) with hub: with hub.start_span(op=OP.FUNCTION, description=coro.__qualname__): try: await coro except Exception: reraise(*_capture_exception(hub)) # Trying to use user set task factory (if there is one) if orig_task_factory: return orig_task_factory(loop, _coro_creating_hub_and_span()) # type: ignore # The default task factory in `asyncio` does not have its own function # but is just a couple of lines in `asyncio.base_events.create_task()` # Those lines are copied here. # WARNING: # If the default behavior of the task creation in asyncio changes, # this will break! task = Task(_coro_creating_hub_and_span(), loop=loop) if task._source_traceback: # type: ignore del task._source_traceback[-1] # type: ignore return task loop.set_task_factory(_sentry_task_factory) except RuntimeError: # When there is no running loop, we have nothing to patch. pass def _capture_exception(hub): # type: (Hub) -> ExcInfo exc_info = sys.exc_info() integration = hub.get_integration(AsyncioIntegration) if integration is not None: # If an integration is there, a client has to be there. client = hub.client # type: Any event, hint = event_from_exception( exc_info, client_options=client.options, mechanism={"type": "asyncio", "handled": False}, ) hub.capture_event(event, hint=hint) return exc_info class AsyncioIntegration(Integration): identifier = "asyncio" @staticmethod def setup_once(): # type: () -> None patch_asyncio()
2,787
Python
28.978494
93
0.592034
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/fastapi.py
import asyncio import threading from sentry_sdk._types import MYPY from sentry_sdk.hub import Hub, _should_send_default_pii from sentry_sdk.integrations import DidNotEnable from sentry_sdk.integrations.starlette import ( StarletteIntegration, StarletteRequestExtractor, ) from sentry_sdk.tracing import SOURCE_FOR_STYLE, TRANSACTION_SOURCE_ROUTE from sentry_sdk.utils import transaction_from_function if MYPY: from typing import Any, Callable, Dict from sentry_sdk.scope import Scope try: import fastapi # type: ignore except ImportError: raise DidNotEnable("FastAPI is not installed") _DEFAULT_TRANSACTION_NAME = "generic FastAPI request" class FastApiIntegration(StarletteIntegration): identifier = "fastapi" @staticmethod def setup_once(): # type: () -> None patch_get_request_handler() def _set_transaction_name_and_source(scope, transaction_style, request): # type: (Scope, str, Any) -> None name = "" if transaction_style == "endpoint": endpoint = request.scope.get("endpoint") if endpoint: name = transaction_from_function(endpoint) or "" elif transaction_style == "url": route = request.scope.get("route") if route: path = getattr(route, "path", None) if path is not None: name = path if not name: name = _DEFAULT_TRANSACTION_NAME source = TRANSACTION_SOURCE_ROUTE else: source = SOURCE_FOR_STYLE[transaction_style] scope.set_transaction_name(name, source=source) def patch_get_request_handler(): # type: () -> None old_get_request_handler = fastapi.routing.get_request_handler def _sentry_get_request_handler(*args, **kwargs): # type: (*Any, **Any) -> Any dependant = kwargs.get("dependant") if ( dependant and dependant.call is not None and not asyncio.iscoroutinefunction(dependant.call) ): old_call = dependant.call def _sentry_call(*args, **kwargs): # type: (*Any, **Any) -> Any hub = Hub.current with hub.configure_scope() as sentry_scope: if sentry_scope.profile is not None: sentry_scope.profile.active_thread_id = ( threading.current_thread().ident ) return old_call(*args, **kwargs) dependant.call = _sentry_call old_app = old_get_request_handler(*args, **kwargs) async def _sentry_app(*args, **kwargs): # type: (*Any, **Any) -> Any hub = Hub.current integration = hub.get_integration(FastApiIntegration) if integration is None: return await old_app(*args, **kwargs) with hub.configure_scope() as sentry_scope: request = args[0] _set_transaction_name_and_source( sentry_scope, integration.transaction_style, request ) extractor = StarletteRequestExtractor(request) info = await extractor.extract_request_info() def _make_request_event_processor(req, integration): # type: (Any, Any) -> Callable[[Dict[str, Any], Dict[str, Any]], Dict[str, Any]] def event_processor(event, hint): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] # Extract information from request request_info = event.get("request", {}) if info: if "cookies" in info and _should_send_default_pii(): request_info["cookies"] = info["cookies"] if "data" in info: request_info["data"] = info["data"] event["request"] = request_info return event return event_processor sentry_scope._name = FastApiIntegration.identifier sentry_scope.add_event_processor( _make_request_event_processor(request, integration) ) return await old_app(*args, **kwargs) return _sentry_app fastapi.routing.get_request_handler = _sentry_get_request_handler
4,446
Python
31.940741
100
0.562753
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/excepthook.py
import sys from sentry_sdk.hub import Hub from sentry_sdk.utils import capture_internal_exceptions, event_from_exception from sentry_sdk.integrations import Integration from sentry_sdk._types import MYPY if MYPY: from typing import Callable from typing import Any from typing import Type from typing import Optional from types import TracebackType Excepthook = Callable[ [Type[BaseException], BaseException, Optional[TracebackType]], Any, ] class ExcepthookIntegration(Integration): identifier = "excepthook" always_run = False def __init__(self, always_run=False): # type: (bool) -> None if not isinstance(always_run, bool): raise ValueError( "Invalid value for always_run: %s (must be type boolean)" % (always_run,) ) self.always_run = always_run @staticmethod def setup_once(): # type: () -> None sys.excepthook = _make_excepthook(sys.excepthook) def _make_excepthook(old_excepthook): # type: (Excepthook) -> Excepthook def sentry_sdk_excepthook(type_, value, traceback): # type: (Type[BaseException], BaseException, Optional[TracebackType]) -> None hub = Hub.current integration = hub.get_integration(ExcepthookIntegration) if integration is not None and _should_send(integration.always_run): # If an integration is there, a client has to be there. client = hub.client # type: Any with capture_internal_exceptions(): event, hint = event_from_exception( (type_, value, traceback), client_options=client.options, mechanism={"type": "excepthook", "handled": False}, ) hub.capture_event(event, hint=hint) return old_excepthook(type_, value, traceback) return sentry_sdk_excepthook def _should_send(always_run=False): # type: (bool) -> bool if always_run: return True if hasattr(sys, "ps1"): # Disable the excepthook for interactive Python shells, otherwise # every typo gets sent to Sentry. return False return True
2,242
Python
27.392405
85
0.621766
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/chalice.py
import sys from sentry_sdk._compat import reraise from sentry_sdk.hub import Hub from sentry_sdk.integrations import Integration, DidNotEnable from sentry_sdk.integrations.aws_lambda import _make_request_event_processor from sentry_sdk.tracing import TRANSACTION_SOURCE_COMPONENT from sentry_sdk.utils import ( capture_internal_exceptions, event_from_exception, ) from sentry_sdk._types import MYPY from sentry_sdk._functools import wraps import chalice # type: ignore from chalice import Chalice, ChaliceViewError from chalice.app import EventSourceHandler as ChaliceEventSourceHandler # type: ignore if MYPY: from typing import Any from typing import Dict from typing import TypeVar from typing import Callable F = TypeVar("F", bound=Callable[..., Any]) try: from chalice import __version__ as CHALICE_VERSION except ImportError: raise DidNotEnable("Chalice is not installed") class EventSourceHandler(ChaliceEventSourceHandler): # type: ignore def __call__(self, event, context): # type: (Any, Any) -> Any hub = Hub.current client = hub.client # type: Any with hub.push_scope() as scope: with capture_internal_exceptions(): configured_time = context.get_remaining_time_in_millis() scope.add_event_processor( _make_request_event_processor(event, context, configured_time) ) try: return ChaliceEventSourceHandler.__call__(self, event, context) except Exception: exc_info = sys.exc_info() event, hint = event_from_exception( exc_info, client_options=client.options, mechanism={"type": "chalice", "handled": False}, ) hub.capture_event(event, hint=hint) hub.flush() reraise(*exc_info) def _get_view_function_response(app, view_function, function_args): # type: (Any, F, Any) -> F @wraps(view_function) def wrapped_view_function(**function_args): # type: (**Any) -> Any hub = Hub.current client = hub.client # type: Any with hub.push_scope() as scope: with capture_internal_exceptions(): configured_time = app.lambda_context.get_remaining_time_in_millis() scope.set_transaction_name( app.lambda_context.function_name, source=TRANSACTION_SOURCE_COMPONENT, ) scope.add_event_processor( _make_request_event_processor( app.current_request.to_dict(), app.lambda_context, configured_time, ) ) try: return view_function(**function_args) except Exception as exc: if isinstance(exc, ChaliceViewError): raise exc_info = sys.exc_info() event, hint = event_from_exception( exc_info, client_options=client.options, mechanism={"type": "chalice", "handled": False}, ) hub.capture_event(event, hint=hint) hub.flush() raise return wrapped_view_function # type: ignore class ChaliceIntegration(Integration): identifier = "chalice" @staticmethod def setup_once(): # type: () -> None try: version = tuple(map(int, CHALICE_VERSION.split(".")[:3])) except (ValueError, TypeError): raise DidNotEnable("Unparsable Chalice version: {}".format(CHALICE_VERSION)) if version < (1, 20): old_get_view_function_response = Chalice._get_view_function_response else: from chalice.app import RestAPIEventHandler old_get_view_function_response = ( RestAPIEventHandler._get_view_function_response ) def sentry_event_response(app, view_function, function_args): # type: (Any, F, Dict[str, Any]) -> Any wrapped_view_function = _get_view_function_response( app, view_function, function_args ) return old_get_view_function_response( app, wrapped_view_function, function_args ) if version < (1, 20): Chalice._get_view_function_response = sentry_event_response else: RestAPIEventHandler._get_view_function_response = sentry_event_response # for everything else (like events) chalice.app.EventSourceHandler = EventSourceHandler
4,775
Python
34.641791
88
0.578429
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/stdlib.py
import os import subprocess import sys import platform from sentry_sdk.consts import OP from sentry_sdk.hub import Hub from sentry_sdk.integrations import Integration from sentry_sdk.scope import add_global_event_processor from sentry_sdk.tracing_utils import EnvironHeaders from sentry_sdk.utils import capture_internal_exceptions, logger, safe_repr from sentry_sdk._types import MYPY if MYPY: from typing import Any from typing import Callable from typing import Dict from typing import Optional from typing import List from sentry_sdk._types import Event, Hint try: from httplib import HTTPConnection # type: ignore except ImportError: from http.client import HTTPConnection _RUNTIME_CONTEXT = { "name": platform.python_implementation(), "version": "%s.%s.%s" % (sys.version_info[:3]), "build": sys.version, } class StdlibIntegration(Integration): identifier = "stdlib" @staticmethod def setup_once(): # type: () -> None _install_httplib() _install_subprocess() @add_global_event_processor def add_python_runtime_context(event, hint): # type: (Event, Hint) -> Optional[Event] if Hub.current.get_integration(StdlibIntegration) is not None: contexts = event.setdefault("contexts", {}) if isinstance(contexts, dict) and "runtime" not in contexts: contexts["runtime"] = _RUNTIME_CONTEXT return event def _install_httplib(): # type: () -> None real_putrequest = HTTPConnection.putrequest real_getresponse = HTTPConnection.getresponse def putrequest(self, method, url, *args, **kwargs): # type: (HTTPConnection, str, str, *Any, **Any) -> Any hub = Hub.current if hub.get_integration(StdlibIntegration) is None: return real_putrequest(self, method, url, *args, **kwargs) host = self.host port = self.port default_port = self.default_port real_url = url if real_url is None or not real_url.startswith(("http://", "https://")): real_url = "%s://%s%s%s" % ( default_port == 443 and "https" or "http", host, port != default_port and ":%s" % port or "", url, ) span = hub.start_span( op=OP.HTTP_CLIENT, description="%s %s" % (method, real_url) ) span.set_data("method", method) span.set_data("url", real_url) rv = real_putrequest(self, method, url, *args, **kwargs) for key, value in hub.iter_trace_propagation_headers(span): logger.debug( "[Tracing] Adding `{key}` header {value} to outgoing request to {real_url}.".format( key=key, value=value, real_url=real_url ) ) self.putheader(key, value) self._sentrysdk_span = span return rv def getresponse(self, *args, **kwargs): # type: (HTTPConnection, *Any, **Any) -> Any span = getattr(self, "_sentrysdk_span", None) if span is None: return real_getresponse(self, *args, **kwargs) rv = real_getresponse(self, *args, **kwargs) span.set_data("status_code", rv.status) span.set_http_status(int(rv.status)) span.set_data("reason", rv.reason) span.finish() return rv HTTPConnection.putrequest = putrequest HTTPConnection.getresponse = getresponse def _init_argument(args, kwargs, name, position, setdefault_callback=None): # type: (List[Any], Dict[Any, Any], str, int, Optional[Callable[[Any], Any]]) -> Any """ given (*args, **kwargs) of a function call, retrieve (and optionally set a default for) an argument by either name or position. This is useful for wrapping functions with complex type signatures and extracting a few arguments without needing to redefine that function's entire type signature. """ if name in kwargs: rv = kwargs[name] if setdefault_callback is not None: rv = setdefault_callback(rv) if rv is not None: kwargs[name] = rv elif position < len(args): rv = args[position] if setdefault_callback is not None: rv = setdefault_callback(rv) if rv is not None: args[position] = rv else: rv = setdefault_callback and setdefault_callback(None) if rv is not None: kwargs[name] = rv return rv def _install_subprocess(): # type: () -> None old_popen_init = subprocess.Popen.__init__ def sentry_patched_popen_init(self, *a, **kw): # type: (subprocess.Popen[Any], *Any, **Any) -> None hub = Hub.current if hub.get_integration(StdlibIntegration) is None: return old_popen_init(self, *a, **kw) # Convert from tuple to list to be able to set values. a = list(a) args = _init_argument(a, kw, "args", 0) or [] cwd = _init_argument(a, kw, "cwd", 9) # if args is not a list or tuple (and e.g. some iterator instead), # let's not use it at all. There are too many things that can go wrong # when trying to collect an iterator into a list and setting that list # into `a` again. # # Also invocations where `args` is not a sequence are not actually # legal. They just happen to work under CPython. description = None if isinstance(args, (list, tuple)) and len(args) < 100: with capture_internal_exceptions(): description = " ".join(map(str, args)) if description is None: description = safe_repr(args) env = None with hub.start_span(op=OP.SUBPROCESS, description=description) as span: for k, v in hub.iter_trace_propagation_headers(span): if env is None: env = _init_argument( a, kw, "env", 10, lambda x: dict(x or os.environ) ) env["SUBPROCESS_" + k.upper().replace("-", "_")] = v if cwd: span.set_data("subprocess.cwd", cwd) rv = old_popen_init(self, *a, **kw) span.set_tag("subprocess.pid", self.pid) return rv subprocess.Popen.__init__ = sentry_patched_popen_init # type: ignore old_popen_wait = subprocess.Popen.wait def sentry_patched_popen_wait(self, *a, **kw): # type: (subprocess.Popen[Any], *Any, **Any) -> Any hub = Hub.current if hub.get_integration(StdlibIntegration) is None: return old_popen_wait(self, *a, **kw) with hub.start_span(op=OP.SUBPROCESS_WAIT) as span: span.set_tag("subprocess.pid", self.pid) return old_popen_wait(self, *a, **kw) subprocess.Popen.wait = sentry_patched_popen_wait # type: ignore old_popen_communicate = subprocess.Popen.communicate def sentry_patched_popen_communicate(self, *a, **kw): # type: (subprocess.Popen[Any], *Any, **Any) -> Any hub = Hub.current if hub.get_integration(StdlibIntegration) is None: return old_popen_communicate(self, *a, **kw) with hub.start_span(op=OP.SUBPROCESS_COMMUNICATE) as span: span.set_tag("subprocess.pid", self.pid) return old_popen_communicate(self, *a, **kw) subprocess.Popen.communicate = sentry_patched_popen_communicate # type: ignore def get_subprocess_traceparent_headers(): # type: () -> EnvironHeaders return EnvironHeaders(os.environ, prefix="SUBPROCESS_")
7,705
Python
30.975104
100
0.597404
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/starlette.py
from __future__ import absolute_import import asyncio import functools import threading from sentry_sdk._compat import iteritems from sentry_sdk._types import MYPY from sentry_sdk.consts import OP from sentry_sdk.hub import Hub, _should_send_default_pii from sentry_sdk.integrations import DidNotEnable, Integration from sentry_sdk.integrations._wsgi_common import ( _is_json_content_type, request_body_within_bounds, ) from sentry_sdk.integrations.asgi import SentryAsgiMiddleware from sentry_sdk.tracing import SOURCE_FOR_STYLE, TRANSACTION_SOURCE_ROUTE from sentry_sdk.utils import ( AnnotatedValue, capture_internal_exceptions, event_from_exception, transaction_from_function, ) if MYPY: from typing import Any, Awaitable, Callable, Dict, Optional from sentry_sdk.scope import Scope as SentryScope try: import starlette # type: ignore from starlette.applications import Starlette # type: ignore from starlette.datastructures import UploadFile # type: ignore from starlette.middleware import Middleware # type: ignore from starlette.middleware.authentication import ( # type: ignore AuthenticationMiddleware, ) from starlette.requests import Request # type: ignore from starlette.routing import Match # type: ignore from starlette.types import ASGIApp, Receive, Scope as StarletteScope, Send # type: ignore except ImportError: raise DidNotEnable("Starlette is not installed") try: # Starlette 0.20 from starlette.middleware.exceptions import ExceptionMiddleware # type: ignore except ImportError: # Startlette 0.19.1 from starlette.exceptions import ExceptionMiddleware # type: ignore try: # Optional dependency of Starlette to parse form data. import multipart # type: ignore except ImportError: multipart = None _DEFAULT_TRANSACTION_NAME = "generic Starlette request" TRANSACTION_STYLE_VALUES = ("endpoint", "url") class StarletteIntegration(Integration): identifier = "starlette" transaction_style = "" def __init__(self, transaction_style="url"): # type: (str) -> None if transaction_style not in TRANSACTION_STYLE_VALUES: raise ValueError( "Invalid value for transaction_style: %s (must be in %s)" % (transaction_style, TRANSACTION_STYLE_VALUES) ) self.transaction_style = transaction_style @staticmethod def setup_once(): # type: () -> None patch_middlewares() patch_asgi_app() patch_request_response() def _enable_span_for_middleware(middleware_class): # type: (Any) -> type old_call = middleware_class.__call__ async def _create_span_call(app, scope, receive, send, **kwargs): # type: (Any, Dict[str, Any], Callable[[], Awaitable[Dict[str, Any]]], Callable[[Dict[str, Any]], Awaitable[None]], Any) -> None hub = Hub.current integration = hub.get_integration(StarletteIntegration) if integration is not None: middleware_name = app.__class__.__name__ with hub.start_span( op=OP.MIDDLEWARE_STARLETTE, description=middleware_name ) as middleware_span: middleware_span.set_tag("starlette.middleware_name", middleware_name) # Creating spans for the "receive" callback async def _sentry_receive(*args, **kwargs): # type: (*Any, **Any) -> Any hub = Hub.current with hub.start_span( op=OP.MIDDLEWARE_STARLETTE_RECEIVE, description=getattr(receive, "__qualname__", str(receive)), ) as span: span.set_tag("starlette.middleware_name", middleware_name) return await receive(*args, **kwargs) receive_name = getattr(receive, "__name__", str(receive)) receive_patched = receive_name == "_sentry_receive" new_receive = _sentry_receive if not receive_patched else receive # Creating spans for the "send" callback async def _sentry_send(*args, **kwargs): # type: (*Any, **Any) -> Any hub = Hub.current with hub.start_span( op=OP.MIDDLEWARE_STARLETTE_SEND, description=getattr(send, "__qualname__", str(send)), ) as span: span.set_tag("starlette.middleware_name", middleware_name) return await send(*args, **kwargs) send_name = getattr(send, "__name__", str(send)) send_patched = send_name == "_sentry_send" new_send = _sentry_send if not send_patched else send return await old_call(app, scope, new_receive, new_send, **kwargs) else: return await old_call(app, scope, receive, send, **kwargs) not_yet_patched = old_call.__name__ not in [ "_create_span_call", "_sentry_authenticationmiddleware_call", "_sentry_exceptionmiddleware_call", ] if not_yet_patched: middleware_class.__call__ = _create_span_call return middleware_class def _capture_exception(exception, handled=False): # type: (BaseException, **Any) -> None hub = Hub.current if hub.get_integration(StarletteIntegration) is None: return event, hint = event_from_exception( exception, client_options=hub.client.options if hub.client else None, mechanism={"type": StarletteIntegration.identifier, "handled": handled}, ) hub.capture_event(event, hint=hint) def patch_exception_middleware(middleware_class): # type: (Any) -> None """ Capture all exceptions in Starlette app and also extract user information. """ old_middleware_init = middleware_class.__init__ not_yet_patched = "_sentry_middleware_init" not in str(old_middleware_init) if not_yet_patched: def _sentry_middleware_init(self, *args, **kwargs): # type: (Any, Any, Any) -> None old_middleware_init(self, *args, **kwargs) # Patch existing exception handlers old_handlers = self._exception_handlers.copy() async def _sentry_patched_exception_handler(self, *args, **kwargs): # type: (Any, Any, Any) -> None exp = args[0] is_http_server_error = ( hasattr(exp, "status_code") and exp.status_code >= 500 ) if is_http_server_error: _capture_exception(exp, handled=True) # Find a matching handler old_handler = None for cls in type(exp).__mro__: if cls in old_handlers: old_handler = old_handlers[cls] break if old_handler is None: return if _is_async_callable(old_handler): return await old_handler(self, *args, **kwargs) else: return old_handler(self, *args, **kwargs) for key in self._exception_handlers.keys(): self._exception_handlers[key] = _sentry_patched_exception_handler middleware_class.__init__ = _sentry_middleware_init old_call = middleware_class.__call__ async def _sentry_exceptionmiddleware_call(self, scope, receive, send): # type: (Dict[str, Any], Dict[str, Any], Callable[[], Awaitable[Dict[str, Any]]], Callable[[Dict[str, Any]], Awaitable[None]]) -> None # Also add the user (that was eventually set by be Authentication middle # that was called before this middleware). This is done because the authentication # middleware sets the user in the scope and then (in the same function) # calls this exception middelware. In case there is no exception (or no handler # for the type of exception occuring) then the exception bubbles up and setting the # user information into the sentry scope is done in auth middleware and the # ASGI middleware will then send everything to Sentry and this is fine. # But if there is an exception happening that the exception middleware here # has a handler for, it will send the exception directly to Sentry, so we need # the user information right now. # This is why we do it here. _add_user_to_sentry_scope(scope) await old_call(self, scope, receive, send) middleware_class.__call__ = _sentry_exceptionmiddleware_call def _add_user_to_sentry_scope(scope): # type: (Dict[str, Any]) -> None """ Extracts user information from the ASGI scope and adds it to Sentry's scope. """ if "user" not in scope: return if not _should_send_default_pii(): return hub = Hub.current if hub.get_integration(StarletteIntegration) is None: return with hub.configure_scope() as sentry_scope: user_info = {} # type: Dict[str, Any] starlette_user = scope["user"] username = getattr(starlette_user, "username", None) if username: user_info.setdefault("username", starlette_user.username) user_id = getattr(starlette_user, "id", None) if user_id: user_info.setdefault("id", starlette_user.id) email = getattr(starlette_user, "email", None) if email: user_info.setdefault("email", starlette_user.email) sentry_scope.user = user_info def patch_authentication_middleware(middleware_class): # type: (Any) -> None """ Add user information to Sentry scope. """ old_call = middleware_class.__call__ not_yet_patched = "_sentry_authenticationmiddleware_call" not in str(old_call) if not_yet_patched: async def _sentry_authenticationmiddleware_call(self, scope, receive, send): # type: (Dict[str, Any], Dict[str, Any], Callable[[], Awaitable[Dict[str, Any]]], Callable[[Dict[str, Any]], Awaitable[None]]) -> None await old_call(self, scope, receive, send) _add_user_to_sentry_scope(scope) middleware_class.__call__ = _sentry_authenticationmiddleware_call def patch_middlewares(): # type: () -> None """ Patches Starlettes `Middleware` class to record spans for every middleware invoked. """ old_middleware_init = Middleware.__init__ not_yet_patched = "_sentry_middleware_init" not in str(old_middleware_init) if not_yet_patched: def _sentry_middleware_init(self, cls, **options): # type: (Any, Any, Any) -> None if cls == SentryAsgiMiddleware: return old_middleware_init(self, cls, **options) span_enabled_cls = _enable_span_for_middleware(cls) old_middleware_init(self, span_enabled_cls, **options) if cls == AuthenticationMiddleware: patch_authentication_middleware(cls) if cls == ExceptionMiddleware: patch_exception_middleware(cls) Middleware.__init__ = _sentry_middleware_init def patch_asgi_app(): # type: () -> None """ Instrument Starlette ASGI app using the SentryAsgiMiddleware. """ old_app = Starlette.__call__ async def _sentry_patched_asgi_app(self, scope, receive, send): # type: (Starlette, StarletteScope, Receive, Send) -> None if Hub.current.get_integration(StarletteIntegration) is None: return await old_app(self, scope, receive, send) middleware = SentryAsgiMiddleware( lambda *a, **kw: old_app(self, *a, **kw), mechanism_type=StarletteIntegration.identifier, ) middleware.__call__ = middleware._run_asgi3 return await middleware(scope, receive, send) Starlette.__call__ = _sentry_patched_asgi_app # This was vendored in from Starlette to support Starlette 0.19.1 because # this function was only introduced in 0.20.x def _is_async_callable(obj): # type: (Any) -> bool while isinstance(obj, functools.partial): obj = obj.func return asyncio.iscoroutinefunction(obj) or ( callable(obj) and asyncio.iscoroutinefunction(obj.__call__) ) def patch_request_response(): # type: () -> None old_request_response = starlette.routing.request_response def _sentry_request_response(func): # type: (Callable[[Any], Any]) -> ASGIApp old_func = func is_coroutine = _is_async_callable(old_func) if is_coroutine: async def _sentry_async_func(*args, **kwargs): # type: (*Any, **Any) -> Any hub = Hub.current integration = hub.get_integration(StarletteIntegration) if integration is None: return await old_func(*args, **kwargs) with hub.configure_scope() as sentry_scope: request = args[0] _set_transaction_name_and_source( sentry_scope, integration.transaction_style, request ) extractor = StarletteRequestExtractor(request) info = await extractor.extract_request_info() def _make_request_event_processor(req, integration): # type: (Any, Any) -> Callable[[Dict[str, Any], Dict[str, Any]], Dict[str, Any]] def event_processor(event, hint): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] # Add info from request to event request_info = event.get("request", {}) if info: if "cookies" in info: request_info["cookies"] = info["cookies"] if "data" in info: request_info["data"] = info["data"] event["request"] = request_info return event return event_processor sentry_scope._name = StarletteIntegration.identifier sentry_scope.add_event_processor( _make_request_event_processor(request, integration) ) return await old_func(*args, **kwargs) func = _sentry_async_func else: def _sentry_sync_func(*args, **kwargs): # type: (*Any, **Any) -> Any hub = Hub.current integration = hub.get_integration(StarletteIntegration) if integration is None: return old_func(*args, **kwargs) with hub.configure_scope() as sentry_scope: if sentry_scope.profile is not None: sentry_scope.profile.active_thread_id = ( threading.current_thread().ident ) request = args[0] _set_transaction_name_and_source( sentry_scope, integration.transaction_style, request ) extractor = StarletteRequestExtractor(request) cookies = extractor.extract_cookies_from_request() def _make_request_event_processor(req, integration): # type: (Any, Any) -> Callable[[Dict[str, Any], Dict[str, Any]], Dict[str, Any]] def event_processor(event, hint): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] # Extract information from request request_info = event.get("request", {}) if cookies: request_info["cookies"] = cookies event["request"] = request_info return event return event_processor sentry_scope._name = StarletteIntegration.identifier sentry_scope.add_event_processor( _make_request_event_processor(request, integration) ) return old_func(*args, **kwargs) func = _sentry_sync_func return old_request_response(func) starlette.routing.request_response = _sentry_request_response class StarletteRequestExtractor: """ Extracts useful information from the Starlette request (like form data or cookies) and adds it to the Sentry event. """ request = None # type: Request def __init__(self, request): # type: (StarletteRequestExtractor, Request) -> None self.request = request def extract_cookies_from_request(self): # type: (StarletteRequestExtractor) -> Optional[Dict[str, Any]] client = Hub.current.client if client is None: return None cookies = None # type: Optional[Dict[str, Any]] if _should_send_default_pii(): cookies = self.cookies() return cookies async def extract_request_info(self): # type: (StarletteRequestExtractor) -> Optional[Dict[str, Any]] client = Hub.current.client if client is None: return None request_info = {} # type: Dict[str, Any] with capture_internal_exceptions(): # Add cookies if _should_send_default_pii(): request_info["cookies"] = self.cookies() # If there is no body, just return the cookies content_length = await self.content_length() if not content_length: return request_info # Add annotation if body is too big if content_length and not request_body_within_bounds( client, content_length ): request_info["data"] = AnnotatedValue.removed_because_over_size_limit() return request_info # Add JSON body, if it is a JSON request json = await self.json() if json: request_info["data"] = json return request_info # Add form as key/value pairs, if request has form data form = await self.form() if form: form_data = {} for key, val in iteritems(form): is_file = isinstance(val, UploadFile) form_data[key] = ( val if not is_file else AnnotatedValue.removed_because_raw_data() ) request_info["data"] = form_data return request_info # Raw data, do not add body just an annotation request_info["data"] = AnnotatedValue.removed_because_raw_data() return request_info async def content_length(self): # type: (StarletteRequestExtractor) -> Optional[int] if "content-length" in self.request.headers: return int(self.request.headers["content-length"]) return None def cookies(self): # type: (StarletteRequestExtractor) -> Dict[str, Any] return self.request.cookies async def form(self): # type: (StarletteRequestExtractor) -> Any if multipart is None: return None # Parse the body first to get it cached, as Starlette does not cache form() as it # does with body() and json() https://github.com/encode/starlette/discussions/1933 # Calling `.form()` without calling `.body()` first will # potentially break the users project. await self.request.body() return await self.request.form() def is_json(self): # type: (StarletteRequestExtractor) -> bool return _is_json_content_type(self.request.headers.get("content-type")) async def json(self): # type: (StarletteRequestExtractor) -> Optional[Dict[str, Any]] if not self.is_json(): return None return await self.request.json() def _set_transaction_name_and_source(scope, transaction_style, request): # type: (SentryScope, str, Any) -> None name = "" if transaction_style == "endpoint": endpoint = request.scope.get("endpoint") if endpoint: name = transaction_from_function(endpoint) or "" elif transaction_style == "url": router = request.scope["router"] for route in router.routes: match = route.matches(request.scope) if match[0] == Match.FULL: if transaction_style == "endpoint": name = transaction_from_function(match[1]["endpoint"]) or "" break elif transaction_style == "url": name = route.path break if not name: name = _DEFAULT_TRANSACTION_NAME source = TRANSACTION_SOURCE_ROUTE else: source = SOURCE_FOR_STYLE[transaction_style] scope.set_transaction_name(name, source=source)
21,474
Python
34.911371
146
0.575626
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/atexit.py
from __future__ import absolute_import import os import sys import atexit from sentry_sdk.hub import Hub from sentry_sdk.utils import logger from sentry_sdk.integrations import Integration from sentry_sdk._types import MYPY if MYPY: from typing import Any from typing import Optional def default_callback(pending, timeout): # type: (int, int) -> None """This is the default shutdown callback that is set on the options. It prints out a message to stderr that informs the user that some events are still pending and the process is waiting for them to flush out. """ def echo(msg): # type: (str) -> None sys.stderr.write(msg + "\n") echo("Sentry is attempting to send %i pending error messages" % pending) echo("Waiting up to %s seconds" % timeout) echo("Press Ctrl-%s to quit" % (os.name == "nt" and "Break" or "C")) sys.stderr.flush() class AtexitIntegration(Integration): identifier = "atexit" def __init__(self, callback=None): # type: (Optional[Any]) -> None if callback is None: callback = default_callback self.callback = callback @staticmethod def setup_once(): # type: () -> None @atexit.register def _shutdown(): # type: () -> None logger.debug("atexit: got shutdown signal") hub = Hub.main integration = hub.get_integration(AtexitIntegration) if integration is not None: logger.debug("atexit: shutting down client") # If there is a session on the hub, close it now. hub.end_session() # If an integration is there, a client has to be there. client = hub.client # type: Any client.close(callback=integration.callback)
1,837
Python
28.174603
76
0.616766
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/falcon.py
from __future__ import absolute_import from sentry_sdk.hub import Hub from sentry_sdk.integrations import Integration, DidNotEnable from sentry_sdk.integrations._wsgi_common import RequestExtractor from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware from sentry_sdk.tracing import SOURCE_FOR_STYLE from sentry_sdk.utils import ( capture_internal_exceptions, event_from_exception, ) from sentry_sdk._types import MYPY if MYPY: from typing import Any from typing import Dict from typing import Optional from sentry_sdk._types import EventProcessor try: import falcon # type: ignore import falcon.api_helpers # type: ignore from falcon import __version__ as FALCON_VERSION except ImportError: raise DidNotEnable("Falcon not installed") class FalconRequestExtractor(RequestExtractor): def env(self): # type: () -> Dict[str, Any] return self.request.env def cookies(self): # type: () -> Dict[str, Any] return self.request.cookies def form(self): # type: () -> None return None # No such concept in Falcon def files(self): # type: () -> None return None # No such concept in Falcon def raw_data(self): # type: () -> Optional[str] # As request data can only be read once we won't make this available # to Sentry. Just send back a dummy string in case there was a # content length. # TODO(jmagnusson): Figure out if there's a way to support this content_length = self.content_length() if content_length > 0: return "[REQUEST_CONTAINING_RAW_DATA]" else: return None def json(self): # type: () -> Optional[Dict[str, Any]] try: return self.request.media except falcon.errors.HTTPBadRequest: # NOTE(jmagnusson): We return `falcon.Request._media` here because # falcon 1.4 doesn't do proper type checking in # `falcon.Request.media`. This has been fixed in 2.0. # Relevant code: https://github.com/falconry/falcon/blob/1.4.1/falcon/request.py#L953 return self.request._media class SentryFalconMiddleware(object): """Captures exceptions in Falcon requests and send to Sentry""" def process_request(self, req, resp, *args, **kwargs): # type: (Any, Any, *Any, **Any) -> None hub = Hub.current integration = hub.get_integration(FalconIntegration) if integration is None: return with hub.configure_scope() as scope: scope._name = "falcon" scope.add_event_processor(_make_request_event_processor(req, integration)) TRANSACTION_STYLE_VALUES = ("uri_template", "path") class FalconIntegration(Integration): identifier = "falcon" transaction_style = "" def __init__(self, transaction_style="uri_template"): # type: (str) -> None if transaction_style not in TRANSACTION_STYLE_VALUES: raise ValueError( "Invalid value for transaction_style: %s (must be in %s)" % (transaction_style, TRANSACTION_STYLE_VALUES) ) self.transaction_style = transaction_style @staticmethod def setup_once(): # type: () -> None try: version = tuple(map(int, FALCON_VERSION.split("."))) except (ValueError, TypeError): raise DidNotEnable("Unparsable Falcon version: {}".format(FALCON_VERSION)) if version < (1, 4): raise DidNotEnable("Falcon 1.4 or newer required.") _patch_wsgi_app() _patch_handle_exception() _patch_prepare_middleware() def _patch_wsgi_app(): # type: () -> None original_wsgi_app = falcon.API.__call__ def sentry_patched_wsgi_app(self, env, start_response): # type: (falcon.API, Any, Any) -> Any hub = Hub.current integration = hub.get_integration(FalconIntegration) if integration is None: return original_wsgi_app(self, env, start_response) sentry_wrapped = SentryWsgiMiddleware( lambda envi, start_resp: original_wsgi_app(self, envi, start_resp) ) return sentry_wrapped(env, start_response) falcon.API.__call__ = sentry_patched_wsgi_app def _patch_handle_exception(): # type: () -> None original_handle_exception = falcon.API._handle_exception def sentry_patched_handle_exception(self, *args): # type: (falcon.API, *Any) -> Any # NOTE(jmagnusson): falcon 2.0 changed falcon.API._handle_exception # method signature from `(ex, req, resp, params)` to # `(req, resp, ex, params)` if isinstance(args[0], Exception): ex = args[0] else: ex = args[2] was_handled = original_handle_exception(self, *args) hub = Hub.current integration = hub.get_integration(FalconIntegration) if integration is not None and _exception_leads_to_http_5xx(ex): # If an integration is there, a client has to be there. client = hub.client # type: Any event, hint = event_from_exception( ex, client_options=client.options, mechanism={"type": "falcon", "handled": False}, ) hub.capture_event(event, hint=hint) return was_handled falcon.API._handle_exception = sentry_patched_handle_exception def _patch_prepare_middleware(): # type: () -> None original_prepare_middleware = falcon.api_helpers.prepare_middleware def sentry_patched_prepare_middleware( middleware=None, independent_middleware=False ): # type: (Any, Any) -> Any hub = Hub.current integration = hub.get_integration(FalconIntegration) if integration is not None: middleware = [SentryFalconMiddleware()] + (middleware or []) return original_prepare_middleware(middleware, independent_middleware) falcon.api_helpers.prepare_middleware = sentry_patched_prepare_middleware def _exception_leads_to_http_5xx(ex): # type: (Exception) -> bool is_server_error = isinstance(ex, falcon.HTTPError) and (ex.status or "").startswith( "5" ) is_unhandled_error = not isinstance( ex, (falcon.HTTPError, falcon.http_status.HTTPStatus) ) return is_server_error or is_unhandled_error def _set_transaction_name_and_source(event, transaction_style, request): # type: (Dict[str, Any], str, falcon.Request) -> None name_for_style = { "uri_template": request.uri_template, "path": request.path, } event["transaction"] = name_for_style[transaction_style] event["transaction_info"] = {"source": SOURCE_FOR_STYLE[transaction_style]} def _make_request_event_processor(req, integration): # type: (falcon.Request, FalconIntegration) -> EventProcessor def event_processor(event, hint): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] _set_transaction_name_and_source(event, integration.transaction_style, req) with capture_internal_exceptions(): FalconRequestExtractor(req).extract_into_event(event) return event return event_processor
7,322
Python
31.259912
97
0.630975
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/bottle.py
from __future__ import absolute_import from sentry_sdk.hub import Hub from sentry_sdk.tracing import SOURCE_FOR_STYLE from sentry_sdk.utils import ( capture_internal_exceptions, event_from_exception, transaction_from_function, ) from sentry_sdk.integrations import Integration, DidNotEnable from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware from sentry_sdk.integrations._wsgi_common import RequestExtractor from sentry_sdk._types import MYPY if MYPY: from sentry_sdk.integrations.wsgi import _ScopedResponse from typing import Any from typing import Dict from typing import Callable from typing import Optional from bottle import FileUpload, FormsDict, LocalRequest # type: ignore from sentry_sdk._types import EventProcessor, Event try: from bottle import ( Bottle, Route, request as bottle_request, HTTPResponse, __version__ as BOTTLE_VERSION, ) except ImportError: raise DidNotEnable("Bottle not installed") TRANSACTION_STYLE_VALUES = ("endpoint", "url") class BottleIntegration(Integration): identifier = "bottle" transaction_style = "" def __init__(self, transaction_style="endpoint"): # type: (str) -> None if transaction_style not in TRANSACTION_STYLE_VALUES: raise ValueError( "Invalid value for transaction_style: %s (must be in %s)" % (transaction_style, TRANSACTION_STYLE_VALUES) ) self.transaction_style = transaction_style @staticmethod def setup_once(): # type: () -> None try: version = tuple(map(int, BOTTLE_VERSION.replace("-dev", "").split("."))) except (TypeError, ValueError): raise DidNotEnable("Unparsable Bottle version: {}".format(version)) if version < (0, 12): raise DidNotEnable("Bottle 0.12 or newer required.") # monkey patch method Bottle.__call__ old_app = Bottle.__call__ def sentry_patched_wsgi_app(self, environ, start_response): # type: (Any, Dict[str, str], Callable[..., Any]) -> _ScopedResponse hub = Hub.current integration = hub.get_integration(BottleIntegration) if integration is None: return old_app(self, environ, start_response) return SentryWsgiMiddleware(lambda *a, **kw: old_app(self, *a, **kw))( environ, start_response ) Bottle.__call__ = sentry_patched_wsgi_app # monkey patch method Bottle._handle old_handle = Bottle._handle def _patched_handle(self, environ): # type: (Bottle, Dict[str, Any]) -> Any hub = Hub.current integration = hub.get_integration(BottleIntegration) if integration is None: return old_handle(self, environ) # create new scope scope_manager = hub.push_scope() with scope_manager: app = self with hub.configure_scope() as scope: scope._name = "bottle" scope.add_event_processor( _make_request_event_processor(app, bottle_request, integration) ) res = old_handle(self, environ) # scope cleanup return res Bottle._handle = _patched_handle # monkey patch method Route._make_callback old_make_callback = Route._make_callback def patched_make_callback(self, *args, **kwargs): # type: (Route, *object, **object) -> Any hub = Hub.current integration = hub.get_integration(BottleIntegration) prepared_callback = old_make_callback(self, *args, **kwargs) if integration is None: return prepared_callback # If an integration is there, a client has to be there. client = hub.client # type: Any def wrapped_callback(*args, **kwargs): # type: (*object, **object) -> Any try: res = prepared_callback(*args, **kwargs) except HTTPResponse: raise except Exception as exception: event, hint = event_from_exception( exception, client_options=client.options, mechanism={"type": "bottle", "handled": False}, ) hub.capture_event(event, hint=hint) raise exception return res return wrapped_callback Route._make_callback = patched_make_callback class BottleRequestExtractor(RequestExtractor): def env(self): # type: () -> Dict[str, str] return self.request.environ def cookies(self): # type: () -> Dict[str, str] return self.request.cookies def raw_data(self): # type: () -> bytes return self.request.body.read() def form(self): # type: () -> FormsDict if self.is_json(): return None return self.request.forms.decode() def files(self): # type: () -> Optional[Dict[str, str]] if self.is_json(): return None return self.request.files def size_of_file(self, file): # type: (FileUpload) -> int return file.content_length def _set_transaction_name_and_source(event, transaction_style, request): # type: (Event, str, Any) -> None name = "" if transaction_style == "url": name = request.route.rule or "" elif transaction_style == "endpoint": name = ( request.route.name or transaction_from_function(request.route.callback) or "" ) event["transaction"] = name event["transaction_info"] = {"source": SOURCE_FOR_STYLE[transaction_style]} def _make_request_event_processor(app, request, integration): # type: (Bottle, LocalRequest, BottleIntegration) -> EventProcessor def event_processor(event, hint): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] _set_transaction_name_and_source(event, integration.transaction_style, request) with capture_internal_exceptions(): BottleRequestExtractor(request).extract_into_event(event) return event return event_processor
6,488
Python
29.753554
87
0.582922
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/rq.py
from __future__ import absolute_import import weakref from sentry_sdk.consts import OP from sentry_sdk.hub import Hub from sentry_sdk.integrations import DidNotEnable, Integration from sentry_sdk.integrations.logging import ignore_logger from sentry_sdk.tracing import Transaction, TRANSACTION_SOURCE_TASK from sentry_sdk.utils import ( capture_internal_exceptions, event_from_exception, format_timestamp, ) try: from rq.queue import Queue from rq.timeouts import JobTimeoutException from rq.version import VERSION as RQ_VERSION from rq.worker import Worker except ImportError: raise DidNotEnable("RQ not installed") from sentry_sdk._types import MYPY if MYPY: from typing import Any, Callable, Dict from sentry_sdk._types import EventProcessor from sentry_sdk.utils import ExcInfo from rq.job import Job class RqIntegration(Integration): identifier = "rq" @staticmethod def setup_once(): # type: () -> None try: version = tuple(map(int, RQ_VERSION.split(".")[:3])) except (ValueError, TypeError): raise DidNotEnable("Unparsable RQ version: {}".format(RQ_VERSION)) if version < (0, 6): raise DidNotEnable("RQ 0.6 or newer is required.") old_perform_job = Worker.perform_job def sentry_patched_perform_job(self, job, *args, **kwargs): # type: (Any, Job, *Queue, **Any) -> bool hub = Hub.current integration = hub.get_integration(RqIntegration) if integration is None: return old_perform_job(self, job, *args, **kwargs) client = hub.client assert client is not None with hub.push_scope() as scope: scope.clear_breadcrumbs() scope.add_event_processor(_make_event_processor(weakref.ref(job))) transaction = Transaction.continue_from_headers( job.meta.get("_sentry_trace_headers") or {}, op=OP.QUEUE_TASK_RQ, name="unknown RQ task", source=TRANSACTION_SOURCE_TASK, ) with capture_internal_exceptions(): transaction.name = job.func_name with hub.start_transaction( transaction, custom_sampling_context={"rq_job": job} ): rv = old_perform_job(self, job, *args, **kwargs) if self.is_horse: # We're inside of a forked process and RQ is # about to call `os._exit`. Make sure that our # events get sent out. client.flush() return rv Worker.perform_job = sentry_patched_perform_job old_handle_exception = Worker.handle_exception def sentry_patched_handle_exception(self, job, *exc_info, **kwargs): # type: (Worker, Any, *Any, **Any) -> Any if job.is_failed: _capture_exception(exc_info) # type: ignore return old_handle_exception(self, job, *exc_info, **kwargs) Worker.handle_exception = sentry_patched_handle_exception old_enqueue_job = Queue.enqueue_job def sentry_patched_enqueue_job(self, job, **kwargs): # type: (Queue, Any, **Any) -> Any hub = Hub.current if hub.get_integration(RqIntegration) is not None: job.meta["_sentry_trace_headers"] = dict( hub.iter_trace_propagation_headers() ) return old_enqueue_job(self, job, **kwargs) Queue.enqueue_job = sentry_patched_enqueue_job ignore_logger("rq.worker") def _make_event_processor(weak_job): # type: (Callable[[], Job]) -> EventProcessor def event_processor(event, hint): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] job = weak_job() if job is not None: with capture_internal_exceptions(): extra = event.setdefault("extra", {}) extra["rq-job"] = { "job_id": job.id, "func": job.func_name, "args": job.args, "kwargs": job.kwargs, "description": job.description, } if job.enqueued_at: extra["rq-job"]["enqueued_at"] = format_timestamp(job.enqueued_at) if job.started_at: extra["rq-job"]["started_at"] = format_timestamp(job.started_at) if "exc_info" in hint: with capture_internal_exceptions(): if issubclass(hint["exc_info"][0], JobTimeoutException): event["fingerprint"] = ["rq", "JobTimeoutException", job.func_name] return event return event_processor def _capture_exception(exc_info, **kwargs): # type: (ExcInfo, **Any) -> None hub = Hub.current if hub.get_integration(RqIntegration) is None: return # If an integration is there, a client has to be there. client = hub.client # type: Any event, hint = event_from_exception( exc_info, client_options=client.options, mechanism={"type": "rq", "handled": False}, ) hub.capture_event(event, hint=hint)
5,350
Python
31.041916
87
0.571963
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/logging.py
from __future__ import absolute_import import logging import datetime from fnmatch import fnmatch from sentry_sdk.hub import Hub from sentry_sdk.utils import ( to_string, event_from_exception, current_stacktrace, capture_internal_exceptions, ) from sentry_sdk.integrations import Integration from sentry_sdk._compat import iteritems from sentry_sdk._types import MYPY if MYPY: from logging import LogRecord from typing import Any from typing import Dict from typing import Optional DEFAULT_LEVEL = logging.INFO DEFAULT_EVENT_LEVEL = logging.ERROR LOGGING_TO_EVENT_LEVEL = { logging.NOTSET: "notset", logging.DEBUG: "debug", logging.INFO: "info", logging.WARN: "warning", # WARN is same a WARNING logging.WARNING: "warning", logging.ERROR: "error", logging.FATAL: "fatal", logging.CRITICAL: "fatal", # CRITICAL is same as FATAL } # Capturing events from those loggers causes recursion errors. We cannot allow # the user to unconditionally create events from those loggers under any # circumstances. # # Note: Ignoring by logger name here is better than mucking with thread-locals. # We do not necessarily know whether thread-locals work 100% correctly in the user's environment. _IGNORED_LOGGERS = set( ["sentry_sdk.errors", "urllib3.connectionpool", "urllib3.connection"] ) def ignore_logger( name, # type: str ): # type: (...) -> None """This disables recording (both in breadcrumbs and as events) calls to a logger of a specific name. Among other uses, many of our integrations use this to prevent their actions being recorded as breadcrumbs. Exposed to users as a way to quiet spammy loggers. :param name: The name of the logger to ignore (same string you would pass to ``logging.getLogger``). """ _IGNORED_LOGGERS.add(name) class LoggingIntegration(Integration): identifier = "logging" def __init__(self, level=DEFAULT_LEVEL, event_level=DEFAULT_EVENT_LEVEL): # type: (Optional[int], Optional[int]) -> None self._handler = None self._breadcrumb_handler = None if level is not None: self._breadcrumb_handler = BreadcrumbHandler(level=level) if event_level is not None: self._handler = EventHandler(level=event_level) def _handle_record(self, record): # type: (LogRecord) -> None if self._handler is not None and record.levelno >= self._handler.level: self._handler.handle(record) if ( self._breadcrumb_handler is not None and record.levelno >= self._breadcrumb_handler.level ): self._breadcrumb_handler.handle(record) @staticmethod def setup_once(): # type: () -> None old_callhandlers = logging.Logger.callHandlers def sentry_patched_callhandlers(self, record): # type: (Any, LogRecord) -> Any try: return old_callhandlers(self, record) finally: # This check is done twice, once also here before we even get # the integration. Otherwise we have a high chance of getting # into a recursion error when the integration is resolved # (this also is slower). if record.name not in _IGNORED_LOGGERS: integration = Hub.current.get_integration(LoggingIntegration) if integration is not None: integration._handle_record(record) logging.Logger.callHandlers = sentry_patched_callhandlers # type: ignore def _can_record(record): # type: (LogRecord) -> bool """Prevents ignored loggers from recording""" for logger in _IGNORED_LOGGERS: if fnmatch(record.name, logger): return False return True def _breadcrumb_from_record(record): # type: (LogRecord) -> Dict[str, Any] return { "type": "log", "level": _logging_to_event_level(record), "category": record.name, "message": record.message, "timestamp": datetime.datetime.utcfromtimestamp(record.created), "data": _extra_from_record(record), } def _logging_to_event_level(record): # type: (LogRecord) -> str return LOGGING_TO_EVENT_LEVEL.get( record.levelno, record.levelname.lower() if record.levelname else "" ) COMMON_RECORD_ATTRS = frozenset( ( "args", "created", "exc_info", "exc_text", "filename", "funcName", "levelname", "levelno", "linenno", "lineno", "message", "module", "msecs", "msg", "name", "pathname", "process", "processName", "relativeCreated", "stack", "tags", "thread", "threadName", "stack_info", ) ) def _extra_from_record(record): # type: (LogRecord) -> Dict[str, None] return { k: v for k, v in iteritems(vars(record)) if k not in COMMON_RECORD_ATTRS and (not isinstance(k, str) or not k.startswith("_")) } class EventHandler(logging.Handler, object): """ A logging handler that emits Sentry events for each log record Note that you do not have to use this class if the logging integration is enabled, which it is by default. """ def emit(self, record): # type: (LogRecord) -> Any with capture_internal_exceptions(): self.format(record) return self._emit(record) def _emit(self, record): # type: (LogRecord) -> None if not _can_record(record): return hub = Hub.current if hub.client is None: return client_options = hub.client.options # exc_info might be None or (None, None, None) # # exc_info may also be any falsy value due to Python stdlib being # liberal with what it receives and Celery's billiard being "liberal" # with what it sends. See # https://github.com/getsentry/sentry-python/issues/904 if record.exc_info and record.exc_info[0] is not None: event, hint = event_from_exception( record.exc_info, client_options=client_options, mechanism={"type": "logging", "handled": True}, ) elif record.exc_info and record.exc_info[0] is None: event = {} hint = {} with capture_internal_exceptions(): event["threads"] = { "values": [ { "stacktrace": current_stacktrace( client_options["with_locals"] ), "crashed": False, "current": True, } ] } else: event = {} hint = {} hint["log_record"] = record event["level"] = _logging_to_event_level(record) event["logger"] = record.name # Log records from `warnings` module as separate issues record_caputured_from_warnings_module = ( record.name == "py.warnings" and record.msg == "%s" ) if record_caputured_from_warnings_module: # use the actual message and not "%s" as the message # this prevents grouping all warnings under one "%s" issue msg = record.args[0] # type: ignore event["logentry"] = { "message": msg, "params": (), } else: event["logentry"] = { "message": to_string(record.msg), "params": record.args, } event["extra"] = _extra_from_record(record) hub.capture_event(event, hint=hint) # Legacy name SentryHandler = EventHandler class BreadcrumbHandler(logging.Handler, object): """ A logging handler that records breadcrumbs for each log record. Note that you do not have to use this class if the logging integration is enabled, which it is by default. """ def emit(self, record): # type: (LogRecord) -> Any with capture_internal_exceptions(): self.format(record) return self._emit(record) def _emit(self, record): # type: (LogRecord) -> None if not _can_record(record): return Hub.current.add_breadcrumb( _breadcrumb_from_record(record), hint={"log_record": record} )
8,656
Python
29.059028
110
0.581331
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/beam.py
from __future__ import absolute_import import sys import types from sentry_sdk._functools import wraps from sentry_sdk.hub import Hub from sentry_sdk._compat import reraise from sentry_sdk.utils import capture_internal_exceptions, event_from_exception from sentry_sdk.integrations import Integration from sentry_sdk.integrations.logging import ignore_logger from sentry_sdk._types import MYPY if MYPY: from typing import Any from typing import Iterator from typing import TypeVar from typing import Optional from typing import Callable from sentry_sdk.client import Client from sentry_sdk._types import ExcInfo T = TypeVar("T") F = TypeVar("F", bound=Callable[..., Any]) WRAPPED_FUNC = "_wrapped_{}_" INSPECT_FUNC = "_inspect_{}" # Required format per apache_beam/transforms/core.py USED_FUNC = "_sentry_used_" class BeamIntegration(Integration): identifier = "beam" @staticmethod def setup_once(): # type: () -> None from apache_beam.transforms.core import DoFn, ParDo # type: ignore ignore_logger("root") ignore_logger("bundle_processor.create") function_patches = ["process", "start_bundle", "finish_bundle", "setup"] for func_name in function_patches: setattr( DoFn, INSPECT_FUNC.format(func_name), _wrap_inspect_call(DoFn, func_name), ) old_init = ParDo.__init__ def sentry_init_pardo(self, fn, *args, **kwargs): # type: (ParDo, Any, *Any, **Any) -> Any # Do not monkey patch init twice if not getattr(self, "_sentry_is_patched", False): for func_name in function_patches: if not hasattr(fn, func_name): continue wrapped_func = WRAPPED_FUNC.format(func_name) # Check to see if inspect is set and process is not # to avoid monkey patching process twice. # Check to see if function is part of object for # backwards compatibility. process_func = getattr(fn, func_name) inspect_func = getattr(fn, INSPECT_FUNC.format(func_name)) if not getattr(inspect_func, USED_FUNC, False) and not getattr( process_func, USED_FUNC, False ): setattr(fn, wrapped_func, process_func) setattr(fn, func_name, _wrap_task_call(process_func)) self._sentry_is_patched = True old_init(self, fn, *args, **kwargs) ParDo.__init__ = sentry_init_pardo def _wrap_inspect_call(cls, func_name): # type: (Any, Any) -> Any if not hasattr(cls, func_name): return None def _inspect(self): # type: (Any) -> Any """ Inspect function overrides the way Beam gets argspec. """ wrapped_func = WRAPPED_FUNC.format(func_name) if hasattr(self, wrapped_func): process_func = getattr(self, wrapped_func) else: process_func = getattr(self, func_name) setattr(self, func_name, _wrap_task_call(process_func)) setattr(self, wrapped_func, process_func) # getfullargspec is deprecated in more recent beam versions and get_function_args_defaults # (which uses Signatures internally) should be used instead. try: from apache_beam.transforms.core import get_function_args_defaults return get_function_args_defaults(process_func) except ImportError: from apache_beam.typehints.decorators import getfullargspec # type: ignore return getfullargspec(process_func) setattr(_inspect, USED_FUNC, True) return _inspect def _wrap_task_call(func): # type: (F) -> F """ Wrap task call with a try catch to get exceptions. Pass the client on to raise_exception so it can get rebinded. """ client = Hub.current.client @wraps(func) def _inner(*args, **kwargs): # type: (*Any, **Any) -> Any try: gen = func(*args, **kwargs) except Exception: raise_exception(client) if not isinstance(gen, types.GeneratorType): return gen return _wrap_generator_call(gen, client) setattr(_inner, USED_FUNC, True) return _inner # type: ignore def _capture_exception(exc_info, hub): # type: (ExcInfo, Hub) -> None """ Send Beam exception to Sentry. """ integration = hub.get_integration(BeamIntegration) if integration is None: return client = hub.client if client is None: return event, hint = event_from_exception( exc_info, client_options=client.options, mechanism={"type": "beam", "handled": False}, ) hub.capture_event(event, hint=hint) def raise_exception(client): # type: (Optional[Client]) -> None """ Raise an exception. If the client is not in the hub, rebind it. """ hub = Hub.current if hub.client is None: hub.bind_client(client) exc_info = sys.exc_info() with capture_internal_exceptions(): _capture_exception(exc_info, hub) reraise(*exc_info) def _wrap_generator_call(gen, client): # type: (Iterator[T], Optional[Client]) -> Iterator[T] """ Wrap the generator to handle any failures. """ while True: try: yield next(gen) except StopIteration: break except Exception: raise_exception(client)
5,671
Python
29.494623
98
0.596015
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/_wsgi_common.py
import json from sentry_sdk.hub import Hub, _should_send_default_pii from sentry_sdk.utils import AnnotatedValue from sentry_sdk._compat import text_type, iteritems from sentry_sdk._types import MYPY if MYPY: import sentry_sdk from typing import Any from typing import Dict from typing import Optional from typing import Union SENSITIVE_ENV_KEYS = ( "REMOTE_ADDR", "HTTP_X_FORWARDED_FOR", "HTTP_SET_COOKIE", "HTTP_COOKIE", "HTTP_AUTHORIZATION", "HTTP_X_API_KEY", "HTTP_X_FORWARDED_FOR", "HTTP_X_REAL_IP", ) SENSITIVE_HEADERS = tuple( x[len("HTTP_") :] for x in SENSITIVE_ENV_KEYS if x.startswith("HTTP_") ) def request_body_within_bounds(client, content_length): # type: (Optional[sentry_sdk.Client], int) -> bool if client is None: return False bodies = client.options["request_bodies"] return not ( bodies == "never" or (bodies == "small" and content_length > 10**3) or (bodies == "medium" and content_length > 10**4) ) class RequestExtractor(object): def __init__(self, request): # type: (Any) -> None self.request = request def extract_into_event(self, event): # type: (Dict[str, Any]) -> None client = Hub.current.client if client is None: return data = None # type: Optional[Union[AnnotatedValue, Dict[str, Any]]] content_length = self.content_length() request_info = event.get("request", {}) if _should_send_default_pii(): request_info["cookies"] = dict(self.cookies()) if not request_body_within_bounds(client, content_length): data = AnnotatedValue.removed_because_over_size_limit() else: parsed_body = self.parsed_body() if parsed_body is not None: data = parsed_body elif self.raw_data(): data = AnnotatedValue.removed_because_raw_data() else: data = None if data is not None: request_info["data"] = data event["request"] = request_info def content_length(self): # type: () -> int try: return int(self.env().get("CONTENT_LENGTH", 0)) except ValueError: return 0 def cookies(self): # type: () -> Dict[str, Any] raise NotImplementedError() def raw_data(self): # type: () -> Optional[Union[str, bytes]] raise NotImplementedError() def form(self): # type: () -> Optional[Dict[str, Any]] raise NotImplementedError() def parsed_body(self): # type: () -> Optional[Dict[str, Any]] form = self.form() files = self.files() if form or files: data = dict(iteritems(form)) for key, _ in iteritems(files): data[key] = AnnotatedValue.removed_because_raw_data() return data return self.json() def is_json(self): # type: () -> bool return _is_json_content_type(self.env().get("CONTENT_TYPE")) def json(self): # type: () -> Optional[Any] try: if not self.is_json(): return None raw_data = self.raw_data() if raw_data is None: return None if isinstance(raw_data, text_type): return json.loads(raw_data) else: return json.loads(raw_data.decode("utf-8")) except ValueError: pass return None def files(self): # type: () -> Optional[Dict[str, Any]] raise NotImplementedError() def size_of_file(self, file): # type: (Any) -> int raise NotImplementedError() def env(self): # type: () -> Dict[str, Any] raise NotImplementedError() def _is_json_content_type(ct): # type: (Optional[str]) -> bool mt = (ct or "").split(";", 1)[0] return ( mt == "application/json" or (mt.startswith("application/")) and mt.endswith("+json") ) def _filter_headers(headers): # type: (Dict[str, str]) -> Dict[str, str] if _should_send_default_pii(): return headers return { k: ( v if k.upper().replace("-", "_") not in SENSITIVE_HEADERS else AnnotatedValue.removed_because_over_size_limit() ) for k, v in iteritems(headers) }
4,476
Python
24.878613
76
0.552949
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/sanic.py
import sys import weakref from inspect import isawaitable from sentry_sdk._compat import urlparse, reraise from sentry_sdk.hub import Hub from sentry_sdk.tracing import TRANSACTION_SOURCE_COMPONENT from sentry_sdk.utils import ( capture_internal_exceptions, event_from_exception, HAS_REAL_CONTEXTVARS, CONTEXTVARS_ERROR_MESSAGE, ) from sentry_sdk.integrations import Integration, DidNotEnable from sentry_sdk.integrations._wsgi_common import RequestExtractor, _filter_headers from sentry_sdk.integrations.logging import ignore_logger from sentry_sdk._types import MYPY if MYPY: from typing import Any from typing import Callable from typing import Optional from typing import Union from typing import Tuple from typing import Dict from sanic.request import Request, RequestParameters from sentry_sdk._types import Event, EventProcessor, Hint from sanic.router import Route try: from sanic import Sanic, __version__ as SANIC_VERSION from sanic.exceptions import SanicException from sanic.router import Router from sanic.handlers import ErrorHandler except ImportError: raise DidNotEnable("Sanic not installed") old_error_handler_lookup = ErrorHandler.lookup old_handle_request = Sanic.handle_request old_router_get = Router.get try: # This method was introduced in Sanic v21.9 old_startup = Sanic._startup except AttributeError: pass class SanicIntegration(Integration): identifier = "sanic" version = (0, 0) # type: Tuple[int, ...] @staticmethod def setup_once(): # type: () -> None try: SanicIntegration.version = tuple(map(int, SANIC_VERSION.split("."))) except (TypeError, ValueError): raise DidNotEnable("Unparsable Sanic version: {}".format(SANIC_VERSION)) if SanicIntegration.version < (0, 8): raise DidNotEnable("Sanic 0.8 or newer required.") if not HAS_REAL_CONTEXTVARS: # We better have contextvars or we're going to leak state between # requests. raise DidNotEnable( "The sanic integration for Sentry requires Python 3.7+ " " or the aiocontextvars package." + CONTEXTVARS_ERROR_MESSAGE ) if SANIC_VERSION.startswith("0.8."): # Sanic 0.8 and older creates a logger named "root" and puts a # stringified version of every exception in there (without exc_info), # which our error deduplication can't detect. # # We explicitly check the version here because it is a very # invasive step to ignore this logger and not necessary in newer # versions at all. # # https://github.com/huge-success/sanic/issues/1332 ignore_logger("root") if SanicIntegration.version < (21, 9): _setup_legacy_sanic() return _setup_sanic() class SanicRequestExtractor(RequestExtractor): def content_length(self): # type: () -> int if self.request.body is None: return 0 return len(self.request.body) def cookies(self): # type: () -> Dict[str, str] return dict(self.request.cookies) def raw_data(self): # type: () -> bytes return self.request.body def form(self): # type: () -> RequestParameters return self.request.form def is_json(self): # type: () -> bool raise NotImplementedError() def json(self): # type: () -> Optional[Any] return self.request.json def files(self): # type: () -> RequestParameters return self.request.files def size_of_file(self, file): # type: (Any) -> int return len(file.body or ()) def _setup_sanic(): # type: () -> None Sanic._startup = _startup ErrorHandler.lookup = _sentry_error_handler_lookup def _setup_legacy_sanic(): # type: () -> None Sanic.handle_request = _legacy_handle_request Router.get = _legacy_router_get ErrorHandler.lookup = _sentry_error_handler_lookup async def _startup(self): # type: (Sanic) -> None # This happens about as early in the lifecycle as possible, just after the # Request object is created. The body has not yet been consumed. self.signal("http.lifecycle.request")(_hub_enter) # This happens after the handler is complete. In v21.9 this signal is not # dispatched when there is an exception. Therefore we need to close out # and call _hub_exit from the custom exception handler as well. # See https://github.com/sanic-org/sanic/issues/2297 self.signal("http.lifecycle.response")(_hub_exit) # This happens inside of request handling immediately after the route # has been identified by the router. self.signal("http.routing.after")(_set_transaction) # The above signals need to be declared before this can be called. await old_startup(self) async def _hub_enter(request): # type: (Request) -> None hub = Hub.current request.ctx._sentry_do_integration = ( hub.get_integration(SanicIntegration) is not None ) if not request.ctx._sentry_do_integration: return weak_request = weakref.ref(request) request.ctx._sentry_hub = Hub(hub) request.ctx._sentry_hub.__enter__() with request.ctx._sentry_hub.configure_scope() as scope: scope.clear_breadcrumbs() scope.add_event_processor(_make_request_processor(weak_request)) async def _hub_exit(request, **_): # type: (Request, **Any) -> None request.ctx._sentry_hub.__exit__(None, None, None) async def _set_transaction(request, route, **kwargs): # type: (Request, Route, **Any) -> None hub = Hub.current if hub.get_integration(SanicIntegration) is not None: with capture_internal_exceptions(): with hub.configure_scope() as scope: route_name = route.name.replace(request.app.name, "").strip(".") scope.set_transaction_name( route_name, source=TRANSACTION_SOURCE_COMPONENT ) def _sentry_error_handler_lookup(self, exception, *args, **kwargs): # type: (Any, Exception, *Any, **Any) -> Optional[object] _capture_exception(exception) old_error_handler = old_error_handler_lookup(self, exception, *args, **kwargs) if old_error_handler is None: return None if Hub.current.get_integration(SanicIntegration) is None: return old_error_handler async def sentry_wrapped_error_handler(request, exception): # type: (Request, Exception) -> Any try: response = old_error_handler(request, exception) if isawaitable(response): response = await response return response except Exception: # Report errors that occur in Sanic error handler. These # exceptions will not even show up in Sanic's # `sanic.exceptions` logger. exc_info = sys.exc_info() _capture_exception(exc_info) reraise(*exc_info) finally: # As mentioned in previous comment in _startup, this can be removed # after https://github.com/sanic-org/sanic/issues/2297 is resolved if SanicIntegration.version == (21, 9): await _hub_exit(request) return sentry_wrapped_error_handler async def _legacy_handle_request(self, request, *args, **kwargs): # type: (Any, Request, *Any, **Any) -> Any hub = Hub.current if hub.get_integration(SanicIntegration) is None: return old_handle_request(self, request, *args, **kwargs) weak_request = weakref.ref(request) with Hub(hub) as hub: with hub.configure_scope() as scope: scope.clear_breadcrumbs() scope.add_event_processor(_make_request_processor(weak_request)) response = old_handle_request(self, request, *args, **kwargs) if isawaitable(response): response = await response return response def _legacy_router_get(self, *args): # type: (Any, Union[Any, Request]) -> Any rv = old_router_get(self, *args) hub = Hub.current if hub.get_integration(SanicIntegration) is not None: with capture_internal_exceptions(): with hub.configure_scope() as scope: if SanicIntegration.version and SanicIntegration.version >= (21, 3): # Sanic versions above and including 21.3 append the app name to the # route name, and so we need to remove it from Route name so the # transaction name is consistent across all versions sanic_app_name = self.ctx.app.name sanic_route = rv[0].name if sanic_route.startswith("%s." % sanic_app_name): # We add a 1 to the len of the sanic_app_name because there is a dot # that joins app name and the route name # Format: app_name.route_name sanic_route = sanic_route[len(sanic_app_name) + 1 :] scope.set_transaction_name( sanic_route, source=TRANSACTION_SOURCE_COMPONENT ) else: scope.set_transaction_name( rv[0].__name__, source=TRANSACTION_SOURCE_COMPONENT ) return rv def _capture_exception(exception): # type: (Union[Tuple[Optional[type], Optional[BaseException], Any], BaseException]) -> None hub = Hub.current integration = hub.get_integration(SanicIntegration) if integration is None: return # If an integration is there, a client has to be there. client = hub.client # type: Any with capture_internal_exceptions(): event, hint = event_from_exception( exception, client_options=client.options, mechanism={"type": "sanic", "handled": False}, ) hub.capture_event(event, hint=hint) def _make_request_processor(weak_request): # type: (Callable[[], Request]) -> EventProcessor def sanic_processor(event, hint): # type: (Event, Optional[Hint]) -> Optional[Event] try: if hint and issubclass(hint["exc_info"][0], SanicException): return None except KeyError: pass request = weak_request() if request is None: return event with capture_internal_exceptions(): extractor = SanicRequestExtractor(request) extractor.extract_into_event(event) request_info = event["request"] urlparts = urlparse.urlsplit(request.url) request_info["url"] = "%s://%s%s" % ( urlparts.scheme, urlparts.netloc, urlparts.path, ) request_info["query_string"] = urlparts.query request_info["method"] = request.method request_info["env"] = {"REMOTE_ADDR": request.remote_addr} request_info["headers"] = _filter_headers(dict(request.headers)) return event return sanic_processor
11,311
Python
32.270588
95
0.618867
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/opentelemetry/__init__.py
from sentry_sdk.integrations.opentelemetry.span_processor import ( # noqa: F401 SentrySpanProcessor, ) from sentry_sdk.integrations.opentelemetry.propagator import ( # noqa: F401 SentryPropagator, )
210
Python
25.374997
80
0.771429
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/opentelemetry/propagator.py
from opentelemetry import trace # type: ignore from opentelemetry.context import ( # type: ignore Context, get_current, set_value, ) from opentelemetry.propagators.textmap import ( # type: ignore CarrierT, Getter, Setter, TextMapPropagator, default_getter, default_setter, ) from opentelemetry.trace import ( # type: ignore TraceFlags, NonRecordingSpan, SpanContext, ) from sentry_sdk.integrations.opentelemetry.consts import ( SENTRY_BAGGAGE_KEY, SENTRY_TRACE_KEY, ) from sentry_sdk.integrations.opentelemetry.span_processor import ( SentrySpanProcessor, ) from sentry_sdk.tracing import ( BAGGAGE_HEADER_NAME, SENTRY_TRACE_HEADER_NAME, ) from sentry_sdk.tracing_utils import Baggage, extract_sentrytrace_data from sentry_sdk._types import MYPY if MYPY: from typing import Optional from typing import Set class SentryPropagator(TextMapPropagator): # type: ignore """ Propagates tracing headers for Sentry's tracing system in a way OTel understands. """ def extract(self, carrier, context=None, getter=default_getter): # type: (CarrierT, Optional[Context], Getter) -> Context if context is None: context = get_current() sentry_trace = getter.get(carrier, SENTRY_TRACE_HEADER_NAME) if not sentry_trace: return context sentrytrace = extract_sentrytrace_data(sentry_trace[0]) if not sentrytrace: return context context = set_value(SENTRY_TRACE_KEY, sentrytrace, context) trace_id, span_id = sentrytrace["trace_id"], sentrytrace["parent_span_id"] span_context = SpanContext( trace_id=int(trace_id, 16), # type: ignore span_id=int(span_id, 16), # type: ignore # we simulate a sampled trace on the otel side and leave the sampling to sentry trace_flags=TraceFlags(TraceFlags.SAMPLED), is_remote=True, ) baggage_header = getter.get(carrier, BAGGAGE_HEADER_NAME) if baggage_header: baggage = Baggage.from_incoming_header(baggage_header[0]) else: # If there's an incoming sentry-trace but no incoming baggage header, # for instance in traces coming from older SDKs, # baggage will be empty and frozen and won't be populated as head SDK. baggage = Baggage(sentry_items={}) baggage.freeze() context = set_value(SENTRY_BAGGAGE_KEY, baggage, context) span = NonRecordingSpan(span_context) modified_context = trace.set_span_in_context(span, context) return modified_context def inject(self, carrier, context=None, setter=default_setter): # type: (CarrierT, Optional[Context], Setter) -> None if context is None: context = get_current() current_span = trace.get_current_span(context) if not current_span.context.is_valid: return span_id = trace.format_span_id(current_span.context.span_id) span_map = SentrySpanProcessor().otel_span_map sentry_span = span_map.get(span_id, None) if not sentry_span: return setter.set(carrier, SENTRY_TRACE_HEADER_NAME, sentry_span.to_traceparent()) baggage = sentry_span.containing_transaction.get_baggage() if baggage: setter.set(carrier, BAGGAGE_HEADER_NAME, baggage.serialize()) @property def fields(self): # type: () -> Set[str] return {SENTRY_TRACE_HEADER_NAME, BAGGAGE_HEADER_NAME}
3,591
Python
30.508772
91
0.651072
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/opentelemetry/consts.py
from opentelemetry.context import ( # type: ignore create_key, ) SENTRY_TRACE_KEY = create_key("sentry-trace") SENTRY_BAGGAGE_KEY = create_key("sentry-baggage")
167
Python
22.999997
51
0.724551
omniverse-code/kit/exts/omni.kit.pip_archive/pip_prebundle/sentry_sdk/integrations/opentelemetry/span_processor.py
from datetime import datetime from opentelemetry.context import get_value # type: ignore from opentelemetry.sdk.trace import SpanProcessor # type: ignore from opentelemetry.semconv.trace import SpanAttributes # type: ignore from opentelemetry.trace import ( # type: ignore format_span_id, format_trace_id, get_current_span, SpanContext, Span as OTelSpan, SpanKind, ) from opentelemetry.trace.span import ( # type: ignore INVALID_SPAN_ID, INVALID_TRACE_ID, ) from sentry_sdk.consts import INSTRUMENTER from sentry_sdk.hub import Hub from sentry_sdk.integrations.opentelemetry.consts import ( SENTRY_BAGGAGE_KEY, SENTRY_TRACE_KEY, ) from sentry_sdk.scope import add_global_event_processor from sentry_sdk.tracing import Transaction, Span as SentrySpan from sentry_sdk.utils import Dsn from sentry_sdk._types import MYPY from urllib3.util import parse_url as urlparse # type: ignore if MYPY: from typing import Any from typing import Dict from typing import Union from sentry_sdk._types import Event, Hint OPEN_TELEMETRY_CONTEXT = "otel" def link_trace_context_to_error_event(event, otel_span_map): # type: (Event, Dict[str, Union[Transaction, OTelSpan]]) -> Event hub = Hub.current if not hub: return event if hub.client and hub.client.options["instrumenter"] != INSTRUMENTER.OTEL: return event if hasattr(event, "type") and event["type"] == "transaction": return event otel_span = get_current_span() if not otel_span: return event ctx = otel_span.get_span_context() trace_id = format_trace_id(ctx.trace_id) span_id = format_span_id(ctx.span_id) if trace_id == INVALID_TRACE_ID or span_id == INVALID_SPAN_ID: return event sentry_span = otel_span_map.get(span_id, None) if not sentry_span: return event contexts = event.setdefault("contexts", {}) contexts.setdefault("trace", {}).update(sentry_span.get_trace_context()) return event class SentrySpanProcessor(SpanProcessor): # type: ignore """ Converts OTel spans into Sentry spans so they can be sent to the Sentry backend. """ # The mapping from otel span ids to sentry spans otel_span_map = {} # type: Dict[str, Union[Transaction, OTelSpan]] def __new__(cls): # type: () -> SentrySpanProcessor if not hasattr(cls, "instance"): cls.instance = super(SentrySpanProcessor, cls).__new__(cls) return cls.instance def __init__(self): # type: () -> None @add_global_event_processor def global_event_processor(event, hint): # type: (Event, Hint) -> Event return link_trace_context_to_error_event(event, self.otel_span_map) def on_start(self, otel_span, parent_context=None): # type: (OTelSpan, SpanContext) -> None hub = Hub.current if not hub: return if not hub.client or (hub.client and not hub.client.dsn): return try: _ = Dsn(hub.client.dsn or "") except Exception: return if hub.client and hub.client.options["instrumenter"] != INSTRUMENTER.OTEL: return if not otel_span.context.is_valid: return if self._is_sentry_span(hub, otel_span): return trace_data = self._get_trace_data(otel_span, parent_context) parent_span_id = trace_data["parent_span_id"] sentry_parent_span = ( self.otel_span_map.get(parent_span_id, None) if parent_span_id else None ) sentry_span = None if sentry_parent_span: sentry_span = sentry_parent_span.start_child( span_id=trace_data["span_id"], description=otel_span.name, start_timestamp=datetime.fromtimestamp(otel_span.start_time / 1e9), instrumenter=INSTRUMENTER.OTEL, ) else: sentry_span = hub.start_transaction( name=otel_span.name, span_id=trace_data["span_id"], parent_span_id=parent_span_id, trace_id=trace_data["trace_id"], baggage=trace_data["baggage"], start_timestamp=datetime.fromtimestamp(otel_span.start_time / 1e9), instrumenter=INSTRUMENTER.OTEL, ) self.otel_span_map[trace_data["span_id"]] = sentry_span def on_end(self, otel_span): # type: (OTelSpan) -> None hub = Hub.current if not hub: return if hub.client and hub.client.options["instrumenter"] != INSTRUMENTER.OTEL: return if not otel_span.context.is_valid: return span_id = format_span_id(otel_span.context.span_id) sentry_span = self.otel_span_map.pop(span_id, None) if not sentry_span: return sentry_span.op = otel_span.name if isinstance(sentry_span, Transaction): sentry_span.name = otel_span.name sentry_span.set_context( OPEN_TELEMETRY_CONTEXT, self._get_otel_context(otel_span) ) else: self._update_span_with_otel_data(sentry_span, otel_span) sentry_span.finish( end_timestamp=datetime.fromtimestamp(otel_span.end_time / 1e9) ) def _is_sentry_span(self, hub, otel_span): # type: (Hub, OTelSpan) -> bool """ Break infinite loop: HTTP requests to Sentry are caught by OTel and send again to Sentry. """ otel_span_url = otel_span.attributes.get(SpanAttributes.HTTP_URL, None) dsn_url = hub.client and Dsn(hub.client.dsn or "").netloc if otel_span_url and dsn_url in otel_span_url: return True return False def _get_otel_context(self, otel_span): # type: (OTelSpan) -> Dict[str, Any] """ Returns the OTel context for Sentry. See: https://develop.sentry.dev/sdk/performance/opentelemetry/#step-5-add-opentelemetry-context """ ctx = {} if otel_span.attributes: ctx["attributes"] = dict(otel_span.attributes) if otel_span.resource.attributes: ctx["resource"] = dict(otel_span.resource.attributes) return ctx def _get_trace_data(self, otel_span, parent_context): # type: (OTelSpan, SpanContext) -> Dict[str, Any] """ Extracts tracing information from one OTel span and its parent OTel context. """ trace_data = {} span_id = format_span_id(otel_span.context.span_id) trace_data["span_id"] = span_id trace_id = format_trace_id(otel_span.context.trace_id) trace_data["trace_id"] = trace_id parent_span_id = ( format_span_id(otel_span.parent.span_id) if otel_span.parent else None ) trace_data["parent_span_id"] = parent_span_id sentry_trace_data = get_value(SENTRY_TRACE_KEY, parent_context) trace_data["parent_sampled"] = ( sentry_trace_data["parent_sampled"] if sentry_trace_data else None ) baggage = get_value(SENTRY_BAGGAGE_KEY, parent_context) trace_data["baggage"] = baggage return trace_data def _update_span_with_otel_data(self, sentry_span, otel_span): # type: (SentrySpan, OTelSpan) -> None """ Convert OTel span data and update the Sentry span with it. This should eventually happen on the server when ingesting the spans. """ for key, val in otel_span.attributes.items(): sentry_span.set_data(key, val) sentry_span.set_data("otel.kind", otel_span.kind) op = otel_span.name description = otel_span.name http_method = otel_span.attributes.get(SpanAttributes.HTTP_METHOD, None) db_query = otel_span.attributes.get(SpanAttributes.DB_SYSTEM, None) if http_method: op = "http" if otel_span.kind == SpanKind.SERVER: op += ".server" elif otel_span.kind == SpanKind.CLIENT: op += ".client" description = http_method peer_name = otel_span.attributes.get(SpanAttributes.NET_PEER_NAME, None) if peer_name: description += " {}".format(peer_name) target = otel_span.attributes.get(SpanAttributes.HTTP_TARGET, None) if target: description += " {}".format(target) if not peer_name and not target: url = otel_span.attributes.get(SpanAttributes.HTTP_URL, None) if url: parsed_url = urlparse(url) url = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}" description += " {}".format(url) status_code = otel_span.attributes.get( SpanAttributes.HTTP_STATUS_CODE, None ) if status_code: sentry_span.set_http_status(status_code) elif db_query: op = "db" statement = otel_span.attributes.get(SpanAttributes.DB_STATEMENT, None) if statement: description = statement sentry_span.op = op sentry_span.description = description
9,388
Python
31.154109
103
0.597784