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

Python moves.intern函数代码示例

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

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



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

示例1: map_sum

    def map_sum(self, expr):
        sum_kind = None

        term_kind_matrix = intern("matrix")
        term_kind_vector = intern("vector")
        term_kind_scalar = intern("scalar")

        result = 0
        for child in expr.children:
            rec_child = self.rec(child)

            if is_zero(rec_child):
                continue

            if isinstance(rec_child, np.ndarray):
                if self.is_kind_matrix(rec_child):
                    term_kind = term_kind_matrix
                elif self.is_kind_vector(rec_child):
                    term_kind = term_kind_vector
                else:
                    raise RuntimeError("unexpected array rank")
            else:
                term_kind = term_kind_scalar

            if sum_kind is None:
                sum_kind = term_kind

            if term_kind != sum_kind:
                raise RuntimeError("encountered %s in sum of kind %s"
                        % (term_kind, sum_kind))

            result = result + rec_child

        return result
开发者ID:inducer,项目名称:pytential,代码行数:34,代码来源:matrix.py


示例2: __init__

    def __init__(self, next_attr_name=None, prev_attr_name=None):
        """Initializes this list.

        next_attr_name: The name of the attribute that holds a reference
                        to the next item in the list.

        prev_attr_name: the name of the attribute that holds a reference
                        to the previous item in the list.
        """

        # Keep an interned version of the attribute names. This should
        # speed up the process of looking up the attributes.
        self.next_name = intern(next_attr_name)
        self.prev_name = intern(prev_attr_name)
开发者ID:Aries-Sushi,项目名称:ryu,代码行数:14,代码来源:circlist.py


示例3: __init__

    def __init__(self, **kwargs):
        kwargs["name"] = intern(kwargs.pop("name"))

        target = kwargs.pop("target", None)

        dtype = kwargs.pop("dtype", None)

        if 'for_atomic' in kwargs:
            for_atomic = kwargs['for_atomic']
        else:
            for_atomic = False

        from loopy.types import to_loopy_type
        dtype = to_loopy_type(
                dtype, allow_auto=True, allow_none=True, for_atomic=for_atomic,
                target=target)

        import loopy as lp
        if dtype is lp.auto:
            warn("Argument/temporary data type for '%s' should be None if "
                   "unspecified, not auto. This usage will be disallowed in 2018."
                    % kwargs["name"],
                    DeprecationWarning, stacklevel=2)

            dtype = None

        kwargs["dtype"] = dtype

        ImmutableRecord.__init__(self, **kwargs)
开发者ID:inducer,项目名称:loopy,代码行数:29,代码来源:data.py


示例4: normalize_chromosome

def normalize_chromosome(c):
    try:
        return NORMALIZE_CHROMOSOME_CACHE[c]
    except KeyError:
        pass

    if not (is_string(c) or is_integer(c)):
        raise TypeError("Chromosome cannot be '%s' : %s" % (c, type(c)))

    result = str(c)
    if result == "0":
        raise ValueError("Chromosome name cannot be 0")
    elif result == "":
        raise ValueError("Chromosome name cannot be empty")

    # only strip off lowercase chr since some of the non-chromosomal
    # contigs start with "CHR"
    if result.startswith("chr"):
        result = result[3:]

    # just in case someone is being lazy, capitalize "M", "MT", X", "Y"
    result = result.upper()

    # standardize mitochondrial genome to be "MT"
    if result == "M":
        result = "MT"

    # interning strings since the chromosome names probably get constructed
    # or parsed millions of times, can save memory in tight situations
    # (such as parsing GTF files)
    result = intern(result)

    NORMALIZE_CHROMOSOME_CACHE[c] = result

    return result
开发者ID:BioInfoTools,项目名称:pyensembl,代码行数:35,代码来源:locus.py


示例5: memoize_method

