當前位置: 首頁>>代碼示例>>Python>>正文


Python typing.Tuple方法代碼示例

本文整理匯總了Python中typing.Tuple方法的典型用法代碼示例。如果您正苦於以下問題:Python typing.Tuple方法的具體用法?Python typing.Tuple怎麽用?Python typing.Tuple使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在typing的用法示例。


在下文中一共展示了typing.Tuple方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: calculate_page_limit_and_offset

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Tuple [as 別名]
def calculate_page_limit_and_offset(paginate: bool, page_size: int, page: int, result_length: int,
                                    offset: int, limit: int) -> Tuple[int, int]:
    """Calculate page limit and offset for pagination.
    :param paginate: Showing whether pagination is enable/disable.
    :param page_size: Number maximum elements showed in a page.
    :param page: page number.
    :param result_length: Length of the list containing desired elements.
    :param offset: offset value.
    :param limit: page limit.
    :return: page limit and offset.
    """
    if limit is not None:
        page_size = limit
    if paginate is True:
        if offset is None:
            offset = (page - 1) * page_size
        limit = page_size
    else:
        offset = 0
        limit = result_length

    return limit, offset 
開發者ID:HTTP-APIs,項目名稱:hydrus,代碼行數:24,代碼來源:crud_helpers.py

示例2: add_pagination_iri_mappings

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Tuple [as 別名]
def add_pagination_iri_mappings(template: str,
                                template_mapping: List[IriTemplateMapping]
                                ) -> Tuple[str, List[IriTemplateMapping]]:
    """Add various pagination related to variable to the IRI template and also adds mappings for them.
    :param template: IriTemplate string.
    :param template_mapping: List of template mappings.
    :return: Final IriTemplate string and related list of mappings.
    """
    paginate_variables = ["pageIndex", "limit", "offset"]
    for i in range(len(paginate_variables)):
        # If final variable then do not add space and comma and add the final parentheses
        if i == len(paginate_variables) - 1:
            template += "{})".format(paginate_variables[i])
        else:
            template += "{}, ".format(paginate_variables[i])
        mapping = IriTemplateMapping(variable=paginate_variables[i], prop=paginate_variables[i])
        template_mapping.append(mapping)
    return template, template_mapping 
開發者ID:HTTP-APIs,項目名稱:hydrus,代碼行數:20,代碼來源:helpers.py

示例3: get_link_props_for_multiple_objects

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Tuple [as 別名]
def get_link_props_for_multiple_objects(path: str,
                                        object_list: List[Dict[str, Any]]
                                        ) -> Tuple[List[Dict[str, Any]], bool]:
    """
    Get link_props of multiple objects.
    :param path: Path of the collection or non-collection class.
    :param object_list: List of objects being inserted.
    :return: List of link properties processed with the help of get_link_props.
    """
    link_prop_list = list()
    for object_ in object_list:
        link_props, type_check = get_link_props(path, object_)
        if type_check is True:
            link_prop_list.append(link_props)
        else:
            return [], False
    return link_prop_list, True 
開發者ID:HTTP-APIs,項目名稱:hydrus,代碼行數:19,代碼來源:helpers.py

示例4: filename_to_url

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Tuple [as 別名]
def filename_to_url(filename: str, cache_dir: Union[str, Path] = None) -> Tuple[str, str]:
    """
    Return the url and etag (which may be ``None``) stored for `filename`.
    Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist.
    """
    if cache_dir is None:
        cache_dir = PYTORCH_PRETRAINED_BERT_CACHE
    if isinstance(cache_dir, Path):
        cache_dir = str(cache_dir)

    cache_path = os.path.join(cache_dir, filename)
    if not os.path.exists(cache_path):
        raise FileNotFoundError("file {} not found".format(cache_path))

    meta_path = cache_path + '.json'
    if not os.path.exists(meta_path):
        raise FileNotFoundError("file {} not found".format(meta_path))

    with open(meta_path) as meta_file:
        metadata = json.load(meta_file)
    url = metadata['url']
    etag = metadata['etag']

    return url, etag 
開發者ID:ymcui,項目名稱:cmrc2019,代碼行數:26,代碼來源:file_utils.py

示例5: _empty_column_check

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Tuple [as 別名]
def _empty_column_check(cards: dict) -> Tuple[bool, bool, bool, bool]:
    """檢查是否周末和晚上有課,返回三個布爾值"""
    with tracer.trace('_empty_column_check'):
        # 空閑周末判斷,考慮到大多數人周末都是沒有課程的
        empty_sat = True
        for cls_time in range(1, 7):
            if (6, cls_time) in cards:
                empty_sat = False

        empty_sun = True
        for cls_time in range(1, 7):
            if (7, cls_time) in cards:
                empty_sun = False

        # 空閑課程判斷,考慮到大多數人11-12節都是沒有課程的
        empty_6 = True
        for cls_day in range(1, 8):
            if (cls_day, 6) in cards:
                empty_6 = False
        empty_5 = True
        for cls_day in range(1, 8):
            if (cls_day, 5) in cards:
                empty_5 = False
    return empty_5, empty_6, empty_sat, empty_sun 
