Instruction:
How would you implement a function in Python 3 that
gets a list of all police force objects. Uses the forces_ API call.

Response:
def get_forces(self):
        """
        Get a list of all police forces. Uses the forces_ API call.

        .. _forces: https://data.police.uk/docs/method/forces/

        :rtype: list
        :return: A list of :class:`forces.Force` objects (one for each police
                 force represented in the API)
        """

        forces = []
        for f in self.service.request('GET', 'forces'):
            forces.append(Force(self, id=f['id'], name=f['name']))
        return forces


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

        if not isinstance(force, Force):
            force = Force(self, id=force)

        neighbourhoods = []
        for n in self.service.request('GET', '%s/neighbourhoods' % force.id):
            neighbourhoods.append(
                Neighbourhood(self, force=force, id=n['id'], name=n['name']))
        return sorted(neighbourhoods, key=lambda n: n.name)

Response:
Get a list of all neighbourhoods for a given force. Uses the neighbourhoods_
        API call.


Instruction:
Explain what the following Python 3 code does
def get_neighbourhood(self, force, id, **attrs):

        if not isinstance(force, Force):
            force = Force(self, id=force, **attrs)

        return Neighbourhood(self, force=force, id=id, **attrs)

Response: Get a specific neighbourhood. Uses the neighbourhood_ API call.


Instruction:
Write a Python 3 function for
finding a neighbourhood by location. Uses the locate - neighbourhood_ API call.

Response:
def locate_neighbourhood(self, lat, lng):
        """
        Find a neighbourhood by location. Uses the locate-neighbourhood_ API
        call.

        .. _locate-neighbourhood:
            https://data.police.uk/docs/method/neighbourhood-locate/

        :param lat: The latitude of the location.
        :type lat: float or str
        :param lng: The longitude of the location.
        :type lng: float or str
        :rtype: Neighbourhood or None
        :return: The Neighbourhood object representing the Neighbourhood
                 Policing Team responsible for the given location.
         """

        method = 'locate-neighbourhood'
        q = '%s,%s' % (lat, lng)
        try:
            result = self.service.request('GET', method, q=q)
            return self.get_neighbourhood(result['force'],
                                          result['neighbourhood'])
        except APIError:
            pass


Instruction:
Implement a Python 3 function for
getting a list of crime categories valid for a particular date. Uses the clf API call.

Response:
def get_crime_categories(self, date=None):
        """
        Get a list of crime categories, valid for a particular date. Uses the
        crime-categories_ API call.

        .. _crime-categories:
            https://data.police.uk/docs/method/crime-categories/

        :rtype: list
        :param date: The date of the crime categories to get.
        :type date: str or None
        :return: A ``list`` of crime categories which are valid at the
                 specified date (or at the latest date, if ``None``).
        """

        return sorted(self._get_crime_categories(date=date).values(),
                      key=lambda c: c.name)


Instruction:
Can you implement a function in Python 3 that
gets a particular crime category by ID valid at a particular date. Uses the _get_crime_categories_ API call.

Response:
def get_crime_category(self, id, date=None):
        """
        Get a particular crime category by ID, valid at a particular date. Uses
        the crime-categories_ API call.

        :rtype: CrimeCategory
        :param str id: The ID of the crime category to get.
        :param date: The date that the given crime category is valid for (the
                     latest date is used if ``None``).
        :type date: str or None
        :return: A crime category with the given ID which is valid for the
                 specified date (or at the latest date, if ``None``).
        """

        try:
            return self._get_crime_categories(date=date)[id]
        except KeyError:
            raise InvalidCategoryException(
                'Category %s not found for %s' % (id, date))


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

        method = 'outcomes-for-crime/%s' % persistent_id
        response = self.service.request('GET', method)
        crime = Crime(self, data=response['crime'])
        crime._outcomes = []
        outcomes = response['outcomes']
        if outcomes is not None:
            for o in outcomes:
                o.update({
                    'crime': crime,
                })
                crime._outcomes.append(crime.Outcome(self, o))
        return crime

Response: Get a particular crime by persistent ID. Uses the outcomes - for - crime_COOKIE API call.


Instruction:
Implement a Python 3 function for
getting crimes within a 1 - mile radius of a location.

Response:
def get_crimes_point(self, lat, lng, date=None, category=None):
        """
        Get crimes within a 1-mile radius of a location. Uses the crime-street_
        API call.

        .. _crime-street: https//data.police.uk/docs/method/crime-street/

        :rtype: list
        :param lat: The latitude of the location.
        :type lat: float or str
        :param lng: The longitude of the location.
        :type lng: float or str
        :param date: The month in which the crimes were reported in the format
                    ``YYYY-MM`` (the latest date is used if ``None``).
        :type date: str or None
        :param category: The category of the crimes to filter by (either by ID
                         or CrimeCategory object)
        :type category: str or CrimeCategory
        :return: A ``list`` of crimes which were reported within 1 mile of the
                 specified location, in the given month (optionally filtered by
                 category).
        """

        if isinstance(category, CrimeCategory):
            category = category.id
        method = 'crimes-street/%s' % (category or 'all-crime')
        kwargs = {
            'lat': lat,
            'lng': lng,
        }
        crimes = []
        if date is not None:
            kwargs['date'] = date
        for c in self.service.request('GET', method, **kwargs):
            crimes.append(Crime(self, data=c))
        return crimes


Instruction:
Can you generate the documentation for the following Python 3 function
def get_crimes_area(self, points, date=None, category=None):

        if isinstance(category, CrimeCategory):
            category = category.id
        method = 'crimes-street/%s' % (category or 'all-crime')
        kwargs = {
            'poly': encode_polygon(points),
        }
        crimes = []
        if date is not None:
            kwargs['date'] = date
        for c in self.service.request('POST', method, **kwargs):
            crimes.append(Crime(self, data=c))
        return crimes

Response: Get crimes within a custom area.


Instruction:
Make a summary of the following Python 3 code
def get_crimes_location(self, location_id, date=None):

        kwargs = {
            'location_id': location_id,
        }
        crimes = []
        if date is not None:
            kwargs['date'] = date
        for c in self.service.request('GET', 'crimes-at-location', **kwargs):
            crimes.append(Crime(self, data=c))
        return crimes

Response: Get crimes at a particular location. Uses the crimes - at - location_ API call.


Instruction:
Given the following Python 3 function, write the documentation
def get_crimes_no_location(self, force, date=None, category=None):

        if not isinstance(force, Force):
            force = Force(self, id=force)

        if isinstance(category, CrimeCategory):
            category = category.id

        kwargs = {
            'force': force.id,
            'category': category or 'all-crime',
        }
        crimes = []
        if date is not None:
            kwargs['date'] = date
        for c in self.service.request('GET', 'crimes-no-location', **kwargs):
            crimes.append(NoLocationCrime(self, data=c))
        return crimes

Response: Get crimes with no location for a given force.


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

        scoreTagToString = ""
        if scoreTag == "P+":
            scoreTagToString = 'strong positive'
        elif scoreTag == "P":
            scoreTagToString = 'positive'
        elif scoreTag == "NEU":
            scoreTagToString = 'neutral'
        elif scoreTag == "N":
            scoreTagToString = 'negative'
        elif scoreTag == "N+":
            scoreTagToString = 'strong negative'
        elif scoreTag == "NONE":
            scoreTagToString = 'no sentiment'

        return scoreTagToString

Response: returns a string representation of the scoreTag


Instruction:
Explain what the following Python 3 code does
def _retrocom(rx, tx, game, kwargs):
    env = RetroWrapper.retro_make_func(game, **kwargs)

    # Sit around on the queue, waiting for calls from RetroWrapper
    while True:
        attr, args, kwargs = rx.get()

        # First, handle special case where the wrapper is asking if attr is callable.
        # In this case, we actually have RetroWrapper.symbol, attr, and {}.
        if attr == RetroWrapper.symbol:
            result = env.__getattribute__(args)
            tx.put(callable(result))
        elif attr == "close":
            env.close()
            break
        else:
            # Otherwise, handle the request
            result = getattr(env, attr)
            if callable(result):
                result = result(*args, **kwargs)
            tx.put(result)

Response:
This function is the target for RetroWrapper s internal
    process. It is the target for RetroWrapper s internal
    process. It is the target for RetroWrapper s internal
    process. It is the target for RetroWrapper s internal
    process. It is the target for RetroWrapper s internal
    process.


Instruction:
Write a Python 3 script for
checking if the attribute is callable.

Response:
def _ask_if_attr_is_callable(self, attr):
        """
        Returns whether or not the attribute is a callable.
        """
        self._tx.put((RetroWrapper.symbol, attr, {}))
        return self._rx.get()


Instruction:
Write a Python 3 script to
add a parameter to the request

Response:
def addParam(self, paramName, paramValue):
        """
        Add a parameter to the request

        :param paramName:
            Name of the parameter
        :param paramValue:
            Value of the parameter
        """

        if not paramName:
            raise ValueError('paramName cannot be empty')
        self._params[paramName] = paramValue


Instruction:
Here you have a function in Python 3, explain what it does
def setContent(self, type_, value):

        if type_ in [self.CONTENT_TYPE_TXT, self.CONTENT_TYPE_URL,
                     self.CONTENT_TYPE_FILE]:
            if type_ == self.CONTENT_TYPE_FILE:
                self._file = {}
                self._file = {'doc': open(value, 'rb')}
            else:
                self.addParam(type_, value)

Response: Sets the content that s going to be sent to analyze according to its type_ and value.


