Instruction:
Create a Python 3 function to
get a dictionary with related structure models for given class or model

Response:
def get_related_models(cls, model):
        """ Get a dictionary with related structure models for given class or model:

            >> SupportedServices.get_related_models(gitlab_models.Project)
            {
                'service': nodeconductor_gitlab.models.GitLabService,
                'service_project_link': nodeconductor_gitlab.models.GitLabServiceProjectLink,
                'resources': [
                    nodeconductor_gitlab.models.Group,
                    nodeconductor_gitlab.models.Project,
                ]
            }
        """
        from waldur_core.structure.models import ServiceSettings

        if isinstance(model, ServiceSettings):
            model_str = cls._registry.get(model.type, {}).get('model_name', '')
        else:
            model_str = cls._get_model_str(model)

        for models in cls.get_service_models().values():
            if model_str == cls._get_model_str(models['service']) or \
               model_str == cls._get_model_str(models['service_project_link']):
                return models

            for resource_model in models['resources']:
                if model_str == cls._get_model_str(resource_model):
                    return models


Instruction:
Implement a function in Python 3 to
check if model app name is in list of INSTALLED_APPS

Response:
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('.')[:2]) in settings.INSTALLED_APPS or
                '.'.join(model.__module__.split('.')[:1]) in settings.INSTALLED_APPS)


Instruction:
Explain what the following Python 3 code does
def process(self, event):

        conf = settings.WALDUR_CORE.get('GOOGLE_API') or {}
        keys = conf.get(dict(self.Type.CHOICES)[self.type])

        if not keys or not self.token:
            return

        endpoint = 'https://gcm-http.googleapis.com/gcm/send'
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'key=%s' % keys['server_key'],
        }
        payload = {
            'to': self.token,
            'notification': {
                'body': event.get('message', 'New event'),
                'title': conf.get('NOTIFICATION_TITLE', 'Waldur notification'),
                'image': 'icon',
            },
            'data': {
                'event': event
            },
        }
        if self.type == self.Type.IOS:
            payload['content-available'] = '1'
        logger.debug('Submitting GCM push notification with headers %s, payload: %s' % (headers, payload))
        requests.post(endpoint, json=payload, headers=headers)

Response: Send events as push notification via Google Cloud Messaging API.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_context_data_from_headers(request, headers_schema):

    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.validate(xml2obj(header[0], headers_schema))

Response: Extracts context data from request headers according to specified schema.


Instruction:
Explain what the following Python 3 code does
def lru_cache(maxsize=128, key_fn=None):

    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(args, kwargs):
                return get_args_tuple(args, kwargs, arg_names, kwargs_defaults)

        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            key = cache_key(args, kwargs)
            try:
                return cache[key]
            except KeyError:
                value = fn(*args, **kwargs)
                cache[key] = value
                return value

        wrapper.clear = cache.clear

        return wrapper

    return decorator

Response: A decorator that adds an LRU cache of size maxsize to a function that returns the value of the specified key.


Instruction:
Make a summary of the following Python 3 code
def cached_per_instance():

    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, kwargs_defaults)

        def clear_cache(instance_key, ref):
            del cache[instance_key]

        @functools.wraps(fun)
        def new_fun(self, *args, **kwargs):
            instance_key = id(self)
            if instance_key not in cache:
                ref = weakref.ref(self, functools.partial(clear_cache, instance_key))
                cache[instance_key] = (ref, {})
            instance_cache = cache[instance_key][1]

            k = cache_key(args, kwargs)
            if k not in instance_cache:
                instance_cache[k] = fun(self, *args, **kwargs)
            return instance_cache[k]

        # just so unit tests can check that this is cleaned up correctly
        new_fun.__cached_per_instance_cache__ = cache
        return new_fun

    return cache_fun

Response: Decorator that adds caching to an instance method.


Instruction:
Write a Python 3 function for
generating a cache key from the passed in arguments.

Response:
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:
                args_list.append(kwargs[arg_name])
            args_len += 1
    except KeyError as e:
        raise TypeError("Missing argument %r" % (e.args[0],))
    return tuple(args_list)


Instruction:
Given the following Python 3 function, write the documentation
def get_kwargs_defaults(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):
        kwargs_defaults.update(argspec.kwonlydefaults)
    return kwargs_defaults

