• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python compat.is_string函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中nengo.utils.compat.is_string函数的典型用法代码示例。如果您正苦于以下问题:Python is_string函数的具体用法?Python is_string怎么用?Python is_string使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: validate

    def validate(self, instance, ndarray):
        ndim = len(self.shape)
        try:
            ndarray = np.asarray(ndarray, dtype=np.float64)
        except TypeError:
            raise ValueError("Must be a float NumPy array (got type '%s')"
                             % ndarray.__class__.__name__)

        if ndarray.ndim != ndim:
            raise ValueError("ndarray must be %dD (got %dD)"
                             % (ndim, ndarray.ndim))
        for i, attr in enumerate(self.shape):
            assert is_integer(attr) or is_string(attr), (
                "shape can only be an int or str representing an attribute")
            if attr == '*':
                continue

            if is_integer(attr):
                desired = attr
            elif is_string(attr):
                desired = getattr(instance, attr)

            if ndarray.shape[i] != desired:
                raise ValueError("shape[%d] should be %d (got %d)"
                                 % (i, desired, ndarray.shape[i]))
        return ndarray
开发者ID:bopo,项目名称:nengo,代码行数:26,代码来源:params.py


示例2: shrink

    def shrink(self, limit=None):
        """Reduces the size of the cache to meet a limit.

        Parameters
        ----------
        limit : int, optional
            Maximum size of the cache in bytes.
        """
        if limit is None:
            limit = rc.get('decoder_cache', 'size')
        if is_string(limit):
            limit = human2bytes(limit)

        fileinfo = []
        for filename in self.get_files():
            path = os.path.join(self.cache_dir, filename)
            stat = safe_stat(path)
            if stat is not None:
                fileinfo.append((stat.st_atime, stat.st_size, path))

        # Remove the least recently accessed first
        fileinfo.sort()

        excess = self.get_size_in_bytes() - limit
        for _, size, path in fileinfo:
            if excess <= 0:
                break

            excess -= size
            safe_remove(path)

        # We may have removed a decoder file but not solver_info file
        # or vice versa, so we'll remove all orphans
        self.remove_orphans()
开发者ID:Tayyar,项目名称:nengo,代码行数:34,代码来源:cache.py


示例3: shrink

    def shrink(self, limit=None):
        """Reduces the size of the cache to meet a limit.

        Parameters
        ----------
        limit : int, optional
            Maximum size of the cache in bytes.
        """
        if limit is None:
            limit = rc.get('decoder_cache', 'size')
        if is_string(limit):
            limit = human2bytes(limit)

        fileinfo = []
        excess = -limit
        for path in self.get_files():
            stat = safe_stat(path)
            if stat is not None:
                aligned_size = byte_align(stat.st_size, self._fragment_size)
                excess += aligned_size
                fileinfo.append((stat.st_atime, aligned_size, path))

        # Remove the least recently accessed first
        fileinfo.sort()

        for _, size, path in fileinfo:
            if excess <= 0:
                break

            excess -= size
            safe_remove(path)
开发者ID:CamZHU,项目名称:nengo,代码行数:31,代码来源:cache.py


示例4: recorder_dirname

def recorder_dirname(request, name):
    """Returns the directory to put test artifacts in.

    Test artifacts produced by Nengo include plots and analytics.

    Note that the return value might be None, which indicates that the
    artifacts should not be saved.
    """
    record = request.config.getvalue(name)
    if is_string(record):
        return record
    elif not record:
        return None

    simulator, nl = TestConfig.RefSimulator, None
    if 'Simulator' in request.funcargnames:
        simulator = request.getfuncargvalue('Simulator')
    # 'nl' stands for the non-linearity used in the neuron equation
    if 'nl' in request.funcargnames:
        nl = request.getfuncargvalue('nl')
    elif 'nl_nodirect' in request.funcargnames:
        nl = request.getfuncargvalue('nl_nodirect')

    dirname = "%s.%s" % (simulator.__module__, name)
    if nl is not None:
        dirname = os.path.join(dirname, nl.__name__)
    return dirname
开发者ID:4n6strider,项目名称:nengo,代码行数:27,代码来源:conftest.py


