当前位置: 首页>>代码示例>>Python>>正文


Python typing.Sized方法代码示例

本文整理汇总了Python中typing.Sized方法的典型用法代码示例。如果您正苦于以下问题:Python typing.Sized方法的具体用法?Python typing.Sized怎么用?Python typing.Sized使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在typing的用法示例。


在下文中一共展示了typing.Sized方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: zip_equal

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sized [as 别名]
def zip_equal(*args: Union[Sized, Iterable]) -> Iterable[Tuple]:
    """
    zip over the given iterables, but enforce that all of them exhaust simultaneously.

    Examples
    --------
    >>> zip_equal([1, 2, 3], [4, 5, 6]) # ok
    >>> zip_equal([1, 2, 3], [4, 5, 6, 7]) # raises ValueError
    # ValueError is raised even if the lengths are not known
    >>> zip_equal([1, 2, 3], map(np.sqrt, [4, 5, 6])) # ok
    >>> zip_equal([1, 2, 3], map(np.sqrt, [4, 5, 6, 7])) # raises ValueError
    """
    if not args:
        return

    lengths = []
    all_lengths = []
    for arg in args:
        try:
            lengths.append(len(arg))
            all_lengths.append(len(arg))
        except TypeError:
            all_lengths.append('?')

    if lengths and not all(x == lengths[0] for x in lengths):
        from .checks import join
        raise ValueError(f'The arguments have different lengths: {join(all_lengths)}.')

    iterables = [iter(arg) for arg in args]
    while True:
        result = []
        for it in iterables:
            with suppress(StopIteration):
                result.append(next(it))

        if len(result) != len(args):
            break
        yield tuple(result)

    if len(result) != 0:
        raise ValueError(f'The iterables did not exhaust simultaneously.') 
开发者ID:neuro-ml,项目名称:deep_pipe,代码行数:43,代码来源:itertools.py

示例2: test_sized

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sized [as 别名]
def test_sized(self):
        assert isinstance([], typing.Sized)
        assert not isinstance(42, typing.Sized) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:5,代码来源:test_typing.py

示例3: predict_batch

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sized [as 别名]
def predict_batch(self, observations: [Sized, Iterable]) -> np.ndarray:
        """
        Returns a vector of actions chosen at random.
        :param observations: Represents a vector of observations. Only used in determining the size
        of the returned array.
        :return: Numpy array containing the action chosen for each observation.
        """

        if not self.use_block:
            return np.random.randint(0, high=int(self.n_actions), size=(len(observations),))
        self._i += 1
        return self.noise[: len(observations), self._i % self.samples] 
开发者ID:Guillemdb,项目名称:FractalAI,代码行数:14,代码来源:model.py

示例4: serialize

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sized [as 别名]
def serialize(self, instance: Sized):
        _check_type_and_size(instance, self.actual_type, len(self.items), SerializationError)
        return self.actual_type(serialize(o, t) for t, o in zip(self.items, instance)) 
开发者ID:zyfra,项目名称:ebonite,代码行数:5,代码来源:dataset_type.py

示例5: contains

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sized [as 别名]
def contains(self, x):
        if not isinstance(x, Sized):
            return False

        if not (self.min_seq_length <= len(x) <= self.max_seq_length):
            return False

        return all([self.space.contains(el) for el in x]) 
开发者ID:facebookresearch,项目名称:habitat-api,代码行数:10,代码来源:spaces.py

示例6: are_none

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sized [as 别名]
def are_none(sequences: Sequence[Sized]) -> bool:
    """
    Returns True if all sequences are None.
    """
    if not sequences:
        return True
    return all(s is None for s in sequences) 
开发者ID:awslabs,项目名称:sockeye,代码行数:9,代码来源:data_io.py

示例7: are_token_parallel

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sized [as 别名]
def are_token_parallel(sequences: Sequence[Sized]) -> bool:
    """
    Returns True if all sequences in the list have the same length.
    """
    if not sequences or len(sequences) == 1:
        return True
    return all(len(s) == len(sequences[0]) for s in sequences) 
开发者ID:awslabs,项目名称:sockeye,代码行数:9,代码来源:data_io.py

示例8: test_sized

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sized [as 别名]
def test_sized(self):
        self.assertIsInstance([], typing.Sized)
        self.assertNotIsInstance(42, typing.Sized) 
开发者ID:ShikyoKira,项目名称:Project-New-Reign---Nemesis-Main,代码行数:5,代码来源:test_typing.py

