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


Python typing.Hashable方法代码示例

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


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

示例1: schedule_task

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Hashable [as 别名]
def schedule_task(self, task_id: t.Hashable, task_data: t.Any) -> None:
        """
        Schedules a task.

        `task_data` is passed to the `Scheduler._scheduled_task()` coroutine.
        """
        log.trace(f"{self.cog_name}: scheduling task #{task_id}...")

        if task_id in self._scheduled_tasks:
            log.debug(
                f"{self.cog_name}: did not schedule task #{task_id}; task was already scheduled."
            )
            return

        task = asyncio.create_task(self._scheduled_task(task_data))
        task.add_done_callback(partial(self._task_done_callback, task_id))

        self._scheduled_tasks[task_id] = task
        log.debug(f"{self.cog_name}: scheduled task #{task_id} {id(task)}.") 
开发者ID:python-discord,项目名称:bot,代码行数:21,代码来源:scheduling.py

示例2: cancel_task

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Hashable [as 别名]
def cancel_task(self, task_id: t.Hashable, ignore_missing: bool = False) -> None:
        """
        Unschedule the task identified by `task_id`.

        If `ignore_missing` is True, a warning will not be sent if a task isn't found.
        """
        log.trace(f"{self.cog_name}: cancelling task #{task_id}...")
        task = self._scheduled_tasks.get(task_id)

        if not task:
            if not ignore_missing:
                log.warning(f"{self.cog_name}: failed to unschedule {task_id} (no task found).")
            return

        del self._scheduled_tasks[task_id]
        task.cancel()

        log.debug(f"{self.cog_name}: unscheduled task #{task_id} {id(task)}.") 
开发者ID:python-discord,项目名称:bot,代码行数:20,代码来源:scheduling.py

示例3: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Hashable [as 别名]
def __init__(self,
                 team_type: Type['Team'],
                 identifier: Union[Hashable, str, int],  # workaround mypy bug
                 access_token=None) -> None:
        if not isinstance(team_type, type):
            raise TypeError('team_type must be a type, not ' + repr(team_type))
        from .team import Team  # noqa: F811
        if not issubclass(team_type, Team):
            raise TypeError('team_type must be a subclass of {0.__module__}.'
                            '{0.__qualname__}'.format(Team))
        elif not callable(getattr(identifier, '__hash__')):
            raise TypeError('identifier must be hashable, not ' +
                            repr(identifier))
        self.team_type = cast(Type[Team], team_type)
        self.identifier = identifier  # type: Union[Hashable, str, int]
        self.access_token = access_token 
开发者ID:spoqa,项目名称:geofront,代码行数:18,代码来源:identity.py

示例4: finish_trajectory

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Hashable [as 别名]
def finish_trajectory(self, key: Hashable = None) -> types.TrajectoryWithRew:
        """Complete the trajectory labelled with `key`.

        Args:
            key: key uniquely identifying which in-progress trajectory to remove.

        Returns:
            traj: list of completed trajectories popped from
                `self.partial_trajectories`.
        """
        part_dicts = self.partial_trajectories[key]
        del self.partial_trajectories[key]
        out_dict_unstacked = collections.defaultdict(list)
        for part_dict in part_dicts:
            for key, array in part_dict.items():
                out_dict_unstacked[key].append(array)
        out_dict_stacked = {
            key: np.stack(arr_list, axis=0)
            for key, arr_list in out_dict_unstacked.items()
        }
        traj = types.TrajectoryWithRew(**out_dict_stacked)
        assert traj.rews.shape[0] == traj.acts.shape[0] == traj.obs.shape[0] - 1
        return traj 
开发者ID:HumanCompatibleAI,项目名称:imitation,代码行数:25,代码来源:rollout.py

示例5: incompatibilities_for

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Hashable [as 别名]
def incompatibilities_for(
        self, package, version
    ):  # type: (Hashable, Any) -> List[Incompatibility]
        """
        Returns the incompatibilities of a given package and version
        """
        dependencies = self.dependencies_for(package, version)
        package_constraint = Constraint(package, Range(version, version, True, True))

        incompatibilities = []
        for dependency in dependencies:
            constraint = self.convert_dependency(dependency)

            if not isinstance(constraint, Constraint):
                constraint = Constraint(package, constraint)

            incompatibility = Incompatibility(
                [Term(package_constraint, True), Term(constraint, False)],
                cause=DependencyCause(),
            )
            incompatibilities.append(incompatibility)

        return incompatibilities 