開發者ID:everyclass,項目名稱:everyclass-server,代碼行數:26,代碼來源:views.py

示例6: get_semester_date

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Tuple [as 別名]
def get_semester_date(date: datetime.date) -> Tuple[str, int, int]:
    """獲取日期對應的學期、所屬周次及星期(0表示周日,1表示周一...)

    >>> get_semester_date(datetime.date(2020, 2, 22))
    ('2019-2020-1', 26, 6)

    >>> get_semester_date(datetime.date(2020, 2, 23))
    ('2019-2020-2', 1, 0)
    """
    config = get_config()

    semesters = list(config.AVAILABLE_SEMESTERS.items())
    semesters.sort(key=lambda x: x[0], reverse=True)

    for sem in semesters:
        sem_start_date = datetime.date(*sem[1]["start"])
        if date >= sem_start_date:
            days_delta = (date - sem_start_date).days
            return "-".join([str(x) for x in sem[0]]), days_delta // 7 + 1, days_delta % 7
    raise ValueError("no applicable semester") 
開發者ID:everyclass,項目名稱:everyclass-server,代碼行數:22,代碼來源:domain.py

示例7: _precompute_exp_log

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Tuple [as 別名]
def _precompute_exp_log() -> Tuple[List[int], List[int]]:
    exp = [0 for i in range(255)]
    log = [0 for i in range(256)]

    poly = 1
    for i in range(255):
        exp[i] = poly
        log[poly] = i

        # Multiply poly by the polynomial x + 1.
        poly = (poly << 1) ^ poly

        # Reduce poly by x^8 + x^4 + x^3 + x + 1.
        if poly & 0x100:
            poly ^= 0x11B

    return exp, log 
開發者ID:trezor,項目名稱:python-shamir-mnemonic,代碼行數:19,代碼來源:shamir.py

示例8: apply

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Tuple [as 別名]
def apply(self, variables: Optional[dict] = None, parallelism: int = 10) -> Tuple[str, str, str]:
        """
        Will run a terraform apply on a workspace & will pass all variables to the terraform apply as terraform
        variables

        Arguments:
            :param variables: the variables to pass to the terraform apply command
            :param parallelism: the number of parallel resource operations

        Returns:
            :return return_code: the return code of the terraform apply
            :return stdout: the stdout stream of the terraform apply
            :return stderr: the stderr stream of the terraform apply
        """
        if variables is None:
            variables = {}

        return_code, stdout, stderr = self.tf.apply(no_color=IsFlagged, var=variables, skip_plan=True,
                                                    parallelism=parallelism)
        return return_code, stdout, stderr 
開發者ID:naorlivne,項目名稱:terraformize,代碼行數:22,代碼來源:terraformize_terraform_wrapper.py

示例9: destroy

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Tuple [as 別名]
def destroy(self, variables: Optional[dict] = None, parallelism: int = 10) -> Tuple[str, str, str]:
        """

        Arguments:
            :param variables: the variables to pass to the terraform destroy command
            :param parallelism: the number of parallel resource operations

        Will run a terraform destroy on a workspace will pass all variables to the terraform destroy as terraform
        variables, not deleting the workspace as one might want to keep historical data or have multiple modules under
        the same workspace name

        Arguments:

        Returns:
            :return return_code: the return code of the terraform destroy
            :return stdout: the stdout stream of the terraform destroy
            :return stderr: the stderr stream of the terraform destroy
        """
        return_code, stdout, stderr = self.tf.destroy(no_color=IsFlagged, var=variables, auto_approve=True,
                                                      parallelism=parallelism)
        return return_code, stdout, stderr 
開發者ID:naorlivne,項目名稱:terraformize,代碼行數:23,代碼來源:terraformize_terraform_wrapper.py

示例10: parse_arguments

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Tuple [as 別名]
def parse_arguments() -> Tuple[argparse.Namespace, str]:
    """Parse command line arguments and return namespace

    :return: Namespace for arguments and help text as a tuple
    """
    parser = argparse.ArgumentParser(description='FireProx API Gateway Manager')
    parser.add_argument('--profile_name',
                        help='AWS Profile Name to store/retrieve credentials', type=str, default=None)
    parser.add_argument('--access_key',
                        help='AWS Access Key', type=str, default=None)
    parser.add_argument('--secret_access_key',
                        help='AWS Secret Access Key', type=str, default=None)
    parser.add_argument('--session_token',
                        help='AWS Session Token', type=str, default=None)
    parser.add_argument('--region',
                        help='AWS Region', type=str, default=None)
    parser.add_argument('--command',
                        help='Commands: list, create, delete, update', type=str, default=None)
    parser.add_argument('--api_id',
                        help='API ID', type=str, required=False)
    parser.add_argument('--url',
                        help='URL end-point', type=str, required=False)
    return parser.parse_args(), parser.format_help() 
