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


Python SortedDict.items方法代码示例

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


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

示例1: __init__

# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import items [as 别名]
class TwoDimensionTable:
    def __init__(self):
        self.__rows = SortedDict()

    @classmethod
    def from_json(cls, input_file):
        with open(input_file, 'r') as json_f:
            json_data = json.load(json_f)

        table = TwoDimensionTable()

        for d in json_data:
            speedup = d['speedup_mine_over_sol']
            input_size = d['input_size']
            proc_count = d['proc_count']
            table.add(row=proc_count, col=input_size, val=speedup)

        return table

    def add(self, row, col, val):
        if row not in self.__rows:
            self.__add_new_row(row)

        for r, c in self.__rows.items():
            if r == row:
                c[col] = val
            elif col not in c:
                c[col] = None

    def row_items(self):
        return self.__rows.items()

    def __add_new_row(self, row_name):
        self.__rows[row_name] = SortedDict()
        for r, c in self.__rows.items():
            if r is not row_name:
                for c_title, _ in c.items():
                    self.__rows[row_name][c_title] = None
                break

    def __repr__(self):
        return self.__str__()

    def __str__(self):
        table = ['rows ' + u'\u2193' + ' columns ' + u'\u2192']
        for r_title, col in self.row_items():
            row = [str(r_title), '->']
            for c_title, val in col.items():
                row.append('({0}, {1})'.format(c_title, val))

            table.append(' '.join(row))

        return '\n'.join(table)
开发者ID:udeyrishi,项目名称:hello-distributed-programming,代码行数:55,代码来源:excel_export.py

示例2: __init__

# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import items [as 别名]
class PositionMapping:

    __slots__ = ('_pos', '_posmap')

    DUPLICATION_CHECK = True

    def __init__(self):
        self._pos = 0
        self._posmap = SortedDict()

    def items(self):
        return self._posmap.items()

    #
    # Properties
    #

    @property
    def pos(self):
        return self._pos

    @pos.setter
    def pos(self, v):
        self._pos = v

    #
    # Public methods
    #

    def add_mapping(self, start_pos, length, obj):
        # duplication check
        if self.DUPLICATION_CHECK:
            try:
                pre = next(self._posmap.irange(maximum=start_pos, reverse=True))
                if start_pos in self._posmap[pre]:
                    raise ValueError("New mapping is overlapping with an existing element.")
            except StopIteration:
                pass

        self._posmap[start_pos] = PositionMappingElement(start_pos, length, obj)

    def tick_pos(self, delta):
        self._pos += delta

    def get_node(self, pos):
        element = self.get_element(pos)
        if element is None:
            return None
        return element.obj

    def get_element(self, pos):
        try:
            pre = next(self._posmap.irange(maximum=pos, reverse=True))
        except StopIteration:
            return None

        element = self._posmap[pre]
        if pos in element:
            return element
        return None
开发者ID:AmesianX,项目名称:angr,代码行数:62,代码来源:structured_codegen.py

示例3: test_clear

# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import items [as 别名]
def test_clear():
    mapping = [(val, pos) for pos, val in enumerate(string.ascii_lowercase)]
    temp = SortedDict(mapping)
    assert len(temp) == 26
    assert list(temp.items()) == mapping
    temp.clear()
    assert len(temp) == 0
开发者ID:danbornside,项目名称:sorted_containers,代码行数:9,代码来源:test_coverage_sorteddict.py

示例4: test_update

# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import items [as 别名]
def test_update():
    mapping = [(val, pos) for pos, val in enumerate(string.ascii_lowercase)]
    temp = SortedDict()
    temp.update()
    temp.update(mapping)
    temp.update(dict(mapping))
    assert list(temp.items()) == mapping
开发者ID:Muon,项目名称:sorted_containers,代码行数:9,代码来源:test_coverage_sorteddict.py

示例5: InMemoryStorage

# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import items [as 别名]
class InMemoryStorage(object):
    def __init__(self):
        self.kvstore = SortedDict()  # hashtable

    def get(self, k):
        try:
            return self.kvstore[k]
        except:
            return 1

    def put(self, k, v):
        self.kvstore[k] = v
        return 0

    def delete(self, k):
        try:
            del self.kvstore[k]
            return 0
        except:
            return 1

    def split(self, section, keyspace_mid):
        """ delete one half of keystore for group split operation """
        midKey = None
        for key in self.kvstore.keys():  # TODO make more efficient for better performance
            if key > str(keyspace_mid):  # use iloc to estimate midpoint
                midKey = self.kvstore.index(key)
                break

        if section:  # section is either 0 or 1
            self.kvstore = self.kvstore.items()[midKey:]

        else:
            self.kvstore = self.kvstore.items()[:midKey]
        print(self.kvstore)
        return 0

    def save(self):  # need metadata here
        save_state("data/backup/db_copy.pkl", self.kvstore)

    def load(self):
        self.kvstore = load_state("data/backup/db_copy.pkl")
