code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
history_item = self.history_tree_store[child_tree_iter][self.HISTORY_ITEM_STORAGE_ID] if history_item is None: # is dummy item if self.history_tree_store.iter_n_children(child_tree_iter) > 0: child_iter = self.history_tree_store.iter_nth_child(child_tree_iter, 0) history_item = self.history_tree_store[child_iter][self.HISTORY_ITEM_STORAGE_ID] else: logger.debug("In a dummy history should be respective real call element.") return history_item
def get_history_item_for_tree_iter(self, child_tree_iter)
Hands history item for tree iter and compensate if tree item is a dummy item :param Gtk.TreeIter child_tree_iter: Tree iter of row :rtype rafcon.core.execution.execution_history.HistoryItem: :return history tree item:
3.434066
3.432692
1.0004
def store_tree_expansion(child_tree_iter, expansion_state): tree_item_path = self.history_tree_store.get_path(child_tree_iter) history_item = self.get_history_item_for_tree_iter(child_tree_iter) # store expansion state if tree item path is valid and expansion state was not stored already if tree_item_path is not None: # if first element of sub-tree has same history_item as the parent ignore it's expansion state if history_item not in expansion_state: expansion_state[history_item] = self.history_tree.row_expanded(tree_item_path) for n in range(self.history_tree_store.iter_n_children(child_tree_iter)): child_iter = self.history_tree_store.iter_nth_child(child_tree_iter, n) store_tree_expansion(child_iter, expansion_state) root_iter = self.history_tree_store.get_iter_first() if not root_iter: return current_expansion_state = {} # this can be the case when the execution history tree is currently being deleted if not self.get_history_item_for_tree_iter(root_iter).state_reference: return state_machine = self.get_history_item_for_tree_iter(root_iter).state_reference.get_state_machine() self._expansion_state[state_machine.state_machine_id] = current_expansion_state while root_iter: store_tree_expansion(root_iter, current_expansion_state) root_iter = self.history_tree_store.iter_next(root_iter)
def _store_expansion_state(self)
Iter recursively all tree items and store expansion state
2.93538
2.840655
1.033346
def restore_tree_expansion(child_tree_iter, expansion_state): tree_item_path = self.history_tree_store.get_path(child_tree_iter) history_item = self.get_history_item_for_tree_iter(child_tree_iter) # restore expansion state if tree item path is valid and expansion state was not stored already if tree_item_path and history_item in expansion_state: if expansion_state[history_item]: self.history_tree.expand_to_path(tree_item_path) for n in range(self.history_tree_store.iter_n_children(child_tree_iter)): child_iter = self.history_tree_store.iter_nth_child(child_tree_iter, n) restore_tree_expansion(child_iter, expansion_state) root_iter = self.history_tree_store.get_iter_first() if not root_iter: return state_machine = self.get_history_item_for_tree_iter(root_iter).state_reference.get_state_machine() if state_machine.state_machine_id not in self._expansion_state: return while root_iter: restore_tree_expansion(root_iter, self._expansion_state[state_machine.state_machine_id]) root_iter = self.history_tree_store.iter_next(root_iter)
def _restore_expansion_state(self)
Iter recursively all tree items and restore expansion state
2.463566
2.403318
1.025068
selected_state_machine_id = self.model.selected_state_machine_id if selected_state_machine_id is None: return self.update()
def notification_selected_sm_changed(self, model, prop_name, info)
If a new state machine is selected, make sure expansion state is stored and tree updated
4.278278
3.271622
1.307693
for state_machine_id in list(self._expansion_state.keys()): if state_machine_id not in self.model.state_machines: del self._expansion_state[state_machine_id]
def notification_sm_changed(self, model, prop_name, info)
Remove references to non-existing state machines
4.200238
2.857498
1.4699
if state_machine_execution_engine.status.execution_mode in \ [StateMachineExecutionStatus.STARTED, StateMachineExecutionStatus.STOPPED, StateMachineExecutionStatus.FINISHED]: if self.parent is not None and hasattr(self.parent, "focus_notebook_page_of_controller"): # request focus -> which has not have to be satisfied self.parent.focus_notebook_page_of_controller(self) if state_machine_execution_engine.status.execution_mode is not StateMachineExecutionStatus.STARTED: if not self.model.selected_state_machine_id == self.model.state_machine_manager.active_state_machine_id: pass else: self.update()
def execution_history_focus(self, model, prop_name, info)
Arranges to put execution-history widget page to become top page in notebook when execution starts and stops and resets the boolean of modification_history_was_focused to False each time this notification are observed.
5.843915
5.459163
1.070478
self.history_tree_store.clear() selected_sm_m = self.model.get_selected_state_machine_model() if selected_sm_m: # the core may continue running without the GUI and for this it needs its execution histories if state_machine_execution_engine.finished_or_stopped(): selected_sm_m.state_machine.destroy_execution_histories() self.update()
def clean_history(self, widget, event=None)
Triggered when the 'Clean History' button is clicked. Empties the execution history tree by adjusting the start index and updates tree store and view.
11.560283
10.443255
1.106962
# with self._update_lock: self._update_lock.acquire() self._store_expansion_state() self.history_tree_store.clear() selected_sm_m = self.model.get_selected_state_machine_model() if not selected_sm_m: return for execution_number, execution_history in enumerate(selected_sm_m.state_machine.execution_histories): if len(execution_history) > 0: first_history_item = execution_history[0] # the next lines filter out the StateMachineStartItem, which is not intended to # be displayed, but merely as convenient entry point in the saved log file if isinstance(first_history_item, StateMachineStartItem): if len(execution_history) > 1: first_history_item = execution_history[1] tree_item = self.history_tree_store.insert_after( None, None, (first_history_item.state_reference.name + " - Run " + str(execution_number + 1), first_history_item, self.TOOL_TIP_TEXT)) self.insert_execution_history(tree_item, execution_history[1:], is_root=True) else: pass # there was only the Start item in the history else: tree_item = self.history_tree_store.insert_after( None, None, (first_history_item.state_reference.name + " - Run " + str(execution_number + 1), first_history_item, self.TOOL_TIP_TEXT)) self.insert_execution_history(tree_item, execution_history, is_root=True) self._restore_expansion_state() self._update_lock.release()
def update(self)
rebuild the tree view of the history item tree store :return:
3.35173
3.169244
1.05758
if not history_item.state_reference: logger.error("This must never happen! Current history_item is {}".format(history_item)) return None content = None if global_gui_config.get_config_value("SHOW_PATH_NAMES_IN_EXECUTION_HISTORY", False): content = (history_item.state_reference.name + " - " + history_item.state_reference.get_path() + " - " + description, None if dummy else history_item, None if dummy else self.TOOL_TIP_TEXT) else: content = (history_item.state_reference.name + " - " + description, None if dummy else history_item, None if dummy else self.TOOL_TIP_TEXT) tree_item = self.history_tree_store.insert_before( parent, None, content) return tree_item
def insert_history_item(self, parent, history_item, description, dummy=False)
Enters a single history item into the tree store :param Gtk.TreeItem parent: Parent tree item :param HistoryItem history_item: History item to be inserted :param str description: A description to be added to the entry :param None dummy: Whether this is just a dummy entry (wrapper for concurrency items) :return: Inserted tree item :rtype: Gtk.TreeItem
4.16947
4.196863
0.993473
current_parent = parent execution_history_iterator = iter(execution_history) for history_item in execution_history_iterator: if isinstance(history_item, ConcurrencyItem): self.insert_concurrent_execution_histories(current_parent, history_item.execution_histories) elif isinstance(history_item, CallItem): tree_item = self.insert_history_item(current_parent, history_item, "Enter" if is_root else "Call") if not tree_item: return if history_item.call_type is CallType.EXECUTE: # this is necessary that already the CallType.EXECUTE item opens a new hierarchy in the # tree view and not the CallType.CONTAINER item next_history_item = history_item.next if next_history_item and next_history_item.call_type is CallType.CONTAINER: current_parent = tree_item self.insert_history_item(current_parent, next_history_item, "Enter") try: next(execution_history_iterator) # skips the next history item in the iterator except StopIteration as e: # the execution engine does not have another item return else: # history_item is ReturnItem if current_parent is None: # The reasons here can be: missing history items, items in the wrong order etc. # Does not happen when using RAFCON without plugins logger.error("Invalid execution history: current_parent is None") return if history_item.call_type is CallType.EXECUTE: self.insert_history_item(current_parent, history_item, "Return") else: # CONTAINER self.insert_history_item(current_parent, history_item, "Exit") current_parent = self.history_tree_store.iter_parent(current_parent) is_root = False
def insert_execution_history(self, parent, execution_history, is_root=False)
Insert a list of history items into a the tree store If there are concurrency history items, the method is called recursively. :param Gtk.TreeItem parent: the parent to add the next history item to :param ExecutionHistory execution_history: all history items of a certain state machine execution :param bool is_root: Whether this is the root execution history
4.045884
3.964765
1.02046
for execution_history in concurrent_execution_histories: if len(execution_history) >= 1: first_history_item = execution_history[0] # this is just a dummy item to have an extra parent for each branch # gives better overview in case that one of the child state is a simple execution state tree_item = self.insert_history_item(parent, first_history_item, "Concurrency Branch", dummy=True) self.insert_execution_history(tree_item, execution_history)
def insert_concurrent_execution_histories(self, parent, concurrent_execution_histories)
Adds the child execution histories of a concurrency state. :param Gtk.TreeItem parent: the parent to add the next history item to :param list[ExecutionHistory] concurrent_execution_histories: a list of all child execution histories :return:
6.584224
6.362774
1.034804
library_state = self._get_selected_library_state() import rafcon.gui.helpers.state_machine as gui_helper_state_machine gui_helper_state_machine.add_state_by_drag_and_drop(library_state, data)
def on_drag_data_get(self, widget, context, data, info, time)
dragged state is inserted and its state_id sent to the receiver :param widget: :param context: :param data: SelectionData: contains state_id :param info: :param time:
8.453434
7.690404
1.099218
(model, row_path) = self.view.get_selection().get_selected() if row_path: physical_library_path = model[row_path][self.ITEM_STORAGE_ID] smm = gui_singletons.state_machine_manager_model.state_machine_manager sm = smm.get_open_state_machine_of_file_system_path(physical_library_path) if sm: gui_singletons.state_machine_manager_model.selected_state_machine_id = sm.state_machine_id
def select_open_state_machine_of_selected_library_element(self)
Select respective state machine of selected library in state machine manager if already open
4.150083
4.152991
0.9993
menu_item_text = self.get_menu_item_text(menu_item) logger.info("Delete item '{0}' pressed.".format(menu_item_text)) model, path = self.view.get_selection().get_selected() if path: # Second confirmation to delete library tree_m_row = self.tree_store[path] library_os_path, library_path, library_name, item_key = self.extract_library_properties_from_selected_row() # assert isinstance(tree_m_row[self.ITEM_STORAGE_ID], str) library_file_system_path = library_os_path if "root" in menu_item_text: button_texts = [menu_item_text + "from tree and config", "Cancel"] partial_message = "This will remove the library root from your configuration (config.yaml)." else: button_texts = [menu_item_text, "Cancel"] partial_message = "This folder will be removed from hard drive! You really wanna do that?" message_string = "You choose to {2} with " \ "\n\nlibrary tree path: {0}" \ "\n\nphysical path: {1}.\n\n\n"\ "{3}" \ "".format(os.path.join(self.convert_if_human_readable(tree_m_row[self.LIB_PATH_STORAGE_ID]), item_key), library_file_system_path, menu_item_text.lower(), partial_message) width = 8*len("physical path: " + library_file_system_path) dialog = RAFCONButtonDialog(message_string, button_texts, message_type=Gtk.MessageType.QUESTION, parent=self.get_root_window(), width=min(width, 1400)) response_id = dialog.run() dialog.destroy() if response_id == 1: if "root" in menu_item_text: logger.info("Remove library root key '{0}' from config.".format(item_key)) from rafcon.gui.singleton import global_config library_paths = global_config.get_config_value('LIBRARY_PATHS') del library_paths[tree_m_row[self.LIB_KEY_STORAGE_ID]] global_config.save_configuration() self.model.library_manager.refresh_libraries() elif "libraries" in menu_item_text: logger.debug("Remove of all libraries in {} is triggered.".format(library_os_path)) import shutil shutil.rmtree(library_os_path) self.model.library_manager.refresh_libraries() else: logger.debug("Remove of Library {} is triggered.".format(library_os_path)) self.model.library_manager.remove_library_from_file_system(library_path, library_name) elif response_id in [2, -4]: pass else: logger.warning("Response id: {} is not considered".format(response_id)) return True return False
def menu_item_remove_libraries_or_root_clicked(self, menu_item)
Removes library from hard drive after request second confirmation
4.283175
4.184503
1.02358
(model, row) = self.view.get_selection().get_selected() tree_item_key = model[row][self.ID_STORAGE_ID] library_item = model[row][self.ITEM_STORAGE_ID] library_path = model[row][self.LIB_PATH_STORAGE_ID] if isinstance(library_item, dict): # sub-tree os_path = model[row][self.OS_PATH_STORAGE_ID] return os_path, None, None, tree_item_key # relevant elements of sub-tree assert isinstance(library_item, string_types) library_os_path = library_item library_name = library_os_path.split(os.path.sep)[-1] return library_os_path, library_path, library_name, tree_item_key
def extract_library_properties_from_selected_row(self)
Extracts properties library_os_path, library_path, library_name and tree_item_key from tree store row
3.699026
2.873375
1.287345
library_os_path, library_path, library_name, item_key = self.extract_library_properties_from_selected_row() if library_path is None: return None logger.debug("Link library state '{0}' (with library tree path: {2} and file system path: {1}) into state " "machine.".format(str(item_key), library_os_path, self.convert_if_human_readable(str(library_path)) + "/" + str(item_key))) library_name = library_os_path.split(os.path.sep)[-1] return LibraryState(library_path, library_name, "0.1", format_folder_name_human_readable(library_name))
def _get_selected_library_state(self)
Returns the LibraryState which was selected in the LibraryTree :return: selected state in TreeView :rtype: LibraryState
6.549146
6.328375
1.034886
self.execution_history = execution_history if generate_run_id: self._run_id = run_id_generator() self.backward_execution = copy.copy(backward_execution) self.thread = threading.Thread(target=self.run) self.thread.start()
def start(self, execution_history, backward_execution=False, generate_run_id=True)
Starts the execution of the state in a new thread. :return:
2.561288
2.703745
0.947311
if self.thread: self.thread.join() self.thread = None else: logger.debug("Cannot join {0}, as the state hasn't been started, yet or is already finished!".format(self))
def join(self)
Waits until the state finished execution.
7.415958
5.395878
1.374375
self.state_execution_status = StateExecutionStatus.ACTIVE self.preempted = False if not isinstance(self.input_data, dict): raise TypeError("input_data must be of type dict") if not isinstance(self.output_data, dict): raise TypeError("output_data must be of type dict") self.check_input_data_type()
def setup_run(self)
Executes a generic set of actions that has to be called in the run methods of each derived state class. :raises exceptions.TypeError: if the input or output data are not of type dict
3.607099
2.972469
1.213503
self.preempted = True self.paused = False self.started = False
def recursively_preempt_states(self)
Preempt the state
7.862587
6.610847
1.189346
from rafcon.core.states.library_state import LibraryState result_dict = {} for input_port_key, value in state.input_data_ports.items(): if isinstance(state, LibraryState): if state.use_runtime_value_input_data_ports[input_port_key]: default = state.input_data_port_runtime_values[input_port_key] else: default = value.default_value else: default = value.default_value # if the user sets the default value to a string starting with $, try to retrieve the value # from the global variable manager if isinstance(default, string_types) and len(default) > 0 and default[0] == '$': from rafcon.core.singleton import global_variable_manager as gvm var_name = default[1:] if not gvm.variable_exist(var_name): logger.error("The global variable '{0}' does not exist".format(var_name)) global_value = None else: global_value = gvm.get_variable(var_name) result_dict[value.name] = global_value else: # set input to its default value result_dict[value.name] = copy.copy(default) return result_dict
def get_default_input_values_for_state(self, state)
Computes the default input values for a state :param State state: the state to get the default input values for
3.242601
3.21653
1.008105
from rafcon.core.states.library_state import LibraryState result_dict = {} for key, data_port in state.output_data_ports.items(): if isinstance(state, LibraryState) and state.use_runtime_value_output_data_ports[key]: result_dict[data_port.name] = copy.copy(state.output_data_port_runtime_values[key]) else: result_dict[data_port.name] = copy.copy(data_port.default_value) return result_dict
def create_output_dictionary_for_state(state)
Return empty output dictionary for a state :param state: the state of which the output data is determined :return: the output data of the target state
3.780943
3.842551
0.983967
if data_port_id is None: # All data port ids have to passed to the id generation as the data port id has to be unique inside a state data_port_id = generate_data_port_id(self.get_data_port_ids()) self._input_data_ports[data_port_id] = InputDataPort(name, data_type, default_value, data_port_id, self) # Check for name uniqueness valid, message = self._check_data_port_name(self._input_data_ports[data_port_id]) if not valid: self._input_data_ports[data_port_id].parent = None del self._input_data_ports[data_port_id] raise ValueError(message) return data_port_id
def add_input_data_port(self, name, data_type=None, default_value=None, data_port_id=None)
Add a new input data port to the state. :param str name: the name of the new input data port :param data_type: the type of the new output data port considered of class :class:`type` or :class:`str` which has to be convertible to :class:`type` :param default_value: the default value of the data port :param int data_port_id: the data_port_id of the new data port :return: data_port_id of new input data port :rtype: int :raises exceptions.ValueError: if name of the input port is not unique
3.015994
3.097372
0.973727
if data_port_id in self._input_data_ports: if destroy: self.remove_data_flows_with_data_port_id(data_port_id) self._input_data_ports[data_port_id].parent = None return self._input_data_ports.pop(data_port_id) else: raise AttributeError("input data port with name %s does not exit", data_port_id)
def remove_input_data_port(self, data_port_id, force=False, destroy=True)
Remove an input data port from the state :param int data_port_id: the id or the output data port to remove :param bool force: if the removal should be forced without checking constraints :raises exceptions.AttributeError: if the specified input data port does not exist
2.792438
2.999208
0.931058
if not self.is_root_state: # delete all data flows in parent related to data_port_id and self.state_id data_flow_ids_to_remove = [] for data_flow_id, data_flow in self.parent.data_flows.items(): if data_flow.from_state == self.state_id and data_flow.from_key == data_port_id or \ data_flow.to_state == self.state_id and data_flow.to_key == data_port_id: data_flow_ids_to_remove.append(data_flow_id) for data_flow_id in data_flow_ids_to_remove: self.parent.remove_data_flow(data_flow_id)
def remove_data_flows_with_data_port_id(self, data_port_id)
Remove all data flows whose from_key or to_key equals the passed data_port_id :param data_port_id: the id of a data_port of which all data_flows should be removed, the id can be a input or output data port id
2.327431
2.221099
1.047873
if data_port_id is None: # All data port ids have to passed to the id generation as the data port id has to be unique inside a state data_port_id = generate_data_port_id(self.get_data_port_ids()) self._output_data_ports[data_port_id] = OutputDataPort(name, data_type, default_value, data_port_id, self) # Check for name uniqueness valid, message = self._check_data_port_name(self._output_data_ports[data_port_id]) if not valid: self._output_data_ports[data_port_id].parent = None del self._output_data_ports[data_port_id] raise ValueError(message) return data_port_id
def add_output_data_port(self, name, data_type, default_value=None, data_port_id=None)
Add a new output data port to the state :param str name: the name of the new output data port :param data_type: the type of the new output data port considered of class :class:`type` or :class:`str` which has to be convertible to :class:`type` :param default_value: the default value of the data port :param int data_port_id: the data_port_id of the new data port :return: data_port_id of new output data port :rtype: int :raises exceptions.ValueError: if name of the output port is not unique
2.982672
3.081381
0.967966
if data_port_id in self._output_data_ports: if destroy: self.remove_data_flows_with_data_port_id(data_port_id) self._output_data_ports[data_port_id].parent = None return self._output_data_ports.pop(data_port_id) else: raise AttributeError("output data port with name %s does not exit", data_port_id)
def remove_output_data_port(self, data_port_id, force=False, destroy=True)
Remove an output data port from the state :param int data_port_id: the id of the output data port to remove :raises exceptions.AttributeError: if the specified input data port does not exist
2.774422
2.864763
0.968465
if data_port_type is InputDataPort: for ip_id, output_port in self.input_data_ports.items(): if output_port.name == name: return ip_id raise AttributeError("Name '{0}' is not in input_data_ports".format(name)) elif data_port_type is OutputDataPort: for op_id, output_port in self.output_data_ports.items(): if output_port.name == name: return op_id # 'error' is an automatically generated output port in case of errors and exception and doesn't have an id if name == "error": return raise AttributeError("Name '{0}' is not in output_data_ports".format(name))
def get_io_data_port_id_from_name_and_type(self, name, data_port_type)
Returns the data_port_id of a data_port with a certain name and data port type :param name: the name of the target data_port :param data_port_type: the data port type of the target data port :return: the data port specified by the name and the type :raises exceptions.AttributeError: if the specified data port does not exist in the input or output data ports
3.016627
3.120995
0.966559
if data_port_id in self.input_data_ports: return self.input_data_ports[data_port_id] elif data_port_id in self.output_data_ports: return self.output_data_ports[data_port_id] return None
def get_data_port_by_id(self, data_port_id)
Search for the given data port id in the data ports of the state The method tries to find a data port in the input and output data ports. :param int data_port_id: the unique id of the data port :return: the data port with the searched id or None if it is not found
1.652139
1.76994
0.933444
if by_name: state_identifier = self.name else: state_identifier = self.state_id if not self.is_root_state: if appendix is None: return self.parent.get_path(state_identifier, by_name) else: return self.parent.get_path(state_identifier + PATH_SEPARATOR + appendix, by_name) else: if appendix is None: return state_identifier else: return state_identifier + PATH_SEPARATOR + appendix
def get_path(self, appendix=None, by_name=False)
Recursively create the path of the state. The path is generated in bottom up method i.e. from the nested child states to the root state. The method concatenates either State.state_id (always unique) or State.name (maybe not unique but human readable) as state identifier for the path. :param str appendix: the part of the path that was already calculated by previous function calls :param bool by_name: The boolean enables name usage to generate the path :rtype: str :return: the full path to the root state
2.212743
2.01293
1.099264
state_identifier = storage.get_storage_id_for_state(self) if not self.is_root_state: if appendix is None: return self.parent.get_storage_path(state_identifier) else: return self.parent.get_storage_path(state_identifier + PATH_SEPARATOR + appendix) else: if appendix is None: return state_identifier else: return state_identifier + PATH_SEPARATOR + appendix
def get_storage_path(self, appendix=None)
Recursively create the storage path of the state. The path is generated in bottom up method i.e. from the nested child states to the root state. The method concatenates the concatenation of (State.name and State.state_id) as state identifier for the path. :param str appendix: the part of the path that was already calculated by previous function calls :rtype: str :return: the full path to the root state
2.666851
2.697344
0.988695
if self.parent: if self.is_root_state: return self.parent else: return self.parent.get_state_machine() return None
def get_state_machine(self)
Get a reference of the state_machine the state belongs to :rtype rafcon.core.state_machine.StateMachine :return: respective state machine
3.715851
3.903624
0.951898
if not isinstance(file_system_path, string_types): raise TypeError("file_system_path must be a string") self._file_system_path = file_system_path
def file_system_path(self, file_system_path)
Setter for file_system_path attribute of state :param str file_system_path: :return:
2.208388
2.408467
0.916927
if outcome_id is None: outcome_id = generate_outcome_id(list(self.outcomes.keys())) if name in self._outcomes: logger.error("Two outcomes cannot have the same names") return if outcome_id in self.outcomes: logger.error("Two outcomes cannot have the same outcome_ids") return outcome = Outcome(outcome_id, name, self) self._outcomes[outcome_id] = outcome return outcome_id
def add_outcome(self, name, outcome_id=None)
Add a new outcome to the state :param str name: the name of the outcome to add :param int outcome_id: the optional outcome_id of the new outcome :return: outcome_id: the outcome if of the generated state :rtype: int
2.599854
2.616438
0.993661
if isinstance(state_element, Income): self.remove_income(force, destroy=destroy) if isinstance(state_element, Outcome): return self.remove_outcome(state_element.outcome_id, force=force, destroy=destroy) elif isinstance(state_element, InputDataPort): return self.remove_input_data_port(state_element.data_port_id, force, destroy=destroy) elif isinstance(state_element, OutputDataPort): return self.remove_output_data_port(state_element.data_port_id, force, destroy=destroy) else: raise ValueError("Cannot remove state_element with invalid type")
def remove(self, state_element, recursive=True, force=False, destroy=True)
Remove item from state :param StateElement state_element: State element to be removed :param bool recursive: Only applies to removal of state and decides whether the removal should be called recursively on all child states :param bool force: if the removal should be forced without checking constraints :param bool destroy: a flag that signals that the state element will be fully removed and disassembled
2.266693
2.479165
0.914297
if outcome_id not in self.outcomes: raise AttributeError("There is no outcome_id %s" % str(outcome_id)) if not force: if outcome_id == -1 or outcome_id == -2: raise AttributeError("You cannot remove the outcomes with id -1 or -2 as a state must always be able" "to return aborted or preempted") # Remove internal transitions to this outcome self.remove_outcome_hook(outcome_id) # delete possible transition connected to this outcome if destroy and not self.is_root_state: for transition_id, transition in self.parent.transitions.items(): if transition.from_outcome == outcome_id and transition.from_state == self.state_id: self.parent.remove_transition(transition_id) break # found the one outgoing transition # delete outcome it self self._outcomes[outcome_id].parent = None return self._outcomes.pop(outcome_id)
def remove_outcome(self, outcome_id, force=False, destroy=True)
Remove an outcome from the state :param int outcome_id: the id of the outcome to remove :raises exceptions.AttributeError: if the specified outcome does not exist or equals the aborted or preempted outcome
5.11829
4.686224
1.092199
# Check type of child and call appropriate validity test if isinstance(child, Income): return self._check_income_validity(child) if isinstance(child, Outcome): return self._check_outcome_validity(child) if isinstance(child, DataPort): return self._check_data_port_validity(child) if isinstance(child, ScopedData): return self._check_scoped_data_validity(child) return False, "Invalid state element for state of type {}".format(self.__class__.__name__)
def check_child_validity(self, child)
Check validity of passed child object The method is called by state child objects (outcomes, data ports) when these are initialized or changed. The method checks the type of the child and then checks its validity in the context of the state. :param object child: The child of the state that is to be tested :return bool validity, str message: validity is True, when the child is valid, False else. message gives more information especially if the child is not valid
3.522591
2.801625
1.257339
for outcome_id, outcome in self.outcomes.items(): # Do not compare outcome with itself when checking for existing name/id if check_outcome is not outcome: if check_outcome.outcome_id == outcome_id: return False, "outcome id '{0}' existing in state".format(check_outcome.outcome_id) if check_outcome.name == outcome.name: return False, "outcome name '{0}' existing in state".format(check_outcome.name) return True, "valid"
def _check_outcome_validity(self, check_outcome)
Checks the validity of an outcome Checks whether the id or the name of the outcome is already used by another outcome within the state. :param rafcon.core.logical_port.Outcome check_outcome: The outcome to be checked :return bool validity, str message: validity is True, when the outcome is valid, False else. message gives more information especially if the outcome is not valid
3.31776
2.991939
1.1089
valid, message = self._check_data_port_id(check_data_port) if not valid: return False, message valid, message = self._check_data_port_name(check_data_port) if not valid: return False, message # Check whether the type matches any connected data port type # Only relevant, if there is a parent state, otherwise the port cannot be connected to data flows # TODO: check of internal connections if not self.is_root_state: # Call the check in the parent state, where the data flows are stored return self.parent.check_data_port_connection(check_data_port) else: from rafcon.core.states.container_state import ContainerState if isinstance(self, ContainerState): return self.check_data_port_connection(check_data_port) return True, "valid"
def _check_data_port_validity(self, check_data_port)
Checks the validity of a data port Checks whether the data flows connected to the port do not conflict with the data types. :param rafcon.core.data_port.DataPort check_data_port: The data port to be checked :return bool validity, str message: validity is True, when the data port is valid, False else. message gives more information especially if the data port is not valid
4.458174
3.994132
1.116181
for input_data_port_id, input_data_port in self.input_data_ports.items(): if data_port.data_port_id == input_data_port_id and data_port is not input_data_port: return False, "data port id already existing in state" for output_data_port_id, output_data_port in self.output_data_ports.items(): if data_port.data_port_id == output_data_port_id and data_port is not output_data_port: return False, "data port id already existing in state" return True, "valid"
def _check_data_port_id(self, data_port)
Checks the validity of a data port id Checks whether the id of the given data port is already used by anther data port (input, output) within the state. :param rafcon.core.data_port.DataPort data_port: The data port to be checked :return bool validity, str message: validity is True, when the data port is valid, False else. message gives more information especially if the data port is not valid
1.917455
1.736266
1.104355
if data_port.data_port_id in self.input_data_ports: for input_data_port in self.input_data_ports.values(): if data_port.name == input_data_port.name and data_port is not input_data_port: return False, "data port name already existing in state's input data ports" elif data_port.data_port_id in self.output_data_ports: for output_data_port in self.output_data_ports.values(): if data_port.name == output_data_port.name and data_port is not output_data_port: return False, "data port name already existing in state's output data ports" return True, "valid"
def _check_data_port_name(self, data_port)
Checks the validity of a data port name Checks whether the name of the given data port is already used by anther data port within the state. Names must be unique with input data ports and output data ports. :param rafcon.core.data_port.DataPort data_port: The data port to be checked :return bool validity, str message: validity is True, when the data port is valid, False else. message gives more information especially if the data port is not valid
1.954756
1.792561
1.090482
for data_port in self.input_data_ports.values(): if data_port.name in self.input_data and self.input_data[data_port.name] is not None: #check for class if not isinstance(self.input_data[data_port.name], data_port.data_type): logger.error("{0} had an data port error: Input of execute function must be of type '{1}' not '{2}'" " as current value '{3}'".format(self, data_port.data_type.__name__, type(self.input_data[data_port.name]).__name__, self.input_data[data_port.name]))
def check_input_data_type(self)
Check the input data types of the state Checks all input data ports if the handed data is not of the specified type and generate an error logger message with details of the found type conflict.
3.354319
2.929518
1.145007
for data_port in self.output_data_ports.values(): if data_port.name in self.output_data and self.output_data[data_port.name] is not None: # check for class if not isinstance(self.output_data[data_port.name], data_port.data_type): logger.error("{0} had an data port error: Output of execute function must be of type '{1}' not " "'{2}' as current value {3}".format(self, data_port.data_type.__name__, type(self.output_data[data_port.name]).__name__, self.output_data[data_port.name]))
def check_output_data_type(self)
Check the output data types of the state Checks all output data ports if the handed data is not of the specified type and generate an error logger message with details of the found type conflict.
3.403724
2.957041
1.151057
if state_id is None: state_id = state_id_generator(used_state_ids=[self.state_id]) if not self.is_root_state and not self.is_root_state_of_library: used_ids = list(self.parent.states.keys()) + [self.parent.state_id, self.state_id] if state_id in used_ids: state_id = state_id_generator(used_state_ids=used_ids) self._state_id = state_id
def change_state_id(self, state_id=None)
Changes the id of the state to a new id If no state_id is passed as parameter, a new state id is generated. :param str state_id: The new state id of the state :return:
2.848798
3.027189
0.94107
target_dict = self.semantic_data for path_element in path_as_list: if path_element in target_dict: target_dict = target_dict[path_element] else: raise KeyError("The state with name {1} and id {2} holds no semantic data with path {0}." "".format(path_as_list[:path_as_list.index(path_element) + 1], self.name, self.state_id)) return target_dict
def get_semantic_data(self, path_as_list)
Retrieves an entry of the semantic data. :param list path_as_list: The path in the vividict to retrieve the value from :return:
3.369121
3.449226
0.976776
assert isinstance(key, string_types) target_dict = self.get_semantic_data(path_as_list) target_dict[key] = value return path_as_list + [key]
def add_semantic_data(self, path_as_list, value, key)
Adds a semantic data entry. :param list path_as_list: The path in the vividict to enter the value :param value: The value of the new entry. :param key: The key of the new entry. :return:
3.366578
4.229849
0.79591
if len(path_as_list) == 0: raise AttributeError("The argument path_as_list is empty but but the method remove_semantic_data needs a " "valid path to remove a vividict item.") target_dict = self.get_semantic_data(path_as_list[0:-1]) removed_element = target_dict[path_as_list[-1]] del target_dict[path_as_list[-1]] return removed_element
def remove_semantic_data(self, path_as_list)
Removes a entry from the semantic data vividict. :param list path_as_list: The path of the vividict to delete. :return: removed value or dict
4.345964
3.374361
1.287937
for in_key in list(self.input_data_ports.keys()): self.remove_input_data_port(in_key, force=True, destroy=recursive) for out_key in list(self.output_data_ports.keys()): self.remove_output_data_port(out_key, force=True, destroy=recursive) if self._income: self.remove_income(force=True, destroy=recursive) for outcome_key in list(self.outcomes.keys()): self.remove_outcome(outcome_key, force=True, destroy=recursive)
def destroy(self, recursive)
Removes all the state elements. :param recursive: Flag wether to destroy all state elements which are removed
2.335178
2.562335
0.911348
if not isinstance(input_data_ports, dict): raise TypeError("input_data_ports must be of type dict") if [port_id for port_id, port in input_data_ports.items() if not port_id == port.data_port_id]: raise AttributeError("The key of the input dictionary and the id of the data port do not match") # This is a fix for older state machines, which didn't distinguish between input and output ports for port_id, port in input_data_ports.items(): if not isinstance(port, InputDataPort): if isinstance(port, DataPort): port = InputDataPort(port.name, port.data_type, port.default_value, port.data_port_id) input_data_ports[port_id] = port else: raise TypeError("Elements of input_data_ports must be of type InputDataPort, given: {0}".format( type(port).__name__)) old_input_data_ports = self._input_data_ports self._input_data_ports = input_data_ports for port_id, port in input_data_ports.items(): try: port.parent = self except ValueError: self._input_data_ports = old_input_data_ports raise # check that all old_input_data_ports are no more referencing self as there parent for old_input_data_port in old_input_data_ports.values(): if old_input_data_port not in self._input_data_ports.values() and old_input_data_port.parent is self: old_input_data_port.parent = None
def input_data_ports(self, input_data_ports)
Property for the _input_data_ports field See Property. :param dict input_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type :class:`rafcon.core.state_elements.data_port.InputDataPort` :raises exceptions.TypeError: if the input_data_ports parameter has the wrong type :raises exceptions.AttributeError: if the key of the input dictionary and the id of the data port do not match
2.467485
2.27376
1.0852
if not isinstance(output_data_ports, dict): raise TypeError("output_data_ports must be of type dict") if [port_id for port_id, port in output_data_ports.items() if not port_id == port.data_port_id]: raise AttributeError("The key of the output dictionary and the id of the data port do not match") # This is a fix for older state machines, which didn't distinguish between input and output ports for port_id, port in output_data_ports.items(): if not isinstance(port, OutputDataPort): if isinstance(port, DataPort): port = OutputDataPort(port.name, port.data_type, port.default_value, port.data_port_id) output_data_ports[port_id] = port else: raise TypeError("Elements of output_data_ports must be of type OutputDataPort, given: {0}".format( type(port).__name__)) old_output_data_ports = self._output_data_ports self._output_data_ports = output_data_ports for port_id, port in output_data_ports.items(): try: port.parent = self except ValueError: self._output_data_ports = old_output_data_ports raise # check that all old_output_data_ports are no more referencing self as there parent for old_output_data_port in old_output_data_ports.values(): if old_output_data_port not in self._output_data_ports.values() and old_output_data_port.parent is self: old_output_data_port.parent = None
def output_data_ports(self, output_data_ports)
Setter for _output_data_ports field See property :param dict output_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type :class:`rafcon.core.state_elements.data_port.OutputDataPort` :raises exceptions.TypeError: if the output_data_ports parameter has the wrong type :raises exceptions.AttributeError: if the key of the output dictionary and the id of the data port do not match
2.475539
2.281868
1.084874
if not isinstance(income, Income): raise ValueError("income must be of type Income") old_income = self.income self._income = income try: income.parent = self except ValueError: self._income = old_income raise
def income(self, income)
Setter for the state's income
3.303313
3.326169
0.993128
if not isinstance(outcomes, dict): raise TypeError("outcomes must be of type dict") if [outcome_id for outcome_id, outcome in outcomes.items() if not isinstance(outcome, Outcome)]: raise TypeError("element of outcomes must be of type Outcome") if [outcome_id for outcome_id, outcome in outcomes.items() if not outcome_id == outcome.outcome_id]: raise AttributeError("The key of the outcomes dictionary and the id of the outcome do not match") old_outcomes = self.outcomes self._outcomes = outcomes for outcome_id, outcome in outcomes.items(): try: outcome.parent = self except ValueError: self._outcomes = old_outcomes raise # aborted and preempted must always exist if -1 not in outcomes: self._outcomes[-1] = Outcome(outcome_id=-1, name="aborted", parent=self) if -2 not in outcomes: self._outcomes[-2] = Outcome(outcome_id=-2, name="preempted", parent=self) # check that all old_outcomes are no more referencing self as there parent for old_outcome in old_outcomes.values(): if old_outcome not in iter(list(self._outcomes.values())) and old_outcome.parent is self: old_outcome.parent = None
def outcomes(self, outcomes)
Setter for _outcomes field See property. :param dict outcomes: Dictionary outcomes[outcome_id] that maps :class:`int` outcome_ids onto values of type :class:`rafcon.core.state_elements.logical_port.Outcome` :raises exceptions.TypeError: if outcomes parameter has the wrong type :raises exceptions.AttributeError: if the key of the outcome dictionary and the id of the outcome do not match
2.827133
2.611081
1.082744
from rafcon.core.states.library_state import LibraryState return isinstance(self.parent, LibraryState)
def is_root_state_of_library(self)
If self is the attribute LibraryState.state_copy of a LibraryState its the library root state and its parent is a LibraryState :return True or False :rtype bool
10.052298
8.028709
1.252044
from rafcon.core.state_machine import StateMachine if self.is_root_state_of_library: return self state = self while state.parent is not None and not isinstance(state.parent, StateMachine): if state.parent.is_root_state_of_library: return state.parent state = state.parent return None
def get_next_upper_library_root_state(self)
Get next upper library root state The method recursively checks state parent states till finding a StateMachine as parent or a library root state. If self is a LibraryState the next upper library root state is searched and it is not handed self.state_copy. :return library root state (Execution or ContainerState) or None if self is not a library root state or inside of such :rtype rafcon.core.states.library_state.State:
3.513957
2.487322
1.412747
library_root_state = self.get_next_upper_library_root_state() parent_library_root_state = library_root_state # initial a library root state has to be found and if there is no further parent root state # parent_library_root_state and library_root_state are no more identical while parent_library_root_state and library_root_state is parent_library_root_state: if library_root_state: parent_library_root_state = library_root_state.parent.get_next_upper_library_root_state() if parent_library_root_state: library_root_state = parent_library_root_state return library_root_state
def get_uppermost_library_root_state(self)
Find state_copy of uppermost LibraryState Method checks if there is a parent library root state and assigns it to be the current library root state till there is no further parent library root state.
3.134434
2.776105
1.129076
# Set the final outcome of the state if outcome is not None: self.final_outcome = outcome # If we are within a concurrency state, we have to notify it about our finalization if self.concurrency_queue: self.concurrency_queue.put(self.state_id) logger.debug("Finished execution of {0}: {1}".format(self, self.final_outcome)) return None
def finalize(self, outcome=None)
Finalize state This method is called when the run method finishes :param rafcon.core.logical_port.Outcome outcome: final outcome of the state :return: Nothing for the moment
5.309249
5.430619
0.977651
network_c = Network() buses = aggregatebuses( network, busmap, { 'x': _leading( busmap, network.buses), 'y': _leading( busmap, network.buses)}) # keep attached lines lines = network.lines.copy() mask = lines.bus0.isin(buses.index) lines = lines.loc[mask, :] # keep attached links links = network.links.copy() mask = links.bus0.isin(buses.index) links = links.loc[mask, :] # keep attached transformer transformers = network.transformers.copy() mask = transformers.bus0.isin(buses.index) transformers = transformers.loc[mask, :] io.import_components_from_dataframe(network_c, buses, "Bus") io.import_components_from_dataframe(network_c, lines, "Line") io.import_components_from_dataframe(network_c, links, "Link") io.import_components_from_dataframe(network_c, transformers, "Transformer") if with_time: network_c.snapshots = network.snapshots network_c.set_snapshots(network.snapshots) network_c.snapshot_weightings = network.snapshot_weightings.copy() # dealing with generators network.generators.control = "PV" network.generators['weight'] = 1 new_df, new_pnl = aggregategenerators(network, busmap, with_time) io.import_components_from_dataframe(network_c, new_df, 'Generator') for attr, df in iteritems(new_pnl): io.import_series_from_dataframe(network_c, df, 'Generator', attr) # dealing with all other components aggregate_one_ports = components.one_port_components.copy() aggregate_one_ports.discard('Generator') for one_port in aggregate_one_ports: new_df, new_pnl = aggregateoneport( network, busmap, component=one_port, with_time=with_time) io.import_components_from_dataframe(network_c, new_df, one_port) for attr, df in iteritems(new_pnl): io.import_series_from_dataframe(network_c, df, one_port, attr) network_c.determine_network_topology() return network_c
def cluster_on_extra_high_voltage(network, busmap, with_time=True)
Main function of the EHV-Clustering approach. Creates a new clustered pypsa.Network given a busmap mapping all bus_ids to other bus_ids of the same network. Parameters ---------- network : pypsa.Network Container for all network components. busmap : dict Maps old bus_ids to new bus_ids. with_time : bool If true time-varying data will also be aggregated. Returns ------- network : pypsa.Network Container for all network components of the clustered network.
2.671345
2.784112
0.959497
M = nx.MultiGraph() for e in edges: n0, n1, weight, key = e M.add_edge(n0, n1, weight=weight, key=key) return M
def graph_from_edges(edges)
Constructs an undirected multigraph from a list containing data on weighted edges. Parameters ---------- edges : list List of tuples each containing first node, second node, weight, key. Returns ------- M : :class:`networkx.classes.multigraph.MultiGraph
3.333912
3.228939
1.03251
# TODO There could be a more convenient way of doing this. This generators # single purpose is to prepare data for multiprocessing's starmap function. g = graph.copy() for i in range(0, len(nodes), n): yield (nodes[i:i + n], g)
def gen(nodes, n, graph)
Generator for applying multiprocessing. Parameters ---------- nodes : list List of nodes in the system. n : int Number of desired multiprocessing units. graph : :class:`networkx.classes.multigraph.MultiGraph Graph representation of an electrical grid. Returns ------- None
11.535728
11.861383
0.972545
def fetch(): query = session.query(EgoGridPfHvBusmap.bus0, EgoGridPfHvBusmap.bus1).\ filter(EgoGridPfHvBusmap.scn_name == scn_name) return dict(query.all()) busmap = fetch() # TODO: Or better try/except/finally if not busmap: print('Busmap does not exist and will be created.\n') cpu_cores = input('cpu_cores (default 4): ') or '4' busmap_by_shortest_path(network, session, scn_name, fromlvl=[110], tolvl=[220, 380, 400, 450], cpu_cores=int(cpu_cores)) busmap = fetch() return busmap
def busmap_from_psql(network, session, scn_name)
Retrieves busmap from `model_draft.ego_grid_pf_hv_busmap` on the <OpenEnergyPlatform>[www.openenergy-platform.org] by a given scenario name. If this busmap does not exist, it is created with default values. Parameters ---------- network : pypsa.Network object Container for all network components. session : sqlalchemy.orm.session.Session object Establishes interactions with the database. scn_name : str Name of the scenario. Returns ------- busmap : dict Maps old bus_ids to new bus_ids.
5.768881
4.63146
1.245586
super(DescriptionEditorController, self).register_actions(shortcut_manager) shortcut_manager.add_callback_for_action("abort", self._abort)
def register_actions(self, shortcut_manager)
Register callback methods for triggered actions :param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings between shortcuts and actions.
9.350896
7.680743
1.217447
super(GraphicalEditorController, self).register_view(view) self.view.connect('meta_data_changed', self._meta_data_changed) self.focus_changed_handler_id = self.view.editor.connect('focus-changed', self._move_focused_item_into_viewport) self.view.editor.connect("drag-data-received", self.on_drag_data_received) self.drag_motion_handler_id = self.view.editor.connect("drag-motion", self.on_drag_motion) self.setup_canvas()
def register_view(self, view)
Called when the View was registered
3.715854
3.690944
1.006749
shortcut_manager.add_callback_for_action("add", partial(self._add_new_state, state_type=StateType.EXECUTION)) shortcut_manager.add_callback_for_action("add_execution_state", partial(self._add_new_state, state_type=StateType.EXECUTION)) shortcut_manager.add_callback_for_action("add_hierarchy_state", partial(self._add_new_state, state_type=StateType.HIERARCHY)) shortcut_manager.add_callback_for_action("add_barrier_state", partial(self._add_new_state, state_type=StateType.BARRIER_CONCURRENCY)) shortcut_manager.add_callback_for_action("add_preemptive_state", partial(self._add_new_state, state_type=StateType.PREEMPTION_CONCURRENCY)) shortcut_manager.add_callback_for_action("add_output", partial(self._add_data_port_to_selected_state, data_port_type='OUTPUT')) shortcut_manager.add_callback_for_action("add_input", partial(self._add_data_port_to_selected_state, data_port_type='INPUT')) shortcut_manager.add_callback_for_action("add_scoped_variable", self._add_scoped_variable_to_selected_state) shortcut_manager.add_callback_for_action("add_outcome", self._add_outcome_to_selected_state) shortcut_manager.add_callback_for_action("delete", self._remove_selected_elements) shortcut_manager.add_callback_for_action("copy", self._copy_selection) shortcut_manager.add_callback_for_action("paste", self._paste_clipboard) shortcut_manager.add_callback_for_action("cut", self._cut_selection) shortcut_manager.add_callback_for_action('show_data_flows', self.update_view) shortcut_manager.add_callback_for_action('show_data_values', self.update_view) shortcut_manager.add_callback_for_action('data_flow_mode', self.data_flow_mode) shortcut_manager.add_callback_for_action('show_aborted_preempted', self.update_view)
def register_actions(self, shortcut_manager)
Register callback methods for triggered actions :param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings between shortcuts and actions.
1.986754
1.973637
1.006646
config_key = info['args'][1] # config_value = info['args'][2] if config_key in ["ENABLE_CACHING", "SHOW_ABORTED_PREEMPTED", "SHOW_DATA_FLOWS", "SHOW_DATA_FLOW_VALUE_LABELS", "SHOW_NAMES_ON_DATA_FLOWS", "ROTATE_NAMES_ON_CONNECTION"]: self.update_view()
def on_config_value_changed(self, config_m, prop_name, info)
Callback when a config value has been changed :param ConfigModel config_m: The config model that has been changed :param str prop_name: Should always be 'config' :param dict info: Information e.g. about the changed config key
8.422421
9.453359
0.890945
state_id_insert = data.get_text() parent_m = self.model.selection.get_selected_state() if not isinstance(parent_m, ContainerStateModel): return state_v = self.canvas.get_view_for_model(parent_m.states[state_id_insert]) pos_start = state_v.model.get_meta_data_editor()['rel_pos'] motion = InMotion(state_v, self.view.editor) motion.start_move(self.view.editor.get_matrix_i2v(state_v).transform_point(pos_start[0], pos_start[1])) motion.move((x, y)) motion.stop_move() state_v.model.set_meta_data_editor('rel_pos', motion.item.position) self.canvas.wait_for_update(trigger_update=True) self._meta_data_changed(None, state_v.model, 'append_to_last_change', True)
def on_drag_data_received(self, widget, context, x, y, data, info, time)
Receives state_id from LibraryTree and moves the state to the position of the mouse :param widget: :param context: :param x: Integer: x-position of mouse :param y: Integer: y-position of mouse :param data: SelectionData: contains state_id :param info: :param time:
6.100075
5.950928
1.025063
hovered_item = ItemFinder(self.view.editor).get_item_at_point((x, y)) if isinstance(hovered_item, NameView): hovered_item = hovered_item.parent if hovered_item is None: self.view.editor.unselect_all() elif isinstance(hovered_item.model, ContainerStateModel): if len(self.view.editor.selected_items) == 1 and hovered_item in self.view.editor.selected_items: return if len(self.view.editor.selected_items) > 0: self.view.editor.unselect_all() if not rafcon.gui.singleton.global_gui_config.get_config_value('DRAG_N_DROP_WITH_FOCUS'): self.view.editor.handler_block(self.focus_changed_handler_id) self.view.editor.focused_item = hovered_item if not rafcon.gui.singleton.global_gui_config.get_config_value('DRAG_N_DROP_WITH_FOCUS'): self.view.editor.handler_unblock(self.focus_changed_handler_id)
def on_drag_motion(self, widget, context, x, y, time)
Changes the selection on mouse over during drag motion :param widget: :param context: :param x: Integer: x-position of mouse :param y: Integer: y-position of mouse :param time:
2.996083
3.129306
0.957427
if react_to_event(self.view, self.view.editor, event): state_type = StateType.EXECUTION if 'state_type' not in kwargs else kwargs['state_type'] return gui_helper_state_machine.add_new_state(self.model, state_type)
def _add_new_state(self, *event, **kwargs)
Triggered when shortcut keys for adding a new state are pressed, or Menu Bar "Edit, Add State" is clicked. Adds a new state only if the graphical editor is in focus.
6.886406
6.872108
1.002081
if react_to_event(self.view, self.view.editor, event): logger.debug("copy selection") global_clipboard.copy(self.model.selection) return True
def _copy_selection(self, *event)
Copies the current selection to the clipboard.
9.696259
8.462726
1.145761
if react_to_event(self.view, self.view.editor, event): logger.debug("cut selection") global_clipboard.cut(self.model.selection) return True
def _cut_selection(self, *event)
Cuts the current selection and copys it to the clipboard.
10.463627
8.90394
1.175168
if react_to_event(self.view, self.view.editor, event): logger.debug("Paste") gui_helper_state_machine.paste_into_selected_state(self.model) return True
def _paste_clipboard(self, *event)
Paste the current clipboard into the current selection if the current selection is a container state.
12.746082
9.759113
1.30607
self.view.editor.handler_block(self.drag_motion_handler_id) self.move_item_into_viewport(focused_item) self.view.editor.handler_unblock(self.drag_motion_handler_id)
def _move_focused_item_into_viewport(self, view, focused_item)
Called when an item is focused, moves the item into the viewport :param view: :param StateView | ConnectionView | PortView focused_item: The focused item
3.386444
3.566251
0.949581
if not item: return HORIZONTAL = 0 VERTICAL = 1 if not isinstance(item, Item): state_v = item.parent elif not isinstance(item, StateView): state_v = self.canvas.get_parent(item) else: state_v = item viewport_size = self.view.editor.get_allocation().width, self.view.editor.get_allocation().height state_size = self.view.editor.get_matrix_i2v(state_v).transform_distance(state_v.width, state_v.height) min_relative_size = min(viewport_size[i] / state_size[i] for i in [HORIZONTAL, VERTICAL]) if min_relative_size != 1: # Allow margin around state margin_relative = 1. / gui_constants.BORDER_WIDTH_STATE_SIZE_FACTOR zoom_factor = min_relative_size * (1 - margin_relative) if zoom_factor > 1: zoom_base = 4 zoom_factor = max(1, math.log(zoom_factor*zoom_base, zoom_base)) self.view.editor.zoom(zoom_factor) # The zoom operation must be performed before the pan operation to work on updated GtkAdjustments (scroll # bars) self.canvas.wait_for_update() state_pos = self.view.editor.get_matrix_i2v(state_v).transform_point(0, 0) state_size = self.view.editor.get_matrix_i2v(state_v).transform_distance(state_v.width, state_v.height) viewport_size = self.view.editor.get_allocation().width, self.view.editor.get_allocation().height # Calculate offset around state so that the state is centered in the viewport padding_offset_horizontal = (viewport_size[HORIZONTAL] - state_size[HORIZONTAL]) / 2. padding_offset_vertical = (viewport_size[VERTICAL] - state_size[VERTICAL]) / 2. self.view.editor.hadjustment.set_value(state_pos[HORIZONTAL] - padding_offset_horizontal) self.view.editor.vadjustment.set_value(state_pos[VERTICAL] - padding_offset_vertical)
def move_item_into_viewport(self, item)
Causes the `item` to be moved into the viewport The zoom factor and the position of the viewport are updated to move the `item` into the viewport. If `item` is not a `StateView`, the parental `StateView` is moved into the viewport. :param StateView | ConnectionView | PortView item: The item to be moved into the viewport
3.07743
3.037743
1.013065
if self.model is model: # only used for the state machine destruction case self.canvas.get_view_for_model(self.root_state_m).remove()
def state_machine_destruction(self, model, prop_name, info)
Clean up when state machine is being destructed
16.76527
15.474015
1.083447
meta_signal_message = info['arg'] if meta_signal_message.origin == "graphical_editor_gaphas": # Ignore changes caused by ourself return if meta_signal_message.origin == "load_meta_data": # Meta data can't be applied, as the view has not yet return # been created notification = meta_signal_message.notification if not notification: # For changes applied to the root state, there are always two notifications return # Ignore the one with less information if self.model.ongoing_complex_actions: return model = notification.model view = self.canvas.get_view_for_model(model) if meta_signal_message.change == 'show_content': library_state_m = model library_state_v = view if library_state_m.meta['gui']['show_content'] is not library_state_m.show_content(): logger.warning("The content of the LibraryState won't be shown, because " "MAX_VISIBLE_LIBRARY_HIERARCHY is 1.") if library_state_m.show_content(): if not library_state_m.state_copy_initialized: logger.warning("Show library content without initialized state copy does not work {0}" "".format(library_state_m)) logger.debug("Show content of {}".format(library_state_m.state)) gui_helper_meta_data.scale_library_content(library_state_m) self.add_state_view_for_model(library_state_m.state_copy, view, hierarchy_level=library_state_v.hierarchy_level + 1) else: logger.debug("Hide content of {}".format(library_state_m.state)) state_copy_v = self.canvas.get_view_for_model(library_state_m.state_copy) if state_copy_v: state_copy_v.remove() else: if isinstance(view, StateView): view.apply_meta_data(recursive=meta_signal_message.affects_children) else: view.apply_meta_data() self.canvas.request_update(view, matrix=True) self.canvas.wait_for_update()
def meta_changed_notify_after(self, state_machine_m, _, info)
Handle notification about the change of a state's meta data The meta data of the affected state(s) are read and the view updated accordingly. :param StateMachineModel state_machine_m: Always the state machine model belonging to this editor :param str _: Always "state_meta_signal" :param dict info: Information about the change, contains the MetaSignalMessage in the 'arg' key value
5.59145
5.185667
1.078251
state_machine_m = self.model state_v = self.canvas.get_view_for_model(state_m) if state_v is None: logger.warning('There is no view for state model {0}'.format(state_m)) self.move_item_into_viewport(state_v) # check_relative size in view and call it again if the state is still very small state_v = self.canvas.get_view_for_model(state_machine_m.root_state) state_size = self.view.editor.get_matrix_i2v(state_v).transform_distance(state_v.width, state_v.height) viewport_size = self.view.editor.get_allocation().width, self.view.editor.get_allocation().height if state_size[0] < ratio_requested*viewport_size[0] and state_size[1] < ratio_requested*viewport_size[1]: self.set_focus_to_state_model(state_m, ratio_requested)
def set_focus_to_state_model(self, state_m, ratio_requested=0.8)
Focus a state view of respective state model :param rafcon.gui.model.state state_m: Respective state model of state view to be focused :param ratio_requested: Minimum ratio of the screen which is requested, so can be more :return:
3.86407
3.877949
0.996421
parent_state_v = self.canvas.get_view_for_model(parent_state_m) hierarchy_level = parent_state_v.hierarchy_level transition_v = TransitionView(transition_m, hierarchy_level) # Draw transition above all other state elements self.canvas.add(transition_v, parent_state_v, index=None) self._connect_transition_to_ports(transition_m, transition_v, parent_state_m, parent_state_v) return transition_v
def add_transition_view_for_model(self, transition_m, parent_state_m)
Creates a `TransitionView` and adds it to the canvas The method creates a`TransitionView` from the given `TransitionModel `transition_m` and adds it to the canvas. :param TransitionModel transition_m: The transition for which a view is to be created :param ContainerStateModel parent_state_m: The parental `StateModel` of the transition
3.559163
3.663338
0.971563
parent_state_v = self.canvas.get_view_for_model(parent_state_m) hierarchy_level = parent_state_v.hierarchy_level data_flow_v = DataFlowView(data_flow_m, hierarchy_level) # Draw data flow above NameView but beneath all other state elements self.canvas.add(data_flow_v, parent_state_v, index=1) self._connect_data_flow_to_ports(data_flow_m, data_flow_v, parent_state_m)
def add_data_flow_view_for_model(self, data_flow_m, parent_state_m)
Creates a `DataFlowView` and adds it to the canvas The method creates a`DataFlowView` from the given `DataFlowModel `data_flow_m` and adds it to the canvas. :param DataFlowModel data_flow_m: The data flow for which a view is to be created :param ContainerStateModel parent_state_m: The parental `StateModel` of the data flow
4.001435
4.144979
0.965369
if not react_to_event(self.view, self.view.editor, event): return False if not rafcon.gui.singleton.state_machine_manager_model.selected_state_machine_id == \ self.model.state_machine.state_machine_id: return False return True
def react_to_event(self, event)
Check whether the given event should be handled Checks, whether the editor widget has the focus and whether the selected state machine corresponds to the state machine of this editor. :param event: GTK event object :return: True if the event should be handled, else False :rtype: bool
8.156754
6.092654
1.338785
global _loop _loop = bot.loop player_manager.user_id = bot.user.id player_manager.channel_finder_func = bot.get_channel register_event_listener(_handle_event) register_update_listener(_handle_update) lavalink_node = node.Node( _loop, dispatch, bot._connection._get_websocket, host, password, port=ws_port, rest=rest_port, user_id=player_manager.user_id, num_shards=bot.shard_count if bot.shard_count is not None else 1, ) await lavalink_node.connect(timeout=timeout) bot.add_listener(node.on_socket_response) bot.add_listener(_on_guild_remove, name="on_guild_remove") return lavalink_node
async def initialize(bot: Bot, host, password, rest_port, ws_port, timeout=30)
Initializes the websocket connection to the lavalink player. .. important:: This function must only be called AFTER the bot has received its "on_ready" event! Parameters ---------- bot : Bot An instance of a discord.py `Bot` object. host : str The hostname or IP address of the Lavalink node. password : str The password of the Lavalink node. rest_port : int The port of the REST API on the Lavalink node. ws_port : int The websocket port on the Lavalink Node. timeout : int Amount of time to allow retries to occur, ``None`` is considered forever.
4.072563
4.040466
1.007944
node_ = node.get_node(channel.guild.id) p = await node_.player_manager.create_player(channel) return p
async def connect(channel: discord.VoiceChannel)
Connects to a discord voice channel. This is the publicly exposed way to connect to a discord voice channel. The :py:func:`initialize` function must be called first! Parameters ---------- channel Returns ------- Player The created Player object. Raises ------ IndexError If there are no available lavalink nodes ready to connect to discord.
7.778236
9.826791
0.791534
if not asyncio.iscoroutinefunction(coro): raise TypeError("Function is not a coroutine.") if coro not in _event_listeners: _event_listeners.append(coro)
def register_event_listener(coro)
Registers a coroutine to receive lavalink event information. This coroutine will accept three arguments: :py:class:`Player`, :py:class:`LavalinkEvents`, and possibly an extra. The value of the extra depends on the value of the second argument. If the second argument is :py:attr:`LavalinkEvents.TRACK_END`, the extra will be a :py:class:`TrackEndReason`. If the second argument is :py:attr:`LavalinkEvents.TRACK_EXCEPTION`, the extra will be an error string. If the second argument is :py:attr:`LavalinkEvents.TRACK_STUCK`, the extra will be the threshold milliseconds that the track has been stuck for. If the second argument is :py:attr:`LavalinkEvents.TRACK_START`, the extra will be a :py:class:`Track` object. If the second argument is any other value, the third argument will not exist. Parameters ---------- coro A coroutine function that accepts the arguments listed above. Raises ------ TypeError If ``coro`` is not a coroutine.
2.804415
4.376673
0.640764
if not asyncio.iscoroutinefunction(coro): raise TypeError("Function is not a coroutine.") if coro not in _update_listeners: _update_listeners.append(coro)
def register_update_listener(coro)
Registers a coroutine to receive lavalink player update information. This coroutine will accept a two arguments: an instance of :py:class:`Player` and an instance of :py:class:`PlayerState`. Parameters ---------- coro Raises ------ TypeError If ``coro`` is not a coroutine.
2.790328
3.945185
0.707274
if not asyncio.iscoroutinefunction(coro): raise TypeError("Function is not a coroutine.") if coro not in _stats_listeners: _stats_listeners.append(coro)
def register_stats_listener(coro)
Registers a coroutine to receive lavalink server stats information. This coroutine will accept a single argument which will be an instance of :py:class:`Stats`. Parameters ---------- coro Raises ------ TypeError If ``coro`` is not a coroutine.
2.751209
3.995045
0.688655
self._tool = None self._painter = None self.relieve_model(self._selection) self._selection = None # clear observer class attributes, also see ExtendenController.destroy() self._Observer__PROP_TO_METHS.clear() self._Observer__METH_TO_PROPS.clear() self._Observer__PAT_TO_METHS.clear() self._Observer__METH_TO_PAT.clear() self._Observer__PAT_METH_TO_KWARGS.clear()
def prepare_destruction(self)
Get rid of circular references
8.265122
7.578549
1.090594
# Method had to be inherited, as the base method has a bug: # It misses the statement max_dist = d v2i = self.get_matrix_v2i vx, vy = vpos max_dist = distance port = None glue_pos = None item = None rect = (vx - distance, vy - distance, distance * 2, distance * 2) items = self.get_items_in_rectangle(rect, reverse=True) for i in items: if exclude and i in exclude: continue for p in i.ports(): if not p.connectable: continue if exclude_port_fun and exclude_port_fun(p): continue ix, iy = v2i(i).transform_point(vx, vy) pg, d = p.glue((ix, iy)) if d > max_dist: continue max_dist = d item = i port = p # transform coordinates from connectable item space to view # space i2v = self.get_matrix_i2v(i).transform_point glue_pos = i2v(*pg) return item, port, glue_pos
def get_port_at_point(self, vpos, distance=10, exclude=None, exclude_port_fun=None)
Find item with port closest to specified position. List of items to be ignored can be specified with `exclude` parameter. Tuple is returned - found item - closest, connectable port - closest point on found port (in view coordinates) :Parameters: vpos Position specified in view coordinates. distance Max distance from point to a port (default 10) exclude Set of items to ignore.
4.902061
4.786205
1.024206
items = self._qtree.find_intersect((pos[0], pos[1], 1, 1)) for item in self._canvas.sort(items, reverse=True): if not selected and item in self.selected_items: continue # skip selected items if item in exclude: continue v2i = self.get_matrix_v2i(item) ix, iy = v2i.transform_point(*pos) if item.point((ix, iy)) < 0.5: return item return None
def get_item_at_point_exclude(self, pos, selected=True, exclude=None)
Return the topmost item located at ``pos`` (x, y). Parameters: - selected: if False returns first non-selected item - exclude: if specified don't check for these items
4.976125
5.594161
0.889521
gaphas_items = [] for item in items: if isinstance(item, Element): gaphas_items.append(item) else: try: gaphas_items.append(item.parent) except AttributeError: pass super(ExtendedGtkView, self).queue_draw_item(*gaphas_items)
def queue_draw_item(self, *items)
Extends the base class method to allow Ports to be passed as item :param items: Items that are to be redrawn
3.838955
4.119693
0.931855
items = self._qtree.find_intersect((pos[0] - distance, pos[1] - distance, 2 * distance, 2 * distance)) filtered_items = [] for item in self._canvas.sort(items, reverse=True): if not selected and item in self.selected_items: continue # skip selected items v2i = self.get_matrix_v2i(item) i2v = self.get_matrix_i2v(item) ix, iy = v2i.transform_point(*pos) distance_i = item.point((ix, iy)) distance_v = i2v.transform_distance(distance_i, 0)[0] if distance_v <= distance: filtered_items.append(item) return filtered_items
def get_items_at_point(self, pos, selected=True, distance=0)
Return the items located at ``pos`` (x, y). :param bool selected: if False returns first non-selected item :param float distance: Maximum distance to be considered as "at point" (in viewport pixel)
3.562135
3.664108
0.97217
if not items: return elif not hasattr(items, "__iter__"): items = (items,) selection_changed = False with self._suppress_selection_events(): for item in items: self.queue_draw_item(item) if item is not None and item.model not in self._selection: self._selection.add(item.model) selection_changed = True if selection_changed: self.emit('selection-changed', self._get_selected_items())
def select_item(self, items)
Select an items. This adds `items` to the set of selected items.
3.069423
2.844323
1.07914
self.queue_draw_item(item) if item.model in self._selection: with self._suppress_selection_events(): self._selection.remove(item.model) self.emit('selection-changed', self._get_selected_items())
def unselect_item(self, item)
Unselect an item.
5.154698
4.935197
1.044477
items = self._get_selected_items() with self._suppress_selection_events(): self._selection.clear() self.queue_draw_item(*items) self.emit('selection-changed', self._get_selected_items())
def unselect_all(self)
Clearing the selected_item also clears the focused_item.
5.324268
5.085895
1.04687
return set(self.canvas.get_view_for_model(model) for model in self._selection)
def _get_selected_items(self)
Return an Item (e.g. StateView) for each model (e.g. StateModel) in the current selection
15.388551
7.198242
2.137821
if items is None: items = () elif not hasattr(items, "__iter__"): items = (items,) models = set(item.model for item in items) self._selection.handle_new_selection(models)
def handle_new_selection(self, items)
Determines the selection The selection is based on the previous selection, the currently pressed keys and the passes newly selected items :param items: The newly selected item(s)
3.523543
4.651376
0.757527
focused_model = self._selection.focus if not focused_model: return None return self.canvas.get_view_for_model(focused_model)
def _get_focused_item(self)
Returns the currently focused item
7.465989
6.84926
1.090043
if not item: return self._del_focused_item() if item.model is not self._selection.focus: self.queue_draw_item(self._focused_item, item) self._selection.focus = item.model self.emit('focus-changed', item)
def _set_focused_item(self, item)
Sets the focus to the passed item
5.236814
5.189744
1.00907
previous = {} next_ = {} concurrent = {} grouped_by_run_id = {} start_item = None for k,v in execution_history_items.items(): if v['item_type'] == 'StateMachineStartItem': start_item = v else: # connect the item to its predecessor prev_item_id = native_str(v['prev_history_item_id']) if prev_item_id in execution_history_items: ## should always be the case except if shelve is broken/missing data previous[k] = prev_item_id if execution_history_items[prev_item_id]['item_type'] == 'ConcurrencyItem' and \ execution_history_items[k]['item_type'] != 'ReturnItem': # this is not a return item, thus this 'previous' relationship of this # item must be a call item of one of the concurrent branches of # the concurrency state if prev_item_id in concurrent: concurrent[prev_item_id].append(k) else: concurrent[prev_item_id] = [k] else: # this is a logical 'next' relationship next_[prev_item_id] = k else: logger.warning('HistoryItem is referring to a non-existing previous history item, HistoryItem was %s' % str(v)) rid = v['run_id'] if rid in grouped_by_run_id: grouped_by_run_id[rid].append(v) else: grouped_by_run_id[rid] = [v] return start_item, previous, next_, concurrent, grouped_by_run_id
def log_to_raw_structure(execution_history_items)
:param dict execution_history_items: history items, in the simplest case directly the opened shelve log file :return: start_item, the StateMachineStartItem of the log file previous, a dict mapping history_item_id --> history_item_id of previous history item next_, a dict mapping history_item_id --> history_item_id of the next history item (except if next item is a concurrent execution branch) concurrent, a dict mapping history_item_id --> []list of concurrent next history_item_ids (if present) grouped, a dict mapping run_id --> []list of history items with this run_id :rtype: tuple
4.161215
3.402051
1.223149
try: import pandas as pd except ImportError: raise ImportError("The Python package 'pandas' is required for log_to_DataFrame.") start, next_, concurrency, hierarchy, gitems = log_to_collapsed_structure( execution_history_items, throw_on_pickle_error=throw_on_pickle_error) gitems.pop(start['run_id']) if len(gitems) == 0: return pd.DataFrame() # remove columns which are not generic over all states (basically the # data flow stuff) df_keys = list(list(gitems.values())[0].keys()) df_keys.remove('data_ins') df_keys.remove('data_outs') df_keys.remove('scoped_data_ins') df_keys.remove('scoped_data_outs') df_keys.remove('semantic_data') df_keys.sort() df_items = [] for rid, item in gitems.items(): row_data = [item[k] for k in df_keys] for key, selected_columns in [('data_ins', data_in_columns), ('data_outs', data_out_columns), ('scoped_data_ins', scoped_in_columns), ('scoped_data_outs', scoped_out_columns), ('semantic_data', semantic_data_columns)]: for column_key in selected_columns: row_data.append(item[key].get(column_key, None)) df_items.append(row_data) for key, selected_columns in [('data_ins', data_in_columns), ('data_outs', data_out_columns), ('scoped_data_ins', scoped_in_columns), ('scoped_data_outs', scoped_out_columns), ('semantic_data', semantic_data_columns)]: df_keys.extend([key + '__' + s for s in selected_columns]) df = pd.DataFrame(df_items, columns=df_keys) # convert epoch to datetime df.timestamp_call = pd.to_datetime(df.timestamp_call, unit='s') df.timestamp_return = pd.to_datetime(df.timestamp_return, unit='s') # use call timestamp as index df_timed = df.set_index(df.timestamp_call) df_timed.sort_index(inplace=True) return df_timed
def log_to_DataFrame(execution_history_items, data_in_columns=[], data_out_columns=[], scoped_in_columns=[], scoped_out_columns=[], semantic_data_columns=[], throw_on_pickle_error=True)
Returns all collapsed items in a table-like structure (pandas.DataFrame) with one row per executed state and a set of properties resp. columns (e.g. state_name, outcome, run_id) for this state. The data flow (data_in/out, scoped_data_in/out, semantic_data) is omitted from this table representation by default, as the different states have different data in-/out-port, scoped_data- ports and semantic_data defined. However, you can ask specific data-/scoped_data-ports and semantic data to be exported as table column, given they are primitive-valued, by including the port / key names in the *_selected-parameters. These table-columns will obviously only be well-defined for states having this kind of port-name-/semantic-key and otherwise will contain a None-like value, indicating missing data. The available data per execution item (row in the table) can be printed using pandas.DataFrame.columns.
2.514972
2.404979
1.045736
import matplotlib.pyplot as plt import matplotlib.dates as dates import numpy as np d = log_to_DataFrame(execution_history_items) # de-duplicate states and make mapping from state to idx unique_states, idx = np.unique(d.path_by_name, return_index=True) ordered_unique_states = np.array(d.path_by_name)[np.sort(idx)] name2idx = {k: i for i, k in enumerate(ordered_unique_states)} calldate = dates.date2num(d.timestamp_call.dt.to_pydatetime()) returndate = dates.date2num(d.timestamp_return.dt.to_pydatetime()) state2color = {'HierarchyState': 'k', 'ExecutionState': 'g', 'BarrierConcurrencyState': 'y', 'PreemptiveConcurrencyState': 'y'} fig, ax = plt.subplots(1, 1) ax.barh(bottom=[name2idx[k] for k in d.path_by_name], width=returndate-calldate, left=calldate, align='center', color=[state2color[s] for s in d.state_type], lw=0.0) plt.yticks(list(range(len(ordered_unique_states))), ordered_unique_states)
def log_to_ganttplot(execution_history_items)
Example how to use the DataFrame representation
3.64608
3.576683
1.019402
from future.utils import raise_ from threading import Condition import sys from rafcon.utils import log global exception_info, result from gi.repository import GLib condition = Condition() exception_info = None @log.log_exceptions() def fun(): global exception_info, result result = None try: result = callback(*args) except: # Exception within this asynchronously called function won't reach pytest. This is why we have to store # the information about the exception to re-raise it at the end of the synchronous call. exception_info = sys.exc_info() finally: # Finally is also executed in the case of exceptions condition.acquire() condition.notify() condition.release() if "priority" in kwargs: priority = kwargs["priority"] else: priority = GLib.PRIORITY_LOW condition.acquire() GLib.idle_add(fun, priority=priority) # Wait for the condition to be notified # TODO: implement timeout that raises an exception condition.wait() condition.release() if exception_info: e_type, e_value, e_traceback = exception_info raise_(e_type, e_value, e_traceback) return result
def call_gui_callback(callback, *args, **kwargs)
Wrapper method for GLib.idle_add This method is intended as replacement for idle_add. It wraps the method with a callback option. The advantage is that this way, the call is blocking. The method return, when the callback method has been called and executed. :param callback: The callback method, e.g. on_open_activate :param args: The parameters to be passed to the callback method
4.527769
4.550701
0.994961
tooltip_event_box = Gtk.EventBox() tooltip_event_box.set_tooltip_text(tab_name) tab_label = Gtk.Label() if global_gui_config.get_config_value('USE_ICONS_AS_TAB_LABELS', True): tab_label.set_markup('<span font_desc="%s %s">&#x%s;</span>' % (constants.ICON_FONT, constants.FONT_SIZE_BIG, icons[tab_name])) else: tab_label.set_text(get_widget_title(tab_name)) tab_label.set_angle(90) tab_label.show() tooltip_event_box.add(tab_label) tooltip_event_box.set_visible_window(False) tooltip_event_box.show() return tooltip_event_box
def create_tab_header_label(tab_name, icons)
Create the tab header labels for notebook tabs. If USE_ICONS_AS_TAB_LABELS is set to True in the gui_config, icons are used as headers. Otherwise, the titles of the tabs are rotated by 90 degrees. :param tab_name: The label text of the tab, written in small letters and separated by underscores, e.g. states_tree :param icons: A dict mapping each tab_name to its corresponding icon :return: The GTK Eventbox holding the tab label
2.906571
2.63732
1.102093