text
stringlengths
81
112k
Unregisters a registered delegate function or a method. Args: callback(function): method to trigger when push center receives events def remove_delegate(self, callback): """ Unregisters a registered delegate function or a method. Args: callback(function...
Reads the configuration file if any def _read_config(cls): """ Reads the configuration file if any """ cls._config_parser = configparser.ConfigParser() cls._config_parser.read(cls._default_attribute_values_configuration_file_path)
Gets the default value of a given property for a given object. These properties can be set in a config INI file looking like .. code-block:: ini [NUEntity] default_behavior = THIS speed = 1000 [NUOtherEntity] att...
Filter each resource separately using its own filter def filter(self, request, queryset, view): """ Filter each resource separately using its own filter """ summary_queryset = queryset filtered_querysets = [] for queryset in summary_queryset.querysets: filter_class = self._g...
This function creates a standard form type from a simplified form. >>> from datetime import date, datetime >>> from pyws.functions.args import TypeFactory >>> from pyws.functions.args import String, Integer, Float, Date, DateTime >>> TypeFactory(str) == String True >>> TypeFactory(float) == Flo...
Generate empty image in temporary file for testing def dummy_image(filetype='gif'): """ Generate empty image in temporary file for testing """ # 1x1px Transparent GIF GIF = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7' tmp_file = tempfile.NamedTemporaryFile(suffix='.%s' % filetype) tmp...
Gets time delta in microseconds. Note: Do NOT use this function without keyword arguments. It will become much-much harder to add extra time ranges later if positional arguments are used. def utime_delta(days=0, hours=0, minutes=0, seconds=0): """Gets time delta in microseconds. Note: Do NOT use this...
Executes specified function with timeout. Uses SIGALRM to interrupt it. :type fn: function :param fn: function to execute :type args: tuple :param args: function args :type kwargs: dict :param kwargs: function kwargs :type timeout: float :param timeout: timeout, seconds; 0 or None me...
Gets the very original function of a decorated one. def get_original_fn(fn): """Gets the very original function of a decorated one.""" fn_type = type(fn) if fn_type is classmethod or fn_type is staticmethod: return get_original_fn(fn.__func__) if hasattr(fn, "original_fn"): return fn.o...
Gets full class or function name. def get_full_name(src): """Gets full class or function name.""" if hasattr(src, "_full_name_"): return src._full_name_ if hasattr(src, "is_decorator"): # Our own decorator or binder if hasattr(src, "decorator"): # Our own binder ...
Converts method call (function and its arguments) to a str(...)-like string. def get_function_call_str(fn, args, kwargs): """Converts method call (function and its arguments) to a str(...)-like string.""" def str_converter(v): try: return str(v) except Exception: try: ...
Converts method call (function and its arguments) to a repr(...)-like string. def get_function_call_repr(fn, args, kwargs): """Converts method call (function and its arguments) to a repr(...)-like string.""" result = get_full_name(fn) + "(" first = True for v in args: if first: fir...
Variation of inspect.getargspec that works for more functions. This function works for Cythonized, non-cpdef functions, which expose argspec information but are not accepted by getargspec. It also works for Python 3 functions that use annotations, which are simply ignored. However, keyword-only arguments a...
Returns whether this function is either a generator function or a Cythonized function. def is_cython_or_generator(fn): """Returns whether this function is either a generator function or a Cythonized function.""" if hasattr(fn, "__func__"): fn = fn.__func__ # Class method, static method if inspect....
Checks if a function is compiled w/Cython. def is_cython_function(fn): """Checks if a function is compiled w/Cython.""" if hasattr(fn, "__func__"): fn = fn.__func__ # Class method, static method name = type(fn).__name__ return ( name == "method_descriptor" or name == "cython_fu...
Returns whether f is a classmethod. def is_classmethod(fn): """Returns whether f is a classmethod.""" # This is True for bound methods if not inspect.ismethod(fn): return False if not hasattr(fn, "__self__"): return False im_self = fn.__self__ # This is None for instance methods...
Cython-compatible functools.wraps implementation. def wraps( wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES ): """Cython-compatible functools.wraps implementation.""" if not is_cython_function(wrapped): return functools.wraps(wrapped, assigned, updated) else:...
Returns all subclasses (direct and recursive) of cls. def get_subclass_tree(cls, ensure_unique=True): """Returns all subclasses (direct and recursive) of cls.""" subclasses = [] # cls.__subclasses__() fails on classes inheriting from type for subcls in type.__subclasses__(cls): subclasses.appen...
This function creates a dict type with the specified name and fields. >>> from pyws.functions.args import DictOf, Field >>> dct = DictOf( ... 'HelloWorldDict', Field('hello', str), Field('hello', int)) >>> issubclass(dct, Dict) True >>> dct.__name__ 'HelloWorldDict' >>> len(dct.fiel...
This function creates a list type with element type ``element_type`` and an empty element value ``element_none_value``. >>> from pyws.functions.args import Integer, ListOf >>> lst = ListOf(int) >>> issubclass(lst, List) True >>> lst.__name__ 'IntegerList' >>> lst.element_type == Integer...
Return metadata for resource-specific actions, such as start, stop, unlink def get_actions(self, request, view): """ Return metadata for resource-specific actions, such as start, stop, unlink """ metadata = OrderedDict() actions = self.get_resource_actions(view) ...
Get fields exposed by action's serializer def get_action_fields(self, view, action_name, resource): """ Get fields exposed by action's serializer """ serializer = view.get_serializer(resource) fields = OrderedDict() if not isinstance(serializer, view.serializer_class) or...
Given an instance of a serializer, return a dictionary of metadata about its fields. def get_serializer_info(self, serializer): """ Given an instance of a serializer, return a dictionary of metadata about its fields. """ if hasattr(serializer, 'child'): # If ...
Get fields metadata skipping empty fields def get_fields(self, serializer_fields): """ Get fields metadata skipping empty fields """ fields = OrderedDict() for field_name, field in serializer_fields.items(): # Skip tags field in action because it is needed only for r...
Given an instance of a serializer field, return a dictionary of metadata about it. def get_field_info(self, field, field_name): """ Given an instance of a serializer field, return a dictionary of metadata about it. """ field_info = OrderedDict() field_info['type'...
把async方法执行后的对象创建为async上下文模式 def connect( database: str, loop: asyncio.BaseEventLoop = None, executor: concurrent.futures.Executor = None, timeout: int = 5, echo: bool = False, isolation_level: str = '', check_same_thread: bool = False, **kwargs: dict ): ...
Recalculate price of consumables that were used by resource until now. Regular task. It is too expensive to calculate consumed price on each request, so we store cached price each hour. If recalculate_total is True - task also recalculates total estimate for current month. def recalcul...
Needs to return the string source for the module. def get_data(self, path): """Needs to return the string source for the module.""" return LineCacheNotebookDecoder( code=self.code, raw=self.raw, markdown=self.markdown ).decode(self.decode(), self.path)
Create a lazy loader source file loader. def loader(self): """Create a lazy loader source file loader.""" loader = super().loader if self._lazy and (sys.version_info.major, sys.version_info.minor) != (3, 4): loader = LazyLoader.factory(loader) # Strip the leading underscore ...
Import a notebook as a module from a filename. dir: The directory to load the file from. main: Load the module in the __main__ context. > assert Notebook.load('loader.ipynb') def load(cls, filename, dir=None, main=False, **kwargs): """Import a notebook as a module from...
* Convert the current source to ast * Apply ast transformers. * Compile the code. def source_to_code(self, nodes, path, *, _optimize=-1): """* Convert the current source to ast * Apply ast transformers. * Compile the code.""" if not isinstance(nodes, ast.Module): ...
Inject extra action URLs. def get_urls(self): """ Inject extra action URLs. """ urls = [] for action in self.get_extra_actions(): regex = r'^{}/$'.format(self._get_action_href(action)) view = self.admin_site.admin_view(action) urls.append(url...
Inject extra links into template context. def changelist_view(self, request, extra_context=None): """ Inject extra links into template context. """ links = [] for action in self.get_extra_actions(): links.append({ 'label': self._get_action_label(acti...
Starts the session. Starting the session will actually get the API key of the current user def start(self): """ Starts the session. Starting the session will actually get the API key of the current user """ if NURESTSession.session_stack: bambo...
Initialize new instances quotas def init_quotas(sender, instance, created=False, **kwargs): """ Initialize new instances quotas """ if not created: return for field in sender.get_quotas_fields(): try: field.get_or_create_quota(scope=instance) except CreationConditionFail...
Creates handler that will recalculate count_quota on creation/deletion def count_quota_handler_factory(count_quota_field): """ Creates handler that will recalculate count_quota on creation/deletion """ def recalculate_count_quota(sender, instance, **kwargs): signal = kwargs['signal'] if signal...
Call aggregated quotas fields update methods def handle_aggregated_quotas(sender, instance, **kwargs): """ Call aggregated quotas fields update methods """ quota = instance # aggregation is not supported for global quotas. if quota.scope is None: return quota_field = quota.get_field() #...
URL of service settings def get_settings(self, link): """ URL of service settings """ return reverse( 'servicesettings-detail', kwargs={'uuid': link.service.settings.uuid}, request=self.context['request'])
URL of service def get_url(self, link): """ URL of service """ view_name = SupportedServices.get_detail_view_for_model(link.service) return reverse(view_name, kwargs={'uuid': link.service.uuid.hex}, request=self.context['request'])
Count total number of all resources connected to link def get_resources_count(self, link): """ Count total number of all resources connected to link """ total = 0 for model in SupportedServices.get_service_resources(link.service): # Format query path from resource to...
When max_na_values was informed, remove columns when the proportion of total NA values more than max_na_values threshold. When max_unique_values was informed, remove columns when the proportion of the total of unique values is more than the max_unique_values threshold, just for columns ...
:return: def dropna(self): """ :return: """ step = { 'data-set': self.iid, 'operation': 'drop-na', 'expression': '{"axis": 0}' } self.attr_update(attr='steps', value=[step])
@deprecated :param message: :return: def log(self, message: str): """ @deprecated :param message: :return: """ dset_log_id = '_%s_log' % self.iid if dset_log_id not in self.parent.data.keys(): dset = self.parent.data.create_dataset...
:param compute: if should call compute method :return: def summary(self, compute=False) -> pd.DataFrame: """ :param compute: if should call compute method :return: """ if compute or self.result is None: self.compute() return summary(self.result)
Twisted Web adapter. It has two arguments: #. ``request`` is a Twisted Web request object, #. ``server`` is a pyws server object. First one is the context of an application, function ``serve`` transforms it into a pyws request object. Then it feeds the request to the server, gets the response, set...
Returns list of application models in topological order. It is used in order to correctly delete dependent resources. def get_sorted_dependencies(service_model): """ Returns list of application models in topological order. It is used in order to correctly delete dependent resources. """ app_mod...
Update instance fields based on imported from backend data. Save changes to DB only one or more fields were changed. def update_pulled_fields(instance, imported_instance, fields): """ Update instance fields based on imported from backend data. Save changes to DB only one or more fields were changed. ...
Set resource state to ERRED and append/create "not found" error message. def handle_resource_not_found(resource): """ Set resource state to ERRED and append/create "not found" error message. """ resource.set_erred() resource.runtime_state = '' message = 'Does not exist at backend.' if messa...
Recover resource if its state is ERRED and clear error message. def handle_resource_update_success(resource): """ Recover resource if its state is ERRED and clear error message. """ update_fields = [] if resource.state == resource.States.ERRED: resource.recover() update_fields.appen...
Set header value def set_header(self, header, value): """ Set header value """ # requests>=2.11 only accepts `str` or `bytes` header values # raising an exception here, instead of leaving it to `requests` makes # it easy to know where we passed a wrong header type in the code. i...
Mark instance as erred and save error message def set_instance_erred(self, instance, error_message): """ Mark instance as erred and save error message """ instance.set_erred() instance.error_message = error_message instance.save(update_fields=['state', 'error_message'])
Use ISO 639-3 ?? def map_language(language, dash3=True): """ Use ISO 639-3 ?? """ if dash3: from iso639 import languages else: from pycountry import languages if '_' in language: language = language.split('_')[0] if len(language) == 2: try: return languages.get(alph...
Delete each resource using specific executor. Convert executors to task and combine all deletion task into single sequential task. def get_task_signature(cls, instance, serialized_instance, **kwargs): """ Delete each resource using specific executor. Convert executors to task and combin...
Return a OrderedDict ordered by key names from the :unsorted_dict: def sort_dict(unsorted_dict): """ Return a OrderedDict ordered by key names from the :unsorted_dict: """ sorted_dict = OrderedDict() # sort items before inserting them into a dict for key, value in sorted(unsorted_dict.items(), ...
Format time_and_value_list to time segments Parameters ^^^^^^^^^^ time_and_value_list: list of tuples Have to be sorted by time Example: [(time, value), (time, value) ...] segments_count: integer How many segments will be in result Returns ^^^^^^^ List of dictionarie...
Serialize Django model instance def serialize_instance(instance): """ Serialize Django model instance """ model_name = force_text(instance._meta) return '{}:{}'.format(model_name, instance.pk)
Deserialize Django model instance def deserialize_instance(serialized_instance): """ Deserialize Django model instance """ model_name, pk = serialized_instance.split(':') model = apps.get_model(model_name) return model._default_manager.get(pk=pk)
Deserialize Python class def deserialize_class(serilalized_cls): """ Deserialize Python class """ module_name, cls_name = serilalized_cls.split(':') module = importlib.import_module(module_name) return getattr(module, cls_name)
Restore instance from URL def instance_from_url(url, user=None): """ Restore instance from URL """ # XXX: This circular dependency will be removed then filter_queryset_for_user # will be moved to model manager method from waldur_core.structure.managers import filter_queryset_for_user url = clear_u...
Close this transaction. If this transaction is the base transaction in a begin/commit nesting, the transaction will rollback(). Otherwise, the method returns. This is used to cancel a Transaction without affecting the scope of an enclosing transaction. def close(self): ...
Commit this transaction. def commit(self): """ Commit this transaction. """ if not self._parent._is_active: raise exc.InvalidRequestError("This transaction is inactive") yield from self._do_commit() self._is_active = False
Returns an app config for the given name, not by label. def _get_app_config(self, app_name): """ Returns an app config for the given name, not by label. """ matches = [app_config for app_config in apps.get_app_configs() if app_config.name == app_name] if not ...
Some plugins ship multiple applications and extensions. However all of them have the same version, because they are released together. That's why only-top level module is used to fetch version information. def _get_app_version(self, app_config): """ Some plugins ship multiple applicatio...
Returns a list of ListLink items to be added to Quick Access tab. Contains: - links to Organizations, Projects and Users; - a link to shared service settings; - custom configured links in admin/settings FLUENT_DASHBOARD_QUICK_ACCESS_LINKS attribute; def _get_quick_access_info(self): ...
Returns a LinkList based module which contains link to shared service setting instances in ERRED state. def _get_erred_shared_settings_module(self): """ Returns a LinkList based module which contains link to shared service setting instances in ERRED state. """ result_module = modules.Li...
Returns a list of links to resources which are in ERRED state and linked to a shared service settings. def _get_erred_resources_module(self): """ Returns a list of links to resources which are in ERRED state and linked to a shared service settings. """ result_module = modules.LinkList(t...
Django adapter. It has three arguments: #. ``request`` is a Django request object, #. ``tail`` is everything that's left from an URL, which adapter is attached to, #. ``server`` is a pyws server object. First two are the context of an application, function ``serve`` transforms them into a p...
Get index of the given item Args: nurest_object (bambou.NURESTObject): the NURESTObject object to verify Returns: Returns the position of the object. Raises: Raise a ValueError exception if object is not present def index(self, nures...
Register the fetcher for a served object. This method will fill the fetcher with `managed_class` instances Args: parent_object: the instance of the parent object to serve Returns: It returns the fetcher instance. def fetcher_with_object(cls, parent...
Prepare headers for the given request Args: request: the NURESTRequest to send filter: string order_by: string group_by: list of names page: int page_size: int def _prepare_headers(self, request, filter=None, o...
Fetch objects according to given filter and page. Note: This method fetches all managed class objects and store them in local_name of the served object. which means that the parent object will hold them in a list. You can prevent this behavior ...
Fetching objects has been done def _did_fetch(self, connection): """ Fetching objects has been done """ self.current_connection = connection response = connection.response should_commit = 'commit' not in connection.user_info or connection.user_info['commit'] if connection.resp...
Fetch object and directly return them Note: `get` won't put the fetched objects in the parent's children list. You cannot override this behavior. If you want to commit them in the parent you can use :method:vsdk.NURESTFetcher.fetch or manually add the list wi...
Fetch object and directly return the first one Note: `get_first` won't put the fetched object in the parent's children list. You cannot override this behavior. If you want to commit it in the parent you can use :method:vsdk.NURESTFetcher.fetch or manually add...
Get the total count of objects that can be fetched according to filter This method can be asynchronous and trigger the callback method when result is ready. Args: filter (string): string that represents a predicate fitler (eg. name == 'x') order_by (...
Get the total count of objects that can be fetched according to filter Args: filter (string): string that represents a predicate fitler (eg. name == 'x') order_by (string): string that represents an order by clause group_by (string): list of names for groupin...
Called when count if finished def _did_count(self, connection): """ Called when count if finished """ self.current_connection = connection response = connection.response count = 0 callback = None if 'X-Nuage-Count' in response.headers: count = int(response....
Send a content array from the connection def _send_content(self, content, connection): """ Send a content array from the connection """ if connection: if connection.async: callback = connection.callbacks['remote'] if callback: callback(...
Save how much consumables were used and update current configuration. Return True if configuration changed. def update_configuration(self, new_configuration): """ Save how much consumables were used and update current configuration. Return True if configuration changed. """ ...
How many resources were (or will be) consumed until end of the month 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...
How many consumables were (or will be) used by resource until given time. 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: ...
How much minutes passed from last update to given time 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)
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. def get_for_resource(resource): """ Get list of all price list items that should be used for resource. If p...
Get a list of available extensions 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_mo...
Truncates a string to be at most max_length long. 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)] + "..."
Wrapper for str() that catches exceptions. 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 repr() that catches exceptions. 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)
Returns an object with the key-value pairs in source as attributes. 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
Shallow copies all public attributes from source_obj to dest_obj. Overwrites them if they already exist. 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.getmemb...
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...
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. def catchable_exceptions(exceptions): """Returns True if exceptions can be caught in the except clause. The exception can be caught if it is an Exceptio...
Temporarily overrides the old value with the new one. 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
Execute validation for actions that are related to particular object 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) an...
returns dictionary version of row using keys from self.field_map 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 detected dialect of filepath and sets self.has_header if not passed in __init__ kwargs Arguments: filepath (str): filepath of target csv file def _dialect(self, filepath): """returns detected dialect of filepath and sets self.has_header if not passed in __init__ kwar...
Get list of services content types 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)
Create default price list items for each registered resource. 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...
Re-initialize configuration for resource if it has been changed. This method should be called if resource consumption strategy was changed. def reinit_configurations(self, request): """ Re-initialize configuration for resource if it has been changed. This method should be called if re...
Encrypt the given message def encrypt(self, message): """ Encrypt the given message """ if not isinstance(message, (bytes, str)): raise TypeError return hashlib.sha1(message.encode('utf-8')).hexdigest()
Updates next_trigger_at field if: - instance become active - instance.schedule changed - instance is new def save(self, *args, **kwargs): """ Updates next_trigger_at field if: - instance become active - instance.schedule changed - instance is new ...