def enhanceImage(algorithm, image, enhanceSteps): kernel = np.array([1 << idx for idx in range(9)]).reshape(3, 3) imageFromAlgorithmIndices = np.vectorize(cache(lambda idx: algorithm[idx])) fillValue = 0 for _ in range(enhanceSteps): algorithmIndices = convolve2d(image, kernel, fillvalue=fillValue) image = imageFromAlgorithmIndices(algorithmIndices) fillValue = algorithm[(0, -1)[fillValue]] return image
def __init__(self, tree, updater, is_scene_update): """:tree: tree which should be updated :_updater: generator which should update given tree :is_exhausted: the status of the generator - read only :last_node: last node which going to be processed by the generator - read only""" self.tree: SvTree = tree self.is_scene_update: bool = is_scene_update self.is_exhausted = False self.last_node = None self._updater: Generator = updater self.__hash__ = cache(self.__hash__)
def decorator(user_function: F) -> F: """The decorator focus on given condition.""" cache_decorated_function = cast(F, cache(user_function)) @wraps(user_function) def decorated(*args: Any, **kwargs: Any) -> Any: """The decorated user function.""" if not condition(user_function, args, kwargs): # Execute directly. return user_function(*args, **kwargs) return cache_decorated_function(*args, **kwargs) return cast(F, decorated)
def test(): """Simple test program.""" import sys url = "http://www.python.org/" if sys.argv[1:]: url = sys.argv[1] c = cache() for i in range(3): api = c.open(url, 'GET', {}) while 1: message, ready = api.pollmeta() print(message) if ready: meta = api.getmeta() print(repr(meta)) break while 1: message, ready = api.polldata() print(message) if ready: data = api.getdata(512) print(repr(data)) if not data: break api.close()
def _singleton_fixture(f): return _fixture(cache(f))
import arbor import functools from functools import lru_cache as cache import unittest from pathlib import Path import subprocess import warnings import atexit _mpi_enabled = arbor.__config__["mpi"] _mpi4py_enabled = arbor.__config__["mpi4py"] # The API of `functools`'s caches went through a bunch of breaking changes from # 3.6 to 3.9. Patch them up in a local `cache` function. try: cache(lambda: None) except TypeError: # If `lru_cache` does not accept user functions as first arg, it expects # the max cache size as first arg, we pass None to produce a cache decorator # without max size. cache = cache(None) def _fix(param_name, fixture, func): """ Decorates `func` to inject the `fixture` callable result as `param_name`. """ @functools.wraps(func) def wrapper(*args, **kwargs): kwargs[param_name] = fixture() return func(*args, **kwargs)
# modify it under the terms of the MIT License; see the # LICENSE file for more details. import functools from flask import current_app, request from flask_multipass import InvalidCredentials, Multipass, NoSuchUser from werkzeug.local import LocalProxy from indico.core.config import config from indico.core.limiter import make_rate_limiter from indico.core.logger import Logger logger = Logger.get('auth') login_rate_limiter = LocalProxy( functools.cache( lambda: make_rate_limiter('login', config.FAILED_LOGIN_RATE_LIMIT))) class IndicoMultipass(Multipass): @property def default_local_auth_provider(self): """The default form-based auth provider.""" return next((p for p in self.auth_providers.values() if not p.is_external and p.settings.get('default')), None) @property def sync_provider(self): """The synchronization provider. This is the identity provider used to sync user data. """
def single_thread_with_cache(inputs): """ Compute single threaded with cache. """ f_memoized = cache(f) return [f_memoized(x) for x in inputs]
""" objects = values_from_signal(signal_response, return_plugins=True) if plugin_attr is not None: for plugin, cls in objects: setattr(cls, plugin_attr, plugin) mapping = {getattr(cls, name_attr): cls for _, cls in objects} # check for two different objects having the same name, e.g. because of # two plugins using a too generic name for their object conflicting = {cls for _, cls in objects} - set(mapping.values()) if conflicting: names = ', '.join(sorted(getattr(x, name_attr) for x in conflicting)) raise RuntimeError(f'Non-unique object names: {names}') return mapping _inspect_signature = functools.cache(inspect.signature) def make_interceptable(func, key=None, ctx=None): """Create a wrapper to make a function call interceptable. The returned wrapper behaves like the original function, but it triggers a signal which can modify its call arguments or even override the return value (in which case the original function would not get called at all, unless the signal handler decides to do so itself). This function can also be used as a decorator; in that case neither a key nor context can be provided (but it would not make sense anyway). :param func: The function to make interceptable :param key: An optional key in case using just the function name would be too generic
if j is None: j = len(y) if i == 0: return j if j == 0: return i return min( edit_dist(x, y, i - 1, j - 1) + (x[i - 1] != y[j - 1]), edit_dist(x, y, i, j - 1) + 1, edit_dist(x, y, i - 1, j) + 1, ) print(f"Recursive edit_dist({x},{y}) = {edit_dist(x, y)}") # Memoisation as if we had used the decorator (explicitly using # cache() works the same way). from functools import cache edit_dist = cache(edit_dist) print(f"Cached edit_dist({x},{y}) = {edit_dist(x, y)}") def edit_dist(x, y, i=None, j=None, tbl=None): if i is None: i = len(x) if j is None: j = len(y) if tbl is None: tbl = {} if i == 0: tbl[i, j] = j elif j == 0: tbl[i, j] = i else: tbl[i, j] = min(
def update_event(self, inp=-1): self.set_output_val(0, functools.cache(self.input(0)))
def cache_e(expression): return cache(e(expression))
def __init__(self, load_fn: Callable[[], Awaitable[Sequence[ItemType]]]): self.load_fn = functools.cache(load_fn)
def cached_property(f): cf = functools.cache(f) return property(cf)
from indico.modules.rb.models.rooms import Room from indico.modules.users.util import get_user_by_email try: import cx_Oracle except ImportError: cx_Oracle = None class SkipRoom(Exception): pass # memoize results in case we are on the slower auth API get_user_by_email = functools.cache(get_user_by_email) def OutputTypeHandler(cursor, name, defaultType, size, precision, scale): """ Unicode output handler for oracle connections Source: http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html """ if defaultType in (cx_Oracle.STRING, cx_Oracle.FIXED_CHAR): return cursor.var(str, size, cursor.arraysize) def _get_room_role_map(connection, logger): roles = defaultdict(set) cursor = connection.cursor() cursor.execute('SELECT BUILDING, FLOOR, ROOM_NUMBER, EMAIL FROM aispub.app_indico_space_managers')
def method(self, *args, **kwargs): instance_cache = cache_dict.get(self) if instance_cache is None: instance_cache = cache(partial(func, self)) cache_dict[self] = instance_cache return instance_cache(*args, **kwargs)