Instruction:
Can you generate the documentation for the following Python 3 function
def is_locked(self, key):
        key = str(key)
        if key in self.__variable_locks:
            return self.__variable_locks[key].locked()
        return False

Response: Returns the status of the lock of a global variable


Instruction:
Can you generate the documentation for the following Python 3 function
def get_all_keys_starting_with(self, start_key):
        start_key = str(start_key)
        output_list = []
        if len(self.__global_variable_dictionary) == 0:
            return output_list
        for g_key in self.__global_variable_dictionary.keys():
            # string comparison
            if g_key and start_key in g_key:
                output_list.append(g_key)
        return output_list

Response: Returns all keys which start with a certain pattern defined in start_key.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def global_variable_dictionary(self):
        dict_copy = {}
        for key, value in self.__global_variable_dictionary.items():
            if key in self.__variable_references and self.__variable_references[key]:
                dict_copy[key] = value
            else:
                dict_copy[key] = copy.deepcopy(value)

        return dict_copy

Response: Property for the _global_variable_dictionary field


Instruction:
Can you create a Python 3 function that
checks if a given value is of a specific type

Response:
def check_value_and_type(value, data_type):
        """Checks if a given value is of a specific type

        :param value: the value to check
        :param data_type: the type to be checked upon
        :return:
        """
        if value is not None and data_type is not type(None):
            # if not isinstance(value, data_type):
            if not type_inherits_of_type(data_type, type(value)):
                raise TypeError(
                    "Value: '{0}' is not of data type: '{1}', value type: {2}".format(value, data_type, type(value)))


Instruction:
Make a summary of the following Python 3 code
def glue(self, pos):
        # Distance between border of rectangle and point
        # Equation from http://stackoverflow.com/a/18157551/3568069
        dx = max(self.point.x - self.width / 2. - pos[0], 0, pos[0] - (self.point.x + self.width / 2.))
        dy = max(self.point.y - self.height / 2. - pos[1], 0, pos[1] - (self.point.y + self.height / 2.))
        dist = sqrt(dx*dx + dy*dy)
        return self.point, dist

Response: Calculates the distance between the given position and the port


Instruction:
How would you explain what the following Python 3 function does
def format_time(time):
    h, r = divmod(time / 1000, 3600)
    m, s = divmod(r, 60)

    return "%02d:%02d:%02d" % (h, m, s)

Response: Formats the given time into HHMMSS format.


Instruction:
Explain what the following Python 3 code does
def __destroy(self):
        if self.parent:
            self.parent.remove_controller(self)
        else:
            self.destroy()

Response: Remove controller from parent controller and destroy it self.


Instruction:
Explain what the following Python 3 code does
def register_view(self, view):
        super(PreferencesWindowController, self).register_view(view)
        self.view['add_library_button'].connect('clicked', self._on_add_library)
        self.view["remove_library_button"].connect('clicked', self._on_remove_library)

        self.view['config_tree_view'].connect("button_press_event", self._on_row_clicked_trigger_toggle_of_boolean,
                                              self.core_config_model, self.core_list_store)
        self.view['gui_tree_view'].connect("button_press_event", self._on_row_clicked_trigger_toggle_of_boolean,
                                           self.gui_config_model, self.gui_list_store)

        self.view['core_config_value_renderer'].set_property('editable', True)
        self.view['core_config_value_renderer'].connect('edited', self._on_config_value_changed, self.core_config_model,
                                                        self.core_list_store)

        self.view['gui_config_value_renderer'].set_property('editable', True)
        self.view['gui_config_value_renderer'].connect('edited', self._on_config_value_changed, self.gui_config_model,
                                                       self.gui_list_store)

        self.view['shortcut_config_value_renderer'].set_property('editable', True)
        self.view['shortcut_config_value_renderer'].connect('edited', self._on_shortcut_changed)

        self.view['library_config_key_renderer'].set_property('editable', True)
        self.view['library_config_key_renderer'].connect('edited', self._on_library_name_changed)

        self.view['library_config_value_renderer'].set_property('editable', True)
        self.view['library_config_value_renderer'].connect('edited', self._on_library_path_changed)

        self.view['config_tree_view'].set_model(self.core_list_store)
        self.view['library_tree_view'].set_model(self.library_list_store)
        self.view['gui_tree_view'].set_model(self.gui_list_store)
        self.view['shortcut_tree_view'].set_model(self.shortcut_list_store)

        self.view['apply_button'].connect("clicked", self._on_apply_button_clicked)
        self.view['ok_button'].connect('clicked', self._on_ok_button_clicked)
        self.view['cancel_button'].connect('clicked', self._on_cancel_button_clicked)

        self.view['import_button'].connect("clicked", self._on_import_config)
        self.view['export_button'].connect('clicked', self._on_export_config)

        self.view['preferences_window'].connect('delete_event', self._on_delete_event)

        self.update_all()

Response: Called when the View was registered


Instruction:
Implement a Python 3 function for
handling changes in config values

Response:
def _handle_config_update(self, config_m, config_key):
        """Handles changes in config values

        The method ensure that the correct list stores are updated with the new values.

        :param ConfigModel config_m: The config model that has been changed
        :param config_key: The config key who's value has been changed
        :return:
        """
        if config_key == "LIBRARY_PATHS":
            self.update_libraries_list_store()
        if config_key == "SHORTCUTS":
            self.update_shortcut_settings()
        else:
            self.update_config_value(config_m, config_key)


Instruction:
Can you generate the documentation for the following Python 3 function
def update_all(self):
        self.update_path_labels()
        self.update_core_config_list_store()
        self.update_gui_config_list_store()
        self.update_libraries_list_store()
        self.update_shortcut_settings()
        self.check_for_preliminary_config()

Response: Shorthand method to update all collection information


Instruction:
Given the following Python 3 function, write the documentation
def check_for_preliminary_config(self):
        if any([self.model.preliminary_config, self.gui_config_model.preliminary_config]):
            self.view['apply_button'].set_sensitive(True)
        else:
            self.view['apply_button'].set_sensitive(False)

Response: Activates the Apply button if there are preliminary changes


Instruction:
Can you write a function in Python 3 where it
updates labels showing config paths

Response:
def update_path_labels(self):
        """Update labels showing config paths
        """
        self.view['core_label'].set_text("Core Config Path: " + str(self.core_config_model.config.config_file_path))
        self.view['gui_label'].set_text("GUI Config Path: " + str(self.gui_config_model.config.config_file_path))


Instruction:
Explain what the following Python 3 code does
def update_config_value(self, config_m, config_key):
        config_value = config_m.get_current_config_value(config_key)
        if config_m is self.core_config_model:
            list_store = self.core_list_store
        elif config_m is self.gui_config_model:
            list_store = self.gui_list_store
        else:
            return
        self._update_list_store_entry(list_store, config_key, config_value)

Response: Updates the corresponding list store entry for a changed config value


Instruction:
Here you have a function in Python 3, explain what it does
def _update_list_store_entry(self, list_store, config_key, config_value):
        for row_num, row in enumerate(list_store):
            if row[self.KEY_STORAGE_ID] == config_key:
                row[self.VALUE_STORAGE_ID] = str(config_value)
                row[self.TOGGLE_VALUE_STORAGE_ID] = config_value
                return row_num

Response: Helper method to update a list store entry


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _update_list_store(config_m, list_store, ignore_keys=None):
        ignore_keys = [] if ignore_keys is None else ignore_keys
        list_store.clear()
        for config_key in sorted(config_m.config.keys):
            if config_key in ignore_keys:
                continue
            config_value = config_m.get_current_config_value(config_key)
            # (config_key, text, text_visible, toggle_activatable, toggle_visible, text_editable, toggle_state)
            if isinstance(config_value, bool):
                list_store.append((str(config_key), str(config_value), False, True, True, False, config_value))
            else:
                list_store.append((str(config_key), str(config_value), True, False, False, True, config_value))

Response: Generic method to update list store for a given config model


Instruction:
How would you explain what the following Python 3 function does
def update_libraries_list_store(self):
        self.library_list_store.clear()
        libraries = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True, default={})
        library_names = sorted(libraries.keys())
        for library_name in library_names:
            library_path = libraries[library_name]
            self.library_list_store.append((library_name, library_path))

Response: Updates the list store for the libraries that are currently loaded.


Instruction:
Can you write a function in Python 3 where it
updates the list store for the shortcuts

Response:
def update_shortcut_settings(self):
        """Creates the list store for the shortcuts
        """
        self.shortcut_list_store.clear()
        shortcuts = self.gui_config_model.get_current_config_value("SHORTCUTS", use_preliminary=True, default={})
        actions = sorted(shortcuts.keys())
        for action in actions:
            keys = shortcuts[action]
            self.shortcut_list_store.append((str(action), str(keys)))


Instruction:
Explain what the following Python 3 code does
def _select_row_by_column_value(tree_view, list_store, column, value):
        for row_num, iter_elem in enumerate(list_store):
            if iter_elem[column] == value:
                tree_view.set_cursor(row_num)
                return row_num

Response: Helper method to select a tree view row by column value


Instruction:
Can you generate the documentation for the following Python 3 function
def _on_add_library(self, *event):
        self.view['library_tree_view'].grab_focus()
        if react_to_event(self.view, self.view['library_tree_view'], event):
            temp_library_name = "<LIB_NAME_%s>" % self._lib_counter
            self._lib_counter += 1
            library_config = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True,
                                                                             default={})
            library_config[temp_library_name] = "<LIB_PATH>"
            self.core_config_model.set_preliminary_config_value("LIBRARY_PATHS", library_config)
            self._select_row_by_column_value(self.view['library_tree_view'], self.library_list_store,
                                             self.KEY_STORAGE_ID, temp_library_name)
            return True

Response: Callback method handling the addition of a new library


Instruction:
Given the following Python 3 function, write the documentation
def _on_remove_library(self, *event):
        self.view['library_tree_view'].grab_focus()
        if react_to_event(self.view, self.view['library_tree_view'], event):
            path = self.view["library_tree_view"].get_cursor()[0]
            if path is not None:
                library_name = self.library_list_store[int(path[0])][0]
                library_config = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True,
                                                                                default={})
                del library_config[library_name]
                self.core_config_model.set_preliminary_config_value("LIBRARY_PATHS", library_config)
                if len(self.library_list_store) > 0:
                    self.view['library_tree_view'].set_cursor(min(path[0], len(self.library_list_store) - 1))
            return True

