import io
from typing import TypeVar, Callable

from python_crontab.interfaces.icron_entry import ICronEntry
from utilities import run_bash_cmd

Self = TypeVar("Self", bound="CronScriptManager")


class CronScriptManager:
    def __init__(self, crontab_gen: ICronEntry):
        """
        Manages the "CRUD" operation done in the cron scripts
        @param crontab_gen: concrete implementation of class for setting the python script through crontab script
        """
        self.crontab_gen = crontab_gen
        self.was_entry_modified = False
        self._new_cron_io = io.StringIO()
        self._base_crontab_command = run_bash_cmd(["crontab", "-l"],
                                                  show_output=True)
        self._cron_io: io.TextIOWrapper = self._base_crontab_command.result
        self.some_entry_exists: bool = True if self._base_crontab_command.return_code == 0 else False

    def _io_wrapper(self, func: Callable[..., str]) -> Callable[..., str]:
        def inner_wrapper(*args, **kwargs) -> str:
            update_crontab_script = func(*args, **kwargs)
            self._new_cron_io.close()
            run_bash_cmd(["crontab", "-r"])
            return update_crontab_script.strip()

        return inner_wrapper
Beispiel #2
0
    Dict,
    List,
    Type,
    TypeVar,
)

from .event import Events
from .exception import RunnerAlreadyExistsError
from .stats import RequestStats
from .runners import Runner, LocalRunner, MasterRunner, WorkerRunner
from .web import WebUI
from .user import User
from .user.task import filter_tasks_by_tags
from .shape import LoadTestShape

RunnerType = TypeVar("RunnerType", bound=Runner)


class Environment:
    events: Events = None
    """
    Event hooks used by Locust internally, as well as to extend Locust's functionality
    See :ref:`events` for available events.
    """

    user_classes: List[Type[User]] = []
    """User classes that the runner will run"""

    shape_class: LoadTestShape = None
    """A shape class to control the shape of the load test"""
Beispiel #3
0
from __future__ import annotations

from typing import TYPE_CHECKING, TypeVar

from qtpy.QtWidgets import QListView

from ._base_item_view import _BaseEventedItemView
from .qt_list_model import QtListModel

if TYPE_CHECKING:
    from qtpy.QtWidgets import QWidget

    from ...utils.events.containers import SelectableEventedList

ItemType = TypeVar("ItemType")