def memoize_method(method):
    """Supports cache deletion via ``method_name.clear_cache(self)``.

    .. note::
        *clear_cache* support requires Python 2.5 or newer.
    """

    cache_dict_name = intern("_memoize_dic_"+method.__name__)

    def wrapper(self, *args, **kwargs):
        if kwargs:
            key = (_HasKwargs, frozenset(six.iteritems(kwargs))) + args
        else:
            key = args

        try:
            return getattr(self, cache_dict_name)[key]
        except AttributeError:
            result = method(self, *args, **kwargs)
            setattr(self, cache_dict_name, {key: result})
            return result
        except KeyError:
            result = method(self, *args, **kwargs)
            getattr(self, cache_dict_name)[key] = result
            return result

    def clear_cache(self):
        delattr(self, cache_dict_name)

    if sys.version_info >= (2, 5):
        from functools import update_wrapper
        new_wrapper = update_wrapper(wrapper, method)
        new_wrapper.clear_cache = clear_cache

    return new_wrapper
开发者ID:himikof,项目名称:pytools,代码行数:35,代码来源:__init__.py


示例6: memoize_method_nested

def memoize_method_nested(inner):
    """Adds a cache to a function nested inside a method. The cache is attached
    to *memoize_cache_context* (if it exists) or *self* in the outer (method)
    namespace.

    Requires Python 2.5 or newer.
    """

    from functools import wraps
    cache_dict_name = intern("_memoize_inner_dic_%s_%s_%d"
            % (inner.__name__, inner.__code__.co_filename,
                inner.__code__.co_firstlineno))

    from inspect import currentframe
    outer_frame = currentframe().f_back
    cache_context = outer_frame.f_locals.get("memoize_cache_context")
    if cache_context is None:
        cache_context = outer_frame.f_locals.get("self")

    try:
        cache_dict = getattr(cache_context, cache_dict_name)
    except AttributeError:
        cache_dict = {}
        setattr(cache_context, cache_dict_name, cache_dict)

    @wraps(inner)
    def new_inner(*args):
        try:
            return cache_dict[args]
        except KeyError:
            result = inner(*args)
            cache_dict[args] = result
            return result

    return new_inner
开发者ID:blino,项目名称:pytools,代码行数:35,代码来源:__init__.py


示例7: realize_conditional

    def realize_conditional(self, node, context_cond=None):
        scope = self.scope_stack[-1]

        cond_name = intern("loopy_cond%d" % self.condition_id_counter)
        self.condition_id_counter += 1
        assert cond_name not in scope.type_map

        scope.type_map[cond_name] = np.int32

        from pymbolic import var
        cond_var = var(cond_name)

        self.add_expression_instruction(
                cond_var, self.parse_expr(node, node.expr))

        cond_expr = cond_var
        if context_cond is not None:
            from pymbolic.primitives import LogicalAnd
            cond_expr = LogicalAnd((cond_var, context_cond))

            self.conditions_data.append((context_cond, cond_var))
        else:
            self.conditions_data.append((None, cond_var))

        self.conditions.append(cond_expr)
开发者ID:inducer,项目名称:loopy,代码行数:25,代码来源:translator.py


示例8: memoize_method

def memoize_method(method):
    """Supports cache deletion via ``method_name.clear_cache(self)``.

    .. note::
        *clear_cache* support requires Python 2.5 or newer.
    """

    return memoize_on_first_arg(method, intern("_memoize_dic_"+method.__name__))
开发者ID:kayarre,项目名称:pytools,代码行数:8,代码来源:__init__.py


示例9: make_unique_instruction_id

    def make_unique_instruction_id(self, insns=None, based_on="insn",
            extra_used_ids=set()):
        if insns is None:
            insns = self.instructions

        used_ids = set(insn.id for insn in insns) | extra_used_ids

        for id_str in generate_unique_names(based_on):
            if id_str not in used_ids:
                return intern(id_str)
开发者ID:cmsquared,项目名称:loopy,代码行数:10,代码来源:__init__.py


示例10: __call__

    def __call__(self, based_on="id"):
        based_on = self.forced_prefix + based_on

        for var_name in generate_unique_names(based_on):
            if not self.is_name_conflicting(var_name):
                break

        var_name = intern(var_name)

        self.existing_names.add(var_name)
        return var_name
