Instruction:
Can you generate the documentation for the following Python 3 function
def update(self, model, prop_name, info):
        # logger.debug("History changed %s\n%s\n%s" % (model, prop_name, info))
        if self.parent is not None and hasattr(self.parent, "focus_notebook_page_of_controller"):
            # request focus -> which has not have to be satisfied
            self.parent.focus_notebook_page_of_controller(self)

        if self._selected_sm_model is None or self._selected_sm_model.history.fake or \
                info is not None and info.method_name not in ["insert_action", "undo", "redo", "reset"]:
            return

        self.doing_update = True
        self.history_tree_store.clear()
        self.list_tree_iter = {}
        trail_actions = [action.version_id for action in self._selected_sm_model.history.modifications.single_trail_history()]

        def insert_this_action(action, parent_tree_item, init_branch=False):
            """ The function insert a action with respective arguments (e.g. method_name, instance) into a TreeStore.
                - final trail or tree specific gtk-tree-levels -> 'trail' has no levels as well as 'branch' without tree
                - defines which element is marked as active
                - generate branch labels with version-id
            """
            model = action.before_overview['model'][-1]
            method_name = action.before_overview['method_name'][-1]
            instance = action.before_overview['instance'][-1]
            parameters = []
            tool_tip = None
            if action.before_overview['type'] == 'signal':
                if isinstance(action.before_overview['signal'][0], MetaSignalMsg):
                    # logger.info(action.before_overview._overview_dict)
                    parameters.append(str(action.meta))
                elif isinstance(action.before_overview['signal'][-1], ActionSignalMsg):
                    if action.action_type not in ['paste', 'cut']:
                        parameters.append(str(action.before_overview['signal'][-1].kwargs))
                else:
                    logger.warning("no parameters defined for signal: {0}".format(action.before_overview['signal']))
                    # for index, signal in enumerate(action.before_overview['signal']):
                    #     print("\n", index, signal)
            else:
                for index, value in enumerate(action.before_overview['args'][-1]):
                    if not index == 0:
                        parameters.append(str(value))
            for name, value in action.before_overview['kwargs'][-1].items():
                parameters.append("{0}: {1}".format(name, value))

            if hasattr(action, 'action_type') and action.action_type == "script_text" and hasattr(action, 'script_diff'):
                line = ""
                for elem in action.script_diff.split('\n'):
                    line = elem
                    if not line.replace(' ', '') == '' and (line.startswith('+') or line.startswith('-')):
                        break
                tool_tip = action.script_diff
                parameters = [line]  # + "\n -> [hover for source script diff in tooltip.]"]
            if hasattr(action, 'action_type') and action.action_type == "description" and hasattr(action, 'description_diff'):
                line = ""
                for elem in action.description_diff.split('\n'):
                    line = elem
                    if not line.replace(' ', '') == '' and (line.startswith('+') or line.startswith('-')):
                        break
                tool_tip = action.description_diff
                parameters = [line]  # + "\n -> [hover for source script diff in tooltip.]"]

            # find active actions in to be marked in view
            if self._mode == 'trail':
                active = len(self.history_tree_store) <= self._selected_sm_model.history.modifications.trail_pointer
            else:
                all_active = self._selected_sm_model.history.modifications.get_all_active_actions()
                active = action.version_id in all_active

            # generate label to mark branches
            version_label = action.version_id
            if init_branch:
                version_label = 'b.' + str(action.version_id)
                tool_tip = "The element '{0}' starts a new branch of actions.".format(version_label)

            tree_row_iter = self.new_change(model, str(method_name).replace('_', ' '), instance, info, version_label, active,
                                            parent_tree_item, ', '.join(parameters), tool_tip)
            self.list_tree_iter[action.version_id] = (tree_row_iter, parent_tree_item)
            return tree_row_iter

        def insert_all_next_actions(version_id, parent_tree_item=None):
            """ The function defines linkage of history-tree-elements in a gtk-tree-view to create a optimal overview.
            """
            if len(self._selected_sm_model.history.modifications.all_time_history) == 1:
                return
            next_id = version_id
            while next_id is not None:
                # print(next_id, len(self._selected_sm_model.history.modifications.all_time_history))
                version_id = next_id
                history_tree_elem = self._selected_sm_model.history.modifications.all_time_history[next_id]
                next_id = history_tree_elem.next_id
                prev_tree_elem = None
                if history_tree_elem.prev_id is not None:
                    prev_tree_elem = self._selected_sm_model.history.modifications.all_time_history[history_tree_elem.prev_id]
                action = history_tree_elem.action
                # logger.info("prev branch #{0} <-> {1}, trail_actions are {2}".format(history_tree_elem.action.version_id, prev_tree_elem, trail_actions))
                in_trail = history_tree_elem.action.version_id in trail_actions
                if in_trail:
                    # in trail parent is always None
                    if prev_tree_elem is not None and prev_tree_elem.old_next_ids:
                        child_tree_item = insert_this_action(action, None, init_branch=True)
                    else:
                        child_tree_item = insert_this_action(action, None)
                elif prev_tree_elem is not None and prev_tree_elem.old_next_ids:
                    # branch and not trail -> level + 1 ... child of prev_id -> parent_iter is prev_id_iter
                    prev_id_iter = self.list_tree_iter[prev_tree_elem.action.version_id][0]
                    child_tree_item = insert_this_action(action, prev_id_iter, init_branch=True)
                elif prev_tree_elem is not None and not prev_tree_elem.old_next_ids:
                    # no branch and not trail
                    prev_prev_tree_elem = self._selected_sm_model.history.modifications.all_time_history[prev_tree_elem.prev_id]
                    branch_limit_for_extra_ident_level = 1 if prev_tree_elem.prev_id in trail_actions else 0
                    if len(prev_prev_tree_elem.old_next_ids) > branch_limit_for_extra_ident_level:
                        # -> level + 1 as previous element, because to many branches -> so prev_id iter as parent_iter
                        iter_of_prev_id = self.list_tree_iter[prev_tree_elem.action.version_id][0]
                        child_tree_item = insert_this_action(action, iter_of_prev_id)
                    else:
                        # -> same level as previous element -> so same parent_iter as prev_id
                        parent_iter_of_prev_id = self.list_tree_iter[prev_tree_elem.action.version_id][1]
                        child_tree_item = insert_this_action(action, parent_iter_of_prev_id)
                else:
                    logger.warning("relative level could not be found -> this should not happen")
                    child_tree_item = insert_this_action(action, parent_tree_item)

                if history_tree_elem.old_next_ids and self._mode == 'branch':
                    old_next_ids = history_tree_elem.old_next_ids
                    for old_next_id in old_next_ids:
                        insert_all_next_actions(old_next_id, child_tree_item)

        insert_all_next_actions(version_id=0)

        # set selection of Tree
        if self._selected_sm_model.history.modifications.trail_pointer is not None and len(self.history_tree_store) > 1:
            searched_row_version_id = self._selected_sm_model.history.modifications.single_trail_history()[self._selected_sm_model.history.modifications.trail_pointer].version_id
            row_number = 0
            for action_entry in self.history_tree_store:
                # compare action.version_id
                if int(action_entry[1].split('.')[-1]) == searched_row_version_id:
                    self.view['history_tree'].set_cursor(row_number)
                    break
                row_number += 1

        # set colors of Tree
        # - is state full and all element which are open to be re-done gray
        self.doing_update = False