class QtListView(_BaseEventedItemView[ItemType], QListView):
    """A QListView for a :class:`~napari.utils.events.SelectableEventedList`.

    Designed to work with :class:`~napari._qt.containers.QtListModel`.

    This class is an adapter between
    :class:`~napari.utils.events.SelectableEventedList` and Qt's
    `QAbstractItemView` interface (see `Qt Model/View Programming
    <https://doc.qt.io/qt-5/model-view-programming.html>`_). It allows python
    users to interact with the list in the "usual" python ways, updating any Qt
    Views that may be connected, and also updates the python list object if any
    GUI events occur in the view.

    See docstring of :class:`_BaseEventedItemView` for additional background.
Beispiel #4
0
import asyncio
from concurrent.futures import Executor
from functools import partial, total_ordering
from pathlib import Path
from typing import Any, Awaitable, Callable, Generator, Optional, TypeVar, Union

from .compat import EventLoopMixin
from .thread_pool import threaded

T = TypeVar("T")


def proxy_method_async(
    name: str,
    in_executor: bool = True,
) -> Callable[..., Any]:
    def wrap_to_future(loop: asyncio.AbstractEventLoop, func: Callable[..., T],
                       *args: Any, **kwargs: Any) -> asyncio.Future:
        future = loop.create_future()

        def _inner():  # type: ignore
            try:
                return future.set_result(func(*args, **kwargs))
            except Exception as e:
                return future.set_exception(e)

        loop.call_soon(_inner)
        return future

    def wrap_to_thread(loop: asyncio.AbstractEventLoop, func: Callable[..., T],
                       executor: Executor, *args: Any,
import copy
from typing import Any, Type, TypeVar

import boost_histogram

from .._core import axis as ca
from .utils import register, set_module

T = TypeVar("T", bound="AxisTransform")


@set_module("boost_histogram.axis.transform")
class AxisTransform:
    __slots__ = ("_this",)
    _family: object
    _this: Any

    def __init_subclass__(cls, *, family: object) -> None:
        super().__init_subclass__()
        cls._family = family

    def __copy__(self: T) -> T:
        other: T = self.__class__.__new__(self.__class__)
        other._this = copy.copy(self._this)
        return other

    @classmethod
    def _convert_cpp(cls: Type[T], this: Any) -> T:
        self: T = cls.__new__(cls)
        self._this = this
        return self
Beispiel #6
0
    def map_special_case(instance_class: type,
                         entity_type: Platform) -> Platform:
        if instance_class is veraApi.VeraSwitch and vera_device.device_id in remap:
            return Platform.LIGHT
        return entity_type

    return next(
        iter(
            map_special_case(instance_class, entity_type)
            for instance_class, entity_type in type_map.items()
            if isinstance(vera_device, instance_class)),
        None,
    )


_DeviceTypeT = TypeVar("_DeviceTypeT", bound=veraApi.VeraDevice)


class VeraDevice(Generic[_DeviceTypeT], Entity):
    """Representation of a Vera device entity."""
    def __init__(self, vera_device: _DeviceTypeT,
                 controller_data: ControllerData) -> None:
        """Initialize the device."""
        self.vera_device = vera_device
        self.controller = controller_data.controller

        self._name = self.vera_device.name
        # Append device id to prevent name clashes in HA.
        self.vera_id = VERA_ID_FORMAT.format(slugify(vera_device.name),
                                             vera_device.vera_device_id)
Beispiel #7
0
            callbacks = self.callbacks[event][:]
        for callback in callbacks:
            # FIXME: if callback throws, we will lose the traceback
            if asyncio.iscoroutinefunction(callback):
                asyncio.run_coroutine_threadsafe(callback(event, *args), self.asyncio_loop)
            else:
                self.asyncio_loop.call_soon_threadsafe(callback, event, *args)


callback_mgr = CallbackManager()
trigger_callback = callback_mgr.trigger_callback
register_callback = callback_mgr.register_callback
unregister_callback = callback_mgr.unregister_callback


_NetAddrType = TypeVar("_NetAddrType")


class NetworkRetryManager(Generic[_NetAddrType]):
    """Truncated Exponential Backoff for network connections."""

    def __init__(
            self, *,
            max_retry_delay_normal: float,
            init_retry_delay_normal: float,
            max_retry_delay_urgent: float = None,
            init_retry_delay_urgent: float = None,
    ):
        self._last_tried_addr = {}  # type: Dict[_NetAddrType, Tuple[float, int]]  # (unix ts, num_attempts)

        # note: these all use "seconds" as unit
Beispiel #8
0
from ranzen import implements
from ranzen.misc import str_to_enum

__all__ = [
    "GreedyCoreSetSampler",
    "SequentialBatchSampler",
    "SizedDataset",
    "StratifiedBatchSampler",
    "Subset",
    "TrainTestSplit",
    "TrainingMode",
    "prop_random_split",
    "stratified_split_indices",
]

T_co = TypeVar("T_co", covariant=True)


@runtime_checkable
class SizedDataset(Protocol[T_co]):
    def __getitem__(self, index: int) -> T_co:
        ...

    def __len__(self) -> int:
        ...


D = TypeVar("D", bound=SizedDataset)


class Subset(Generic[D]):
Beispiel #9
0
@attr.s(slots=True)  # pragma: no mutate
class OperationDefinition:
    """A wrapper to store not resolved API operation definitions.

    To prevent recursion errors we need to store definitions without resolving references. But operation definitions
    itself can be behind a reference (when there is a ``$ref`` in ``paths`` values), therefore we need to store this
    scope change to have a proper reference resolving later.
    """

    raw: Dict[str, Any] = attr.ib()  # pragma: no mutate
    resolved: Dict[str, Any] = attr.ib()  # pragma: no mutate
    scope: str = attr.ib()  # pragma: no mutate
    parameters: Sequence[Parameter] = attr.ib()  # pragma: no mutate


P = TypeVar("P", bound=Parameter)


@attr.s  # pragma: no mutate
class APIOperation(Generic[P]):
    """A single operation defined in an API."""

    # `path` does not contain `basePath`
    # Example <scheme>://<host>/<basePath>/users - "/users" is path
    # https://swagger.io/docs/specification/2-0/api-host-and-base-path/
    path: str = attr.ib()  # pragma: no mutate
    method: str = attr.ib()  # pragma: no mutate
    definition: OperationDefinition = attr.ib(repr=False)  # pragma: no mutate
    schema: "BaseSchema" = attr.ib()  # pragma: no mutate
    app: Any = attr.ib(default=None)  # pragma: no mutate
    base_url: Optional[str] = attr.ib(default=None)  # pragma: no mutate
Beispiel #10
0
    Type,
    TypeVar,
    Union,
    cast,
)

from make_it_sync import make_sync

from func_adl.util_types import unwrap_iterable

from .util_ast import as_ast, function_call, parse_as_ast

# Attribute that will be used to store the executor reference
executor_attr_name = "_func_adl_executor"

T = TypeVar("T")
S = TypeVar("S")


class ReturnedDataPlaceHolder:
    """Type returned for awkward, etc.,"""

    pass


def _local_simplification(a: ast.Lambda) -> ast.Lambda:
    """Simplify the AST by removing unnecessary statements and
    syntatic sugar
    """
    from func_adl.ast.syntatic_sugar import resolve_syntatic_sugar
Beispiel #11
0
from typing_extensions import ParamSpec, Protocol


# submodules
from .datamodel import DataModel
from .dataoptions import DataOptions
from .typing import DataType, Order, Shape, Sizes


# constants
DEFAULT_OPTIONS = DataOptions(xr.DataArray)


# type hints
P = ParamSpec("P")
TDataArray = TypeVar("TDataArray", bound=xr.DataArray)


class DataClass(Protocol[P]):
    """Type hint for a dataclass object."""

    def __init__(self, *args: P.args, **kwargs: P.kwargs) -> None:
        ...

    __dataclass_fields__: Dict[str, Field[Any]]


class DataArrayClass(Protocol[P, TDataArray]):
    """Type hint for a dataclass object with a DataArray factory."""

    def __init__(self, *args: P.args, **kwargs: P.kwargs) -> None:
Beispiel #12
0
    """
    Patch the py-evm chain with a VMState that pauses when state data
    is missing, and emits an event which requests the missing data.
    """
    pausing_vm_config = tuple(
        (starting_block, pausing_vm_decorator(vm, event_bus, loop, urgent=urgent))
        for starting_block, vm in vm_config
    )
    PausingBeamChain = BeamChain.configure(
        vm_configuration=pausing_vm_config,
        chain_id=chain_id,
    )
    return PausingBeamChain(db)


TVMFuncReturn = TypeVar('TVMFuncReturn')


def pausing_vm_decorator(
        original_vm_class: Type[VirtualMachineAPI],
        event_bus: EndpointAPI,
        loop: asyncio.AbstractEventLoop,
        urgent: bool = True) -> Type[VirtualMachineAPI]:
    """
    Decorate a py-evm VM so that it will pause when data is missing
    """
    async def request_missing_storage(
            missing_node_hash: Hash32,
            storage_key: Hash32,
            storage_root_hash: Hash32,
            account_address: Address) -> MissingStorageCollected:
from typing import List, TypeVar, Generic, Tuple
T = TypeVar('T', int, float)


class Edge(Generic[T]):
    def __init__(self, dst: int, weight: T) -> None:
        self.dst: int = dst
        self.weight: T = weight

    def __lt__(self, e: 'Edge') -> bool:
        return self.weight > e.weight


class Graph(Generic[T]):
    def __init__(self, V: int) -> None:
        self.V: int = V
        self.E: List[List[Edge[T]]] = [[] for _ in range(V)]
        self.edge_size: int = 0

    def add_edge(self, src: int, dst: int, weight: T) -> None:
        self.E[src].append(Edge(dst, weight))
        self.edge_size += 1


class HeavyLightDecomposition(Generic[T]):
    def __init__(self, G: Graph[T]) -> None:
        self.G: Graph[T] = G
        self.vid: List[int] = [0] * G.V
        self.head: List[int] = [0] * G.V
        self.heavy: List[int] = [-1] * G.V
        self.parent: List[int] = [0] * G.V
Beispiel #14
0
    Sequence,
    Type,
    TypeVar,
    Union,
)

from typing_extensions import final

from returns._generated.futures import _future, _future_result
from returns._generated.iterable import iterable
from returns.io import IO, IOResult
from returns.primitives.container import BaseContainer
from returns.result import Failure, Result, Success

# Definitions:
_ValueType = TypeVar('_ValueType', covariant=True)
_NewValueType = TypeVar('_NewValueType')
_ErrorType = TypeVar('_ErrorType', covariant=True)
_NewErrorType = TypeVar('_NewErrorType')

# Aliases:
_FirstType = TypeVar('_FirstType')
_SecondType = TypeVar('_SecondType')


# Public composition helpers:

async def async_identity(instance: _FirstType) -> _FirstType:
    """
    Async function that returns its argument.
