本文整理匯總了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 + ')'
示例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]] = {}
示例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
示例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
示例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)
示例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)
示例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
示例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
示例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],
)
示例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:]),
}
示例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
示例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
示例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
示例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()
示例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