コード例 #1
0
import torch.distributed as dist

from . import constants as rpc_constants

BackendValue = collections.namedtuple(
    "BackendValue",
    ["construct_rpc_backend_options_handler", "init_backend_handler"])


def _backend_type_repr(self):
    return "BackendType." + self.name


# Create an enum type, `BackendType`, with empty members.
BackendType = enum.Enum(value="BackendType", names={})
BackendType.__repr__ = _backend_type_repr


def backend_registered(backend_name):
    """
    Checks if backend_name is registered as an RPC backend.

    Arguments:
        backend_name (str): string to identify the RPC backend.
    Returns:
        True if the backend has been registered with ``register_backend``, else
        False.
    """
    return backend_name in BackendType.__members__.keys()
コード例 #2
0
ファイル: mock.py プロジェクト: Wesmania/asynctest
    if new == DEFAULT and not new_callable:
        original = patcher.get_original()[0]
        if isinstance(original, (classmethod, staticmethod)):
            # the original object is the raw descriptor, if it's a classmethod
            # or a static method, we need to unwrap it
            original = original.__get__(None, object)

        if asyncio.iscoroutinefunction(original):
            patcher.new_callable = CoroutineMock
        else:
            patcher.new_callable = MagicMock

    return patcher


PatchScope = enum.Enum('PatchScope', 'LIMITED GLOBAL')

#: Value of ``scope``, deactivating a patch when a decorated generator or
#: a coroutine pauses (``yield`` or ``await``).
LIMITED = PatchScope.LIMITED

#: Value of ``scope``, activating a patch until the decorated generator or
#: coroutine returns or raises an exception.
GLOBAL = PatchScope.GLOBAL


def _decorate_coroutine_callable(func, new_patching):
    if hasattr(func, 'patchings'):
        func.patchings.append(new_patching)
        return func
