本文整理汇总了Python中sortedcontainers.SortedDict.values方法的典型用法代码示例。如果您正苦于以下问题:Python SortedDict.values方法的具体用法?Python SortedDict.values怎么用?Python SortedDict.values使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sortedcontainers.SortedDict
的用法示例。
在下文中一共展示了SortedDict.values方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: signal_crosses
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import values [as 别名]
def signal_crosses(short_moving_averages, long_moving_averages):
short_moving_averages = SortedDict(short_moving_averages)
long_moving_averages = SortedDict(long_moving_averages)
short_len = len(short_moving_averages.values())
long_len = len(long_moving_averages.values())
if(short_len != long_len):
print "[Error] signal_crosses: inputs must be same size"
return {}
signal_crosses = {}
last_diff_dir = 0
for date, short_average in short_moving_averages.iteritems():
long_average = long_moving_averages[date]
diff = short_average - long_average
if(last_diff_dir == 0):
signal_crosses[date] = HOLD
if(diff != 0):
last_diff_dir = sign(diff)
continue
if(sign(diff) != last_diff_dir):
signal_crosses[date] = BUY if last_diff_dir < 0 else SELL
last_diff_dir = -last_diff_dir
else:
signal_crosses[date] = HOLD
return SortedDict(signal_crosses)
示例2: get_sort_vector
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import values [as 别名]
def get_sort_vector( self, col, order, key_func = None, filter_func = None ) :
if filter_func : # is not None,
# create a sort vector from scratch, filtered
getter_func = self._make_key_getter( col )
sorted_dict = SortedDict( key_func )
for j in range( len( self.vocab ) ) :
if filter_func( self.vocab_kview[j], self.vocab_vview[j][1] ) :
k = getter_func( j )
sorted_dict[ k ] = j
vector = sorted_dict.values()
if order != Qt.AscendingOrder :
vector = [j for j in reversed( vector ) ]
else : # no filter_func, try to reuse a cached vector
vector = self.sort_up_vectors[ col ]
if not vector or key_func is not self.sort_key_funcs[ col ] :
# there is no ascending vector for this column, or there
# is one but it was made with a different key_func.
getter_func = self._make_key_getter( col )
sorted_dict = SortedDict( key_func )
for j in range( len( self.vocab ) ) :
k = getter_func( j )
sorted_dict[ k ] = j
vector = self.sort_up_vectors[ col ] = sorted_dict.values()
self.sort_key_funcs[ col ] = key_func
if order != Qt.AscendingOrder :
# what is wanted is a descending order vector, do we have one?
if self.sort_down_vectors[ col ] is None :
# no, so create one from the asc. vector we now have
self.sort_down_vectors[ col ] = [ j for j in reversed( vector ) ]
# yes we do (now)
vector = self.sort_down_vectors[ col ]
# one way or another, vector is a sort vector
# note the actual word count available through that vector
self.active_word_count = len(vector)
return vector
示例3: sort
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import values [as 别名]
def sort( self, col, order ) :
self.active_sort_vector = []
if 0 == len(self.message_tuples) : # nothing to display
return
self.layoutAboutToBeChanged.emit([],QAbstractItemModel.VerticalSortHint)
# treat columns 0 and 1 the same
if col : # is 1 or 2
col -= 1 # make it 0 or 1
# we need an ascending vector in all cases.
vector = self.sort_vectors_ascending[ col ]
if vector is None : # we need to create the ascending vector
sorted_dict = SortedDict()
for j in range( len( self.message_tuples ) ) :
line_col_msg_tuple = self.message_tuples[ j ]
if col : # is 1, meaning sort on messages
key = line_col_msg_tuple[2]+line_col_msg_tuple[0]
else : # col is 0, sort on line#+col#
key = line_col_msg_tuple[0]+line_col_msg_tuple[1]
key += str(j) # ensure uniqueness
sorted_dict[key] = j
vector = self.sort_vectors_ascending[ col ] = sorted_dict.values()
# vector now has an ascending sort vector which is cached..
if order == Qt.DescendingOrder : # ..but we need the descending one
if self.sort_vectors_descending[ col ] is None : # we need to make it
self.sort_vectors_descending[ col ] = [ j for j in reversed( vector ) ]
vector = self.sort_vectors_descending[ col ]
self.active_sort_vector = vector
self.layoutChanged.emit([],QAbstractItemModel.VerticalSortHint)
示例4: ProductReport
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import values [as 别名]
class ProductReport(object):
"""Read overview page of one job group and generate a report for the product."""
def __init__(self, browser, job_group_url, root_url, args):
"""Construct a product report object with options."""
self.args = args
self.job_group_url = job_group_url
self.group = job_group_url.split('/')[-1]
current_url, previous_url = get_build_urls_to_compare(browser, job_group_url, args.builds, args.against_reviewed, args.running_threshold)
# read last finished
current_details = browser.get_soup(current_url)
previous_details = browser.get_soup(previous_url)
for details in current_details, previous_details:
assert sum(int(badge.text) for badge in details.find_all(class_='badge')) > 0, \
"invalid page with no test results found, make sure you specified valid builds (leading zero missing?)"
current_summary = parse_summary(current_details)
previous_summary = parse_summary(previous_details)
changes = {k: v - previous_summary.get(k, 0) for k, v in iteritems(current_summary) if k != 'none' and k != 'incomplete'}
log.info("Changes since last build:\n\t%s" % '\n\t'.join("%s: %s" % (k, v) for k, v in iteritems(changes)))
self.build = get_build_nr(current_url)
self.ref_build = get_build_nr(previous_url)
# for each architecture iterate over all
cur_archs, prev_archs = (set(arch.text for arch in details.find_all('th', id=re.compile('flavor_'))) for details in [current_details, previous_details])
archs = cur_archs
if args.arch:
assert args.arch in cur_archs, "Selected arch {} was not found in test results {}".format(args.arch, cur_archs)
archs = [args.arch]
self.missing_archs = sorted(prev_archs - cur_archs)
if self.missing_archs:
log.info("%s missing completely from current run: %s" %
(pluralize(len(self.missing_archs), "architecture is", "architectures are"), ', '.join(self.missing_archs)))
# create arch reports
self.reports = SortedDict()
progress_browser = progress_browser_factory(args) if args.query_issue_status else None
bugzilla_browser = bugzilla_browser_factory(args) if args.query_issue_status else None
for arch in sorted(archs):
results = get_arch_state_results(arch, current_details, previous_details, args.output_state_results)
self.reports[arch] = ArchReport(arch, results, args, root_url, progress_browser, bugzilla_browser, browser)
def __str__(self):
"""Return report for product."""
now_str = datetime.datetime.now().strftime('%Y-%m-%d - %H:%M')
missing_archs_str = '\n * **Missing architectures**: %s' % ', '.join(self.missing_archs) if self.missing_archs else ''
build_str = self.build
if self.args.verbose_test and self.args.verbose_test > 1:
build_str += ' (reference %s)' % self.ref_build
openqa_review_report_product = openqa_review_report_product_template.substitute({
'now': now_str,
'build': build_str,
'common_issues': common_issues(missing_archs_str, self.args.show_empty),
'arch_report': '<hr>'.join(map(str, self.reports.values()))
})
return openqa_review_report_product
示例5: simulation
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import values [as 别名]
def simulation(prices, signal_crosses, budget):
simulation = {}
prices = SortedDict(prices)
cash_on_hand = budget
shares = 0
for date, price in prices.iteritems():
signal = signal_crosses[date]
if(signal == SELL):
shares += cash_on_hand / price
cash_on_hand = 0
elif(signal == BUY):
cash_on_hand += shares * price
shares = 0
simulation[date] = { 'shares': shares, 'cash_on_hand': cash_on_hand }
final_value = max(cash_on_hand, shares * prices.values()[-1])
earnings = final_value - budget
return simulation, earnings
示例6: ImageFlow
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import values [as 别名]
class ImageFlow(QtCore.QObject):
# _dataPosChanged = QtCore.pyqtSignal(int)
def __init__(self):
self.processors = SortedDict()
def add_processor(self,processor):
self.processors[len(self.processors)] = processor
def apply(self,data):
if len(self.processors) == 0:
return data
data = data.copy()
for p in self.processors.values():
data = p.apply(data)
return data
示例7: test_valuesview
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import values [as 别名]
def test_valuesview():
mapping = [(val, pos) for pos, val in enumerate(string.ascii_lowercase)]
temp = SortedDict(mapping[:13])
values = temp.values()
assert len(values) == 13
assert 0 in values
assert list(values) == [pos for val, pos in mapping[:13]]
assert values[0] == 0
assert values[-3:] == [10, 11, 12]
assert list(reversed(values)) == list(reversed(range(13)))
assert values.index(5) == 5
assert values.count(10) == 1
temp.update(mapping[13:])
assert len(values) == 26
assert 25 in values
assert list(values) == [pos for val, pos in mapping]
values = SortedDict(mapping[:2]).values()
assert repr(values) == "SortedValuesView(SortedDict({'a': 0, 'b': 1}))"
示例8: plotWidth
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import values [as 别名]
def plotWidth(dwdictX,fname,nameX,mX,cuts):
sorted_dwdictX = SortedDict(dwdictX)
n = len(sorted_dwdictX)-1
x = array('d',sorted_dwdictX.keys())
y = array('d',sorted_dwdictX.values())
gwX = TGraph(n,x,y)
gwX.SetName("gwX")
gwX.SetTitle("")
gwX.GetXaxis().SetTitle("tan#beta")
gwX.GetYaxis().SetTitle("#Gamma_{#it{"+nameX+"}}/#it{m}_{#it{"+nameX+"}} [%]")
gwX.SetLineColor(ROOT.kBlack)
gwX.SetMarkerColor(ROOT.kBlack)
gwX.SetMarkerStyle(20)
gwX.SetMarkerSize(0.5)
ptxt = TPaveText(0.62,0.70,0.87,0.87,"NDC")
ptxt.SetFillStyle(4000) #will be transparent
ptxt.SetFillColor(0)
ptxt.SetTextFont(42)
ptxt.SetBorderSize(0)
ptxt.AddText("sin(#beta-#alpha)=1")
ptxt.AddText("#it{m}_{#it{"+nameX+"}}="+str(mX)+" GeV")
c = TCanvas("c","c",600,600)
c.cd()
c.SetLogx()
c.SetLogy()
c.SetGridx()
c.SetGridy()
c.SetTicks(1,1)
c.Draw()
# gwX.Draw("p")
gwX.Draw()
ptxt.Draw("same")
c.Modified()
c.Update()
c.SaveAs(fname)
示例9: TreePage
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import values [as 别名]
class TreePage(BasePage):
"""
Page object, implemented with a sorted dict. Who knows what's underneath!
"""
def __init__(self, *args, **kwargs):
storage = kwargs.pop("storage", None)
super(TreePage, self).__init__(*args, **kwargs)
self._storage = SortedDict() if storage is None else storage
def keys(self):
if len(self._storage) == 0:
return set()
else:
return set.union(*(set(range(*self._resolve_range(mo))) for mo in self._storage.values()))
def replace_mo(self, state, old_mo, new_mo):
start, end = self._resolve_range(old_mo)
for key in self._storage.irange(start, end-1):
val = self._storage[key]
if val is old_mo:
#assert new_mo.includes(a)
self._storage[key] = new_mo
def store_overwrite(self, state, new_mo, start, end):
# iterate over each item we might overwrite
# track our mutations separately since we're in the process of iterating
deletes = []
updates = { start: new_mo }
for key in self._storage.irange(maximum=end-1, reverse=True):
old_mo = self._storage[key]
# make sure we aren't overwriting all of an item that overlaps the end boundary
if end < self._page_addr + self._page_size and end not in updates and old_mo.includes(end):
updates[end] = old_mo
# we can't set a minimum on the range because we need to do the above for
# the first object before start too
if key < start:
break
# delete any key that falls within the range
deletes.append(key)
#assert all(m.includes(i) for i,m in updates.items())
# perform mutations
for key in deletes:
del self._storage[key]
self._storage.update(updates)
def store_underwrite(self, state, new_mo, start, end):
# track the point that we need to write up to
last_missing = end - 1
# track also updates since we can't update while iterating
updates = {}
for key in self._storage.irange(maximum=end-1, reverse=True):
mo = self._storage[key]
# if the mo stops
if mo.base <= last_missing and not mo.includes(last_missing):
updates[max(mo.last_addr+1, start)] = new_mo
last_missing = mo.base - 1
# we can't set a minimum on the range because we need to do the above for
# the first object before start too
if last_missing < start:
break
# if there are no memory objects <= start, we won't have filled start yet
if last_missing >= start:
updates[start] = new_mo
#assert all(m.includes(i) for i,m in updates.items())
self._storage.update(updates)
def load_mo(self, state, page_idx):
"""
Loads a memory object from memory.
:param page_idx: the index into the page
:returns: a tuple of the object
"""
try:
key = next(self._storage.irange(maximum=page_idx, reverse=True))
except StopIteration:
return None
else:
return self._storage[key]
def load_slice(self, state, start, end):
"""
Return the memory objects overlapping with the provided slice.
:param start: the start address
#.........这里部分代码省略.........
示例10: Node
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import values [as 别名]
class Node(BaseNode):
def __init__(self, *args, **kwargs):
self.rest = None
super(Node, self).__init__(*args, **kwargs)
def _select(self, key):
"""
Selects the bucket the key should belong to.
"""
if key < min(self.bucket):
new_node = self.rest
return new_node
elif key >= max(self.bucket):
new_node = self.bucket.values()[-1]
return new_node
for i in range(0, len(self.bucket.keys())-1):
if key >= self.bucket.keys()[i] and key < self.bucket.keys()[i + 1]:
new_node = self.bucket.values()[i]
return new_node
pass
def _insert(self, key, value):
"""
Recursively inserts the key and value by selecting the bucket the key
should belong to, and inserting the key and value into that back. If the
node has been split, it inserts the key of the newly created node into
the bucket of this node.
"""
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):
"""
Creates a new node of the same type and splits the contents of the
bucket into two parts of an equal size. The lower keys are being stored
in the bucket of the current node. The higher keys are being stored in
the bucket of the new node. Afterwards, the new node is being returned.
"""
other = self.__class__(tree=self.tree)
size = len(self.bucket)
values = self.bucket.items()
self.bucket = 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 __getitem__(self, key):
selected_node = self._select(key)
return selected_node.__getitem__(key)
def __iter__(self):
if self.rest != None:
for key in self.rest:
yield key
for child in self.bucket.values():
for key in child:
yield key
def __len__(self):
return sum([len(child) for child in self.buckt.values()])+len(self.rest)
示例11: FederationRemoteSendQueue
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import values [as 别名]
class FederationRemoteSendQueue(object):
"""A drop in replacement for FederationSender"""
def __init__(self, hs):
self.server_name = hs.hostname
self.clock = hs.get_clock()
self.notifier = hs.get_notifier()
self.is_mine_id = hs.is_mine_id
self.presence_map = {} # Pending presence map user_id -> UserPresenceState
self.presence_changed = SortedDict() # Stream position -> list[user_id]
# Stores the destinations we need to explicitly send presence to about a
# given user.
# Stream position -> (user_id, destinations)
self.presence_destinations = SortedDict()
self.keyed_edu = {} # (destination, key) -> EDU
self.keyed_edu_changed = SortedDict() # stream position -> (destination, key)
self.edus = SortedDict() # stream position -> Edu
self.device_messages = SortedDict() # stream position -> destination
self.pos = 1
self.pos_time = SortedDict()
# EVERYTHING IS SAD. In particular, python only makes new scopes when
# we make a new function, so we need to make a new function so the inner
# lambda binds to the queue rather than to the name of the queue which
# changes. ARGH.
def register(name, queue):
LaterGauge("synapse_federation_send_queue_%s_size" % (queue_name,),
"", [], lambda: len(queue))
for queue_name in [
"presence_map", "presence_changed", "keyed_edu", "keyed_edu_changed",
"edus", "device_messages", "pos_time", "presence_destinations",
]:
register(queue_name, getattr(self, queue_name))
self.clock.looping_call(self._clear_queue, 30 * 1000)
def _next_pos(self):
pos = self.pos
self.pos += 1
self.pos_time[self.clock.time_msec()] = pos
return pos
def _clear_queue(self):
"""Clear the queues for anything older than N minutes"""
FIVE_MINUTES_AGO = 5 * 60 * 1000
now = self.clock.time_msec()
keys = self.pos_time.keys()
time = self.pos_time.bisect_left(now - FIVE_MINUTES_AGO)
if not keys[:time]:
return
position_to_delete = max(keys[:time])
for key in keys[:time]:
del self.pos_time[key]
self._clear_queue_before_pos(position_to_delete)
def _clear_queue_before_pos(self, position_to_delete):
"""Clear all the queues from before a given position"""
with Measure(self.clock, "send_queue._clear"):
# Delete things out of presence maps
keys = self.presence_changed.keys()
i = self.presence_changed.bisect_left(position_to_delete)
for key in keys[:i]:
del self.presence_changed[key]
user_ids = set(
user_id
for uids in self.presence_changed.values()
for user_id in uids
)
keys = self.presence_destinations.keys()
i = self.presence_destinations.bisect_left(position_to_delete)
for key in keys[:i]:
del self.presence_destinations[key]
user_ids.update(
user_id for user_id, _ in self.presence_destinations.values()
)
to_del = [
user_id for user_id in self.presence_map if user_id not in user_ids
]
for user_id in to_del:
del self.presence_map[user_id]
# Delete things out of keyed edus
keys = self.keyed_edu_changed.keys()
i = self.keyed_edu_changed.bisect_left(position_to_delete)
for key in keys[:i]:
#.........这里部分代码省略.........
示例12: Node
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import values [as 别名]
class Node(BaseNode):
def __init__(self, *args, **kwargs):
self.rest = None
self.offset = None
super().__init__(*args, **kwargs)
def _select(self, key):
"""
Selects the bucket the key should belong to.
"""
# If the key is smaller than the min or larger than the max, immediately return.
if key < min(self.bucket):
return self.rest
elif key >= max(self.bucket):
return self.bucket.values()[-1]
# Else find the correct node
for k, v in reversed(list(self.bucket.items())):
if k <= key:
return v
return self.rest
def _insert(self, key, value):
"""
Recursively inserts the key and value by selecting the bucket the key
should belong to, and inserting the key and value into that back. If the
node has been split, it inserts the key of the newly created node into
the bucket of this node.
"""
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)
#other = Node(self.tree)
values = self.bucket.items()
self.bucket = SortedDict(values[:len(values) // 2])
other.bucket = SortedDict(values[len(values) // 2:])
key, value = other.bucket.popitem(last=False)
other.rest = value
return (key, other)
def _commit(self):
self.rest._commit()
for child in self.bucket.values():
child._commit()
data = packb({
'rest': self.rest.offset,
'values': {k: v.offset for k, v in self.bucket.items()}
})
return self.tree.store.write(data)
def __getitem__(self, key):
return self._select(key)[key]
def __len__(self):
print(len(self.rest))
print (self.bucket.values())
return sum([len(child) for child in self.bucket.values()]) + len(self.rest)
def __iter__(self):
for key in self.rest:
yield key
for child in self.bucket.values():
for key in child:
yield key
示例13: test_values
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import values [as 别名]
def test_values():
mapping = [(val, pos) for pos, val in enumerate(string.ascii_lowercase)]
temp = SortedDict(mapping)
assert list(temp.values()) == [pos for key, pos in mapping]
示例14: __init__
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import values [as 别名]
class Topics:
"""
A class that manages a collection of `Topic`s.
"""
def __init__(self):
self.logger = getLogger('topics')
self.logger.info('started session')
self.clear()
def clear(self):
self.logger.info('Cleared all topics and received data')
self.topic_list = SortedDict()
self.transfers = dict()
def create(self, topic, source='remote'):
# Create the topic if it doesn't exist already
if not topic in self.topic_list:
self.topic_list[topic] = Topic(topic,source=source)
self.logger.info('new:topic ' + topic)
def process(self, topic, payload, options=None):
# Create the topic if it doesn't exist already
self.create(topic)
# Add the new sample
self.topic_list[topic].new_sample(payload,options)
# logging
if options:
self.logger.debug('new sample | {0} [{1}] {2}'.format(topic, options['index'], payload))
else:
self.logger.debug('new sample | {0} {1}'.format(topic, payload))
# If there is an active transfer, transfer received data to the queue
if topic in self.transfers:
# If transfer requires indexed data, check there is an index
if self.transfers[topic]['type'] == 'indexed' and options is not None:
x = options['index']
self.transfers[topic]['queue'].put([x, payload])
# For linear data, provide sample id for x and payload for y
elif self.transfers[topic]['type'] == 'linear':
x = self.transfers[topic]['lastindex']
self.transfers[topic]['queue'].put([x, payload])
self.transfers[topic]['lastindex'] += 1
def ls(self,source='remote'):
if source is None:
return sorted([t.name for t in self.topic_list.keys()])
else:
return sorted([t.name for t in self.topic_list.values() if t.source == source])
def samples(self,topic,amount=1):
if not topic in self.topic_list:
return None
if amount == 0 or amount is None:
return self.topic_list[topic].raw
return self.topic_list[topic].raw[-amount:]
def count(self,topic):
if not topic in self.topic_list:
return 0
return len(self.topic_list[topic].raw)
def exists(self,topic):
return topic in self.topic_list
def transfer(self, topic, queue, transfer_type = "linear"):
# If the topic data is not already transfered to some queue
if not topic in self.transfers:
self.transfers[topic] = dict()
self.transfers[topic]['queue'] = queue
self.transfers[topic]['lastindex'] = 0
self.transfers[topic]['type'] = transfer_type
self.logger.info('start transfer | {0}'.format(topic))
# If there is already existing data under the topic
if topic in self.topic_list:
if transfer_type == 'indexed':
for key, value in self.topic_list[topic].indexes.iteritems():
queue.put([key, value])
elif transfer_type == 'linear':
for item in self.topic_list[topic].raw:
queue.put([self.transfers[topic]['lastindex'], item])
self.transfers[topic]['lastindex'] += 1
def untransfer(self,topic):
# If the topic data is already transfered to some queue
if topic in self.transfers:
# Remove it from the transfer list
del self.transfers[topic]
self.logger.info('stop transfer | {0}'.format(topic))
def intransfer(self,topic):
return topic in self.transfers
#.........这里部分代码省略.........
示例15: CacheStore
# 需要导入模块: from sortedcontainers import SortedDict [as 别名]
# 或者: from sortedcontainers.SortedDict import values [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)