Instruction:
Explain what the following Python 3 code does
def sendRequest(self, extraHeaders=""):

        self.addParam('src', 'mc-python')

        params = urlencode(self._params)

        url = self._url

        if 'doc' in self._file.keys():
            headers = {}

            if (extraHeaders is not None) and (extraHeaders is dict):
                headers = headers.update(extraHeaders)

            result = requests.post(url=url, data=self._params, files=self._file, headers=headers)
            result.encoding = 'utf-8'
            return result
        else:
            headers = {'Content-Type': 'application/x-www-form-urlencoded'}
            if (extraHeaders is not None) and (extraHeaders is dict):
                headers = headers.update(extraHeaders)
            result = requests.request("POST", url=url, data=params, headers=headers)
            result.encoding = 'utf-8'
            return result

Response: Sends a request to the URL specified and returns a response only if the HTTP code returned is OK


Instruction:
Can you implement a function in Python 3 that
returns the last node of the type specified by type_.

Response:
def getTypeLastNode(self, type_):
        """
        Obtains the last node or leaf of the type specified

        :param type_:
            Type we want to analize (sementity, semtheme)
        :return:
            Last node of the type
        """

        lastNode = ""
        if type_ and (type(type_) is not list) and (type(type_) is not dict):
            aType = type_.split('>')
            lastNode = aType[len(aType) - 1]
        return lastNode


Instruction:
Create a Python 3 function for
calling by the event loop when a new connection is made.

Response:
def __conn_listener(self, state):
        """
        Connection event listener

        :param state: The new connection state
        """
        if state == KazooState.CONNECTED:
            self.__online = True
            if not self.__connected:
                self.__connected = True
                self._logger.info("Connected to ZooKeeper")
                self._queue.enqueue(self.on_first_connection)
            else:
                self._logger.warning("Re-connected to ZooKeeper")
                self._queue.enqueue(self.on_client_reconnection)
        elif state == KazooState.SUSPENDED:
            self._logger.warning("Connection suspended")
            self.__online = False
        elif state == KazooState.LOST:
            self.__online = False
            self.__connected = False

            if self.__stop:
                self._logger.info("Disconnected from ZooKeeper (requested)")
            else:
                self._logger.warning("Connection lost")


Instruction:
Make a summary of the following Python 3 code
def __path(self, path):
        if path.startswith(self.__prefix):
            return path

        return "{}{}".format(self.__prefix, path)

Response: Adds the prefix to the given path


Instruction:
How would you code a function in Python 3 to
create a ZooKeeper node with the given data

Response:
def create(self, path, data, ephemeral=False, sequence=False):
        """
        Creates a ZooKeeper node

        :param path: Z-Path
        :param data: Node Content
        :param ephemeral: Ephemeral flag
        :param sequence: Sequential flag
        """
        return self._zk.create(
            self.__path(path), data, ephemeral=ephemeral, sequence=sequence
        )


Instruction:
Write a Python 3 script for
getting the content of a ZooKeeper node

Response:
def get(self, path, watch=None):
        """
        Gets the content of a ZooKeeper node

        :param path: Z-Path
        :param watch: Watch method
        """
        return self._zk.get(self.__path(path), watch=watch)


Instruction:
Write a Python 3 script for
getting the list of children of a node

Response:
def get_children(self, path, watch=None):
        """
        Gets the list of children of a node

        :param path: Z-Path
        :param watch: Watch method
        """
        return self._zk.get_children(self.__path(path), watch=watch)


Instruction:
Make a summary of the following Python 3 code
def set(self, path, data):
        return self._zk.set(self.__path(path), data)

Response: Sets the content of a ZooKeeper node


Instruction:
Implement a function in Python 3 to
retrieve a tuple containing the service reference to the iPOPO service and the service itself

Response:
def get_ipopo_svc_ref(bundle_context):
    # type: (BundleContext) -> Optional[Tuple[ServiceReference, Any]]
    """
    Retrieves a tuple containing the service reference to iPOPO and the service
    itself

    :param bundle_context: The calling bundle context
    :return: The reference to the iPOPO service and the service itself,
             None if not available
    """
    # Look after the service
    ref = bundle_context.get_service_reference(SERVICE_IPOPO)
    if ref is None:
        return None

    try:
        # Get it
        svc = bundle_context.get_service(ref)
    except BundleException:
        # Service reference has been invalidated
        return None

    # Return both the reference (to call unget_service()) and the service
    return ref, svc


Instruction:
Can you generate a brief explanation for the following Python 3 code
def use_waiting_list(bundle_context):
    # type: (BundleContext) -> Any
    """
    Utility context to use the iPOPO waiting list safely in a "with" block.
    It looks after the the iPOPO waiting list service and releases its
    reference when exiting the context.

    :param bundle_context: The calling bundle context
    :return: The iPOPO waiting list service
    :raise BundleException: Service not found
    """
    # Get the service and its reference
    ref = bundle_context.get_service_reference(SERVICE_IPOPO_WAITING_LIST)
    if ref is None:
        raise BundleException("No iPOPO waiting list service available")

    try:
        # Give the service
        yield bundle_context.get_service(ref)
    finally:
        try:
            # Release it
            bundle_context.unget_service(ref)
        except BundleException:
            # Service might have already been unregistered
            pass

Response: Utility context to use the iPOPO waiting list safely in a with block.


Instruction:
Write a Python 3 script to
compute the content of the __jsonclass__ field for the given object

Response:
def _compute_jsonclass(obj):
    """
    Compute the content of the __jsonclass__ field for the given object

    :param obj: An object
    :return: The content of the __jsonclass__ field
    """
    # It's not a standard type, so it needs __jsonclass__
    module_name = inspect.getmodule(obj).__name__
    json_class = obj.__class__.__name__
    if module_name not in ("", "__main__"):
        json_class = "{0}.{1}".format(module_name, json_class)

    return [json_class, []]


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _is_builtin(obj):
    module_ = inspect.getmodule(obj)
    if module_ in (None, builtins):
        return True

    return module_.__name__ in ("", "__main__")

Response: Checks if the object is a built - in one or not


Instruction:
Write a Python 3 script to
check if the given Java class is one we might have set up

Response:
def _is_converted_class(java_class):
    """
    Checks if the given Java class is one we *might* have set up
    """
    if not java_class:
        return False

    return (
        JAVA_MAPS_PATTERN.match(java_class) is not None
        or JAVA_LISTS_PATTERN.match(java_class) is not None
        or JAVA_SETS_PATTERN.match(java_class) is not None
    )


Instruction:
Here you have a function in Python 3, explain what it does
def to_jabsorb(value):
    # None ?
    if value is None:
        return None

    # Map ?
    elif isinstance(value, dict):
        if JAVA_CLASS in value or JSON_CLASS in value:
            if not _is_converted_class(value.get(JAVA_CLASS)):
                # Bean representation
                converted_result = {}

                for key, content in value.items():
                    converted_result[key] = to_jabsorb(content)

                try:
                    # Keep the raw jsonrpclib information
                    converted_result[JSON_CLASS] = value[JSON_CLASS]
                except KeyError:
                    pass

            else:
                # We already worked on this value
                converted_result = value

        else:
            # Needs the whole transformation
            converted_result = {JAVA_CLASS: "java.util.HashMap"}
            converted_result["map"] = map_pairs = {}
            for key, content in value.items():
                map_pairs[key] = to_jabsorb(content)

            try:
                # Keep the raw jsonrpclib information
                map_pairs[JSON_CLASS] = value[JSON_CLASS]
            except KeyError:
                pass

    # List ? (consider tuples as an array)
    elif isinstance(value, list):
        converted_result = {
            JAVA_CLASS: "java.util.ArrayList",
            "list": [to_jabsorb(entry) for entry in value],
        }

    # Set ?
    elif isinstance(value, (set, frozenset)):
        converted_result = {
            JAVA_CLASS: "java.util.HashSet",
            "set": [to_jabsorb(entry) for entry in value],
        }

    # Tuple ? (used as array, except if it is empty)
    elif isinstance(value, tuple):
        converted_result = [to_jabsorb(entry) for entry in value]

    elif hasattr(value, JAVA_CLASS):
        # Class with a Java class hint: convert into a dictionary
        class_members = {
            name: getattr(value, name)
            for name in dir(value)
            if not name.startswith("_")
        }

        converted_result = HashableDict(
            (name, to_jabsorb(content))
            for name, content in class_members.items()
            if not inspect.ismethod(content)
        )

        # Do not forget the Java class
        converted_result[JAVA_CLASS] = getattr(value, JAVA_CLASS)

        # Also add a __jsonclass__ entry
        converted_result[JSON_CLASS] = _compute_jsonclass(value)

    # Other ?
    else:
        converted_result = value

    return converted_result

Response: Converts a Python object to a Jabsorb map format.