开发者ID:sdispater,项目名称:mixology,代码行数:25,代码来源:package_source.py

示例6: decide

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Hashable [as 别名]
def decide(self, package, version):  # type: (Hashable, Any) -> None
        """
        Adds an assignment of package as a decision
        and increments the decision level.
        """
        # When we make a new decision after backtracking, count an additional
        # attempted solution. If we backtrack multiple times in a row, though, we
        # only want to count one, since we haven't actually started attempting a
        # new solution.
        if self._backtracking:
            self._attempted_solutions += 1

        self._backtracking = False
        self._decisions[package] = version

        self._assign(
            Assignment.decision(
                package, version, self.decision_level, len(self._assignments)
            )
        ) 
开发者ID:sdispater,项目名称:mixology,代码行数:22,代码来源:partial_solution.py

示例7: uniform_undirected_graph_device

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Hashable [as 别名]
def uniform_undirected_graph_device(
        edges: Iterable[Iterable[ops.Qid]],
        edge_label: Optional[UndirectedGraphDeviceEdge] = None
) -> UndirectedGraphDevice:
    """An undirected graph device all of whose edges are the same.

    Args:
        edges: The edges.
        edge_label: The label to apply to all edges. Defaults to None.
    """

    labelled_edges: Dict[Iterable[Hashable], Any] = {
        frozenset(edge): edge_label for edge in edges
    }
    device_graph = UndirectedHypergraph(labelled_edges=labelled_edges)
    return UndirectedGraphDevice(device_graph=device_graph) 
开发者ID:quantumlib,项目名称:Cirq,代码行数:18,代码来源:uniform_graph_device.py

示例8: addMarketEvent

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Hashable [as 别名]
def addMarketEvent(
            self, _symbol: typing.Hashable, _data: DataStruct
    ) -> ReturnMarket:
        """
        add new tick data into market register, and add event

        :param _symbol:
        :param _data:
        :return:
        """
        for k in self.symbol_dict[_symbol]:
            # add event for each strategy if necessary
            for strategy in self.register_dict[k].strategy_set:
                self.engine.addEvent(MarketEvent(k, strategy, _symbol, _data))
        logging.debug('Data({}) {}'.format(_symbol, _data.toDict()))
        return ReturnMarket(_symbol, _data) 
开发者ID:ppaanngggg,项目名称:ParadoxTrading,代码行数:18,代码来源:MarketSupply.py

示例9: find_as_list

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Hashable [as 别名]
def find_as_list(
        self,
        database: str,
        collection: str,
        query: Dict[Hashable, Any] = None,
        projection: Dict[Hashable, Any] = None,
    ) -> Iterable:
        """
        Do a find operation on a mongo collection, but return the data as a list

        Args:
            database: db name
            collection: collection name
            query: a dictionary providing the criteria for the find command
            projection: a dictionary that gives the projection - the fields to return.

        Returns:
            a list representation of the returned data.

        """
        cursor = self.find_as_cursor(
            database=database, collection=collection, query=query, projection=projection
        )
        return [c for c in cursor] 
开发者ID:r-bioinformatics,项目名称:edgePy,代码行数:26,代码来源:mongo_wrapper.py

示例10: _sample_group_dict

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Hashable [as 别名]
def _sample_group_dict(groups_list: List[str], samples: np.array):
        """
        Converts data in the form ['group1', 'group1', 'group2', 'group2']
        to the form  {'group1': ['sample1', 'sample2'], 'group2': ['sample3', 'sample4'}

        Args:
            groups_list: group names in a list, in the same order as samples.

        Returns:
            dictionary containing the sample types, each with a list of samples.

        """
        d: Dict[Hashable, Any] = {}
        log.info(samples)
        for idx, group in enumerate(groups_list):
            if group not in d:
                d[group] = []
            d[group].append(samples[idx])
        return d 
开发者ID:r-bioinformatics,项目名称:edgePy,代码行数:21,代码来源:DGEList.py