Response: Callback method handling the removal of an existing library


Instruction:
Explain what the following Python 3 code does
def _on_checkbox_toggled(self, renderer, path, config_m, config_list_store):
        config_key = config_list_store[int(path)][self.KEY_STORAGE_ID]
        config_value = bool(config_list_store[int(path)][self.TOGGLE_VALUE_STORAGE_ID])
        config_value ^= True
        config_m.set_preliminary_config_value(config_key, config_value)

Response: Callback method that is called when a checkbox is toggled


Instruction:
Can you implement a function in Python 3 that
applies the configurations and closes the window

Response:
def _on_ok_button_clicked(self, *args):
        """OK button clicked: Applies the configurations and closes the window
        """
        if self.core_config_model.preliminary_config or self.gui_config_model.preliminary_config:
            self._on_apply_button_clicked()
        self.__destroy()


Instruction:
Write a Python 3 function that can
dismiss preliminary config and close the window

Response:
def _on_cancel_button_clicked(self, *args):
        """Cancel button clicked: Dismiss preliminary config and close the window
        """
        self.core_config_model.preliminary_config.clear()
        self.gui_config_model.preliminary_config.clear()
        self.__destroy()


Instruction:
Here you have a function in Python 3, explain what it does
def _on_apply_button_clicked(self, *args):
        refresh_required = self.core_config_model.apply_preliminary_config()
        refresh_required |= self.gui_config_model.apply_preliminary_config()

        if not self.gui_config_model.config.get_config_value("SESSION_RESTORE_ENABLED"):
            import rafcon.gui.backup.session as backup_session
            logger.info("Removing current session")
            backup_session.reset_session()
        if refresh_required:
            from rafcon.gui.singleton import main_window_controller
            main_window_controller.get_controller('menu_bar_controller').on_refresh_all_activate(None, None)
        self._popup_message()

Response: Apply button clicked: Apply the configuration


Instruction:
Here you have a function in Python 3, explain what it does
def _on_shortcut_changed(self, renderer, path, new_shortcuts):
        action = self.shortcut_list_store[int(path)][self.KEY_STORAGE_ID]
        old_shortcuts = self.gui_config_model.get_current_config_value("SHORTCUTS", use_preliminary=True)[action]

        from ast import literal_eval
        try:
            new_shortcuts = literal_eval(new_shortcuts)
            if not isinstance(new_shortcuts, list) and \
               not all([isinstance(shortcut, string_types) for shortcut in new_shortcuts]):
                raise ValueError()
        except (ValueError, SyntaxError):
            logger.warning("Shortcuts must be a list of strings")
            new_shortcuts = old_shortcuts

        shortcuts = self.gui_config_model.get_current_config_value("SHORTCUTS", use_preliminary=True,  default={})
        shortcuts[action] = new_shortcuts
        self.gui_config_model.set_preliminary_config_value("SHORTCUTS", shortcuts)
        self._select_row_by_column_value(self.view['shortcut_tree_view'], self.shortcut_list_store,
                                         self.KEY_STORAGE_ID, action)

Response: Callback for when a new entry in the list store has changed


Instruction:
Can you tell what is the following Python 3 function doing
def _on_config_value_changed(self, renderer, path, new_value, config_m, list_store):
        config_key = list_store[int(path)][self.KEY_STORAGE_ID]
        old_value = config_m.get_current_config_value(config_key, use_preliminary=True)

        if old_value == new_value:
            return

        # Try to maintain the correct data type, which is extracted from the old value
        if isinstance(old_value, bool):
            if new_value in ["True", "true"]:
                new_value = True
            elif new_value in ["False", "false"]:
                new_value = False
            else:
                logger.warning("'{}' must be a boolean value".format(config_key))
                new_value = old_value
        elif isinstance(old_value, (int, float)):
            try:
                new_value = int(new_value)
            except ValueError:
                try:
                    new_value = float(new_value)
                except ValueError:
                    logger.warning("'{}' must be a numeric value".format(config_key))
                    new_value = old_value

        config_m.set_preliminary_config_value(config_key, new_value)

Response: Callback for when a config value is changed


Instruction:
Can you tell what is the following Python 3 function doing
def _config_chooser_dialog(self, title_text, description):
        dialog = Gtk.Dialog(title_text, self.view["preferences_window"],
                            flags=0, buttons=
                            (Gtk.STOCK_CANCEL, Gtk.ResponseType.REJECT,
                             Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT))
        label = Gtk.Label(label=description)
        label.set_padding(xpad=10, ypad=10)
        dialog.vbox.pack_start(label, True, True, 0)
        label.show()
        self._gui_checkbox = Gtk.CheckButton(label="GUI Config")
        dialog.vbox.pack_start(self._gui_checkbox, True, True, 0)
        self._gui_checkbox.show()
        self._core_checkbox = Gtk.CheckButton(label="Core Config")
        self._core_checkbox.show()
        dialog.vbox.pack_start(self._core_checkbox, True, True, 0)
        response = dialog.run()
        dialog.destroy()
        return response

Response: Function that opens a dialog to select which config shall be exported


Instruction:
Write a Python 3 function for
checking if an object is inside the values of a dict.

Response:
def check_if_dict_contains_object_reference_in_values(object_to_check, dict_to_check):
    """ Method to check if an object is inside the values of a dict.
    A simple object_to_check in dict_to_check.values() does not work as it uses the __eq__ function of the object
    and not the object reference.

    :param object_to_check: The target object.
    :param dict_to_check: The dict to search in.
    :return:
    """
    for key, value in dict_to_check.items():
        if object_to_check is value:
            return True
    return False