Beispiel #15
0
from pandas.core.internals.base import (
    DataManager,
    SingleDataManager,
    interleaved_dtype,
)
from pandas.core.internals.blocks import (
    ensure_block_shape,
    external_values,
    new_block,
    to_native_types,
)

if TYPE_CHECKING:
    from pandas import Float64Index

T = TypeVar("T", bound="ArrayManager")


class ArrayManager(DataManager):
    """
    Core internal data structure to implement DataFrame and Series.

    Alternative to the BlockManager, storing a list of 1D arrays instead of
    Blocks.

    This is *not* a public API class

    Parameters
    ----------
    arrays : Sequence of arrays
    axes : Sequence of Index
 def current_user(self, request=None) -> TypeVar('User'):
     """ retrieves the User instance for a request, otherwise None """
import os
import time
import unittest

from multiprocessing.sharedctypes import Synchronized

# We need to pick an ID for this test-backend invocation, and store it
# in this global so it can be used in init_worker; this is used to
# ensure the database IDs we select are unique for each `test-backend`
# run.  This probably should use a locking mechanism rather than the
# below hack, which fails 1/10000000 of the itme.
random_id_range_start = random.randint(1, 10000000) * 100

_worker_id = 0  # Used to identify the worker process.

ReturnT = TypeVar('ReturnT')  # Constrain return type to match

def slow(slowness_reason: str) -> Callable[[Callable[..., ReturnT]], Callable[..., ReturnT]]:
    '''
    This is a decorate that annotates a test as being "known
    to be slow."  The decorator will set expected_run_time and slowness_reason
    as attributes of the function.  Other code can use this annotation
    as needed, e.g. to exclude these tests in "fast" mode.
    '''
    def decorator(f: Any) -> ReturnT:
        f.slowness_reason = slowness_reason
        return f

    return decorator

def is_known_slow_test(test_method: Any) -> bool:
Beispiel #18
0
# -*- coding: utf-8 -*-

from typing import TypeVar

from odoo import models

from . import adapter

AdapterType = TypeVar(
    'AdapterType',
    bound='.'.join([adapter.Adapter.__module__, adapter.Adapter.__name__]))

OdooModelType = TypeVar('ModelType',
                        bound='.'.join(
                            [models.Model.__module__, models.Model.__name__]))
from typing import Any, Dict, List, Type, TypeVar

import attr

T = TypeVar("T", bound="CurrentUserInfoResponse200TeamsItem")


@attr.s(auto_attribs=True)
class CurrentUserInfoResponse200TeamsItem:
    """ """

    id: str
    name: str
    is_team_manager: int
    additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)

    def to_dict(self) -> Dict[str, Any]:
        id = self.id
        name = self.name
        is_team_manager = self.is_team_manager

        field_dict: Dict[str, Any] = {}
        field_dict.update(self.additional_properties)
        field_dict.update({
            "id": id,
            "name": name,
            "isTeamManager": is_team_manager,
        })

        return field_dict
Beispiel #20
0
#  Unless required by applicable law or agreed to in writing,
#  software distributed under the License is distributed on an
#  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
#  KIND, either express or implied.  See the License for the
#  specific language governing permissions and limitations
#  under the License.

import functools
import re
import warnings
from collections.abc import Collection as ABCCollection
from typing import Any, Callable, Collection, Iterable, List, TypeVar, Union, cast

import pandas as pd  # type: ignore

RT = TypeVar("RT")


def deprecated_api(
    replace_with: str,
) -> Callable[[Callable[..., RT]], Callable[..., RT]]:
    def wrapper(f: Callable[..., RT]) -> Callable[..., RT]:
        @functools.wraps(f)
        def wrapped(*args: Any, **kwargs: Any) -> RT:
            warnings.warn(
                f"{f.__name__} is deprecated, use {replace_with} instead",
                DeprecationWarning,
                stacklevel=2,
            )
            return f(*args, **kwargs)
Beispiel #21
0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Utilities to use within loggers."""

