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


Python typing.Collection方法代码示例

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


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

示例1: ellipsize_recipes

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Collection [as 别名]
def ellipsize_recipes(recipes: Collection[str], recipe_folder: str,
                      n: int = 5, m: int = 50) -> str:
    """Logging helper showing recipe list

    Args:
      recipes: List of recipes
      recipe_folder: Folder name to strip from recipes.
      n: Show at most this number of recipes, with "..." if more are found.
      m: Don't show anything if more recipes than this
         (pointless to show first 5 of 5000)
    Returns:
      A string like " (htslib, samtools, ...)" or ""
    """
    if not recipes or len(recipes) > m:
        return ""
    if len(recipes) > n:
        if not isinstance(recipes, Sequence):
            recipes = list(recipes)
        recipes = recipes[:n]
        append = ", ..."
    else:
        append = ""
    return ' ('+', '.join(recipe.lstrip(recipe_folder).lstrip('/')
                     for recipe in recipes) + append + ')' 
开发者ID:bioconda,项目名称:bioconda-utils,代码行数:26,代码来源:utils.py

示例2: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Collection [as 别名]
def __init__(
        self,
        gcp_key_path: Optional[str] = None,
        # See: https://github.com/PyCQA/pylint/issues/2377
        scopes: Optional[Collection[str]] = _DEFAULT_SCOPESS,  # pylint: disable=unsubscriptable-object
        name: str = DEFAULT_LOGGER_NAME,
        transport: Type[Transport] = BackgroundThreadTransport,
        resource: Resource = _GLOBAL_RESOURCE,
        labels: Optional[Dict[str, str]] = None,
    ):
        super().__init__()
        self.gcp_key_path: Optional[str] = gcp_key_path
        # See: https://github.com/PyCQA/pylint/issues/2377
        self.scopes: Optional[Collection[str]] = scopes  # pylint: disable=unsubscriptable-object
        self.name: str = name
        self.transport_type: Type[Transport] = transport
        self.resource: Resource = resource
        self.labels: Optional[Dict[str, str]] = labels
        self.task_instance_labels: Optional[Dict[str, str]] = {} 
开发者ID:apache,项目名称:airflow,代码行数:21,代码来源:stackdriver_task_handler.py

示例3: extend

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Collection [as 别名]
def extend(cls, services: 'Collection[IServable]') -> 'List[IServable]':
        """
        Extends services list with reflection service:

        .. code-block:: python3

            from grpclib.reflection.service import ServerReflection

            services = [Greeter()]
            services = ServerReflection.extend(services)

            server = Server(services)
            ...

        Returns new services list with reflection support added.
        """
        service_names = []
        for service in services:
            service_names.append(_service_name(service))
        services = list(services)
        services.append(cls(_service_names=service_names))
        services.append(_ServerReflectionV1Alpha(_service_names=service_names))
        return services 
开发者ID:vmagamedov,项目名称:grpclib,代码行数:25,代码来源:service.py

示例4: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Collection [as 别名]
def __init__(
        self,
        services: Collection['IServable'],
        codec: Optional[CodecBase] = None,
        status_details_codec: Optional[StatusDetailsCodecBase] = None,
    ) -> None:
        """
        :param services: list of services you want to test

        :param codec: instance of a codec to encode and decode messages,
            if omitted ``ProtoCodec`` is used by default

        :param status_details_codec: instance of a status details codec to
            encode and decode error details in a trailing metadata, if omitted
            ``ProtoStatusDetailsCodec`` is used by default
        """
        self._services = services
        self._codec = codec
        self._status_details_codec = status_details_codec 
开发者ID:vmagamedov,项目名称:grpclib,代码行数:21,代码来源:testing.py

示例5: param

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Collection [as 别名]
def param(
    *values: object,
    marks: "Union[MarkDecorator, typing.Collection[Union[MarkDecorator, Mark]]]" = (),
    id: Optional[str] = None
) -> ParameterSet:
    """Specify a parameter in `pytest.mark.parametrize`_ calls or
    :ref:`parametrized fixtures <fixture-parametrize-marks>`.

    .. code-block:: python

        @pytest.mark.parametrize(
            "test_input,expected",
            [("3+5", 8), pytest.param("6*9", 42, marks=pytest.mark.xfail),],
        )
        def test_eval(test_input, expected):
            assert eval(test_input) == expected

    :param values: variable args of the values of the parameter set, in order.
    :keyword marks: a single mark or a list of marks to be applied to this parameter set.
    :keyword str id: the id to attribute to this parameter set.
    """
    return ParameterSet.param(*values, marks=marks, id=id) 