Response: This method updates the history of the treeview.


Instruction:
Can you tell what is the following Python 3 function doing
def exception_message(self) -> Union[str, None]:
        if self.has_error:
            exception_data = self._raw.get("exception", {})
            return exception_data.get("message")
        return None

Response: Return the exception message.


Instruction:
How would you implement a function in Python 3 that
executes a loadtracks request. Only works on Lavalink V3.

Response:
async def load_tracks(self, query) -> LoadResult:
        """
        Executes a loadtracks request. Only works on Lavalink V3.

        Parameters
        ----------
        query : str

        Returns
        -------
        LoadResult
        """
        self.__check_node_ready()
        url = self._uri + quote(str(query))

        data = await self._get(url)

        if isinstance(data, dict):
            return LoadResult(data)
        elif isinstance(data, list):
            modified_data = {
                "loadType": LoadType.V2_COMPAT,
                "tracks": data
            }
            return LoadResult(modified_data)


Instruction:
Can you implement a function in Python 3 that
gets tracks from lavalink.

Response:
async def get_tracks(self, query) -> Tuple[Track, ...]:
        """
        Gets tracks from lavalink.

        Parameters
        ----------
        query : str

        Returns
        -------
        Tuple[Track, ...]
        """
        if not self._warned:
            log.warn("get_tracks() is now deprecated. Please switch to using load_tracks().")
            self._warned = True
        result = await self.load_tracks(query)
        return result.tracks


Instruction:
Write a Python 3 script to
return a tuple which can be used for setup. py s data_files

Response:
def get_data_files_tuple(*rel_path, **kwargs):
    """Return a tuple which can be used for setup.py's data_files

    :param tuple path: List of path elements pointing to a file or a directory of files
    :param dict kwargs: Set path_to_file to True is `path` points to a file
    :return: tuple of install directory and list of source files
    :rtype: tuple(str, [str])
    """
    rel_path = os.path.join(*rel_path)
    target_path = os.path.join("share", *rel_path.split(os.sep)[1:])  # remove source/ (package_dir)
    if "path_to_file" in kwargs and kwargs["path_to_file"]:
        source_files = [rel_path]
        target_path = os.path.dirname(target_path)
    else:
        source_files = [os.path.join(rel_path, filename) for filename in os.listdir(rel_path)]
    return target_path, source_files


