Use LinkedHashMap to implement LRU cache

As pointed out by Jeffrey, you are using accessOrder. When you created the LinkedHashMap, the third parameter specify how the order is changed. “true for access-order, false for insertion-order” For more detailed implementation of LRU, you can look at this http://www.programcreek.com/2013/03/leetcode-lru-cache-java/

Use functools’ @lru_cache without specifying maxsize parameter

You have to at least call lru_cache without args: @lru_cache() def f(): #content of the function This way, lru_cache is initialized with default parameters. This is because decorators in python (with the @ notation) are special functions which are evaluated and called when the interpreter is importing the module. When you write @decorator_name you tell … Read more

How to limit the size of a dictionary?

Python 2.7 and 3.1 have OrderedDict and there are pure-Python implementations for earlier Pythons. from collections import OrderedDict class LimitedSizeDict(OrderedDict): def __init__(self, *args, **kwds): self.size_limit = kwds.pop(“size_limit”, None) OrderedDict.__init__(self, *args, **kwds) self._check_size_limit() def __setitem__(self, key, value): OrderedDict.__setitem__(self, key, value) self._check_size_limit() def _check_size_limit(self): if self.size_limit is not None: while len(self) > self.size_limit: self.popitem(last=False) You would also … Read more

Make @lru_cache ignore some of the function arguments

With cachetools you can write: from cachetools import cached from cachetools.keys import hashkey from random import randint @cached(cache={}, key=lambda db_handle, query: hashkey(query)) def find_object(db_handle, query): print(“processing {0}”.format(query)) return query queries = list(range(5)) queries.extend(range(5)) for q in queries: print(“result: {0}”.format(find_object(randint(0, 1000), q))) You will need to install cachetools (pip install cachetools). The syntax is: @cached( cache={}, … Read more

Easy, simple to use LRU cache in java

You can use a LinkedHashMap (Java 1.4+) : // Create cache final int MAX_ENTRIES = 100; Map cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) { // This method is called just after a new entry has been added public boolean removeEldestEntry(Map.Entry eldest) { return size() > MAX_ENTRIES; } }; // Add to cache Object key = … Read more

Python functools lru_cache with instance methods: release object

This is not the cleanest solution, but it’s entirely transparent to the programmer: import functools import weakref def memoized_method(*lru_args, **lru_kwargs): def decorator(func): @functools.wraps(func) def wrapped_func(self, *args, **kwargs): # We’re storing the wrapped method inside the instance. If we had # a strong reference to self the instance would never die. self_weak = weakref.ref(self) @functools.wraps(func) @functools.lru_cache(*lru_args, … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)