开发者ID:hatmer,项目名称:python-congregate,代码行数:44,代码来源:storage.py

示例6: test_init

# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import items [as 别名]
def test_init():
    sdict = SortedDict()
    sdict._check()

    sdict = SortedDict()
    sdict._reset(17)
    sdict._check()

    sdict = SortedDict((val, -val) for val in range(10000))
    sdict._check()
    assert all(key == -val for key, val in sdict.items())

    sdict.clear()
    sdict._check()
    assert len(sdict) == 0

    sdict = SortedDict.fromkeys(range(1000), None)
    assert all(sdict[key] == None for key in range(1000))
开发者ID:grantjenks,项目名称:sorted_containers,代码行数:20,代码来源:test_stress_sorteddict.py

示例7: test_itemsview

# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import items [as 别名]
def test_itemsview():
    mapping = [(val, pos) for pos, val in enumerate(string.ascii_lowercase)]
    temp = SortedDict(mapping[:13])
    items = temp.items()

    assert len(items) == 13
    assert ('a', 0) in items
    assert list(items) == mapping[:13]
    assert items[0] == ('a', 0)
    assert items[-3:] == [('k', 10), ('l', 11), ('m', 12)]
    assert list(reversed(items)) == list(reversed(mapping[:13]))
    assert items.index(('f', 5)) == 5
    assert items.count(('m', 12)) == 1
    assert items.isdisjoint([('0', 26), ('1', 27)])
    assert not items.isdisjoint([('a', 0), ('b', 1)])

    temp.update(mapping[13:])

    assert len(items) == 26
    assert ('z', 25) in items
    assert list(items) == mapping

    that = dict(mapping)
    that_items = get_itemsview(that)

    assert items == that_items
    assert not (items != that_items)
    assert not (items < that_items)
    assert not (items > that_items)
    assert items <= that_items
    assert items >= that_items

    assert list(items & that_items) == mapping
    assert list(items | that_items) == mapping
    assert list(items - that_items) == []
    assert list(items ^ that_items) == []

    items = SortedDict(mapping[:2]).items()
    assert repr(items) == "SortedItemsView(SortedDict({'a': 0, 'b': 1}))"
开发者ID:grantjenks,项目名称:sorted_containers,代码行数:41,代码来源:test_coverage_sorteddict.py

示例8: __init__

# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import items [as 别名]
class KeyedRegion:
    """
    KeyedRegion keeps a mapping between stack offsets and all objects covering that offset. It assumes no variable in
    this region overlap with another variable in this region.

    Registers and function frames can all be viewed as a keyed region.
    """

    __slots__ = ('_storage', '_object_mapping', '_phi_node_contains' )

    def __init__(self, tree=None, phi_node_contains=None):
        self._storage = SortedDict() if tree is None else tree
        self._object_mapping = weakref.WeakValueDictionary()
        self._phi_node_contains = phi_node_contains

    def __getstate__(self):
        return self._storage, dict(self._object_mapping), self._phi_node_contains

    def __setstate__(self, s):
        self._storage, om, self._phi_node_contains = s
        self._object_mapping = weakref.WeakValueDictionary(om)

    def _get_container(self, offset):
        try:
            base_offset = next(self._storage.irange(maximum=offset, reverse=True))
        except StopIteration:
            return offset, None
        else:
            container = self._storage[base_offset]
            if container.includes(offset):
                return base_offset, container
            return offset, None

    def __contains__(self, offset):
        """
        Test if there is at least one variable covering the given offset.

        :param offset:
        :return:
        """

        if type(offset) is not int:
            raise TypeError("KeyedRegion only accepts concrete offsets.")

        return self._get_container(offset)[1] is not None

    def __len__(self):
        return len(self._storage)

    def __iter__(self):
        return iter(self._storage.values())

    def __eq__(self, other):
        if set(self._storage.keys()) != set(other._storage.keys()):
            return False

        for k, v in self._storage.items():
            if v != other._storage[k]:
                return False

        return True

    def copy(self):
        if not self._storage:
            return KeyedRegion(phi_node_contains=self._phi_node_contains)

        kr = KeyedRegion(phi_node_contains=self._phi_node_contains)
        for key, ro in self._storage.items():
            kr._storage[key] = ro.copy()
        kr._object_mapping = self._object_mapping.copy()
        return kr

    def merge(self, other, replacements=None):
        """
        Merge another KeyedRegion into this KeyedRegion.

        :param KeyedRegion other: The other instance to merge with.
        :return: None
        """

        # TODO: is the current solution not optimal enough?
        for _, item in other._storage.items():  # type: RegionObject
            for so in item.stored_objects:  # type: StoredObject
                if replacements and so.obj in replacements:
                    so = StoredObject(so.start, replacements[so.obj], so.size)
                self._object_mapping[so.obj_id] = so
                self.__store(so, overwrite=False)

        return self

    def replace(self, replacements):
        """
        Replace variables with other variables.

        :param dict replacements:   A dict of variable replacements.
        :return:                    self
        """

        for old_var, new_var in replacements.items():
            old_var_id = id(old_var)