Instruction:
Write a Python 3 function for
adding all files of the specified path to a list of data files compatible

Response:
def get_data_files_recursively(*rel_root_path, **kwargs):
    """ Adds all files of the specified path to a data_files compatible list

    :param tuple rel_root_path: List of path elements pointing to a directory of files
    :return: list of tuples of install directory and list of source files
    :rtype: list(tuple(str, [str]))
    """
    result_list = list()
    rel_root_dir = os.path.join(*rel_root_path)
    share_target_root = os.path.join("share", kwargs.get("share_target_root", "rafcon"))
    distutils.log.debug("recursively generating data files for folder '{}' ...".format(
        rel_root_dir))

    for dir_, _, files in os.walk(rel_root_dir):
        relative_directory = os.path.relpath(dir_, rel_root_dir)
        file_list = list()
        for fileName in files:
            rel_file_path = os.path.join(relative_directory, fileName)
            abs_file_path = os.path.join(rel_root_dir, rel_file_path)
            file_list.append(abs_file_path)
        if len(file_list) > 0:
            # this is a valid path in ~/.local folder: e.g. share/rafcon/libraries/generic/wait
            target_path = os.path.join(share_target_root, relative_directory)
            result_list.append((target_path, file_list))
    return result_list


Instruction:
Explain what the following Python 3 code does
def generate_data_files():
    assets_folder = path.join('source', 'rafcon', 'gui', 'assets')
    share_folder = path.join(assets_folder, 'share')
    themes_folder = path.join(share_folder, 'themes', 'RAFCON')
    examples_folder = path.join('share', 'examples')
    libraries_folder = path.join('share', 'libraries')

    gui_data_files = [
        get_data_files_tuple(assets_folder, 'splashscreens'),
        get_data_files_tuple(assets_folder, 'fonts', 'FontAwesome'),
        get_data_files_tuple(assets_folder, 'fonts', 'Source Sans Pro'),
        get_data_files_tuple(themes_folder, 'gtk-3.0', 'gtk.css', path_to_file=True),
        get_data_files_tuple(themes_folder, 'gtk-3.0', 'gtk-dark.css', path_to_file=True),
        get_data_files_tuple(themes_folder, 'assets'),
        get_data_files_tuple(themes_folder, 'sass'),
        get_data_files_tuple(themes_folder, 'gtk-sourceview'),
        get_data_files_tuple(themes_folder, 'colors.json', path_to_file=True),
        get_data_files_tuple(themes_folder, 'colors-dark.json', path_to_file=True)
    ]
    # print("gui_data_files", gui_data_files)

    icon_data_files = get_data_files_recursively(path.join(share_folder, 'icons'), share_target_root="icons")
    # print("icon_data_files", icon_data_files)

    locale_data_files = create_mo_files()
    # example tuple
    # locale_data_files = [('share/rafcon/locale/de/LC_MESSAGES', ['source/rafcon/locale/de/LC_MESSAGES/rafcon.mo'])]
    # print("locale_data_files", locale_data_files)

    version_data_file = [("./", ["VERSION"])]
    desktop_data_file = [("share/applications", [path.join('share', 'applications', 'de.dlr.rm.RAFCON.desktop')])]

    examples_data_files = get_data_files_recursively(examples_folder, share_target_root=path.join("rafcon", "examples"))
    libraries_data_files = get_data_files_recursively(libraries_folder, share_target_root=path.join("rafcon",
                                                                                "libraries"))
    generated_data_files = gui_data_files + icon_data_files + locale_data_files + version_data_file + \
                           desktop_data_file + examples_data_files + libraries_data_files
    # for elem in generated_data_files:
    #     print(elem)
    return generated_data_files

Response: Generate the data_files list used in the setup function