开发者ID:himikof,项目名称:pytools,代码行数:11,代码来源:__init__.py


示例11: __init__

    def __init__(self, **kwargs):
        kwargs["name"] = intern(kwargs.pop("name"))

        dtype = kwargs.pop("dtype", None)

        if isinstance(dtype, np.dtype):
            from loopy.tools import PicklableDtype
            kwargs["picklable_dtype"] = PicklableDtype(dtype)
        else:
            kwargs["picklable_dtype"] = dtype

        Record.__init__(self, **kwargs)
开发者ID:navjotk,项目名称:loopy,代码行数:12,代码来源:data.py


示例12: parse_if_necessary

def parse_if_necessary(insn, defines):
    if isinstance(insn, InstructionBase):
        yield insn.copy(
                id=intern(insn.id) if isinstance(insn.id, str) else insn.id,
                insn_deps=frozenset(intern(dep) for dep in insn.insn_deps),
                groups=frozenset(intern(grp) for grp in insn.groups),
                conflicts_with_groups=frozenset(
                    intern(grp) for grp in insn.conflicts_with_groups),
                forced_iname_deps=frozenset(
                    intern(iname) for iname in insn.forced_iname_deps),
                predicates=frozenset(
                    intern(pred) for pred in insn.predicates),
                ), []
        return
    elif not isinstance(insn, str):
        raise TypeError("Instructions must be either an Instruction "
                "instance or a parseable string. got '%s' instead."
                % type(insn))

    for insn in insn.split("\n"):
        comment_start = insn.find("#")
        if comment_start >= 0:
            insn = insn[:comment_start]

        insn = insn.strip()
        if not insn:
            continue

        for sub_insn in expand_defines(insn, defines, single_valued=False):
            yield parse_insn(sub_insn)
开发者ID:navjotk,项目名称:loopy,代码行数:30,代码来源:creation.py


示例13: cursor_to_dict

    def cursor_to_dict(cursor):
        """Converts a SQL cursor into an list of dicts.

        Args:
            cursor : The DBAPI cursor which has executed a query.
        Returns:
            A list of dicts where the key is the column header.
        """
        col_headers = list(intern(str(column[0])) for column in cursor.description)
        results = list(
            dict(zip(col_headers, row)) for row in cursor
        )
        return results
开发者ID:gergelypolonkai,项目名称:synapse,代码行数:13,代码来源:_base.py


示例14: __setstate__

    def __setstate__(self, val):
        super(InstructionBase, self).__setstate__(val)

        from loopy.tools import intern_frozenset_of_ids

        if self.id is not None:  # pylint:disable=access-member-before-definition
            self.id = intern(self.id)
        self.depends_on = intern_frozenset_of_ids(self.depends_on)
        self.groups = intern_frozenset_of_ids(self.groups)
        self.conflicts_with_groups = (
                intern_frozenset_of_ids(self.conflicts_with_groups))
        self.within_inames = (
                intern_frozenset_of_ids(self.within_inames))
开发者ID:inducer,项目名称:loopy,代码行数:13,代码来源:instruction.py


示例15: intern_string

def intern_string(string):
    """Takes a (potentially) unicode string and interns it if it's ascii
    """
    if string is None:
        return None

    try:
        if six.PY2:
            string = string.encode("ascii")

        return intern(string)
    except UnicodeEncodeError:
        return string
开发者ID:DoubleMalt,项目名称:synapse,代码行数:13,代码来源:__init__.py


示例16: der_parse_OID

def der_parse_OID(derblob):
    oidvals = [0]
    for byte in map(ord, derblob):
        if byte & 0x80 != 0x00:
            oidvals[-1] = (oidvals[-1] << 7) | (byte & 0x7f)
        else:
            oidvals[-1] = (oidvals[-1] << 7) | byte
            oidvals.append(0)
    fst = oidvals[0] // 40
    snd = oidvals[0] % 40
    oidvals = [fst, snd] + oidvals[1:-1]
    retval = '.'.join(map(str, oidvals))
    return intern(retval)