Instruction:
Here you have a function in Python 3, explain what it does
def update_data_flows(model, data_flow_dict, tree_dict_combos):
    data_flow_dict['internal'] = {}
    data_flow_dict['external'] = {}
    tree_dict_combos['internal'] = {}
    tree_dict_combos['external'] = {}

    # free input ports and scopes are real to_keys and real states
    [free_to_port_internal, from_ports_internal] = find_free_keys(model)
    [free_to_port_external, from_ports_external] = find_free_keys(model.parent)

    def take_from_dict(from_dict, key):
        if key in from_dict:
            return from_dict[key]
        else:
            logger.warning("Key '%s' is not in %s" % (key, from_dict))
            pass

    # from_state, to_key, to_state, to_key, external
    if isinstance(model, ContainerStateModel):
        for data_flow in list(model.state.data_flows.values()):  # model.data_flow_list_store:

            # TREE STORE LABEL
            # check if from Self_state
            if data_flow.from_state == model.state.state_id:
                from_state = model.state
                from_state_label = 'self.' + model.state.name + '.' + data_flow.from_state
            else:
                if take_from_dict(model.state.states, data_flow.from_state):
                    from_state = take_from_dict(model.state.states, data_flow.from_state)
                    from_state_label = from_state.name + '.' + data_flow.from_state
                else:
                    # print(data_flow.from_state, data_flow.from_key, data_flow.to_state, data_flow.to_key)
                    logger.warning("DO break in ctrl/data_flow.py -1")
                    break
            # check if to Self_state
            if data_flow.to_state == model.state.state_id:
                to_state = model.state
                to_state_label = 'self.' + model.state.name + '.' + data_flow.to_state
            else:
                if take_from_dict(model.state.states, data_flow.to_state):
                    to_state = take_from_dict(model.state.states, data_flow.to_state)
                    to_state_label = to_state.name + '.' + data_flow.to_state
                else:
                    # print(data_flow.from_state, data_flow.from_key, data_flow.to_state, data_flow.to_key)
                    logger.warning("DO break in ctrl/data_flow.py 0")
                    break

            from_key_port = from_state.get_data_port_by_id(data_flow.from_key)
            from_key_label = ''
            if from_key_port is not None:
                from_key_label = PORT_TYPE_TAG.get(type(from_key_port), 'None') + '.' + \
                                 from_key_port.data_type.__name__ + '.' + \
                                 from_key_port.name

            to_key_port = to_state.get_data_port_by_id(data_flow.to_key)
            # to_key_label = ''
            if to_key_port is not None:
                to_key_label = PORT_TYPE_TAG.get(type(to_key_port), 'None') + '.' + \
                               (to_key_port.data_type.__name__ or 'None') + '.' + \
                               to_key_port.name
            data_flow_dict['internal'][data_flow.data_flow_id] = {'from_state': from_state_label,
                                                                  'from_key': from_key_label,
                                                                  'to_state': to_state_label,
                                                                  'to_key': to_key_label}

            # ALL INTERNAL COMBOS
            from_states_store = Gtk.ListStore(GObject.TYPE_STRING)
            to_states_store = Gtk.ListStore(GObject.TYPE_STRING)
            if isinstance(model, ContainerStateModel):
                if model.state.state_id in free_to_port_internal or model.state.state_id == data_flow.to_state:
                    to_states_store.append(['self.' + model.state.name + '.' + model.state.state_id])
                if model.state.state_id in from_ports_internal or model.state.state_id == data_flow.from_state:
                    from_states_store.append(['self.' + model.state.name + '.' + model.state.state_id])
                for state_model in list(model.states.values()):
                    if state_model.state.state_id in free_to_port_internal or \
                                    state_model.state.state_id == data_flow.to_state:
                        to_states_store.append([state_model.state.name + '.' + state_model.state.state_id])
                    if state_model.state.state_id in from_ports_internal or \
                                    state_model.state.state_id == data_flow.from_state:
                        from_states_store.append([state_model.state.name + '.' + state_model.state.state_id])

            from_keys_store = Gtk.ListStore(GObject.TYPE_STRING)
            if model.state.state_id == data_flow.from_state:
                # print("input_ports", model.state.input_data_ports)
                # print(type(model))
                if isinstance(model, ContainerStateModel):
                    # print("scoped_variables", model.state.scoped_variables)
                    combined_ports = {}
                    combined_ports.update(model.state.scoped_variables)
                    combined_ports.update(model.state.input_data_ports)
                    get_key_combos(combined_ports, from_keys_store, data_flow.from_key)
                else:
                    get_key_combos(model.state.input_data_ports, from_keys_store, data_flow.from_key)
            else:
                # print("output_ports", model.states[data_flow.from_state].state.output_data_ports)
                get_key_combos(model.state.states[data_flow.from_state].output_data_ports,
                               from_keys_store, data_flow.from_key)

            to_keys_store = Gtk.ListStore(GObject.TYPE_STRING)
            if model.state.state_id == data_flow.to_state:
                # print("output_ports", model.state.output_data_ports)
                # print(type(model))
                if isinstance(model, ContainerStateModel):
                    # print("scoped_variables", model.state.scoped_variables)
                    combined_ports = {}
                    combined_ports.update(model.state.scoped_variables)
                    combined_ports.update(model.state.output_data_ports)
                    get_key_combos(combined_ports, to_keys_store, data_flow.to_key)
                else:
                    get_key_combos(model.state.output_data_ports, to_keys_store, data_flow.to_key)
            else:
                # print("input_ports", model.states[data_flow.to_state].state.input_data_ports)
                get_key_combos(model.state.states[data_flow.to_state].input_data_ports
                               , to_keys_store, data_flow.to_key)
            tree_dict_combos['internal'][data_flow.data_flow_id] = {'from_state': from_states_store,
                                                                    'from_key': from_keys_store,
                                                                    'to_state': to_states_store,
                                                                    'to_key': to_keys_store}
            # print("internal", data_flow_dict['internal'][data_flow.data_flow_id])

    if not model.state.is_root_state:
        for data_flow in list(model.parent.state.data_flows.values()):  # model.parent.data_flow_list_store:

            # TREE STORE LABEL
            # check if from Self_state
            if model.state.state_id == data_flow.from_state:
                from_state = model.state
                from_state_label = 'self.' + model.state.name + '.' + data_flow.from_state
            else:
                if model.parent.state.state_id == data_flow.from_state:
                    from_state = model.parent.state
                    from_state_label = 'parent.' + model.parent.state.name + '.' + data_flow.from_state
                else:
                    if take_from_dict(model.parent.state.states, data_flow.from_state):
                        from_state = take_from_dict(model.parent.state.states, data_flow.from_state)
                        from_state_label = from_state.name + '.' + data_flow.from_state
                    else:
                        # print("#", data_flow.from_state, data_flow.from_key, data_flow.to_state, data_flow.to_key)
                        logger.warning("DO break in ctrl/data_flow.py 1")
                        break

            # check if to Self_state
            if model.state.state_id == data_flow.to_state:
                to_state = model.state
                to_state_label = 'self.' + model.state.name + '.' + data_flow.to_state
            else:
                if model.parent.state.state_id == data_flow.to_state:
                    to_state = model.parent.state
                    to_state_label = 'parent.' + model.parent.state.name + '.' + data_flow.to_state
                else:
                    if take_from_dict(model.parent.state.states, data_flow.to_state):
                        to_state = take_from_dict(model.parent.state.states, data_flow.to_state)
                        to_state_label = to_state.name + '.' + data_flow.to_state
                    else:
                        # print("##", data_flow.from_state, data_flow.from_key, data_flow.to_state, data_flow.to_key)
                        logger.warning("DO break in ctrl/data_flow.py 2")
                        break
            if model.state.state_id in [data_flow.from_state, data_flow.to_state]:
                from_key_port = from_state.get_data_port_by_id(data_flow.from_key)
                if from_key_port is None:
                    continue
                from_key_label = PORT_TYPE_TAG.get(type(from_key_port), 'None') + '.' + \
                                 from_key_port.data_type.__name__ + '.' + \
                                 from_key_port.name
                to_key_port = to_state.get_data_port_by_id(data_flow.to_key)
                if to_key_port is None:
                    continue
                to_key_label = PORT_TYPE_TAG.get(type(to_key_port), 'None') + '.' + \
                               to_key_port.data_type.__name__ + '.' + \
                               to_key_port.name
                data_flow_dict['external'][data_flow.data_flow_id] = {'from_state': from_state_label,
                                                                      'from_key': from_key_label,
                                                                      'to_state': to_state_label,
                                                                      'to_key': to_key_label}

            # ALL EXTERNAL COMBOS
            if model.state.state_id in [data_flow.from_state, data_flow.to_state]:

                # only self-state
                from_states_store = Gtk.ListStore(GObject.TYPE_STRING)
                for state_id in list(from_ports_external.keys()):
                    if model.parent.state.state_id == state_id:
                        state_model = model.parent
                    else:
                        state_model = model.parent.states[state_id]
                    if state_model.state.state_id == model.state.state_id:
                        from_states_store.append(['self.' + state_model.state.name + '.' + state_model.state.state_id])
                    else:
                        from_states_store.append([state_model.state.name + '.' + state_model.state.state_id])
                        # from_states_store.append(['self.' + model.state.name + '.' + model.state.state_id])

                # only outports of self
                from_keys_store = Gtk.ListStore(GObject.TYPE_STRING)
                if model.parent.state.state_id == data_flow.from_state:
                    # print("output_ports", model.parent.states[data_flow.from_state].state.output_data_ports)
                    combined_ports = {}
                    combined_ports.update(model.parent.state.input_data_ports)
                    combined_ports.update(model.parent.state.scoped_variables)
                    get_key_combos(combined_ports, from_keys_store, data_flow.to_key)
                elif data_flow.from_state in [state_m.state.state_id for state_m in list(model.parent.states.values())]:
                    get_key_combos(model.parent.state.states[data_flow.from_state].output_data_ports,
                                   from_keys_store, data_flow.to_key)
                else:
                    logger.error(
                        "---------------- FAILURE %s ------------- external from_state PARENT or STATES" % model.state.state_id)

                # all states and parent-state
                to_states_store = Gtk.ListStore(GObject.TYPE_STRING)
                for state_id in list(free_to_port_external.keys()):
                    if model.parent.state.state_id == state_id:
                        state_model = model.parent
                    else:
                        state_model = model.parent.states[state_id]
                    if state_model.state.state_id == model.state.state_id:
                        to_states_store.append(['self.' + state_model.state.name + '.' + state_model.state.state_id])
                    else:
                        to_states_store.append([state_model.state.name + '.' + state_model.state.state_id])

                # all keys of actual to-state
                to_keys_store = Gtk.ListStore(GObject.TYPE_STRING)
                if get_state_model(model.parent, data_flow.to_state):
                    to_state_model = get_state_model(model.parent, data_flow.to_state)
                    from_state_model = get_state_model(model.parent, data_flow.to_state)
                    act_from_key_port = from_state_model.state.get_data_port_by_id(data_flow.from_key)
                    act_to_key_port = to_state_model.state.get_data_port_by_id(data_flow.to_key)

                    # first actual port
                    to_keys_store.append([PORT_TYPE_TAG.get(type(act_to_key_port), 'None') + '.#' +
                                          str(act_to_key_port.data_port_id) + '.' +
                                          act_to_key_port.data_type.__name__ + '.' +
                                          act_to_key_port.name])

                    # second all other possible ones
                    if to_state_model.state is model.state.parent:
                        possible_port_ids = list(to_state_model.state.output_data_ports.keys()) + list(to_state_model.state.scoped_variables.keys())
                    else:
                        possible_port_ids = list(to_state_model.state.input_data_ports.keys())
                    for port_id in possible_port_ids:
                        port = to_state_model.state.get_data_port_by_id(port_id)
                        # to_state = get_state_model(model.parent, data_flow.to_state).state
                        if not (PORT_TYPE_TAG.get(type(act_from_key_port), 'None') == 'SV' and port.data_port_id == data_flow.from_key)\
                                and port is not act_to_key_port:
                            to_keys_store.append([PORT_TYPE_TAG.get(type(port), 'None') + '.#' +
                                                  str(port.data_port_id) + '.' +
                                                  port.data_type.__name__ + '.' +
                                                  port.name])

                tree_dict_combos['external'][data_flow.data_flow_id] = {'from_state': from_states_store,
                                                                        'from_key': from_keys_store,
                                                                        'to_state': to_states_store,
                                                                        'to_key': to_keys_store}
                # print("external", data_flow_dict['external'][data_flow.data_flow_id])

    # print("ALL SCANNED: ", data_flow_dict['internal'].keys(), data_flow_dict['external'].keys(), \)
    #     tree_dict_combos['internal'].keys(), tree_dict_combos['external'].keys()
    return free_to_port_internal, free_to_port_external, from_ports_internal, from_ports_external

Response: Updates the data flow dictionary and combo dictionary of the widget according handed model.


Instruction:
Make a summary of the following Python 3 code
def register_view(self, view):
        super(StateDataFlowsListController, self).register_view(view)

        def cell_text(column, cell_renderer, model, iter, container_model):
            df_id = model.get_value(iter, self.ID_STORAGE_ID)
            in_external = 'external' if model.get_value(iter, self.IS_EXTERNAL_STORAGE_ID) else 'internal'

            if column.get_title() == 'Source State':
                cell_renderer.set_property("model", self.tree_dict_combos[in_external][df_id]['from_state'])
                cell_renderer.set_property("text-column", 0)
                cell_renderer.set_property("has-entry", False)
            elif column.get_title() == 'Source Port':
                cell_renderer.set_property("model", self.tree_dict_combos[in_external][df_id]['from_key'])
                cell_renderer.set_property("text-column", 0)
                cell_renderer.set_property("has-entry", False)
            elif column.get_title() == 'Target State':
                cell_renderer.set_property("model", self.tree_dict_combos[in_external][df_id]['to_state'])
                cell_renderer.set_property("text-column", 0)
                cell_renderer.set_property("has-entry", False)
            elif column.get_title() == 'Target Port':
                cell_renderer.set_property("model", self.tree_dict_combos[in_external][df_id]['to_key'])
                cell_renderer.set_property("text-column", 0)
                cell_renderer.set_property("has-entry", False)
            else:
                logger.warning("Column has no cell_data_func %s %s" % (column.get_name(), column.get_title()))

        view['from_state_col'].set_cell_data_func(view['from_state_combo'], cell_text, self.model)
        view['to_state_col'].set_cell_data_func(view['to_state_combo'], cell_text, self.model)
        view['from_key_col'].set_cell_data_func(view['from_key_combo'], cell_text, self.model)
        view['to_key_col'].set_cell_data_func(view['to_key_combo'], cell_text, self.model)

        if self.model.state.get_next_upper_library_root_state():
            view['from_state_combo'].set_property("editable", False)
            view['from_key_combo'].set_property("editable", False)
            view['to_state_combo'].set_property("editable", False)
            view['to_key_combo'].set_property("editable", False)
        else:
            self.connect_signal(view['from_state_combo'], "edited", self.on_combo_changed_from_state)
            self.connect_signal(view['from_key_combo'], "edited", self.on_combo_changed_from_key)
            self.connect_signal(view['to_state_combo'], "edited", self.on_combo_changed_to_state)
            self.connect_signal(view['to_key_combo'], "edited", self.on_combo_changed_to_key)

        self.tree_view.connect("grab-focus", self.on_focus)
        self.update(initiator='"register view"')