This tool recursively checks that the embedded variables and outputs tables in
README files, match what is generated at runtime by tfdoc based on current
sources. As such, it accepts pretty much the same options as tfdoc does. Its
main use is in CI pipelines triggered by pull requests.
'''

import difflib
import enum
import pathlib

import click
import tfdoc

BASEDIR = pathlib.Path(__file__).resolve().parents[1]

State = enum.Enum('State', 'OK FAIL SKIP')


def _check_dir(dir_name, exclude_files=None, files=False, show_extra=False):
  'Invoke tfdoc on folder, using the relevant options.'
  dir_path = BASEDIR / dir_name
  for readme_path in sorted(dir_path.glob('**/README.md')):
    if '.terraform' in str(readme_path):
      continue
    diff = None
    readme = readme_path.read_text()
    mod_name = str(readme_path.relative_to(dir_path).parent)
    result = tfdoc.get_doc(readme)
    if not result:
      state = State.SKIP
    else:
コード例 #4
0
import enum
import Xlib.display
import Xlib.ext
import Xlib.ext.xtest
import Xlib.X
import Xlib.protocol

from pynput._util.xorg import (display_manager, ListenerMixin)
from . import _base

# pylint: disable=C0103
Button = enum.Enum('Button',
                   module=__name__,
                   names=[('unknown', None), ('left', 1), ('middle', 2),
                          ('right', 3), ('scroll_up', 4), ('scroll_down', 5),
                          ('scroll_left', 6),
                          ('scroll_right', 7)] + [('button%d' % i, i)
                                                  for i in range(8, 31)])
# pylint: enable=C0103


class Controller(_base.Controller):
    def __init__(self, *args, **kwargs):
        super(Controller, self).__init__(*args, **kwargs)
        self._display = Xlib.display.Display()

    def __del__(self):
        if hasattr(self, '_display'):
            self._display.close()
コード例 #5
0
UNGRAMMATICAL = "Ungrammatical-question"  # this role is for predicted question with non-grammatical structure
"""
SemanticRole will represented by a string, denoting the roles by:
    "R0", "R1", "R2", "where", "when", ..., "R2_about", "R2_against", ..., "where_about", "where_against", ... 
"""
role_space = {"R0", "R1", "R2"} | \
             adjunct_wh_words | \
             {"R2_" + p
              for p in all_prepositions_in_dataset} | \
             {wh + "_" + p
              for wh in adjunct_wh_words
              for p in all_prepositions_in_dataset} | \
             {UNGRAMMATICAL} # this role is for predicted question with non-grammatical structure

SemanticRole = enum.Enum("SemanticRole", {r: r for r in role_space})


def is_equivalent_question(q1: Question, q2: Question) -> bool:
    return question_to_sem_role(q1) == question_to_sem_role(q2)


def question_to_sem_role(q: Question) -> SemanticRole:
    """ Refer to Table 7 at He et. al. (2015). """
    def get_R2() -> SemanticRole:
        # distinguish direct object-2 or indirect object-2 by presence of preposition
        if q.prep:
            return SemanticRole("R2_" + q.prep)
        else:
            return SemanticRole.R2
コード例 #6
0
import enum

BugStatus = enum.Enum(
    value='BugStatus',
    names=('fix_released fix_committed in_progress '
           'wont_fix invalid incomplete new'),
)

print('Member: {}'.format(BugStatus.new))

print('\nAll members:')
for status in BugStatus:
    print('{:15} = {}'.format(status.name, status.value))

print('*' * 60)

BugStatus = enum.Enum(
    value='BugStatus',
    names=[
        ('new', 7),
        ('incomplete', 6),
        ('invalid', 5),
        ('wont_fix', 4),
        ('in_progress', 3),
        ('fix_committed', 2),
        ('fix_released', 1),
    ],
)

print('All members:')
for status in BugStatus:
コード例 #7
0
 def test_enum(self):
     """Test is_enum with an enum."""
     e = enum.Enum('Foo', 'bar, baz')
     assert utils.is_enum(e)
コード例 #8
0
def create_fruit_labels(fruits=("apple", "banana", "mix")):
    FruitLabel = enum.Enum('FruitLabel', zip(fruits, itertools.count()))
    return FruitLabel
コード例 #9
0
ファイル: usertypes.py プロジェクト: zfenj/qutebrowser
        """Get the last item in the list."""
        if not self._items:
            raise IndexError("No items found!")
        self._idx = len(self._items) - 1
        return self.curitem()

    def reset(self):
        """Reset the position to the default."""
        if self._default is _UNSET:
            raise ValueError("No default set!")
        self._idx = self._items.index(self._default)
        return self.curitem()


# The mode of a Question.
PromptMode = enum.Enum('PromptMode', ['yesno', 'text', 'user_pwd', 'alert',
                                      'download'])


class ClickTarget(enum.Enum):

    """How to open a clicked link."""

    normal = 0  #: Open the link in the current tab
    tab = 1  #: Open the link in a new foreground tab
    tab_bg = 2  #: Open the link in a new background tab
    window = 3  #: Open the link in a new window
    hover = 4  #: Only hover over the link


class KeyMode(enum.Enum):
コード例 #10
0
class TestRegister:
    def test_simple(self):
        @cmdutils.register()
        def fun():
            """Blah."""

        cmd = objects.commands['fun']
        assert cmd.handler is fun
        assert cmd.name == 'fun'
        assert len(objects.commands) == 1

    def test_underlines(self):
        """Make sure the function name is normalized correctly (_ -> -)."""
        @cmdutils.register()
        def eggs_bacon():
            """Blah."""

        assert objects.commands['eggs-bacon'].name == 'eggs-bacon'
        assert 'eggs_bacon' not in objects.commands

    def test_lowercasing(self):
        """Make sure the function name is normalized correctly (uppercase)."""
        @cmdutils.register()
        def Test():  # noqa: N801,N806 pylint: disable=invalid-name
            """Blah."""

        assert objects.commands['test'].name == 'test'
        assert 'Test' not in objects.commands

    def test_explicit_name(self):
        """Test register with explicit name."""
        @cmdutils.register(name='foobar')
        def fun():
            """Blah."""

        assert objects.commands['foobar'].name == 'foobar'
        assert 'fun' not in objects.commands
        assert len(objects.commands) == 1

    def test_multiple_registrations(self):
        """Make sure registering the same name twice raises ValueError."""
        @cmdutils.register(name='foobar')
        def fun():
            """Blah."""

        with pytest.raises(ValueError):

            @cmdutils.register(name='foobar')
            def fun2():
                """Blah."""

    def test_instance(self):
        """Make sure the instance gets passed to Command."""
        @cmdutils.register(instance='foobar')
        def fun(self):
            """Blah."""

        assert objects.commands['fun']._instance == 'foobar'

    def test_star_args(self):
        """Check handling of *args."""
        @cmdutils.register()
        def fun(*args):
            """Blah."""
            assert args == ['one', 'two']

        objects.commands['fun'].parser.parse_args(['one', 'two'])

    def test_star_args_empty(self):
        """Check handling of *args without any value."""
        @cmdutils.register()
        def fun(*args):
            """Blah."""
            assert not args

        with pytest.raises(argparser.ArgumentParserError):
            objects.commands['fun'].parser.parse_args([])

    def test_star_args_type(self):
        """Check handling of *args with a type.

        This isn't implemented, so be sure we catch it.
        """
        with pytest.raises(AssertionError):

            @cmdutils.register()
            def fun(*args: int):
                """Blah."""

    def test_star_args_optional(self):
        """Check handling of *args withstar_args_optional."""
        @cmdutils.register(star_args_optional=True)
        def fun(*args):
            """Blah."""
            assert not args

        cmd = objects.commands['fun']
        cmd.namespace = cmd.parser.parse_args([])
        args, kwargs = cmd._get_call_args(win_id=0)
        fun(*args, **kwargs)

    def test_star_args_optional_annotated(self):
        @cmdutils.register(star_args_optional=True)
        def fun(*args: str):
            """Blah."""

        cmd = objects.commands['fun']
        cmd.namespace = cmd.parser.parse_args([])
        cmd._get_call_args(win_id=0)

    @pytest.mark.parametrize('inp, expected', [(['--arg'], True),
                                               (['-a'], True), ([], False)])
    def test_flag(self, inp, expected):
        @cmdutils.register()
        def fun(arg=False):
            """Blah."""
            assert arg == expected

        cmd = objects.commands['fun']
        cmd.namespace = cmd.parser.parse_args(inp)
        assert cmd.namespace.arg == expected

    def test_flag_argument(self):
        @cmdutils.register()
        @cmdutils.argument('arg', flag='b')
        def fun(arg=False):
            """Blah."""
            assert arg

        cmd = objects.commands['fun']

        with pytest.raises(argparser.ArgumentParserError):
            cmd.parser.parse_args(['-a'])

        cmd.namespace = cmd.parser.parse_args(['-b'])
        assert cmd.namespace.arg
        args, kwargs = cmd._get_call_args(win_id=0)
        fun(*args, **kwargs)

    def test_self_without_instance(self):
        with pytest.raises(TypeError,
                           match="fun is a class method, but "
                           "instance was not given!"):

            @cmdutils.register()
            def fun(self):
                """Blah."""

    def test_instance_without_self(self):
        with pytest.raises(TypeError,
                           match="fun is not a class method, but "
                           "instance was given!"):

            @cmdutils.register(instance='inst')
            def fun():
                """Blah."""

    def test_var_kw(self):
        with pytest.raises(TypeError,
                           match="fun: functions with varkw "
                           "arguments are not supported!"):

            @cmdutils.register()
            def fun(**kwargs):
                """Blah."""

    def test_partial_arg(self):
        """Test with only some arguments decorated with @cmdutils.argument."""
        @cmdutils.register()
        @cmdutils.argument('arg1', flag='b')
        def fun(arg1=False, arg2=False):
            """Blah."""

    def test_win_id(self):
        @cmdutils.register()
        @cmdutils.argument('win_id', value=cmdutils.Value.win_id)
        def fun(win_id):
            """Blah."""

        assert objects.commands['fun']._get_call_args(42) == ([42], {})

    def test_count(self):
        @cmdutils.register()
        @cmdutils.argument('count', value=cmdutils.Value.count)
        def fun(count=0):
            """Blah."""

        assert objects.commands['fun']._get_call_args(42) == ([0], {})

    def test_fill_self(self):
        with pytest.raises(TypeError,
                           match="fun: Can't fill 'self' with "
                           "value!"):

            @cmdutils.register(instance='foobar')
            @cmdutils.argument('self', value=cmdutils.Value.count)
            def fun(self):
                """Blah."""

    def test_fill_invalid(self):
        with pytest.raises(TypeError,
                           match="fun: Invalid value='foo' for "
                           "argument 'arg'!"):

            @cmdutils.register()
            @cmdutils.argument('arg', value='foo')
            def fun(arg):
                """Blah."""

    def test_count_without_default(self):
        with pytest.raises(TypeError,
                           match="fun: handler has count parameter "
                           "without default!"):

            @cmdutils.register()
            @cmdutils.argument('count', value=cmdutils.Value.count)
            def fun(count):
                """Blah."""

    @pytest.mark.parametrize('hide', [True, False])
    def test_pos_args(self, hide):
        @cmdutils.register()
        @cmdutils.argument('arg', hide=hide)
        def fun(arg):
            """Blah."""

        pos_args = objects.commands['fun'].pos_args
        if hide:
            assert pos_args == []
        else:
            assert pos_args == [('arg', 'arg')]

    Enum = enum.Enum('Test', ['x', 'y'])

    @pytest.mark.parametrize(
        'typ, inp, choices, expected',
        [
            (int, '42', None, 42),
            (int, 'x', None, cmdexc.ArgumentTypeError),
            (str, 'foo', None, 'foo'),
            (typing.Union[str, int], 'foo', None, 'foo'),
            (typing.Union[str, int], '42', None, 42),

            # Choices
            (str, 'foo', ['foo'], 'foo'),
            (str, 'bar', ['foo'], cmdexc.ArgumentTypeError),

            # Choices with Union: only checked when it's a str
            (typing.Union[str, int], 'foo', ['foo'], 'foo'),
            (typing.Union[str, int], 'bar', ['foo'], cmdexc.ArgumentTypeError),
            (typing.Union[str, int], '42', ['foo'], 42),
            (Enum, 'x', None, Enum.x),
            (Enum, 'z', None, cmdexc.ArgumentTypeError),
        ])
    def test_typed_args(self, typ, inp, choices, expected):
        @cmdutils.register()
        @cmdutils.argument('arg', choices=choices)
        def fun(arg: typ):
            """Blah."""
            assert arg == expected

        cmd = objects.commands['fun']
        cmd.namespace = cmd.parser.parse_args([inp])

        if expected is cmdexc.ArgumentTypeError:
            with pytest.raises(cmdexc.ArgumentTypeError):
                cmd._get_call_args(win_id=0)
        else:
            args, kwargs = cmd._get_call_args(win_id=0)
            assert args == [expected]
            assert kwargs == {}
            fun(*args, **kwargs)

    def test_choices_no_annotation(self):
        # https://github.com/qutebrowser/qutebrowser/issues/1871
        @cmdutils.register()
        @cmdutils.argument('arg', choices=['foo', 'bar'])
        def fun(arg):
            """Blah."""

        cmd = objects.commands['fun']
        cmd.namespace = cmd.parser.parse_args(['fish'])

        with pytest.raises(cmdexc.ArgumentTypeError):
            cmd._get_call_args(win_id=0)

    def test_choices_no_annotation_kwonly(self):
        # https://github.com/qutebrowser/qutebrowser/issues/1871
        @cmdutils.register()
        @cmdutils.argument('arg', choices=['foo', 'bar'])
        def fun(*, arg='foo'):
            """Blah."""

        cmd = objects.commands['fun']
        cmd.namespace = cmd.parser.parse_args(['--arg=fish'])

        with pytest.raises(cmdexc.ArgumentTypeError):
            cmd._get_call_args(win_id=0)

    def test_pos_arg_info(self):
        @cmdutils.register()
        @cmdutils.argument('foo', choices=('a', 'b'))
        @cmdutils.argument('bar', choices=('x', 'y'))
        @cmdutils.argument('opt')
        def fun(foo, bar, opt=False):
            """Blah."""

        cmd = objects.commands['fun']
        assert cmd.get_pos_arg_info(0) == command.ArgInfo(choices=('a', 'b'))
        assert cmd.get_pos_arg_info(1) == command.ArgInfo(choices=('x', 'y'))
        with pytest.raises(IndexError):
            cmd.get_pos_arg_info(2)

    def test_keyword_only_without_default(self):
        # https://github.com/qutebrowser/qutebrowser/issues/1872
        def fun(*, target):
            """Blah."""

        with pytest.raises(TypeError,
                           match="fun: handler has keyword only "
                           "argument 'target' without default!"):
            fun = cmdutils.register()(fun)

    def test_typed_keyword_only_without_default(self):
        # https://github.com/qutebrowser/qutebrowser/issues/1872
        def fun(*, target: int):
            """Blah."""

        with pytest.raises(TypeError,
                           match="fun: handler has keyword only "
                           "argument 'target' without default!"):
            fun = cmdutils.register()(fun)
コード例 #11
0
import enum
import hashlib
from abc import ABC, abstractmethod
from functools import partial
from pathlib import Path
from typing import Optional, BinaryIO, Mapping, Iterable, Tuple
from typing_extensions import TypedDict


ChecksumAlgorithm = enum.Enum(
    'Algorithm', {
        name: partial(hashlib.new, name)
        for name in hashlib.algorithms_available
    }
)


class FileInfo(TypedDict):
    ticket: str
    size: int
    checksum: Tuple[str, str]  # (algorithm, value)
    namespace: str
    metadata: Optional[dict] = None


class Storage(ABC):
    name: str
    root: Path

    @abstractmethod
    def generate_ticket(self) -> str:
コード例 #12
0
'''