Response: Computes a kwargs_defaults dictionary for use by get_args_tuple given an argspec.


Instruction:
Can you tell what is the following Python 3 function doing
def memoize(fun):
    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):
        k = cache_key(args, kwargs)
        if k not in new_fun.__cache:
            new_fun.__cache[k] = fun(*args, **kwargs)
        return new_fun.__cache[k]

    def clear_cache():
        """Removes all cached values for this function."""
        new_fun.__cache.clear()

    new_fun.__cache = {}
    new_fun.clear_cache = clear_cache
    return new_fun

Response: Memoizes return values of the decorated function.


Instruction:
Make a summary of the following Python 3 code
def memoize_with_ttl(ttl_secs=60 * 60 * 24):

    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_names = argspec.args + argspec.kwonlyargs
        kwargs_defaults = get_kwargs_defaults(argspec)

        def cache_key(args, kwargs):
            return repr(get_args_tuple(args, kwargs, arg_names, kwargs_defaults))

        @functools.wraps(fun)
        def new_fun(*args, **kwargs):
            k = cache_key(args, kwargs)
            current_time = int(time.time())

            # k is not in the cache; perform the function and cache the result.
            if k not in new_fun.__cache or k not in new_fun.__cache_times:
                new_fun.__cache[k] = fun(*args, **kwargs)
                new_fun.__cache_times[k] = current_time
                return new_fun.__cache[k]

            # k is in the cache at this point. Check if the ttl has expired;
            # if so, recompute the value and cache it.
            cache_time = new_fun.__cache_times[k]
            if current_time - cache_time > ttl_secs:
                new_fun.__cache[k] = fun(*args, **kwargs)
                new_fun.__cache_times[k] = current_time

            # finally, return the cached result.
            return new_fun.__cache[k]

        def clear_cache():
            """Removes all cached values for this function."""
            new_fun.__cache.clear()
            new_fun.__cache_times.clear()

        def dirty(*args, **kwargs):
            """Dirties the function for a given set of arguments."""
            k = cache_key(args, kwargs)
            new_fun.__cache.pop(k, None)
            new_fun.__cache_times.pop(k, None)

        new_fun.__cache = {}
        new_fun.__cache_times = {}
        new_fun.clear_cache = clear_cache
        new_fun.dirty = dirty
        return new_fun

    return cache_fun

Response: Memoizes return values of a decorated function for a given time - to - live.


Instruction:
Can you implement a function in Python 3 that
returns the value of the constant.

Response:
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


Instruction:
Can you write a function in Python 3 where it
computes the value. Does not look at the cache.

Response:
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


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get(self, key, default=miss):
        if key not in self._dict:
            return default

        # invokes __getitem__, which updates the item
        return self[key]

Response: Return the value for given key if it exists.


Instruction:
Write a Python 3 function that can
empty the cache and optionally invoke item_evicted callback.

Response:
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()


Instruction:
How would you explain what the following Python 3 function does
def create_task(coro, loop):
    # pragma: no cover
    """Compatibility wrapper for the loop.create_task() call introduced in
    3.4.2."""
    if hasattr(loop, 'create_task'):
        return loop.create_task(coro)
    return asyncio.Task(coro, loop=loop)

Response: Compatibility wrapper for asyncio. create_task


Instruction:
How would you code a function in Python 3 to
return a dictionary of objects that can be used to search objects available to user.

Response:
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}


Instruction:
Can you implement a function in Python 3 that
checks whether user has role in entity.

Response:
def has_user(self, user, role=None, timestamp=False):
        """
        Checks whether user has role in entity.
        `timestamp` can have following values:
            - False - check whether user has role in entity at the moment.
            - None - check whether user has permanent role in entity.
            - Datetime object - check whether user will have role in entity at specific timestamp.
        """
        permissions = self.permissions.filter(user=user, is_active=True)

        if role is not None:
            permissions = permissions.filter(role=role)

        if timestamp is None:
            permissions = permissions.filter(expiration_time=None)
        elif timestamp:
            permissions = permissions.filter(Q(expiration_time=None) | Q(expiration_time__gte=timestamp))

        return permissions.exists()


Instruction:
Can you create a Python 3 function that
identifies the contents of buf and return it.