Response: Called when the View was registered


Instruction:
Write a Python 3 script to
remove respective core element of handed data flow model

Response:
def remove_core_element(self, model):
        """Remove respective core element of handed data flow model

        :param DataFlowModel model: Data Flow model which core element should be removed
        :return:
        """
        assert model.data_flow.parent is self.model.state or model.data_flow.parent is self.model.parent.state
        gui_helper_state_machine.delete_core_element_of_model(model)


Instruction:
Create a Python 3 function for
calling when the view was registered

Response:
def register_view(self, view):
        """Called when the View was registered

        Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application
        """
        super(StateDataFlowsEditorController, self).register_view(view)
        view['add_d_button'].connect('clicked', self.df_list_ctrl.on_add)
        view['remove_d_button'].connect('clicked', self.df_list_ctrl.on_remove)
        view['connected_to_d_checkbutton'].connect('toggled', self.toggled_button, 'data_flows_external')
        view['internal_d_checkbutton'].connect('toggled', self.toggled_button, 'data_flows_internal')

        if isinstance(self.model.state, LibraryState):
            view['internal_d_checkbutton'].set_sensitive(False)
            view['internal_d_checkbutton'].set_active(False)

        if self.model.parent is not None and isinstance(self.model.parent.state, LibraryState) or \
                self.model.state.get_next_upper_library_root_state():
            view['add_d_button'].set_sensitive(False)
            view['remove_d_button'].set_sensitive(False)

        if self.model.state.is_root_state:
            self.df_list_ctrl.view_dict['data_flows_external'] = False
            view['connected_to_d_checkbutton'].set_active(False)

        if not isinstance(self.model, ContainerStateModel):
            self.df_list_ctrl.view_dict['data_flows_internal'] = False
            view['internal_d_checkbutton'].set_active(False)


Instruction:
Can you implement a function in Python 3 that
starts the execution of the root state.

Response:
def start(self):
        """Starts the execution of the root state.
        """
        # load default input data for the state
        self._root_state.input_data = self._root_state.get_default_input_values_for_state(self._root_state)
        self._root_state.output_data = self._root_state.create_output_dictionary_for_state(self._root_state)
        new_execution_history = self._add_new_execution_history()
        new_execution_history.push_state_machine_start_history_item(self, run_id_generator())
        self._root_state.start(new_execution_history)


Instruction:
How would you explain what the following Python 3 function does
def join(self):
        self._root_state.join()
        # execution finished, close execution history log file (if present)
        if len(self._execution_histories) > 0:
            if self._execution_histories[-1].execution_history_storage is not None:
                set_read_and_writable_for_all = global_config.get_config_value("EXECUTION_LOG_SET_READ_AND_WRITABLE_FOR_ALL", False)
                self._execution_histories[-1].execution_history_storage.close(set_read_and_writable_for_all)
        from rafcon.core.states.state import StateExecutionStatus
        self._root_state.state_execution_status = StateExecutionStatus.INACTIVE

Response: Wait for root state to finish execution


Instruction:
Make a summary of the following Python 3 code
def get_port_area(self, view):
        state_v = self.parent
        center = self.handle.pos
        margin = self.port_side_size / 4.
        if self.side in [SnappedSide.LEFT, SnappedSide.RIGHT]:
            height, width = self.port_size
        else:
            width, height = self.port_size
        upper_left = center[0] - width / 2 - margin, center[1] - height / 2 - margin
        lower_right = center[0] + width / 2 + margin, center[1] + height / 2 + margin
        port_upper_left = view.get_matrix_i2v(state_v).transform_point(*upper_left)
        port_lower_right = view.get_matrix_i2v(state_v).transform_point(*lower_right)
        size = port_lower_right[0] - port_upper_left[0], port_lower_right[1] - port_upper_left[1]
        return port_upper_left[0], port_upper_left[1], size[0], size[1]

Response: Calculates the drawing area affected by the port.


Instruction:
Write a Python 3 function that can
draw the simple state port of a simple state.

Response:
def _draw_simple_state_port(self, context, direction, color, transparency):
        """Draw the port of a simple state (ExecutionState, LibraryState)

        Connector for execution states can only be connected to the outside. Thus the connector fills the whole
        border of the state.

        :param context: Cairo context
        :param direction: The direction the port is pointing to
        :param color: Desired color of the port
        :param transparency: The level of transparency
        """
        c = context

        width, height = self.port_size
        c.set_line_width(self.port_side_size * 0.03 * self._port_image_cache.multiplicator)

        # Save/restore context, as we move and rotate the connector to the desired pose
        c.save()
        c.rel_move_to(self.port_side_size / 2., self.port_side_size / 2.)
        PortView._rotate_context(c, direction)
        PortView._draw_single_connector(c, width, height)
        c.restore()

        # Colorize the generated connector path
        if self.connected:
            c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
        else:
            c.set_source_rgb(*gui_config.gtk_colors['PORT_UNCONNECTED'].to_floats())
        c.fill_preserve()
        c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
        c.stroke()


Instruction:
Here you have a function in Python 3, explain what it does
def _draw_container_state_port(self, context, direction, color, transparency):
        c = context

        width, height = self.port_size
        c.set_line_width(self.port_side_size / constants.BORDER_WIDTH_OUTLINE_WIDTH_FACTOR *
                         self._port_image_cache.multiplicator)

        # Save/restore context, as we move and rotate the connector to the desired pose
        cur_point = c.get_current_point()
        c.save()
        c.rel_move_to(self.port_side_size / 2., self.port_side_size / 2.)
        PortView._rotate_context(c, direction)
        PortView._draw_inner_connector(c, width, height)
        c.restore()

        if self.connected_incoming:
            c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
        else:
            c.set_source_rgb(*gui_config.gtk_colors['PORT_UNCONNECTED'].to_floats())
        c.fill_preserve()
        c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
        c.stroke()

        c.move_to(*cur_point)
        c.save()
        c.rel_move_to(self.port_side_size / 2., self.port_side_size / 2.)
        PortView._rotate_context(c, direction)
        PortView._draw_outer_connector(c, width, height)
        c.restore()

        if self.connected_outgoing:
            c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
        else:
            c.set_source_rgb(*gui_config.gtk_colors['PORT_UNCONNECTED'].to_floats())
        c.fill_preserve()
        c.set_source_rgba(*gap_draw_helper.get_col_rgba(color, transparency))
        c.stroke()

Response: Draw the port of a container state.


Instruction:
Write a Python 3 function that can
draw the connector for execution states in a single context.

Response:
def _draw_single_connector(context, width, height):
        """Draw the connector for execution states

        Connector for execution states can only be connected to the outside. Thus the connector fills the whole
        border of the state.

        :param context: Cairo context
        :param float port_size: The side length of the port
        """
        c = context
        # Current pos is center
        # Arrow is drawn upright

        arrow_height = height / 2.0

        # First move to bottom left corner
        c.rel_move_to(-width / 2., height / 2.)
        # Draw line to bottom right corner
        c.rel_line_to(width, 0)
        # Draw line to upper right corner
        c.rel_line_to(0, -(height - arrow_height))
        # Draw line to center top (arrow)
        c.rel_line_to(-width / 2., -arrow_height)
        # Draw line to upper left corner
        c.rel_line_to(-width / 2., arrow_height)
        # Draw line back to the origin (lower left corner)
        c.close_path()


Instruction:
How would you code a function in Python 3 to
draw the connector for container states

Response:
def _draw_inner_connector(context, width, height):
        """Draw the connector for container states

        Connector for container states can be connected from the inside and the outside. Thus the connector is split
        in two parts: A rectangle on the inside and an arrow on the outside. This methods draws the inner rectangle.

        :param context: Cairo context
        :param float port_size: The side length of the port
        """
        c = context
        # Current pos is center
        # Arrow is drawn upright

        gap = height / 6.
        connector_height = (height - gap) / 2.

        # First move to bottom left corner
        c.rel_move_to(-width / 2., height / 2.)

        # Draw inner connector (rectangle)
        c.rel_line_to(width, 0)
        c.rel_line_to(0, -connector_height)
        c.rel_line_to(-width, 0)
        c.close_path()


Instruction:
Create a Python 3 function for
drawing the outer connector for container states.

Response:
def _draw_outer_connector(context, width, height):
        """Draw the outer connector for container states

        Connector for container states can be connected from the inside and the outside. Thus the connector is split
        in two parts: A rectangle on the inside and an arrow on the outside. This method draws the outer arrow.

        :param context: Cairo context
        :param float port_size: The side length of the port
        """
        c = context
        # Current pos is center
        # Arrow is drawn upright

        arrow_height = height / 2.5
        gap = height / 6.
        connector_height = (height - gap) / 2.

        # Move to bottom left corner of outer connector
        c.rel_move_to(-width / 2., -gap / 2.)

        # Draw line to bottom right corner
        c.rel_line_to(width, 0)
        # Draw line to upper right corner
        c.rel_line_to(0, -(connector_height - arrow_height))
        # Draw line to center top (arrow)
        c.rel_line_to(-width / 2., -arrow_height)
        # Draw line to upper left corner
        c.rel_line_to(-width / 2., arrow_height)
        # Draw line back to the origin (lower left corner)
        c.close_path()


Instruction:
How would you explain what the following Python 3 function does
def _draw_rectangle(context, width, height):
        c = context
        # First move to upper left corner
        c.rel_move_to(-width / 2., -height / 2.)
        # Draw closed rectangle
        c.rel_line_to(width, 0)
        c.rel_line_to(0, height)
        c.rel_line_to(-width, 0)
        c.close_path()

Response: Draw a rectangle of the current size