@attr.s
class DistributionInfo:
    """Information about the running distribution."""

    id = attr.ib()  # type: typing.Optional[str]
    parsed = attr.ib()  # type: Distribution
    version = attr.ib()  # type: typing.Optional[typing.Tuple[str, ...]]
    pretty = attr.ib()  # type: str


pastebin_url = None
Distribution = enum.Enum('Distribution', [
    'unknown', 'ubuntu', 'debian', 'void', 'arch', 'gentoo', 'fedora',
    'opensuse', 'linuxmint', 'manjaro', 'kde_flatpak'
])


def distribution() -> typing.Optional[DistributionInfo]:
    """Get some information about the running Linux distribution.

    Returns:
        A DistributionInfo object, or None if no info could be determined.
            parsed: A Distribution enum member
            version: A Version object, or None
            pretty: Always a string (might be "Unknown")
    """
    filename = os.environ.get('QUTE_FAKE_OS_RELEASE', '/etc/os-release')
    info = {}
    try:
コード例 #13
0
def AutoNameEnum(enum_type_name, enum_fields):
    return enum.Enum(enum_type_name, [(field, field.lower()) for field in enum_fields])
コード例 #14
0
ファイル: classes.py プロジェクト: statnett/relevant_assets
import math
import enum

BranchTypeEnum = enum.Enum(value='BranchTypeEnum',
                           names=('Line', 'Coupler', 'Transformer',
                                  'Transformer2W', 'Transformer3W3', 'Transformer3W2'))