示例9: _get_all_dimensions

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sized [as 别名]
def _get_all_dimensions(batch: Sequence, level: int = 0, res: Optional[List[List[int]]] = None) -> List[List[int]]:
    """Return all presented element sizes of each dimension.

    Args:
        batch: Data array.
        level: Recursion level.
        res: List containing element sizes of each dimension.

    Return:
        List, i-th element of which is list containing all presented sized of batch's i-th dimension.

    Examples:
        >>> x = [[[1], [2, 3]], [[4], [5, 6, 7], [8, 9]]]
        >>> _get_all_dimensions(x)
        [[2], [2, 3], [1, 2, 1, 3, 2]]

    """
    if not level:
        res = [[len(batch)]]
    if len(batch) and isinstance(batch[0], Sized) and not isinstance(batch[0], str):
        level += 1
        if len(res) <= level:
            res.append([])
        for item in batch:
            res[level].append(len(item))
            _get_all_dimensions(item, level, res)
    return res 
开发者ID:deepmipt,项目名称:DeepPavlov,代码行数:29,代码来源:utils.py

示例10: from_parameters

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sized [as 别名]
def from_parameters(cls, parameters: Sequence[float]) -> Sized:
        """Construct Robot from Kinematic Chain parameters."""
        # FIXME: assumes MDH revolute robot
        kc = MDHKinematicChain.from_parameters(parameters)
        return cls(kinematic_chain=kc) 
开发者ID:nnadeau,项目名称:pybotics,代码行数:7,代码来源:robot.py

示例11: predict_batch

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sized [as 别名]
def predict_batch(self, observations: [Sized, Iterable]) -> np.ndarray:
        """
        Returns a vector of actions chosen at random.
        :param observations: Represents a vector of observations. Only used in determining the size
        of the returned array.
        :return: Numpy array containing the action chosen for each observation.
        """

        if not self.use_block:
            return np.random.randint(0, high=int(self.n_actions), size=(len(observations),))
        self._i += 1
        return self.noise[:len(observations), self._i % self.samples] 
开发者ID:FragileTech,项目名称:FractalAI,代码行数:14,代码来源:model.py

示例12: _count_values

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sized [as 别名]
def _count_values(dictionary: Dict[str, Sized]) -> int:
        return sum(len(e) for e in dictionary.values()) 
开发者ID:fkie-cad,项目名称:FACT_core,代码行数:4,代码来源:miscellaneous_routes.py

示例13: plot_assignments

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Sized [as 别名]
def plot_assignments(
    assignments: torch.Tensor,
    im: Optional[AxesImage] = None,
    figsize: Tuple[int, int] = (5, 5),
    classes: Optional[Sized] = None,
) -> AxesImage:
    # language=rst
    """
    Plot the two-dimensional neuron assignments.

    :param assignments: Vector of neuron label assignments.
    :param im: Used for re-drawing the assignments plot.
    :param figsize: Horizontal, vertical figure size in inches.
    :param classes: Iterable of labels for colorbar ticks corresponding to data labels.
    :return: Used for re-drawing the assigments plot.
    """
    locals_assignments = assignments.detach().clone().cpu().numpy()
    if not im:
        fig, ax = plt.subplots(figsize=figsize)
        ax.set_title("Categorical assignments")

        if classes is None:
            color = plt.get_cmap("RdBu", 11)
            im = ax.matshow(
                locals_assignments, cmap=color, vmin=-1.5, vmax=9.5
            )
        else:
            color = plt.get_cmap("RdBu", len(classes) + 1)
            im = ax.matshow(
                locals_assignments,
                cmap=color,
                vmin=-1.5,
                vmax=len(classes) - 0.5,
            )

        div = make_axes_locatable(ax)
        cax = div.append_axes("right", size="5%", pad=0.05)

        if classes is None:
            cbar = plt.colorbar(im, cax=cax, ticks=list(range(-1, 11)))
            cbar.ax.set_yticklabels(["none"] + list(range(10)))
        else:
            cbar = plt.colorbar(im, cax=cax, ticks=np.arange(-1, len(classes)))
            cbar.ax.set_yticklabels(["none"] + list(classes))

        ax.set_xticks(())
        ax.set_yticks(())
        fig.tight_layout()
    else:
        im.set_data(locals_assignments)

    return im 
开发者ID:BINDS-LAB-UMASS,项目名称:bindsnet,代码行数:54,代码来源:plotting.py


注:本文中的typing.Sized方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。