Response:
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', errors='replace')
                return maybe_decode(magic_buffer(self.cookie, buf))
            except MagicException as e:
                return self._handle509Bug(e)


Instruction:
Given the following Python 3 function, write the documentation
def start(self, timeout=None, root_object=None):

        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_object

        from .nurest_session import NURESTSession
        current_session = NURESTSession.get_current_session()
        args_session = {'session': current_session}

        self._thread = StoppableThread(target=self._listen, name='push-center', kwargs=args_session)
        self._thread.daemon = True
        self._thread.start()

Response: Starts listening to events.


Instruction:
Write a Python 3 function that can
stop listening for events.

Response:
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


Instruction:
Can you generate the documentation for the following Python 3 function
def wait_until_exit(self):

        if self._timeout is None:
            raise Exception("Thread will never exit. Use stop or specify timeout when starting it!")

        self._thread.join()
        self.stop()

Response: Wait until thread exits


Instruction:
Can you write a function in Python 3 where it
calls by the event loop when a new event is received from the connection.

Response:
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)


Instruction:
Here you have a function in Python 3, explain what it does
def _listen(self, uuid=None, session=None):

        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()

Response: Listen a connection uuid


Instruction:
How would you explain what the following Python 3 function does
def add_delegate(self, callback):

        if callback in self._delegate_methods:
            return

        self._delegate_methods.append(callback)

Response: Registers a new delegate callback


Instruction:
Here you have a function in Python 3, explain what it does
def remove_delegate(self, callback):

        if callback not in self._delegate_methods:
            return

        self._delegate_methods.remove(callback)

Response: Unregisters a registered delegate function or a method.


Instruction:
Here you have a function in Python 3, explain what it does
def _read_config(cls):

        cls._config_parser = configparser.ConfigParser()
        cls._config_parser.read(cls._default_attribute_values_configuration_file_path)

Response:
Reads the configuration file if any
        is True.


Instruction:
Given the following Python 3 function, write the documentation
def get_default_attribute_value(cls, object_class, property_name, attr_type=str):

        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)

Response: Gets the default value of a given property for a given object.


Instruction:
How would you code a function in Python 3 to
filter each resource separately using its own filter

Response:
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


Instruction:
How would you explain what the following Python 3 function does
def TypeFactory(type_):
    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_)

Response: This function creates a standard form type from a simplified form.


Instruction:
Explain what the following Python 3 code does
def dummy_image(filetype='gif'):
    # 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')

Response: Generate empty image in temporary file for testing


Instruction:
Can you tell what is the following Python 3 function doing
def utime_delta(days=0, hours=0, minutes=0, seconds=0):
    return (days * DAY) + (hours * HOUR) + (minutes * MINUTE) + (seconds * SECOND)

Response: Gets time delta in microseconds.


Instruction:
Explain what the following Python 3 code does
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)

Response: Executes specified function with timeout.


Instruction:
How would you explain what the following Python 3 function does
def get_original_fn(fn):

    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

Response: Gets the very original function of a decorated one.


Instruction:
Create a Python 3 function to
get full class or function name.

Response:
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_


Instruction:
Make a summary of the following Python 3 code
def get_function_call_str(fn, args, kwargs):

    def str_converter(v):
        try:
            return str(v)
        except Exception:
            try:
                return repr(v)
            except Exception:
                return "<n/a str raised>"

    result = get_full_name(fn) + "("
    first = True
    for v in args:
        if first:
            first = False
        else:
            result += ","
        result += str_converter(v)
    for k, v in kwargs.items():
        if first:
            first = False
        else:
            result += ","
        result += str(k) + "=" + str_converter(v)
    result += ")"
    return result

Response: Converts a function call to a str(... - like string.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_function_call_repr(fn, args, kwargs):

    result = get_full_name(fn) + "("
    first = True
    for v in args:
        if first:
            first = False
        else:
            result += ","
        result += repr(v)
    for k, v in kwargs.items():
        if first:
            first = False
        else:
            result += ","
        result += str(k) + "=" + repr(v)
    result += ")"
    return result

Response: Converts a function call to a repr(... - like string.


Instruction:
Can you generate the documentation for the following Python 3 function
def getargspec(func):
    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__)

Response:
Variation of inspect. getargspec that works for more functions but
    is not accepted by getargspec.


Instruction:
Make a summary of the following Python 3 code
def is_cython_or_generator(fn):
    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"
    )

