text
stringlengths
81
112k
Unique identifier of user object def id(self): """ Unique identifier of user object""" return sa.Column(sa.Integer, primary_key=True, autoincrement=True)
Date of user's last login def last_login_date(self): """ Date of user's last login """ return sa.Column( sa.TIMESTAMP(timezone=False), default=lambda x: datetime.utcnow(), server_default=sa.func.now(), )
Date of user's security code update def security_code_date(self): """ Date of user's security code update """ return sa.Column( sa.TIMESTAMP(timezone=False), default=datetime(2000, 1, 1), server_default="2000-01-01 01:01", )
returns dynamic relationship for groups - allowing for filtering of data def groups_dynamic(self): """ returns dynamic relationship for groups - allowing for filtering of data """ return sa.orm.relationship( "Group", secondary="users_groups", lazy="dy...
Returns all resources directly owned by user, can be used to assign ownership of new resources:: user.resources.append(resource) def resources(self): """ Returns all resources directly owned by user, can be used to assign ownership of new resources:: user.resources.app...
Returns all resources directly owned by group, can be used to assign ownership of new resources:: user.resources.append(resource) def resources_dynamic(self): """ Returns all resources directly owned by group, can be used to assign ownership of new resources:: user.res...
validates if group can get assigned with permission def validate_permission(self, key, permission): """ validates if group can get assigned with permission""" if permission.perm_name not in self.__possible_permissions__: raise AssertionError( "perm_name is not one of {}".for...
Iterates through each of the feed URLs, parses their items, and sends any items to the channel that have not been previously been parsed. def parse_feeds(self, message_channel=True): """ Iterates through each of the feed URLs, parses their items, and sends any items to the chann...
[ { 'self': [1, 1, 3, 3, 1, 1], 'f': lambda x: x%2, 'assert': lambda ret: ret == [[1, 1], [3, 3], [1, 1]] } ] def ChunkBy(self: dict, f=None): """ [ { 'self': [1, 1, 3, 3, 1, 1], 'f': lambda x: x%2, 'assert': l...
[ { 'self': [1, 2, 3], 'f': lambda x: x%2, 'assert': lambda ret: ret[0] == [2] and ret[1] == [1, 3] } ] def GroupBy(self: dict, f=None): """ [ { 'self': [1, 2, 3], 'f': lambda x: x%2, 'assert': lambda ret: ret[...
[ { 'self': [1, 2, 3], 'n': 2, 'assert': lambda ret: list(ret) == [1, 2] } ] def Take(self: dict, n): """ [ { 'self': [1, 2, 3], 'n': 2, 'assert': lambda ret: list(ret) == [1, 2] } ] """ ...
[ { 'self': [1, 2, 3], 'f': lambda e: e%2, 'assert': lambda ret: list(ret) == [1, 3] } ] def TakeIf(self: dict, f): """ [ { 'self': [1, 2, 3], 'f': lambda e: e%2, 'assert': lambda ret: list(ret) == [1, 3] ...
[ { 'self': [1, 2, 3, 4, 5], 'f': lambda x: x < 4, 'assert': lambda ret: list(ret) == [1, 2, 3] } ] def TakeWhile(self: dict, f): """ [ { 'self': [1, 2, 3, 4, 5], 'f': lambda x: x < 4, 'assert': lambda ret: li...
[ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [1, 2] } ] def Drop(self: dict, n): """ [ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [1, 2] } ] ...
[ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [4, 5] } ] def Skip(self: dict, n): """ [ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ...
Output readings for specified number of rows to console def print_meter_record(file_path, rows=5): """ Output readings for specified number of rows to console """ m = nr.read_nem_file(file_path) print('Header:', m.header) print('Transactions:', m.transactions) for nmi in m.readings: for cha...
returns all users that have permissions for this resource def users(self): """ returns all users that have permissions for this resource""" return sa.orm.relationship( "User", secondary="users_resources_permissions", passive_deletes=True, passive_updates=...
This returns you subtree of ordered objects relative to the start resource_id (currently only implemented in postgresql) :param resource_id: :param limit_depth: :param db_session: :return: def from_resource_deeper( cls, resource_id=None, limit_depth=1000000, db_session=...
This deletes whole branch with children starting from resource_id :param resource_id: :param db_session: :return: def delete_branch(cls, resource_id=None, db_session=None, *args, **kwargs): """ This deletes whole branch with children starting from resource_id :param re...
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: def from_parent_deeper( cls, parent_id=None, limit_depth=1000000, db_session=None, ...
Returns a dictionary in form of {node:Resource, children:{node_id: Resource}} :param result: :return: def build_subtree_strut(self, result, *args, **kwargs): """ Returns a dictionary in form of {node:Resource, children:{node_id: Resource}} :param result: ...
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: def path_upper( cls, object_id, limit_depth=1000000, 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: def move_to_position( cls, resource_id, to_position, new_parent_id=noop, ...
Shifts ordering to "open a gap" for node insertion, begins the shift from given position :param parent_id: :param position: :param db_session: :return: def shift_ordering_up(cls, parent_id, position, db_session=None, *args, **kwargs): """ Shifts ordering to "ope...
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): def set_position(cls, resource_id, to_position, db_session=None, *args, **kwargs): ...
Checks if parent destination is valid for node :param resource_id: :param new_parent_id: :param db_session: :return: def check_node_parent( cls, resource_id, new_parent_id, db_session=None, *args, **kwargs ): """ Checks if parent destination is valid for nod...
Counts children of resource node :param resource_id: :param db_session: :return: def count_children(cls, resource_id, db_session=None, *args, **kwargs): """ Counts children of resource node :param resource_id: :param db_session: :return: """ ...
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: :return: def check_node_position( cls, parent_id, ...
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/Exte...
Add the needed transformations and supressions. 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_a...
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 created def output_as_csv(file_name, nmi=No...
Fetch row using primary key - will use existing object in session if already present :param group_id: :param db_session: :return: def get(cls, group_id, db_session=None): """ Fetch row using primary key - will use existing object in session if already present ...
fetch group by name :param group_name: :param db_session: :return: 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) ...
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: def get_user_paginator( cls, instance, page=1, item_count=Non...
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_types: :param db_session: :return: def resources_with_possible_perms( ...
创建支持上下文管理的pool 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=lo...
Wait for closing all pool's connections. 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 .c...
同步关闭 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: ...
iterate over free connections and remove timeouted ones 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( ...
Adds the function to the list of registered functions. 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(functi...
Returns a function if it is registered, the context is ignored. 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)
Verbatim copy from: https://github.com/django/django/blob/1.9.13/django/db/models/fields/subclassing.py#L38 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 ...
Replace generic key related attribute with filters by object_id and content_type fields 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....
:param data: :param col_name: :param new_col_name: :param categories: :param max_categories: max proportion threshold of categories :return: new categories :rtype dict: def categorize( data, col_name: str = None, new_col_name: str = None, categories: dict = None, max_categories: float =...
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 second running horizontally ...
Remove columns with more NA values than threshold level :param data: :param max_na_values: proportion threshold of max na values :return: 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...
Remove columns with more NA values than threshold level :param data: :param columns_name: :return: 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 = ...
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: def drop_columns_with_unique_values( data: pd.DataFrame, max_unique_values: int = 0.25...
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/* def list(self, request, *args, **kwargs): """ To get an actual value for object quotas limit and usag...
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>** endpoint. Example of ...
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. 1. Send...
Gets object url 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_kw...
Serializes any object to his url representation 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)} ...
Restores model instance from its url 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, u...
Check that the start is before the end. 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
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(in...
Add description to celery log output 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 NotImplementedErr...
Deserialize input data and start backend operation execution def run(self, serialized_instance, *args, **kwargs): """ Deserialize input data and start backend operation execution """ try: instance = utils.deserialize_instance(serialized_instance) except ObjectDoesNotExist: ...
Return True if exist task that is equal to current and is uncompleted 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 ...
Do not run background task if previous task is uncompleted 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, beca...
Returns key to be used in cache 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...
Checks whether task must be skipped and decreases the counter in that case. 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 = ca...
Increases penalty for the task and resets the counter. 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.MA...
Clears cache for the task. 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 remo...
Logging for backend method. Expects django model instance as first argument. 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, **k...
Get a list of services endpoints. { "Oracle": "/api/oracle/", "OpenStack": "/api/openstack/", "GitLab": "/api/gitlab/", "DigitalOcean": "/api/digitalocean/" } def get_services(cls, request=None): """ Get a list of services ...
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/" } def get_res...
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...
Get a list of service models. { ... 'gitlab': { "service": nodeconductor_gitlab.models.GitLabService, "service_project_link": nodeconductor_gitlab.models.GitLabServiceProjectLink, "resources": [ ...
Get a list of resource models. { 'DigitalOcean.Droplet': waldur_digitalocean.models.Droplet, 'JIRA.Project': waldur_jira.models.Project, 'OpenStack.Tenant': waldur_openstack.models.Tenant } def get_resource_models(cls): """ Get a list of r...
Get resource models by service model 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)
Get resource models by service name 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]
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 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 <se...
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.GitLabServiceProjec...
Check is model app name is in list of INSTALLED_APPS 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 "w...
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': { ...
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() >>> request.parsed_data = Fake() >>> request....
Decorator to make a function that takes no arguments use the LazyConstant class. 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.g...
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, there is no reason not to ...
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 cached_per_instance(): """Decorator that adds caching to an instance method. The cached value i...
Generates a cache key from the passed in arguments. def get_args_tuple(args, kwargs, arg_names, kwargs_defaults): """Generates a cache key from the passed in arguments.""" args_list = list(args) args_len = len(args) all_args_len = len(arg_names) try: while args_len < all_args_len: ...
Computes a kwargs_defaults dictionary for use by get_args_tuple given an argspec. def get_kwargs_defaults(argspec): """Computes a kwargs_defaults dictionary for use by get_args_tuple given an argspec.""" arg_names = tuple(argspec.args) defaults = argspec.defaults or () num_args = len(argspec.args) - le...
Memoizes return values of the decorated function. Similar to l0cache, but the cache persists for the duration of the process, unless clear_cache() is called on the function. def memoize(fun): """Memoizes return values of the decorated function. Similar to l0cache, but the cache persists for the durat...
Memoizes return values of the decorated function for a given time-to-live. Similar to l0cache, but the cache persists for the duration of the process, unless clear_cache() is called on the function or the time-to-live expires. By default, the time-to-live is set to 24 hours. def memoize_with_ttl(ttl_secs=...
Returns the value of the constant. def get_value(self): """Returns the value of the constant.""" if self.value is not_computed: self.value = self.value_provider() if self.value is not_computed: return None return self.value
Computes the value. Does not look at the cache. def compute(self): """Computes the value. Does not look at the cache.""" self.value = self.value_provider() if self.value is not_computed: return None else: return self.value
Return the value for given key if it exists. def get(self, key, default=miss): """Return the value for given key if it exists.""" if key not in self._dict: return default # invokes __getitem__, which updates the item return self[key]
Empty the cache and optionally invoke item_evicted callback. def clear(self, omit_item_evicted=False): """Empty the cache and optionally invoke item_evicted callback.""" if not omit_item_evicted: items = self._dict.items() for key, value in items: self._evict_ite...
Compatibility wrapper for the loop.create_future() call introduced in 3.5.2. def create_future(loop): # pragma: no cover """Compatibility wrapper for the loop.create_future() call introduced in 3.5.2.""" if hasattr(loop, 'create_future'): return loop.create_future() return asyncio.Futur...
Compatibility wrapper for the loop.create_task() call introduced in 3.4.2. def create_task(coro, loop): # pragma: no cover """Compatibility wrapper for the loop.create_task() call introduced in 3.4.2.""" if hasattr(loop, 'create_task'): return loop.create_task(coro) return asyncio.Task(...
为类添加代理属性 def proxy_property_directly(bind_attr, attrs): """ 为类添加代理属性 """ def cls_builder(cls): """ 添加到类 """ for attr_name in attrs: setattr(cls, attr_name, _make_proxy_property(bind_attr, attr_name)) return cls return cls_builder
Return query dictionary to search objects available to user. def get_permitted_objects_uuids(cls, user): """ Return query dictionary to search objects available to user. """ uuids = filter_queryset_for_user(cls.objects.all(), user).values_list('uuid', flat=True) key = core_utils...
Checks whether user has role in entity. `timestamp` can have following values: - False - check whether user has role in entity at the moment. - None - check whether user has permanent role in entity. - Datetime object - check whether user will have role in entity at specific ...
Identify the contents of `buf` def from_buffer(self, buf): """ Identify the contents of `buf` """ with self.lock: try: # if we're on python3, convert buf to bytes # otherwise this string is passed as wchar* # which is not what ...
Starts listening to events. Args: timeout (int): number of seconds before timeout. Used for testing purpose only. root_object (bambou.NURESTRootObject): NURESTRootObject object that is listening. Used for testing purpose only. def start(self, timeout=None, root_object=None)...
Stops listening for events. def stop(self): """ Stops listening for events. """ if not self._is_running: return pushcenter_logger.debug("[NURESTPushCenter] Stopping...") self._thread.stop() self._thread.join() self._is_running = False self._curren...
Wait until thread exit Used for testing purpose only def wait_until_exit(self): """ Wait until thread exit Used for testing purpose only """ if self._timeout is None: raise Exception("Thread will never exit. Use stop or specify timeout when starting it!") ...
Receive an event from connection def _did_receive_event(self, connection): """ Receive an event from connection """ if not self._is_running: return if connection.has_timeouted: return response = connection.response data = None if response.stat...
Listen a connection uuid def _listen(self, uuid=None, session=None): """ Listen a connection uuid """ if self.url is None: raise Exception("NURESTPushCenter needs to have a valid URL. please use setURL: before starting it.") events_url = "%s/events" % self.url if uuid: ...
Registers a new delegate callback The prototype should be function(data), where data will be the decoded json push Args: callback (function): method to trigger when push center receives events def add_delegate(self, callback): """ Registers a new delegate callback ...