Instruction:
Can you tell what is the following Python 3 function doing
def from_jabsorb(request, seems_raw=False):
    if isinstance(request, (tuple, set, frozenset)):
        # Special case : JSON arrays (Python lists)
        return type(request)(from_jabsorb(element) for element in request)

    elif isinstance(request, list):
        # Check if we were a list or a tuple
        if seems_raw:
            return list(from_jabsorb(element) for element in request)

        return tuple(from_jabsorb(element) for element in request)

    elif isinstance(request, dict):
        # Dictionary
        java_class = request.get(JAVA_CLASS)
        json_class = request.get(JSON_CLASS)
        seems_raw = not java_class and not json_class

        if java_class:
            # Java Map ?
            if JAVA_MAPS_PATTERN.match(java_class) is not None:
                return HashableDict(
                    (from_jabsorb(key), from_jabsorb(value))
                    for key, value in request["map"].items()
                )

            # Java List ?
            elif JAVA_LISTS_PATTERN.match(java_class) is not None:
                return HashableList(
                    from_jabsorb(element) for element in request["list"]
                )

            # Java Set ?
            elif JAVA_SETS_PATTERN.match(java_class) is not None:
                return HashableSet(
                    from_jabsorb(element) for element in request["set"]
                )

        # Any other case
        result = AttributeMap(
            (from_jabsorb(key), from_jabsorb(value, seems_raw))
            for key, value in request.items()
        )

        # Keep JSON class information as is
        if json_class:
            result[JSON_CLASS] = json_class

        return result

    elif not _is_builtin(request):
        # Bean
        for attr in dir(request):
            # Only convert public fields
            if not attr[0] == "_":
                # Field conversion
                setattr(request, attr, from_jabsorb(getattr(request, attr)))

        return request

    else:
        # Any other case
        return request

Response: Converts a Jabsorb request into a more Python data model.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def copy(self):
        # type: () -> Requirement
        """
        Returns a copy of this instance

        :return: A copy of this instance
        """
        return Requirement(
            self.specification,
            self.aggregate,
            self.optional,
            self.__original_filter,
            self.immediate_rebind,
        )

Response: Returns a copy of this instance of Requirement


Instruction:
Can you implement a function in Python 3 that
sets the filter for the given oneCOOKIE.

Response:
def set_filter(self, props_filter):
        """
        Changes the current filter for the given one

        :param props_filter: The new requirement filter on service properties
        :raise TypeError: Unknown filter type
        """
        if props_filter is not None and not (
            is_string(props_filter)
            or isinstance(
                props_filter, (ldapfilter.LDAPFilter, ldapfilter.LDAPCriteria)
            )
        ):
            # Unknown type
            raise TypeError(
                "Invalid filter type {0}".format(type(props_filter).__name__)
            )

        if props_filter is not None:
            # Filter given, keep its string form
            self.__original_filter = str(props_filter)
        else:
            # No filter
            self.__original_filter = None

        # Parse the filter
        self.filter = ldapfilter.get_ldap_filter(props_filter)

        # Prepare the full filter
        spec_filter = "({0}={1})".format(OBJECTCLASS, self.specification)
        self.__full_filter = ldapfilter.combine_filters(
            (spec_filter, self.filter)
        )


Instruction:
Write a Python 3 script for
returning a deep copy of the current FactoryContext instance

Response:
def copy(self, inheritance=False):
        # type: (bool) -> FactoryContext
        """
        Returns a deep copy of the current FactoryContext instance

        :param inheritance: If True, current handlers configurations are stored
                            as inherited ones
        """
        # Create a new factory context and duplicate its values
        new_context = FactoryContext()
        for field in self.__slots__:
            if not field.startswith("_"):
                setattr(
                    new_context, field, self._deepcopy(getattr(self, field))
                )

        if inheritance:
            # Store configuration as inherited one
            new_context.__inherited_configuration = self.__handlers.copy()
            new_context.__handlers = {}

        # Remove instances in any case
        new_context.__instances.clear()
        new_context.is_singleton_active = False
        return new_context


Instruction:
Can you create a Python 3 function that
merges the inherited configuration with the current ones.

Response:
def inherit_handlers(self, excluded_handlers):
        # type: (Iterable[str]) -> None
        """
        Merges the inherited configuration with the current ones

        :param excluded_handlers: Excluded handlers
        """
        if not excluded_handlers:
            excluded_handlers = tuple()

        for handler, configuration in self.__inherited_configuration.items():
            if handler in excluded_handlers:
                # Excluded handler
                continue

            elif handler not in self.__handlers:
                # Fully inherited configuration
                self.__handlers[handler] = configuration

            # Merge configuration...
            elif isinstance(configuration, dict):
                # Dictionary
                self.__handlers.setdefault(handler, {}).update(configuration)

            elif isinstance(configuration, list):
                # List
                handler_conf = self.__handlers.setdefault(handler, [])
                for item in configuration:
                    if item not in handler_conf:
                        handler_conf.append(item)

        # Clear the inherited configuration dictionary
        self.__inherited_configuration.clear()


Instruction:
Here you have a function in Python 3, explain what it does
def add_instance(self, name, properties):
        # type: (str, dict) -> None
        """
        Stores the description of a component instance. The given properties
        are stored as is.

        :param name: Instance name
        :param properties: Instance properties
        :raise NameError: Already known instance name
        """
        if name in self.__instances:
            raise NameError(name)

        # Store properties "as-is"
        self.__instances[name] = properties

Response: Stores the description of a component instance. The given properties are stored as is.


Instruction:
Create a Python 3 function for
returning the registered method for the given event. Returns None if the event is not registered for the given event.

Response:
def get_field_callback(self, field, event):
        # type: (str, str) -> Optional[Tuple[Callable, bool]]
        """
        Retrieves the registered method for the given event. Returns None if
        not found

        :param field: Name of the dependency field
        :param event: A component life cycle event
        :return: A 2-tuple containing the callback associated to the given
                 event and flag indicating if the callback must be called in
                 valid state only
        """
        try:
            return self.factory_context.field_callbacks[field][event]
        except KeyError:
            return None


Instruction:
Can you generate a brief explanation for the following Python 3 code
def grab_hidden_properties(self):
        # type: () -> dict
        """
        A one-shot access to hidden properties (the field is then destroyed)

        :return: A copy of the hidden properties dictionary on the first call
        :raise AttributeError: On any call after the first one
        """
        # Copy properties
        result = self.__hidden_properties.copy()

        # Destroy the field
        self.__hidden_properties.clear()
        del self.__hidden_properties
        return result

Response: Returns a copy of the hidden properties dictionary on the first call.


Instruction:
Can you generate the documentation for the following Python 3 function
def _field_property_generator(self, public_properties):
        # Local variable, to avoid messing with "self"
        stored_instance = self._ipopo_instance

        # Choose public or hidden properties
        # and select the method to call to notify about the property update
        if public_properties:
            properties = stored_instance.context.properties
            update_notifier = stored_instance.update_property
        else:
            # Copy Hidden properties and remove them from the context
            properties = stored_instance.context.grab_hidden_properties()
            update_notifier = stored_instance.update_hidden_property

        def get_value(_, name):
            """
            Retrieves the property value, from the iPOPO dictionaries

            :param name: The property name
            :return: The property value
            """
            return properties.get(name)

        def set_value(_, name, new_value):
            """
            Sets the property value and trigger an update event

            :param name: The property name
            :param new_value: The new property value
            """
            assert stored_instance.context is not None

            # Get the previous value
            old_value = properties.get(name)
            if new_value != old_value:
                # Change the property
                properties[name] = new_value

                # New value is different of the old one, trigger an event
                update_notifier(name, old_value, new_value)

            return new_value

        return get_value, set_value

Response:
Generates the methods called by the injected class properties
            and returns the values that are set to the new value.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_methods_names(public_properties):
        if public_properties:
            prefix = ipopo_constants.IPOPO_PROPERTY_PREFIX
        else:
            prefix = ipopo_constants.IPOPO_HIDDEN_PROPERTY_PREFIX

        return (
            "{0}{1}".format(prefix, ipopo_constants.IPOPO_GETTER_SUFFIX),
            "{0}{1}".format(prefix, ipopo_constants.IPOPO_SETTER_SUFFIX),
        )

Response: Generates the names of the methods that are used to inject the getter and setter of the class properties.


Instruction:
Can you tell what is the following Python 3 function doing
def manipulate(self, stored_instance, component_instance):
        # Store the stored instance
        self._ipopo_instance = stored_instance

        # Public flags to generate (True for public accessors)
        flags_to_generate = set()
        if stored_instance.context.properties:
            flags_to_generate.add(True)

        # (False for hidden ones)
        if stored_instance.context.has_hidden_properties():
            flags_to_generate.add(False)

        # Inject properties getters and setters
        for public_flag in flags_to_generate:
            # Prepare methods
            getter, setter = self._field_property_generator(public_flag)

            # Inject the getter and setter at the instance level
            getter_name, setter_name = self.get_methods_names(public_flag)
            setattr(component_instance, getter_name, getter)
            setattr(component_instance, setter_name, setter)

Response: This method is used to manipulate the iPOPO component instance.


Instruction:
Can you implement a function in Python 3 that
returns the full name of the class of the given object

Response:
def _full_class_name(obj):
    """
    Returns the full name of the class of the given object

    :param obj: Any Python object
    :return: The full name of the class of the object (if possible)
    """
    module = obj.__class__.__module__
    if module is None or module == str.__class__.__module__:
        return obj.__class__.__name__
    return module + "." + obj.__class__.__name__


Instruction:
How would you explain what the following Python 3 function does
def _prompt(self, prompt=None):
        if prompt:
            # Print the prompt
            self.write(prompt)
            self.output.flush()

        # Read the line
        return to_str(self.input.readline())

Response: Reads a line written by the user and returns a string


Instruction:
Implement a function in Python 3 to
convert the given data then writes it to the output stream.

Response:
def _write_bytes(self, data):
        """
        Converts the given data then writes it

        :param data: Data to be written
        :return: The result of ``self.output.write()``
        """
        with self.__lock:
            self.output.write(to_bytes(data, self.encoding))