开发者ID:pytest-dev,项目名称:pytest,代码行数:24,代码来源:__init__.py

示例6: param

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Collection [as 别名]
def param(
        cls,
        *values: object,
        marks: "Union[MarkDecorator, typing.Collection[Union[MarkDecorator, Mark]]]" = (),
        id: Optional[str] = None
    ) -> "ParameterSet":
        if isinstance(marks, MarkDecorator):
            marks = (marks,)
        else:
            # TODO(py36): Change to collections.abc.Collection.
            assert isinstance(marks, (collections.abc.Sequence, set))

        if id is not None:
            if not isinstance(id, str):
                raise TypeError(
                    "Expected id to be a string, got {}: {!r}".format(type(id), id)
                )
            id = ascii_escaped(id)
        return cls(values, marks, id) 
开发者ID:pytest-dev,项目名称:pytest,代码行数:21,代码来源:structures.py

示例7: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Collection [as 别名]
def __init__(
        self,
        presentation_schema,
        presentation_context,
        seed_generator: SlideSeedGenerator,
        num_slides: int,
        used_elements: Optional[Collection[Union[str, ImageData]]] = None,
        prohibited_generators: Optional[Collection[SlideGeneratorData]] = None,
        int_seed: Optional[int] = None,
    ):
        self.presentation_schema = presentation_schema
        self.presentation_context = presentation_context
        self.seed_generator: SlideSeedGenerator = seed_generator
        self.num_slides = num_slides
        self.used_elements = used_elements
        self.prohibited_generators = prohibited_generators
        self.int_seed = int_seed 
开发者ID:korymath,项目名称:talk-generator,代码行数:19,代码来源:presentation_schema.py

示例8: read_service_instance_names

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Collection [as 别名]
def read_service_instance_names(
    service: str, instance_type: str, cluster: str, soa_dir: str
) -> Collection[Tuple[str, str]]:
    instance_list = []
    conf_file = f"{instance_type}-{cluster}"
    config = service_configuration_lib.read_extra_service_information(
        service, conf_file, soa_dir=soa_dir, deepcopy=False,
    )
    config = filter_templates_from_config(config)
    if instance_type == "tron":
        for job_name, job in config.items():
            action_names = list(job.get("actions", {}).keys())
            for name in action_names:
                instance = f"{job_name}.{name}"
                instance_list.append((service, instance))
    else:
        for instance in config:
            instance_list.append((service, instance))
    return instance_list 
开发者ID:Yelp,项目名称:paasta,代码行数:21,代码来源:utils.py

示例9: undrain_tasks

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Collection [as 别名]
def undrain_tasks(
    to_undrain: Collection[MarathonTask],
    leave_draining: Collection[MarathonTask],
    drain_method: drain_lib.DrainMethod,
    log_deploy_error: LogDeployError,
) -> None:
    # If any tasks on the new app happen to be draining (e.g. someone reverts to an older version with
    # `paasta mark-for-deployment`), then we should undrain them.

    async def undrain_task(task: MarathonTask) -> None:
        if task not in leave_draining:
            if task.state == "TASK_UNREACHABLE":
                return
            try:
                await drain_method.stop_draining(task)
            except Exception:
                log_deploy_error(
                    f"Ignoring exception during stop_draining of task {task.id}: {traceback.format_exc()}"
                )

    if to_undrain:
        a_sync.block(
            asyncio.wait,
            [asyncio.ensure_future(undrain_task(task)) for task in to_undrain],
        ) 
开发者ID:Yelp,项目名称:paasta,代码行数:27,代码来源:setup_marathon_job.py