示例11: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Hashable [as 别名]
def __init__(
            self, simulation: 'Simulation', data_override: Dict[str, Array], delta: Array, costs: Array,
            start_time: float, end_time: float, iteration_stats: Dict[Hashable, SolverStats]) -> None:
        """Structure simulation results."""
        self.simulation = simulation
        self.product_data = update_matrices(
            simulation.product_data,
            {k: (v, v.dtype) for k, v in data_override.items()}
        )
        self.delta = delta
        self.costs = costs
        self.computation_time = end_time - start_time
        self.fp_converged = np.array(
            [iteration_stats[t].converged for t in simulation.unique_market_ids], dtype=np.bool
        )
        self.fp_iterations = np.array(
            [iteration_stats[t].iterations for t in simulation.unique_market_ids], dtype=np.int
        )
        self.contraction_evaluations = np.array(
            [iteration_stats[t].evaluations for t in simulation.unique_market_ids], dtype=np.int
        )
        self._data_override = data_override 
开发者ID:jeffgortmaker,项目名称:pyblp,代码行数:24,代码来源:simulation_results.py

示例12: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Hashable [as 别名]
def __init__(self):
        # Keep track of the child cog's name so the logs are clear.
        self.cog_name = self.__class__.__name__

        self._scheduled_tasks: t.Dict[t.Hashable, asyncio.Task] = {} 
开发者ID:python-discord,项目名称:bot,代码行数:7,代码来源:scheduling.py

示例13: _task_done_callback

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Hashable [as 别名]
def _task_done_callback(self, task_id: t.Hashable, done_task: asyncio.Task) -> None:
        """
        Delete the task and raise its exception if one exists.

        If `done_task` and the task associated with `task_id` are different, then the latter
        will not be deleted. In this case, a new task was likely rescheduled with the same ID.
        """
        log.trace(f"{self.cog_name}: performing done callback for task #{task_id} {id(done_task)}.")

        scheduled_task = self._scheduled_tasks.get(task_id)

        if scheduled_task and done_task is scheduled_task:
            # A task for the ID exists and its the same as the done task.
            # Since this is the done callback, the task is already done so no need to cancel it.
            log.trace(f"{self.cog_name}: deleting task #{task_id} {id(done_task)}.")
            del self._scheduled_tasks[task_id]
        elif scheduled_task:
            # A new task was likely rescheduled with the same ID.
            log.debug(
                f"{self.cog_name}: the scheduled task #{task_id} {id(scheduled_task)} "
                f"and the done task {id(done_task)} differ."
            )
        elif not done_task.cancelled():
            log.warning(
                f"{self.cog_name}: task #{task_id} not found while handling task {id(done_task)}! "
                f"A task somehow got unscheduled improperly (i.e. deleted but not cancelled)."
            )

        with contextlib.suppress(asyncio.CancelledError):
            exception = done_task.exception()
            # Log the exception if one exists.
            if exception:
                log.error(
                    f"{self.cog_name}: error in task #{task_id} {id(done_task)}!",
                    exc_info=exception
                ) 
开发者ID:python-discord,项目名称:bot,代码行数:38,代码来源:scheduling.py

示例14: get_value_hash

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Hashable [as 别名]
def get_value_hash(self) -> tp.Hashable:
        hashes: tp.List[tp.Hashable] = []
        for ind in self.indices:
            c = self.choices[int(ind)]
            const = isinstance(c, core.Constant) or not isinstance(c, core.Parameter)
            hashes.append(int(ind) if const else (int(ind), c.get_value_hash()))
        return tuple(hashes) if len(hashes) > 1 else hashes[0] 
开发者ID:facebookresearch,项目名称:nevergrad,代码行数:9,代码来源:choice.py

示例15: get_value_hash

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Hashable [as 别名]
def get_value_hash(self) -> tp.Hashable:
        """Hashable object representing the current value of the instance
        """
        val = self.value
        if isinstance(val, (str, bytes, float, int)):
            return val
        elif isinstance(val, np.ndarray):
            return val.tobytes()
        else:
            raise utils.NotSupportedError(f"Value hash is not supported for object {self.name}") 
开发者ID:facebookresearch,项目名称:nevergrad,代码行数:12,代码来源:core.py


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