#.........这里部分代码省略.........
开发者ID:AmesianX,项目名称:angr,代码行数:103,代码来源:keyed_region.py

示例9: Replica

# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import items [as 别名]

#.........这里部分代码省略.........
    def isNextInOrdering(self, commit: Commit):
        viewNo, ppSeqNo = commit.viewNo, commit.ppSeqNo
        if self.ordered and self.ordered[-1] == (viewNo, ppSeqNo-1):
            return True
        for (v, p) in self.commits:
            if v < viewNo:
                # Have commits from previous view that are unordered.
                # TODO: Question: would commits be always ordered, what if
                # some are never ordered and its fine, go to PBFT.
                return False
            if v == viewNo and p < ppSeqNo and (v, p) not in self.ordered:
                # If unordered commits are found with lower ppSeqNo then this
                # cannot be ordered.
                return False

        # TODO: Revisit PBFT paper, how to make sure that last request of the
        # last view has been ordered? Need change in `VIEW CHANGE` mechanism.
        # Somehow view change needs to communicate what the last request was.
        # Also what if some COMMITs were completely missed in the same view
        return True

    def orderStashedCommits(self):
        # TODO: What if the first few commits were out of order and stashed?
        # `self.ordered` would be empty
        if self.ordered:
            lastOrdered = self.ordered[-1]
            vToRemove = set()
            for v in self.stashedCommitsForOrdering:
                if v < lastOrdered[0] and self.stashedCommitsForOrdering[v]:
                    raise RuntimeError("{} found commits from previous view {}"
                                       " that were not ordered but last ordered"
                                       " is {}".format(self, v, lastOrdered))
                pToRemove = set()
                for p, commit in self.stashedCommitsForOrdering[v].items():
                    if (v == lastOrdered[0] and lastOrdered == (v, p - 1)) or \
                            (v > lastOrdered[0] and
                                self.isLowestCommitInView(commit)):
                        logger.debug("{} ordering stashed commit {}".
                                     format(self, commit))
                        if self.tryOrdering(commit):
                            lastOrdered = (v, p)
                            pToRemove.add(p)

                for p in pToRemove:
                    del self.stashedCommitsForOrdering[v][p]
                if not self.stashedCommitsForOrdering[v]:
                    vToRemove.add(v)

            for v in vToRemove:
                del self.stashedCommitsForOrdering[v]

            # if self.stashedCommitsForOrdering:
            #     self._schedule(self.orderStashedCommits, 2)
            if not self.stashedCommitsForOrdering:
                self.stopRepeating(self.orderStashedCommits)

    def isLowestCommitInView(self, commit):
        # TODO: Assumption: This assumes that at least one commit that was sent
        #  for any request by any node has been received in the view of this
        # commit
        ppSeqNos = []
        for v, p in self.commits:
            if v == commit.viewNo:
                ppSeqNos.append(p)
        return min(ppSeqNos) == commit.ppSeqNo if ppSeqNos else True
开发者ID:evernym,项目名称:plenum,代码行数:69,代码来源:replica.py

示例10: Node

# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import items [as 别名]
class Node(BaseNode, Mapping):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.rest = None

    def _select(self, key):
        for k, v in reversed(list(self.values.items())):
            if k <= key:
                return v

        return self.rest

    def _insert(self, key, value):
        result = self._select(key)._insert(key, value)
        self.changed = True

        if result is None:
            return

        key, other = result
        return super()._insert(key, other)

    def _split(self):
        other = LazyNode(node=Node(tree=self.tree, changed=True),
            tree=self.tree)

        values = self.values.items()
        self.values = SortedDict(values[:len(values) // 2])
        other.values = SortedDict(values[len(values) // 2:])

        key, value = other.values.popitem(last=False)
        other.rest = value

        return (key, other)

    def _commit(self):
        self.rest._commit()

        for child in self.values.values():
            child._commit()

        data = packb({
            'rest': self.rest.offset,
            'values': {k: v.offset for k, v in self.values.items()},
        })

        self.tree.chunk.write(ChunkId.Node, data)
        return self.tree.chunk.tell()

    def __getitem__(self, key):
        return self._select(key)[key]

    def __len__(self):
        return sum([len(value) for child in self.values.values() + \
            len(self.rest)])

    def __iter__(self):
        for key in self.rest:
            yield key

        for child in self.values.values():
            for key in child:
                yield key
开发者ID:Eragon666,项目名称:ModerneDatabases,代码行数:65,代码来源:btree.py

示例11: IntervalTree

# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import items [as 别名]

#.........这里部分代码省略.........
        True
        >>> tree.overlaps(1.7)
        False
        >>> tree.overlaps(1.7, 1.8)
        False
        >>> tree.overlaps(-1.2, -1.1)
        False
        >>> tree.overlaps(-1.2, -1.0)
        True
    
    Sizing::

        >>> tree = IntervalTree([Interval(-1.1, 1.1), Interval(-0.5, 1.5), Interval(0.5, 1.7)])
        >>> len(tree)
        3
        >>> tree.is_empty()
        False
        >>> IntervalTree().is_empty()
        True
        >>> not tree
        False
        >>> not IntervalTree()
        True
        >>> print(tree.begin())    # using print() because of floats in Python 2.6
        -1.1
        >>> print(tree.end())      # ditto
        1.7
        
    Iteration::

        >>> tree = IntervalTree([Interval(-11, 11), Interval(-5, 15), Interval(5, 17)])
        >>> [iv.begin for iv in sorted(tree)]
        [-11, -5, 5]
        >>> assert tree.items() == set([Interval(-5, 15), Interval(-11, 11), Interval(5, 17)])

    Copy- and typecasting, pickling::
    
        >>> tree0 = IntervalTree([Interval(0, 1, "x"), Interval(1, 2, ["x"])])
        >>> tree1 = IntervalTree(tree0)  # Shares Interval objects
        >>> tree2 = tree0.copy()         # Shallow copy (same as above, as Intervals are singletons)
        >>> import pickle
        >>> tree3 = pickle.loads(pickle.dumps(tree0))  # Deep copy
        >>> list(tree0[1])[0].data[0] = "y"  # affects shallow copies, but not deep copies
        >>> tree0
        IntervalTree([Interval(0, 1, 'x'), Interval(1, 2, ['y'])])
        >>> tree1
        IntervalTree([Interval(0, 1, 'x'), Interval(1, 2, ['y'])])
        >>> tree2
        IntervalTree([Interval(0, 1, 'x'), Interval(1, 2, ['y'])])
        >>> tree3
        IntervalTree([Interval(0, 1, 'x'), Interval(1, 2, ['x'])])
        
    Equality testing::
    
        >>> IntervalTree([Interval(0, 1)]) == IntervalTree([Interval(0, 1)])
        True
        >>> IntervalTree([Interval(0, 1)]) == IntervalTree([Interval(0, 1, "x")])
        False
    """
    @classmethod
    def from_tuples(cls, tups):
        """
        Create a new IntervalTree from an iterable of 2- or 3-tuples,
         where the tuple lists begin, end, and optionally data.
        """
        ivs = [Interval(*t) for t in tups]
开发者ID:ProgVal,项目名称:intervaltree,代码行数:70,代码来源:intervaltree.py

示例12: KeyedRegion

# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import items [as 别名]
class KeyedRegion(object):
    """
    KeyedRegion keeps a mapping between stack offsets and all objects covering that offset. It assumes no variable in
    this region overlap with another variable in this region.

    Registers and function frames can all be viewed as a keyed region.
    """
    def __init__(self, tree=None):
        self._storage = SortedDict() if tree is None else tree

    def _get_container(self, offset):
        try:
            base_offset = next(self._storage.irange(maximum=offset, reverse=True))
        except StopIteration:
            return offset, None
        else:
            container = self._storage[base_offset]
            if container.includes(offset):
                return base_offset, container
            return offset, None

    def __contains__(self, offset):
        """
        Test if there is at least one varaible covering the given offset.

        :param offset:
        :return:
        """

        return self._get_container(offset)[1] is not None

    def __len__(self):
        return len(self._storage)

    def __iter__(self):
        return iter(self._storage.values())

    def __eq__(self, other):
        if set(self._storage.keys()) != set(other._storage.keys()):
            return False

        for k, v in self._storage.items():
            if v != other._storage[k]:
                return False

        return True

    def copy(self):
        if not self._storage:
            return KeyedRegion()

        kr = KeyedRegion()
        for key, ro in self._storage.items():
            kr._storage[key] = ro.copy()
        return kr

    def merge(self, other, make_phi_func=None):
        """
        Merge another KeyedRegion into this KeyedRegion.

        :param KeyedRegion other: The other instance to merge with.
        :return: None
        """

        # TODO: is the current solution not optimal enough?
        for _, item in other._storage.items():  # type: RegionObject
            for loc_and_var in item.stored_objects:
                self.__store(loc_and_var, overwrite=False, make_phi_func=make_phi_func)

        return self

    def dbg_repr(self):
        """
        Get a debugging representation of this keyed region.
        :return: A string of debugging output.
        """
        keys = self._storage.keys()
        offset_to_vars = { }

        for key in sorted(keys):
            ro = self._storage[key]
            variables = [ obj.obj for obj in ro.stored_objects ]
            offset_to_vars[key] = variables

        s = [ ]
        for offset, variables in offset_to_vars.items():
            s.append("Offset %#x: %s" % (offset, variables))
        return "\n".join(s)

    def add_variable(self, start, variable):
        """
        Add a variable to this region at the given offset.

        :param int start:
        :param SimVariable variable:
        :return: None
        """

        size = variable.size if variable.size is not None else 1

#.........这里部分代码省略.........
开发者ID:angriestalien,项目名称:angr,代码行数:103,代码来源:keyed_region.py

示例13: generate_report

# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import items [as 别名]
def generate_report(year=None, quarter=None):

    dir = os.path.dirname(__file__)
    config = ConfigParser()
    config.read(os.path.join(dir, 'config.cfg'))

    report = SortedDict()
    gbif = gbif_downloads()

    for date_str, downloads in gbif.items():

        m, y = map(int, date_str.split('-'))

        if year and y != year:
            continue

        if quarter and m not in quarter_months[quarter]:
            continue

        report_add_entry(report, y, m, 'gbif_records', downloads['records'])
        report_add_entry(report, y, m, 'gbif_download_events', downloads['download_events'])


    last_timestamp = 0

    # Load the legacy data
    # This has been derived from redis/celery task queue
    # Which is how we did things before storing the download count in the
    # ckanpackager stats.db
    with open(os.path.join(dir, 'src', 'legacy.json')) as data_file:
        data = json.load(data_file)

        for row in data:
            ts = timestring.Date(row['date'])

            # We want to know what the last timestamp is
            if ts.to_unixtime() > last_timestamp:
                last_timestamp = ts.to_unixtime()

            process_row(report, year, quarter, ts, row.get('resource_id'), row.get('count', None))

    db = config.get('sqlite', 'db')

    if not os.path.isfile(db):
        raise IOError('Stats.db does not exist')

    conn = sqlite3.connect(db)

    # Retrieve all requests received after the last entry in the legacy data
    requests = conn.execute("SELECT * FROM requests WHERE timestamp > '%s'" % last_timestamp)

    # Loop through requests, adding them to the stats
    for request in requests:
        resource_id = request[2]
        ts = datetime.datetime.fromtimestamp(request[3])
        count = int(request[4]) if request[4] else None
        process_row(report, year, quarter, ts, resource_id, count)


    header = OrderedDict([
        ('collection_records', 'Collection records'),
        ('other_records', 'Other records'),
        ('gbif_records', 'GBIF records'),
        ('collection_download_events', 'Collection download events'),
        ('other_download_events', 'Other download events'),
        ('gbif_download_events', 'GBIF download events'),
    ])

    table = Texttable()
    table.set_deco(Texttable.HEADER)
    rows = []

    totals = OrderedDict([(k, 0) for k in header.keys()])

    for year, months in report.items():
        if len(rows) == 0:
            rows.append(['Month'] + header.values())
        for month, items in months.items():
            row = [get_color_string(bcolors.GREEN, '%s %s' % (calendar.month_abbr[month], str(year)[2:4]))]

            for key in header.keys():
                row.append(str(items.get(key, '')))

                # Update totals
                totals[key] += items.get(key, 0)

            rows.append(row)
    rows.append([get_color_string(bcolors.YELLOW, str(t)) for t in ['Totals'] + totals.values()])

    table.add_rows(rows)
    print(table.draw())
开发者ID:NaturalHistoryMuseum,项目名称:DataPortalStats,代码行数:93,代码来源:run.py

示例14: CacheStore

# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import items [as 别名]
class CacheStore(object):
    class CacheItem(object):
        __slots__ = ('valid', 'data')

        def __init__(self):
            self.valid = Event()
            self.data = None

    def __init__(self, key=None):
        self.lock = RLock()
        self.store = SortedDict(key)

    def __getitem__(self, item):
        return self.get(item)

    def put(self, key, data):
        with self.lock:
            try:
                item = self.store[key]
                item.data = data
                item.valid.set()
                return False
            except KeyError:
                item = self.CacheItem()
                item.data = data
                item.valid.set()
                self.store[key] = item
                return True

    def update(self, **kwargs):
        with self.lock:
            items = {}
            created = []
            updated = []
            for k, v in kwargs.items():
                items[k] = self.CacheItem()
                items[k].data = v
                items[k].valid.set()
                if k in self.store:
                    updated.append(k)
                else:
                    created.append(k)

            self.store.update(**items)
            return created, updated

    def update_one(self, key, **kwargs):
        with self.lock:
            item = self.get(key)
            if not item:
                return False

            for k, v in kwargs.items():
                set(item, k, v)

            self.put(key, item)
            return True

    def update_many(self, key, predicate, **kwargs):
        with self.lock:
            updated = []
            for k, v in self.itervalid():
                if predicate(v):
                    if self.update_one(k, **kwargs):
                        updated.append(key)

            return updated

    def get(self, key, default=None, timeout=None):
        item = self.store.get(key)
        if item:
            item.valid.wait(timeout)
            return item.data

        return default

    def remove(self, key):
        with self.lock:
            try:
                del self.store[key]
                return True
            except KeyError:
                return False

    def remove_many(self, keys):
        with self.lock:
            removed = []
            for key in keys:
                try:
                    del self.store[key]
                    removed.append(key)
                except KeyError:
                    pass

            return removed

    def clear(self):
        with self.lock:
            items = list(self.store.keys())
            self.store.clear()
#.........这里部分代码省略.........
开发者ID:erinix,项目名称:middleware,代码行数:103,代码来源:cache.py

示例15: CacheStore

# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import items [as 别名]
class CacheStore(object):
    class CacheItem(object):
        def __init__(self):
            self.valid = Event()
            self.data = None

    def __init__(self, key=None):
        self.lock = RLock()
        self.store = SortedDict(key)

    def __getitem__(self, item):
        return self.get(item)

    def put(self, key, data):
        with self.lock:
            item = self.store[key] if key in self.store else self.CacheItem()
            item.data = data
            item.valid.set()

            if key not in self.store:
                self.store[key] = item
                return True

            return False

    def get(self, key, default=None, timeout=None):
        item = self.store.get(key)
        if item:
            item.valid.wait(timeout)
            return item.data

        return default

    def remove(self, key):
        with self.lock:
            if key in self.store:
                del self.store[key]
                return True

            return False

    def exists(self, key):
        return key in self.store

    def rename(self, oldkey, newkey):
        with self.lock:
            obj = self.get(oldkey)
            obj['id'] = newkey
            self.put(newkey, obj)
            self.remove(oldkey)

    def is_valid(self, key):
        item = self.store.get(key)
        if item:
            return item.valid.is_set()

        return False

    def invalidate(self, key):
        with self.lock:
            item = self.store.get(key)
            if item:
                item.valid.clear()

    def itervalid(self):
        for key, value in list(self.store.items()):
            if value.valid.is_set():
                yield (key, value.data)

    def validvalues(self):
        for value in list(self.store.values()):
            if value.valid.is_set():
                yield value.data

    def remove_predicate(self, predicate):
        result = []
        for k, v in self.itervalid():
            if predicate(v):
                self.remove(k)
                result.append(k)

        return result

    def query(self, *filter, **params):
        return wrap(list(self.validvalues())).query(*filter, **params)
开发者ID:650elx,项目名称:middleware,代码行数:87,代码来源:cache.py


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