class Branch:
    n_of_branches = 0
    IATL_max = 5000  # Threshold above which IATL are regarded as infinite.
    Sbase = 1.0  # MVA, for p.u conversion.

    def __init__(self, name_from, name_to, order, impedance, PATL, v_base,
                 branch_type, display_name):
        self.index = Branch.n_of_branches
        self.name_from = name_from
        self.name_to = name_to
        self.name_branch = name_from + " " + name_to + " " + order
        self.display_name = display_name
        self.order = order
        self.country = None
        self.node_from = None
        self.node_to = None
        self.ring = 99
        self.connected = False
        self.is_tie_line = False
        self.type = branch_type
        self.v_base = v_base  # in kV
        self.impedance = impedance  # should be given in p.u.
        if PATL > Branch.IATL_max * math.sqrt(3) * self.v_base / 1000:
コード例 #15
0
#enum_programmatic_create.py

import enum

BugStatus = enum.Enum(
    value='BugStatus',
    names=('fix_released fix_committed in_progress '
           'wont_fix invalid incomplete new'),
)

print('Membri: {}'.format(BugStatus.new))

print('\nTutti i membri:')
for status in BugStatus:
    print('{:15} = {}'.format(status.name, status.value))
コード例 #16
0
ファイル: usertypes.py プロジェクト: zfenj/qutebrowser
class NeighborList(collections.abc.Sequence):

    """A list of items which saves its current position.

    Class attributes:
        Modes: Different modes, see constructor documentation.

    Attributes:
        fuzzyval: The value which is currently set but not in the list.
        _idx: The current position in the list.
        _items: A list of all items, accessed through item property.
        _mode: The current mode.
    """

    Modes = enum.Enum('Modes', ['edge', 'exception'])

    def __init__(self, items=None, default=_UNSET, mode=Modes.exception):
        """Constructor.

        Args:
            items: The list of items to iterate in.
            _default: The initially selected value.
            _mode: Behavior when the first/last item is reached.
                   Modes.edge: Go to the first/last item
                   Modes.exception: Raise an IndexError.
        """
        if not isinstance(mode, self.Modes):
            raise TypeError("Mode {} is not a Modes member!".format(mode))
        if items is None:
            self._items = []
        else:
            self._items = list(items)
        self._default = default
        if default is not _UNSET:
            self._idx = self._items.index(default)
        else:
            self._idx = None
        self._mode = mode
        self.fuzzyval = None

    def __getitem__(self, key):
        return self._items[key]

    def __len__(self):
        return len(self._items)

    def __repr__(self):
        return utils.get_repr(self, items=self._items, mode=self._mode,
                              idx=self._idx, fuzzyval=self.fuzzyval)

    def _snap_in(self, offset):
        """Set the current item to the closest item to self.fuzzyval.

        Args:
            offset: negative to get the next smaller item, positive for the
                    next bigger one.

        Return:
            True if the value snapped in (changed),
            False when the value already was in the list.
        """
        op = operator.le if offset < 0 else operator.ge
        items = [(idx, e) for (idx, e) in enumerate(self._items)
                 if op(e, self.fuzzyval)]
        if items:
            item = min(items, key=lambda tpl: abs(self.fuzzyval - tpl[1]))
        else:
            sorted_items = sorted(((idx, e) for (idx, e) in
                                   enumerate(self.items)), key=lambda e: e[1])
            idx = 0 if offset < 0 else -1
            item = sorted_items[idx]
        self._idx = item[0]
        return self.fuzzyval not in self._items

    def _get_new_item(self, offset):
        """Logic for getitem to get the item at offset.

        Args:
            offset: The offset of the current item, relative to the last one.

        Return:
            The new item.
        """
        try:
            if self._idx + offset >= 0:
                new = self._items[self._idx + offset]
            else:
                raise IndexError
        except IndexError:
            if self._mode == self.Modes.edge:
                assert offset != 0
                if offset > 0:
                    new = self.lastitem()
                else:
                    new = self.firstitem()
            elif self._mode == self.Modes.exception:  # pragma: no branch
                raise
        else:
            self._idx += offset
        return new

    @property
    def items(self):
        """Getter for items, which should not be set."""
        return self._items

    def getitem(self, offset):
        """Get the item with a relative position.

        Args:
            offset: The offset of the current item, relative to the last one.

        Return:
            The new item.
        """
        log.misc.debug("{} items, idx {}, offset {}".format(
            len(self._items), self._idx, offset))
        if not self._items:
            raise IndexError("No items found!")
        if self.fuzzyval is not None:
            # Value has been set to something not in the list, so we snap in to
            # the closest value in the right direction and count this as one
            # step towards offset.
            snapped = self._snap_in(offset)
            if snapped and offset > 0:
                offset -= 1
            elif snapped:
                offset += 1
            self.fuzzyval = None
        return self._get_new_item(offset)

    def curitem(self):
        """Get the current item in the list."""
        if self._idx is not None:
            return self._items[self._idx]
        else:
            raise IndexError("No current item!")

    def nextitem(self):
        """Get the next item in the list."""
        return self.getitem(1)

    def previtem(self):
        """Get the previous item in the list."""
        return self.getitem(-1)

    def firstitem(self):
        """Get the first item in the list."""
        if not self._items:
            raise IndexError("No items found!")
        self._idx = 0
        return self.curitem()

    def lastitem(self):
        """Get the last item in the list."""
        if not self._items:
            raise IndexError("No items found!")
        self._idx = len(self._items) - 1
        return self.curitem()

    def reset(self):
        """Reset the position to the default."""
        if self._default is _UNSET:
            raise ValueError("No default set!")
        self._idx = self._items.index(self._default)
        return self.curitem()