Instruction:
Make a summary of the following Python 3 code
def _write_str(self, data):
        with self.__lock:
            self.output.write(
                to_str(data, self.encoding)
                .encode()
                .decode(self.out_encoding, errors="replace")
            )

Response: Converts the given data then writes it to the output file.


Instruction:
Can you generate the documentation for the following Python 3 function
def write_line(self, line=None, *args, **kwargs):
        if line is None:
            # Empty line
            self.write("\n")
        else:
            # Format the line, if arguments have been given
            if args or kwargs:
                line = line.format(*args, **kwargs)

            with self.__lock:
                # Write it
                self.write(line)
                try:
                    if line[-1] != "\n":
                        # Add the trailing new line
                        self.write("\n")
                except IndexError:
                    # Got an empty string
                    self.write("\n")

        self.flush()

Response: Formats and writes a line to the output


Instruction:
Can you create a Python 3 function that
formats and writes a line to the output file.

Response:
def write_line_no_feed(self, line=None, *args, **kwargs):
        """
        Formats and writes a line to the output
        """
        if line is None:
            # Empty line
            line = ""
        else:
            # Format the line, if arguments have been given
            if args or kwargs:
                line = line.format(*args, **kwargs)

            # Remove the trailing line feed
            if line[-1] == "\n":
                line = line[:-1]

        # Write it
        self.write(line)
        self.flush()


Instruction:
Implement a Python 3 function for
returning a list of handlers associated to the given component.

Response:
def get_handlers(self, component_context, instance):
        """
        Sets up service providers for the given component

        :param component_context: The ComponentContext bean
        :param instance: The component instance
        :return: The list of handlers associated to the given component
                 (never None)
        """
        # Extract information from the context
        logger_field = component_context.get_handler(constants.HANDLER_LOGGER)
        if not logger_field:
            # Error: log it and either raise an exception
            # or ignore this handler
            _logger.warning("Logger iPOPO handler can't find its configuration")

            # Here, we ignore the error and do not give any handler to iPOPO
            return []

        else:
            # Construct a handler and return it in a list
            return [_LoggerHandler(logger_field, component_context.name)]


Instruction:
Can you generate the documentation for the following Python 3 function
def manipulate(self, stored_instance, component_instance):
        # Create the logger for this component instance
        self._logger = logging.getLogger(self._name)

        # Inject it
        setattr(component_instance, self._field, self._logger)

Response: This method is called by iPOPO when the component is instantiated.


Instruction:
Explain what the following Python 3 code does
def clear(self):
        self._logger.debug("Component handlers are cleared")

        # Clean up everything to avoid stale references, ...
        self._field = None
        self._name = None
        self._logger = None

Response: Clears out the component s state.


Instruction:
Create a Python 3 function for
returning the possible completions of the current argument in the current shell session.

Response:
def completion_hints(config, prompt, session, context, current, arguments):
    # type: (CompletionInfo, str, ShellSession, BundleContext, str, List[str]) -> List[str]
    """
    Returns the possible completions of the current argument

    :param config: Configuration of the current completion
    :param prompt: The shell prompt string
    :param session: Current shell session
    :param context: Context of the shell UI bundle
    :param current: Current argument (to be completed)
    :param arguments: List of all arguments in their current state
    :return: A list of possible completions
    """
    if not current:
        # No word yet, so the current position is after the existing ones
        arg_idx = len(arguments)
    else:
        # Find the current word position
        arg_idx = arguments.index(current)

    # Find the ID of the next completer
    completers = config.completers
    if arg_idx > len(completers) - 1:
        # Argument is too far to be positional, try
        if config.multiple:
            # Multiple calls allowed for the last completer
            completer_id = completers[-1]
        else:
            # Nothing to return
            return []
    else:
        completer_id = completers[arg_idx]

    if completer_id == DUMMY:
        # Dummy completer: do nothing
        return []

    # Find the matching service
    svc_ref = context.get_service_reference(
        SVC_COMPLETER, "({}={})".format(PROP_COMPLETER_ID, completer_id)
    )
    if svc_ref is None:
        # Handler not found
        _logger.debug("Unknown shell completer ID: %s", completer_id)
        return []

    # Call the completer
    try:
        with use_service(context, svc_ref) as completer:
            matches = completer.complete(
                config, prompt, session, context, arguments, current
            )
            if not matches:
                return []

            return matches
    except Exception as ex:
        _logger.exception("Error calling completer %s: %s", completer_id, ex)
        return []


Instruction:
Implement a function in Python 3 to
return a list of handlers associated to the given component.

Response:
def get_handlers(self, component_context, instance):
        """
        Sets up service providers for the given component

        :param component_context: The ComponentContext bean
        :param instance: The component instance
        :return: The list of handlers associated to the given component
                 (never None)
        """
        # Extract information from the context
        logger_field = component_context.get_handler(constants.HANDLER_LOGGER)
        if not logger_field:
            # Error: log it and either raise an exception
            # or ignore this handler
            _logger.warning("Logger iPOPO handler can't find its configuration")

        else:
            # Create the logger for this component instance
            logger = logging.getLogger(component_context.name)

            # Inject it
            setattr(instance, logger_field, logger)
            logger.debug("Logger has been injected")

        # No need to have an instance handler
        return []


Instruction:
Can you implement a function in Python 3 that
checks if the file exists and returns its absolute path. If it does not return None.

Response:
def _resolve_file(file_name):
    """
    Checks if the file exists.

    If the file exists, the method returns its absolute path.
    Else, it returns None

    :param file_name: The name of the file to check
    :return: An absolute path, or None
    """
    if not file_name:
        return None

    path = os.path.realpath(file_name)
    if os.path.isfile(path):
        return path

    return None


Instruction:
How would you explain what the following Python 3 function does
def make_common_parser():
    parser = argparse.ArgumentParser(add_help=False)

    # Version number
    parser.add_argument(
        "--version",
        action="version",
        version="Pelix {0} from {1}".format(pelix.__version__, pelix.__file__),
    )

    # Framework options
    group = parser.add_argument_group("Framework options")
    group.add_argument(
        "-D",
        nargs="+",
        dest="properties",
        metavar="KEY=VALUE",
        help="Sets framework properties",
    )
    group.add_argument(
        "-v",
        "--verbose",
        action="store_true",
        help="Set loggers to DEBUG level",
    )

    # Initial configuration
    group = parser.add_argument_group("Initial configuration")
    group.add_argument(
        "-c",
        "--conf",
        dest="init_conf",
        metavar="FILE",
        help="Name of an initial configuration file to use "
        "(default configuration is also loaded)",
    )
    group.add_argument(
        "-C",
        "--exclusive-conf",
        dest="init_conf_exclusive",
        metavar="FILE",
        help="Name of an initial configuration file to use "
        "(without the default configuration)",
    )
    group.add_argument(
        "-e",
        "--empty-conf",
        dest="init_empty",
        action="store_true",
        help="Don't load any initial configuration",
    )

    # Initial script
    group = parser.add_argument_group("Script execution arguments")
    group.add_argument(
        "--init",
        action="store",
        dest="init_script",
        metavar="SCRIPT",
        help="Runs the given shell script before starting the console",
    )
    group.add_argument(
        "--run",
        action="store",
        dest="run_script",
        metavar="SCRIPT",
        help="Runs the given shell script then stops the framework",
    )
    return parser

Response: Creates an argument parser that can be used as a parent argument in the argument parser.


Instruction:
Can you write a function in Python 3 where it
handles the common arguments defined by the parser.

Response:
def handle_common_arguments(parsed_args):
    """
    Handles the arguments defined by :meth:`~make_common_parser`

    :param parsed_args: Argument parsed with ``argparse`` (``Namespace``)
    :return: An :class:`~InitFileHandler` object
    :raise IOError: Initial or run script not found
    """
    # Setup the logger
    logging.basicConfig(
        level=logging.DEBUG if parsed_args.verbose else logging.WARNING
    )

    # Framework properties dictionary
    props = {}

    # Read the initial configuration script
    init = InitFileHandler()
    if not parsed_args.init_empty:
        if not parsed_args.init_conf_exclusive:
            # Load default configuration
            init.load()

        # Load the given configuration file
        conf_file = parsed_args.init_conf_exclusive or parsed_args.init_conf
        if conf_file:
            init.load(conf_file)

        # Normalize configuration
        init.normalize()

        # Set initial framework properties
        props.update(init.properties)

    # Compute framework properties
    for prop_def in parsed_args.properties or []:
        key, value = prop_def.split("=", 1)
        props[key] = value

    # Check initial run script(s)
    if parsed_args.init_script:
        path = props[PROP_INIT_FILE] = _resolve_file(parsed_args.init_script)
        if not path:
            raise IOError(
                "Initial script file not found: {0}".format(
                    parsed_args.init_script
                )
            )

    if parsed_args.run_script:
        # Find the file
        path = props[PROP_RUN_FILE] = _resolve_file(parsed_args.run_script)
        if not path:
            raise IOError(
                "Script file not found: {0}".format(parsed_args.run_script)
            )

    # Update the stored configuration
    init.properties.update(props)
    return init


Instruction:
Can you tell what is the following Python 3 function doing
def _normal_prompt(self):
        sys.stdout.write(self.__get_ps1())
        sys.stdout.flush()
        return safe_input()

Response: Flushes the prompt before requesting the command line