開發者ID:ustayready,項目名稱:fireprox,代碼行數:25,代碼來源:fire.py

示例11: __init__

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Tuple [as 別名]
def __init__(self,
                 optimal_value: float,
                 optimal_parameters: numpy.ndarray,
                 num_evaluations: Optional[int]=None,
                 cost_spent: Optional[float]=None,
                 function_values: Optional[List[Tuple[
                     float, Optional[float], Optional[numpy.ndarray]
                     ]]]=None,
                 wait_times: Optional[List[float]]=None,
                 time: Optional[int]=None,
                 seed: Optional[int]=None,
                 status: Optional[int]=None,
                 message: Optional[str]=None) -> None:
        self.optimal_value = optimal_value
        self.optimal_parameters = optimal_parameters
        self.num_evaluations = num_evaluations
        self.cost_spent = cost_spent
        self.function_values = function_values
        self.wait_times = wait_times
        self.time = time
        self.seed = seed
        self.status = status
        self.message = message 
開發者ID:quantumlib,項目名稱:OpenFermion-Cirq,代碼行數:25,代碼來源:result.py

示例12: noise_bounds

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Tuple [as 別名]
def noise_bounds(self,
                     cost: float,
                     confidence: Optional[float]=None
                     ) -> Tuple[float, float]:
        """Exact or approximate bounds on noise in the objective function.

        Returns a tuple (a, b) such that when `evaluate_with_cost` is called
        with the given cost and returns an approximate function value y, the
        true function value lies in the interval [y + a, y + b]. Thus, it should
        be the case that a <= 0 <= b.

        This function takes an optional `confidence` parameter which is a real
        number strictly between 0 and 1 that gives the confidence level in the
        bound. This is used for situations in which exact bounds on the noise
        cannot be guaranteed. The value can be interpreted as the probability
        that a repeated call to `evaluate_with_cost` with the same cost will
        return a value within the bounds.
        """
        return -numpy.inf, numpy.inf 
開發者ID:quantumlib,項目名稱:OpenFermion-Cirq,代碼行數:21,代碼來源:black_box.py

示例13: __init__

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Tuple [as 別名]
def __init__(self,
                 save_x_vals: bool=False,
                 **kwargs) -> None:
        """
        Args:
            save_x_vals: Whether to save all points (x values) that the
                black box was queried at. Setting this to True will cause the
                black box to consume a lot more memory. This does not affect
                whether the function values (y values) are saved (they are
                saved no matter what).
        """
        self.function_values = [] \
            # type: List[Tuple[float, Optional[float], Optional[numpy.ndarray]]]
        self.cost_spent = 0.0
        self.wait_times = []  # type: List[float]
        self._save_x_vals = save_x_vals
        self._time_of_last_query = None  # type: Optional[float]
        super().__init__(**kwargs) 
開發者ID:quantumlib,項目名稱:OpenFermion-Cirq,代碼行數:20,代碼來源:black_box.py

示例14: noise_bounds

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Tuple [as 別名]
def noise_bounds(self,
                     cost: float,
                     confidence: Optional[float]=None
                     ) -> Tuple[float, float]:
        """Exact or approximate bounds on noise.

        Returns a tuple (a, b) such that when `noise` is called with the given
        cost, the returned value lies between a and b. It should be the case
        that a <= 0 <= b.

        This function takes an optional `confidence` parameter which is a real
        number strictly between 0 and 1 that gives the probability of the bounds
        being correct. This is used for situations in which exact bounds on the
        noise cannot be guaranteed.
        """
        return -numpy.inf, numpy.inf 
開發者ID:quantumlib,項目名稱:OpenFermion-Cirq,代碼行數:18,代碼來源:objective.py

示例15: find_package

# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Tuple [as 別名]
def find_package(name: str) -> Tuple[Optional[Path], Path]:
    """Finds packages install prefix (or None) and it's containing Folder
    """
    module = name.split(".")[0]
    loader = pkgutil.get_loader(module)
    if name == "__main__" or loader is None:
        package_path = Path.cwd()
    else:
        if hasattr(loader, "get_filename"):
            filename = loader.get_filename(module)  # type: ignore
        else:
            __import__(name)
            filename = sys.modules[name].__file__
        package_path = Path(filename).resolve().parent
        if hasattr(loader, "is_package"):
            is_package = loader.is_package(module)  # type: ignore
            if is_package:
                package_path = Path(package_path).resolve().parent
    sys_prefix = Path(sys.prefix).resolve()
    try:
        package_path.relative_to(sys_prefix)
    except ValueError:
        return None, package_path
    else:
        return sys_prefix, package_path 
開發者ID:pgjones,項目名稱:quart,代碼行數:27,代碼來源:helpers.py


注:本文中的typing.Tuple方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。