コード例 #17
0
import enum
from logging import getLogger

from reversi_zero.agent.player import HistoryItem
from reversi_zero.agent.player import ReversiPlayer
from reversi_zero.config import Config
from reversi_zero.env.reversi_env import Player, ReversiEnv
from reversi_zero.lib.bitboard import find_correct_moves
from reversi_zero.lib.model_helpler import load_best_model_weight, reload_newest_next_generation_model_if_changed

logger = getLogger(__name__)

GameEvent = enum.Enum("GameEvent", "update ai_move over pass")


class PlayWithHuman:
    def __init__(self, config: Config):
        self.config = config
        self.human_color = None
        self.observers = []
        self.env = ReversiEnv().reset()
        self.model = self._load_model()
        self.ai = None  # type: ReversiPlayer
        self.last_evaluation = None
        self.last_history = None  # type: HistoryItem

    def add_observer(self, observer_func):
        self.observers.append(observer_func)

    def notify_all(self, event):
        for ob_func in self.observers:
コード例 #18
0
from hat.asn1 import common
from hat.asn1 import doc
from hat.asn1.common import (Data, Value, Boolean, Integer, BitString,
                             OctetString, Null, ObjectIdentifier, String,
                             External, Real, Enumerated, EmbeddedPDV, Choice,
                             Set, SetOf, Sequence, SequenceOf, Entity,
                             is_oid_eq)