Instruction:
Can you implement a function in Python 3 that
moves the current position to position and rotates the context according to direction

Response:
def _rotate_context(context, direction):
        """Moves the current position to 'position' and rotates the context according to 'direction'

        :param context: Cairo context
        :param direction: Direction enum
        """
        if direction is Direction.UP:
            pass
        elif direction is Direction.RIGHT:
            context.rotate(deg2rad(90))
        elif direction is Direction.DOWN:
            context.rotate(deg2rad(180))
        elif direction is Direction.LEFT:
            context.rotate(deg2rad(-90))


Instruction:
Given the following Python 3 function, write the documentation
def draw_name(self, context, transparency, only_calculate_size=False):
        c = context
        cairo_context = c
        if isinstance(c, CairoBoundingBoxContext):
            cairo_context = c._cairo
        # c.set_antialias(Antialias.GOOD)

        side_length = self.port_side_size

        layout = PangoCairo.create_layout(cairo_context)
        font_name = constants.INTERFACE_FONT
        font_size = gap_draw_helper.FONT_SIZE
        font = FontDescription(font_name + " " + str(font_size))
        layout.set_font_description(font)
        layout.set_text(self.name, -1)

        ink_extents, logical_extents = layout.get_extents()
        extents = [extent / float(SCALE) for extent in [logical_extents.x, logical_extents.y,
                                                        logical_extents.width, logical_extents.height]]
        real_name_size = extents[2], extents[3]
        desired_height = side_length * 0.75
        scale_factor = real_name_size[1] / desired_height

        # Determine the size of the text, increase the width to have more margin left and right of the text
        margin = side_length / 4.
        name_size = real_name_size[0] / scale_factor, desired_height
        name_size_with_margin = name_size[0] + margin * 2, name_size[1] + margin * 2

        # Only the size is required, stop here
        if only_calculate_size:
            return name_size_with_margin

        # Current position is the center of the port rectangle
        c.save()
        if self.side is SnappedSide.RIGHT or self.side is SnappedSide.LEFT:
            c.rotate(deg2rad(-90))
        c.rel_move_to(-name_size[0] / 2, -name_size[1] / 2)
        c.scale(1. / scale_factor, 1. / scale_factor)
        c.rel_move_to(-extents[0], -extents[1])

        c.set_source_rgba(*gap_draw_helper.get_col_rgba(self.text_color, transparency))
        PangoCairo.update_layout(cairo_context, layout)
        PangoCairo.show_layout(cairo_context, layout)
        c.restore()

        return name_size_with_margin

Response: Draws the name of the port.


Instruction:
Can you write a function in Python 3 where it
draws the rectangle path for the port.

Response:
def _draw_rectangle_path(self, context, width, height, only_get_extents=False):
        """Draws the rectangle path for the port

        The rectangle is correctly rotated. Height therefore refers to the border thickness and width to the length
        of the port.

        :param context: The context to draw on
        :param float width: The width of the rectangle
        :param float height: The height of the rectangle
        """
        c = context

        # Current position is the center of the rectangle
        c.save()
        if self.side is SnappedSide.LEFT or self.side is SnappedSide.RIGHT:
            c.rotate(deg2rad(90))
        c.rel_move_to(-width / 2., - height / 2.)
        c.rel_line_to(width, 0)
        c.rel_line_to(0, height)
        c.rel_line_to(-width, 0)
        c.close_path()
        c.restore()

        if only_get_extents:
            extents = c.path_extents()
            c.new_path()
            return extents


Instruction:
Here you have a function in Python 3, explain what it does
def _get_port_center_position(self, width):
        x, y = self.pos.x.value, self.pos.y.value
        if self.side is SnappedSide.TOP or self.side is SnappedSide.BOTTOM:
            if x - width / 2. < 0:
                x = width / 2
            elif x + width / 2. > self.parent.width:
                x = self.parent.width - width / 2.
        else:
            if y - width / 2. < 0:
                y = width / 2
            elif y + width / 2. > self.parent.height:
                y = self.parent.height - width / 2.
        return x, y

Response: Calculates the center position of the port rectangle.


Instruction:
How would you explain what the following Python 3 function does
def register_actions(self, shortcut_manager):
        shortcut_manager.add_callback_for_action('rename', self.rename_selected_state)
        super(StatesEditorController, self).register_actions(shortcut_manager)

Response: Register callback methods for triggered actions


Instruction:
Write a Python 3 script to
return the state model of the currently open tab

Response:
def get_current_state_m(self):
        """Returns the state model of the currently open tab"""
        page_id = self.view.notebook.get_current_page()
        if page_id == -1:
            return None
        page = self.view.notebook.get_nth_page(page_id)
        state_identifier = self.get_state_identifier_for_page(page)
        return self.tabs[state_identifier]['state_m']


Instruction:
Make a summary of the following Python 3 code
def state_machine_manager_notification(self, model, property, info):
        if self.current_state_machine_m is not None:
            selection = self.current_state_machine_m.selection
            if len(selection.states) > 0:
                self.activate_state_tab(selection.get_selected_state())

Response: Triggered whenever a new state machine is created or selected.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def clean_up_tabs(self):
        tabs_to_close = []
        for state_identifier, tab_dict in list(self.tabs.items()):
            if tab_dict['sm_id'] not in self.model.state_machine_manager.state_machines:
                tabs_to_close.append(state_identifier)
        for state_identifier, tab_dict in list(self.closed_tabs.items()):
            if tab_dict['sm_id'] not in self.model.state_machine_manager.state_machines:
                tabs_to_close.append(state_identifier)
        for state_identifier in tabs_to_close:
            self.close_page(state_identifier, delete=True)

Response: Method remove state - tabs for those no state machine exists anymore.


Instruction:
How would you implement a function in Python 3 that
observes all open state machines and their root states

Response:
def state_machines_set_notification(self, model, prop_name, info):
        """Observe all open state machines and their root states
        """
        if info['method_name'] == '__setitem__':
            state_machine_m = info.args[1]
            self.observe_model(state_machine_m)


Instruction:
Can you implement a function in Python 3 that
relives models of closed state machine

Response:
def state_machines_del_notification(self, model, prop_name, info):
        """Relive models of closed state machine
        """
        if info['method_name'] == '__delitem__':
            state_machine_m = info["result"]
            try:
                self.relieve_model(state_machine_m)
            except KeyError:
                pass
            self.clean_up_tabs()


Instruction:
Can you tell what is the following Python 3 function doing
def add_state_editor(self, state_m):
        state_identifier = self.get_state_identifier(state_m)

        if state_identifier in self.closed_tabs:
            state_editor_ctrl = self.closed_tabs[state_identifier]['controller']
            state_editor_view = state_editor_ctrl.view
            handler_id = self.closed_tabs[state_identifier]['source_code_changed_handler_id']
            source_code_view_is_dirty = self.closed_tabs[state_identifier]['source_code_view_is_dirty']
            del self.closed_tabs[state_identifier]  # pages not in self.closed_tabs and self.tabs at the same time
        else:
            state_editor_view = StateEditorView()
            if isinstance(state_m, LibraryStateModel):
                state_editor_view['main_notebook_1'].set_current_page(
                    state_editor_view['main_notebook_1'].page_num(state_editor_view.page_dict["Data Linkage"]))
            state_editor_ctrl = StateEditorController(state_m, state_editor_view)
            self.add_controller(state_identifier, state_editor_ctrl)
            if state_editor_ctrl.get_controller('source_ctrl') and state_m.state.get_next_upper_library_root_state() is None:
                # observe changed to set the mark dirty flag
                handler_id = state_editor_view.source_view.get_buffer().connect('changed', self.script_text_changed,
                                                                                state_m)
                self.view.get_top_widget().connect('draw', state_editor_view.source_view.on_draw)
            else:
                handler_id = None
            source_code_view_is_dirty = False

        (tab, inner_label, sticky_button) = create_tab_header('', self.on_tab_close_clicked,
                                                              self.on_toggle_sticky_clicked, state_m)
        set_tab_label_texts(inner_label, state_m, source_code_view_is_dirty)

        state_editor_view.get_top_widget().title_label = inner_label
        state_editor_view.get_top_widget().sticky_button = sticky_button

        page_content = state_editor_view.get_top_widget()
        page_id = self.view.notebook.prepend_page(page_content, tab)
        page = self.view.notebook.get_nth_page(page_id)
        self.view.notebook.set_tab_reorderable(page, True)
        page.show_all()

        self.view.notebook.show()
        self.tabs[state_identifier] = {'page': page, 'state_m': state_m,
                                       'controller': state_editor_ctrl, 'sm_id': self.model.selected_state_machine_id,
                                       'is_sticky': False,
                                       'source_code_view_is_dirty': source_code_view_is_dirty,
                                       'source_code_changed_handler_id': handler_id}
        return page_id

Response: Triggered whenever a state is selected.


Instruction:
How would you code a function in Python 3 to
update the gui elements according text buffer changes

Response:
def script_text_changed(self, text_buffer, state_m):
        """ Update gui elements according text buffer changes

        Checks if the dirty flag needs to be set and the tab label to be updated.

        :param TextBuffer text_buffer: Text buffer of the edited script
        :param rafcon.gui.models.state.StateModel state_m: The state model related to the text buffer
        :return:
        """

        state_identifier = self.get_state_identifier(state_m)
        if state_identifier in self.tabs:
            tab_list = self.tabs
        elif state_identifier in self.closed_tabs:
            tab_list = self.closed_tabs
        else:
            logger.warning('It was tried to check a source script of a state with no state-editor')
            return
        if tab_list[state_identifier]['controller'].get_controller('source_ctrl') is None:
            logger.warning('It was tried to check a source script of a state with no source-editor')
            return
        current_text = tab_list[state_identifier]['controller'].get_controller('source_ctrl').view.get_text()
        old_is_dirty = tab_list[state_identifier]['source_code_view_is_dirty']
        source_script_state_m = state_m.state_copy if isinstance(state_m, LibraryStateModel) else state_m
        # remove next two lines and tab is also set dirty for source scripts inside of a LibraryState (maybe in future)
        if isinstance(state_m, LibraryStateModel) or state_m.state.get_next_upper_library_root_state() is not None:
            return
        if source_script_state_m.state.script_text == current_text:
            tab_list[state_identifier]['source_code_view_is_dirty'] = False
        else:
            tab_list[state_identifier]['source_code_view_is_dirty'] = True
        if old_is_dirty is not tab_list[state_identifier]['source_code_view_is_dirty']:
            self.update_tab_label(source_script_state_m)


Instruction:
Create a Python 3 function for
destroying the desired page and disconnects the page from signals and removes interconnection to parent - controller or observables.

Response:
def destroy_page(self, tab_dict):
        """ Destroys desired page

        Disconnects the page from signals and removes interconnection to parent-controller or observables.

        :param tab_dict: Tab-dictionary that holds all necessary information of a page and state-editor.
        """
        # logger.info("destroy page %s" % tab_dict['controller'].model.state.get_path())
        if tab_dict['source_code_changed_handler_id'] is not None:
            handler_id = tab_dict['source_code_changed_handler_id']
            if tab_dict['controller'].view.source_view.get_buffer().handler_is_connected(handler_id):
                tab_dict['controller'].view.source_view.get_buffer().disconnect(handler_id)
            else:
                logger.warning("Source code changed handler of state {0} was already removed.".format(tab_dict['state_m']))
        self.remove_controller(tab_dict['controller'])


Instruction:
How would you code a function in Python 3 to
close the desired page with the specified state_identifier.

Response:
def close_page(self, state_identifier, delete=True):
        """Closes the desired page

        The page belonging to the state with the specified state_identifier is closed. If the deletion flag is set to
        False, the controller of the page is stored for later usage.

        :param state_identifier: Identifier of the page's state
        :param delete: Whether to delete the controller (deletion is necessary if teh state is deleted)
        """
        # delete old controller references
        if delete and state_identifier in self.closed_tabs:
            self.destroy_page(self.closed_tabs[state_identifier])
            del self.closed_tabs[state_identifier]

        # check for open page of state
        if state_identifier in self.tabs:
            page_to_close = self.tabs[state_identifier]['page']
            current_page_id = self.view.notebook.page_num(page_to_close)
            if not delete:
                self.closed_tabs[state_identifier] = self.tabs[state_identifier]
            else:
                self.destroy_page(self.tabs[state_identifier])
            del self.tabs[state_identifier]
            # Finally remove the page, this triggers the callback handles on_switch_page
            self.view.notebook.remove_page(current_page_id)


Instruction:
Write a Python 3 script for
returning the identifier and page of a given state model

Response:
def find_page_of_state_m(self, state_m):
        """Return the identifier and page of a given state model

        :param state_m: The state model to be searched
        :return: page containing the state and the state_identifier
        """
        for state_identifier, page_info in list(self.tabs.items()):
            if page_info['state_m'] is state_m:
                return page_info['page'], state_identifier
        return None, None


Instruction:
Can you generate a brief explanation for the following Python 3 code
def on_tab_close_clicked(self, event, state_m):
        [page, state_identifier] = self.find_page_of_state_m(state_m)
        if page:
            self.close_page(state_identifier, delete=False)

Response:
Triggered when the states - editor close button is clicked
            Closes the tab.


Instruction:
Explain what the following Python 3 code does
def close_all_pages(self):
        states_to_be_closed = []
        for state_identifier in self.tabs:
            states_to_be_closed.append(state_identifier)
        for state_identifier in states_to_be_closed:
            self.close_page(state_identifier, delete=False)

Response: Closes all tabs of the states editor


Instruction:
Write a Python 3 function that can
close all tabs of the states editor for a specific sm_id

Response:
def close_pages_for_specific_sm_id(self, sm_id):
        """Closes all tabs of the states editor for a specific sm_id"""
        states_to_be_closed = []
        for state_identifier in self.tabs:
            state_m = self.tabs[state_identifier]["state_m"]
            if state_m.state.get_state_machine().state_machine_id == sm_id:
                states_to_be_closed.append(state_identifier)
        for state_identifier in states_to_be_closed:
            self.close_page(state_identifier, delete=False)


Instruction:
How would you implement a function in Python 3 that
updates state selection when the active tab was changed

Response:
def on_switch_page(self, notebook, page_pointer, page_num, user_param1=None):
        """Update state selection when the active tab was changed
        """
        page = notebook.get_nth_page(page_num)

        # find state of selected tab
        for tab_info in list(self.tabs.values()):
            if tab_info['page'] is page:
                state_m = tab_info['state_m']
                sm_id = state_m.state.get_state_machine().state_machine_id
                selected_state_m = self.current_state_machine_m.selection.get_selected_state()

                # If the state of the selected tab is not in the selection, set it there
                if selected_state_m is not state_m and sm_id in self.model.state_machine_manager.state_machines:
                    self.model.selected_state_machine_id = sm_id
                    self.current_state_machine_m.selection.set(state_m)
                return


Instruction:
How would you implement a function in Python 3 that
opens the tab for the given state model.

Response:
def activate_state_tab(self, state_m):
        """Opens the tab for the specified state model

        The tab with the given state model is opened or set to foreground.

        :param state_m: The desired state model (the selected state)
        """
        # The current shown state differs from the desired one
        current_state_m = self.get_current_state_m()
        if current_state_m is not state_m:
            state_identifier = self.get_state_identifier(state_m)

            # The desired state is not open, yet
            if state_identifier not in self.tabs:
                # add tab for desired state
                page_id = self.add_state_editor(state_m)
                self.view.notebook.set_current_page(page_id)
            # bring tab for desired state into foreground
            else:
                page = self.tabs[state_identifier]['page']
                page_id = self.view.notebook.page_num(page)
                self.view.notebook.set_current_page(page_id)

        self.keep_only_sticked_and_selected_tabs()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def keep_only_sticked_and_selected_tabs(self):
        # Only if the user didn't deactivate this behaviour
        if not global_gui_config.get_config_value('KEEP_ONLY_STICKY_STATES_OPEN', True):
            return

        page_id = self.view.notebook.get_current_page()
        # No tabs are open
        if page_id == -1:
            return

        page = self.view.notebook.get_nth_page(page_id)
        current_state_identifier = self.get_state_identifier_for_page(page)

        states_to_be_closed = []
        # Iterate over all tabs
        for state_identifier, tab_info in list(self.tabs.items()):
            # If the tab is currently open, keep it open
            if current_state_identifier == state_identifier:
                continue
            # If the tab is sticky, keep it open
            if tab_info['is_sticky']:
                continue
            # Otherwise close it
            states_to_be_closed.append(state_identifier)

        for state_identifier in states_to_be_closed:
            self.close_page(state_identifier, delete=False)

Response: Keep only sticked and selected tabs


Instruction:
Create a Python 3 function for
checking whether the name of a state was changed and change the tab label accordingly.

Response:
def notify_state_name_change(self, model, prop_name, info):
        """Checks whether the name of a state was changed and change the tab label accordingly
        """
        # avoid updates or checks because of execution status updates
        if is_execution_status_update_notification_from_state_machine_model(prop_name, info):
            return

        overview = NotificationOverview(info, False, self.__class__.__name__)
        changed_model = overview['model'][-1]
        method_name = overview['method_name'][-1]
        if isinstance(changed_model, AbstractStateModel) and method_name in ['name', 'script_text']:
            self.update_tab_label(changed_model)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def update_tab_label(self, state_m):
        state_identifier = self.get_state_identifier(state_m)
        if state_identifier not in self.tabs and state_identifier not in self.closed_tabs:
            return
        tab_info = self.tabs[state_identifier] if state_identifier in self.tabs else self.closed_tabs[state_identifier]
        page = tab_info['page']
        set_tab_label_texts(page.title_label, state_m, tab_info['source_code_view_is_dirty'])

Response: Update all tab labels that are currently open for the given state_m.


Instruction:
Write a Python 3 script to
return the state identifier for a given page

Response:
def get_state_identifier_for_page(self, page):
        """Return the state identifier for a given page
        """
        for identifier, page_info in list(self.tabs.items()):
            if page_info["page"] is page:  # reference comparison on purpose
                return identifier


Instruction:
Here you have a function in Python 3, explain what it does
def rename_selected_state(self, key_value, modifier_mask):
        selection = self.current_state_machine_m.selection
        if len(selection.states) == 1 and len(selection) == 1:
            selected_state = selection.get_selected_state()
            self.activate_state_tab(selected_state)
            _, state_identifier = self.find_page_of_state_m(selected_state)
            state_controller = self.tabs[state_identifier]['controller']
            state_controller.rename()

Response: Callback method for shortcut action rename_selected_state


Instruction:
Can you generate a brief explanation for the following Python 3 code
def generate_semantic_data_key(used_semantic_keys):
    semantic_data_id_counter = -1
    while True:
        semantic_data_id_counter += 1
        if "semantic data key " + str(semantic_data_id_counter) not in used_semantic_keys:
            break
    return "semantic data key " + str(semantic_data_id_counter)

Response: Generate a new and unique semantic data key.


Instruction:
Write a Python 3 script to
generate a new state id for a state.

Response:
def state_id_generator(size=STATE_ID_LENGTH, chars=string.ascii_uppercase, used_state_ids=None):
    """ Create a new and unique state id

    Generates an id for a state. It randomly samples from random ascii uppercase letters size times
    and concatenates them. If the id already exists it draws a new one.

    :param size: the length of the generated keys
    :param chars: the set of characters a sample draws from
    :param list used_state_ids: Handed list of ids already in use
    :rtype: str
    :return: new_state_id
    """
    new_state_id = ''.join(random.choice(chars) for x in range(size))
    while used_state_ids is not None and new_state_id in used_state_ids:
        new_state_id = ''.join(random.choice(chars) for x in range(size))
    return new_state_id


Instruction:
Implement a Python 3 function for
generating a new id for a global variable.

Response:
def global_variable_id_generator(size=10, chars=string.ascii_uppercase):
    """ Create a new and unique global variable id

    Generates an id for a global variable. It randomly samples from random ascii uppercase letters size times
    and concatenates them. If the id already exists it draws a new one.

    :param size: the length of the generated keys
    :param chars: the set of characters a sample draws from
    """
    new_global_variable_id = ''.join(random.choice(chars) for x in range(size))
    while new_global_variable_id in used_global_variable_ids:
        new_global_variable_id = ''.join(random.choice(chars) for x in range(size))
    used_global_variable_ids.append(new_global_variable_id)
    return new_global_variable_id


Instruction:
Given the following Python 3 function, write the documentation
def set(self):
        glColor4f(self.r, self.g, self.b, self.a)

Response: Set the color as current OpenGL color


Instruction:
Write a Python 3 script for
configuring viewport This method is called when the widget is resized or a redraw is triggered.

Response:
def _configure(self, *args):
        """Configure viewport

        This method is called when the widget is resized or something triggers a redraw. The method configures the
        view to show all elements in an orthogonal perspective.
        """
        # Obtain a reference to the OpenGL drawable
        # and rendering context.
        gldrawable = self.get_gl_drawable()
        glcontext = self.get_gl_context()

        # logger.debug("configure")
        # OpenGL begin
        if not gldrawable or not gldrawable.gl_begin(glcontext):
            return False

        # Draw on the full viewport
        glViewport(0, 0, self.get_allocation().width, self.get_allocation().height)

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()

        # Orthogonal view with correct aspect ratio
        self._apply_orthogonal_view()

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        # OpenGL end
        gldrawable.gl_end()

        return False


Instruction:
How would you code a function in Python 3 to
calculate the ratio between pixel and OpenGL s view coordinates.

Response:
def pixel_to_size_ratio(self):
        """Calculates the ratio between pixel and OpenGL distances

        OpenGL keeps its own coordinate system. This method can be used to transform between pixel and OpenGL
        coordinates.

        :return: pixel/size ratio
        """
        left, right, _, _ = self.get_view_coordinates()
        width = right - left
        display_width = self.get_allocation().width
        return display_width / float(width)


Instruction:
Write a Python 3 function for
exposing the drawing routine to the current rendering context.

Response:
def expose_init(self, *args):
        """Process the drawing routine
        """
        # Obtain a reference to the OpenGL drawable
        # and rendering context.
        gldrawable = self.get_gl_drawable()
        glcontext = self.get_gl_context()

        # OpenGL begin
        if not gldrawable or not gldrawable.gl_begin(glcontext):
            return False

        # logger.debug("expose_init")

        # Reset buffers
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # Prepare name stack
        glInitNames()
        glPushName(0)
        self.name_counter = 1

        return False


Instruction:
Can you implement a function in Python 3 that
draws a state with the given properties This method is called by the controller to draw the specified (container) state. :param name: Name of the state :param pos: position (x, y) of the state :param size: size (width, height) of the state :param outcomes: outcomes of the state (list with outcome objects) :param input_ports_m: input ports of the state :param output_ports_m: output ports of the state :param selected: whether to display the state as selected :param active: in which color to display the state :param depth: The z layer :return: The OpenGL id and the positions of teh outcomes (as dictionary with outcome id as key)

Response:
def draw_state(self, name, pos, size, outcomes=None, input_ports_m=None, output_ports_m=None, selected=False,
                   active=False, depth=0):
        """Draw a state with the given properties

        This method is called by the controller to draw the specified (container) state.

        :param name: Name of the state
        :param pos: position (x, y) of the state
        :param size: size (width, height) of the state
        :param outcomes: outcomes of the state (list with outcome objects)
        :param input_ports_m: input ports of the state
        :param output_ports_m: output ports of the state
        :param selected: whether to display the state as selected
        :param active: in which color to display the state
        :param depth: The z layer
        :return: The OpenGL id and the positions of teh outcomes (as dictionary with outcome id as key)
        """
        if not outcomes:
            outcomes = []
        if not input_ports_m:
            input_ports_m = []
        if not output_ports_m:
            output_ports_m = []
        # "Generate" unique ID for each object
        opengl_id = self.name_counter
        self.name_counter += 1
        glPushName(opengl_id)
        self._set_closest_stroke_width(1.5)

        width = size[0]
        height = size[1]

        # First draw the face of the rectangular, then the outline
        fill_color = self.state_color
        border_color = self.border_color

        from rafcon.core.states.state import StateExecutionStatus
        border_width = min(size) / 10.
        if active is StateExecutionStatus.ACTIVE:
            fill_color = self.state_active_color
        elif active is StateExecutionStatus.EXECUTE_CHILDREN:
            fill_color = self.state_child_active_color
        elif active is StateExecutionStatus.WAIT_FOR_NEXT_STATE:
            fill_color = self.state_waiting_for_next_state_color

        if selected:
            border_width *= 2
            border_color = self.border_selected_color

        self._draw_rect(pos[0], pos[0] + width, pos[1] - height, pos[1], depth, border_width,
                        fill_color, border_color)

        # Put the name of the state in the upper left corner of the state
        margin = min(size) / 12.
        font_size = min(size) / 8.
        name = self._shorten_string(name, font_size, width - 2 * margin)
        self._write_string(name, pos[0] + margin, pos[1] - margin, font_size, self.state_name_color, True,
                           False, depth=depth + 0.01)

        resize_length = min(width, height) / 8.
        p1 = (pos[0] + width, pos[1] - height)
        p2 = (p1[0] - resize_length, p1[1])
        p3 = (p1[0], p1[1] + resize_length)
        self._draw_triangle(p1, p2, p3, depth + 0.01, border_width, fill_color, border_color)

        # Draw outcomes as circle on the right side of the state
        # Every state has at least the default outcomes "aborted" and "preempted"
        num_outcomes = max(0, len(outcomes))
        if num_outcomes < 2:
            # logger.warning("Expecting at least 2 outcomes, found {num:d}".format(num=num_outcomes))
            pass
        else:
            num_outcomes -= 2
        i = 0
        outcome_pos = {}
        outcome_radius = min(min(height, width) / 23., min(height, width) / (2. * num_outcomes + 3))
        for key in outcomes:
            # Color of outcome is defined by its type, "aborted", "preempted" or else
            outcome_name = outcomes[key].name
            color = self.outcome_plain_color

            # Distribute outcomes (as circles) on the right edge of the state
            outcome_x = pos[0] + width
            outcome_y = pos[1] - height / (num_outcomes + 1) * (i + 1)

            if outcome_name in ["aborted", "preempted"]:
                step = min(size) / 10.
                outcome_y = pos[1]
                if outcome_name == "aborted":
                    outcome_x -= step
                    color = self.outcome_aborted_color
                else:
                    outcome_x -= 3 * step
                    color = self.outcome_preempted_color
            else:
                outcome_font_size = font_size * 0.5
                max_outcome_name_width = width / 2.
                outcome_name = self._shorten_string(outcome_name, outcome_font_size, max_outcome_name_width)
                outcome_name_pos_x = outcome_x - margin
                outcome_name_pos_y = outcome_y + outcome_font_size * 0.65
                self._write_string(outcome_name, outcome_name_pos_x, outcome_name_pos_y, outcome_font_size,
                                   self.state_name_color, align_right=True, depth=depth+0.1)
                i += 1

            color.set()
            outcome_pos[key] = (outcome_x, outcome_y)

            self._draw_circle(outcome_x, outcome_y, outcome_radius, depth + 0.1, fill_color=color)

        # Draw "income" as a half circle of the left center
        income_pos = (pos[0], pos[1] - height / 2)
        self._draw_circle(income_pos[0], income_pos[1], outcome_radius, depth + 0.1, fill_color=self.income_color,
                          from_angle=1.5 * pi, to_angle=0.5 * pi)

        # Draw input and output data ports
        port_radius = margin / 4.
        num_ports = len(input_ports_m) + len(output_ports_m)
        if num_ports > 0:
            max_name_width = 0
            margin = min(size) / 10.0
            max_allowed_name_width = 0.7 * width - margin
            str_height = height / 12.0

            # Determine the maximum width of all port labels
            for ports in [input_ports_m, output_ports_m]:
                for port_m in ports:
                    str_width = self._string_width(port_m.data_port.name, str_height)
                    if str_width > max_name_width:
                        max_name_width = str_width

            #fill_color = self.port_color if not selected else self.state_selected_color

            port_width = min(max_name_width, max_allowed_name_width)
            port_pos_left_x = pos[0] + (width - port_width - margin) / 2
            port_pos_right_x = port_pos_left_x + port_width + margin
            port_pos_bottom_y = pos[1] - height - num_ports * (str_height + margin)
            self._draw_rect(port_pos_left_x, port_pos_right_x, port_pos_bottom_y, pos[1] - height, depth, border_width,
                            fill_color, border_color)

            def draw_port(port_m, num, is_input):

                port_name = self._shorten_string(port_m.data_port.name, str_height, port_width)

                string_pos_x = port_pos_left_x + margin / 2.
                if not is_input:
                    string_pos_x += port_width
                string_pos_y = pos[1] - height - margin / 2. - num * (str_height + margin)
                self._write_string(port_name, string_pos_x, string_pos_y,
                                   str_height, self.port_name_color, False, not is_input, depth + 0.01)

                circle_pos_x = port_pos_left_x if is_input else port_pos_right_x
                circle_pos_y = string_pos_y - margin / 2.
                self._draw_circle(circle_pos_x, circle_pos_y, port_radius, depth + 0.02, stroke_width=margin / 5.,
                                  border_color=self.port_name_color, fill_color=self.port_connector_fill_color)
                return circle_pos_x, circle_pos_y

            output_num = 0
            for port_m in input_ports_m:
                con_pos_x, con_pos_y = draw_port(port_m, output_num, True)
                port_m.temp['gui']['editor']['outer_connector_radius'] = port_radius
                port_m.temp['gui']['editor']['outer_connector_pos'] = (con_pos_x, con_pos_y)
                output_num += 1

            for port_m in output_ports_m:
                con_pos_x, con_pos_y = draw_port(port_m, output_num, False)
                port_m.temp['gui']['editor']['outer_connector_radius'] = port_radius
                port_m.temp['gui']['editor']['outer_connector_pos'] = (con_pos_x, con_pos_y)
                output_num += 1

        glPopName()
        return opengl_id, income_pos, outcome_pos, outcome_radius, resize_length


Instruction:
How would you code a function in Python 3 to
draw a state with the given properties This method is called by the controller to draw the specified transition. :param tuple from_pos: Starting position :param tuple to_pos: Ending position :param float width: A measure for the width of a transition line :param list waypoints: A list of optional waypoints to connect in between :param bool selected: Whether the transition shell be shown as active/selected :param float depth: The Z layer :return: The OpenGL id of the transition :rtype: int

Response:
def draw_transition(self, from_pos, to_pos, width, waypoints=None, selected=False, depth=0):
        """Draw a state with the given properties

        This method is called by the controller to draw the specified transition.

        :param tuple from_pos: Starting position
        :param tuple to_pos: Ending position
        :param float width: A measure for the width of a transition line
        :param list waypoints: A list of optional waypoints to connect in between
        :param bool selected: Whether the transition shell be shown as active/selected
        :param float depth: The Z layer
        :return: The OpenGL id of the transition
        :rtype: int
        """
        if not waypoints:
            waypoints = []
        # "Generate" unique ID for each object
        id = self.name_counter
        self.name_counter += 1

        glPushName(id)
        self._set_closest_stroke_width(width)

        color = self.transition_color if not selected else self.transition_selected_color
        color.set()

        points = [from_pos]
        points.extend(waypoints)

        last_p = to_pos  # Transition endpoint
        sec_last_p = points[len(points) - 1]  # Point before endpoint
        # Calculate max possible arrow length
        length = min(width, dist(sec_last_p, last_p) / 2.)
        mid, p2, p3 = self._calculate_arrow_points(last_p, sec_last_p, length)
        self._draw_triangle(last_p, p2, p3, depth, fill_color=color)

        points.append(mid)

        # Draw the transitions as simple straight line connecting start- way- and endpoints
        glBegin(GL_LINE_STRIP)
        for point in points:
            glVertex3f(point[0], point[1], depth)
        glEnd()

        self._set_closest_stroke_width(width / 1.5)
        for waypoint in waypoints:
            self._draw_circle(waypoint[0], waypoint[1], width / 6., depth + 1, fill_color=color)

        glPopName()

        return id


Instruction:
Can you generate the documentation for the following Python 3 function
def _write_string(self, string, pos_x, pos_y, height, color, bold=False, align_right=False, depth=0.):
        stroke_width = height / 8.
        if bold:
            stroke_width = height / 5.
        color.set()
        self._set_closest_stroke_width(stroke_width)
        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        pos_y -= height
        if not align_right:
            glTranslatef(pos_x, pos_y, depth)
        else:
            width = self._string_width(string, height)
            glTranslatef(pos_x - width, pos_y, depth)
        font_height = 119.5  # According to https://www.opengl.org/resources/libraries/glut/spec3/node78.html
        scale_factor = height / font_height
        glScalef(scale_factor, scale_factor, scale_factor)
        for c in string:
            # glTranslatef(0, 0, 0)
            glutStrokeCharacter(GLUT_STROKE_ROMAN, ord(c))
            # width = glutStrokeWidth(GLUT_STROKE_ROMAN, ord(c))

        glPopMatrix()

Response: Write a string with a simple OpenGL method.


Instruction:
Here you have a function in Python 3, explain what it does
def prepare_selection(self, pos_x, pos_y, width, height):
        glSelectBuffer(self.name_counter * 6)
        viewport = glGetInteger(GL_VIEWPORT)

        glMatrixMode(GL_PROJECTION)
        glPushMatrix()

        glRenderMode(GL_SELECT)

        glLoadIdentity()

        if width < 1:
            width = 1
        if height < 1:
            height = 1
        pos_x += width / 2.
        pos_y += height / 2.
        # The system y axis is inverse to the OpenGL y axis
        gluPickMatrix(pos_x, viewport[3] - pos_y + viewport[1], width, height, viewport)

        self._apply_orthogonal_view()

Response: Prepares the selection rendering for the object being clicked on.


Instruction:
Make a summary of the following Python 3 code
def find_selection():
        hits = glRenderMode(GL_RENDER)

        glMatrixMode(GL_PROJECTION)
        glPopMatrix()
        glMatrixMode(GL_MODELVIEW)

        return hits

Response: Finds the selected ids of the selected objects


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

        # Adapt line width to zooming level
        width *= self.pixel_to_size_ratio() / 6.
        stroke_width_range = glGetFloatv(GL_LINE_WIDTH_RANGE)
        stroke_width_granularity = glGetFloatv(GL_LINE_WIDTH_GRANULARITY)

        if width < stroke_width_range[0]:
            glLineWidth(stroke_width_range[0])
            return
        if width > stroke_width_range[1]:
            glLineWidth(stroke_width_range[1])
            return
        glLineWidth(round(width / stroke_width_granularity) * stroke_width_granularity)

Response: Sets the line width to the closest supported one


Instruction:
Here you have a function in Python 3, explain what it does
def _draw_circle(self, pos_x, pos_y, radius, depth, stroke_width=1., fill_color=None, border_color=None,
                     from_angle=0., to_angle=2 * pi):
        """Draws a circle

        Draws a circle with a line segment a desired position with desired size.

        :param float pos_x: Center x position
        :param float pos_y: Center y position
        :param float depth: The Z layer
        :param float radius: Radius of the circle
        """

        visible = False
        # Check whether circle center is in the viewport
        if not self.point_outside_view((pos_x, pos_y)):
            visible = True
        # Check whether at least on point on the border of the circle is within the viewport
        if not visible:
            for i in range(0, 8):
                angle = 2 * pi / 8. * i
                x = pos_x + cos(angle) * radius
                y = pos_y + sin(angle) * radius
                if not self.point_outside_view((x, y)):
                    visible = True
                    break
        if not visible:
            return False

        angle_sum = to_angle - from_angle
        if angle_sum < 0:
            angle_sum = float(to_angle + 2 * pi - from_angle)
        segments = self.pixel_to_size_ratio() * radius * 1.5
        segments = max(4, segments)
        segments = int(round(segments * angle_sum / (2. * pi)))

        types = []
        if fill_color is not None:
            types.append(GL_POLYGON)
        if border_color is not None:
            types.append(GL_LINE_LOOP)

        for type in types:
            if type == GL_POLYGON:
                fill_color.set()
            else:
                self._set_closest_stroke_width(stroke_width)
                border_color.set()
            glBegin(type)
            angle = from_angle
            for i in range(0, segments):
                x = pos_x + cos(angle) * radius
                y = pos_y + sin(angle) * radius
                glVertex3f(x, y, depth)
                angle += angle_sum / (segments - 1)
                if angle > 2 * pi:
                    angle -= 2 * pi
                if i == segments - 2:
                    angle = to_angle
            glEnd()

        return True

Response: Draws a circle with a desired position with desired size.


Instruction:
Given the following Python 3 function, write the documentation
def _apply_orthogonal_view(self):
        left, right, bottom, top = self.get_view_coordinates()
        glOrtho(left, right, bottom, top, -10, 0)

Response: Apply orthogonal view to the current view


Instruction:
How would you code a function in Python 3 to
cluster the time series with the same number of hours and cluster_weights.

Response:
def tsam_cluster(timeseries_df, typical_periods=10, how='daily'):
    """
    Parameters
    ----------
    df : pd.DataFrame
        DataFrame with timeseries to cluster

    Returns
    -------
    timeseries : pd.DataFrame
        Clustered timeseries
    """

    if how == 'daily':
        hours = 24
    if how == 'weekly':
        hours = 168

    aggregation = tsam.TimeSeriesAggregation(
        timeseries_df,
        noTypicalPeriods=typical_periods,
        rescaleClusterPeriods=False,
        hoursPerPeriod=hours,
        clusterMethod='hierarchical')

    timeseries = aggregation.createTypicalPeriods()
    cluster_weights = aggregation.clusterPeriodNoOccur

    # get the medoids/ the clusterCenterIndices
    clusterCenterIndices = aggregation.clusterCenterIndices

    # get all index for every hour of that day of the clusterCenterIndices
    start = []
    # get the first hour of the clusterCenterIndices (days start with 0)
    for i in clusterCenterIndices:
        start.append(i * hours)

    # get a list with all hours belonging to the clusterCenterIndices
    nrhours = []
    for j in start:
        nrhours.append(j)
        x = 1
        while x < hours:
            j = j + 1
            nrhours.append(j)
            x = x + 1

    # get the origial Datetimeindex
    dates = timeseries_df.iloc[nrhours].index

    return timeseries, cluster_weights, dates, hours


Instruction:
Write a Python 3 function that can
update the snapshots weights and dataframes based on the original data in the network and the medoids created by clustering .

Response:
def update_data_frames(network, cluster_weights, dates, hours):
    """ Updates the snapshots, snapshots weights and the dataframes based on
    the original data in the network and the medoids created by clustering
    these original data.

    Parameters
    -----------
    network : pyPSA network object
    cluster_weights: dictionary
    dates: Datetimeindex

    Returns
    -------
    network

    """
    network.snapshot_weightings = network.snapshot_weightings.loc[dates]
    network.snapshots = network.snapshot_weightings.index

    # set new snapshot weights from cluster_weights
    snapshot_weightings = []
    for i in cluster_weights.values():
        x = 0
        while x < hours:
            snapshot_weightings.append(i)
            x += 1
    for i in range(len(network.snapshot_weightings)):
        network.snapshot_weightings[i] = snapshot_weightings[i]

    # put the snapshot in the right order
    network.snapshots.sort_values()
    network.snapshot_weightings.sort_index()

    return network


Instruction:
Can you implement a function in Python 3 that
installs necessary GUI resources By default, RAFCON should be installed via `setup.py` (`pip install rafcon`). Thereby, all resources are being installed. However, if this is not the case, one can set the `RAFCON_CHECK_INSTALLATION` env variable to `True`. Then, the installation will be performed before starting the GUI.

Response:
def setup_installation():
    """Install necessary GUI resources

    By default, RAFCON should be installed via `setup.py` (`pip install rafcon`). Thereby, all resources are being
    installed. However, if this is not the case, one can set the `RAFCON_CHECK_INSTALLATION` env variable to `True`.
    Then, the installation will be performed before starting the GUI.
    """
    if os.environ.get("RAFCON_CHECK_INSTALLATION", False) == "True":
        rafcon_root = os.path.dirname(rafcon.__file__)
        installation.assets_folder = os.path.join(rafcon_root, 'gui', 'assets')
        installation.share_folder = os.path.join(os.path.dirname(os.path.dirname(rafcon_root)), 'share')
        installation.install_fonts(logger, restart=True)
        installation.install_gtk_source_view_styles(logger)
        installation.install_libraries(logger, overwrite=False)