text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_service_resources(cls, model): """ Get resource models by service model """
key = cls.get_model_key(model) return cls.get_service_name_resources(key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_service_name_resources(cls, service_name): """ Get resource models by service name """
from django.apps import apps resources = cls._registry[service_name]['resources'].keys() return [apps.get_model(resource) for resource in resources]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_active_model(cls, model): """ Check is model app name is in list of INSTALLED_APPS """
# We need to use such tricky way to check because of inconsistent apps names: # some apps are included in format "<module_name>.<app_name>" like "waldur_core.openstack" # other apps are included in format "<app_name>" like "nodecondcutor_sugarcrm" return ('.'.join(model.__module__.split...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_context_data_from_headers(request, headers_schema): """ Extracts context data from request headers according to specified schema. True """
if not headers_schema: return None env = request.parsed_data.xml.xpath( '/soap:Envelope', namespaces=SoapProtocol.namespaces)[0] header = env.xpath( './soap:Header/*', namespaces=SoapProtocol.namespaces) if len(header) < 1: return None return headers_schema.valid...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lazy_constant(fn): """Decorator to make a function that takes no arguments use the LazyConstant class."""
class NewLazyConstant(LazyConstant): @functools.wraps(fn) def __call__(self): return self.get_value() return NewLazyConstant(fn)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lru_cache(maxsize=128, key_fn=None): """Decorator that adds an LRU cache of size maxsize to the decorated function. maxsize is the number of different keys c...
def decorator(fn): cache = LRUCache(maxsize) argspec = inspect2.getfullargspec(fn) arg_names = argspec.args[1:] + argspec.kwonlyargs # remove self kwargs_defaults = get_kwargs_defaults(argspec) cache_key = key_fn if cache_key is None: def cache_key(ar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cached_per_instance(): """Decorator that adds caching to an instance method. The cached value is stored so that it gets garbage collected together with the i...
def cache_fun(fun): argspec = inspect2.getfullargspec(fun) arg_names = argspec.args[1:] + argspec.kwonlyargs # remove self kwargs_defaults = get_kwargs_defaults(argspec) cache = {} def cache_key(args, kwargs): return get_args_tuple(args, kwargs, arg_names, kwa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_args_tuple(args, kwargs, arg_names, kwargs_defaults): """Generates a cache key from the passed in arguments."""
args_list = list(args) args_len = len(args) all_args_len = len(arg_names) try: while args_len < all_args_len: arg_name = arg_names[args_len] if arg_name in kwargs_defaults: args_list.append(kwargs.get(arg_name, kwargs_defaults[arg_name])) else...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_kwargs_defaults(argspec): """Computes a kwargs_defaults dictionary for use by get_args_tuple given an argspec."""
arg_names = tuple(argspec.args) defaults = argspec.defaults or () num_args = len(argspec.args) - len(defaults) kwargs_defaults = {} for i, default_value in enumerate(defaults): kwargs_defaults[arg_names[num_args + i]] = default_value if getattr(argspec, "kwonlydefaults", None): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def memoize(fun): """Memoizes return values of the decorated function. Similar to l0cache, but the cache persists for the duration of the process, unless clear_c...
argspec = inspect2.getfullargspec(fun) arg_names = argspec.args + argspec.kwonlyargs kwargs_defaults = get_kwargs_defaults(argspec) def cache_key(args, kwargs): return get_args_tuple(args, kwargs, arg_names, kwargs_defaults) @functools.wraps(fun) def new_fun(*args, **kwargs): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def memoize_with_ttl(ttl_secs=60 * 60 * 24): """Memoizes return values of the decorated function for a given time-to-live. Similar to l0cache, but the cache pers...
error_msg = ( "Incorrect usage of qcore.caching.memoize_with_ttl: " "ttl_secs must be a positive integer." ) assert_is_instance(ttl_secs, six.integer_types, error_msg) assert_gt(ttl_secs, 0, error_msg) def cache_fun(fun): argspec = inspect2.getfullargspec(fun) arg_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_value(self): """Returns the value of the constant."""
if self.value is not_computed: self.value = self.value_provider() if self.value is not_computed: return None return self.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute(self): """Computes the value. Does not look at the cache."""
self.value = self.value_provider() if self.value is not_computed: return None else: return self.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, key, default=miss): """Return the value for given key if it exists."""
if key not in self._dict: return default # invokes __getitem__, which updates the item return self[key]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self, omit_item_evicted=False): """Empty the cache and optionally invoke item_evicted callback."""
if not omit_item_evicted: items = self._dict.items() for key, value in items: self._evict_item(key, value) self._dict.clear()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_permitted_objects_uuids(cls, user): """ Return query dictionary to search objects available to user. """
uuids = filter_queryset_for_user(cls.objects.all(), user).values_list('uuid', flat=True) key = core_utils.camel_case_to_underscore(cls.__name__) + '_uuid' return {key: uuids}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_buffer(self, buf): """ Identify the contents of `buf` """
with self.lock: try: # if we're on python3, convert buf to bytes # otherwise this string is passed as wchar* # which is not what libmagic expects if isinstance(buf, str) and str != bytes: buf = buf.encode('utf-8', e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self, timeout=None, root_object=None): """ Starts listening to events. Args: timeout (int): number of seconds before timeout. Used for testing purpose...
if self._is_running: return if timeout: self._timeout = timeout self._start_time = int(time()) pushcenter_logger.debug("[NURESTPushCenter] Starting push center on url %s ..." % self.url) self._is_running = True self.__root_object = root_obj...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self): """ Stops listening for events. """
if not self._is_running: return pushcenter_logger.debug("[NURESTPushCenter] Stopping...") self._thread.stop() self._thread.join() self._is_running = False self._current_connection = None self._start_time = None self._timeout = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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=eve...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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: ca...
if callback in self._delegate_methods: return self._delegate_methods.append(callback)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 re...
if callback not in self._delegate_methods: return self._delegate_methods.remove(callback)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 proper...
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_p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def TypeFactory(type_): """ This function creates a standard form type from a simplified form. True True True True True 'HelloWorldDict' 2 True True True True Tr...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 bec...
return (days * DAY) + (hours * HOUR) + (minutes * MINUTE) + (seconds * SECOND)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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, timeo...
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 resu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 arg...
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") a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 Fals...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: return lambda wrapper: wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def DictOf(name, *fields): """ This function creates a dict type with the specified name and fields. True 'HelloWorldDict' 2 """
ret = type(name, (Dict,), {'fields': []}) #noinspection PyUnresolvedReferences ret.add_fields(*fields) return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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_...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 t...
# 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 resour...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 from slots return partial( loader, **{object.lstrip("_"): getattr(self, object) for object in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(regex, view)) return urls + super(ExtraActionsMixin, self).get_urls()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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() ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 CreationConditionFailedQuotaError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_settings(self, link): """ URL of service settings """
return reverse( 'servicesettings-detail', kwargs={'uuid': link.service.settings.uuid}, request=self.context['request'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 to...
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 = { ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 resour...
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) ) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 mor...
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' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.append('state') if resource.state in (resource.States.UPDATING, resource.States.CREATING): resource.set_ok() update_fields.append('state') if resource.error_message: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. if not isinstance(value, (str, bytes)): raise TypeError("header values must ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(alpha2=language.lower()) except KeyError: pass elif len(language) == 3: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ...
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize_instance(instance): """ Serialize Django model instance """
model_name = force_text(instance._meta) return '{}:{}'.format(model_name, instance.pk)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_url(url) match = resolve(url) model = get_model_from_resolve_match(match) queryset = model.o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 r...
base_name = app_config.__module__.split('.')[0] module = __import__(base_name) return getattr(module, '__version__', 'N/A')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 setti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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_...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:...
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'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ob...
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=r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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(conn...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 obje...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 retu...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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.call...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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._ge...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a 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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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, oth...
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_l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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. ...
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,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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...
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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ne...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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),...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 consumpti...
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.PriceE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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:> Solve the following problem using Python, implementing the functions described below, one line at a time <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_d...
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....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <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 ...
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_C...