__all__ = [
    'Data', 'Value', 'Boolean', 'Integer', 'BitString', 'OctetString', 'Null',
    'ObjectIdentifier', 'String', 'External', 'Real', 'Enumerated',
    'EmbeddedPDV', 'Choice', 'Set', 'SetOf', 'Sequence', 'SequenceOf',
    'Entity', 'is_oid_eq', 'Encoding', 'Encoder', 'Repository'
]

Encoding = enum.Enum('Encoding', ['BER'])


class Repository:
    """ASN.1 type definition repository.

    Repository can be initialized with multiple arguments, which can be
    instances of ``pathlib.PurePath``, ``str`` or ``Repository``.

    If an argument is of type ``pathlib.PurePath``, and path points to file
    with a suffix '.asn', ASN.1 type definitions are decoded from the file.
    Otherwise, it is assumed that path points to a directory,
    which is recursively searched for ASN.1 definitions. All decoded types
    are added to the repository. Previously added type definitions with the
    same references are replaced.
コード例 #19
0
test makes more listtransactions and getbalance calls to confirm that the
importing nodes pick up the new transactions regardless of whether rescans
happened previously.
"""

from test_framework.authproxy import JSONRPCException
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (start_nodes, connect_nodes, sync_blocks,
                                 assert_equal, set_node_times)
