def test_capacity(self): lru = LRUCache(3) for d in ['A', 'B', 'C', 'D', 'E', 'F', 'G']: lru.get(d) self.assertEqual(lru.getCacheState(), ['G', 'F', 'E'])
def test_promoteFromHead(self): lru = LRUCache(3) for d in ['A', 'B', 'C', 'A']: lru.get(d) self.assertEqual(lru.getCacheState(), ['A', 'C', 'B'])
class queueManager: def __init__(self, inputmbrs): self.qu1 = kNNLRUCache(100) self.qu2 = LRUCache(100) self.mbrs = inputmbrs self.hit1 = 0 self.miss1 = 0 self.hit2 = 0 self.miss2 = 0 def getSpatial(self, x, y, r): for mbr in self.mbrs: if mbr.dist2p(x, y) < r: # print("checking" + str(mbr)) result1 = self.qu1.get(str(mbr)) if result1 == -1: self.miss1 += 1 self.qu1.set(str(mbr), 0) else: self.hit1 += 1 result2 = self.qu2.get(str(mbr)) if result2 == -1: self.miss2 += 1 self.qu2.set(str(mbr), 0) else: self.hit2 += 1 if result1 != result2: print("different!")
def __init__(self, inputmbrs): self.qu1 = kNNLRUCache(100) self.qu2 = LRUCache(100) self.mbrs = inputmbrs self.hit1 = 0 self.miss1 = 0 self.hit2 = 0 self.miss2 = 0
def setUp(self): self.cache1 = LRUCache(2) node1 = Node(1, 1) node2 = Node(2, 2) self.cache1.head.next = node1 node1.prev = self.cache1.head node1.next = node2 node2.prev = node1 node2.next = self.cache1.tail self.cache1.tail.prev = node2 self.cache1.valdict[1] = node1 self.cache1.valdict[2] = node2
def __init__(self, api_file_path='./api.txt'): self.api_file_path = api_file_path self.api_key = None self.payload = None self.load_api_key() self.package_cache = {} self.response_caches = LRUCache(150) return
def reset(cache: LRUCache): ''' Deletes a key from the cache; no-op if DNE Args: cache: LRUCache instance ''' # check if cache exists, if not no-op if is_cache_none(cache): return cache.reset() print('successfully resetted the cache')
def test_lru_cache_expired(self): self.LRU = LRUCache(3) self.LRU.put(1, 1, 2) self.assertEqual(self.LRU.get(1), 1) time.sleep(3) self.assertEqual(self.LRU.get(1), -1) self.LRU.put(1, 1, 3) self.LRU.put(2, 2, 10) self.LRU.put(3, 3, 3) time.sleep(4) self.assertEqual(self.LRU.get(2), 2) self.assertEqual(self.LRU.get(3), -1) self.assertEqual(self.LRU.get(1), -1)
def put(cache: LRUCache): ''' Inserts a new entry into the cache Args: cache: LRUCache instance ''' # check if cache exists, if not no-op if is_cache_none(cache): return # insert key, value into cache key, val = input('Enter key: ').strip(), input('Enter value: ') cache.put(key, val) print(f'successfully inserted [{key}: {val}] into the cache.')
def test_reset(self): """ Test if Reset function removes all items in the cache. """ cache = LRUCache(2) cache.put(1, 1) cache.reset() self.assertEqual( cache.cache, OrderedDict(), f"The result must be {OrderedDict()} instead of {cache.cache}") cache.put(1, 1) cache.put(2, 2) cache.reset() self.assertEqual( cache.cache, OrderedDict(), f"The result must be {OrderedDict()} instead of {cache.cache}")
def test_init(self): cache = LRUCache(4) self.assertEqual(cache.capacity, 4) self.assertEqual(cache.head, cache.tail) self.assertEqual(len(cache.key_to_prev), 0) self.assertTrue(isinstance(cache, LRUCache))
def create(cache) -> LRUCache: ''' Creates a new cache Args: cache: LRUCache instance Returns: A new LRUCache ''' # check if cache exists, wipe if confirmed if cache is not None: confirm = input( 'WARNING: cache is not empty, confirm reset (YES|NO): ') if confirm.upper() != 'YES': print('ERROR: user denied destroying existing cache.') return cache else: cache = None # request cache capacity try: max_size = int(input('Enter maximum capacity: ')) except ValueError: print('ERROR: entered capacity is not an integer.') return # try to make cache; otherwise retry try: cache = LRUCache(max_size) print(f'Cache successfully created with max. capacity: {max_size}') return cache except ValueError as e: print(e) return
def test_default_behaviour(self): self.LRU = LRUCache(2) self.assertEqual(self.LRU.get(1), -1) self.LRU.put(1, 1) self.assertEqual(self.LRU.get(1), 1) self.LRU.put(2, 4) self.LRU.put(3, 9) self.LRU.put(4, 16) self.assertEqual(self.LRU.get(4), 16) self.assertEqual(self.LRU.get(2), -1) self.assertEqual(len(self.LRU.get_all()), 2) self.LRU.put(5, 5) self.LRU.put(6, 6) self.LRU.put(7, 7) self.assertEqual(self.LRU.get(6), 6) self.assertEqual(self.LRU.get(5), -1)
def test_operation2(self): cache = LRUCache(1) cache.set(2, 1, 11) self.assertEqual(cache.get(2), 1) cache.set(3, 2, 11) self.assertEqual(cache.get(2), -1) self.assertEqual(cache.get(3), 2)
def main(): lru = LRUCache(4) lru.put(4) lru.put(2) assert lru.get_cache() == [4, 2], "put method failed" print("put method passed") assert lru.get(3) == -1, "put method failed" print("put method passed") lru.put(5) lru.put(4) assert lru.get(2) == 4, "put method failed" print("put method passed") assert lru.get_cache() == [2, 5, 4], "put method failed" print("get_cache passed") print(" LRU completed")
def test_operation1(self): cache = LRUCache(2) cache.set(2, 1, 11) cache.set(1, 1, 11) self.assertEqual(cache.get(2), 1) cache.set(4, 1, 11) self.assertEqual(cache.get(1), -1) self.assertEqual(cache.get(2), 1)
def supply_sample_cache(): # initialize sample cache with capacity = 5 cache = LRUCache(6) # insert sample data cache.put('one', 1) cache.put('two', 2) cache.put('three', 3) cache.put('four', 4) cache.put('five', 5) return cache
def __init__(self, ucac_path=None): if ucac_path is None: try: ucac_path = Path(os.environ["ucac4_path"]) print("found environ with ucac4 path", ucac_path) except KeyError: logging.debug( "No ucac path passed, and no environment var, using default" ) ucac_path = Path("./support/ucac4/UCAC4/") logging.info(f"Ucac path is {ucac_path}") # star id given by munipack self.ucac_path = ucac_path self.zones_cache = LRUCache(capacity=10) self.bucket_cache = LRUCache(capacity=100000) self.zone_bucket_cache = LRUCache(capacity=10000) self.index_cache = None self.ra_range = 360 * 3600 * 100 # read index file with open( str(Path(ucac_path, "u4i", "u4index.unf")), mode="rb" ) as file: # b is important -> binary self.index_cache = file.read() self.zone_starformat = "=iiHHBBBbbBBBHHhhbbIHHHBBBBBBHHHHHbbbbbBIBBIHI" self.zone_star_length = struct.calcsize(self.zone_starformat) self.unpack_zone_fileformat = struct.Struct(self.zone_starformat).unpack ( self.result_n0_running_star_number, self.result_nn_stars_in_bin, ) = UCAC4._get_n0_and_nn(self.index_cache)
def test_delete(self): """ Test if Delete function actually deletes the (key, value) pair from the cache. """ cache = LRUCache(2) cache.put(1, 1) cache.delete(2) self.assertEqual( cache.cache, OrderedDict([(1, 1)]), f"The result must be {OrderedDict([(1, 1)])} instead of {cache.cache}" ) cache.delete(1) self.assertEqual( cache.cache, OrderedDict(), f"The result must be {OrderedDict()} instead of {cache.cache}")
class FibonacciWithLRU: def __init__(self): self.lru = LRUCache(4) def fib(self, number): self.lru.put(0, 0) self.lru.put(1, 1) for i in range(2, number + 1): self.lru.put(i, self.lru.get(i-1) + self.lru.get(i-2)) return self.lru.get(number)
def wrapper(*args, **kwargs): # had to retrofit to pass test_lru_cache.py if func.__name__[:3] == 'get' or func.__name__ == 'fibonacci': global lru_get if lru_get is None: lru_get = LRUCache(size) if lru_get.maxSize != size: lru_get = LRUCache(size) if args[0] in lru_get.dictCache: return lru_get[args[0]] else: out = func(*args, **kwargs) lru_get[args[0]] = out return out pass elif func.__name__ == 'put': global lru_put if lru_put is None: lru_put = LRUCache(size) hashCode = serialize_PUT(args[0])[1] if hashCode in lru_put.dictCache: return lru_put[hashCode] else: out = func(*args, **kwargs) lru_put[hashCode] = out return out elif func.__name__ == 'delete': global lru_delete if lru_delete is None: lru_delete = LRUCache(size) if args[0] in lru_delete.dictCache: return lru_delete[args[0]] else: out = func(*args, **kwargs) lru_delete[args[0]] = out return out else: pass return func(*args, **kwargs)
def initialize(): if len(sys.argv) != 4: # Some error checking print("Error, correct usage is {} [my id] [my port] [k]".format( sys.argv[0])) sys.exit(-1) global local_id, my_port, k, my_hostname, my_address, hash_table, k_buckets local_id = int(sys.argv[1]) # Storing the local id my_port = str(int(sys.argv[2])) # Storing the portnum k_buckets = [[] for i in range(N)] k = int(sys.argv[3]) hash_table = LRUCache( k) # Initializing LRU cache datastructure in LRUCache.py my_hostname = socket.gethostname( ) # Calculating the hostname with the given parameters my_address = socket.gethostbyname(my_hostname)
def get(cache: LRUCache): ''' Retrieves an item from the cache Args: cache: LRUCache instance ''' # check if cache exists, if not no-op if is_cache_none(cache): return # retrieve value key = input('Enter key: ').strip() try: val = cache.get(key) print(f'The value is: {val}') except KeyError as e: print(e)
def produce(self, new_coordinates: Tuple[float, float]): ''' Yield a Proxy instance configured to have an LRUCache instance with the parameters given to the factory at initialization and origin instance that was provided to the factory at initialization. The returned Proxy instance will be initialized with the coordinated given to this method as arguments, provided a Proxy instance with the same coordinates is not already owned by the origin instance associated with this factory (and its products). ''' for coordinates, proxy in self.origin.proxies.items(): if (new_coordinates == coordinates): raise ValueError(new_coordinates) proxy = Proxy( new_coordinates, LRUCache(max_size=self.max_size_of_LRUCache, max_age=self.max_age_of_LRUCache), self.origin) proxy.LRUCache.set_miss_callback(self.origin.get) self.origin.proxies[new_coordinates] = proxy self.origin._deploy_proxy(proxy) return proxy
def test_put(self): """ Test if Put function add or update the value of a key correctly. """ cache = LRUCache(2) cache.put(1, 1) self.assertEqual( cache.cache, OrderedDict([(1, 1)]), f"The result must be {OrderedDict([(1, 1)])} instead of {cache.cache}" ) cache.put(2, 2) self.assertEqual( cache.cache, OrderedDict([(1, 1), (2, 2)]), f"The result must be {OrderedDict([(1, 1), (2, 2)])} instead of {cache.cache}" ) cache.put(3, 3) self.assertEqual( cache.cache, OrderedDict([(2, 2), (3, 3)]), f"The result must be {OrderedDict([(2, 2), (3, 3)])} instead of {cache.cache}" )
def test_create_LRUCache(): print("Test name:\ntest create LRUCache\n") test_cases = [ valid_pair for valid_pair in zip(valid_max_sizes, valid_max_ages) ] test_cases += [ invalid_pair for invalid_pair in zip(invalid_max_sizes, valid_max_ages) ] test_cases += [ invalid_pair for invalid_pair in zip(valid_max_sizes, invalid_max_ages) ] test_oracles = (LRUCache, ) * len(valid_max_sizes) + (ValueError, ) * ( len(invalid_max_sizes) * 2) test_results = {"pass": 0, "fail": 0} for i, test_case in enumerate(test_cases): oracle = test_oracles[i] valid_max_size, valid_max_age = test_case result = None print( "\nTest case {}:\nChecking whether {} and {} are valid arguments to initialize a LRUCache instance" .format(i + 1, *test_case), end=' ') try: result = LRUCache(valid_max_size, valid_max_age) except ValueError as e: result = e if (type(result) == oracle): print("passed", end=' ') test_results["pass"] += 1 else: print("failed", end=' ') test_results["fail"] += 1 print("(expected {}).".format(oracle)) assert test_results["pass"] + test_results["fail"] == len( test_cases) # ensure all tests have been completed print("\nTest results:\n{} completed, {} failed".format( len(test_cases), test_results["fail"])) # display results
def getRCache(self, nritems): """ Least-Recently-Used (LRU) cache. Written by http://evan.prodromou.name/Software/Python/LRUCache Instances of this class provide a least-recently-used (LRU) cache. They emulate a Python mapping type. You can use an LRU cache more or less like a Python dictionary, with the exception that objects you put into the cache may be discarded before you take them out. Some example usage:: cache = LRUCache(32) # new cache cache['foo'] = get_file_contents('foo') # or whatever if 'foo' in cache: # if it's still in cache... # use cached version contents = cache['foo'] else: # recalculate contents = get_file_contents('foo') # store in cache for next time cache['foo'] = contents print cache.size # Maximum size print len(cache) # 0 <= len(cache) <= cache.size cache.size = 10 # Auto-shrink on size assignment for i in range(50): # note: larger than cache size cache[i] = i if 0 not in cache: print 'Zero was discarded.' if 42 in cache: del cache[42] # Manual deletion for j in cache: # iterate (in LRU order) print j, cache[j] # iterator produces keys, not values """ return LRUCache(nritems)
def test_all(self): """ Test all functions! """ cache = LRUCache(2) cache.put(1, 1) cache.put(2, 2) cache.get(1) cache.put(3, 3) cache.get(2) cache.get(3) cache.delete(3) cache.reset() cache.put(4, 4) self.assertEqual( cache.cache, OrderedDict([(4, 4)]), f"The result must be {OrderedDict([(4, 4)])} instead of {cache.cache}" )
def test_get(self): """ Test if Get function returns the value of a key correctly. """ cache = LRUCache(2) self.assertEqual( cache.get(1), -1, "It must return -1 (i.e. key doesn't exist in the cache") cache.put(1, 1) self.assertEqual(cache.get(1), 1, "It must return 1 (i.e. key exists in the cache") cache.put(2, 2) cache.get(1) self.assertEqual( cache.cache, OrderedDict([(2, 2), (1, 1)]), f"The result must be {OrderedDict([(2, 2), (1, 1)])} instead of {cache.cache}" ) cache.get(2) self.assertEqual(cache.get(2), 2, "It must return 2 (i.e. key exists in the cache")
def setUp(self): self.test_cache = LRUCache(3) self.test_cache.put("1", "one") self.test_cache.put("2", "two") self.test_cache.put("3", "three")
class TestLRUCache(unittest.TestCase): def setUp(self): self.test_cache = LRUCache(3) self.test_cache.put("1", "one") self.test_cache.put("2", "two") self.test_cache.put("3", "three") def test_cache_capacity_1(self): self.test_cache.put("4", "four") self.test_cache.put("5", "five") self.test_cache.put("6", "six") val = self.test_cache.get("4") self.assertEqual(val, 'four') def test_cache_capacity_2(self): self.test_cache.put("4", "four") self.test_cache.put("5", "five") self.test_cache.put("6", "six") val = self.test_cache.get("3") self.assertEqual(val, None) def test_cache_touch(self): val = self.test_cache.get("1") self.test_cache.put("4", "four") self.test_cache.put("5", "five") val = self.test_cache.get("1") self.assertEqual(val, "one") def test_cache_purge(self): self.test_cache.purge("1") val = self.test_cache.get("1") self.assertEqual(val, None) def test_cache_clear(self): self.test_cache.clear() val = self.test_cache.get("1") self.assertEqual(val, None) def test_cache_statistics(self): self.test_cache.get("1") self.test_cache.get("2") self.test_cache.get("3") self.test_cache.get("4") self.test_cache.get("5") self.test_cache.get("6") res = {"hit": 3, "miss": 3, "percentage": 0.5} self.assertEqual(self.test_cache.stats(), res) def test_iterable(self): all_data = {(x, y) for x, y in self.test_cache} actual_data = {("1", "one"), ("2", "two"), ("3", "three")} self.assertEqual(all_data, actual_data) def test_contains(self): self.assertTrue("3" in self.test_cache) def test_not_contains(self): self.assertFalse("4" in self.test_cache) def test_len_n(self): self.assertEqual(len(self.test_cache), 3)
def create_mock_cache(max_size: int, max_age: int): return LRUCache(max_size, max_age)