Response: Returns whether this function is either a Cythonized function or a Cythonized function.


Instruction:
Write a Python 3 script for
checking if a function is compiled w / Cython.

Response:
def is_cython_function(fn):
    """Checks if a function is compiled w/Cython."""
    if hasattr(fn, "__func__"):
        fn = fn.__func__  # Class method, static method
    name = type(fn).__name__
    return (
        name == "method_descriptor"
        or name == "cython_function_or_method"
        or name == "builtin_function_or_method"
    )


Instruction:
Given the following Python 3 function, write the documentation
def is_classmethod(fn):
    # 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)

Response: Returns whether f is a classmethod.


Instruction:
Explain what the following Python 3 code does
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

Response: Cython - compatible functools. wraps implementation.


Instruction:
Explain what the following Python 3 code does
def get_subclass_tree(cls, ensure_unique=True):
    subclasses = []
    # cls.__subclasses__() fails on classes inheriting from type
    for subcls in type.__subclasses__(cls):
        subclasses.append(subcls)
        subclasses.extend(get_subclass_tree(subcls, ensure_unique))
    return list(set(subclasses)) if ensure_unique else subclasses

Response: Returns all subclasses of cls recursively.


Instruction:
Can you generate the documentation for the following Python 3 function
def DictOf(name, *fields):
    ret = type(name, (Dict,), {'fields': []})
    #noinspection PyUnresolvedReferences
    ret.add_fields(*fields)
    return ret

Response: Returns a new Dict type with the specified name and fields.


Instruction:
Given the following Python 3 function, write the documentation
def ListOf(element_type, element_none_value=None):
    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})

Response: This function creates a list type with element type element_type and an optional element value element_none_value.


Instruction:
Here you have a function in Python 3, explain what it does
def get_actions(self, request, view):
        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

Response: Return metadata for resource - specific actions


Instruction:
How would you explain what the following Python 3 function does
def get_action_fields(self, view, action_name, resource):
        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

Response: Get fields exposed by action s serializer


Instruction:
Write a Python 3 function for
giving an instance of a serializer return a dictionary of metadata about its fields.

Response:
def get_serializer_info(self, serializer):
        """
        Given an instance of a serializer, return a dictionary of metadata
        about its fields.
        """
        if hasattr(serializer, 'child'):
            # If this is a `ListSerializer` then we want to examine the
            # underlying child serializer instance instead.
            serializer = serializer.child
        return self.get_fields(serializer.fields)


Instruction:
Create a Python 3 function for
getting fields metadata skipping empty fields

Response:
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


Instruction:
Write a Python 3 function that can
return a dictionary of metadata about the given instance of a serializer field.

Response:
def get_field_info(self, field, field_name):
        """
        Given an instance of a serializer field, return a dictionary
        of metadata about it.
        """
        field_info = OrderedDict()
        field_info['type'] = self.label_lookup[field]
        field_info['required'] = getattr(field, 'required', False)

        attrs = [
            'label', 'help_text', 'default_value', 'placeholder', 'required',
            'min_length', 'max_length', 'min_value', 'max_value', 'many'
        ]

        if getattr(field, 'read_only', False):
            return None

        for attr in attrs:
            value = getattr(field, attr, None)
            if value is not None and value != '':
                field_info[attr] = force_text(value, strings_only=True)

        if 'label' not in field_info:
            field_info['label'] = field_name.replace('_', ' ').title()

        if hasattr(field, 'view_name'):
            list_view = field.view_name.replace('-detail', '-list')
            base_url = reverse(list_view, request=self.request)
            field_info['type'] = 'select'
            field_info['url'] = base_url
            if hasattr(field, 'query_params'):
                field_info['url'] += '?%s' % urlencode(field.query_params)
            field_info['value_field'] = getattr(field, 'value_field', 'url')
            field_info['display_name_field'] = getattr(field, 'display_name_field', 'display_name')

        if hasattr(field, 'choices') and not hasattr(field, 'queryset'):
            field_info['choices'] = [
                {
                    'value': choice_value,
                    'display_name': force_text(choice_name, strings_only=True)
                }
                for choice_value, choice_name in field.choices.items()
            ]

        return field_info