Instruction:
Given the following Python 3 function, write the documentation
def loop_input(self, on_quit=None):
        # Start the init script
        self._run_script(
            self.__session, self._context.get_property(PROP_INIT_FILE)
        )

        # Run the script
        script_file = self._context.get_property(PROP_RUN_FILE)
        if script_file:
            self._run_script(self.__session, script_file)
        else:
            # No script: run the main loop (blocking)
            self._run_loop(self.__session)

        # Nothing more to do
        self._stop_event.set()
        sys.stdout.write("Bye !\n")
        sys.stdout.flush()
        if on_quit is not None:
            # Call a handler if needed
            on_quit()

Response: Reads the standard input until the shell session is stopped.


Instruction:
Write a Python 3 function for
running the given script file_path and returns True if a file has been executed False otherwise

Response:
def _run_script(self, session, file_path):
        """
        Runs the given script file

        :param session: Current shell session
        :param file_path: Path to the file to execute
        :return: True if a file has been execute
        """
        if file_path:
            # The 'run' command returns False in case of error
            # The 'execute' method returns False if the run command fails
            return self._shell.execute('run "{0}"'.format(file_path), session)

        return None


Instruction:
Given the following Python 3 function, write the documentation
def _run_loop(self, session):
        try:
            first_prompt = True

            # Set up the prompt
            prompt = (
                self._readline_prompt
                if readline is not None
                else self._normal_prompt
            )

            while not self._stop_event.is_set():
                # Wait for the shell to be there
                # Before Python 2.7, wait() doesn't return a result
                if self._shell_event.wait(.2) or self._shell_event.is_set():
                    # Shell present
                    if first_prompt:
                        # Show the banner on first prompt
                        sys.stdout.write(self._shell.get_banner())
                        first_prompt = False

                    # Read the next line
                    line = prompt()

                    with self._lock:
                        if self._shell_event.is_set():
                            # Execute it
                            self._shell.execute(line, session)

                        elif not self._stop_event.is_set():
                            # Shell service lost while not stopping
                            sys.stdout.write("Shell service lost.")
                            sys.stdout.flush()
        except (EOFError, KeyboardInterrupt, SystemExit):
            # Input closed or keyboard interruption
            pass

Response: Runs the main input loop.


Instruction:
Make a summary of the following Python 3 code
def readline_completer(self, text, state):
        if state == 0:
            # New completion, reset the list of matches and the display hook
            self._readline_matches = []
            try:
                readline.set_completion_display_matches_hook(None)
            except AttributeError:
                pass

            # Get the full line
            full_line = readline.get_line_buffer()
            begin_idx = readline.get_begidx()

            # Parse arguments as best as we can
            try:
                arguments = shlex.split(full_line)
            except ValueError:
                arguments = full_line.split()

            # Extract the command (maybe with its namespace)
            command = arguments.pop(0)

            if begin_idx > 0:
                # We're completing after the command (and maybe some args)
                try:
                    # Find the command
                    ns, command = self._shell.get_ns_command(command)
                except ValueError:
                    # Ambiguous command: ignore
                    return None

                # Use the completer associated to the command, if any
                try:
                    configuration = self._shell.get_command_completers(
                        ns, command
                    )
                    if configuration is not None:
                        self._readline_matches = completion_hints(
                            configuration,
                            self.__get_ps1(),
                            self.__session,
                            self._context,
                            text,
                            arguments,
                        )
                except KeyError:
                    # Unknown command
                    pass

            elif "." in command:
                # Completing the command, and a name space is given
                namespace, prefix = text.split(".", 2)
                commands = self._shell.get_commands(namespace)

                # Filter methods according to the prefix
                self._readline_matches = [
                    "{0}.{1}".format(namespace, command)
                    for command in commands
                    if command.startswith(prefix)
                ]
            else:
                # Completing a command or namespace
                prefix = command

                # Default commands goes first...
                possibilities = [
                    "{0} ".format(command)
                    for command in self._shell.get_commands(None)
                    if command.startswith(prefix)
                ]

                # ... then name spaces
                namespaces = self._shell.get_namespaces()
                possibilities.extend(
                    "{0}.".format(namespace)
                    for namespace in namespaces
                    if namespace.startswith(prefix)
                )

                # ... then commands in those name spaces
                possibilities.extend(
                    "{0} ".format(command)
                    for namespace in namespaces
                    if namespace is not None
                    for command in self._shell.get_commands(namespace)
                    if command.startswith(prefix)
                )

                # Filter methods according to the prefix
                self._readline_matches = possibilities

            if not self._readline_matches:
                return None

            # Return the first possibility
            return self._readline_matches[0]

        elif state < len(self._readline_matches):
            # Next try
            return self._readline_matches[state]

        return None

Response: A completer for the readline library.


Instruction:
Create a Python 3 function for
searching for a shell in the context and sets the shell reference.

Response:
def search_shell(self):
        """
        Looks for a shell service
        """
        with self._lock:
            if self._shell is not None:
                # A shell is already there
                return

            reference = self._context.get_service_reference(SERVICE_SHELL)
            if reference is not None:
                self.set_shell(reference)


Instruction:
Implement a function in Python 3 to
call by Pelix when an event changes the service attributes.

Response:
def service_changed(self, event):
        """
        Called by Pelix when an events changes
        """
        kind = event.get_kind()
        reference = event.get_service_reference()

        if kind in (pelix.ServiceEvent.REGISTERED, pelix.ServiceEvent.MODIFIED):
            # A service matches our filter
            self.set_shell(reference)

        else:
            with self._lock:
                # Service is not matching our filter anymore
                self.clear_shell()

                # Request for a new binding
                self.search_shell()


Instruction:
Can you generate the documentation for the following Python 3 function
def set_shell(self, svc_ref):
        if svc_ref is None:
            return

        with self._lock:
            # Get the service
            self._shell_ref = svc_ref
            self._shell = self._context.get_service(self._shell_ref)

            # Set the readline completer
            if readline is not None:
                readline.set_completer(self.readline_completer)

            # Set the flag
            self._shell_event.set()

Response: Binds the given shell service.


Instruction:
Create a Python 3 function for
clearing the active shell

Response:
def clear_shell(self):
        """
        Unbinds the active shell service
        """
        with self._lock:
            # Clear the flag
            self._shell_event.clear()

            # Clear the readline completer
            if readline is not None:
                readline.set_completer(None)
                del self._readline_matches[:]

            if self._shell_ref is not None:
                # Release the service
                self._context.unget_service(self._shell_ref)

            self._shell_ref = None
            self._shell = None


Instruction:
Given the following Python 3 function, write the documentation
def do_POST(self, request, response):
        # pylint: disable=C0103
        """
        Handles a HTTP POST request

        :param request: The HTTP request bean
        :param response: The HTTP response handler
        """
        try:
            # Get the request content
            data = to_str(request.read_data())

            # Dispatch
            result = self._marshaled_dispatch(data, self._simple_dispatch)

            # Send the result
            response.send_content(200, result, "application/json-rpc")
        except Exception as ex:
            response.send_content(
                500, "Internal error:\n{0}\n".format(ex), "text/plain"
            )

Response: Handles a HTTP POST request


Instruction:
Can you generate the documentation for the following Python 3 function
def _prepare_requirements(requirements, requires_filters):
        if not requires_filters or not isinstance(requires_filters, dict):
            # No explicit filter configured
            return requirements

        # We need to change a part of the requirements
        new_requirements = {}
        for field, requirement in requirements.items():
            try:
                explicit_filter = requires_filters[field]

                # Store an updated copy of the requirement
                requirement_copy = requirement.copy()
                requirement_copy.set_filter(explicit_filter)
                new_requirements[field] = requirement_copy

            except (KeyError, TypeError, ValueError):
                # No information for this one, or invalid filter:
                # keep the factory requirement
                new_requirements[field] = requirement

        return new_requirements

Response: Prepare the requirements dictionary for the component - level modules.


Instruction:
Create a Python 3 function for
returning the list of handlers associated to the given component.

Response:
def get_handlers(self, component_context, instance):
        """
        Sets up service providers for the given component

        :param component_context: The ComponentContext bean
        :param instance: The component instance
        :return: The list of handlers associated to the given component
        """
        # Extract information from the context
        requirements = component_context.get_handler(
            ipopo_constants.HANDLER_REQUIRES
        )
        requires_filters = component_context.properties.get(
            ipopo_constants.IPOPO_REQUIRES_FILTERS, None
        )

        # Prepare requirements
        requirements = self._prepare_requirements(
            requirements, requires_filters
        )

        # Set up the runtime dependency handlers
        handlers = []
        for field, requirement in requirements.items():
            # Construct the handler
            if requirement.aggregate:
                handlers.append(AggregateDependency(field, requirement))
            else:
                handlers.append(SimpleDependency(field, requirement))

        return handlers


Instruction:
Explain what the following Python 3 code does
def manipulate(self, stored_instance, component_instance):
        # Store the stored instance...
        self._ipopo_instance = stored_instance

        # ... and the bundle context
        self._context = stored_instance.bundle_context

Response: Stores the given StoredInstance bean and the bundle context.


Instruction:
Can you tell what is the following Python 3 function doing
def clear(self):
        self._lock = None
        self._ipopo_instance = None
        self._context = None
        self.requirement = None
        self._value = None
        self._field = None

Response: Clears the internal state of the current object.


Instruction:
Write a Python 3 script to
call by the framework when a service event occurs.

