當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。