示例10: crossover_bounce

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Collection [as 别名]
def crossover_bounce(
    new_config: BounceMethodConfigDict,
    new_app_running: bool,
    happy_new_tasks: Collection,
    old_non_draining_tasks: Sequence,
    margin_factor=1.0,
) -> BounceMethodResult:
    """Starts a new app if necessary; slowly kills old apps as instances of the new app become happy.

    See the docstring for brutal_bounce() for parameters and return value.
    """

    assert margin_factor > 0
    assert margin_factor <= 1

    needed_count = max(
        int(math.ceil(new_config["instances"] * margin_factor)) - len(happy_new_tasks),
        0,
    )

    return {
        "create_app": not new_app_running,
        "tasks_to_drain": set(old_non_draining_tasks[needed_count:]),
    } 
开发者ID:Yelp,项目名称:paasta,代码行数:26,代码来源:bounce_lib.py

示例11: get_smartstack_status_human

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Collection [as 别名]
def get_smartstack_status_human(
    registration: str, expected_backends_per_location: int, locations: Collection[Any],
) -> List[str]:
    if len(locations) == 0:
        return [f"Smartstack: ERROR - {registration} is NOT in smartstack at all!"]

    output = ["Smartstack:"]
    output.append(f"  Haproxy Service Name: {registration}")
    output.append(f"  Backends:")
    for location in locations:
        backend_status = haproxy_backend_report(
            expected_backends_per_location, location.running_backends_count
        )
        output.append(f"    {location.name} - {backend_status}")

        if location.backends:
            backends_table = build_smartstack_backends_table(location.backends)
            output.extend([f"      {line}" for line in backends_table])

    return output 
开发者ID:Yelp,项目名称:paasta,代码行数:22,代码来源:status.py

示例12: copula_log_lik

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Collection [as 别名]
def copula_log_lik(self, param: Union[float, Collection[float]]) -> float:
        """
        Calculates the log likelihood after setting the new parameters (inserted from the optimizer) of the copula

        Parameters
        ----------
        param: ndarray
            Parameters of the copula

        Returns
        -------
        float
            Negative log likelihood of the copula

        """
        try:
            self.copula.params = param
            return -self.copula.log_lik(self.data, to_pobs=False)
        except ValueError:  # error encountered when setting invalid parameters
            return np.inf 
开发者ID:DanielBok,项目名称:copulae,代码行数:22,代码来源:max_likelihood.py

示例13: _process_vector_observation

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Collection [as 别名]
def _process_vector_observation(
    obs_index: int,
    shape: Tuple[int, ...],
    agent_info_list: Collection[
        AgentInfoProto
    ],  # pylint: disable=unsubscriptable-object
) -> np.ndarray:
    if len(agent_info_list) == 0:
        return np.zeros((0, shape[0]), dtype=np.float32)
    np_obs = np.array(
        [
            agent_obs.observations[obs_index].float_data.data
            for agent_obs in agent_info_list
        ],
        dtype=np.float32,
    )
    _raise_on_nan_and_inf(np_obs, "observations")
    return np_obs 
开发者ID:StepNeverStop,项目名称:RLs,代码行数:20,代码来源:rpc_utils.py

示例14: pass_turn

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Collection [as 别名]
def pass_turn(self, no_action=False, ignored_cps: typing.Collection[ControlPoint]=None):
        logging.info("Pass turn")
        for event in self.events:
            if self.settings.version == "dev":
                # don't damage player CPs in by skipping in dev mode
                if isinstance(event, UnitsDeliveryEvent):
                    event.skip()
            else:
                event.skip()

        for cp in self.theater.enemy_points():
            self._commision_units(cp)
        self._budget_player()

        if not no_action:
            for cp in self.theater.player_points():
                cp.base.affect_strength(+PLAYER_BASE_STRENGTH_RECOVERY)

        self.ignored_cps = []
        if ignored_cps:
            self.ignored_cps = ignored_cps

        self.events = []  # type: typing.List[Event]
        self._generate_events()
        #self._generate_globalinterceptions() 
开发者ID:shdwp,项目名称:dcs_liberation,代码行数:27,代码来源:game.py

示例15: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Collection [as 别名]
def __init__(self, entity: t.Type[Entity], fields: t.Collection[str] = None):
        self.entity = entity
        self.mapped_fields = fields 
开发者ID:pcah,项目名称:python-clean-architecture,代码行数:5,代码来源:repository.py


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