Response:
def service_changed(self, event):
        """
        Called by the framework when a service event occurs
        """
        if (
            self._ipopo_instance is None
            or not self._ipopo_instance.check_event(event)
        ):
            # stop() and clean() may have been called after we have been put
            # inside a listener list copy...
            # or we've been told to ignore this event
            return

        # Call sub-methods
        kind = event.get_kind()
        svc_ref = event.get_service_reference()

        if kind == ServiceEvent.REGISTERED:
            # Service coming
            self.on_service_arrival(svc_ref)

        elif kind in (
            ServiceEvent.UNREGISTERING,
            ServiceEvent.MODIFIED_ENDMATCH,
        ):
            # Service gone or not matching anymore
            self.on_service_departure(svc_ref)

        elif kind == ServiceEvent.MODIFIED:
            # Modified properties (can be a new injection)
            self.on_service_modify(svc_ref, event.get_previous_properties())


Instruction:
Can you write a function in Python 3 where it
starts the dependency manager.

Response:
def start(self):
        """
        Starts the dependency manager
        """
        self._context.add_service_listener(
            self, self.requirement.filter, self.requirement.specification
        )


Instruction:
Implement a Python 3 function for
clearing up the manager.

Response:
def clear(self):
        """
        Cleans up the manager. The manager can't be used after this method has
        been called
        """
        self.reference = None
        self._pending_ref = None
        super(SimpleDependency, self).clear()


Instruction:
Can you tell what is the following Python 3 function doing
def on_service_arrival(self, svc_ref):
        with self._lock:
            if self._value is None:
                # Inject the service
                self.reference = svc_ref
                self._value = self._context.get_service(svc_ref)

                self._ipopo_instance.bind(self, self._value, self.reference)
                return True

        return None

Response: Called when a service is arrived in the framework.


Instruction:
Write a Python 3 script to
call when a service has been modified in the framework

Response:
def on_service_modify(self, svc_ref, old_properties):
        """
        Called when a service has been modified in the framework

        :param svc_ref: A service reference
        :param old_properties: Previous properties values
        """
        with self._lock:
            if self.reference is None:
                # A previously registered service now matches our filter
                self.on_service_arrival(svc_ref)
            elif svc_ref is self.reference:
                # Notify the property modification
                self._ipopo_instance.update(
                    self, self._value, svc_ref, old_properties
                )


Instruction:
Explain what the following Python 3 code does
def stop(self):
        super(SimpleDependency, self).stop()
        if self.reference is not None:
            # Return a tuple of tuple
            return ((self._value, self.reference),)

        return None

Response: Stops the dependency manager and returns the removed bindings or None if the dependency manager is not running.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def is_valid(self):
        return super(SimpleDependency, self).is_valid() or (
            self.requirement.immediate_rebind and self._pending_ref is not None
        )

Response: Tests if the dependency is in a valid state.


Instruction:
How would you implement a function in Python 3 that
searches for the required service and binds it to the component.

Response:
def try_binding(self):
        """
        Searches for the required service if needed

        :raise BundleException: Invalid ServiceReference found
        """
        with self._lock:
            if self.reference is not None:
                # Already bound
                return

            if self._pending_ref is not None:
                # Get the reference we chose to keep this component valid
                ref = self._pending_ref
                self._pending_ref = None
            else:
                # Get the first matching service
                ref = self._context.get_service_reference(
                    self.requirement.specification, self.requirement.filter
                )

            if ref is not None:
                # Found a service
                self.on_service_arrival(ref)


Instruction:
How would you code a function in Python 3 to
clear up the manager.

Response:
def clear(self):
        """
        Cleans up the manager. The manager can't be used after this method has
        been called
        """
        self.services.clear()
        self.services = None
        self._future_value = None
        super(AggregateDependency, self).clear()


Instruction:
Can you tell what is the following Python 3 function doing
def on_service_arrival(self, svc_ref):
        with self._lock:
            if svc_ref not in self.services:
                # Get the new service
                service = self._context.get_service(svc_ref)

                if self._future_value is None:
                    # First value
                    self._future_value = []

                # Store the information
                self._future_value.append(service)
                self.services[svc_ref] = service

                self._ipopo_instance.bind(self, service, svc_ref)
                return True

            return None

Response: Called when a service is arrived in the framework.


Instruction:
How would you implement a function in Python 3 that
calls when a service is deactivated from the framework

Response:
def on_service_departure(self, svc_ref):
        """
        Called when a service has been unregistered from the framework

        :param svc_ref: A service reference
        :return: A tuple (service, reference) if the service has been lost,
                 else None
        """
        with self._lock:
            try:
                # Get the service instance
                service = self.services.pop(svc_ref)
            except KeyError:
                # Not a known service reference: ignore
                pass
            else:
                # Clean the instance values
                self._future_value.remove(service)

                # Nullify the value if needed
                if not self._future_value:
                    self._future_value = None

                self._ipopo_instance.unbind(self, service, svc_ref)
                return True

            return None


Instruction:
Create a Python 3 function for
calling when a service has been modified in the framework

Response:
def on_service_modify(self, svc_ref, old_properties):
        """
        Called when a service has been modified in the framework

        :param svc_ref: A service reference
        :param old_properties: Previous properties values
        :return: A tuple (added, (service, reference)) if the dependency has
                 been changed, else None
        """
        with self._lock:
            try:
                # Look for the service
                service = self.services[svc_ref]
            except KeyError:
                # A previously registered service now matches our filter
                return self.on_service_arrival(svc_ref)
            else:
                # Notify the property modification
                self._ipopo_instance.update(
                    self, service, svc_ref, old_properties
                )

            return None


Instruction:
Explain what the following Python 3 code does
def stop(self):
        super(AggregateDependency, self).stop()

        if self.services:
            return [
                (service, reference)
                for reference, service in self.services.items()
            ]

        return None

Response: Stops the dependency manager and returns a list of the removed bindings or None if no bindings are removed.


Instruction:
Write a Python 3 script to
store a new log entry and notifies listeners

Response:
def _store_entry(self, entry):
        """
        Stores a new log entry and notifies listeners

        :param entry: A LogEntry object
        """
        # Get the logger and log the message
        self.__logs.append(entry)

        # Notify listeners
        for listener in self.__listeners.copy():
            try:
                listener.logged(entry)
            except Exception as ex:
                # Create a new log entry, without using logging nor notifying
                # listener (to avoid a recursion)
                err_entry = LogEntry(
                    logging.WARNING,
                    "Error notifying logging listener {0}: {1}".format(
                        listener, ex
                    ),
                    sys.exc_info(),
                    self._context.get_bundle(),
                    None,
                )

                # Insert the new entry before the real one
                self.__logs.pop()
                self.__logs.append(err_entry)
                self.__logs.append(entry)


Instruction:
Write a Python 3 script to
log a message possibly with an exception context

Response:
def log(self, level, message, exc_info=None, reference=None):
        # pylint: disable=W0212
        """
        Logs a message, possibly with an exception

        :param level: Severity of the message (Python logging level)
        :param message: Human readable message
        :param exc_info: The exception context (sys.exc_info()), if any
        :param reference: The ServiceReference associated to the log
        """
        if not isinstance(reference, pelix.framework.ServiceReference):
            # Ensure we have a clean Service Reference
            reference = None

        if exc_info is not None:
            # Format the exception to avoid memory leaks
            try:
                exception_str = "\n".join(traceback.format_exception(*exc_info))
            except (TypeError, ValueError, AttributeError):
                exception_str = "<Invalid exc_info>"
        else:
            exception_str = None

        # Store the LogEntry
        entry = LogEntry(
            level, message, exception_str, self.__bundle, reference
        )
        self.__reader._store_entry(entry)


Instruction:
Write a Python 3 script to
find the bundle associated to a Python module object.

Response:
def _bundle_from_module(self, module_object):
        """
        Find the bundle associated to a module

        :param module_object: A Python module object
        :return: The Bundle object associated to the module, or None
        """
        try:
            # Get the module name
            module_object = module_object.__name__
        except AttributeError:
            # We got a string
            pass

        return self._framework.get_bundle_by_name(module_object)


Instruction:
Given the following Python 3 function, write the documentation
def emit(self, record):
        # pylint: disable=W0212
        """
        Handle a message logged with the logger

        :param record: A log record
        """
        # Get the bundle
        bundle = self._bundle_from_module(record.module)

        # Convert to a LogEntry
        entry = LogEntry(
            record.levelno, record.getMessage(), None, bundle, None
        )
        self._reader._store_entry(entry)

Response: Handle a log record logged with the logger


Instruction:
Given the following Python 3 function, write the documentation
def publish(self, topic, payload, qos=0, retain=False):
        # TODO: check (full transmission) success
        return self._client.publish(topic, payload, qos, retain)

Response: Publishes a MQTT message.


Instruction:
Can you generate the documentation for the following Python 3 function
def _prepare_requirements(configs, requires_filters):
        if not requires_filters or not isinstance(requires_filters, dict):
            # No explicit filter configured
            return configs

        # We need to change a part of the requirements
        new_requirements = {}
        for field, config in configs.items():
            # Extract values from tuple
            requirement, key, allow_none = config

            try:
                explicit_filter = requires_filters[field]

                # Store an updated copy of the requirement
                requirement_copy = requirement.copy()
                requirement_copy.set_filter(explicit_filter)
                new_requirements[field] = (requirement_copy, key, allow_none)

            except (KeyError, TypeError, ValueError):
                # No information for this one, or invalid filter:
                # keep the factory requirement
                new_requirements[field] = config

        return new_requirements

Response: Prepare the requirements dictionary for the component.


Instruction:
Can you create a Python 3 function that
returns a list of handlers associated to the given component.