示例5: validate

    def validate(self, instance, ndarray):
        ndim = len(self.shape)
        try:
            ndarray = np.asarray(ndarray, dtype=np.float64)
        except TypeError:
            raise ValueError("Must be a float NumPy array (got type '%s')"
                             % ndarray.__class__.__name__)

        if ndarray.ndim != ndim:
            raise ValueError("ndarray must be %dD (got %dD)"
                             % (ndim, ndarray.ndim))
        for i, attr in enumerate(self.shape):
            assert is_integer(attr) or is_string(attr), (
                "shape can only be an int or str representing an attribute")
            if attr == '*':
                continue

            desired = attr if is_integer(attr) else getattr(instance, attr)

            if not is_integer(desired):
                raise ValueError("%s not yet initialized; cannot determine "
                                 "if shape is correct. Consider using a "
                                 "distribution instead." % attr)

            if ndarray.shape[i] != desired:
                raise ValueError("shape[%d] should be %d (got %d)"
                                 % (i, desired, ndarray.shape[i]))
        return ndarray
开发者ID:Ocode,项目名称:nengo,代码行数:28,代码来源:params.py


示例6: __init__

    def __init__(self, *args, **kwargs):
        # Pop the label, seed, and add_to_network, so that they are not passed
        # to self.initialize or self.make.
        self.label = kwargs.pop('label', None)
        self.seed = kwargs.pop('seed', None)
        add_to_network = kwargs.pop(
            'add_to_network', len(NengoObject.context) > 0)

        if not (self.label is None or is_string(self.label)):
            raise ValueError("Label '%s' must be None, str, or unicode." %
                             self.label)

        self.ensembles = []
        self.nodes = []
        self.connections = []
        self.networks = []

        super(Network, self).__init__(
            add_to_network=add_to_network, *args, **kwargs)

        # Start object keys with the model hash.
        # We use the hash because it's deterministic, though this
        # may be confusing if models use the same label.
        self._next_key = hash(self)

        with self:
            self.make(*args, **kwargs)
开发者ID:lisannehuurdeman,项目名称:nengo,代码行数:27,代码来源:objects.py


示例7: find_modules

def find_modules(root_path, prefix=[], pattern='^test_.*\\.py$'):
    """Find matching modules (files) in all subdirectories of a given path.

    Parameters
    ----------
    root_path : string
        The path of the directory in which to begin the search.
    prefix : string or list, optional
        A string or list of strings to append to each returned modules list.
    pattern : string, optional
        A regex pattern for matching individual file names. Defaults to
        looking for all testing scripts.

    Returns
    -------
    modules : list
        A list of modules. Each item in the list is a list of strings
        containing the module path.
    """
    if is_string(prefix):
        prefix = [prefix]
    elif not isinstance(prefix, list):
        raise TypeError("Invalid prefix type '%s'" % type(prefix).__name__)

    modules = []
    for path, dirs, files in os.walk(root_path):
        base = prefix + os.path.relpath(path, root_path).split(os.sep)
        for filename in files:
            if re.search(pattern, filename):
                name, ext = os.path.splitext(filename)
                modules.append(base + [name])

    return modules
开发者ID:goaaron,项目名称:blouw-etal-2015,代码行数:33,代码来源:testing.py


示例8: allclose

def allclose(t, target, signals, plotter=None, filename=None, labels=None,
             atol=1e-8, rtol=1e-5, buf=0, delay=0):
    """Perform an allclose check between two signals, with the potential to
    buffer both ends of the signal, account for a delay, and make a plot."""

    signals = np.asarray(signals)
    vector_in = signals.ndim < 2
    if vector_in:
        signals.shape = (1, -1)

    slice1 = slice(buf, -buf - delay)
    slice2 = slice(buf + delay, -buf)

    if plotter is not None:
        with plotter as plt:
            if labels is None:
                labels = [None] * len(signals)
            elif is_string(labels):
                labels = [labels]

            bound = atol + rtol * np.abs(target)

            # signal plot
            ax = plt.subplot(2, 1, 1)
            ax.plot(t, target, 'k:')
            for signal, label in zip(signals, labels):
                ax.plot(t, signal, label=label)
            ax.plot(t[slice2], (target + bound)[slice1], 'k--')
            ax.plot(t[slice2], (target - bound)[slice1], 'k--')
            ax.set_ylabel('signal')
            legend = (ax.legend(loc=2, bbox_to_anchor=(1., 1.))
                      if labels[0] is not None else None)

            # error plot
            errors = np.array([signal[slice2] - target[slice1]
                               for signal in signals])
            ymax = 1.1 * max(np.abs(errors).max(), bound.max())

            ax = plt.subplot(2, 1, 2)
            ax.plot(t[slice2], np.zeros_like(t[slice2]), 'k:')
            for error, label in zip(errors, labels):
                plt.plot(t[slice2], error, label=label)
            ax.plot(t[slice2], bound[slice1], 'k--')
            ax.plot(t[slice2], -bound[slice1], 'k--')
            ax.set_ylim((-ymax, ymax))
            ax.set_xlabel('time')
            ax.set_ylabel('error')

            if filename is not None:
                plt.savefig(filename, bbox_inches='tight',
                            bbox_extra_artists=(legend,) if legend else ())
            else:
                plt.show()
            plt.close()

    close = [np.allclose(signal[slice2], target[slice1], atol=atol, rtol=rtol)
             for signal in signals]
    return close[0] if vector_in else close