from decimal import Decimal

import collections
import enum
import itertools

Call = enum.Enum("Call", "single multi")
Data = enum.Enum("Data", "address pub priv")
Rescan = enum.Enum("Rescan", "no yes late_timestamp")


class Variant(collections.namedtuple("Variant", "call data rescan prune")):
    """Helper for importing one key and verifying scanned transactions."""
    def do_import(self, timestamp):
        """Call one key import RPC."""

        if self.call == Call.single:
            if self.data == Data.address:
                response, error = try_rpc(self.node.importaddress,
                                          self.address["address"], self.label,
                                          self.rescan == Rescan.yes)
            elif self.data == Data.pub:
コード例 #20
0
import logging

from dataclasses import dataclass

from typing import List, Dict, Any, Tuple, Union
from prefixcommons import curie_util
from ontobio import ontol
from ontobio import ecomap
from ontobio.io import assocparser
from ontobio.io import gaference
from ontobio.model import association
from ontobio.rdfgen import relations

logger = logging.getLogger(__name__)

FailMode = enum.Enum("FailMode", {"SOFT": "soft", "HARD": "hard"})
ResultType = enum.Enum("Result", {"PASS": "******", "WARNING": "Warning", "ERROR": "Error"})
RepairState = enum.Enum("RepairState", {"OKAY": "Okay", "REPAIRED": "Repaired", "FAILED": "Failed"})