Response:
def get_handlers(self, component_context, instance):
        """
        Sets up service providers for the given component

        :param component_context: The ComponentContext bean
        :param instance: The component instance
        :return: The list of handlers associated to the given component
        """
        # Extract information from the context
        configs = component_context.get_handler(
            ipopo_constants.HANDLER_REQUIRES_MAP
        )
        requires_filters = component_context.properties.get(
            ipopo_constants.IPOPO_REQUIRES_FILTERS, None
        )

        # Prepare requirements
        configs = self._prepare_requirements(configs, requires_filters)

        # Set up the runtime dependency handlers
        handlers = []
        for field, config in configs.items():
            # Extract values from tuple
            requirement, key, allow_none = config

            # Construct the handler
            if requirement.aggregate:
                handlers.append(
                    AggregateDependency(field, requirement, key, allow_none)
                )
            else:
                handlers.append(
                    SimpleDependency(field, requirement, key, allow_none)
                )

        return handlers


Instruction:
Can you tell what is the following Python 3 function doing
def manipulate(self, stored_instance, component_instance):
        # Store the stored instance...
        self._ipopo_instance = stored_instance

        # ... and the bundle context
        self._context = stored_instance.bundle_context

        # Set the default value for the field: an empty dictionary
        setattr(component_instance, self._field, {})

Response: Manually updates the component instance with the values from the given StoredInstance bean.


Instruction:
Explain what the following Python 3 code does
def clear(self):
        self.services.clear()
        self._future_value.clear()

        self.services = None
        self._lock = None
        self._ipopo_instance = None
        self._context = None
        self.requirement = None
        self._key = None
        self._allow_none = None
        self._future_value = None
        self._field = None

Response: Clears up the manager.


Instruction:
How would you explain what the following Python 3 function does
def is_valid(self):
        return (
            self.requirement is not None and self.requirement.optional
        ) or bool(self._future_value)

Response: Tests if the dependency is in a valid state.


Instruction:
Create a Python 3 function to
stop the dependency manager and returns a list of the removed bindings or None if no services are available.

Response:
def stop(self):
        """
        Stops the dependency manager (must be called before clear())

        :return: The removed bindings (list) or None
        """
        self._context.remove_service_listener(self)
        if self.services:
            return [
                (service, reference)
                for reference, service in self.services.items()
            ]

        return None


Instruction:
Write a Python 3 script for
trying to bind all services to the required service.

Response:
def try_binding(self):
        """
        Searches for the required service if needed

        :raise BundleException: Invalid ServiceReference found
        """
        with self._lock:
            if self.services:
                # We already are alive (not our first call)
                # => we are updated through service events
                return

            # Get all matching services
            refs = self._context.get_all_service_references(
                self.requirement.specification, self.requirement.filter
            )
            if not refs:
                # No match found
                return

            results = []
            try:
                # Bind all new reference
                for reference in refs:
                    added = self.on_service_arrival(reference)
                    if added:
                        results.append(reference)
            except BundleException as ex:
                # Get the logger for this instance
                logger = logging.getLogger(
                    "-".join((self._ipopo_instance.name, "RequiresMap-Runtime"))
                )
                logger.debug("Error binding multiple references: %s", ex)

                # Undo what has just been done, ignoring errors
                for reference in results:
                    try:
                        self.on_service_departure(reference)

                    except BundleException as ex2:
                        logger.debug("Error cleaning up: %s", ex2)

                del results[:]
                raise


Instruction:
Write a Python 3 function for
calling when a service is arrived in the framework.

Response:
def on_service_arrival(self, svc_ref):
        """
        Called when a service has been registered in the framework

        :param svc_ref: A service reference
        """
        with self._lock:
            if svc_ref not in self.services:
                # Get the key property
                prop_value = svc_ref.get_property(self._key)
                if (
                    prop_value not in self._future_value
                    and prop_value is not None
                    or self._allow_none
                ):
                    # Matching new property value
                    service = self._context.get_service(svc_ref)

                    # Store the information
                    self._future_value[prop_value] = service
                    self.services[svc_ref] = service

                    # Call back iPOPO
                    self._ipopo_instance.bind(self, service, svc_ref)
                    return True

            return None


Instruction:
Explain what the following Python 3 code does
def __store_service(self, key, service):
        self._future_value.setdefault(key, []).append(service)

Response: Stores the given service in the dictionary


Instruction:
Write a Python 3 script to
remove the given service from the future dictionary.

Response:
def __remove_service(self, key, service):
        """
        Removes the given service from the future dictionary

        :param key: Dictionary key
        :param service: Service to remove from the dictionary
        """
        try:
            # Remove the injected service
            prop_services = self._future_value[key]
            prop_services.remove(service)

            # Clean up
            if not prop_services:
                del self._future_value[key]

        except KeyError:
            # Ignore: can occur when removing a service with a None property,
            # if allow_none is False
            pass


Instruction:
Here you have a function in Python 3, explain what it does
def get_value(self):
        with self._lock:
            # The value field must be a deep copy of our dictionary
            if self._future_value is not None:
                return {
                    key: value[:] for key, value in self._future_value.items()
                }

            return None

Response: Retrieves the value to inject in the component


Instruction:
Write a Python 3 script for
calling when a service is deactivated from the framework

Response:
def on_service_departure(self, svc_ref):
        """
        Called when a service has been unregistered from the framework

        :param svc_ref: A service reference
        :return: A tuple (service, reference) if the service has been lost,
                 else None
        """
        with self._lock:
            if svc_ref in self.services:
                # Get the service instance
                service = self.services.pop(svc_ref)

                # Get the key property
                prop_value = svc_ref.get_property(self._key)

                # Remove the injected service
                self.__remove_service(prop_value, service)

                self._ipopo_instance.unbind(self, service, svc_ref)
                return True

            return None


Instruction:
Can you generate the documentation for the following Python 3 function
def on_service_modify(self, svc_ref, old_properties):
        with self._lock:
            if svc_ref not in self.services:
                # A previously registered service now matches our filter
                return self.on_service_arrival(svc_ref)
            else:
                # Get the property values
                service = self.services[svc_ref]
                old_value = old_properties.get(self._key)
                prop_value = svc_ref.get_property(self._key)

                if old_value != prop_value:
                    # Key changed
                    if prop_value is not None or self._allow_none:
                        # New property accepted
                        if old_value is not None or self._allow_none:
                            self.__remove_service(old_value, service)

                        self.__store_service(prop_value, service)

                        # Notify the property modification, with a value change
                        self._ipopo_instance.update(
                            self, service, svc_ref, old_properties, True
                        )
                    else:
                        # Consider the service as gone
                        self.__remove_service(old_value, service)
                        del self.services[svc_ref]
                        self._ipopo_instance.unbind(self, service, svc_ref)
                else:
                    # Simple property update
                    self._ipopo_instance.update(
                        self, service, svc_ref, old_properties, False
                    )

            return None

Response: Called when a service has been modified in the framework.


Instruction:
How would you explain what the following Python 3 function does
def match_sr(self, svc_ref, cid=None):
        # type: (ServiceReference, Optional[Tuple[str, str]] ) -> bool
        """
        Checks if this export registration matches the given service reference

        :param svc_ref: A service reference
        :param cid: A container ID
        :return: True if the service matches this export registration
        """
        with self.__lock:
            our_sr = self.get_reference()
            if our_sr is None:
                return False

            sr_compare = our_sr == svc_ref
            if cid is None:
                return sr_compare

            our_cid = self.get_export_container_id()
            if our_cid is None:
                return False

            return sr_compare and our_cid == cid

Response: Checks if this export registration matches the given service reference and container ID.


Instruction:
Create a Python 3 function for
returning the exception associated to the export if any otherwise returns None.

Response:
def get_exception(self):
        # type: () -> Optional[Tuple[Any, Any, Any]]
        """
        Returns the exception associated to the export

        :return: An exception tuple, if any
        """
        with self.__lock:
            return (
                self.__updateexception
                if self.__updateexception or self.__closed
                else self.__exportref.get_exception()
            )


Instruction:
Can you create a Python 3 function that
closes the export endpoint and all related resources.

Response:
def close(self):
        """
        Cleans up the export endpoint
        """
        publish = False
        exporterid = rsid = exception = export_ref = ed = None
        with self.__lock:
            if not self.__closed:
                exporterid = self.__exportref.get_export_container_id()
                export_ref = self.__exportref
                rsid = self.__exportref.get_remoteservice_id()
                ed = self.__exportref.get_description()
                exception = self.__exportref.get_exception()
                self.__closed = True
                publish = self.__exportref.close(self)
                self.__exportref = None

        # pylint: disable=W0212
        if publish and export_ref and self.__rsa:
            self.__rsa._publish_event(
                RemoteServiceAdminEvent.fromexportunreg(
                    self.__rsa._get_bundle(),
                    exporterid,
                    rsid,
                    export_ref,
                    exception,
                    ed,
                )
            )
            self.__rsa = None


Instruction:
Can you tell what is the following Python 3 function doing
def advertise_endpoint(self, endpoint_description):
        endpoint_id = endpoint_description.get_id()
        with self._published_endpoints_lock:
            if self.get_advertised_endpoint(endpoint_id) is not None:
                return False

            advertise_result = self._advertise(endpoint_description)
            if advertise_result:
                self._add_advertised(endpoint_description, advertise_result)
                return True

            return False

Response: Advertise and add an endpoint_description to the cache.


Instruction:
Write a Python 3 script for
updating an existing endpoint_description.