开发者ID:Dartonw,项目名称:nengo,代码行数:58,代码来源:testing.py


示例9: validate

    def validate(self, instance, ndarray):  # noqa: C901
        if isinstance(ndarray, np.ndarray):
            ndarray = ndarray.view()
        else:
            try:
                ndarray = np.array(ndarray, dtype=np.float64)
            except (ValueError, TypeError):
                raise ValidationError(
                    "Must be a float NumPy array (got type %r)" % ndarray.__class__.__name__,
                    attr=self.name,
                    obj=instance,
                )

        if self.readonly:
            ndarray.setflags(write=False)

        if "..." in self.shape:
            # Convert '...' to the appropriate number of '*'s
            nfixed = len(self.shape) - 1
            n = ndarray.ndim - nfixed
            if n < 0:
                raise ValidationError(
                    "ndarray must be at least %dD (got %dD)" % (nfixed, ndarray.ndim), attr=self.name, obj=instance
                )

            i = self.shape.index("...")
            shape = list(self.shape[:i]) + (["*"] * n)
            if i < len(self.shape) - 1:
                shape.extend(self.shape[i + 1 :])
        else:
            shape = self.shape

        if ndarray.ndim != len(shape):
            raise ValidationError(
                "ndarray must be %dD (got %dD)" % (len(shape), ndarray.ndim), attr=self.name, obj=instance
            )

        for i, attr in enumerate(shape):
            assert is_integer(attr) or is_string(attr), "shape can only be an int or str representing an attribute"
            if attr == "*":
                continue

            desired = attr if is_integer(attr) else getattr(instance, attr)

            if not is_integer(desired):
                raise ValidationError(
                    "%s not yet initialized; cannot determine if shape is "
                    "correct. Consider using a distribution instead." % attr,
                    attr=self.name,
                    obj=instance,
                )

            if ndarray.shape[i] != desired:
                raise ValidationError(
                    "shape[%d] should be %d (got %d)" % (i, desired, ndarray.shape[i]), attr=self.name, obj=instance
                )
        return ndarray
开发者ID:CaiZhongda,项目名称:nengo,代码行数:57,代码来源:params.py


示例10: audio

 def audio(self, audio_):
     if is_string(audio_):
         # Assuming this is a wav file
         audio_, fs = sf.read(audio_)
         self.fs = fs
     assert is_array(audio_)
     if audio_.ndim == 1:
         audio_ = audio_[:, np.newaxis]
     self.mfcc.audio = audio_
     self.periphery.sound_process = ArrayProcess(audio_)
开发者ID:tbekolay,项目名称:phd,代码行数:10,代码来源:sermo.py


示例11: __init__

 def __init__(self, name, default=Unconfigurable, values=(), lower=True, optional=False, readonly=None):
     assert all(is_string(s) for s in values)
     if lower:
         values = tuple(s.lower() for s in values)
     value_set = set(values)
     assert len(values) == len(value_set)
     self.values = values
     self.value_set = value_set
     self.lower = lower
     super(EnumParam, self).__init__(name, default, optional, readonly)
开发者ID:CaiZhongda,项目名称:nengo,代码行数:10,代码来源:params.py