# TestResult = collections.namedtuple("TestResult", ["result_type", "message", "result"])
class TestResult(object):
    def __init__(self, result_type: ResultType, message: str, result: List):
        self.result_type = result_type
        self.message = message
        self.result = result

"""
Send True for passes, and this returns the PASS ResultType, and if False, then
depending on the fail mode it returns either WARNING or ERROR ResultType.
"""
def result(passes: bool, fail_mode: FailMode) -> ResultType:
コード例 #21
0
# https://ctan.org/pkg/dvitype
# https://texdoc.org/serve/dvitype.pdf/0
#
# The file consists of a preamble, some number of pages, a postamble,
# and a finale. Different opcodes are allowed in different contexts,
# so the Dvi object has a parser state:
#
#   pre:       expecting the preamble
#   outer:     between pages (followed by a page or the postamble,
#              also e.g. font definitions are allowed)
#   page:      processing a page
#   post_post: state after the postamble (our current implementation
#              just stops reading)
#   finale:    the finale (unimplemented in our current implementation)

_dvistate = enum.Enum('DviState', 'pre outer inpage post_post finale')

# The marks on a page consist of text and boxes. A page also has dimensions.
Page = namedtuple('Page', 'text boxes height width descent')
Text = namedtuple('Text', 'x y font glyph width')
Box = namedtuple('Box', 'x y height width')

# Opcode argument parsing
#
# Each of the following functions takes a Dvi object and delta,
# which is the difference between the opcode and the minimum opcode
# with the same meaning. Dvi opcodes often encode the number of
# argument bytes in this delta.


def _arg_raw(dvi, delta):
コード例 #22
0
        try:
            return cls[lowered].name
        except KeyError:
            difficulties = '\n'.join(str(m).lower() for m in cls)
            raise commands.BadArgument(
                f'"{arg}"" is not a difficulty. Valid difficulties:\n{difficulties}'
            ) from None

    @classmethod
    def random_example(cls, ctx):
        return random.choice(list(cls._member_map_))


_difficulties = [n for n, v in Board.__dict__.items() if isinstance(v, classmethod)]
_difficulties.remove('from_data')
Difficulty = enum.Enum('Difficulty', _difficulties, type=_EnumConverter)

HELP_TEXT = """
The goal is to fill each space with a number
from 1 to 9, such that each row, column, and
3 x 3 box contains each number exactly **once**.
"""

INPUT_FIELD = """
Send a message in the following format:
`letter number number`
\u200b
Use `A-I` for `row` and `column`.
Use `1-9` for the number.
Use `0` or `clear` for the second number
if you want to clear the tile.