import queue
import threading
from typing import Callable, TypeVar, Generic

from absl import logging


E = TypeVar("E")


class AsyncExecutor(Generic[E]):
  """Executes a blocking function asynchronously on a queue of items."""

  def __init__(
      self,
      fn: Callable[[E], None],
      queue_size: int = 1,
      interruptible_interval_secs: float = 1.0,
  ):
    """Buffers elements in a queue and runs `fn` asynchronously..

    NOTE: Once closed, `AsyncExecutor` will block until current `fn` finishes
      but is not guaranteed to dequeue all elements currently stored in
from typing import List
from abc import abstractmethod
from typing import TypeVar, Protocol


class Comparable(Protocol):
    """Protocol for annotating comparable types."""
    @abstractmethod
    def __lt__(self, other) -> bool:
        pass


CT = TypeVar("CT", bound=Comparable)


class SelectionSort:
    @staticmethod
    def sort(data_list: List[CT]):
        for i in range(len(data_list)):
            min_idx = i
            for j in range(i + 1, len(data_list)):
                if data_list[j] < data_list[min_idx]:
                    min_idx = j
            data_list[i], data_list[min_idx] = data_list[min_idx], data_list[i]


if __name__ == '__main__':
    test_list: List[int] = [1, 4, 2, 3, 6, 5]
    SelectionSort.sort(test_list)
    print(test_list)
Beispiel #23
0
from twisted.internet.defer import Deferred
from twisted.python.failure import Failure
from twisted.web.client import readBody
from twisted.web.iweb import IResponse
from unpaddedbase64 import decode_base64

from sydent.config.exceptions import ConfigError
from sydent.db.hashing_metadata import HashingMetadataStore
from sydent.db.threepid_associations import GlobalAssociationStore, SignedAssociations
from sydent.threepid import threePidAssocFromDict
from sydent.types import JsonDict
from sydent.util import json_decoder
from sydent.util.hash import sha256_and_url_safe_base64
from sydent.util.stringutils import normalise_address

PushUpdateReturn = TypeVar("PushUpdateReturn")

if TYPE_CHECKING:
    from sydent.sydent import Sydent

logger = logging.getLogger(__name__)

SIGNING_KEY_ALGORITHM = "ed25519"


class Peer(Generic[PushUpdateReturn]):
    def __init__(self, servername: str, pubkeys: Dict[str, str]):
        """
        :param server_name: The peer's server name.
        :param pubkeys: The peer's public keys in a Dict[key_id, key_b64]
        """
Beispiel #24
0
import bisect
import warnings
import functools

from torch._utils import _accumulate
from torch import randperm
# No 'default_generator' in torch/__init__.pyi
from torch import default_generator  # type: ignore
from torch.utils.data._typing import _DataPipeMeta
from typing import TypeVar, Generic, Iterable, Iterator, Sequence, List, Optional, Tuple, Dict, Callable
from ... import Tensor, Generator

T_co = TypeVar('T_co', covariant=True)
T = TypeVar('T')


class Dataset(Generic[T_co]):
    r"""An abstract class representing a :class:`Dataset`.

    All datasets that represent a map from keys to data samples should subclass
    it. All subclasses should overwrite :meth:`__getitem__`, supporting fetching a
    data sample for a given key. Subclasses could also optionally overwrite
    :meth:`__len__`, which is expected to return the size of the dataset by many
    :class:`~torch.utils.data.Sampler` implementations and the default options
    of :class:`~torch.utils.data.DataLoader`.

    .. note::
      :class:`~torch.utils.data.DataLoader` by default constructs a index
      sampler that yields integral indices.  To make it work with a map-style
      dataset with non-integral indices/keys, a custom sampler must be provided.
    """
Beispiel #25
0
    TypeVar,
    Iterable,
    Sequence,
    Generic,
    List,
    Callable,
    Set,
    Deque,
    Dict,
    Any,
    Optional,
)
from typing_extensions import Protocol
from heapq import heappush, heappop

T = TypeVar("T")


def linear_contains(iterable: Iterable[T], key: T) -> bool:
    for item in iterable:
        if item == key:
            return True
    return False


C = TypeVar("C", bound="Comparable")


class Comparable(Protocol):
    def __eq__(self, other: Any) -> bool:
        ...
Beispiel #26
0
from __future__ import annotations
from typing import Any, TypeVar, List, Set, Dict, Tuple, Optional, Union

from grapl_analyzerlib.node_types import (
    EdgeT,
    PropType,
    PropPrimitive,
    EdgeRelationship,
)
from grapl_analyzerlib.schema import Schema
from grapl_analyzerlib.nodes.entity import EntitySchema, EntityQuery, EntityView

AQ = TypeVar("AQ", bound="AssetQuery")
AV = TypeVar("AV", bound="AssetView")

T = TypeVar("T")

OneOrMany = Union[List[T], T]


def default_asset_properties() -> Dict[str, PropType]:
    return {
        "hostname": PropType(
            PropPrimitive.Str,
            False,
        ),
    }


def default_asset_edges() -> Dict[str, Tuple[EdgeT, str]]:
    return {
Beispiel #27
0
from typing import Generic, List, Optional, Type, TypeVar

from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlalchemy.orm import Session

from cashback.db.base_class import Base

ModelType = TypeVar("ModelType", bound=Base)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)


# pylint: disable=redefined-builtin
class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
    def __init__(self, model: Type[ModelType]):
        """
        CRUD object with default methods to Create, Read, Update, Delete (CRUD).
        """
        self.model = model

    def get(self, db_session: Session, id: int) -> Optional[ModelType]:
        return db_session.query(self.model).filter(self.model.id == id).first()

    def get_multi(self,
                  db_session: Session,
                  *,
                  skip=0,
                  limit=100) -> List[ModelType]:
        return db_session.query(self.model).offset(skip).limit(limit).all()
Beispiel #28
0
# coding: UTF-8

from typing import Mapping, Tuple, TypeVar

from .accumulative import AccumulativeMonitor
from .base import BaseMonitor
from .combined import CombinedOneShotMonitor
from .idle import IdleMonitor
from .interval import IntervalMonitor
from .perf import PerfMonitor
from .power import PowerMonitor
from .rdtsc import RDTSCMonitor
from .resctrl import ResCtrlMonitor
from .runtime import RuntimeMonitor

MonitorData = TypeVar('MonitorData', int, float, Tuple, Mapping)
Beispiel #29
0
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings

from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling

from ... import models as _models

T = TypeVar('T')
ClsType = Optional[Callable[
    [PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str,
                                                               Any]], Any]]


class VirtualRoutersOperations:
    """VirtualRoutersOperations async operations.

    You should not instantiate this class directly. Instead, you should create a Client instance that
    instantiates it for you and attaches it as an attribute.

    :ivar models: Alias to model classes used in this operation group.
    :type models: ~azure.mgmt.network.v2019_08_01.models
    :param client: Client for service requests.
    :param config: Configuration of service client.
Beispiel #30
0
    @abc.abstractmethod
    def redo(self) -> NoReturn:
        """
        Redo implementation which should be overwritten
        """

    @property
    def text(self) -> str:
        return self._text

    @text.setter
    def text(self, text: str) -> NoReturn:
        self._text = text


T_ = TypeVar('T_', bound=UndoCommand)


def dict_stack_deco(func: Callable) -> Callable:
    def inner(obj, *args, **kwargs):
        # Only do the work to a NotarizedDict.
        if hasattr(obj, '_stack_enabled') and obj._stack_enabled:
            if not kwargs:
                borg.stack.push(DictStack(obj, *args))
            else:
                borg.stack.push(DictStackReCreate(obj, **kwargs))
        else:
            func(obj, *args, **kwargs)
    return inner