示例12: validate

    def validate(self, instance, ndarray):  # noqa: C901
        if isinstance(ndarray, np.ndarray):
            ndarray = ndarray.view()
        else:
            try:
                ndarray = np.array(ndarray, dtype=np.float64)
            except TypeError:
                raise ValueError("Must be a float NumPy array (got type '%s')"
                                 % ndarray.__class__.__name__)
        if self.readonly:
            ndarray.setflags(write=False)

        if '...' in self.shape:
            nfixed = len(self.shape) - 1
            n = ndarray.ndim - nfixed
            if n < 0:
                raise ValueError("ndarray must be at least %dD (got %dD)"
                                 % (nfixed, ndarray.ndim))

            i = self.shape.index('...')
            shape = list(self.shape[:i]) + (['*'] * n)
            if i < len(self.shape) - 1:
                shape.extend(self.shape[i+1:])
        else:
            shape = self.shape

        if ndarray.ndim != len(shape):
            raise ValueError("ndarray must be %dD (got %dD)"
                             % (len(shape), ndarray.ndim))

        for i, attr in enumerate(shape):
            assert is_integer(attr) or is_string(attr), (
                "shape can only be an int or str representing an attribute")
            if attr == '*':
                continue

            desired = attr if is_integer(attr) else getattr(instance, attr)

            if not is_integer(desired):
                raise ValueError("%s not yet initialized; cannot determine "
                                 "if shape is correct. Consider using a "
                                 "distribution instead." % attr)

            if ndarray.shape[i] != desired:
                raise ValueError("shape[%d] should be %d (got %d)"
                                 % (i, desired, ndarray.shape[i]))
        return ndarray
开发者ID:MarcoSaku,项目名称:Spiking-C3D,代码行数:47,代码来源:params.py


示例13: shrink

    def shrink(self, limit=None):  # noqa: C901
        """Reduces the size of the cache to meet a limit.

        Parameters
        ----------
        limit : int, optional
            Maximum size of the cache in bytes.
        """
        if self.readonly:
            logger.info("Tried to shrink a readonly cache.")
            return

        if self._index is None:
            warnings.warn("Cannot shrink outside of a `with cache` block.")
            return

        if limit is None:
            limit = rc.get('decoder_cache', 'size')
        if is_string(limit):
            limit = human2bytes(limit)

        self._close_fd()

        fileinfo = []
        excess = -limit
        for path in self.get_files():
            stat = safe_stat(path)
            if stat is not None:
                aligned_size = byte_align(stat.st_size, self._fragment_size)
                excess += aligned_size
                fileinfo.append((stat.st_atime, aligned_size, path))

        # Remove the least recently accessed first
        fileinfo.sort()

        for _, size, path in fileinfo:
            if excess <= 0:
                break

            excess -= size
            self._index.remove_file_entry(path)
            safe_remove(path)

        self._index.sync()
开发者ID:GYGit,项目名称:nengo,代码行数:44,代码来源:cache.py


示例14: recorder_dirname

def recorder_dirname(request, name):
    record = request.config.getvalue(name)
    if is_string(record):
        return record
    elif not record:
        return None

    simulator, nl = ReferenceSimulator, None
    if 'Simulator' in request.funcargnames:
        simulator = request.getfuncargvalue('Simulator')
    if 'nl' in request.funcargnames:
        nl = request.getfuncargvalue('nl')
    elif 'nl_nodirect' in request.funcargnames:
        nl = request.getfuncargvalue('nl_nodirect')

    dirname = "%s.%s" % (simulator.__module__, name)
    if nl is not None:
        dirname = os.path.join(dirname, nl.__name__)
    return dirname
开发者ID:epaxon,项目名称:nengo,代码行数:19,代码来源:conftest.py


示例15: shrink

    def shrink(self, limit=None):
        """Reduces the size of the cache to meet a limit.

        Parameters
        ----------
        limit : int, optional
            Maximum size of the cache in bytes.
        """
        if limit is None:
            limit = rc.get('decoder_cache', 'size')
        if is_string(limit):
            limit = human2bytes(limit)

        filelist = []
        for filename in os.listdir(self.cache_dir):
            key, ext = os.path.splitext(filename)
            if ext == self._SOLVER_INFO_EXT:
                continue
            path = os.path.join(self.cache_dir, filename)
            stat = os.stat(path)
            filelist.append((stat.st_atime, key))
        filelist.sort()

        excess = self.get_size_in_bytes() - limit
        for _, key in filelist:
            if excess <= 0:
                break

            decoder_path = os.path.join(
                self.cache_dir, key + self._DECODER_EXT)
            solver_info_path = os.path.join(
                self.cache_dir, key + self._SOLVER_INFO_EXT)

            excess -= os.stat(decoder_path).st_size
            os.remove(decoder_path)
            if os.path.exists(solver_info_path):
                excess -= os.stat(solver_info_path).st_size
                os.remove(solver_info_path)
开发者ID:Ocode,项目名称:nengo,代码行数:38,代码来源:cache.py


示例16: allclose

