sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def update_configuration(self, new_configuration): """ Save how much consumables were used and update current configuration. Return True if configuration changed. """ if new_configuration == self.configuration: return False now = timezone.now() if now.mon...
Save how much consumables were used and update current configuration. Return True if configuration changed.
entailment
def consumed_in_month(self): """ How many resources were (or will be) consumed until end of the month """ month_end = core_utils.month_end(datetime.date(self.price_estimate.year, self.price_estimate.month, 1)) return self._get_consumed(month_end)
How many resources were (or will be) consumed until end of the month
entailment
def _get_consumed(self, time): """ How many consumables were (or will be) used by resource until given time. """ minutes_from_last_update = self._get_minutes_from_last_update(time) if minutes_from_last_update < 0: raise ConsumptionDetailCalculateError('Cannot calculate consumption if...
How many consumables were (or will be) used by resource until given time.
entailment
def _get_minutes_from_last_update(self, time): """ How much minutes passed from last update to given time """ time_from_last_update = time - self.last_update_time return int(time_from_last_update.total_seconds() / 60)
How much minutes passed from last update to given time
entailment
def get_for_resource(resource): """ Get list of all price list items that should be used for resource. If price list item is defined for service - return it, otherwise - return default price list item. """ resource_content_type = ContentType.objects.get_for_model(resourc...
Get list of all price list items that should be used for resource. If price list item is defined for service - return it, otherwise - return default price list item.
entailment
def get_extensions(cls): """ Get a list of available extensions """ assemblies = [] for waldur_extension in pkg_resources.iter_entry_points('waldur_extensions'): extension_module = waldur_extension.load() if inspect.isclass(extension_module) and issubclass(extension_modul...
Get a list of available extensions
entailment
def ellipsis(source, max_length): """Truncates a string to be at most max_length long.""" if max_length == 0 or len(source) <= max_length: return source return source[: max(0, max_length - 3)] + "..."
Truncates a string to be at most max_length long.
entailment
def safe_str(source, max_length=0): """Wrapper for str() that catches exceptions.""" try: return ellipsis(str(source), max_length) except Exception as e: return ellipsis("<n/a: str(...) raised %s>" % e, max_length)
Wrapper for str() that catches exceptions.
entailment
def safe_repr(source, max_length=0): """Wrapper for repr() that catches exceptions.""" try: return ellipsis(repr(source), max_length) except Exception as e: return ellipsis("<n/a: repr(...) raised %s>" % e, max_length)
Wrapper for repr() that catches exceptions.
entailment
def dict_to_object(source): """Returns an object with the key-value pairs in source as attributes.""" target = inspectable_class.InspectableClass() for k, v in source.items(): setattr(target, k, v) return target
Returns an object with the key-value pairs in source as attributes.
entailment
def copy_public_attrs(source_obj, dest_obj): """Shallow copies all public attributes from source_obj to dest_obj. Overwrites them if they already exist. """ for name, value in inspect.getmembers(source_obj): if not any(name.startswith(x) for x in ["_", "func", "im"]): setattr(dest_...
Shallow copies all public attributes from source_obj to dest_obj. Overwrites them if they already exist.
entailment
def object_from_string(name): """Creates a Python class or function from its fully qualified name. :param name: A fully qualified name of a class or a function. In Python 3 this is only allowed to be of text type (unicode). In Python 2, both bytes and unicode are allowed. :return: A functio...
Creates a Python class or function from its fully qualified name. :param name: A fully qualified name of a class or a function. In Python 3 this is only allowed to be of text type (unicode). In Python 2, both bytes and unicode are allowed. :return: A function or class object. This method i...
entailment
def catchable_exceptions(exceptions): """Returns True if exceptions can be caught in the except clause. The exception can be caught if it is an Exception type or a tuple of exception types. """ if isinstance(exceptions, type) and issubclass(exceptions, BaseException): return True if (...
Returns True if exceptions can be caught in the except clause. The exception can be caught if it is an Exception type or a tuple of exception types.
entailment
def override(self, value): """Temporarily overrides the old value with the new one.""" if self._value is not value: return _ScopedValueOverrideContext(self, value) else: return empty_context
Temporarily overrides the old value with the new one.
entailment
def validate_object_action(self, action_name, obj=None): """ Execute validation for actions that are related to particular object """ action_method = getattr(self, action_name) if not getattr(action_method, 'detail', False) and action_name not in ('update', 'partial_update', 'destroy'): ...
Execute validation for actions that are related to particular object
entailment
def row_dict(self, row): """returns dictionary version of row using keys from self.field_map""" d = {} for field_name,index in self.field_map.items(): d[field_name] = self.field_value(row, field_name) return d
returns dictionary version of row using keys from self.field_map
entailment
def _dialect(self, filepath): """returns detected dialect of filepath and sets self.has_header if not passed in __init__ kwargs Arguments: filepath (str): filepath of target csv file """ with open(filepath, self.read_mode) as csvfile: sample = csvfile.read...
returns detected dialect of filepath and sets self.has_header if not passed in __init__ kwargs Arguments: filepath (str): filepath of target csv file
entailment
def _get_content_type_queryset(models_list): """ Get list of services content types """ content_type_ids = {c.id for c in ContentType.objects.get_for_models(*models_list).values()} return ContentType.objects.filter(id__in=content_type_ids)
Get list of services content types
entailment
def init_registered(self, request): """ Create default price list items for each registered resource. """ created_items = models.DefaultPriceListItem.init_from_registered_resources() if created_items: message = ungettext( _('Price item was created: %s.') % created_it...
Create default price list items for each registered resource.
entailment
def reinit_configurations(self, request): """ Re-initialize configuration for resource if it has been changed. This method should be called if resource consumption strategy was changed. """ now = timezone.now() # Step 1. Collect all resources with changed configuration. ...
Re-initialize configuration for resource if it has been changed. This method should be called if resource consumption strategy was changed.
entailment
def encrypt(self, message): """ Encrypt the given message """ if not isinstance(message, (bytes, str)): raise TypeError return hashlib.sha1(message.encode('utf-8')).hexdigest()
Encrypt the given message
entailment
def save(self, *args, **kwargs): """ Updates next_trigger_at field if: - instance become active - instance.schedule changed - instance is new """ try: prev_instance = self.__class__.objects.get(pk=self.pk) except self.DoesNotExist: ...
Updates next_trigger_at field if: - instance become active - instance.schedule changed - instance is new
entailment
def get_version_fields(self): """ Get field that are tracked in object history versions. """ options = reversion._get_options(self) return options.fields or [f.name for f in self._meta.fields if f not in options.exclude]
Get field that are tracked in object history versions.
entailment
def _is_version_duplicate(self): """ Define should new version be created for object or no. Reasons to provide custom check instead of default `ignore_revision_duplicates`: - no need to compare all revisions - it is OK if right object version exists in any revision; - need...
Define should new version be created for object or no. Reasons to provide custom check instead of default `ignore_revision_duplicates`: - no need to compare all revisions - it is OK if right object version exists in any revision; - need to compare object attributes (not serialized...
entailment
def get_ancestors(self): """ Get all unique instance ancestors """ ancestors = list(self.get_parents()) ancestor_unique_attributes = set([(a.__class__, a.id) for a in ancestors]) ancestors_with_parents = [a for a in ancestors if isinstance(a, DescendantMixin)] for ancestor in anc...
Get all unique instance ancestors
entailment
def has_succeed(self): """ Check if the connection has succeed Returns: Returns True if connection has succeed. False otherwise. """ status_code = self._response.status_code if status_code in [HTTP_CODE_ZERO, HTTP_CODE_SUCCESS, HTTP_CODE_CRE...
Check if the connection has succeed Returns: Returns True if connection has succeed. False otherwise.
entailment
def handle_response_for_connection(self, should_post=False): """ Check if the response succeed or not. In case of error, this method also print messages and set an array of errors in the response object. Returns: Returns True if the response has succeed, Fal...
Check if the response succeed or not. In case of error, this method also print messages and set an array of errors in the response object. Returns: Returns True if the response has succeed, False otherwise
entailment
def _did_receive_response(self, response): """ Called when a response is received """ try: data = response.json() except: data = None self._response = NURESTResponse(status_code=response.status_code, headers=response.headers, data=data, reason=response.reason) ...
Called when a response is received
entailment
def _did_timeout(self): """ Called when a resquest has timeout """ bambou_logger.debug('Bambou %s on %s has timeout (timeout=%ss)..' % (self._request.method, self._request.url, self.timeout)) self._has_timeouted = True if self.async: self._callback(self) else: ...
Called when a resquest has timeout
entailment
def _make_request(self, session=None): """ Make a synchronous request """ if session is None: session = NURESTSession.get_current_session() self._has_timeouted = False # Add specific headers controller = session.login_controller enterprise = controller.ent...
Make a synchronous request
entailment
def __make_request(self, requests_session, method, url, params, data, headers, certificate): """ Encapsulate requests call """ verify = False timeout = self.timeout try: # TODO : Remove this ugly try/except after fixing Java issue: http://mvjira.mv.usa.alcatel.com/browse/VSD-54...
Encapsulate requests call
entailment
def start(self): """ Make an HTTP request with a specific method """ # TODO : Use Timeout here and _ignore_request_idle from .nurest_session import NURESTSession session = NURESTSession.get_current_session() if self.async: thread = threading.Thread(target=self._make...
Make an HTTP request with a specific method
entailment
def reset(self): """ Reset the connection """ self._request = None self._response = None self._transaction_id = uuid.uuid4().hex
Reset the connection
entailment
def create(self, price_estimate): """ Take configuration from previous month, it it exists. Set last_update_time equals to the beginning of the month. """ kwargs = {} try: previous_price_estimate = price_estimate.get_previous() except ObjectDoesNotExist: ...
Take configuration from previous month, it it exists. Set last_update_time equals to the beginning of the month.
entailment
def get_fields(self): """ When static declaration is used, event type choices are fetched too early - even before all apps are initialized. As a result, some event types are missing. When dynamic declaration is used, all valid event types are available as choices. """ fie...
When static declaration is used, event type choices are fetched too early - even before all apps are initialized. As a result, some event types are missing. When dynamic declaration is used, all valid event types are available as choices.
entailment
def build_nested_field(self, field_name, relation_info, nested_depth): """ Use PriceEstimateSerializer to serialize estimate children """ if field_name != 'children': return super(PriceEstimateSerializer, self).build_nested_field(field_name, relation_info, nested_depth) field_class =...
Use PriceEstimateSerializer to serialize estimate children
entailment
def prepare_for_reraise(error, exc_info=None): """Prepares the exception for re-raising with reraise method. This method attaches type and traceback info to the error object so that reraise can properly reraise it using this info. """ if not hasattr(error, "_type_"): if exc_info is None: ...
Prepares the exception for re-raising with reraise method. This method attaches type and traceback info to the error object so that reraise can properly reraise it using this info.
entailment
def reraise(error): """Re-raises the error that was processed by prepare_for_reraise earlier.""" if hasattr(error, "_type_"): six.reraise(type(error), error, error._traceback) raise error
Re-raises the error that was processed by prepare_for_reraise earlier.
entailment
def register(*args, **kwargs): """ Creates a registrator that, being called with a function as the only argument, wraps a function with ``pyws.functions.NativeFunctionAdapter`` and registers it to the server. Arguments are exactly the same as for ``pyws.functions.NativeFunctionAdapter`` except that ...
Creates a registrator that, being called with a function as the only argument, wraps a function with ``pyws.functions.NativeFunctionAdapter`` and registers it to the server. Arguments are exactly the same as for ``pyws.functions.NativeFunctionAdapter`` except that you can pass an additional keyword argu...
entailment
def rest_name(cls): """ Represents a singular REST name """ if cls.__name__ == "NURESTRootObject" or cls.__name__ == "NURESTObject": return "Not Implemented" if cls.__rest_name__ is None: raise NotImplementedError('%s has no defined name. Implement rest_name prop...
Represents a singular REST name
entailment
def resource_name(cls): """ Represents the resource name """ if cls.__name__ == "NURESTRootObject" or cls.__name__ == "NURESTObject": return "Not Implemented" if cls.__resource_name__ is None: raise NotImplementedError('%s has no defined resource name. Implement ...
Represents the resource name
entailment
def _compute_args(self, data=dict(), **kwargs): """ Compute the arguments Try to import attributes from data. Otherwise compute kwargs arguments. Args: data: a dict() kwargs: a list of arguments """ for name, remote_attribute...
Compute the arguments Try to import attributes from data. Otherwise compute kwargs arguments. Args: data: a dict() kwargs: a list of arguments
entailment
def children_rest_names(self): """ Gets the list of all possible children ReST names. Returns: list: list containing all possible rest names as string Example: >>> entity = NUEntity() >>> entity.children_rest_names ["foo",...
Gets the list of all possible children ReST names. Returns: list: list containing all possible rest names as string Example: >>> entity = NUEntity() >>> entity.children_rest_names ["foo", "bar"]
entailment
def get_resource_url(self): """ Get resource complete url """ name = self.__class__.resource_name url = self.__class__.rest_base_url() if self.id is not None: return "%s/%s/%s" % (url, name, self.id) return "%s/%s" % (url, name)
Get resource complete url
entailment
def validate(self): """ Validate the current object attributes. Check all attributes and store errors Returns: Returns True if all attibutes of the object respect contraints. Returns False otherwise and store error in errors dict. ...
Validate the current object attributes. Check all attributes and store errors Returns: Returns True if all attibutes of the object respect contraints. Returns False otherwise and store error in errors dict.
entailment
def expose_attribute(self, local_name, attribute_type, remote_name=None, display_name=None, is_required=False, is_readonly=False, max_length=None, min_length=None, is_identifier=False, choices=None, is_unique=False, is_email=False, is_login=False, is_editable=True, is_password=False, can_order=False, can_search=False, ...
Expose local_name as remote_name An exposed attribute `local_name` will be sent within the HTTP request as a `remote_name`
entailment
def is_owned_by_current_user(self): """ Check if the current user owns the object """ from bambou.nurest_root_object import NURESTRootObject root_object = NURESTRootObject.get_default_root_object() return self._owner == root_object.id
Check if the current user owns the object
entailment
def parent_for_matching_rest_name(self, rest_names): """ Return parent that matches a rest name """ parent = self while parent: if parent.rest_name in rest_names: return parent parent = parent.parent_object return None
Return parent that matches a rest name
entailment
def genealogic_types(self): """ Get genealogic types Returns: Returns a list of all parent types """ types = [] parent = self while parent: types.append(parent.rest_name) parent = parent.parent_object return types
Get genealogic types Returns: Returns a list of all parent types
entailment
def genealogic_ids(self): """ Get all genealogic ids Returns: A list of all parent ids """ ids = [] parent = self while parent: ids.append(parent.id) parent = parent.parent_object return ids
Get all genealogic ids Returns: A list of all parent ids
entailment
def get_formated_creation_date(self, format='%b %Y %d %H:%I:%S'): """ Return creation date with a given format. Default is '%b %Y %d %H:%I:%S' """ if not self._creation_date: return None date = datetime.datetime.utcfromtimestamp(self._creation_date) return date.strftime(for...
Return creation date with a given format. Default is '%b %Y %d %H:%I:%S'
entailment
def add_child(self, child): """ Add a child """ rest_name = child.rest_name children = self.fetcher_for_rest_name(rest_name) if children is None: raise InternalConsitencyError('Could not find fetcher with name %s while adding %s in parent %s' % (rest_name, child, self)) ...
Add a child
entailment
def remove_child(self, child): """ Remove a child """ rest_name = child.rest_name children = self.fetcher_for_rest_name(rest_name) target_child = None for local_child in children: if local_child.id == child.id: target_child = local_child ...
Remove a child
entailment
def update_child(self, child): """ Update child """ rest_name = child.rest_name children = self.fetcher_for_rest_name(rest_name) index = None for local_child in children: if local_child.id == child.id: index = children.index(local_child) ...
Update child
entailment
def to_dict(self): """ Converts the current object into a Dictionary using all exposed ReST attributes. Returns: dict: the dictionary containing all the exposed ReST attributes and their values. Example:: >>> print entity.to_dict() {"name...
Converts the current object into a Dictionary using all exposed ReST attributes. Returns: dict: the dictionary containing all the exposed ReST attributes and their values. Example:: >>> print entity.to_dict() {"name": "my entity", "description": ...
entailment
def from_dict(self, dictionary): """ Sets all the exposed ReST attribues from the given dictionary Args: dictionary (dict): dictionnary containing the raw object attributes and their values. Example: >>> info = {"name": "my group", "private": False} ...
Sets all the exposed ReST attribues from the given dictionary Args: dictionary (dict): dictionnary containing the raw object attributes and their values. Example: >>> info = {"name": "my group", "private": False} >>> group = NUGroup() ...
entailment
def delete(self, response_choice=1, async=False, callback=None): """ Delete object and call given callback in case of call. Args: response_choice (int): Automatically send a response choice when confirmation is needed async (bool): Boolean to make an asynchronous cal...
Delete object and call given callback in case of call. Args: response_choice (int): Automatically send a response choice when confirmation is needed async (bool): Boolean to make an asynchronous call. Default is False callback (function): Callback method that...
entailment
def save(self, response_choice=None, async=False, callback=None): """ Update object and call given callback in case of async call Args: async (bool): Boolean to make an asynchronous call. Default is False callback (function): Callback method that will be triggered in...
Update object and call given callback in case of async call Args: async (bool): Boolean to make an asynchronous call. Default is False callback (function): Callback method that will be triggered in case of asynchronous call Example: >>> entity.na...
entailment
def send_request(self, request, async=False, local_callback=None, remote_callback=None, user_info=None): """ Sends a request, calls the local callback, then the remote callback in case of async call Args: request: The request to send local_callback: local method that...
Sends a request, calls the local callback, then the remote callback in case of async call Args: request: The request to send local_callback: local method that will be triggered in case of async call remote_callback: remote moethd that will be triggered in cas...
entailment
def _manage_child_object(self, nurest_object, method=HTTP_METHOD_GET, async=False, callback=None, handler=None, response_choice=None, commit=False): """ Low level child management. Send given HTTP method with given nurest_object to given ressource of current object Args: nurest_obje...
Low level child management. Send given HTTP method with given nurest_object to given ressource of current object Args: nurest_object: the NURESTObject object to manage method: the HTTP method to use (GET, POST, PUT, DELETE) callback: the callback to call at t...
entailment
def _did_receive_response(self, connection): """ Receive a response from the connection """ if connection.has_timeouted: bambou_logger.info("NURESTConnection has timeout.") return has_callbacks = connection.has_callbacks() should_post = not has_callbacks ...
Receive a response from the connection
entailment
def _did_retrieve(self, connection): """ Callback called after fetching the object """ response = connection.response try: self.from_dict(response.data[0]) except: pass return self._did_perform_standard_operation(connection)
Callback called after fetching the object
entailment
def _did_perform_standard_operation(self, connection): """ Performs standard opertions """ if connection.async: callback = connection.callbacks['remote'] if connection.user_info and 'nurest_object' in connection.user_info: callback(connection.user_info['nurest_o...
Performs standard opertions
entailment
def create_child(self, nurest_object, response_choice=None, async=False, callback=None, commit=True): """ Add given nurest_object to the current object For example, to add a child into a parent, you can call parent.create_child(nurest_object=child) Args: nur...
Add given nurest_object to the current object For example, to add a child into a parent, you can call parent.create_child(nurest_object=child) Args: nurest_object (bambou.NURESTObject): the NURESTObject object to add response_choice (int): Automatica...
entailment
def instantiate_child(self, nurest_object, from_template, response_choice=None, async=False, callback=None, commit=True): """ Instantiate an nurest_object from a template object Args: nurest_object: the NURESTObject object to add from_template: the NURESTObject templ...
Instantiate an nurest_object from a template object Args: nurest_object: the NURESTObject object to add from_template: the NURESTObject template object callback: callback containing the object and the connection Returns: Returns t...
entailment
def _did_create_child(self, connection): """ Callback called after adding a new child nurest_object """ response = connection.response try: connection.user_info['nurest_object'].from_dict(response.data[0]) except Exception: pass return self._did_perform_...
Callback called after adding a new child nurest_object
entailment
def assign(self, objects, nurest_object_type, async=False, callback=None, commit=True): """ Reference a list of objects into the current resource Args: objects (list): list of NURESTObject to link nurest_object_type (type): Type of the object to link ...
Reference a list of objects into the current resource Args: objects (list): list of NURESTObject to link nurest_object_type (type): Type of the object to link callback (function): Callback method that should be fired at the end Returns: ...
entailment
def rest_equals(self, rest_object): """ Compare objects REST attributes """ if not self.equals(rest_object): return False return self.to_dict() == rest_object.to_dict()
Compare objects REST attributes
entailment
def equals(self, rest_object): """ Compare with another object """ if self._is_dirty: return False if rest_object is None: return False if not isinstance(rest_object, NURESTObject): raise TypeError('The object is not a NURESTObject %s' % rest_object...
Compare with another object
entailment
def get_ip_address(request): """ Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR """ if 'HTTP_X_FORWARDED_FOR' in request.META: return request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip() else: return request.META['REMOTE_ADDR']
Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR
entailment
def get_estimates_without_scope_in_month(self, customer): """ It is expected that valid row for each month contains at least one price estimate for customer, service setting, service, service project link, project and resource. Otherwise all price estimates in the row should be d...
It is expected that valid row for each month contains at least one price estimate for customer, service setting, service, service project link, project and resource. Otherwise all price estimates in the row should be deleted.
entailment
def is_identifier(self, is_identifier): """ Setter for is_identifier """ if is_identifier: self.is_editable = False self._is_identifier = is_identifier
Setter for is_identifier
entailment
def is_password(self, is_password): """ Setter for is_identifier """ if is_password: self.is_forgetable = True self._is_password = is_password
Setter for is_identifier
entailment
def choices(self, choices): """ Setter for is_identifier """ if choices is not None and len(choices) > 0: self.has_choices = True self._choices = choices
Setter for is_identifier
entailment
def get_default_value(self): """ Get a default value of the attribute_type """ if self.choices: return self.choices[0] value = self.attribute_type() if self.attribute_type is time: value = int(value) elif self.attribute_type is str: value =...
Get a default value of the attribute_type
entailment
def get_min_value(self): """ Get the minimum value """ value = self.get_default_value() if self.attribute_type is str: min_value = value[:self.min_length - 1] elif self.attribute_type is int: min_value = self.min_length - 1 else: raise Type...
Get the minimum value
entailment
def get_max_value(self): """ Get the maximum value """ value = self.get_default_value() if self.attribute_type is str: max_value = value.ljust(self.max_length + 1, 'a') elif self.attribute_type is int: max_value = self.max_length + 1 else: ...
Get the maximum value
entailment
def get_api_root_view(self, api_urls=None): """ Return a basic root view. """ api_root_dict = OrderedDict() list_name = self.routes[0].name for prefix, viewset, basename in self.registry: api_root_dict[prefix] = list_name.format(basename=basename) cla...
Return a basic root view.
entailment
def get_default_base_name(self, viewset): """ Attempt to automatically determine base name using `get_url_name`. """ queryset = getattr(viewset, 'queryset', None) if queryset is not None: get_url_name = getattr(queryset.model, 'get_url_name', None) if get...
Attempt to automatically determine base name using `get_url_name`.
entailment
def change_customer_nc_users_quota(sender, structure, user, role, signal, **kwargs): """ Modify nc_user_count quota usage on structure role grant or revoke """ assert signal in (signals.structure_role_granted, signals.structure_role_revoked), \ 'Handler "change_customer_nc_users_quota" has to be used on...
Modify nc_user_count quota usage on structure role grant or revoke
entailment
def delete_service_settings_on_service_delete(sender, instance, **kwargs): """ Delete not shared service settings without services """ service = instance try: service_settings = service.settings except ServiceSettings.DoesNotExist: # If this handler works together with delete_service_set...
Delete not shared service settings without services
entailment
def delete_service_settings_on_scope_delete(sender, instance, **kwargs): """ If VM that contains service settings were deleted - all settings resources could be safely deleted from NC. """ for service_settings in ServiceSettings.objects.filter(scope=instance): service_settings.unlink_descend...
If VM that contains service settings were deleted - all settings resources could be safely deleted from NC.
entailment
def url(self, url): """ Set API URL endpoint Args: url: the url of the API endpoint """ if url and url.endswith('/'): url = url[:-1] self._url = url
Set API URL endpoint Args: url: the url of the API endpoint
entailment
def get_authentication_header(self, user=None, api_key=None, password=None, certificate=None): """ Return authenication string to place in Authorization Header If API Token is set, it'll be used. Otherwise, the clear text password will be sent. Users of NURESTLoginController are respons...
Return authenication string to place in Authorization Header If API Token is set, it'll be used. Otherwise, the clear text password will be sent. Users of NURESTLoginController are responsible to clean the password property. Returns: Returns the XREST Au...
entailment
def reset(self): """ Reset controller It removes all information about previous session """ self._is_impersonating = False self._impersonation = None self.user = None self.password = None self.api_key = None self.enterprise = None se...
Reset controller It removes all information about previous session
entailment
def impersonate(self, user, enterprise): """ Impersonate a user in a enterprise Args: user: the name of the user to impersonate enterprise: the name of the enterprise where to use impersonation """ if not user or not enterprise: raise Val...
Impersonate a user in a enterprise Args: user: the name of the user to impersonate enterprise: the name of the enterprise where to use impersonation
entailment
def equals(self, controller): """ Verify if the controller corresponds to the current one. """ if controller is None: return False return self.user == controller.user and self.enterprise == controller.enterprise and self.url == controller.url
Verify if the controller corresponds to the current one.
entailment
def create_application(server, root_url): """ WSGI adapter. It creates a simple WSGI application, that can be used with any WSGI server. The arguments are: #. ``server`` is a pyws server object, #. ``root_url`` is an URL to which the server will be bound. An application created by the function...
WSGI adapter. It creates a simple WSGI application, that can be used with any WSGI server. The arguments are: #. ``server`` is a pyws server object, #. ``root_url`` is an URL to which the server will be bound. An application created by the function transforms WSGI environment into a pyws request o...
entailment
def compiler_dialect(paramstyle='named'): """ 构建dialect """ dialect = SQLiteDialect_pysqlite( json_serializer=json.dumps, json_deserializer=json_deserializer, paramstyle=paramstyle ) dialect.default_paramstyle = paramstyle dialect.statement_compiler = ACompiler_sqlite...
构建dialect
entailment
def create_engine( database, minsize=1, maxsize=10, loop=None, dialect=_dialect, paramstyle=None, **kwargs): """ A coroutine for Engine creation. Returns Engine instance with embedded connection pool. The pool has *minsize* opened connections to ...
A coroutine for Engine creation. Returns Engine instance with embedded connection pool. The pool has *minsize* opened connections to sqlite3.
entailment
def release(self, conn): """Revert back connection to pool.""" if conn.in_transaction: raise InvalidRequestError( "Cannot release a connection with " "not finished transaction" ) raw = conn.connection res = yield from self._pool.rel...
Revert back connection to pool.
entailment
def get_configuration(cls, resource): """ Return how much consumables are used by resource with current configuration. Output example: { <ConsumableItem instance>: <usage>, <ConsumableItem instance>: <usage>, ... } """ ...
Return how much consumables are used by resource with current configuration. Output example: { <ConsumableItem instance>: <usage>, <ConsumableItem instance>: <usage>, ... }
entailment
def close(self): """Close this ResultProxy. Closes the underlying DBAPI cursor corresponding to the execution. Note that any data cached within this ResultProxy is still available. For some types of results, this may include buffered rows. If this ResultProxy was generated from a...
Close this ResultProxy. Closes the underlying DBAPI cursor corresponding to the execution. Note that any data cached within this ResultProxy is still available. For some types of results, this may include buffered rows. If this ResultProxy was generated from an implicit execution, ...
entailment
def get_version(): """Obtain the version number""" import imp import os mod = imp.load_source( 'version', os.path.join('skdata', '__init__.py') ) return mod.__version__
Obtain the version number
entailment
def accept(self, request, uuid=None): """ Accept invitation for current user. To replace user's email with email from invitation - add parameter 'replace_email' to request POST body. """ invitation = self.get_object() if invitation.state != models.Invitation.Sta...
Accept invitation for current user. To replace user's email with email from invitation - add parameter 'replace_email' to request POST body.
entailment
def scope_deletion(sender, instance, **kwargs): """ Run different actions on price estimate scope deletion. If scope is a customer - delete all customer estimates and their children. If scope is a deleted resource - redefine consumption details, recalculate ...
Run different actions on price estimate scope deletion. If scope is a customer - delete all customer estimates and their children. If scope is a deleted resource - redefine consumption details, recalculate ancestors estimates and update estimate details. ...
entailment
def _resource_deletion(resource): """ Recalculate consumption details and save resource details """ if resource.__class__ not in CostTrackingRegister.registered_resources: return new_configuration = {} price_estimate = models.PriceEstimate.update_resource_estimate(resource, new_configuration) ...
Recalculate consumption details and save resource details
entailment
def resource_update(sender, instance, created=False, **kwargs): """ Update resource consumption details and price estimate if its configuration has changed. Create estimates for previous months if resource was created not in current month. """ resource = instance try: new_configuration =...
Update resource consumption details and price estimate if its configuration has changed. Create estimates for previous months if resource was created not in current month.
entailment
def resource_quota_update(sender, instance, **kwargs): """ Update resource consumption details and price estimate if its configuration has changed """ quota = instance resource = quota.scope try: new_configuration = CostTrackingRegister.get_configuration(resource) except ResourceNotRegistere...
Update resource consumption details and price estimate if its configuration has changed
entailment
def _create_historical_estimates(resource, configuration): """ Create consumption details and price estimates for past months. Usually we need to update historical values on resource import. """ today = timezone.now() month_start = core_utils.month_start(today) while month_start > resource....
Create consumption details and price estimates for past months. Usually we need to update historical values on resource import.
entailment