Instruction:
Given the following Python 3 function, write the documentation
def extendable(network, args, line_max):

    """
    Function that sets selected components extendable

    'network' for all lines, links and transformers
    'german_network' for all lines, links and transformers located in Germany
    'foreign_network' for all foreign lines, links and transformers
    'transformers' for all transformers
    'storages' for extendable storages
    'overlay_network' for lines, links and trafos in extension scenerio(s)

    Parameters
    ----------
    network : :class:`pypsa.Network
        Overall container of PyPSA
    args  : dict
        Arguments set in appl.py

    Returns
    -------
    network : :class:`pypsa.Network
        Overall container of PyPSA
    """

    if 'network' in args['extendable']:
        network.lines.s_nom_extendable = True
        network.lines.s_nom_min = network.lines.s_nom

        if not line_max==None:
            network.lines.s_nom_max = line_max * network.lines.s_nom

        else:
            network.lines.s_nom_max = float("inf")

        if not network.transformers.empty:
            network.transformers.s_nom_extendable = True
            network.transformers.s_nom_min = network.transformers.s_nom

            if not line_max==None:
                network.transformers.s_nom_max =\
                line_max * network.transformers.s_nom

            else:
                network.transformers.s_nom_max = float("inf")

        if not network.links.empty:
            network.links.p_nom_extendable = True
            network.links.p_nom_min = network.links.p_nom
            network.links.p_nom_max = float("inf")
            if not line_max==None:
                network.links.p_nom_max=\
                line_max * network.links.p_nom

            else:
                network.links.p_nom_max = float("inf")

        network = set_line_costs(network, args)
        network = set_trafo_costs(network, args)

    if 'german_network' in args['extendable']:
        buses = network.buses[~network.buses.index.isin(
                buses_by_country(network).index)]
        network.lines.loc[(network.lines.bus0.isin(buses.index)) &
                          (network.lines.bus1.isin(buses.index)),
                          's_nom_extendable'] = True
        network.lines.loc[(network.lines.bus0.isin(buses.index)) &
                          (network.lines.bus1.isin(buses.index)),
                          's_nom_min'] = network.lines.s_nom
        network.lines.loc[(network.lines.bus0.isin(buses.index)) &
                          (network.lines.bus1.isin(buses.index)),
                          's_nom_max'] = float("inf")

        if not line_max==None:
            network.lines.loc[(network.lines.bus0.isin(buses.index)) &
                    (network.lines.bus1.isin(buses.index)),
                    's_nom_max'] = line_max * network.lines.s_nom

        else:
            network.lines.loc[(network.lines.bus0.isin(buses.index)) &
                    (network.lines.bus1.isin(buses.index)),
                    's_nom_max'] = float("inf")

        if not network.transformers.empty:
            network.transformers.loc[network.transformers.bus0.isin(
                    buses.index),'s_nom_extendable'] = True
            network.transformers.loc[network.transformers.bus0.isin(
                    buses.index),'s_nom_min'] = network.transformers.s_nom

            if not line_max==None:
                network.transformers.loc[network.transformers.bus0.isin(
                    buses.index),'s_nom_max'] = \
                line_max * network.transformers.s_nom

            else:
                network.transformers.loc[network.transformers.bus0.isin(
                    buses.index),'s_nom_max'] = float("inf")

        if not network.links.empty:
            network.links.loc[(network.links.bus0.isin(buses.index)) &
                              (network.links.bus1.isin(buses.index)),
                              'p_nom_extendable'] = True
            network.links.loc[(network.links.bus0.isin(buses.index)) &
                              (network.links.bus1.isin(buses.index)),
                          'p_nom_min'] = network.links.p_nom

            if not line_max==None:
                network.links.loc[(network.links.bus0.isin(buses.index)) &
                        (network.links.bus1.isin(buses.index)),
                          'p_nom_max'] = line_max * network.links.p_nom

            else:
                network.links.loc[(network.links.bus0.isin(buses.index)) &
                        (network.links.bus1.isin(buses.index)),
                          'p_nom_max'] = float("inf")

        network = set_line_costs(network, args)
        network = set_trafo_costs(network, args)

    if 'foreign_network' in args['extendable']:
        buses = network.buses[network.buses.index.isin(
                buses_by_country(network).index)]
        network.lines.loc[network.lines.bus0.isin(buses.index) |
                          network.lines.bus1.isin(buses.index) ,
                          's_nom_extendable'] = True
        network.lines.loc[network.lines.bus0.isin(buses.index) |
                          network.lines.bus1.isin(buses.index),
                          's_nom_min'] = network.lines.s_nom

        if not line_max==None:
            network.lines.loc[network.lines.bus0.isin(buses.index) |
                          network.lines.bus1.isin(buses.index),
                    's_nom_max'] = line_max * network.lines.s_nom

        else:
            network.lines.loc[network.lines.bus0.isin(buses.index) |
                          network.lines.bus1.isin(buses.index),
                    's_nom_max'] = float("inf")

        if not network.transformers.empty:
            network.transformers.loc[network.transformers.bus0.isin(
                    buses.index) | network.transformers.bus1.isin(
                    buses.index) ,'s_nom_extendable'] = True
            network.transformers.loc[network.transformers.bus0.isin(
                    buses.index) | network.transformers.bus1.isin(
                    buses.index) ,'s_nom_min'] = network.transformers.s_nom

            if not line_max==None:
                network.transformers.loc[network.transformers.bus0.isin(
                    buses.index) | network.transformers.bus1.isin(
                    buses.index),'s_nom_max'] = \
                line_max * network.transformers.s_nom

            else:
                network.transformers.loc[network.transformers.bus0.isin(
                    buses.index) | network.transformers.bus1.isin(
                    buses.index),'s_nom_max'] = float("inf")

        if not network.links.empty:
            network.links.loc[(network.links.bus0.isin(buses.index)) |
                              (network.links.bus1.isin(buses.index)),
                          'p_nom_extendable'] = True
            network.links.loc[(network.links.bus0.isin(buses.index)) |
                              (network.links.bus1.isin(buses.index)),
                          'p_nom_min'] = network.links.p_nom

            if not line_max==None:
                network.links.loc[(network.links.bus0.isin(buses.index)) |
                              (network.links.bus1.isin(buses.index)),
                          'p_nom_max'] = line_max * network.links.p_nom

            else:
                network.links.loc[(network.links.bus0.isin(buses.index)) |
                              (network.links.bus1.isin(buses.index)),
                          'p_nom_max'] = float("inf")

        network = set_line_costs(network, args)
        network = set_trafo_costs(network, args)

    if 'transformers' in args['extendable']:
        network.transformers.s_nom_extendable = True
        network.transformers.s_nom_min = network.transformers.s_nom
        network.transformers.s_nom_max = float("inf")
        network = set_trafo_costs(network)

    if 'storages' in args['extendable'] or 'storage' in args['extendable']:
        if network.storage_units.\
            carrier[network.
                    storage_units.carrier ==
                    'extendable_storage'].any() == 'extendable_storage':
            network.storage_units.loc[network.storage_units.carrier ==
                                      'extendable_storage',
                                      'p_nom_extendable'] = True

    if 'generators' in args['extendable']:
        network.generators.p_nom_extendable = True
        network.generators.p_nom_min = network.generators.p_nom
        network.generators.p_nom_max = float("inf")

    if 'foreign_storage' in args['extendable']:
        network.storage_units.p_nom_extendable[(network.storage_units.bus.isin(
                network.buses.index[network.buses.country_code != 'DE'])) & (
                network.storage_units.carrier.isin(
                        ['battery_storage','hydrogen_storage'] ))] = True

        network.storage_units.loc[
                network.storage_units.p_nom_max.isnull(),'p_nom_max'] = \
                network.storage_units.p_nom

        network.storage_units.loc[
                (network.storage_units.carrier == 'battery_storage'),
                'capital_cost'] = network.storage_units.loc[(
                network.storage_units.carrier == 'extendable_storage')
                & (network.storage_units.max_hours == 6),'capital_cost'].max()

        network.storage_units.loc[
                (network.storage_units.carrier == 'hydrogen_storage'),
                'capital_cost'] = network.storage_units.loc[(
                network.storage_units.carrier == 'extendable_storage') &
                (network.storage_units.max_hours == 168),'capital_cost'].max()

        network.storage_units.loc[
                (network.storage_units.carrier == 'battery_storage'),
                'marginal_cost'] = network.storage_units.loc[(
                network.storage_units.carrier == 'extendable_storage')
                & (network.storage_units.max_hours == 6),'marginal_cost'].max()

        network.storage_units.loc[
                (network.storage_units.carrier == 'hydrogen_storage'),
                'marginal_cost'] = network.storage_units.loc[(
                network.storage_units.carrier == 'extendable_storage') &
                (network.storage_units.max_hours == 168),'marginal_cost'].max()

    # Extension settings for extension-NEP 2035 scenarios
    if 'NEP Zubaunetz' in args['extendable']:
        for i in range(len(args['scn_extension'])):
            network.lines.loc[(network.lines.project != 'EnLAG') & (
            network.lines.scn_name == 'extension_' + args['scn_extension'][i]),
            's_nom_extendable'] = True

            network.transformers.loc[(
                    network.transformers.project != 'EnLAG') & (
                            network.transformers.scn_name == (
                                    'extension_'+ args['scn_extension'][i])),
                                        's_nom_extendable'] = True

            network.links.loc[network.links.scn_name == (
            'extension_' + args['scn_extension'][i]
            ), 'p_nom_extendable'] = True

    if 'overlay_network' in args['extendable']:
        for i in range(len(args['scn_extension'])):
            network.lines.loc[network.lines.scn_name == (
            'extension_' + args['scn_extension'][i]
            ), 's_nom_extendable'] = True

            network.lines.loc[network.lines.scn_name == (
            'extension_' + args['scn_extension'][i]
            ), 's_nom_max'] = network.lines.s_nom[network.lines.scn_name == (
            'extension_' + args['scn_extension'][i])]

            network.links.loc[network.links.scn_name == (
            'extension_' + args['scn_extension'][i]
            ), 'p_nom_extendable'] = True

            network.transformers.loc[network.transformers.scn_name == (
            'extension_' + args['scn_extension'][i]
            ), 's_nom_extendable'] = True

            network.lines.loc[network.lines.scn_name == (
            'extension_' + args['scn_extension'][i]
            ), 'capital_cost'] = network.lines.capital_cost/\
                args['branch_capacity_factor']['eHV']

    if 'overlay_lines' in args['extendable']:
        for i in range(len(args['scn_extension'])):
            network.lines.loc[network.lines.scn_name == (
            'extension_' + args['scn_extension'][i]
            ), 's_nom_extendable'] = True

            network.links.loc[network.links.scn_name == (
            'extension_' + args['scn_extension'][i]
            ), 'p_nom_extendable'] = True

            network.lines.loc[network.lines.scn_name == (
            'extension_' + args['scn_extension'][i]),
                'capital_cost'] = network.lines.capital_cost + (2 * 14166)

    network.lines.s_nom_min[network.lines.s_nom_extendable == False] =\
        network.lines.s_nom

    network.transformers.s_nom_min[network.transformers.s_nom_extendable == \
        False] = network.transformers.s_nom

    network.lines.s_nom_max[network.lines.s_nom_extendable == False] =\
        network.lines.s_nom

    network.transformers.s_nom_max[network.transformers.s_nom_extendable == \
        False] = network.transformers.s_nom

    return network

Response: Function that sets the extendable flag of the given PyPSA network.


Instruction:
Implement a Python 3 function for
functioning that returns a new set of extension variables that are used to reduce nubmer of extension variables.

Response:
def extension_preselection(network, args, method, days = 3):

    """
    Function that preselects lines which are extendend in snapshots leading to
    overloading to reduce nubmer of extension variables.

    Parameters
    ----------
    network : :class:`pypsa.Network
        Overall container of PyPSA
    args  : dict
        Arguments set in appl.py
    method: str
        Choose method of selection:
        'extreme_situations' for remarkable timsteps
        (e.g. minimal resiudual load)
        'snapshot_clustering' for snapshot clustering with number of days
    days: int
        Number of clustered days, only used when method = 'snapshot_clustering'

    Returns
    -------
    network : :class:`pypsa.Network
        Overall container of PyPSA
    """

    weighting = network.snapshot_weightings

    if method == 'extreme_situations':
        snapshots = find_snapshots(network, 'residual load')
        snapshots = snapshots.append(find_snapshots(network, 'wind_onshore'))
        snapshots = snapshots.append(find_snapshots(network, 'solar'))
        snapshots = snapshots.drop_duplicates()
        snapshots = snapshots.sort_values()

    if method == 'snapshot_clustering':
        network_cluster = snapshot_clustering(network, how='daily',
                                              clusters=days)
        snapshots = network_cluster.snapshots
        network.snapshot_weightings = network_cluster.snapshot_weightings

    # Set all lines and trafos extendable in network
    network.lines.loc[:, 's_nom_extendable'] = True
    network.lines.loc[:, 's_nom_min'] = network.lines.s_nom
    network.lines.loc[:, 's_nom_max'] = np.inf

    network.links.loc[:, 'p_nom_extendable'] = True
    network.links.loc[:, 'p_nom_min'] = network.links.p_nom
    network.links.loc[:, 'p_nom_max'] = np.inf

    network.transformers.loc[:, 's_nom_extendable'] = True
    network.transformers.loc[:, 's_nom_min'] = network.transformers.s_nom
    network.transformers.loc[:, 's_nom_max'] = np.inf

    network = set_line_costs(network)
    network = set_trafo_costs(network)
    network = convert_capital_costs(network, 1, 1)
    extended_lines = network.lines.index[network.lines.s_nom_opt >
                                         network.lines.s_nom]
    extended_links = network.links.index[network.links.p_nom_opt >
                                         network.links.p_nom]

    x = time.time()
    for i in range(int(snapshots.value_counts().sum())):
        if i > 0:
            network.lopf(snapshots[i], solver_name=args['solver'])
            extended_lines = extended_lines.append(
                    network.lines.index[network.lines.s_nom_opt >
                                        network.lines.s_nom])
            extended_lines = extended_lines.drop_duplicates()
            extended_links = extended_links.append(
                    network.links.index[network.links.p_nom_opt >
                                        network.links.p_nom])
            extended_links = extended_links.drop_duplicates()

    print("Number of preselected lines: ", len(extended_lines))

    network.lines.loc[~network.lines.index.isin(extended_lines),
                      's_nom_extendable'] = False
    network.lines.loc[network.lines.s_nom_extendable, 's_nom_min']\
        = network.lines.s_nom
    network.lines.loc[network.lines.s_nom_extendable, 's_nom_max']\
        = np.inf

    network.links.loc[~network.links.index.isin(extended_links),
                      'p_nom_extendable'] = False
    network.links.loc[network.links.p_nom_extendable, 'p_nom_min']\
        = network.links.p_nom
    network.links.loc[network.links.p_nom_extendable, 'p_nom_max']\
        = np.inf

    network.snapshot_weightings = weighting
    network = set_line_costs(network)
    network = set_trafo_costs(network)
    network = convert_capital_costs(network, args['start_snapshot'],
                                    args['end_snapshot'])

    y = time.time()
    z1st = (y - x) / 60

    print("Time for first LOPF [min]:", round(z1st, 2))

    return network


Instruction:
Here you have a function in Python 3, explain what it does
def handle(self, event):
        # Allow to handle a subset of events while having a grabbed tool (between a button press & release event)
        suppressed_grabbed_tool = None
        if event.type in (Gdk.EventType.SCROLL, Gdk.EventType.KEY_PRESS, Gdk.EventType.KEY_RELEASE):
            suppressed_grabbed_tool = self._grabbed_tool
            self._grabbed_tool = None

        rt = super(ToolChain, self).handle(event)

        if suppressed_grabbed_tool:
            self._grabbed_tool = suppressed_grabbed_tool

        return rt

Response: Handle the event by calling each tool until the event is handled by calling each tool until the event is grabbed.


Instruction:
Can you create a Python 3 function that
filters selection Filter items that cannot be moved and return the rest.

Response:
def movable_items(self):
        """Filter selection

        Filter items of selection that cannot be moved (i.e. are not instances of `Item`) and return the rest.
        """
        view = self.view

        if self._move_name_v:
            yield InMotion(self._item, view)
        else:
            selected_items = set(view.selected_items)
            for item in selected_items:
                if not isinstance(item, Item):
                    continue
                yield InMotion(item, view)


Instruction:
Make a summary of the following Python 3 code
def on_button_press(self, event):
        if event.get_button()[1] not in self._buttons:
            return False  # Only handle events for registered buttons (left mouse clicks)

        if event.get_state()[1] & constants.RUBBERBAND_MODIFIER:
            return False  # Mouse clicks with pressed shift key are handled in another tool

        # Special case: moving the NameView
        # This is only allowed, if the hovered item is a NameView and the Ctrl-key is pressed and the only selected
        # item is the parental StateView. In this case, the selection and _item will no longer be looked at,
        # but only _move_name_v
        self._item = self.get_item()
        if isinstance(self._item, NameView):
            selected_items = self.view.selected_items
            if event.get_state()[1] & Gdk.ModifierType.CONTROL_MASK and len(selected_items) == 1 and next(iter(selected_items)) is \
                    self._item.parent:
                self._move_name_v = True
            else:
                self._item = self._item.parent

        if not self._move_name_v:
            self._old_selection = self.view.selected_items
            if self._item not in self.view.selected_items:
                # When items are to be moved, a button-press should not cause any deselection.
                # However, the selection is stored, in case no move operation is performed.
                self.view.handle_new_selection(self._item)

        if not self.view.is_focus():
            self.view.grab_focus()

        return True

Response: Handles the mouse button press event.


Instruction:
Explain what the following Python 3 code does
def on_button_release(self, event):
        affected_models = {}

        for inmotion in self._movable_items:
            inmotion.move((event.x, event.y))
            rel_pos = gap_helper.calc_rel_pos_to_parent(self.view.canvas, inmotion.item,
                                                        inmotion.item.handles()[NW])
            if isinstance(inmotion.item, StateView):
                state_v = inmotion.item
                state_m = state_v.model
                self.view.canvas.request_update(state_v)
                if state_m.get_meta_data_editor()['rel_pos'] != rel_pos:
                    state_m.set_meta_data_editor('rel_pos', rel_pos)
                    affected_models[state_m] = ("position", True, state_v)
            elif isinstance(inmotion.item, NameView):
                state_v = inmotion.item
                state_m = self.view.canvas.get_parent(state_v).model
                self.view.canvas.request_update(state_v)
                if state_m.get_meta_data_editor()['name']['rel_pos'] != rel_pos:
                    state_m.set_meta_data_editor('name.rel_pos', rel_pos)
                    affected_models[state_m] = ("name_position", False, state_v)
            elif isinstance(inmotion.item, TransitionView):
                transition_v = inmotion.item
                transition_m = transition_v.model
                self.view.canvas.request_update(transition_v)
                current_waypoints = gap_helper.get_relative_positions_of_waypoints(transition_v)
                old_waypoints = transition_m.get_meta_data_editor()['waypoints']
                if current_waypoints != old_waypoints:
                    transition_m.set_meta_data_editor('waypoints', current_waypoints)
                    affected_models[transition_m] = ("waypoints", False, transition_v)

        if len(affected_models) == 1:
            model = next(iter(affected_models))
            change, affects_children, view = affected_models[model]
            self.view.graphical_editor.emit('meta_data_changed', model, change, affects_children)
        elif len(affected_models) > 1:
            # if more than one item has been moved, we need to call the meta_data_changed signal on a common parent
            common_parents = None
            for change, affects_children, view in affected_models.values():
                parents_of_view = set(self.view.canvas.get_ancestors(view))
                if common_parents is None:
                    common_parents = parents_of_view
                else:
                    common_parents = common_parents.intersection(parents_of_view)
            assert len(common_parents) > 0, "The selected elements do not have common parent element"
            for state_v in common_parents:
                # Find most nested state_v
                children_of_state_v = self.view.canvas.get_all_children(state_v)
                if any(common_parent in children_of_state_v for common_parent in common_parents):
                    continue
                self.view.graphical_editor.emit('meta_data_changed', state_v.model, "positions", True)
                break

        if not affected_models and self._old_selection is not None:
            # The selection is handled differently depending on whether states were moved or not
            # If no move operation was performed, we reset the selection to that is was before the button-press event
            # and let the state machine selection handle the selection
            self.view.unselect_all()
            self.view.select_item(self._old_selection)
            self.view.handle_new_selection(self._item)

        self._move_name_v = False
        self._old_selection = None
        return super(MoveItemTool, self).on_button_release(event)