def allclose(t, targets, signals,  # noqa:C901
             atol=1e-8, rtol=1e-5, buf=0, delay=0,
             plt=None, show=False, labels=None, individual_results=False):
    """Ensure all signal elements are within tolerances.

    Allows for delay, removing the beginning of the signal, and plotting.

    Parameters
    ----------
    t : array_like (T,)
        Simulation time for the points in `target` and `signals`.
    targets : array_like (T, 1) or (T, N)
        Reference signal or signals for error comparison.
    signals : array_like (T, N)
        Signals to be tested against the target signals.
    atol, rtol : float
        Absolute and relative tolerances.
    buf : float
        Length of time (in seconds) to remove from the beginnings of signals.
    delay : float
        Amount of delay (in seconds) to account for when doing comparisons.
    plt : matplotlib.pyplot or mock
        Pyplot interface for plotting the results, unless it's mocked out.
    show : bool
        Whether to show the plot immediately.
    labels : list of string, length N
        Labels of each signal to use when plotting.
    individual_results : bool
        If True, returns a separate `allclose` result for each signal.
    """
    t = np.asarray(t)
    dt = t[1] - t[0]
    assert t.ndim == 1
    assert np.allclose(np.diff(t), dt)

    targets = np.asarray(targets)
    signals = np.asarray(signals)
    if targets.ndim == 1:
        targets = targets.reshape((-1, 1))
    if signals.ndim == 1:
        signals = signals.reshape((-1, 1))
    assert targets.ndim == 2 and signals.ndim == 2
    assert t.size == targets.shape[0]
    assert t.size == signals.shape[0]
    assert targets.shape[1] == 1 or targets.shape[1] == signals.shape[1]

    buf = int(np.round(buf / dt))
    delay = int(np.round(delay / dt))
    slice1 = slice(buf, len(t) - delay)
    slice2 = slice(buf + delay, None)

    if plt is not None:
        if labels is None:
            labels = [None] * len(signals)
        elif is_string(labels):
            labels = [labels]

        colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']

        def plot_target(ax, x, b=0, c='k'):
            bound = atol + rtol * np.abs(x)
            y = x - b
            ax.plot(t[slice2], y[slice1], c + ':')
            ax.plot(t[slice2], (y + bound)[slice1], c + '--')
            ax.plot(t[slice2], (y - bound)[slice1], c + '--')

        # signal plot
        ax = plt.subplot(2, 1, 1)
        for y, label in zip(signals.T, labels):
            ax.plot(t, y, label=label)

        if targets.shape[1] == 1:
            plot_target(ax, targets[:, 0], c='k')
        else:
            color_cycle = itertools.cycle(colors)
            for x in targets.T:
                plot_target(ax, x, c=next(color_cycle))

        ax.set_ylabel('signal')
        if labels[0] is not None:
            ax.legend(loc='upper left', bbox_to_anchor=(1., 1.))

        ax = plt.subplot(2, 1, 2)
        if targets.shape[1] == 1:
            x = targets[:, 0]
            plot_target(ax, x, b=x, c='k')
            for y, label in zip(signals.T, labels):
                ax.plot(t[slice2], y[slice2] - x[slice1])
        else:
            color_cycle = itertools.cycle(colors)
            for x, y, label in zip(targets.T, signals.T, labels):
                c = next(color_cycle)
                plot_target(ax, x, b=x, c=c)
                ax.plot(t[slice2], y[slice2] - x[slice1], c, label=label)

        ax.set_xlabel('time')
        ax.set_ylabel('error')

        if show:
            plt.show()
#.........这里部分代码省略.........
开发者ID:Ocode,项目名称:nengo,代码行数:101,代码来源:testing.py


示例17: validate

 def validate(self, instance, string):
     if string is not None and not is_string(string):
         raise ValidationError("Must be a string; got '%s'" % string,
                               attr=self.name, obj=instance)
     super(StringParam, self).validate(instance, string)
开发者ID:JolyZhang,项目名称:nengo,代码行数:5,代码来源:params.py


示例18: validate

 def validate(self, instance, string):
     if string is not None and not is_string(string):
         raise ValueError("Must be a string; got '%s'" % string)
     super(StringParam, self).validate(instance, string)
开发者ID:thingimon,项目名称:nengo,代码行数:4,代码来源:params.py


示例19: ensuretuple

def ensuretuple(val):
    if val is None:
        return val
    if is_string(val) or not is_iterable(val):
        return tuple([val])
    return tuple(val)
开发者ID:tbekolay,项目名称:phd,代码行数:6,代码来源:utils.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python compat.iteritems函数代码示例发布时间:2022-05-27
下一篇:
Python compat.is_number函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap