text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Wait until thread exit <END_TASK> <USER_TASK:> Description: 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!") self._thread.join() self.stop()
<SYSTEM_TASK:> Receive an event from connection <END_TASK> <USER_TASK:> Description: 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.status_code != 200: pushcenter_logger.error("[NURESTPushCenter]: Connection failure [%s] %s" % (response.status_code, response.errors)) else: data = response.data if len(self._delegate_methods) > 0: for m in self._delegate_methods: try: m(data) except Exception as exc: pushcenter_logger.error("[NURESTPushCenter] Delegate method %s failed:\n%s" % (m, exc)) elif data: events = data['events'] self.nb_events_received += len(events) self.nb_push_received += 1 pushcenter_logger.info("[NURESTPushCenter] Received Push #%s (total=%s, latest=%s)\n%s" % (self.nb_push_received, self.nb_events_received, len(events), json.dumps(events, indent=4))) self._last_events.extend(events) if self._is_running: uuid = None if data and 'uuid' in data: uuid = data['uuid'] self._listen(uuid)
<SYSTEM_TASK:> Listen a connection uuid <END_TASK> <USER_TASK:> Description: 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: events_url = "%s?uuid=%s" % (events_url, uuid) request = NURESTRequest(method='GET', url=events_url) # Force async to False so the push center will have only 1 thread running connection = NURESTConnection(request=request, async=True, callback=self._did_receive_event, root_object=self._root_object) if self._timeout: if int(time()) - self._start_time >= self._timeout: pushcenter_logger.debug("[NURESTPushCenter] Timeout (timeout=%ss)." % self._timeout) return else: connection.timeout = self._timeout pushcenter_logger.info('Bambou Sending >>>>>>\n%s %s' % (request.method, request.url)) # connection.ignore_request_idle = True connection.start()
<SYSTEM_TASK:> Registers a new delegate callback <END_TASK> <USER_TASK:> Description: def add_delegate(self, callback): """ 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 """
if callback in self._delegate_methods: return self._delegate_methods.append(callback)
<SYSTEM_TASK:> Unregisters a registered delegate function or a method. <END_TASK> <USER_TASK:> Description: def remove_delegate(self, callback): """ Unregisters a registered delegate function or a method. Args: callback(function): method to trigger when push center receives events """
if callback not in self._delegate_methods: return self._delegate_methods.remove(callback)
<SYSTEM_TASK:> Reads the configuration file if any <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Gets the default value of a given property for a given object. <END_TASK> <USER_TASK:> Description: def get_default_attribute_value(cls, object_class, property_name, attr_type=str): """ 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] attribute_name = a value This will be used when creating a :class:`bambou.NURESTObject` when no parameter or data is provided """
if not cls._default_attribute_values_configuration_file_path: return None if not cls._config_parser: cls._read_config() class_name = object_class.__name__ if not cls._config_parser.has_section(class_name): return None if not cls._config_parser.has_option(class_name, property_name): return None if sys.version_info < (3,): integer_types = (int, long,) else: integer_types = (int,) if isinstance(attr_type, integer_types): return cls._config_parser.getint(class_name, property_name) elif attr_type is bool: return cls._config_parser.getboolean(class_name, property_name) else: return cls._config_parser.get(class_name, property_name)
<SYSTEM_TASK:> Filter each resource separately using its own filter <END_TASK> <USER_TASK:> Description: 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._get_filter(queryset) queryset = filter_class(request.query_params, queryset=queryset).qs filtered_querysets.append(queryset) summary_queryset.querysets = filtered_querysets return summary_queryset
<SYSTEM_TASK:> This function creates a standard form type from a simplified form. <END_TASK> <USER_TASK:> Description: def TypeFactory(type_): """ 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) == Float True >>> TypeFactory(date) == Date True >>> TypeFactory(datetime) == DateTime True >>> from operator import attrgetter >>> from pyws.functions.args import Dict >>> dct = TypeFactory({0: 'HelloWorldDict', 'hello': str, 'world': int}) >>> issubclass(dct, Dict) True >>> dct.__name__ 'HelloWorldDict' >>> fields = sorted(dct.fields, key=attrgetter('name')) >>> len(dct.fields) 2 >>> fields[0].name == 'hello' True >>> fields[0].type == String True >>> fields[1].name == 'world' True >>> fields[1].type == Integer True >>> from pyws.functions.args import List >>> lst = TypeFactory([int]) >>> issubclass(lst, List) True >>> lst.__name__ 'IntegerList' >>> lst.element_type == Integer True """
if isinstance(type_, type) and issubclass(type_, Type): return type_ for x in __types__: if x.represents(type_): return x.get(type_) raise UnknownType(type_)
<SYSTEM_TASK:> Generate empty image in temporary file for testing <END_TASK> <USER_TASK:> Description: 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_file.write(base64.b64decode(GIF)) return open(tmp_file.name, 'rb')
<SYSTEM_TASK:> Gets time delta in microseconds. <END_TASK> <USER_TASK:> Description: def utime_delta(days=0, hours=0, minutes=0, seconds=0): """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. """
return (days * DAY) + (hours * HOUR) + (minutes * MINUTE) + (seconds * SECOND)
<SYSTEM_TASK:> Executes specified function with timeout. Uses SIGALRM to interrupt it. <END_TASK> <USER_TASK:> Description: def execute_with_timeout( fn, args=None, kwargs=None, timeout=None, fail_if_no_timer=True, signal_type=_default_signal_type, timer_type=_default_timer_type, timeout_exception_cls=TimeoutError, ): """ 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 means no timeout :type fail_if_no_timer: bool :param fail_if_no_timer: fail, if timer is nor available; normally it's available only in the main thread :type signal_type: signalnum :param signal_type: type of signal to use (see signal module) :type timer_type: signal.ITIMER_REAL, signal.ITIMER_VIRTUAL or signal.ITIMER_PROF :param timer_type: type of timer to use (see signal module) :type timeout_exception_cls: class :param timeout_exception_cls: exception to throw in case of timeout :return: fn call result. """
if args is None: args = empty_tuple if kwargs is None: kwargs = empty_dict if timeout is None or timeout == 0 or signal_type is None or timer_type is None: return fn(*args, **kwargs) def signal_handler(signum, frame): raise timeout_exception_cls(inspection.get_function_call_str(fn, args, kwargs)) old_signal_handler = none timer_is_set = False try: try: old_signal_handler = signal.signal(signal_type, signal_handler) signal.setitimer(timer_type, timeout) timer_is_set = True except ValueError: if fail_if_no_timer: raise NotSupportedError( "Timer is not available; the code is probably invoked from outside the main " "thread." ) return fn(*args, **kwargs) finally: if timer_is_set: signal.setitimer(timer_type, 0) if old_signal_handler is not none: signal.signal(signal_type, old_signal_handler)
<SYSTEM_TASK:> Gets the very original function of a decorated one. <END_TASK> <USER_TASK:> Description: 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.original_fn if hasattr(fn, "fn"): fn.original_fn = get_original_fn(fn.fn) return fn.original_fn return fn
<SYSTEM_TASK:> Gets full class or function name. <END_TASK> <USER_TASK:> Description: 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 _full_name_ = str(src.decorator) # It's a short-living object, so we don't cache result else: # Our own decorator _full_name_ = str(src) try: src._full_name_ = _full_name_ except AttributeError: pass except TypeError: pass elif hasattr(src, "im_class"): # Bound method cls = src.im_class _full_name_ = get_full_name(cls) + "." + src.__name__ # It's a short-living object, so we don't cache result elif hasattr(src, "__module__") and hasattr(src, "__name__"): # Func or class _full_name_ = ( ("<unknown module>" if src.__module__ is None else src.__module__) + "." + src.__name__ ) try: src._full_name_ = _full_name_ except AttributeError: pass except TypeError: pass else: # Something else _full_name_ = str(get_original_fn(src)) return _full_name_
<SYSTEM_TASK:> Variation of inspect.getargspec that works for more functions. <END_TASK> <USER_TASK:> Description: def getargspec(func): """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 are not supported. """
if inspect.ismethod(func): func = func.__func__ # Cythonized functions have a .__code__, but don't pass inspect.isfunction() try: code = func.__code__ except AttributeError: raise TypeError("{!r} is not a Python function".format(func)) if hasattr(code, "co_kwonlyargcount") and code.co_kwonlyargcount > 0: raise ValueError("keyword-only arguments are not supported by getargspec()") args, varargs, varkw = inspect.getargs(code) return inspect.ArgSpec(args, varargs, varkw, func.__defaults__)
<SYSTEM_TASK:> Returns whether this function is either a generator function or a Cythonized function. <END_TASK> <USER_TASK:> Description: 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.isgeneratorfunction(fn): return True name = type(fn).__name__ return ( name == "generator" or name == "method_descriptor" or name == "cython_function_or_method" or name == "builtin_function_or_method" )
<SYSTEM_TASK:> Returns whether f is a classmethod. <END_TASK> <USER_TASK:> Description: 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 on classes, but True # for instance methods on instances. if im_self is None: return False # This is True for class methods of new- and old-style classes, respectively return isinstance(im_self, six.class_types)
<SYSTEM_TASK:> This function creates a dict type with the specified name and fields. <END_TASK> <USER_TASK:> Description: def DictOf(name, *fields): """ 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.fields) 2 """
ret = type(name, (Dict,), {'fields': []}) #noinspection PyUnresolvedReferences ret.add_fields(*fields) return ret
<SYSTEM_TASK:> This function creates a list type with element type ``element_type`` and an <END_TASK> <USER_TASK:> Description: def ListOf(element_type, element_none_value=None): """ 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 True """
from pyws.functions.args.types import TypeFactory element_type = TypeFactory(element_type) return type(element_type.__name__ + 'List', (List,), { 'element_type': element_type, 'element_none_value': element_none_value})
<SYSTEM_TASK:> Return metadata for resource-specific actions, <END_TASK> <USER_TASK:> Description: 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) resource = view.get_object() for action_name, action in actions.items(): if action_name == 'update': view.request = clone_request(request, 'PUT') else: view.action = action_name data = ActionSerializer(action, action_name, request, view, resource) metadata[action_name] = data.serialize() if not metadata[action_name]['enabled']: continue fields = self.get_action_fields(view, action_name, resource) if not fields: metadata[action_name]['type'] = 'button' else: metadata[action_name]['type'] = 'form' metadata[action_name]['fields'] = fields view.action = None view.request = request return metadata
<SYSTEM_TASK:> Get fields exposed by action's serializer <END_TASK> <USER_TASK:> Description: 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 action_name == 'update': fields = self.get_fields(serializer.fields) return fields
<SYSTEM_TASK:> Get fields metadata skipping empty fields <END_TASK> <USER_TASK:> Description: 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 resource creation # See also: WAL-1223 if field_name == 'tags': continue info = self.get_field_info(field, field_name) if info: fields[field_name] = info return fields
<SYSTEM_TASK:> Recalculate price of consumables that were used by resource until now. <END_TASK> <USER_TASK:> Description: def recalculate_estimate(recalculate_total=False): """ 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. """
# Celery does not import server.urls and does not discover cost tracking modules. # So they should be discovered implicitly. CostTrackingRegister.autodiscover() # Step 1. Recalculate resources estimates. for resource_model in CostTrackingRegister.registered_resources: for resource in resource_model.objects.all(): _update_resource_consumed(resource, recalculate_total=recalculate_total) # Step 2. Move from down to top and recalculate consumed estimate for each # object based on its children. ancestors_models = [m for m in models.PriceEstimate.get_estimated_models() if not issubclass(m, structure_models.ResourceMixin)] for model in ancestors_models: for ancestor in model.objects.all(): _update_ancestor_consumed(ancestor)
<SYSTEM_TASK:> Inject extra links into template context. <END_TASK> <USER_TASK:> Description: 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(action), 'href': self._get_action_href(action) }) extra_context = extra_context or {} extra_context['extra_links'] = links return super(ExtraActionsMixin, self).changelist_view( request, extra_context=extra_context, )
<SYSTEM_TASK:> Starts the session. <END_TASK> <USER_TASK:> Description: def start(self): """ Starts the session. Starting the session will actually get the API key of the current user """
if NURESTSession.session_stack: bambou_logger.critical("Starting a session inside a with statement is not supported.") raise Exception("Starting a session inside a with statement is not supported.") NURESTSession.current_session = self self._authenticate() return self
<SYSTEM_TASK:> Call aggregated quotas fields update methods <END_TASK> <USER_TASK:> Description: 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() # usage aggregation should not count another usage aggregator field to avoid calls duplication. if isinstance(quota_field, fields.UsageAggregatorQuotaField) or quota_field is None: return signal = kwargs['signal'] for aggregator_quota in quota_field.get_aggregator_quotas(quota): field = aggregator_quota.get_field() if signal == signals.post_save: field.post_child_quota_save(aggregator_quota.scope, child_quota=quota, created=kwargs.get('created')) elif signal == signals.pre_delete: field.pre_child_quota_delete(aggregator_quota.scope, child_quota=quota)
<SYSTEM_TASK:> Count total number of all resources connected to link <END_TASK> <USER_TASK:> Description: 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 service project link query = {model.Permissions.project_path.split('__')[0]: link} total += model.objects.filter(**query).count() return total
<SYSTEM_TASK:> When max_na_values was informed, remove columns when the proportion of <END_TASK> <USER_TASK:> Description: def drop_columns( self, max_na_values: int = None, max_unique_values: int = None ): """ 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 with type as object or category. :param max_na_values: proportion threshold of max na values :param max_unique_values: :return: """
step = {} if max_na_values is not None: step = { 'data-set': self.iid, 'operation': 'drop-na', 'expression': '{"max_na_values":%s, "axis": 1}' % max_na_values } if max_unique_values is not None: step = { 'data-set': self.iid, 'operation': 'drop-unique', 'expression': '{"max_unique_values":%s}' % max_unique_values } self.attr_update(attr='steps', value=[step])
<SYSTEM_TASK:> Returns list of application models in topological order. <END_TASK> <USER_TASK:> Description: 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_models = list(service_model._meta.app_config.get_models()) dependencies = {model: set() for model in app_models} relations = ( relation for model in app_models for relation in model._meta.related_objects if relation.on_delete in (models.PROTECT, models.CASCADE) ) for rel in relations: dependencies[rel.model].add(rel.related_model) return stable_topological_sort(app_models, dependencies)
<SYSTEM_TASK:> Update instance fields based on imported from backend data. <END_TASK> <USER_TASK:> Description: 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. """
modified = False for field in fields: pulled_value = getattr(imported_instance, field) current_value = getattr(instance, field) if current_value != pulled_value: setattr(instance, field, pulled_value) logger.info("%s's with PK %s %s field updated from value '%s' to value '%s'", instance.__class__.__name__, instance.pk, field, current_value, pulled_value) modified = True error_message = getattr(imported_instance, 'error_message', '') or getattr(instance, 'error_message', '') if error_message and instance.error_message != error_message: instance.error_message = imported_instance.error_message modified = True if modified: instance.save()
<SYSTEM_TASK:> Mark instance as erred and save error message <END_TASK> <USER_TASK:> Description: 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'])
<SYSTEM_TASK:> Delete each resource using specific executor. <END_TASK> <USER_TASK:> Description: def get_task_signature(cls, instance, serialized_instance, **kwargs): """ Delete each resource using specific executor. Convert executors to task and combine all deletion task into single sequential task. """
cleanup_tasks = [ ProjectResourceCleanupTask().si( core_utils.serialize_class(executor_cls), core_utils.serialize_class(model_cls), serialized_instance, ) for (model_cls, executor_cls) in cls.executors ] if not cleanup_tasks: return core_tasks.EmptyTask() return chain(cleanup_tasks)
<SYSTEM_TASK:> Format time_and_value_list to time segments <END_TASK> <USER_TASK:> Description: def format_time_and_value_to_segment_list(time_and_value_list, segments_count, start_timestamp, end_timestamp, average=False): """ 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 dictionaries Example: [{'from': time1, 'to': time2, 'value': sum_of_values_from_time1_to_time2}, ...] """
segment_list = [] time_step = (end_timestamp - start_timestamp) / segments_count for i in range(segments_count): segment_start_timestamp = start_timestamp + time_step * i segment_end_timestamp = segment_start_timestamp + time_step value_list = [ value for time, value in time_and_value_list if time >= segment_start_timestamp and time < segment_end_timestamp] segment_value = sum(value_list) if average and len(value_list) != 0: segment_value /= len(value_list) segment_list.append({ 'from': segment_start_timestamp, 'to': segment_end_timestamp, 'value': segment_value, }) return segment_list
<SYSTEM_TASK:> Returns an app config for the given name, not by label. <END_TASK> <USER_TASK:> Description: 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 matches: return return matches[0]
<SYSTEM_TASK:> Some plugins ship multiple applications and extensions. <END_TASK> <USER_TASK:> Description: def _get_app_version(self, app_config): """ 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. """
base_name = app_config.__module__.split('.')[0] module = __import__(base_name) return getattr(module, '__version__', 'N/A')
<SYSTEM_TASK:> Returns a LinkList based module which contains link to shared service setting instances in ERRED state. <END_TASK> <USER_TASK:> Description: 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.LinkList(title=_('Shared provider settings in erred state')) result_module.template = 'admin/dashboard/erred_link_list.html' erred_state = structure_models.SharedServiceSettings.States.ERRED queryset = structure_models.SharedServiceSettings.objects settings_in_erred_state = queryset.filter(state=erred_state).count() if settings_in_erred_state: result_module.title = '%s (%s)' % (result_module.title, settings_in_erred_state) for service_settings in queryset.filter(state=erred_state).iterator(): module_child = self._get_link_to_instance(service_settings) module_child['error'] = service_settings.error_message result_module.children.append(module_child) else: result_module.pre_content = _('Nothing found.') return result_module
<SYSTEM_TASK:> Returns a list of links to resources which are in ERRED state and linked to a shared service settings. <END_TASK> <USER_TASK:> Description: 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(title=_('Resources in erred state')) erred_state = structure_models.NewResource.States.ERRED children = [] resource_models = SupportedServices.get_resource_models() resources_in_erred_state_overall = 0 for resource_type, resource_model in resource_models.items(): queryset = resource_model.objects.filter(service_project_link__service__settings__shared=True) erred_amount = queryset.filter(state=erred_state).count() if erred_amount: resources_in_erred_state_overall = resources_in_erred_state_overall + erred_amount link = self._get_erred_resource_link(resource_model, erred_amount, erred_state) children.append(link) if resources_in_erred_state_overall: result_module.title = '%s (%s)' % (result_module.title, resources_in_erred_state_overall) result_module.children = children else: result_module.pre_content = _('Nothing found.') return result_module
<SYSTEM_TASK:> Register the fetcher for a served object. <END_TASK> <USER_TASK:> Description: def fetcher_with_object(cls, parent_object, relationship="child"): """ 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. """
fetcher = cls() fetcher.parent_object = parent_object fetcher.relationship = relationship rest_name = cls.managed_object_rest_name() parent_object.register_fetcher(fetcher, rest_name) return fetcher
<SYSTEM_TASK:> Prepare headers for the given request <END_TASK> <USER_TASK:> Description: def _prepare_headers(self, request, filter=None, order_by=None, group_by=[], page=None, page_size=None): """ 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 """
if filter: request.set_header('X-Nuage-Filter', filter) if order_by: request.set_header('X-Nuage-OrderBy', order_by) if page is not None: request.set_header('X-Nuage-Page', str(page)) if page_size: request.set_header('X-Nuage-PageSize', str(page_size)) if len(group_by) > 0: header = ", ".join(group_by) request.set_header('X-Nuage-GroupBy', 'true') request.set_header('X-Nuage-Attributes', header)
<SYSTEM_TASK:> Fetch objects according to given filter and page. <END_TASK> <USER_TASK:> Description: def fetch(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None): """ 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 by setting commit to False. In that case, the fetched children won't be added in the parent object cache. Args: filter (string): string that represents a predicate filter order_by (string): string that represents an order by clause group_by (string): list of names for grouping page (int): number of the page to load page_size (int): number of results per page commit (bool): boolean to update current object callback (function): Callback that should be called in case of a async request Returns: tuple: Returns a tuple of information (fetcher, served object, fetched objects, connection) Example: >>> entity.children.fetch() (<NUChildrenFetcher at aaaa>, <NUEntity at bbbb>, [<NUChildren at ccc>, <NUChildren at ddd>], <NURESTConnection at zzz>) """
request = NURESTRequest(method=HTTP_METHOD_GET, url=self._prepare_url(), params=query_parameters) self._prepare_headers(request=request, filter=filter, order_by=order_by, group_by=group_by, page=page, page_size=page_size) if async: return self.parent_object.send_request(request=request, async=async, local_callback=self._did_fetch, remote_callback=callback, user_info={'commit': commit}) connection = self.parent_object.send_request(request=request, user_info={'commit': commit}) return self._did_fetch(connection=connection)
<SYSTEM_TASK:> Fetching objects has been done <END_TASK> <USER_TASK:> Description: 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.response.status_code >= 400 and BambouConfig._should_raise_bambou_http_error: raise BambouHTTPError(connection=connection) if response.status_code != 200: if should_commit: self.current_total_count = 0 self.current_page = 0 self.current_ordered_by = '' return self._send_content(content=None, connection=connection) results = response.data fetched_objects = list() current_ids = list() if should_commit: if 'X-Nuage-Count' in response.headers and response.headers['X-Nuage-Count']: self.current_total_count = int(response.headers['X-Nuage-Count']) if 'X-Nuage-Page' in response.headers and response.headers['X-Nuage-Page']: self.current_page = int(response.headers['X-Nuage-Page']) if 'X-Nuage-OrderBy' in response.headers and response.headers['X-Nuage-OrderBy']: self.current_ordered_by = response.headers['X-Nuage-OrderBy'] if results: for result in results: nurest_object = self.new() nurest_object.from_dict(result) nurest_object.parent = self.parent_object fetched_objects.append(nurest_object) if not should_commit: continue current_ids.append(nurest_object.id) if nurest_object in self: idx = self.index(nurest_object) current_object = self[idx] current_object.from_dict(nurest_object.to_dict()) else: self.append(nurest_object) if should_commit: for obj in self: if obj.id not in current_ids: self.remove(obj) return self._send_content(content=fetched_objects, connection=connection)
<SYSTEM_TASK:> Fetch object and directly return them <END_TASK> <USER_TASK:> Description: def get(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None): """ 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 with :method:vsdk.NURESTObject.add_child Args: filter (string): string that represents a predicate filter order_by (string): string that represents an order by clause group_by (string): list of names for grouping page (int): number of the page to load page_size (int): number of results per page commit (bool): boolean to update current object callback (function): Callback that should be called in case of a async request Returns: list: list of vsdk.NURESTObject if any Example: >>> print entity.children.get() [<NUChildren at xxx>, <NUChildren at yyyy>, <NUChildren at zzz>] """
return self.fetch(filter=filter, order_by=order_by, group_by=group_by, page=page, page_size=page_size, query_parameters=query_parameters, commit=commit)[2]
<SYSTEM_TASK:> Fetch object and directly return the first one <END_TASK> <USER_TASK:> Description: def get_first(self, filter=None, order_by=None, group_by=[], query_parameters=None, commit=False, async=False, callback=None): """ 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 it with :method:vsdk.NURESTObject.add_child Args: filter (string): string that represents a predicate filter order_by (string): string that represents an order by clause group_by (string): list of names for grouping page (int): number of the page to load page_size (int): number of results per page commit (bool): boolean to update current object callback (function): Callback that should be called in case of a async request Returns: vsdk.NURESTObject: the first object if any, or None Example: >>> print entity.children.get_first(filter="name == 'My Entity'") <NUChildren at xxx> """
objects = self.get(filter=filter, order_by=order_by, group_by=group_by, page=0, page_size=1, query_parameters=query_parameters, commit=commit) return objects[0] if len(objects) else None
<SYSTEM_TASK:> Called when count if finished <END_TASK> <USER_TASK:> Description: 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.headers['X-Nuage-Count']) if 'remote' in connection.callbacks: callback = connection.callbacks['remote'] if connection.async: if callback: callback(self, self.parent_object, count) self.current_connection.reset() self.current_connection = None else: if connection.response.status_code >= 400 and BambouConfig._should_raise_bambou_http_error: raise BambouHTTPError(connection=connection) return (self, self.parent_object, count)
<SYSTEM_TASK:> Send a content array from the connection <END_TASK> <USER_TASK:> Description: 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(self, self.parent_object, content) self.current_connection.reset() self.current_connection = None else: return (self, self.parent_object, content)
<SYSTEM_TASK:> Save how much consumables were used and update current configuration. <END_TASK> <USER_TASK:> Description: 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.month != self.price_estimate.month: raise ConsumptionDetailUpdateError('It is possible to update consumption details only for current month.') minutes_from_last_update = self._get_minutes_from_last_update(now) for consumable_item, usage in self.configuration.items(): consumed_after_modification = usage * minutes_from_last_update self.consumed_before_update[consumable_item] = ( self.consumed_before_update.get(consumable_item, 0) + consumed_after_modification) self.configuration = new_configuration self.last_update_time = now self.save() return True
<SYSTEM_TASK:> How much minutes passed from last update to given time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Get list of all price list items that should be used for resource. <END_TASK> <USER_TASK:> Description: 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(resource) default_items = set(DefaultPriceListItem.objects.filter(resource_content_type=resource_content_type)) service = resource.service_project_link.service items = set(PriceListItem.objects.filter( default_price_list_item__in=default_items, service=service).select_related('default_price_list_item')) rewrited_defaults = set([i.default_price_list_item for i in items]) return items | (default_items - rewrited_defaults)
<SYSTEM_TASK:> Get a list of available extensions <END_TASK> <USER_TASK:> Description: 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_module, cls): if not extension_module.is_assembly(): yield extension_module else: assemblies.append(extension_module) for assembly in assemblies: yield assembly
<SYSTEM_TASK:> Truncates a string to be at most max_length long. <END_TASK> <USER_TASK:> Description: 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)] + "..."
<SYSTEM_TASK:> Returns an object with the key-value pairs in source as attributes. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Shallow copies all public attributes from source_obj to dest_obj. <END_TASK> <USER_TASK:> Description: 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_obj, name, value)
<SYSTEM_TASK:> Creates a Python class or function from its fully qualified name. <END_TASK> <USER_TASK:> Description: 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 function or class object. This method is used by serialization code to create a function or class from a fully qualified name. """
if six.PY3: if not isinstance(name, str): raise TypeError("name must be str, not %r" % type(name)) else: if isinstance(name, unicode): name = name.encode("ascii") if not isinstance(name, (str, unicode)): raise TypeError("name must be bytes or unicode, got %r" % type(name)) pos = name.rfind(".") if pos < 0: raise ValueError("Invalid function or class name %s" % name) module_name = name[:pos] func_name = name[pos + 1 :] try: mod = __import__(module_name, fromlist=[func_name], level=0) except ImportError: # Hail mary. if the from import doesn't work, then just import the top level module # and do getattr on it, one level at a time. This will handle cases where imports are # done like `from . import submodule as another_name` parts = name.split(".") mod = __import__(parts[0], level=0) for i in range(1, len(parts)): mod = getattr(mod, parts[i]) return mod else: return getattr(mod, func_name)
<SYSTEM_TASK:> Returns True if exceptions can be caught in the except clause. <END_TASK> <USER_TASK:> Description: 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 ( isinstance(exceptions, tuple) and exceptions and all(issubclass(it, BaseException) for it in exceptions) ): return True return False
<SYSTEM_TASK:> Temporarily overrides the old value with the new one. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Execute validation for actions that are related to particular object <END_TASK> <USER_TASK:> Description: 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'): # DRF does not add flag 'detail' to update and delete actions, however they execute operation with # particular object. We need to enable validation for them too. return validators = getattr(self, action_name + '_validators', []) for validator in validators: validator(obj or self.get_object())
<SYSTEM_TASK:> returns dictionary version of row using keys from self.field_map <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Get list of services content types <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Create default price list items for each registered resource. <END_TASK> <USER_TASK:> Description: 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_items[0].name, _('Price items were created: %s.') % ', '.join(item.name for item in created_items), len(created_items) ) self.message_user(request, message) else: self.message_user(request, _('Price items for all registered resources have been updated.')) return redirect(reverse('admin:cost_tracking_defaultpricelistitem_changelist'))
<SYSTEM_TASK:> Re-initialize configuration for resource if it has been changed. <END_TASK> <USER_TASK:> Description: 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. changed_resources = [] for resource_model in CostTrackingRegister.registered_resources: for resource in resource_model.objects.all(): try: pe = models.PriceEstimate.objects.get(scope=resource, month=now.month, year=now.year) except models.PriceEstimate.DoesNotExist: changed_resources.append(resource) else: new_configuration = CostTrackingRegister.get_configuration(resource) if new_configuration != pe.consumption_details.configuration: changed_resources.append(resource) # Step 2. Re-init configuration and recalculate estimate for changed resources. for resource in changed_resources: models.PriceEstimate.update_resource_estimate(resource, CostTrackingRegister.get_configuration(resource)) message = _('Configuration was reinitialized for %(count)s resources') % {'count': len(changed_resources)} self.message_user(request, message) return redirect(reverse('admin:cost_tracking_defaultpricelistitem_changelist'))
<SYSTEM_TASK:> Encrypt the given message <END_TASK> <USER_TASK:> Description: def encrypt(self, message): """ Encrypt the given message """
if not isinstance(message, (bytes, str)): raise TypeError return hashlib.sha1(message.encode('utf-8')).hexdigest()
<SYSTEM_TASK:> Get field that are tracked in object history versions. <END_TASK> <USER_TASK:> Description: 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]
<SYSTEM_TASK:> Define should new version be created for object or no. <END_TASK> <USER_TASK:> Description: 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 to compare object attributes (not serialized data) to avoid version creation on wrong <float> vs <int> comparison; """
if self.id is None: return False try: latest_version = Version.objects.get_for_object(self).latest('revision__date_created') except Version.DoesNotExist: return False latest_version_object = latest_version._object_version.object fields = self.get_version_fields() return all([getattr(self, f) == getattr(latest_version_object, f) for f in fields])
<SYSTEM_TASK:> Get all unique instance ancestors <END_TASK> <USER_TASK:> Description: 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 ancestors_with_parents: for parent in ancestor.get_ancestors(): if (parent.__class__, parent.id) not in ancestor_unique_attributes: ancestors.append(parent) return ancestors
<SYSTEM_TASK:> Check if the connection has succeed <END_TASK> <USER_TASK:> Description: 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_CREATED, HTTP_CODE_EMPTY, HTTP_CODE_MULTIPLE_CHOICES]: return True if status_code in [HTTP_CODE_BAD_REQUEST, HTTP_CODE_UNAUTHORIZED, HTTP_CODE_PERMISSION_DENIED, HTTP_CODE_NOT_FOUND, HTTP_CODE_METHOD_NOT_ALLOWED, HTTP_CODE_CONNECTION_TIMEOUT, HTTP_CODE_CONFLICT, HTTP_CODE_PRECONDITION_FAILED, HTTP_CODE_INTERNAL_SERVER_ERROR, HTTP_CODE_SERVICE_UNAVAILABLE]: return False raise Exception('Unknown status code %s.', status_code)
<SYSTEM_TASK:> Check if the response succeed or not. <END_TASK> <USER_TASK:> Description: 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, False otherwise """
status_code = self._response.status_code data = self._response.data # TODO : Get errors in response data after bug fix : http://mvjira.mv.usa.alcatel.com/browse/VSD-2735 if data and 'errors' in data: self._response.errors = data['errors'] if status_code in [HTTP_CODE_SUCCESS, HTTP_CODE_CREATED, HTTP_CODE_EMPTY]: return True if status_code == HTTP_CODE_MULTIPLE_CHOICES: return False if status_code in [HTTP_CODE_PERMISSION_DENIED, HTTP_CODE_UNAUTHORIZED]: if not should_post: return True return False if status_code in [HTTP_CODE_CONFLICT, HTTP_CODE_NOT_FOUND, HTTP_CODE_BAD_REQUEST, HTTP_CODE_METHOD_NOT_ALLOWED, HTTP_CODE_PRECONDITION_FAILED, HTTP_CODE_SERVICE_UNAVAILABLE]: if not should_post: return True return False if status_code == HTTP_CODE_INTERNAL_SERVER_ERROR: return False if status_code == HTTP_CODE_ZERO: bambou_logger.error("NURESTConnection: Connection error with code 0. Sending NUNURESTConnectionFailureNotification notification and exiting.") return False bambou_logger.error("NURESTConnection: Report this error, because this should not happen: %s" % self._response) return False
<SYSTEM_TASK:> Called when a response is received <END_TASK> <USER_TASK:> Description: 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) level = logging.WARNING if self._response.status_code >= 300 else logging.DEBUG bambou_logger.info('< %s %s %s [%s] ' % (self._request.method, self._request.url, self._request.params if self._request.params else "", self._response.status_code)) bambou_logger.log(level, '< headers: %s' % self._response.headers) bambou_logger.log(level, '< data:\n%s' % json.dumps(self._response.data, indent=4)) self._callback(self) return self
<SYSTEM_TASK:> Called when a resquest has timeout <END_TASK> <USER_TASK:> Description: 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: return self
<SYSTEM_TASK:> Encapsulate requests call <END_TASK> <USER_TASK:> Description: 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-546 response = requests_session.request(method=method, url=url, data=data, headers=headers, verify=verify, timeout=timeout, params=params, cert=certificate) except requests.exceptions.SSLError: try: response = requests_session.request(method=method, url=url, data=data, headers=headers, verify=verify, timeout=timeout, params=params, cert=certificate) except requests.exceptions.Timeout: return self._did_timeout() except requests.exceptions.Timeout: return self._did_timeout() return response
<SYSTEM_TASK:> Make an HTTP request with a specific method <END_TASK> <USER_TASK:> Description: 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_request, kwargs={'session': session}) thread.is_daemon = False thread.start() return self.transaction_id return self._make_request(session=session)
<SYSTEM_TASK:> Reset the connection <END_TASK> <USER_TASK:> Description: def reset(self): """ Reset the connection """
self._request = None self._response = None self._transaction_id = uuid.uuid4().hex
<SYSTEM_TASK:> Take configuration from previous month, it it exists. <END_TASK> <USER_TASK:> Description: 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: pass else: configuration = previous_price_estimate.consumption_details.configuration kwargs['configuration'] = configuration month_start = core_utils.month_start(datetime.date(price_estimate.year, price_estimate.month, 1)) kwargs['last_update_time'] = month_start return super(ConsumptionDetailsQuerySet, self).create(price_estimate=price_estimate, **kwargs)
<SYSTEM_TASK:> When static declaration is used, event type choices are fetched too early - <END_TASK> <USER_TASK:> Description: 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. """
fields = super(BaseHookSerializer, self).get_fields() fields['event_types'] = serializers.MultipleChoiceField( choices=loggers.get_valid_events(), required=False) fields['event_groups'] = serializers.MultipleChoiceField( choices=loggers.get_event_groups_keys(), required=False) return fields
<SYSTEM_TASK:> Use PriceEstimateSerializer to serialize estimate children <END_TASK> <USER_TASK:> Description: 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 = self.__class__ field_kwargs = {'read_only': True, 'many': True, 'context': {'depth': nested_depth - 1}} return field_class, field_kwargs
<SYSTEM_TASK:> Prepares the exception for re-raising with reraise method. <END_TASK> <USER_TASK:> Description: 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: exc_info = sys.exc_info() error._type_ = exc_info[0] error._traceback = exc_info[2] return error
<SYSTEM_TASK:> Re-raises the error that was processed by prepare_for_reraise earlier. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Represents a singular REST name <END_TASK> <USER_TASK:> Description: 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 property first.' % cls) return cls.__rest_name__
<SYSTEM_TASK:> Compute the arguments <END_TASK> <USER_TASK:> Description: 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 in self._attributes.items(): default_value = BambouConfig.get_default_attribute_value(self.__class__, name, remote_attribute.attribute_type) setattr(self, name, default_value) if len(data) > 0: self.from_dict(data) for key, value in kwargs.items(): if hasattr(self, key): setattr(self, key, value)
<SYSTEM_TASK:> Gets the list of all possible children ReST names. <END_TASK> <USER_TASK:> Description: 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", "bar"] """
names = [] for fetcher in self.fetchers: names.append(fetcher.__class__.managed_object_rest_name()) return names
<SYSTEM_TASK:> Validate the current object attributes. <END_TASK> <USER_TASK:> Description: 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. """
self._attribute_errors = dict() # Reset validation errors for local_name, attribute in self._attributes.items(): value = getattr(self, local_name, None) if attribute.is_required and (value is None or value == ""): self._attribute_errors[local_name] = {'title': 'Invalid input', 'description': 'This value is mandatory.', 'remote_name': attribute.remote_name} continue if value is None: continue # without error if not self._validate_type(local_name, attribute.remote_name, value, attribute.attribute_type): continue if attribute.min_length is not None and len(value) < attribute.min_length: self._attribute_errors[local_name] = {'title': 'Invalid length', 'description': 'Attribute %s minimum length should be %s but is %s' % (attribute.remote_name, attribute.min_length, len(value)), 'remote_name': attribute.remote_name} continue if attribute.max_length is not None and len(value) > attribute.max_length: self._attribute_errors[local_name] = {'title': 'Invalid length', 'description': 'Attribute %s maximum length should be %s but is %s' % (attribute.remote_name, attribute.max_length, len(value)), 'remote_name': attribute.remote_name} continue if attribute.attribute_type == list: valid = True for item in value: if valid is True: valid = self._validate_value(local_name, attribute, item) else: self._validate_value(local_name, attribute, value) return self.is_valid()
<SYSTEM_TASK:> Expose local_name as remote_name <END_TASK> <USER_TASK:> Description: 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, subtype=None, min_value=None, max_value=None): """ Expose local_name as remote_name An exposed attribute `local_name` will be sent within the HTTP request as a `remote_name` """
if remote_name is None: remote_name = local_name if display_name is None: display_name = local_name attribute = NURemoteAttribute(local_name=local_name, remote_name=remote_name, attribute_type=attribute_type) attribute.display_name = display_name attribute.is_required = is_required attribute.is_readonly = is_readonly attribute.min_length = min_length attribute.max_length = max_length attribute.is_editable = is_editable attribute.is_identifier = is_identifier attribute.choices = choices attribute.is_unique = is_unique attribute.is_email = is_email attribute.is_login = is_login attribute.is_password = is_password attribute.can_order = can_order attribute.can_search = can_search attribute.subtype = subtype attribute.min_value = min_value attribute.max_value = max_value self._attributes[local_name] = attribute
<SYSTEM_TASK:> Check if the current user owns the object <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Return parent that matches a rest name <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Converts the current object into a Dictionary using all exposed ReST attributes. <END_TASK> <USER_TASK:> Description: 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": "my entity", "description": "Hello World", "ID": "xxxx-xxx-xxxx-xxx", ...} """
dictionary = dict() for local_name, attribute in self._attributes.items(): remote_name = attribute.remote_name if hasattr(self, local_name): value = getattr(self, local_name) # Removed to resolve issue http://mvjira.mv.usa.alcatel.com/browse/VSD-5940 (12/15/2014) # if isinstance(value, bool): # value = int(value) if isinstance(value, NURESTObject): value = value.to_dict() if isinstance(value, list) and len(value) > 0 and isinstance(value[0], NURESTObject): tmp = list() for obj in value: tmp.append(obj.to_dict()) value = tmp dictionary[remote_name] = value else: pass # pragma: no cover return dictionary
<SYSTEM_TASK:> Sets all the exposed ReST attribues from the given dictionary <END_TASK> <USER_TASK:> Description: 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} >>> group = NUGroup() >>> group.from_dict(info) >>> print "name: %s - private: %s" % (group.name, group.private) "name: my group - private: False" """
for remote_name, remote_value in dictionary.items(): # Check if a local attribute is exposed with the remote_name # if no attribute is exposed, return None local_name = next((name for name, attribute in self._attributes.items() if attribute.remote_name == remote_name), None) if local_name: setattr(self, local_name, remote_value) else: # print('Attribute %s could not be added to object %s' % (remote_name, self)) pass
<SYSTEM_TASK:> Delete object and call given callback in case of call. <END_TASK> <USER_TASK:> Description: 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 call. Default is False callback (function): Callback method that will be triggered in case of asynchronous call Example: >>> entity.delete() # will delete the enterprise from the server """
return self._manage_child_object(nurest_object=self, method=HTTP_METHOD_DELETE, async=async, callback=callback, response_choice=response_choice)
<SYSTEM_TASK:> Update object and call given callback in case of async call <END_TASK> <USER_TASK:> Description: 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 case of asynchronous call Example: >>> entity.name = "My Super Object" >>> entity.save() # will save the new name in the server """
return self._manage_child_object(nurest_object=self, method=HTTP_METHOD_PUT, async=async, callback=callback, response_choice=response_choice)
<SYSTEM_TASK:> Sends a request, calls the local callback, then the remote callback in case of async call <END_TASK> <USER_TASK:> Description: 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 will be triggered in case of async call remote_callback: remote moethd that will be triggered in case of async call user_info: contains additionnal information to carry during the request Returns: Returns the object and connection (object, connection) """
callbacks = dict() if local_callback: callbacks['local'] = local_callback if remote_callback: callbacks['remote'] = remote_callback connection = NURESTConnection(request=request, async=async, callback=self._did_receive_response, callbacks=callbacks) connection.user_info = user_info return connection.start()
<SYSTEM_TASK:> Low level child management. Send given HTTP method with given nurest_object to given ressource of current object <END_TASK> <USER_TASK:> Description: 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_object: the NURESTObject object to manage method: the HTTP method to use (GET, POST, PUT, DELETE) callback: the callback to call at the end handler: a custom handler to call when complete, before calling the callback commit: True to auto commit changes in the current object Returns: Returns the object and connection (object, connection) """
url = None if method == HTTP_METHOD_POST: url = self.get_resource_url_for_child_type(nurest_object.__class__) else: url = self.get_resource_url() if response_choice is not None: url += '?responseChoice=%s' % response_choice request = NURESTRequest(method=method, url=url, data=nurest_object.to_dict()) user_info = {'nurest_object': nurest_object, 'commit': commit} if not handler: handler = self._did_perform_standard_operation if async: return self.send_request(request=request, async=async, local_callback=handler, remote_callback=callback, user_info=user_info) else: connection = self.send_request(request=request, user_info=user_info) return handler(connection)
<SYSTEM_TASK:> Receive a response from the connection <END_TASK> <USER_TASK:> Description: 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 if connection.handle_response_for_connection(should_post=should_post) and has_callbacks: callback = connection.callbacks['local'] callback(connection)
<SYSTEM_TASK:> Callback called after fetching the object <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Performs standard opertions <END_TASK> <USER_TASK:> Description: 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_object'], connection) else: callback(self, connection) else: if connection.response.status_code >= 400 and BambouConfig._should_raise_bambou_http_error: raise BambouHTTPError(connection=connection) # Case with multiple objects like assignment if connection.user_info and 'nurest_objects' in connection.user_info: if connection.user_info['commit']: for nurest_object in connection.user_info['nurest_objects']: self.add_child(nurest_object) return (connection.user_info['nurest_objects'], connection) if connection.user_info and 'nurest_object' in connection.user_info: if connection.user_info['commit']: self.add_child(connection.user_info['nurest_object']) return (connection.user_info['nurest_object'], connection) return (self, connection)
<SYSTEM_TASK:> Add given nurest_object to the current object <END_TASK> <USER_TASK:> Description: 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: nurest_object (bambou.NURESTObject): the NURESTObject object to add response_choice (int): Automatically send a response choice when confirmation is needed async (bool): should the request be done asynchronously or not callback (function): callback containing the object and the connection Returns: Returns the object and connection (object, connection) Example: >>> entity = NUEntity(name="Super Entity") >>> parent_entity.create_child(entity) # the new entity as been created in the parent_entity """
# if nurest_object.id: # raise InternalConsitencyError("Cannot create a child that already has an ID: %s." % nurest_object) return self._manage_child_object(nurest_object=nurest_object, async=async, method=HTTP_METHOD_POST, callback=callback, handler=self._did_create_child, response_choice=response_choice, commit=commit)
<SYSTEM_TASK:> Instantiate an nurest_object from a template object <END_TASK> <USER_TASK:> Description: 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 template object callback: callback containing the object and the connection Returns: Returns the object and connection (object, connection) Example: >>> parent_entity = NUParentEntity(id="xxxx-xxxx-xxx-xxxx") # create a NUParentEntity with an existing ID (or retrieve one) >>> other_entity_template = NUOtherEntityTemplate(id="yyyy-yyyy-yyyy-yyyy") # create a NUOtherEntityTemplate with an existing ID (or retrieve one) >>> other_entity_instance = NUOtherEntityInstance(name="my new instance") # create a new NUOtherEntityInstance to be intantiated from other_entity_template >>> >>> parent_entity.instantiate_child(other_entity_instance, other_entity_template) # instatiate the new domain in the server """
# if nurest_object.id: # raise InternalConsitencyError("Cannot instantiate a child that already has an ID: %s." % nurest_object) if not from_template.id: raise InternalConsitencyError("Cannot instantiate a child from a template with no ID: %s." % from_template) nurest_object.template_id = from_template.id return self._manage_child_object(nurest_object=nurest_object, async=async, method=HTTP_METHOD_POST, callback=callback, handler=self._did_create_child, response_choice=response_choice, commit=commit)
<SYSTEM_TASK:> Callback called after adding a new child nurest_object <END_TASK> <USER_TASK:> Description: 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_standard_operation(connection)
<SYSTEM_TASK:> Reference a list of objects into the current resource <END_TASK> <USER_TASK:> Description: 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 callback (function): Callback method that should be fired at the end Returns: Returns the current object and the connection (object, connection) Example: >>> entity.assign([entity1, entity2, entity3], NUEntity) # entity1, entity2 and entity3 are now part of the entity """
ids = list() for nurest_object in objects: ids.append(nurest_object.id) url = self.get_resource_url_for_child_type(nurest_object_type) request = NURESTRequest(method=HTTP_METHOD_PUT, url=url, data=ids) user_info = {'nurest_objects': objects, 'commit': commit} if async: return self.send_request(request=request, async=async, local_callback=self._did_perform_standard_operation, remote_callback=callback, user_info=user_info) else: connection = self.send_request(request=request, user_info=user_info) return self._did_perform_standard_operation(connection)
<SYSTEM_TASK:> Compare with another object <END_TASK> <USER_TASK:> Description: 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) if self.rest_name != rest_object.rest_name: return False if self.id and rest_object.id: return self.id == rest_object.id if self.local_id and rest_object.local_id: return self.local_id == rest_object.local_id return False
<SYSTEM_TASK:> Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR <END_TASK> <USER_TASK:> Description: 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']
<SYSTEM_TASK:> It is expected that valid row for each month contains at least one <END_TASK> <USER_TASK:> Description: 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 deleted. """
estimates = self.get_price_estimates_for_customer(customer) if not estimates: return [] tables = {model: collections.defaultdict(list) for model in self.get_estimated_models()} dates = set() for estimate in estimates: date = (estimate.year, estimate.month) dates.add(date) cls = estimate.content_type.model_class() for model, table in tables.items(): if issubclass(cls, model): table[date].append(estimate) break invalid_estimates = [] for date in dates: if any(map(lambda table: len(table[date]) == 0, tables.values())): for table in tables.values(): invalid_estimates.extend(table[date]) print(invalid_estimates) return invalid_estimates
<SYSTEM_TASK:> Get a default value of the attribute_type <END_TASK> <USER_TASK:> Description: 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 = "A" if self.min_length: if self.attribute_type is str: value = value.ljust(self.min_length, 'a') elif self.attribute_type is int: value = self.min_length elif self.max_length: if self.attribute_type is str: value = value.ljust(self.max_length, 'a') elif self.attribute_type is int: value = self.max_length return value