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


Python utils.native_str方法代码示例

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


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

示例1: __new__

# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native_str [as 别名]
def __new__(cls, offset, name=_Omitted):
        if not isinstance(offset, timedelta):
            raise TypeError("offset must be a timedelta")
        if name is cls._Omitted:
            if not offset:
                return cls.utc
            name = None
        elif not isinstance(name, str):
            ###
            # For Python-Future:
            if PY2 and isinstance(name, native_str):
                name = name.decode()
            else:
                raise TypeError("name must be a string")
            ###
        if not cls._minoffset <= offset <= cls._maxoffset:
            raise ValueError("offset must be a timedelta"
                             " strictly between -timedelta(hours=24) and"
                             " timedelta(hours=24).")
        if (offset.microseconds != 0 or
            offset.seconds % 60 != 0):
            raise ValueError("offset must be a timedelta"
                             " representing a whole number of minutes")
        return cls._create(offset, name) 
开发者ID:Soft8Soft,项目名称:verge3d-blender-addon,代码行数:26,代码来源:datetime.py

示例2: _get_kernel_name

# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native_str [as 别名]
def _get_kernel_name():
    """
    Returns the path of the kernel
    """
    names = ["kernel", ]

    if "NVPROF_ID" in os.environ:
        for frame in tb.extract_stack():
            if nrv_re.search(frame[0]):
                break
            caller = frame[0:2]

        file_path, file_name = os.path.split(caller[0])
        path1, path2 = os.path.split(file_path)
        file_base, ext = os.path.splitext(file_name)

        for name in (path2, file_base, ext):
            name = name_re.sub("", name)
            if name:
                names.append(name)

        names.append(native_str(caller[1]))

    return names 
开发者ID:NervanaSystems,项目名称:neon,代码行数:26,代码来源:float_ew.py

示例3: __init__

# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native_str [as 别名]
def __init__(self, op, lib, dtype,
                 N, C, K,
                 H, W, P, Q,
                 pad_h, pad_w, filter_extern=None, bprop=False):

        super(XpropWinograd_2x2_3x3, self).__init__(lib, dtype,
             N, C, K, 1, H, W, 1, 3, 3, 1, P, Q,
             0, pad_h, pad_w, 1,1,1, 1,1,1, bprop)

        SMs = _get_sm_count()

        self.autotune_key = " ".join(native_str(x) for x in (op + "_2x2_3x3",
           SMs, dtype.itemsize, N, C, K, H, W, P, Q))
        # insert Python version in filename to avoid Py2/Py3 incompatibilities in shelve
        self.autotune_db_file = os.path.join(lib.cache_dir, "autotune%d.db" % sys.version_info[0])

        # allow for .5 seconds worth of warmup when autotuning
        # assume 10 Tflops on 24 SMs
        self.warmup = min(max(int(5e12 / (P * Q * K * N * C * 9 * 2.0) * (SMs / 24.0)), 1), 1000)

        if filter_extern is None:
            self.init()
        else:
            # allow manual override for unit testing
            self.initialized = True
            self.init(autotune=1, filter_extern=filter_extern)

        lib.set_scratch_size(self.filter_trans.size, self.bsum.size) 
开发者ID:NervanaSystems,项目名称:ngraph-python,代码行数:30,代码来源:winograd_conv.py

示例4: __init__

# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native_str [as 别名]
def __init__(self, lib, dtype,
                 N, C, K,
                 D, H, W,
                 T, R, S,
                 M, P, Q,
                 pad_d, pad_h, pad_w,
                 str_d, str_h, str_w,
                 dil_d, dil_h, dil_w):

        assert N % 4 == 0, "N dim must be multiple of 4"

        super(UpdateDirect, self).__init__(lib, dtype,
            N, C, K, D, H, W, T, R, S, M, P, Q,
            pad_d, pad_h, pad_w, str_d, str_h, str_w,
            dil_d, dil_h, dil_w)

        SMs = _get_sm_count()

        self.autotune_key = " ".join(native_str(x) for x in (
            "direct_updat_64x32", SMs, dtype.itemsize, lib.deterministic > 0,
            N, C, K, D, H, W, T, R, S, M, P, Q ))

        # insert Python version in filename to avoid Py2/Py3 incompatibilities in shelve
        self.autotune_db_file = os.path.join(lib.cache_dir, "autotune%d.db" % sys.version_info[0])
        self.init()

        lib.set_scratch_size(self.output_trans.size)

        # allow for .5 seconds worth of warmup when autotuning
        # assume 5 Tflops on 24 SMs
        self.warmup = min(max(int(2e12 / (M * P * Q * K * N * C * T * R * S * 2.0) * (SMs / 24.0)), 1), 5000) 
开发者ID:NervanaSystems,项目名称:ngraph-python,代码行数:33,代码来源:convolution.py

示例5: store_item

# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native_str [as 别名]
def store_item(self, key, value):
        with self.store_lock:
            try:
                self.store[native_str(key)] = value
            except Exception:
                logger.exception('Exception:') 
开发者ID:DLR-RM,项目名称:RAFCON,代码行数:8,代码来源:execution_history.py

示例6: _get_platform

# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native_str [as 别名]
def _get_platform(self):
        from simtk import openmm

        preference = ['CUDA', 'OpenCL', 'CPU', 'Reference']
        from_lower = {x.lower(): x for x in preference}

        properties = {}

        if self.params.compute_platform.lower() == 'auto':
            for platname in preference:
                try:
                    platform = openmm.Platform.getPlatformByName(platname)
                except Exception:  # it just throws "Exception" unfortunately
                    continue
                else:
                    use_platform = platname
                    break
            else:
                raise moldesign.NotSupportedError("Likely OpenMM installation error. "
                                                  "none of the expected platforms were found: "
                                                  + ', '.join(preference))
        else:
            use_platform = self.params.compute_platform

        self.params.compute_platform = use_platform.lower()
        platform = openmm.Platform.getPlatformByName(from_lower[self.params.compute_platform])

        if self.params.compute_platform == 'cpu' and self.params.num_cpus > 0:
            # need to use native_strs here or the swig interface gets confused
            properties[native_str('Threads')] = native_str(self.params.num_cpus)

        return platform, properties 
开发者ID:Autodesk,项目名称:molecular-design-toolkit,代码行数:34,代码来源:openmm.py

示例7: test_compressed_write

# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native_str [as 别名]
def test_compressed_write(bipyridine_xyz, tmpdir, suffix):
    # Note: compressed read is tested elsewhere when reading test data files
    path = pathlib.Path(native_str(tmpdir))
    dest = path / ('bipyr.xyz.' + suffix)
    bipyridine_xyz.write(dest)

    # don't use MDT's reader here! Need to make sure it's really gzip'd
    if suffix == 'gz':
        opener = gzip.open
    elif suffix == 'bz2':
        opener = bz2.BZ2File
    else:
        raise ValueError('Unrecognized suffix "%s"' % suffix)

    if PY2:
        mode = 'r'
    else:
        mode = 'rt'
        if suffix == 'bz2':
            opener = bz2.open

    with opener(str(dest), mode) as infile:
        content = infile.read()

    mol = mdt.read(content, format='xyz')
    assert mol.num_atoms == bipyridine_xyz.num_atoms 
开发者ID:Autodesk,项目名称:molecular-design-toolkit,代码行数:28,代码来源:test_io.py

示例8: test_read_from_buffer

# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native_str [as 别名]
def test_read_from_buffer():
    s = native_str("2\nmy xyz file\n H  1.0 1.0 1.0\n H 1.0 2.0 1.0\n")
    buffer = native_str_buffer(s)
    h2 = mdt.read(buffer, format='xyz')
    assert h2.num_atoms == 2 
开发者ID:Autodesk,项目名称:molecular-design-toolkit,代码行数:7,代码来源:test_io.py

示例9: vividict_to_dict

# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native_str [as 别名]
def vividict_to_dict(vividict, native_strings=False):
        """Helper method to create Python dicts from arbitrary Vividict objects

        :param Vividict vividict: A Vividict to be converted
        :return: A Python dict
        :rtype: dict
        """
        try:
            from numpy import ndarray
        except ImportError:
            ndarray = dict

        dictionary = {}

        def np_to_native(np_val):
            """Recursively convert numpy values to native Python values

            - Converts matrices to lists
            - Converts numpy.dtypes to float/int etc
            :param np_val: value to convert
            :return: value as native Python value
            """
            if isinstance(np_val, dict):
                for key, value in np_val.items():
                    np_val[key] = np_to_native(value)
            # The following condition cannot hold true if no numpy is installed, as ndarray is set to dict, which was
            # already handled in the previous condition
            elif isinstance(np_val, ndarray):
                # noinspection PyUnresolvedReferences
                np_val = np_val.tolist()
            if isinstance(np_val, (list, tuple)):
                native_list = [np_to_native(val) for val in np_val]
                if isinstance(np_val, tuple):
                    return tuple(native_list)
                return native_list
            if not hasattr(np_val, 'dtype'):  # Nothing to convert
                return np_val
            return np_val.item()  # Get the gloat/int etc value

        for key, value in vividict.items():
            if native_strings:  # e.g. converts newstr to str
                if isinstance(key, string_types):
                    key = native_str(key)
                if isinstance(value, string_types):
                    value = native_str(value)
            # Convert numpy values to native Python values
            value = np_to_native(value)

            # run recursively
            if isinstance(value, Vividict):
                value = Vividict.vividict_to_dict(value, native_strings)
            dictionary[key] = value

        return dictionary 
开发者ID:DLR-RM,项目名称:RAFCON,代码行数:56,代码来源:vividict.py

示例10: log_to_raw_structure

# 需要导入模块: from future import utils [as 别名]
# 或者: from future.utils import native_str [as 别名]
def log_to_raw_structure(execution_history_items):
    """
    :param dict execution_history_items: history items, in the simplest case
           directly the opened shelve log file
    :return: start_item, the StateMachineStartItem of the log file
             previous, a dict mapping history_item_id --> history_item_id of previous history item
             next_, a dict mapping history_item_id --> history_item_id of the next history item (except if
                    next item is a concurrent execution branch)
             concurrent, a dict mapping history_item_id --> []list of concurrent next history_item_ids
                         (if present)
             grouped, a dict mapping run_id --> []list of history items with this run_id
    :rtype: tuple
    """
    previous = {}
    next_ = {}
    concurrent = {}
    grouped_by_run_id = {}
    start_item = None

    for k,v in execution_history_items.items():
        if v['item_type'] == 'StateMachineStartItem':
            start_item = v
        else:
            # connect the item to its predecessor
            prev_item_id = native_str(v['prev_history_item_id'])

            if prev_item_id in execution_history_items:
                ## should always be the case except if shelve is broken/missing data

                previous[k] = prev_item_id
                if execution_history_items[prev_item_id]['item_type'] == 'ConcurrencyItem' and \
                   execution_history_items[k]['item_type'] != 'ReturnItem':
                    # this is not a return  item, thus this 'previous' relationship of this
                    # item must be a call item of one of the concurrent branches of
                    # the concurrency state
                    if prev_item_id in concurrent:
                        concurrent[prev_item_id].append(k)
                    else:
                        concurrent[prev_item_id] = [k]
                else:
                    # this is a logical 'next' relationship
                    next_[prev_item_id] = k
            else:
                logger.warning('HistoryItem is referring to a non-existing previous history item, HistoryItem was %s' % str(v))

        rid = v['run_id']
        if rid in grouped_by_run_id:
            grouped_by_run_id[rid].append(v)
        else:
            grouped_by_run_id[rid] = [v]

    return start_item, previous, next_, concurrent, grouped_by_run_id 
开发者ID:DLR-RM,项目名称:RAFCON,代码行数:54,代码来源:execution_log.py


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