code stringlengths 1 18.2k |
|---|
res WHERE res.resource_id = :resource_id UNION ALL SELECT res_u.*, depth+1 AS depth, (st.sorting::CHARACTER VARYING || '/' || LPAD(res_u.ordering::CHARACTER VARYING, 7, '0') ) AS sorting, (st.path::CHARACTER VARYING || '/' || res_u.resource_id::CHARACTER VARYING ) AS path FROM {tablename} res_u, subtree st WHERE res_u.... |
query = db_session.query(cls.model, "depth", "sorting", "path") query = query.from_statement(text_obj) query = query.params(resource_id=resource_id, depth=limit_depth) return query |
def delete_branch(cls, resource_id=None, db_session=None, *args, **kwargs): """ This deletes whole branch with children starting from resource_id :param resource_id: :param db_session: :return: """ tablename = cls.model.__table__.name # lets lock rows to prevent bad tree states resource = ResourceService.lock_resource_... |
UNION ALL SELECT res_u.resource_id FROM {tablename} res_u, subtree st WHERE res_u.parent_id = st.resource_id ) DELETE FROM resources where resource_id in (select * from subtree); """.format( tablename=tablename ) # noqa db_session = get_db_session(db_session) text_obj = sa.text(raw_q) db_session.execute(text_obj, param... |
def from_parent_deeper( cls, parent_id=None, limit_depth=1000000, db_session=None, *args, **kwargs ): """ This returns you subtree of ordered objects relative to the start parent_id (currently only implemented in postgresql) :param resource_id: :param limit_depth: :param db_session: :return: """ if parent_id: limiting_... |
LPAD(res.ordering::CHARACTER VARYING, 7, '0') AS sorting, res.resource_id::CHARACTER VARYING AS path FROM {tablename} AS res WHERE {limiting_clause} UNION ALL SELECT res_u.*, depth+1 AS depth, (st.sorting::CHARACTER VARYING || '/' || LPAD(res_u.ordering::CHARACTER VARYING, 7, '0') ) AS sorting, (st.path::CHARACTER VARY... |
""".format( tablename=tablename, limiting_clause=limiting_clause ) # noqa db_session = get_db_session(db_session) text_obj = sa.text(raw_q) query = db_session.query(cls.model, "depth", "sorting", "path") query = query.from_statement(text_obj) query = query.params(parent_id=parent_id, depth=limit_depth) return query |
def build_subtree_strut(self, result, *args, **kwargs): """ Returns a dictionary in form of {node:Resource, children:{node_id: Resource}} :param result: :return: """ items = list(result) root_elem = {"node": None, "children": OrderedDict()} if len(items) == 0: return root_elem for _, node in enumerate(items): new_elem ... |
parent_node["children"][new_elem["node"].resource_id] = new_elem return root_elem |
def path_upper( cls, object_id, limit_depth=1000000, db_session=None, *args, **kwargs ): """ This returns you path to root node starting from object_id currently only for postgresql :param object_id: :param limit_depth: :param db_session: :return: """ tablename = cls.model.__table__.name raw_q = """ WITH RECURSIVE subt... |
res_u, subtree st WHERE res_u.resource_id = st.parent_id ) SELECT * FROM subtree WHERE depth<=:depth; """.format( tablename=tablename ) db_session = get_db_session(db_session) q = ( db_session.query(cls.model) .from_statement(sa.text(raw_q)) .params(resource_id=object_id, depth=limit_depth) ) return q |
def move_to_position( cls, resource_id, to_position, new_parent_id=noop, db_session=None, *args, **kwargs ): """ Moves node to new location in the tree :param resource_id: resource to move :param to_position: new position :param new_parent_id: new parent id :param db_session: :return: """ db_session = get_db_session(db... |
if parent is same as old if new_parent_id == resource.parent_id: new_parent_id = noop if new_parent_id is not noop: cls.check_node_parent(resource_id, new_parent_id, db_session=db_session) else: same_branch = True if new_parent_id is noop: # it is not guaranteed that parent exists parent_id = resource.parent_id if reso... |
= list(sorted((resource.ordering, to_position))) move_down = resource.ordering > to_position query = db_session.query(cls.model) query = query.filter(cls.model.parent_id == parent_id) query = query.filter(cls.model.ordering.between(*order_range)) if move_down: query.update( {cls.model.ordering: cls.model.ordering + 1},... |
def shift_ordering_up(cls, parent_id, position, db_session=None, *args, **kwargs): """ Shifts ordering to "open a gap" for node insertion, begins the shift from given position :param parent_id: :param position: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model) q... |
def set_position(cls, resource_id, to_position, db_session=None, *args, **kwargs): """ Sets node position for new node in the tree :param resource_id: resource to move :param to_position: new position :param db_session: :return:def count_children(cls, resource_id, db_session=None): """ db_session = get_db_session(db_se... |
to_position return True |
def check_node_parent( cls, resource_id, new_parent_id, db_session=None, *args, **kwargs ): """ Checks if parent destination is valid for node :param resource_id: :param new_parent_id: :param db_session: :return: """ db_session = get_db_session(db_session) new_parent = ResourceService.lock_resource_for_update( resource... |
cls.path_upper(new_parent_id, db_session=db_session) path_ids = [r.resource_id for r in result] if resource_id in path_ids: raise ZigguratResourceTreePathException( "Trying to insert node into itself" ) |
def count_children(cls, resource_id, db_session=None, *args, **kwargs): """ Counts children of resource node :param resource_id: :param db_session: :return: """ query = db_session.query(cls.model.resource_id) query = query.filter(cls.model.parent_id == resource_id) return query.count() |
def check_node_position( cls, parent_id, position, on_same_branch, db_session=None, *args, **kwargs ): """ Checks if node position for given parent is valid, raises exception if this is not the case :param parent_id: :param position: :param on_same_branch: indicates that we are checking same branch :param db_session: :... |
item_count = cls.count_children(parent_id, db_session=db_session) max_value = item_count if on_same_branch else item_count + 1 if position > max_value: raise ZigguratResourceOutOfBoundaryException( "Maximum resource ordering is {}", value=max_value ) |
def egcd(b, n): ''' Given two integers (b, n), returns (gcd(b, n), a, m) such that a*b + n*m = gcd(b, n). Adapted from several sources: https://brilliant.org/wiki/extended-euclidean-algorithm/ https://rosettacode.org/wiki/Modular_inverse https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclid... |
0, 1) while n != 0: (q, b, n) = (b // n, n, b % n) (x0, x1) = (x1, x0 - q * x1) (y0, y1) = (y1, y0 - q * y1) return (b, x0, y0) |
def register(linter): """Add the needed transformations and supressions. """ linter.register_checker(MongoEngineChecker(linter)) add_transform('mongoengine') add_transform('mongomotor') suppress_qs_decorator_messages(linter) suppress_fields_attrs_messages(linter) |
def output_as_csv(file_name, nmi=None, output_file=None): """ Transpose all channels and output a csv that is easier to read and do charting on :param file_name: The NEM file to process :param nmi: Which NMI to output if more than one :param output_file: Specify different output location :returns: The file that was cre... |
NMI channels = list(m.transactions[nmi].keys()) num_records = len(m.readings[nmi][channels[0]]) last_date = m.readings[nmi][channels[0]][-1].t_end if output_file is None: output_file = '{}_{}_transposed.csv'.format( nmi, last_date.strftime('%Y%m%d')) with open(output_file, 'w', newline='') as csvfile: cwriter = csv.wri... |
channels: val = m.readings[nmi][ch][i].read_value row_list.append(val) row_list.append(quality_method) cwriter.writerow(row_list) return output_file |
def get(cls, group_id, db_session=None): """ Fetch row using primary key - will use existing object in session if already present :param group_id: :param db_session: :return: """ db_session = get_db_session(db_session) return db_session.query(cls.model).get(group_id) |
def by_group_name(cls, group_name, db_session=None): """ fetch group by name :param group_name: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model).filter(cls.model.group_name == group_name) return query.first() |
def get_user_paginator( cls, instance, page=1, item_count=None, items_per_page=50, user_ids=None, GET_params=None, ): """ returns paginator over users belonging to the group :param instance: :param page: :param item_count: :param items_per_page: :param user_ids: :param GET_params: :return: """ if not GET_params: GET_pa... |
def resources_with_possible_perms( cls, instance, perm_names=None, resource_ids=None, resource_types=None, db_session=None, ): """ returns list of permissions and resources for this group, resource_ids restricts the search to specific resources :param instance: :param perm_names: :param resource_ids: :param resource_ty... |
resource_ids: query = query.filter( cls.models_proxy.GroupResourcePermission.resource_id.in_(resource_ids) ) if resource_types: query = query.filter( cls.models_proxy.Resource.resource_type.in_(resource_types) ) if perm_names not in ([ANY_PERMISSION], ANY_PERMISSION) and perm_names: query = query.filter( cls.models_pro... |
) return perms |
def create_pool( database, minsize=1, maxsize=10, echo=False, loop=None, **kwargs ): """ 创建支持上下文管理的pool """ coro = _create_pool( database=database, minsize=minsize, maxsize=maxsize, echo=echo, loop=loop, **kwargs ) return _PoolContextManager(coro) |
def wait_closed(self): """ Wait for closing all pool's connections. """ if self._closed: return if not self._closing: raise RuntimeError( ".wait_closed() should be called " "after .close()" ) while self._free: conn = self._free.popleft() if not conn.closed: yield from conn.close() else: # pragma: no cover pass with (yi... |
def sync_close(self): """ 同步关闭 """ if self._closed: return while self._free: conn = self._free.popleft() if not conn.closed: # pragma: no cover conn.sync_close() for conn in self._used: if not conn.closed: # pragma: no cover conn.sync_close() self._terminated.add(conn) self._used.clear() self._closed = True |
def _fill_free_pool(self, override_min): """ iterate over free connections and remove timeouted ones """ while self.size < self.minsize: self._acquiring += 1 try: conn = yield from connect( database=self._database, echo=self._echo, loop=self._loop, **self._conn_kwargs ) self._free.append(conn) self._cond.notify() final... |
-= 1 |
def add_function(self, function): """ Adds the function to the list of registered functions. """ function = self.build_function(function) if function.name in self.functions: raise FunctionAlreadyRegistered(function.name) self.functions[function.name] = function |
def get_one(self, context, name): """ Returns a function if it is registered, the context is ignored. """ try: return self.functions[name] except KeyError: raise FunctionNotFound(name) |
def subfield_get(self, obj, type=None): """ Verbatim copy from: https://github.com/django/django/blob/1.9.13/django/db/models/fields/subclassing.py#L38 """ if obj is None: return self return obj.__dict__[self.field.name] |
def _preprocess_kwargs(self, initial_kwargs): """ Replace generic key related attribute with filters by object_id and content_type fields """ kwargs = initial_kwargs.copy() generic_key_related_kwargs = self._get_generic_key_related_kwargs(initial_kwargs) for key, value in generic_key_related_kwargs.items(): # delete ol... |
kwargs.update(new_kwargs) return kwargs |
def categorize( data, col_name: str = None, new_col_name: str = None, categories: dict = None, max_categories: float = 0.15 ): """ :param data: :param col_name: :param new_col_name: :param categories: :param max_categories: max proportion threshold of categories :return: new categories :rtype dict: """ _categories = {}... |
# create a list of cols with all object columns cols = [ k for k in data.keys() if data[k].dtype == 'object' and (data[k].unique() / data[k].count()) <= max_categories ] else: # create a list with col_name if new_col_name is not None: data[new_col_name] = data[col_name] col_name = new_col_name cols = [col_name] for c i... |
a number assert all(type(k) in (int, float) for k in categories.keys()) # replace values using given categories dict data[c].replace(categories, inplace=True) # change column to categorical type data[c] = data[c].astype('category') # update categories information _categories.update({c: categories}) else: # change colum... |
def dropna(data: pd.DataFrame, axis: int, **params): """ Remove columns with more NA values than threshold level :param data: :param axis: Axes are defined for arrays with more than one dimension. A 2-dimensional array has two corresponding axes: the first running vertically downwards across rows (axis 0), and the seco... |
dropna_rows(data=data, **params) else: dropna_columns(data=data, **params) |
def dropna_columns(data: pd.DataFrame, max_na_values: int=0.15): """ Remove columns with more NA values than threshold level :param data: :param max_na_values: proportion threshold of max na values :return: """ size = data.shape[0] df_na = (data.isnull().sum()/size) >= max_na_values data.drop(df_na[df_na].index, axis=1... |
def dropna_rows(data: pd.DataFrame, columns_name: str=None): """ Remove columns with more NA values than threshold level :param data: :param columns_name: :return: """ params = {} if columns_name is not None: params.update({'subset': columns_name.split(',')}) data.dropna(inplace=True, **params) |
def drop_columns_with_unique_values( data: pd.DataFrame, max_unique_values: int = 0.25 ): """ Remove columns when the proportion of the total of unique values is more than the max_unique_values threshold, just for columns with type as object or category :param data: :param max_unique_values: :return: """ size = data.sh... |
def list(self, request, *args, **kwargs): """ To get an actual value for object quotas limit and usage issue a **GET** request against */api/<objects>/*. To get all quotas visible to the user issue a **GET** request against */api/quotas/* """ return super(QuotaViewSet, self).list(request, *args, **kwargs) |
def retrieve(self, request, *args, **kwargs): """ To set quota limit issue a **PUT** request against */api/quotas/<quota uuid>** with limit values. Please note that if a quota is a cache of a backend quota (e.g. 'storage' size of an OpenStack tenant), it will be impossible to modify it through */api/quotas/<quota uuid>... |
Accept: application/json Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4 Host: example.com { "limit": 2000.0 } Example of changing quota threshold: .. code-block:: http PUT /api/quotas/6ad5f49d6d6c49648573b2b71f44a42b/ HTTP/1.1 Content-Type: application/json Accept: application/json Authorization: Token c... |
def history(self, request, uuid=None): """ Historical data endpoints could be available for any objects (currently implemented for quotas and events count). The data is available at *<object_endpoint>/history/*, for example: */api/quotas/<uuid>/history/*. There are two ways to define datetime points for historical data... |
*?end=<timestamp>*, *?points_count=<integer>* parameters. Result will contain <points_count> points from <start> to <end>. Response format: .. code-block:: javascript [ { "point": <timestamp>, "object": {<object_representation>} }, { "point": <timestamp> "object": {<object_representation>} }, ... ] NB! There will not b... |
request.query_params.get('points_count'), 'point_list': request.query_params.getlist('point'), } history_serializer = HistorySerializer(data={k: v for k, v in mapped.items() if v}) history_serializer.is_valid(raise_exception=True) quota = self.get_object() serializer = self.get_serializer(quota) serialized_versions = [... |
in quota.get_version_fields() }) serialized_versions.append(serialized) return response.Response(serialized_versions, status=status.HTTP_200_OK) |
def _get_url(self, obj): """ Gets object url """ format_kwargs = { 'app_label': obj._meta.app_label, } try: format_kwargs['model_name'] = getattr(obj.__class__, 'get_url_name')() except AttributeError: format_kwargs['model_name'] = obj._meta.object_name.lower() return self._default_view_name % format_kwargs |
def to_representation(self, obj): """ Serializes any object to his url representation """ kwargs = None for field in self.lookup_fields: if hasattr(obj, field): kwargs = {field: getattr(obj, field)} break if kwargs is None: raise AttributeError('Related object does not have any of lookup_fields') request = self._get_re... |
def to_internal_value(self, data): """ Restores model instance from its url """ if not data: return None request = self._get_request() user = request.user try: obj = core_utils.instance_from_url(data, user=user) model = obj.__class__ except ValueError: raise serializers.ValidationError(_('URL is invalid: %s.') % data) ... |
such relationship.') % six.text_type(obj)) return obj |
def validate(self, data): """ Check that the start is before the end. """ if 'start' in data and 'end' in data and data['start'] >= data['end']: raise serializers.ValidationError(_('End must occur after start.')) return data |
def send_task(app_label, task_name): """ A helper function to deal with waldur_core "high-level" tasks. Define high-level task with explicit name using a pattern: waldur_core.<app_label>.<task_name> .. code-block:: python @shared_task(name='waldur_core.openstack.provision_instance') def provision_instance_fn(instance_u... |
return delay |
def log_celery_task(request): """ Add description to celery log output """ task = request.task description = None if isinstance(task, Task): try: description = task.get_description(*request.args, **request.kwargs) except NotImplementedError: pass except Exception as e: # Logging should never break workflow. logger.exce... |
expires:[{0}]'.format(request.expires) if request.expires else '', ) |
def run(self, serialized_instance, *args, **kwargs): """ Deserialize input data and start backend operation execution """ try: instance = utils.deserialize_instance(serialized_instance) except ObjectDoesNotExist: message = ('Cannot restore instance from serialized object %s. Probably it was deleted.' % serialized_insta... |
def is_previous_task_processing(self, *args, **kwargs): """ Return True if exist task that is equal to current and is uncompleted """ app = self._get_app() inspect = app.control.inspect() active = inspect.active() or {} scheduled = inspect.scheduled() or {} reserved = inspect.reserved() or {} uncompleted = sum(list(act... |
def apply_async(self, args=None, kwargs=None, **options): """ Do not run background task if previous task is uncompleted """ if self.is_previous_task_processing(*args, **kwargs): message = 'Background task %s was not scheduled, because its predecessor is not completed yet.' % self.name logger.info(message) # It is expe... |
def _get_cache_key(self, args, kwargs): """ Returns key to be used in cache """ hash_input = json.dumps({'name': self.name, 'args': args, 'kwargs': kwargs}, sort_keys=True) # md5 is used for internal caching, not need to care about security return hashlib.md5(hash_input).hexdigest() |
def apply_async(self, args=None, kwargs=None, **options): """ Checks whether task must be skipped and decreases the counter in that case. """ key = self._get_cache_key(args, kwargs) counter, penalty = cache.get(key, (0, 0)) if not counter: return super(PenalizedBackgroundTask, self).apply_async(args=args, kwargs=kwargs... |
def on_failure(self, exc, task_id, args, kwargs, einfo): """ Increases penalty for the task and resets the counter. """ key = self._get_cache_key(args, kwargs) _, penalty = cache.get(key, (0, 0)) if penalty < self.MAX_PENALTY: penalty += 1 logger.debug('The task %s is penalized and will be executed on %d run.' % (self.... |
def on_success(self, retval, task_id, args, kwargs): """ Clears cache for the task. """ key = self._get_cache_key(args, kwargs) if cache.get(key) is not None: cache.delete(key) logger.debug('Penalty for the task %s has been removed.' % self.name) return super(PenalizedBackgroundTask, self).on_success(retval, task_id, a... |
def log_backend_action(action=None): """ Logging for backend method. Expects django model instance as first argument. """ def decorator(func): @functools.wraps(func) def wrapped(self, instance, *args, **kwargs): action_name = func.func_name.replace('_', ' ') if action is None else action logger.debug('About to %s `%s` ... |
wrapped return decorator |
def get_services(cls, request=None): """ Get a list of services endpoints. { "Oracle": "/api/oracle/", "OpenStack": "/api/openstack/", "GitLab": "/api/gitlab/", "DigitalOcean": "/api/digitalocean/" } """ return {service['name']: reverse(service['list_view'], request=request) for service in cls._registry.values()} |
def get_resources(cls, request=None): """ Get a list of resources endpoints. { "DigitalOcean.Droplet": "/api/digitalocean-droplets/", "Oracle.Database": "/api/oracle-databases/", "GitLab.Group": "/api/gitlab-groups/", "GitLab.Project": "/api/gitlab-projects/" } """ return {'.'.join([service['name'], resource['name']]):... |
def get_services_with_resources(cls, request=None): """ Get a list of services and resources endpoints. { ... "GitLab": { "url": "/api/gitlab/", "service_project_link_url": "/api/gitlab-service-project-link/", "resources": { "Project": "/api/gitlab-projects/", "Group": "/api/gitlab-groups/" } }, ... } """ from django.a... |
for resource in service['resources'].values()}, 'properties': {resource['name']: reverse(resource['list_view'], request=request) for resource in service.get('properties', {}).values()}, 'is_public_service': cls.is_public_service(service_model) } return data |
def get_service_models(cls): """ Get a list of service models. { ... 'gitlab': { "service": nodeconductor_gitlab.models.GitLabService, "service_project_link": nodeconductor_gitlab.models.GitLabServiceProjectLink, "resources": [ nodeconductor_gitlab.models.Group, nodeconductor_gitlab.models.Project ], }, ... } """ from ... |
'.' in r], } return data |
def get_resource_models(cls): """ Get a list of resource models. { 'DigitalOcean.Droplet': waldur_digitalocean.models.Droplet, 'JIRA.Project': waldur_jira.models.Project, 'OpenStack.Tenant': waldur_openstack.models.Tenant } """ from django.apps import apps return {'.'.join([service['name'], attrs['name']]): apps.get_mo... |
def get_service_resources(cls, model): """ Get resource models by service model """ key = cls.get_model_key(model) return cls.get_service_name_resources(key) |
def get_service_name_resources(cls, service_name): """ Get resource models by service name """ from django.apps import apps resources = cls._registry[service_name]['resources'].keys() return [apps.get_model(resource) for resource in resources] |
def get_name_for_model(cls, model): """ Get a name for given class or model: -- it's a service type for a service -- it's a <service_type>.<resource_model_name> for a resource """ key = cls.get_model_key(model) model_str = cls._get_model_str(model) service = cls._registry[key] if model_str in service['resources']: retu... |
def get_related_models(cls, model): """ Get a dictionary with related structure models for given class or model: >> SupportedServices.get_related_models(gitlab_models.Project) { 'service': nodeconductor_gitlab.models.GitLabService, 'service_project_link': nodeconductor_gitlab.models.GitLabServiceProjectLink, 'resources... |
models['resources']: if model_str == cls._get_model_str(resource_model): return models |
def _is_active_model(cls, model): """ Check is model app name is in list of INSTALLED_APPS """ # We need to use such tricky way to check because of inconsistent apps names: # some apps are included in format "<module_name>.<app_name>" like "waldur_core.openstack" # other apps are included in format "<app_name>" like "n... |
def process(self, event): """ Send events as push notification via Google Cloud Messaging. Expected settings as follows: # https://developers.google.com/mobile/add WALDUR_CORE['GOOGLE_API'] = { 'NOTIFICATION_TITLE': "Waldur notification", 'Android': { 'server_key': 'AIzaSyA2_7UaVIxXfKeFvxTjQNZbrzkXG9OTCkg', }, 'iOS': {... |
} payload = { 'to': self.token, 'notification': { 'body': event.get('message', 'New event'), 'title': conf.get('NOTIFICATION_TITLE', 'Waldur notification'), 'image': 'icon', }, 'data': { 'event': event }, } if self.type == self.Type.IOS: payload['content-available'] = '1' logger.debug('Submitting GCM push notification ... |
def get_context_data_from_headers(request, headers_schema): """ Extracts context data from request headers according to specified schema. >>> from lxml import etree as et >>> from datetime import date >>> from pyws.functions.args import TypeFactory >>> Fake = type('Fake', (object, ), {}) >>> request = Fake() >>> reques... |
'</headers>' ... '</s:Header>' ... '</s:Envelope>') >>> data = get_context_data_from_headers(request, TypeFactory( ... {0: 'Headers', 'string': str, 'number': int, 'date': date})) >>> data == {'string': 'hello', 'number': 100, 'date': date(2011, 8, 12)} True """ if not headers_schema: return None env = request.parsed_d... |
def lazy_constant(fn): """Decorator to make a function that takes no arguments use the LazyConstant class.""" class NewLazyConstant(LazyConstant): @functools.wraps(fn) def __call__(self): return self.get_value() return NewLazyConstant(fn) |
def lru_cache(maxsize=128, key_fn=None): """Decorator that adds an LRU cache of size maxsize to the decorated function. maxsize is the number of different keys cache can accomodate. key_fn is the function that builds key from args. The default key function creates a tuple out of args and kwargs. If you use the default,... |
- Your cache key is very large, so you don't want to keep the whole key in memory. - The function takes some arguments that don't affect the result. """ def decorator(fn): cache = LRUCache(maxsize) argspec = inspect2.getfullargspec(fn) arg_names = argspec.args[1:] + argspec.kwonlyargs # remove self kwargs_defaults = ge... |
@functools.wraps(fn) def wrapper(*args, **kwargs): key = cache_key(args, kwargs) try: return cache[key] except KeyError: value = fn(*args, **kwargs) cache[key] = value return value wrapper.clear = cache.clear return wrapper return decorator |
def cached_per_instance(): """Decorator that adds caching to an instance method. The cached value is stored so that it gets garbage collected together with the instance. The cached values are not stored when the object is pickled. """ def cache_fun(fun): argspec = inspect2.getfullargspec(fun) arg_names = argspec.args[1... |
def clear_cache(instance_key, ref): del cache[instance_key] @functools.wraps(fun) def new_fun(self, *args, **kwargs): instance_key = id(self) if instance_key not in cache: ref = weakref.ref(self, functools.partial(clear_cache, instance_key)) cache[instance_key] = (ref, {}) instance_cache = cache[instance_key][1] k = ca... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.