Response:
def update_endpoint(self, updated_ed):
        """
        Update a previously advertised endpoint_description.

        :param endpoint_description: an instance of EndpointDescription to
        update. Must not be None.
        :return: True if advertised, False if not
        (e.g. it's already been advertised)
        """
        endpoint_id = updated_ed.get_id()
        with self._published_endpoints_lock:
            if self.get_advertised_endpoint(endpoint_id) is None:
                return False

            advertise_result = self._update(updated_ed)
            if advertise_result:
                self._remove_advertised(endpoint_id)
                self._add_advertised(updated_ed, advertise_result)
                return True

            return False


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_handlers(self, component_context, instance):
        # Retrieve the handler configuration
        provides = component_context.get_handler(
            ipopo_constants.HANDLER_PROVIDES
        )
        if not provides:
            # Nothing to do
            return ()

        # 1 handler per provided service
        return [
            ServiceRegistrationHandler(
                specs, controller, is_factory, is_prototype
            )
            for specs, controller, is_factory, is_prototype in provides
        ]

Response: Returns a list of handlers associated to the given component.


Instruction:
Write a Python 3 function for
generating the methods called by the injected controller

Response:
def _field_controller_generator(self):
        """
        Generates the methods called by the injected controller
        """
        # Local variable, to avoid messing with "self"
        stored_instance = self._ipopo_instance

        def get_value(self, name):
            # pylint: disable=W0613
            """
            Retrieves the controller value, from the iPOPO dictionaries

            :param name: The property name
            :return: The property value
            """
            return stored_instance.get_controller_state(name)

        def set_value(self, name, new_value):
            # pylint: disable=W0613
            """
            Sets the property value and trigger an update event

            :param name: The property name
            :param new_value: The new property value
            """
            # Get the previous value
            old_value = stored_instance.get_controller_state(name)
            if new_value != old_value:
                # Update the controller state
                stored_instance.set_controller_state(name, new_value)

            return new_value

        return get_value, set_value


Instruction:
Can you implement a function in Python 3 that
manipulates the component instance :param stored_instance: The iPOPO component StoredInstance :param component_instance: The component instance

Response:
def manipulate(self, stored_instance, component_instance):
        """
        Manipulates the component instance

        :param stored_instance: The iPOPO component StoredInstance
        :param component_instance: The component instance
        """
        # Store the stored instance
        self._ipopo_instance = stored_instance

        if self.__controller is None:
            # No controller: do nothing
            return

        # Get the current value of the member (True by default)
        controller_value = getattr(component_instance, self.__controller, True)

        # Store the controller value
        stored_instance.set_controller_state(
            self.__controller, controller_value
        )

        # Prepare the methods names
        getter_name = "{0}{1}".format(
            ipopo_constants.IPOPO_CONTROLLER_PREFIX,
            ipopo_constants.IPOPO_GETTER_SUFFIX,
        )
        setter_name = "{0}{1}".format(
            ipopo_constants.IPOPO_CONTROLLER_PREFIX,
            ipopo_constants.IPOPO_SETTER_SUFFIX,
        )

        # Inject the getter and setter at the instance level
        getter, setter = self._field_controller_generator()
        setattr(component_instance, getter_name, getter)
        setattr(component_instance, setter_name, setter)


Instruction:
How would you explain what the following Python 3 function does
def on_controller_change(self, name, value):
        if self.__controller != name:
            # Nothing to do
            return

        # Update the controller value
        self.__controller_on = value
        if value:
            # Controller switched to "ON"
            self._register_service()
        else:
            # Controller switched to "OFF"
            self._unregister_service()

Response: Called by the instance manager when a controller value has been changed


Instruction:
Explain what the following Python 3 code does
def on_property_change(self, name, old_value, new_value):
        if self._registration is not None:
            # use the registration to trigger the service event
            self._registration.set_properties({name: new_value})

Response: Called by the instance manager when a component property is changed.


Instruction:
Can you create a Python 3 function that
registers the provided service with the component if possible.

Response:
def _register_service(self):
        """
        Registers the provided service, if possible
        """
        if (
            self._registration is None
            and self.specifications
            and self.__validated
            and self.__controller_on
        ):
            # Use a copy of component properties
            properties = self._ipopo_instance.context.properties.copy()
            bundle_context = self._ipopo_instance.bundle_context

            # Register the service
            self._registration = bundle_context.register_service(
                self.specifications,
                self._ipopo_instance.instance,
                properties,
                factory=self.__is_factory,
                prototype=self.__is_prototype,
            )
            self._svc_reference = self._registration.get_reference()

            # Notify the component
            self._ipopo_instance.safe_callback(
                ipopo_constants.IPOPO_CALLBACK_POST_REGISTRATION,
                self._svc_reference,
            )


Instruction:
Can you generate a brief explanation for the following Python 3 code
def use_service(bundle_context, svc_reference):
    if svc_reference is None:
        raise TypeError("Invalid ServiceReference")

    try:
        # Give the service
        yield bundle_context.get_service(svc_reference)
    finally:
        try:
            # Release it
            bundle_context.unget_service(svc_reference)
        except pelix.constants.BundleException:
            # Service might have already been unregistered
            pass

Response: Utility context to safely use a service in a with block.


Instruction:
How would you explain what the following Python 3 function does
def SynchronizedClassMethod(*locks_attr_names, **kwargs):
    # pylint: disable=C1801
    """
    A synchronizer decorator for class methods. An AttributeError can be raised
    at runtime if the given lock attribute doesn't exist or if it is None.

    If a parameter ``sorted`` is found in ``kwargs`` and its value is True,
    then the list of locks names will be sorted before locking.

    :param locks_attr_names: A list of the lock(s) attribute(s) name(s) to be
                             used for synchronization
    :return: The decorator method, surrounded with the lock
    """
    # Filter the names (remove empty ones)
    locks_attr_names = [
        lock_name for lock_name in locks_attr_names if lock_name
    ]

    if not locks_attr_names:
        raise ValueError("The lock names list can't be empty")

    if "sorted" not in kwargs or kwargs["sorted"]:
        # Sort the lock names if requested
        # (locking always in the same order reduces the risk of dead lock)
        locks_attr_names = list(locks_attr_names)
        locks_attr_names.sort()

    def wrapped(method):
        """
        The wrapping method

        :param method: The wrapped method
        :return: The wrapped method
        :raise AttributeError: The given attribute name doesn't exist
        """

        @functools.wraps(method)
        def synchronized(self, *args, **kwargs):
            """
            Calls the wrapped method with a lock
            """
            # Raises an AttributeError if needed
            locks = [getattr(self, attr_name) for attr_name in locks_attr_names]
            locked = collections.deque()
            i = 0

            try:
                # Lock
                for lock in locks:
                    if lock is None:
                        # No lock...
                        raise AttributeError(
                            "Lock '{0}' can't be None in class {1}".format(
                                locks_attr_names[i], type(self).__name__
                            )
                        )

                    # Get the lock
                    i += 1
                    lock.acquire()
                    locked.appendleft(lock)

                # Use the method
                return method(self, *args, **kwargs)

            finally:
                # Unlock what has been locked in all cases
                for lock in locked:
                    lock.release()

                locked.clear()
                del locks[:]

        return synchronized

    # Return the wrapped method
    return wrapped

Response: A synchronizer for class methods.


Instruction:
Here you have a function in Python 3, explain what it does
def is_lock(lock):
    if lock is None:
        # Don't do useless tests
        return False

    for attr in "acquire", "release", "__enter__", "__exit__":
        if not hasattr(lock, attr):
            # Missing something
            return False

    # Same API as a lock
    return True

Response: Tests if the given lock is an instance of a lock class


Instruction:
Write a Python 3 function that can
return a list with duplicates removed in the same order

Response:
def remove_duplicates(items):
    """
    Returns a list without duplicates, keeping elements order

    :param items: A list of items
    :return: The list without duplicates, in the same order
    """
    if items is None:
        return items

    new_list = []
    for item in items:
        if item not in new_list:
            new_list.append(item)
    return new_list


Instruction:
Can you create a Python 3 function that
adds a listener to the list of events in the order they were registered.

Response:
def add_listener(registry, listener):
    """
    Adds a listener in the registry, if it is not yet in

    :param registry: A registry (a list)
    :param listener: The listener to register
    :return: True if the listener has been added
    """
    if listener is None or listener in registry:
        return False

    registry.append(listener)
    return True


Instruction:
Explain what the following Python 3 code does
def remove_listener(registry, listener):
    if listener is not None and listener in registry:
        registry.remove(listener)
        return True

    return False

Response: Removes a listener from the registry


Instruction:
Can you create a Python 3 function that
tries to convert the given value to an iterable if necessary.

Response:
def to_iterable(value, allow_none=True):
    """
    Tries to convert the given value to an iterable, if necessary.
    If the given value is a list, a list is returned; if it is a string, a list
    containing one string is returned, ...

    :param value: Any object
    :param allow_none: If True, the method returns None if value is None, else
                       it returns an empty list
    :return: A list containing the given string, or the given value
    """
    if value is None:
        # None given
        if allow_none:
            return None

        return []

    elif isinstance(value, (list, tuple, set, frozenset)):
        # Iterable given, return it as-is
        return value

    # Return a one-value list
    return [value]


Instruction:
Create a Python 3 function to
log the deprecation message on first call does nothing after is logged

Response:
def __log(self, method_name):
        """
        Logs the deprecation message on first call, does nothing after

        :param method_name: Name of the deprecated method
        """
        if not self.__already_logged:
            # Print only if not already done
            stack = "\n\t".join(traceback.format_stack())

            logging.getLogger(self.__logger).warning(
                "%s: %s\n%s", method_name, self.__message, stack
            )
            self.__already_logged = True