开发者ID:vanrein,项目名称:quick-der,代码行数:13,代码来源:primitive.py


示例17: __setstate__

    def __setstate__(self, val):
        super(InstructionBase, self).__setstate__(val)

        from loopy.tools import intern_frozenset_of_ids

        self.id = intern(self.id)
        self.insn_deps = intern_frozenset_of_ids(self.insn_deps)
        self.groups = intern_frozenset_of_ids(self.groups)
        self.conflicts_with_groups = (
                intern_frozenset_of_ids(self.conflicts_with_groups))
        self.forced_iname_deps = (
                intern_frozenset_of_ids(self.forced_iname_deps))
        self.predicates = (
                intern_frozenset_of_ids(self.predicates))
开发者ID:navjotk,项目名称:loopy,代码行数:14,代码来源:data.py


示例18: __call__

    def __call__(self, based_on="id"):
        based_on = self.forced_prefix + based_on

        counter = self.prefix_to_counter.get(based_on, None)

        for counter, var_name in generate_numbered_unique_names(based_on, counter):
            if not self.is_name_conflicting(var_name):
                break

        self.prefix_to_counter[based_on] = counter

        var_name = intern(var_name)

        self.existing_names.add(var_name)
        return var_name
开发者ID:kayarre,项目名称:pytools,代码行数:15,代码来源:__init__.py


示例19: first_arg_dependent_memoize_nested

def first_arg_dependent_memoize_nested(nested_func):
    """Provides memoization for nested functions. Typically used to cache
    things that get created inside a :class:`pyopencl.Context`, e.g. programs
    and kernels. Assumes that the first argument of the decorated function is
    an OpenCL object that might go away, such as a :class:`pyopencl.Context` or
    a :class:`pyopencl.CommandQueue`, and will therefore respond to
    :func:`clear_first_arg_caches`.

    .. versionadded:: 2013.1

    Requires Python 2.5 or newer.
    """

    from functools import wraps
    cache_dict_name = intern("_memoize_inner_dic_%s_%s_%d"
            % (nested_func.__name__, nested_func.__code__.co_filename,
                nested_func.__code__.co_firstlineno))

    from inspect import currentframe
    # prevent ref cycle
    try:
        caller_frame = currentframe().f_back
        cache_context = caller_frame.f_globals[
                caller_frame.f_code.co_name]
    finally:
        #del caller_frame
        pass

    try:
        cache_dict = getattr(cache_context, cache_dict_name)
    except AttributeError:
        cache_dict = {}
        _first_arg_dependent_caches.append(cache_dict)
        setattr(cache_context, cache_dict_name, cache_dict)

    @wraps(nested_func)
    def new_nested_func(cl_object, *args):
        try:
            return cache_dict[cl_object][args]
        except KeyError:
            arg_dict = cache_dict.setdefault(cl_object, {})
            result = nested_func(cl_object, *args)
            arg_dict[args] = result
            return result

    return new_nested_func
开发者ID:mattwala,项目名称:PyOpenCL,代码行数:46,代码来源:tools.py


示例20: add_expression_instruction

    def add_expression_instruction(self, lhs, rhs):
        scope = self.scope_stack[-1]

        new_id = intern("insn%d" % self.insn_id_counter)
        self.insn_id_counter += 1

        from loopy.kernel.data import Assignment
        insn = Assignment(
                lhs, rhs,
                within_inames=frozenset(
                    scope.active_loopy_inames),
                id=new_id,
                predicates=frozenset(self.conditions),
                tags=tuple(self.instruction_tags))

        scope.previous_instruction_id = new_id
        scope.instructions.append(insn)
开发者ID:inducer,项目名称:loopy,代码行数:17,代码来源:translator.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python moves.izip函数代码示例发布时间:2022-05-27
下一篇:
Python moves.input函数代码示例发布时间: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