Instruction:
Given the following Python 3 function, write the documentation
def connect(
        database: str,
        loop: asyncio.BaseEventLoop = None,
        executor: concurrent.futures.Executor = None,
        timeout: int = 5,
        echo: bool = False,
        isolation_level: str = '',
        check_same_thread: bool = False,
        **kwargs: dict
):
    """
    把async方法执行后的对象创建为async上下文模式
    """
    coro = _connect(
        database,
        loop=loop,
        executor=executor,
        timeout=timeout,
        echo=echo,
        isolation_level=isolation_level,
        check_same_thread=check_same_thread,
        **kwargs
    )
    return _ContextManager(coro)

Response: Connect to a database and return a new context manager.


Instruction:
Can you tell what is the following Python 3 function doing
def recalculate_estimate(recalculate_total=False):
    # 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)

Response: Recalculate consumed price of consumables that were used by resource until now.


Instruction:
Can you implement a function in Python 3 that
needs to return the string source for the module.

Response:
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)


Instruction:
How would you implement a function in Python 3 that
creates a lazy loader source file loader.

Response:
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 self.__slots__}
        )


Instruction:
Explain what the following Python 3 code does
def load(cls, filename, dir=None, main=False, **kwargs):
        name = main and "__main__" or Path(filename).stem
        loader = cls(name, str(filename), **kwargs)
        module = module_from_spec(FileModuleSpec(name, loader, origin=loader.path))
        cwd = str(Path(loader.path).parent)
        try:
            with ExitStack() as stack:
                sys.path.append(cwd)
                loader.name != "__main__" and stack.enter_context(_installed_safely(module))
                loader.exec_module(module)
        finally:
            sys.path.pop()

        return module

Response: Import a notebook as a module from a filename.


Instruction:
Can you implement a function in Python 3 that
converts the current source to ast

Response:
def source_to_code(self, nodes, path, *, _optimize=-1):
        """* Convert the current source to ast
        * Apply ast transformers.
        * Compile the code."""
        if not isinstance(nodes, ast.Module):
            nodes = ast.parse(nodes, self.path)
        if self._markdown_docstring:
            nodes = update_docstring(nodes)
        return super().source_to_code(
            ast.fix_missing_locations(self.visit(nodes)), path, _optimize=_optimize
        )


Instruction:
Given the following Python 3 function, write the documentation
def get_urls(self):
        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()

Response: Inject extra action URLs.


Instruction:
Can you write a function in Python 3 where it
injects extra links into template context.

Response:
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,
        )


Instruction:
How would you explain what the following Python 3 function does
def start(self):

        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

Response:
Starts the session.

            Starting the session will actually get the API key of the current user


Instruction:
Implement a Python 3 function for
initializing new instances quotas

Response:
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


Instruction:
How would you code a function in Python 3 to
create handler that will recalculate count_quota on creation or deletion.

Response:
def count_quota_handler_factory(count_quota_field):
    """ Creates handler that will recalculate count_quota on creation/deletion """

    def recalculate_count_quota(sender, instance, **kwargs):
        signal = kwargs['signal']
        if signal == signals.post_save and kwargs.get('created'):
            count_quota_field.add_usage(instance, delta=1)
        elif signal == signals.post_delete:
            count_quota_field.add_usage(instance, delta=-1, fail_silently=True)

    return recalculate_count_quota


Instruction:
Write a Python 3 script to
call aggregated quotas fields update methods

Response:
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)


Instruction:
Explain what the following Python 3 code does
def get_settings(self, link):
        return reverse(
            'servicesettings-detail', kwargs={'uuid': link.service.settings.uuid}, request=self.context['request'])

Response: Get the URL of the service settings


Instruction:
Explain what the following Python 3 code does
def get_url(self, link):
        view_name = SupportedServices.get_detail_view_for_model(link.service)
        return reverse(view_name, kwargs={'uuid': link.service.uuid.hex}, request=self.context['request'])

Response: Get the URL of the service with the given link.


Instruction:
How would you explain what the following Python 3 function does
def get_resources_count(self, 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

Response: Count the number of all resources connected to link