Пример #1
0
try:
    from typing import TypedDict
except ImportError:
    from typing_extensions import TypedDict

configuration = TypedDict("configuration", {
    "running": str,
    "candidate": str,
    "startup": str
})

alive = TypedDict("alive", {"is_alive": bool})

facts = TypedDict(
    "facts",
    {
        "os_version": str,
        "uptime": int,
        "interface_list": list,
        "vendor": str,
        "serial_number": str,
        "model": str,
        "hostname": str,
        "fqdn": str,
    },
)

interface = TypedDict(
    "interface",
    {
        "is_up": bool,
Пример #2
0
    memory_limit_in_mb: str
    aws_request_id: str
    log_group_name: str
    log_stream_name: str
    identity: _Identity
    client_context: _ClientContext


# Can't use class syntax, bc `cognito:username` is an invalid name
_Claims = TypedDict('_Claims', {
    'aud': str,
    'auth_time': str,
    'cognito:username': str,
    'email': str,
    'email_verified': str,
    'event_id': str,
    'exp': str,
    'iat': str,
    'iss': str,
    'sub': str,
    'token_use': str
})


class _Authorizer(TypedDict, total=False):
    # Included if authorization type is COGNITO_USER_POOLS
    claims: _Claims
    # Included if authorization type is CUSTOM
    principalId: str

Пример #3
0
from cmk.gui.plugins.openapi.restful_objects.parameters import (
    ACCEPT_HEADER, )

from cmk.gui.plugins.openapi.restful_objects.params import to_openapi
from cmk.gui.plugins.openapi.restful_objects.type_defs import OpenAPIParameter

DEFAULT_HEADERS = [
    ('Accept', 'Media type(s) that is/are acceptable for the response.',
     'application/json'),
]

OpenAPIInfoDict = TypedDict(
    'OpenAPIInfoDict',
    {
        'description': str,
        'license': Dict[str, str],
        'contact': Dict[str, str],
    },
    total=True,
)

TagGroup = TypedDict(
    'TagGroup',
    {
        'name': str,
        'tags': List[str],
    },
    total=True,
)

ReDocSpec = TypedDict(
Пример #4
0
    help=
    "Only use conferences that match this string (default: all conferences)")

args, left = parser.parse_known_args()

# Consider pubs in this range only.
startyear = 1970
endyear = 2269

LogType = TypedDict(
    'LogType', {
        'name': bytes,
        'year': int,
        'title': bytes,
        'conf': str,
        'area': str,
        'institution': str,
        'numauthors': int,
        'volume': str,
        'number': str,
        'startPage': int,
        'pageCount': int
    })

ArticleType = TypedDict(
    'ArticleType', {
        'author': List[str],
        'booktitle': str,
        'journal': str,
        'volume': str,
        'number': str,
        'url': str,
Пример #5
0
from typing import Protocol, TypedDict, Generator, Iterable, Any

Rotation = TypedDict('Rotation', {
    'x': float,
    'y': float,
    'z': float,
    'w': float
})

Translation = TypedDict('Translation', {'x': float, 'y': float, 'z': float})

Pose = TypedDict('Pose', {'translation': Translation, 'rotation': Rotation})

ColorImage = TypedDict('ColorImage', {
    'width': int,
    'height': int,
    'data': bytes
})

DepthImage = TypedDict('DepthImage', {
    'width': int,
    'height': int,
    'data': Iterable[float]
})

User = TypedDict('User', {
    'user_id': int,
    'username': str,
    'birthday': int,
    'gender': int
})
Пример #6
0
from ..agent_based_api.v1.type_defs import (
    CheckResult, )

StatusType = int
TempUnitType = str
LevelModes = str

TwoLevelsType = Tuple[Optional[float], Optional[float]]
FourLevelsType = Tuple[Optional[float], Optional[float], Optional[float],
                       Optional[float]]
LevelsType = Union[TwoLevelsType, FourLevelsType]
TrendComputeDict = TypedDict(
    'TrendComputeDict',
    {
        'period': int,
        'trend_levels': TwoLevelsType,
        'trend_levels_lower': TwoLevelsType,
        'trend_timeleft': TwoLevelsType,
    },
    total=False,
)
TempParamDict = TypedDict(
    'TempParamDict',
    {
        'input_unit': TempUnitType,
        'output_unit': TempUnitType,
        'levels': TwoLevelsType,
        'levels_lower': TwoLevelsType,
        'device_levels_handling': LevelModes,
        'trend_compute': TrendComputeDict,
    },
    total=False,
from typing import TypedDict, List, Tuple, Any

response = {
    "body": {
        "message": "success",
        "status_code": 200
    },
    "has_error": False
}
user = {
    "username": "******",
    "age": 100,
}


def get_type_def():
    return [response, user]


# TYPE DEF HERE
TypeBody = TypedDict("TypeBody", {"message": str, "status_code": int})
TypeResponse = TypedDict("TypeResponse", {"body": TypeBody, "has_error": bool})
TypeUser = TypedDict("TypeUser", {"username": str, "age": int})
Пример #8
0
    value = auto()
    label = auto()
    text = label
    index = auto()


class SupportedBrowsers(Enum):
    chromium = "chromium"
    firefox = "firefox"
    webkit = "webkit"


ColorScheme = Enum("ColorScheme", ["dark", "light", "no-preference"])

ViewportDimensions = TypedDict("ViewportDimensions", {
    "width": int,
    "height": int
})


class ElementState(Enum):
    attached = auto()
    detached = auto()
    visible = auto()
    hidden = auto()


AssertionOperator = Enum(
    "AssertionOperator",
    {
        "equal": "==",
        "==": "==",
Пример #9
0
        self.server = server
        self.server_config = server_config
        self.config = config_dict

    @abstractmethod
    def authorize(self, client_address: tuple[str, int],
                  client_request: HTTPParser) -> Optional[HTTPResponse]:
        # True: OK, go on serving
        # False: NOK, 403
        # None: I don't know, move on to next auth handler
        # return None
        ...


_BasicAuthConfig = TypedDict("_BasicAuthConfig", {
    "user": Optional[str],
    "password": Optional[str]
})


class AbstractBasicAuthorization(AbstractAuthorization, ABC):
    """
    HTTP Basic authorization scheme support (RFC 2617)
    """

    USER_ITEM: str
    PASSWORD_ITEM: str

    def __init__(self, server: "TCPServer", server_config: dict[str, Any],
                 **config_dict: Any):
        super().__init__(server, server_config, **config_dict)
        self.global_user = config_dict.get(self.USER_ITEM)
Пример #10
0
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
"""
Declarations used for type checking our code (e.g. manipulation of JSON documents returned by RethinkDB).
"""
import datetime as dt
from typing import Any, List, Literal, Mapping, Tuple, TypedDict

# Check interfaces.

Instance = TypedDict(
    'Instance',
    {
        'host': str,
        'port': int,
        'username': str,
        'password': str,
        'tls_ca_cert': str,
        'tags': List[str]
    },
    total=False,
)

# Configuration documents.
# See: https://rethinkdb.com/docs/system-tables/#configuration-tables

Server = TypedDict('Server', {
    'id': str,
    'name': str,
    'cache_size_mb': str,
    'tags': List[str]
})
Пример #11
0
import csv
import json
import requests
from typing import List, Dict, TypedDict, Union
from dataclasses import dataclass
from pathlib import Path

import pytz
import yaml

Api = TypedDict('Api', {'Key': str})


@dataclass
class Settings:
    API: Api


settings_yaml = Path(__file__).parent / 'settings.yaml'
with open(settings_yaml, 'r') as f:
    settings: Settings = yaml.safe_load(f)
city = {
    'id': 1849584,
    'name': 'Tsurugi-asahimachi',
    'coord': {
        'lat': 36.45,
        'lon': 136.6333
    },
    'country': 'JP',
    'population': 0,
    'timezone': 32400,
Пример #12
0
from collections.abc import Iterable, Mapping
from collections import UserString
from io import IOBase
from os import PathLike
try:
    from types import UnionType
except ImportError:  # Python < 3.10
    UnionType = ()
from typing import Union
try:
    from typing import TypedDict
except ImportError:  # Python < 3.8
    typeddict_types = ()
else:
    typeddict_types = (type(TypedDict('Dummy', {})), )
try:
    from typing_extensions import TypedDict as ExtTypedDict
except ImportError:
    pass
else:
    typeddict_types += (type(ExtTypedDict('Dummy', {})), )

from .platform import PY_VERSION

TRUE_STRINGS = {'TRUE', 'YES', 'ON', '1'}
FALSE_STRINGS = {'FALSE', 'NO', 'OFF', '0', 'NONE', ''}


def is_integer(item):
    return isinstance(item, int)
Пример #13
0
    line_type: str
    visible: bool


ActionResult = Optional[FinalizeRequest]


@dataclass
class ViewProcessTracking:
    amount_unfiltered_rows: int = 0
    amount_filtered_rows: int = 0
    amount_rows_after_limit: int = 0
    duration_fetch_rows: Snapshot = Snapshot.null()
    duration_filter_rows: Snapshot = Snapshot.null()
    duration_view_render: Snapshot = Snapshot.null()


CustomAttr = TypedDict(
    "CustomAttr",
    {
        "title": str,
        "help": str,
        "name": str,
        "topic": str,
        "type": str,
        "add_custom_macro": bool,
        "show_in_table": bool,
    },
    total=True,
)
    BadCodingError,
    Filter,
    InvalidFormat,
    SelfValidatingDataclass,
    assert_is_field,
    assert_is_fqid,
    get_key_type,
    is_reserved_field,
)

from .db_events import ListUpdatesDict

ListFieldsData = TypedDict(
    "ListFieldsData",
    {
        "add": ListUpdatesDict,
        "remove": ListUpdatesDict
    },
    total=False,
)


@dataclass
class CollectionFieldLockWithFilter(SelfValidatingDataclass):
    position: int
    filter: Optional[Filter]


CollectionFieldLock = Union[int, List[CollectionFieldLockWithFilter]]


def assert_no_special_field(field: Any) -> None:
from typing import TypedDict

td = TypedDict("name", total=False, fields={"x": str, "y": int})
Пример #16
0
    "blob",  # base-64 encoded byte-sequence
    "clob",  # character large object: the string is a large array of
    # characters, for example an HTML resource
    # Non-string values
    "decimal",  # the number should be interpreted as a float-point decimal.
    "int",  # the number should be interpreted as an integer.
]  # yapf: disable
CollectionItem = Dict[str, str]
LocationType = Literal["path", "query", "header", "cookie"]
ResultType = Literal["object", "list", "scalar", "void"]
LinkType = Dict[str, str]
CollectionObject = TypedDict(
    "CollectionObject",
    {
        "id": str,
        "domainType": str,
        "links": List[LinkType],
        "value": Any,
        "extensions": Dict[str, str],
    },
)
ObjectProperty = TypedDict(
    "ObjectProperty",
    {
        "id": str,
        "value": Any,
        "disabledReason": str,
        "choices": List[Any],
        "links": List[LinkType],
        "extensions": Dict[str, Any],
    },
    total=False,
import json
import shutil
import subprocess
import sys
import tempfile
import textwrap
from pathlib import Path
from typing import Dict, List, Tuple, TypedDict, cast

import pytest

ScriptResult = TypedDict(
    "ScriptResult",
    {
        "returns": List[int],
        "recomputed": List[int],
        "serialized": Dict[str, bytes],
        "expected": List[int],
    },
)


def run_script(
        directory: Path,
        name: str = "",
        source_var: int = 1,
        closure_var: int = 2,
        closure_func_source_var: int = 3,
        other_var: int = 4,
        as_main: bool = False,
        inputs: Tuple[int] = (2, 3, 2),
Пример #18
0
    clean_up,
    computation_phase,
    data_preparation_phase,
    data_retrieval_phase,
)
from api.process.utils.lamapi.my_wrapper import LamAPIWrapper
from kgdata.wikidata.models import QNode
from sm.prelude import I, M
from tqdm.auto import tqdm

from mantistable_baseline.post_process import CPAMethod, Input, get_cpa, get_cta

Output = TypedDict(
    "MantisTableOutput",
    {
        "cpa": List[Tuple[int, int, str]],
        "cta": Dict[int, str],
        "method": Literal["mantis", "majority", "max-confidence"],
    },
)

Example = TypedDict(
    "Example",
    {
        "table": I.ColumnBasedTable,
        "links": Dict[Tuple[int, int], List[str]],
        "subj_col": Optional[Tuple[int, str]],
    },
)


def predict(
Пример #19
0
    username: Optional[str]
    password: Optional[str]


class PdfMargins(TypedDict):
    top: Optional[Union[str, int]]
    right: Optional[Union[str, int]]
    bottom: Optional[Union[str, int]]
    left: Optional[Union[str, int]]


DeviceDescriptor = TypedDict(
    "DeviceDescriptor",
    {
        "userAgent": str,
        "viewport": IntSize,
        "deviceScaleFactor": int,
        "isMobile": bool,
        "hasTouch": bool,
    },
)
Devices = Dict[str, DeviceDescriptor]


class URLMatcher:
    def __init__(self, match: URLMatch) -> None:
        self._callback: Optional[Callable[[str], bool]] = None
        self._regex_obj: Optional[Pattern] = None
        if isinstance(match, str):
            regex = fnmatch.translate(match)
            self._regex_obj = re.compile(regex)
        elif isinstance(match, Pattern):
Пример #20
0
    State as state,
)
from ..agent_based_api.v1.type_defs import (
    CheckResult,)

StatusType = int
LevelModes = str

TwoLevelsType = Tuple[Optional[float], Optional[float]]
FourLevelsType = Tuple[Optional[float], Optional[float], Optional[float], Optional[float]]
LevelsType = Union[TwoLevelsType, FourLevelsType]
FanParamDict = TypedDict(
    'TempParamDict',
    {
        'levels': TwoLevelsType,
        'levels_lower': TwoLevelsType,
        'device_levels_handling': LevelModes,
    },
    total=False,
)
FanParamType = Union[None, TwoLevelsType, FourLevelsType, FanParamDict]


def _validate_levels(
    levels: Optional[Tuple[Optional[float],
                           Optional[float]]] = None,) -> Optional[Tuple[float, float]]:
    if levels is None:
        return None

    warn, crit = levels
    if warn is None or crit is None:
Пример #21
0
class HostnameTranslation(TypedDict, total=False):
    case: Union[Literal["lower"], Literal["upper"]]
    drop_domain: bool
    mapping: Iterable[Tuple[str, str]]
    regex: Iterable[Tuple[str, str]]


LogLevel = int

LogConfig = TypedDict(
    "LogConfig",
    {
        "cmk.mkeventd": LogLevel,
        "cmk.mkeventd.EventServer": LogLevel,
        "cmk.mkeventd.EventServer.snmp": LogLevel,
        "cmk.mkeventd.EventStatus": LogLevel,
        "cmk.mkeventd.StatusServer": LogLevel,
        "cmk.mkeventd.lock": LogLevel,
    },
)


class ReplicationBase(TypedDict):
    connect_timeout: int
    interval: int
    master: Tuple[str, int]


class Replication(ReplicationBase, total=False):
    fallback: int
Пример #22
0
DB_URI = os.getenv('DB_URI')

KAFKA_URI = os.getenv('KAFKA_URI')
KAFKA_SSL_CAFILE_PATH = os.getenv('KAFKA_SSL_CAFILE_PATH')
KAFKA_SSL_CERTFILE_PATH = os.getenv('KAFKA_SSL_CERTFILE_PATH')
KAFKA_SSL_KEYFILE_PATH = os.getenv('KAFKA_SSL_KEYFILE_PATH')
KAFKA_UPTIME_TOPIC = os.getenv('KAFKA_UPTIME_TOPIC')

WEB_URL = os.getenv('WEB_URL')
DURATION = 2

Stat = TypedDict(
    'Stat',
    {
        'url': str,
        'status_code': int,
        'response_time': str,
        'pattern_exists': bool,
        'pattern_match': Optional[str],
    },
)


def transform_stat(
    url: str,
    res: requests.Response,
) -> Stat:
    stat = {
        'url': url,
        'status_code': res.status_code,
        'response_time': res.elapsed.total_seconds(),
        'pattern_exists': False,
Пример #23
0
import json
from typing import Any, Dict, List

from optuna.study import StudySummary
from optuna.trial import FrozenTrial

try:
    from typing import TypedDict
except ImportError:
    from typing_extensions import TypedDict


Attribute = TypedDict(
    "Attribute",
    {
        "key": str,
        "value": str,
    },
)
IntermediateValue = TypedDict(
    "IntermediateValue",
    {
        "step": int,
        "value": float,
    },
)
TrialParam = TypedDict(
    "TrialParam",
    {
        "name": str,
        "value": str,
Пример #24
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

from typing import Callable, Dict, List, Mapping, Optional, Sequence, TypedDict

from ..agent_based_api.v1 import type_defs

CPUSection = TypedDict(
    'CPUSection',
    {
        'clustermode': Dict[str, Dict[str, str]],
        '7mode': Dict[str, str],
    },
    total=False,
)

Instance = Dict[str, str]
SectionMultipleInstances = Dict[str, List[Instance]]
SectionSingleInstance = Mapping[str, Instance]
CustomKeys = Optional[Sequence[str]]
ItemFunc = Optional[Callable[[str, Instance], str]]


def parse_netapp_api_multiple_instances(
    string_table: type_defs.StringTable,
    custom_keys: CustomKeys = None,
    item_func: ItemFunc = None,
) -> SectionMultipleInstances:
Пример #25
0
from typing import List, Optional, Union

try:
    from typing import TypedDict
except ImportError:
    from typing_extensions import TypedDict

RTCIceServer = TypedDict(
    "RTCIceServer",
    {
        "urls": Union[str, List[str]],
        "username": Optional[str],
        "credential": Optional[str],
    },
    total=False,
)


class RTCConfiguration(TypedDict):
    iceServers: List[RTCIceServer]


class MediaStreamConstraints(TypedDict):
    audio: bool  # TODO: Support MediaTrackConstraints
    video: bool  # TODO: Support MediaTrackConstraints
Пример #26
0
# This sample tests the handling of Required and NotRequired using
# the alternative syntax form of TypedDict.

from typing import TypedDict
from typing_extensions import Required, NotRequired

Example1 = TypedDict("Example", {
    "required": Required[int],
    "not_required": NotRequired[int]
})

v1_0: Example1 = {"required": 1}

# This should generage an error.
v1_1: Example1 = {"not_required": 1}

Example2 = TypedDict("Example",
                     required=Required[int],
                     not_required=NotRequired[int])

v2_0: Example2 = {"required": 1}

# This should generage an error.
v2_1: Example2 = {"not_required": 1}
Пример #27
0
#########################################################################################

from typing import Any, Counter, Dict, Iterable, List, Mapping, Optional, Sequence, Set, TypedDict

import re

from ..agent_based_api.v1 import regex, escape_regex_chars, Result, State as state

from cmk.base.check_api import (  # pylint: disable=cmk-module-layer-violation
    get_checkgroup_parameters, host_extra_conf, host_name,
)

ItemData = TypedDict(
    "ItemData",
    {
        'attr': str,
        'lines': List[str],
    },
    total=True,
)

Section = TypedDict(
    "Section",
    {
        'errors': List[str],
        'logfiles': Dict[str, ItemData],
    },
    total=True,
)


def get_ec_rule_params():
Пример #28
0
from eth_account.account import Account
from web3.types import TxParams
from typing import TypedDict

FlashbotsBundleTx = TypedDict(
    "FlashbotsBundleTx",
    {
        "transaction": TxParams,
        "signer": Account,
    },
)

FlashbotsBundleRawTx = TypedDict(
    "FlashbotsBundleRawTx",
    {
        "signed_transaction": str,
    },
)

FlashbotsOpts = TypedDict(
    "FlashbotsOpts",
    {
        "minTimestamp": int,
        "maxTimestamp": int,
    },
)

# Type missing from eth_account, not really a part of flashbots web3 per sé
SignTx = TypedDict(
    "SignTx",
    {