Response: Write back changes for the items in the current language.


Instruction:
Make a summary of the following Python 3 code
def _filter_library_state(self, items):
        if not items:
            return items

        top_most_item = items[0]
        # If the hovered item is e.g. a connection, we need to get the parental state
        top_most_state_v = top_most_item if isinstance(top_most_item, StateView) else top_most_item.parent
        state = top_most_state_v.model.state

        global_gui_config = gui_helper_state_machine.global_gui_config
        if global_gui_config.get_config_value('STATE_SELECTION_INSIDE_LIBRARY_STATE_ENABLED'):
            # select the library state instead of the library_root_state because it is hidden
            if state.is_root_state_of_library:
                new_topmost_item = self.view.canvas.get_view_for_core_element(state.parent)
                return self.dismiss_upper_items(items, new_topmost_item)
            return items
        else:
            # Find state_copy of uppermost LibraryState
            library_root_state = state.get_uppermost_library_root_state()

            # If the hovered element is a child of a library, make the library the hovered_item
            if library_root_state:
                library_state = library_root_state.parent
                library_state_v = self.view.canvas.get_view_for_core_element(library_state)
                return self.dismiss_upper_items(items, library_state_v)
            return items

Response: Filter out child elements of library state when they cannot be hovered


Instruction:
Given the following Python 3 function, write the documentation
def _filter_hovered_items(self, items, event):
        items = self._filter_library_state(items)
        if not items:
            return items
        top_most_item = items[0]
        second_top_most_item = items[1] if len(items) > 1 else None

        # States/Names take precedence over connections if the connections are on the same hierarchy and if there is
        # a port beneath the cursor
        first_state_v = next(filter(lambda item: isinstance(item, (NameView, StateView)), items))
        first_state_v = first_state_v.parent if isinstance(first_state_v, NameView) else first_state_v
        if first_state_v:
            # There can be several connections above the state/name skip those and find the first non-connection-item
            for item in items:
                if isinstance(item, ConnectionView):
                    # connection is on the same hierarchy level as the state/name, thus we dismiss it
                    if self.view.canvas.get_parent(top_most_item) is not first_state_v:
                        continue
                break

            # Connections are only dismissed, if there is a port beneath the cursor. Search for ports here:
            port_beneath_cursor = False
            state_ports = first_state_v.get_all_ports()
            position = self.view.get_matrix_v2i(first_state_v).transform_point(event.x, event.y)
            i2v_matrix = self.view.get_matrix_i2v(first_state_v)
            for port_v in state_ports:
                item_distance = port_v.port.glue(position)[1]
                view_distance = i2v_matrix.transform_distance(item_distance, 0)[0]
                if view_distance == 0:
                    port_beneath_cursor = True
                    break

            if port_beneath_cursor:
                items = self.dismiss_upper_items(items, item)
                top_most_item = items[0]
                second_top_most_item = items[1] if len(items) > 1 else None

        # NameView can only be hovered if it or its parent state is selected
        if isinstance(top_most_item, NameView):
            state_v = second_top_most_item  # second item in the list must be the parent state of the NameView
            if state_v not in self.view.selected_items and top_most_item not in self.view.selected_items:
                items = items[1:]

        return items

Response: Filter out items that cannot be hovered