repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/constraint.py
PortRectConstraint.update_port_side
def update_port_side(self): """Updates the initial position of the port The port side is ignored but calculated from the port position. Then the port position is limited to the four side lines of the state. """ from rafcon.utils.geometry import point_left_of_line p = (self._initial_pos.x, self._initial_pos.y) nw_x, nw_y, se_x, se_y = self.get_adjusted_border_positions() if point_left_of_line(p, (nw_x, nw_y), (se_x, se_y)): # upper right triangle of state if point_left_of_line(p, (nw_x, se_y), (se_x, nw_y)): # upper quarter triangle of state self._port.side = SnappedSide.TOP self.limit_pos(p[0], se_x, nw_x) else: # right quarter triangle of state self._port.side = SnappedSide.RIGHT self.limit_pos(p[1], se_y, nw_y) else: # lower left triangle of state if point_left_of_line(p, (nw_x, se_y), (se_x, nw_y)): # left quarter triangle of state self._port.side = SnappedSide.LEFT self.limit_pos(p[1], se_y, nw_y) else: # lower quarter triangle of state self._port.side = SnappedSide.BOTTOM self.limit_pos(p[0], se_x, nw_x) self.set_nearest_border()
python
def update_port_side(self): """Updates the initial position of the port The port side is ignored but calculated from the port position. Then the port position is limited to the four side lines of the state. """ from rafcon.utils.geometry import point_left_of_line p = (self._initial_pos.x, self._initial_pos.y) nw_x, nw_y, se_x, se_y = self.get_adjusted_border_positions() if point_left_of_line(p, (nw_x, nw_y), (se_x, se_y)): # upper right triangle of state if point_left_of_line(p, (nw_x, se_y), (se_x, nw_y)): # upper quarter triangle of state self._port.side = SnappedSide.TOP self.limit_pos(p[0], se_x, nw_x) else: # right quarter triangle of state self._port.side = SnappedSide.RIGHT self.limit_pos(p[1], se_y, nw_y) else: # lower left triangle of state if point_left_of_line(p, (nw_x, se_y), (se_x, nw_y)): # left quarter triangle of state self._port.side = SnappedSide.LEFT self.limit_pos(p[1], se_y, nw_y) else: # lower quarter triangle of state self._port.side = SnappedSide.BOTTOM self.limit_pos(p[0], se_x, nw_x) self.set_nearest_border()
[ "def", "update_port_side", "(", "self", ")", ":", "from", "rafcon", ".", "utils", ".", "geometry", "import", "point_left_of_line", "p", "=", "(", "self", ".", "_initial_pos", ".", "x", ",", "self", ".", "_initial_pos", ".", "y", ")", "nw_x", ",", "nw_y",...
Updates the initial position of the port The port side is ignored but calculated from the port position. Then the port position is limited to the four side lines of the state.
[ "Updates", "the", "initial", "position", "of", "the", "port" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/constraint.py#L223-L248
train
40,400
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/constraint.py
PortRectConstraint._solve
def _solve(self): """ Calculates the correct position of the port and keeps it aligned with the binding rect """ # As the size of the containing state may has changed we need to update the distance to the border self.update_distance_to_border() px, py = self._point nw_x, nw_y, se_x, se_y = self.get_adjusted_border_positions() # If the port is located in one of the corners it is possible to move in two directions if ((self._initial_pos.x == nw_x and self._initial_pos.y == nw_y) or (self._initial_pos.x == se_x and self._initial_pos.y == nw_y) or (self._initial_pos.x == se_x and self._initial_pos.y == se_y) or (self._initial_pos.x == nw_x and self._initial_pos.y == se_y)): self.limit_pos(px, se_x, nw_x) self.limit_pos(py, se_y, nw_y) # If port movement starts at LEFT position, keep X position at place and move Y elif self._initial_pos.x == nw_x: _update(px, nw_x) self.limit_pos(py, se_y, nw_y) self._port.side = SnappedSide.LEFT # If port movement starts at TOP position, keep Y position at place and move X elif self._initial_pos.y == nw_y: _update(py, nw_y) self.limit_pos(px, se_x, nw_x) self._port.side = SnappedSide.TOP # If port movement starts at RIGHT position, keep X position at place and move Y elif self._initial_pos.x == se_x: _update(px, se_x) self.limit_pos(py, se_y, nw_y) self._port.side = SnappedSide.RIGHT # If port movement starts at BOTTOM position, keep Y position at place and move X elif self._initial_pos.y == se_y: _update(py, se_y) self.limit_pos(px, se_x, nw_x) self._port.side = SnappedSide.BOTTOM # If containing state has been resized, snap ports accordingly to border else: self.set_nearest_border() # Update initial position for next reference _update(self._initial_pos.x, deepcopy(px.value)) _update(self._initial_pos.y, deepcopy(py.value))
python
def _solve(self): """ Calculates the correct position of the port and keeps it aligned with the binding rect """ # As the size of the containing state may has changed we need to update the distance to the border self.update_distance_to_border() px, py = self._point nw_x, nw_y, se_x, se_y = self.get_adjusted_border_positions() # If the port is located in one of the corners it is possible to move in two directions if ((self._initial_pos.x == nw_x and self._initial_pos.y == nw_y) or (self._initial_pos.x == se_x and self._initial_pos.y == nw_y) or (self._initial_pos.x == se_x and self._initial_pos.y == se_y) or (self._initial_pos.x == nw_x and self._initial_pos.y == se_y)): self.limit_pos(px, se_x, nw_x) self.limit_pos(py, se_y, nw_y) # If port movement starts at LEFT position, keep X position at place and move Y elif self._initial_pos.x == nw_x: _update(px, nw_x) self.limit_pos(py, se_y, nw_y) self._port.side = SnappedSide.LEFT # If port movement starts at TOP position, keep Y position at place and move X elif self._initial_pos.y == nw_y: _update(py, nw_y) self.limit_pos(px, se_x, nw_x) self._port.side = SnappedSide.TOP # If port movement starts at RIGHT position, keep X position at place and move Y elif self._initial_pos.x == se_x: _update(px, se_x) self.limit_pos(py, se_y, nw_y) self._port.side = SnappedSide.RIGHT # If port movement starts at BOTTOM position, keep Y position at place and move X elif self._initial_pos.y == se_y: _update(py, se_y) self.limit_pos(px, se_x, nw_x) self._port.side = SnappedSide.BOTTOM # If containing state has been resized, snap ports accordingly to border else: self.set_nearest_border() # Update initial position for next reference _update(self._initial_pos.x, deepcopy(px.value)) _update(self._initial_pos.y, deepcopy(py.value))
[ "def", "_solve", "(", "self", ")", ":", "# As the size of the containing state may has changed we need to update the distance to the border", "self", ".", "update_distance_to_border", "(", ")", "px", ",", "py", "=", "self", ".", "_point", "nw_x", ",", "nw_y", ",", "se_x...
Calculates the correct position of the port and keeps it aligned with the binding rect
[ "Calculates", "the", "correct", "position", "of", "the", "port", "and", "keeps", "it", "aligned", "with", "the", "binding", "rect" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/constraint.py#L253-L296
train
40,401
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/constraint.py
PortRectConstraint.set_nearest_border
def set_nearest_border(self): """Snaps the port to the correct side upon state size change """ px, py = self._point nw_x, nw_y, se_x, se_y = self.get_adjusted_border_positions() if self._port.side == SnappedSide.RIGHT: _update(px, se_x) elif self._port.side == SnappedSide.BOTTOM: _update(py, se_y) elif self._port.side == SnappedSide.LEFT: _update(px, nw_x) elif self._port.side == SnappedSide.TOP: _update(py, nw_y)
python
def set_nearest_border(self): """Snaps the port to the correct side upon state size change """ px, py = self._point nw_x, nw_y, se_x, se_y = self.get_adjusted_border_positions() if self._port.side == SnappedSide.RIGHT: _update(px, se_x) elif self._port.side == SnappedSide.BOTTOM: _update(py, se_y) elif self._port.side == SnappedSide.LEFT: _update(px, nw_x) elif self._port.side == SnappedSide.TOP: _update(py, nw_y)
[ "def", "set_nearest_border", "(", "self", ")", ":", "px", ",", "py", "=", "self", ".", "_point", "nw_x", ",", "nw_y", ",", "se_x", ",", "se_y", "=", "self", ".", "get_adjusted_border_positions", "(", ")", "if", "self", ".", "_port", ".", "side", "==", ...
Snaps the port to the correct side upon state size change
[ "Snaps", "the", "port", "to", "the", "correct", "side", "upon", "state", "size", "change" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/constraint.py#L330-L343
train
40,402
DLR-RM/RAFCON
source/rafcon/core/storage/storage.py
remove_obsolete_folders
def remove_obsolete_folders(states, path): """Removes obsolete state machine folders This function removes all folders in the file system folder `path` that do not belong to the states given by `states`. :param list states: the states that should reside in this very folder :param str path: the file system path to be checked for valid folders """ elements_in_folder = os.listdir(path) # find all state folder elements in system path state_folders_in_file_system = [] for folder_name in elements_in_folder: if os.path.exists(os.path.join(path, folder_name, FILE_NAME_CORE_DATA)) or \ os.path.exists(os.path.join(path, folder_name, FILE_NAME_CORE_DATA_OLD)): state_folders_in_file_system.append(folder_name) # remove elements used by existing states and storage format for state in states: storage_folder_for_state = get_storage_id_for_state(state) if storage_folder_for_state in state_folders_in_file_system: state_folders_in_file_system.remove(storage_folder_for_state) # remove the remaining state folders for folder_name in state_folders_in_file_system: shutil.rmtree(os.path.join(path, folder_name))
python
def remove_obsolete_folders(states, path): """Removes obsolete state machine folders This function removes all folders in the file system folder `path` that do not belong to the states given by `states`. :param list states: the states that should reside in this very folder :param str path: the file system path to be checked for valid folders """ elements_in_folder = os.listdir(path) # find all state folder elements in system path state_folders_in_file_system = [] for folder_name in elements_in_folder: if os.path.exists(os.path.join(path, folder_name, FILE_NAME_CORE_DATA)) or \ os.path.exists(os.path.join(path, folder_name, FILE_NAME_CORE_DATA_OLD)): state_folders_in_file_system.append(folder_name) # remove elements used by existing states and storage format for state in states: storage_folder_for_state = get_storage_id_for_state(state) if storage_folder_for_state in state_folders_in_file_system: state_folders_in_file_system.remove(storage_folder_for_state) # remove the remaining state folders for folder_name in state_folders_in_file_system: shutil.rmtree(os.path.join(path, folder_name))
[ "def", "remove_obsolete_folders", "(", "states", ",", "path", ")", ":", "elements_in_folder", "=", "os", ".", "listdir", "(", "path", ")", "# find all state folder elements in system path", "state_folders_in_file_system", "=", "[", "]", "for", "folder_name", "in", "el...
Removes obsolete state machine folders This function removes all folders in the file system folder `path` that do not belong to the states given by `states`. :param list states: the states that should reside in this very folder :param str path: the file system path to be checked for valid folders
[ "Removes", "obsolete", "state", "machine", "folders" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/storage/storage.py#L67-L92
train
40,403
DLR-RM/RAFCON
source/rafcon/core/storage/storage.py
save_state_machine_to_path
def save_state_machine_to_path(state_machine, base_path, delete_old_state_machine=False, as_copy=False): """Saves a state machine recursively to the file system The `as_copy` flag determines whether the state machine is saved as copy. If so (`as_copy=True`), some state machine attributes will be left untouched, such as the `file_system_path` or the `dirty_flag`. :param rafcon.core.state_machine.StateMachine state_machine: the state_machine to be saved :param str base_path: base_path to which all further relative paths refers to :param bool delete_old_state_machine: Whether to delete any state machine existing at the given path :param bool as_copy: Whether to use a copy storage for the state machine """ # warns the user in the logger when using deprecated names clean_path_from_deprecated_naming(base_path) state_machine.acquire_modification_lock() try: root_state = state_machine.root_state # clean old path first if delete_old_state_machine: if os.path.exists(base_path): shutil.rmtree(base_path) # Ensure that path is existing if not os.path.exists(base_path): os.makedirs(base_path) old_update_time = state_machine.last_update state_machine.last_update = storage_utils.get_current_time_string() state_machine_dict = state_machine.to_dict() storage_utils.write_dict_to_json(state_machine_dict, os.path.join(base_path, STATEMACHINE_FILE)) # set the file_system_path of the state machine if not as_copy: state_machine.file_system_path = copy.copy(base_path) else: state_machine.last_update = old_update_time # add root state recursively remove_obsolete_folders([root_state], base_path) save_state_recursively(root_state, base_path, "", as_copy) if state_machine.marked_dirty and not as_copy: state_machine.marked_dirty = False logger.debug("State machine with id {0} was saved at {1}".format(state_machine.state_machine_id, base_path)) except Exception: raise finally: state_machine.release_modification_lock()
python
def save_state_machine_to_path(state_machine, base_path, delete_old_state_machine=False, as_copy=False): """Saves a state machine recursively to the file system The `as_copy` flag determines whether the state machine is saved as copy. If so (`as_copy=True`), some state machine attributes will be left untouched, such as the `file_system_path` or the `dirty_flag`. :param rafcon.core.state_machine.StateMachine state_machine: the state_machine to be saved :param str base_path: base_path to which all further relative paths refers to :param bool delete_old_state_machine: Whether to delete any state machine existing at the given path :param bool as_copy: Whether to use a copy storage for the state machine """ # warns the user in the logger when using deprecated names clean_path_from_deprecated_naming(base_path) state_machine.acquire_modification_lock() try: root_state = state_machine.root_state # clean old path first if delete_old_state_machine: if os.path.exists(base_path): shutil.rmtree(base_path) # Ensure that path is existing if not os.path.exists(base_path): os.makedirs(base_path) old_update_time = state_machine.last_update state_machine.last_update = storage_utils.get_current_time_string() state_machine_dict = state_machine.to_dict() storage_utils.write_dict_to_json(state_machine_dict, os.path.join(base_path, STATEMACHINE_FILE)) # set the file_system_path of the state machine if not as_copy: state_machine.file_system_path = copy.copy(base_path) else: state_machine.last_update = old_update_time # add root state recursively remove_obsolete_folders([root_state], base_path) save_state_recursively(root_state, base_path, "", as_copy) if state_machine.marked_dirty and not as_copy: state_machine.marked_dirty = False logger.debug("State machine with id {0} was saved at {1}".format(state_machine.state_machine_id, base_path)) except Exception: raise finally: state_machine.release_modification_lock()
[ "def", "save_state_machine_to_path", "(", "state_machine", ",", "base_path", ",", "delete_old_state_machine", "=", "False", ",", "as_copy", "=", "False", ")", ":", "# warns the user in the logger when using deprecated names", "clean_path_from_deprecated_naming", "(", "base_path...
Saves a state machine recursively to the file system The `as_copy` flag determines whether the state machine is saved as copy. If so (`as_copy=True`), some state machine attributes will be left untouched, such as the `file_system_path` or the `dirty_flag`. :param rafcon.core.state_machine.StateMachine state_machine: the state_machine to be saved :param str base_path: base_path to which all further relative paths refers to :param bool delete_old_state_machine: Whether to delete any state machine existing at the given path :param bool as_copy: Whether to use a copy storage for the state machine
[ "Saves", "a", "state", "machine", "recursively", "to", "the", "file", "system" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/storage/storage.py#L147-L195
train
40,404
DLR-RM/RAFCON
source/rafcon/core/storage/storage.py
save_script_file_for_state_and_source_path
def save_script_file_for_state_and_source_path(state, state_path_full, as_copy=False): """Saves the script file for a state to the directory of the state. The script name will be set to the SCRIPT_FILE constant. :param state: The state of which the script file should be saved :param str state_path_full: The path to the file system storage location of the state :param bool as_copy: Temporary storage flag to signal that the given path is not the new file_system_path """ from rafcon.core.states.execution_state import ExecutionState if isinstance(state, ExecutionState): source_script_file = os.path.join(state.script.path, state.script.filename) destination_script_file = os.path.join(state_path_full, SCRIPT_FILE) try: write_file(destination_script_file, state.script_text) except Exception: logger.exception("Storing of script file failed: {0} -> {1}".format(state.get_path(), destination_script_file)) raise if not source_script_file == destination_script_file and not as_copy: state.script.filename = SCRIPT_FILE state.script.path = state_path_full
python
def save_script_file_for_state_and_source_path(state, state_path_full, as_copy=False): """Saves the script file for a state to the directory of the state. The script name will be set to the SCRIPT_FILE constant. :param state: The state of which the script file should be saved :param str state_path_full: The path to the file system storage location of the state :param bool as_copy: Temporary storage flag to signal that the given path is not the new file_system_path """ from rafcon.core.states.execution_state import ExecutionState if isinstance(state, ExecutionState): source_script_file = os.path.join(state.script.path, state.script.filename) destination_script_file = os.path.join(state_path_full, SCRIPT_FILE) try: write_file(destination_script_file, state.script_text) except Exception: logger.exception("Storing of script file failed: {0} -> {1}".format(state.get_path(), destination_script_file)) raise if not source_script_file == destination_script_file and not as_copy: state.script.filename = SCRIPT_FILE state.script.path = state_path_full
[ "def", "save_script_file_for_state_and_source_path", "(", "state", ",", "state_path_full", ",", "as_copy", "=", "False", ")", ":", "from", "rafcon", ".", "core", ".", "states", ".", "execution_state", "import", "ExecutionState", "if", "isinstance", "(", "state", "...
Saves the script file for a state to the directory of the state. The script name will be set to the SCRIPT_FILE constant. :param state: The state of which the script file should be saved :param str state_path_full: The path to the file system storage location of the state :param bool as_copy: Temporary storage flag to signal that the given path is not the new file_system_path
[ "Saves", "the", "script", "file", "for", "a", "state", "to", "the", "directory", "of", "the", "state", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/storage/storage.py#L198-L221
train
40,405
DLR-RM/RAFCON
source/rafcon/core/storage/storage.py
save_semantic_data_for_state
def save_semantic_data_for_state(state, state_path_full): """Saves the semantic data in a separate json file. :param state: The state of which the script file should be saved :param str state_path_full: The path to the file system storage location of the state """ destination_script_file = os.path.join(state_path_full, SEMANTIC_DATA_FILE) try: storage_utils.write_dict_to_json(state.semantic_data, destination_script_file) except IOError: logger.exception("Storing of semantic data for state {0} failed! Destination path: {1}". format(state.get_path(), destination_script_file)) raise
python
def save_semantic_data_for_state(state, state_path_full): """Saves the semantic data in a separate json file. :param state: The state of which the script file should be saved :param str state_path_full: The path to the file system storage location of the state """ destination_script_file = os.path.join(state_path_full, SEMANTIC_DATA_FILE) try: storage_utils.write_dict_to_json(state.semantic_data, destination_script_file) except IOError: logger.exception("Storing of semantic data for state {0} failed! Destination path: {1}". format(state.get_path(), destination_script_file)) raise
[ "def", "save_semantic_data_for_state", "(", "state", ",", "state_path_full", ")", ":", "destination_script_file", "=", "os", ".", "path", ".", "join", "(", "state_path_full", ",", "SEMANTIC_DATA_FILE", ")", "try", ":", "storage_utils", ".", "write_dict_to_json", "("...
Saves the semantic data in a separate json file. :param state: The state of which the script file should be saved :param str state_path_full: The path to the file system storage location of the state
[ "Saves", "the", "semantic", "data", "in", "a", "separate", "json", "file", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/storage/storage.py#L224-L238
train
40,406
DLR-RM/RAFCON
source/rafcon/core/storage/storage.py
save_state_recursively
def save_state_recursively(state, base_path, parent_path, as_copy=False): """Recursively saves a state to a json file It calls this method on all its substates. :param state: State to be stored :param base_path: Path to the state machine :param parent_path: Path to the parent state :param bool as_copy: Temporary storage flag to signal that the given path is not the new file_system_path :return: """ from rafcon.core.states.execution_state import ExecutionState from rafcon.core.states.container_state import ContainerState state_path = os.path.join(parent_path, get_storage_id_for_state(state)) state_path_full = os.path.join(base_path, state_path) if not os.path.exists(state_path_full): os.makedirs(state_path_full) storage_utils.write_dict_to_json(state, os.path.join(state_path_full, FILE_NAME_CORE_DATA)) if not as_copy: state.file_system_path = state_path_full if isinstance(state, ExecutionState): save_script_file_for_state_and_source_path(state, state_path_full, as_copy) save_semantic_data_for_state(state, state_path_full) # create yaml files for all children if isinstance(state, ContainerState): remove_obsolete_folders(state.states.values(), os.path.join(base_path, state_path)) for state in state.states.values(): save_state_recursively(state, base_path, state_path, as_copy)
python
def save_state_recursively(state, base_path, parent_path, as_copy=False): """Recursively saves a state to a json file It calls this method on all its substates. :param state: State to be stored :param base_path: Path to the state machine :param parent_path: Path to the parent state :param bool as_copy: Temporary storage flag to signal that the given path is not the new file_system_path :return: """ from rafcon.core.states.execution_state import ExecutionState from rafcon.core.states.container_state import ContainerState state_path = os.path.join(parent_path, get_storage_id_for_state(state)) state_path_full = os.path.join(base_path, state_path) if not os.path.exists(state_path_full): os.makedirs(state_path_full) storage_utils.write_dict_to_json(state, os.path.join(state_path_full, FILE_NAME_CORE_DATA)) if not as_copy: state.file_system_path = state_path_full if isinstance(state, ExecutionState): save_script_file_for_state_and_source_path(state, state_path_full, as_copy) save_semantic_data_for_state(state, state_path_full) # create yaml files for all children if isinstance(state, ContainerState): remove_obsolete_folders(state.states.values(), os.path.join(base_path, state_path)) for state in state.states.values(): save_state_recursively(state, base_path, state_path, as_copy)
[ "def", "save_state_recursively", "(", "state", ",", "base_path", ",", "parent_path", ",", "as_copy", "=", "False", ")", ":", "from", "rafcon", ".", "core", ".", "states", ".", "execution_state", "import", "ExecutionState", "from", "rafcon", ".", "core", ".", ...
Recursively saves a state to a json file It calls this method on all its substates. :param state: State to be stored :param base_path: Path to the state machine :param parent_path: Path to the parent state :param bool as_copy: Temporary storage flag to signal that the given path is not the new file_system_path :return:
[ "Recursively", "saves", "a", "state", "to", "a", "json", "file" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/storage/storage.py#L241-L273
train
40,407
DLR-RM/RAFCON
source/rafcon/core/storage/storage.py
load_state_recursively
def load_state_recursively(parent, state_path=None, dirty_states=[]): """Recursively loads the state It calls this method on each sub-state of a container state. :param parent: the root state of the last load call to which the loaded state will be added :param state_path: the path on the filesystem where to find the meta file for the state :param dirty_states: a dict of states which changed during loading :return: """ from rafcon.core.states.execution_state import ExecutionState from rafcon.core.states.container_state import ContainerState from rafcon.core.states.hierarchy_state import HierarchyState path_core_data = os.path.join(state_path, FILE_NAME_CORE_DATA) logger.debug("Load state recursively: {0}".format(str(state_path))) # TODO: Should be removed with next minor release if not os.path.exists(path_core_data): path_core_data = os.path.join(state_path, FILE_NAME_CORE_DATA_OLD) try: state_info = load_data_file(path_core_data) except ValueError as e: logger.exception("Error while loading state data: {0}".format(e)) return except LibraryNotFoundException as e: logger.error("Library could not be loaded: {0}\n" "Skipping library and continuing loading the state machine".format(e)) state_info = storage_utils.load_objects_from_json(path_core_data, as_dict=True) state_id = state_info["state_id"] dummy_state = HierarchyState(LIBRARY_NOT_FOUND_DUMMY_STATE_NAME, state_id=state_id) # set parent of dummy state if isinstance(parent, ContainerState): parent.add_state(dummy_state, storage_load=True) else: dummy_state.parent = parent return dummy_state # Transitions and data flows are not added when loading a state, as also states are not added. # We have to wait until the child states are loaded, before adding transitions and data flows, as otherwise the # validity checks for transitions and data flows would fail if not isinstance(state_info, tuple): state = state_info else: state = state_info[0] transitions = state_info[1] data_flows = state_info[2] # set parent of state if parent is not None and isinstance(parent, ContainerState): parent.add_state(state, storage_load=True) else: state.parent = parent # read script file if an execution state if isinstance(state, ExecutionState): script_text = read_file(state_path, state.script.filename) state.script_text = script_text # load semantic data try: semantic_data = load_data_file(os.path.join(state_path, SEMANTIC_DATA_FILE)) state.semantic_data = semantic_data except Exception as e: # semantic data file does not have to be there pass one_of_my_child_states_not_found = False # load child states for p in os.listdir(state_path): child_state_path = os.path.join(state_path, p) if os.path.isdir(child_state_path): child_state = load_state_recursively(state, child_state_path, dirty_states) if child_state.name is LIBRARY_NOT_FOUND_DUMMY_STATE_NAME: one_of_my_child_states_not_found = True if one_of_my_child_states_not_found: # omit adding transitions and data flows in this case pass else: # Now we can add transitions and data flows, as all child states were added if isinstance(state_info, tuple): state.transitions = transitions state.data_flows = data_flows state.file_system_path = state_path if state.marked_dirty: dirty_states.append(state) return state
python
def load_state_recursively(parent, state_path=None, dirty_states=[]): """Recursively loads the state It calls this method on each sub-state of a container state. :param parent: the root state of the last load call to which the loaded state will be added :param state_path: the path on the filesystem where to find the meta file for the state :param dirty_states: a dict of states which changed during loading :return: """ from rafcon.core.states.execution_state import ExecutionState from rafcon.core.states.container_state import ContainerState from rafcon.core.states.hierarchy_state import HierarchyState path_core_data = os.path.join(state_path, FILE_NAME_CORE_DATA) logger.debug("Load state recursively: {0}".format(str(state_path))) # TODO: Should be removed with next minor release if not os.path.exists(path_core_data): path_core_data = os.path.join(state_path, FILE_NAME_CORE_DATA_OLD) try: state_info = load_data_file(path_core_data) except ValueError as e: logger.exception("Error while loading state data: {0}".format(e)) return except LibraryNotFoundException as e: logger.error("Library could not be loaded: {0}\n" "Skipping library and continuing loading the state machine".format(e)) state_info = storage_utils.load_objects_from_json(path_core_data, as_dict=True) state_id = state_info["state_id"] dummy_state = HierarchyState(LIBRARY_NOT_FOUND_DUMMY_STATE_NAME, state_id=state_id) # set parent of dummy state if isinstance(parent, ContainerState): parent.add_state(dummy_state, storage_load=True) else: dummy_state.parent = parent return dummy_state # Transitions and data flows are not added when loading a state, as also states are not added. # We have to wait until the child states are loaded, before adding transitions and data flows, as otherwise the # validity checks for transitions and data flows would fail if not isinstance(state_info, tuple): state = state_info else: state = state_info[0] transitions = state_info[1] data_flows = state_info[2] # set parent of state if parent is not None and isinstance(parent, ContainerState): parent.add_state(state, storage_load=True) else: state.parent = parent # read script file if an execution state if isinstance(state, ExecutionState): script_text = read_file(state_path, state.script.filename) state.script_text = script_text # load semantic data try: semantic_data = load_data_file(os.path.join(state_path, SEMANTIC_DATA_FILE)) state.semantic_data = semantic_data except Exception as e: # semantic data file does not have to be there pass one_of_my_child_states_not_found = False # load child states for p in os.listdir(state_path): child_state_path = os.path.join(state_path, p) if os.path.isdir(child_state_path): child_state = load_state_recursively(state, child_state_path, dirty_states) if child_state.name is LIBRARY_NOT_FOUND_DUMMY_STATE_NAME: one_of_my_child_states_not_found = True if one_of_my_child_states_not_found: # omit adding transitions and data flows in this case pass else: # Now we can add transitions and data flows, as all child states were added if isinstance(state_info, tuple): state.transitions = transitions state.data_flows = data_flows state.file_system_path = state_path if state.marked_dirty: dirty_states.append(state) return state
[ "def", "load_state_recursively", "(", "parent", ",", "state_path", "=", "None", ",", "dirty_states", "=", "[", "]", ")", ":", "from", "rafcon", ".", "core", ".", "states", ".", "execution_state", "import", "ExecutionState", "from", "rafcon", ".", "core", "."...
Recursively loads the state It calls this method on each sub-state of a container state. :param parent: the root state of the last load call to which the loaded state will be added :param state_path: the path on the filesystem where to find the meta file for the state :param dirty_states: a dict of states which changed during loading :return:
[ "Recursively", "loads", "the", "state" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/storage/storage.py#L374-L467
train
40,408
DLR-RM/RAFCON
source/rafcon/core/storage/storage.py
load_data_file
def load_data_file(path_of_file): """ Loads the content of a file by using json.load. :param path_of_file: the path of the file to load :return: the file content as a string :raises exceptions.ValueError: if the file was not found """ if os.path.exists(path_of_file): return storage_utils.load_objects_from_json(path_of_file) raise ValueError("Data file not found: {0}".format(path_of_file))
python
def load_data_file(path_of_file): """ Loads the content of a file by using json.load. :param path_of_file: the path of the file to load :return: the file content as a string :raises exceptions.ValueError: if the file was not found """ if os.path.exists(path_of_file): return storage_utils.load_objects_from_json(path_of_file) raise ValueError("Data file not found: {0}".format(path_of_file))
[ "def", "load_data_file", "(", "path_of_file", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path_of_file", ")", ":", "return", "storage_utils", ".", "load_objects_from_json", "(", "path_of_file", ")", "raise", "ValueError", "(", "\"Data file not found: {...
Loads the content of a file by using json.load. :param path_of_file: the path of the file to load :return: the file content as a string :raises exceptions.ValueError: if the file was not found
[ "Loads", "the", "content", "of", "a", "file", "by", "using", "json", ".", "load", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/storage/storage.py#L470-L479
train
40,409
DLR-RM/RAFCON
source/rafcon/core/storage/storage.py
clean_path_element
def clean_path_element(text, max_length=None, separator='_'): """ Replace characters that conflict with a free OS choice when in a file system path. :param text: the string to be cleaned :param max_length: the maximum length of the output string :param separator: the separator used for rafcon.core.storage.storage.limit_text_max_length :return: """ elements_to_replace = REPLACED_CHARACTERS_FOR_NO_OS_LIMITATION for elem, replace_with in elements_to_replace.items(): text = text.replace(elem, replace_with) if max_length is not None: text = limit_text_max_length(text, max_length, separator) return text
python
def clean_path_element(text, max_length=None, separator='_'): """ Replace characters that conflict with a free OS choice when in a file system path. :param text: the string to be cleaned :param max_length: the maximum length of the output string :param separator: the separator used for rafcon.core.storage.storage.limit_text_max_length :return: """ elements_to_replace = REPLACED_CHARACTERS_FOR_NO_OS_LIMITATION for elem, replace_with in elements_to_replace.items(): text = text.replace(elem, replace_with) if max_length is not None: text = limit_text_max_length(text, max_length, separator) return text
[ "def", "clean_path_element", "(", "text", ",", "max_length", "=", "None", ",", "separator", "=", "'_'", ")", ":", "elements_to_replace", "=", "REPLACED_CHARACTERS_FOR_NO_OS_LIMITATION", "for", "elem", ",", "replace_with", "in", "elements_to_replace", ".", "items", "...
Replace characters that conflict with a free OS choice when in a file system path. :param text: the string to be cleaned :param max_length: the maximum length of the output string :param separator: the separator used for rafcon.core.storage.storage.limit_text_max_length :return:
[ "Replace", "characters", "that", "conflict", "with", "a", "free", "OS", "choice", "when", "in", "a", "file", "system", "path", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/storage/storage.py#L501-L514
train
40,410
DLR-RM/RAFCON
source/rafcon/core/storage/storage.py
limit_text_to_be_path_element
def limit_text_to_be_path_element(text, max_length=None, separator='_'): """ Replace characters that are not in the valid character set of RAFCON. :param text: the string to be cleaned :param max_length: the maximum length of the output string :param separator: the separator used for rafcon.core.storage.storage.limit_text_max_length :return: """ # TODO: Should there not only be one method i.e. either this one or "clean_path_element" elements_to_replace = {' ': '_', '*': '_'} for elem, replace_with in elements_to_replace.items(): text = text.replace(elem, replace_with) text = re.sub('[^a-zA-Z0-9-_]', '', text) if max_length is not None: text = limit_text_max_length(text, max_length, separator) return text
python
def limit_text_to_be_path_element(text, max_length=None, separator='_'): """ Replace characters that are not in the valid character set of RAFCON. :param text: the string to be cleaned :param max_length: the maximum length of the output string :param separator: the separator used for rafcon.core.storage.storage.limit_text_max_length :return: """ # TODO: Should there not only be one method i.e. either this one or "clean_path_element" elements_to_replace = {' ': '_', '*': '_'} for elem, replace_with in elements_to_replace.items(): text = text.replace(elem, replace_with) text = re.sub('[^a-zA-Z0-9-_]', '', text) if max_length is not None: text = limit_text_max_length(text, max_length, separator) return text
[ "def", "limit_text_to_be_path_element", "(", "text", ",", "max_length", "=", "None", ",", "separator", "=", "'_'", ")", ":", "# TODO: Should there not only be one method i.e. either this one or \"clean_path_element\"", "elements_to_replace", "=", "{", "' '", ":", "'_'", ","...
Replace characters that are not in the valid character set of RAFCON. :param text: the string to be cleaned :param max_length: the maximum length of the output string :param separator: the separator used for rafcon.core.storage.storage.limit_text_max_length :return:
[ "Replace", "characters", "that", "are", "not", "in", "the", "valid", "character", "set", "of", "RAFCON", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/storage/storage.py#L517-L532
train
40,411
DLR-RM/RAFCON
source/rafcon/core/storage/storage.py
get_storage_id_for_state
def get_storage_id_for_state(state): """ Calculates the storage id of a state. This ID can be used for generating the file path for a state. :param rafcon.core.states.state.State state: state the storage_id should is composed for """ if global_config.get_config_value('STORAGE_PATH_WITH_STATE_NAME'): max_length = global_config.get_config_value('MAX_LENGTH_FOR_STATE_NAME_IN_STORAGE_PATH') max_length_of_state_name_in_folder_name = 255 - len(ID_NAME_DELIMITER + state.state_id) # TODO: should we allow "None" in config file? if max_length is None or max_length == "None" or max_length > max_length_of_state_name_in_folder_name: if max_length_of_state_name_in_folder_name < len(state.name): logger.info("The storage folder name is forced to be maximal 255 characters in length.") max_length = max_length_of_state_name_in_folder_name return limit_text_to_be_path_element(state.name, max_length) + ID_NAME_DELIMITER + state.state_id else: return state.state_id
python
def get_storage_id_for_state(state): """ Calculates the storage id of a state. This ID can be used for generating the file path for a state. :param rafcon.core.states.state.State state: state the storage_id should is composed for """ if global_config.get_config_value('STORAGE_PATH_WITH_STATE_NAME'): max_length = global_config.get_config_value('MAX_LENGTH_FOR_STATE_NAME_IN_STORAGE_PATH') max_length_of_state_name_in_folder_name = 255 - len(ID_NAME_DELIMITER + state.state_id) # TODO: should we allow "None" in config file? if max_length is None or max_length == "None" or max_length > max_length_of_state_name_in_folder_name: if max_length_of_state_name_in_folder_name < len(state.name): logger.info("The storage folder name is forced to be maximal 255 characters in length.") max_length = max_length_of_state_name_in_folder_name return limit_text_to_be_path_element(state.name, max_length) + ID_NAME_DELIMITER + state.state_id else: return state.state_id
[ "def", "get_storage_id_for_state", "(", "state", ")", ":", "if", "global_config", ".", "get_config_value", "(", "'STORAGE_PATH_WITH_STATE_NAME'", ")", ":", "max_length", "=", "global_config", ".", "get_config_value", "(", "'MAX_LENGTH_FOR_STATE_NAME_IN_STORAGE_PATH'", ")", ...
Calculates the storage id of a state. This ID can be used for generating the file path for a state. :param rafcon.core.states.state.State state: state the storage_id should is composed for
[ "Calculates", "the", "storage", "id", "of", "a", "state", ".", "This", "ID", "can", "be", "used", "for", "generating", "the", "file", "path", "for", "a", "state", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/storage/storage.py#L535-L552
train
40,412
DLR-RM/RAFCON
source/rafcon/gui/views/state_editor/source_editor.py
SourceEditorView.pane_position_check
def pane_position_check(self): """ Update right bar pane position if needed Checks calculates if the cursor is still visible and updates the pane position if it is close to not be seen. In case of an un-docked right-bar this method does nothing. :return: """ text_buffer = self.get_buffer() # not needed if the right side bar is un-docked from rafcon.gui.singleton import main_window_controller if main_window_controller is None or main_window_controller.view is None: return from rafcon.gui.runtime_config import global_runtime_config if global_runtime_config.get_config_value('RIGHT_BAR_WINDOW_UNDOCKED'): return # move the pane left if the cursor is to far right and the pane position is less then 440 from its max position button_container_min_width = self.button_container_min_width width_of_all = button_container_min_width + self.tab_width text_view_width = button_container_min_width - self.line_numbers_width min_line_string_length = float(button_container_min_width)/float(self.source_view_character_size) current_pane_pos = main_window_controller.view['right_h_pane'].get_property('position') max_position = main_window_controller.view['right_h_pane'].get_property('max_position') pane_rel_pos = main_window_controller.view['right_h_pane'].get_property('max_position') - current_pane_pos if pane_rel_pos >= width_of_all + self.line_numbers_width: pass else: cursor_line_offset = text_buffer.get_iter_at_offset(text_buffer.props.cursor_position).get_line_offset() needed_rel_pos = text_view_width/min_line_string_length*cursor_line_offset \ + self.tab_width + self.line_numbers_width needed_rel_pos = min(width_of_all, needed_rel_pos) if pane_rel_pos >= needed_rel_pos: pass else: main_window_controller.view['right_h_pane'].set_property('position', max_position - needed_rel_pos) spacer_width = int(width_of_all + self.line_numbers_width - needed_rel_pos) self.spacer_frame.set_size_request(width=spacer_width, height=-1)
python
def pane_position_check(self): """ Update right bar pane position if needed Checks calculates if the cursor is still visible and updates the pane position if it is close to not be seen. In case of an un-docked right-bar this method does nothing. :return: """ text_buffer = self.get_buffer() # not needed if the right side bar is un-docked from rafcon.gui.singleton import main_window_controller if main_window_controller is None or main_window_controller.view is None: return from rafcon.gui.runtime_config import global_runtime_config if global_runtime_config.get_config_value('RIGHT_BAR_WINDOW_UNDOCKED'): return # move the pane left if the cursor is to far right and the pane position is less then 440 from its max position button_container_min_width = self.button_container_min_width width_of_all = button_container_min_width + self.tab_width text_view_width = button_container_min_width - self.line_numbers_width min_line_string_length = float(button_container_min_width)/float(self.source_view_character_size) current_pane_pos = main_window_controller.view['right_h_pane'].get_property('position') max_position = main_window_controller.view['right_h_pane'].get_property('max_position') pane_rel_pos = main_window_controller.view['right_h_pane'].get_property('max_position') - current_pane_pos if pane_rel_pos >= width_of_all + self.line_numbers_width: pass else: cursor_line_offset = text_buffer.get_iter_at_offset(text_buffer.props.cursor_position).get_line_offset() needed_rel_pos = text_view_width/min_line_string_length*cursor_line_offset \ + self.tab_width + self.line_numbers_width needed_rel_pos = min(width_of_all, needed_rel_pos) if pane_rel_pos >= needed_rel_pos: pass else: main_window_controller.view['right_h_pane'].set_property('position', max_position - needed_rel_pos) spacer_width = int(width_of_all + self.line_numbers_width - needed_rel_pos) self.spacer_frame.set_size_request(width=spacer_width, height=-1)
[ "def", "pane_position_check", "(", "self", ")", ":", "text_buffer", "=", "self", ".", "get_buffer", "(", ")", "# not needed if the right side bar is un-docked", "from", "rafcon", ".", "gui", ".", "singleton", "import", "main_window_controller", "if", "main_window_contro...
Update right bar pane position if needed Checks calculates if the cursor is still visible and updates the pane position if it is close to not be seen. In case of an un-docked right-bar this method does nothing. :return:
[ "Update", "right", "bar", "pane", "position", "if", "needed" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/state_editor/source_editor.py#L102-L141
train
40,413
DLR-RM/RAFCON
source/rafcon/core/execution/execution_history.py
ExecutionHistory.push_call_history_item
def push_call_history_item(self, state, call_type, state_for_scoped_data, input_data=None): """Adds a new call-history-item to the history item list A call history items stores information about the point in time where a method (entry, execute, exit) of certain state was called. :param state: the state that was called :param call_type: the call type of the execution step, i.e. if it refers to a container state or an execution state :param state_for_scoped_data: the state of which the scoped data needs to be saved for further usages (e.g. backward stepping) """ last_history_item = self.get_last_history_item() from rafcon.core.states.library_state import LibraryState # delayed imported on purpose if isinstance(state_for_scoped_data, LibraryState): state_for_scoped_data = state_for_scoped_data.state_copy return_item = CallItem(state, last_history_item, call_type, state_for_scoped_data, input_data, state.run_id) return self._push_item(last_history_item, return_item)
python
def push_call_history_item(self, state, call_type, state_for_scoped_data, input_data=None): """Adds a new call-history-item to the history item list A call history items stores information about the point in time where a method (entry, execute, exit) of certain state was called. :param state: the state that was called :param call_type: the call type of the execution step, i.e. if it refers to a container state or an execution state :param state_for_scoped_data: the state of which the scoped data needs to be saved for further usages (e.g. backward stepping) """ last_history_item = self.get_last_history_item() from rafcon.core.states.library_state import LibraryState # delayed imported on purpose if isinstance(state_for_scoped_data, LibraryState): state_for_scoped_data = state_for_scoped_data.state_copy return_item = CallItem(state, last_history_item, call_type, state_for_scoped_data, input_data, state.run_id) return self._push_item(last_history_item, return_item)
[ "def", "push_call_history_item", "(", "self", ",", "state", ",", "call_type", ",", "state_for_scoped_data", ",", "input_data", "=", "None", ")", ":", "last_history_item", "=", "self", ".", "get_last_history_item", "(", ")", "from", "rafcon", ".", "core", ".", ...
Adds a new call-history-item to the history item list A call history items stores information about the point in time where a method (entry, execute, exit) of certain state was called. :param state: the state that was called :param call_type: the call type of the execution step, i.e. if it refers to a container state or an execution state :param state_for_scoped_data: the state of which the scoped data needs to be saved for further usages (e.g. backward stepping)
[ "Adds", "a", "new", "call", "-", "history", "-", "item", "to", "the", "history", "item", "list" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/execution/execution_history.py#L169-L187
train
40,414
DLR-RM/RAFCON
source/rafcon/core/execution/execution_history.py
ExecutionHistory.push_return_history_item
def push_return_history_item(self, state, call_type, state_for_scoped_data, output_data=None): """Adds a new return-history-item to the history item list A return history items stores information about the point in time where a method (entry, execute, exit) of certain state returned. :param state: the state that returned :param call_type: the call type of the execution step, i.e. if it refers to a container state or an execution state :param state_for_scoped_data: the state of which the scoped data needs to be saved for further usages (e.g. backward stepping) """ last_history_item = self.get_last_history_item() from rafcon.core.states.library_state import LibraryState # delayed imported on purpose if isinstance(state_for_scoped_data, LibraryState): state_for_scoped_data = state_for_scoped_data.state_copy return_item = ReturnItem(state, last_history_item, call_type, state_for_scoped_data, output_data, state.run_id) return self._push_item(last_history_item, return_item)
python
def push_return_history_item(self, state, call_type, state_for_scoped_data, output_data=None): """Adds a new return-history-item to the history item list A return history items stores information about the point in time where a method (entry, execute, exit) of certain state returned. :param state: the state that returned :param call_type: the call type of the execution step, i.e. if it refers to a container state or an execution state :param state_for_scoped_data: the state of which the scoped data needs to be saved for further usages (e.g. backward stepping) """ last_history_item = self.get_last_history_item() from rafcon.core.states.library_state import LibraryState # delayed imported on purpose if isinstance(state_for_scoped_data, LibraryState): state_for_scoped_data = state_for_scoped_data.state_copy return_item = ReturnItem(state, last_history_item, call_type, state_for_scoped_data, output_data, state.run_id) return self._push_item(last_history_item, return_item)
[ "def", "push_return_history_item", "(", "self", ",", "state", ",", "call_type", ",", "state_for_scoped_data", ",", "output_data", "=", "None", ")", ":", "last_history_item", "=", "self", ".", "get_last_history_item", "(", ")", "from", "rafcon", ".", "core", ".",...
Adds a new return-history-item to the history item list A return history items stores information about the point in time where a method (entry, execute, exit) of certain state returned. :param state: the state that returned :param call_type: the call type of the execution step, i.e. if it refers to a container state or an execution state :param state_for_scoped_data: the state of which the scoped data needs to be saved for further usages (e.g. backward stepping)
[ "Adds", "a", "new", "return", "-", "history", "-", "item", "to", "the", "history", "item", "list" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/execution/execution_history.py#L190-L208
train
40,415
DLR-RM/RAFCON
source/rafcon/core/execution/execution_history.py
ExecutionHistory.push_concurrency_history_item
def push_concurrency_history_item(self, state, number_concurrent_threads): """Adds a new concurrency-history-item to the history item list A concurrent history item stores information about the point in time where a certain number of states is launched concurrently (e.g. in a barrier concurrency state). :param state: the state that launches the state group :param number_concurrent_threads: the number of states that are launched """ last_history_item = self.get_last_history_item() return_item = ConcurrencyItem(state, self.get_last_history_item(), number_concurrent_threads, state.run_id, self.execution_history_storage) return self._push_item(last_history_item, return_item)
python
def push_concurrency_history_item(self, state, number_concurrent_threads): """Adds a new concurrency-history-item to the history item list A concurrent history item stores information about the point in time where a certain number of states is launched concurrently (e.g. in a barrier concurrency state). :param state: the state that launches the state group :param number_concurrent_threads: the number of states that are launched """ last_history_item = self.get_last_history_item() return_item = ConcurrencyItem(state, self.get_last_history_item(), number_concurrent_threads, state.run_id, self.execution_history_storage) return self._push_item(last_history_item, return_item)
[ "def", "push_concurrency_history_item", "(", "self", ",", "state", ",", "number_concurrent_threads", ")", ":", "last_history_item", "=", "self", ".", "get_last_history_item", "(", ")", "return_item", "=", "ConcurrencyItem", "(", "state", ",", "self", ".", "get_last_...
Adds a new concurrency-history-item to the history item list A concurrent history item stores information about the point in time where a certain number of states is launched concurrently (e.g. in a barrier concurrency state). :param state: the state that launches the state group :param number_concurrent_threads: the number of states that are launched
[ "Adds", "a", "new", "concurrency", "-", "history", "-", "item", "to", "the", "history", "item", "list" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/execution/execution_history.py#L211-L225
train
40,416
DLR-RM/RAFCON
source/rafcon/utils/hashable.py
Hashable.update_hash_from_dict
def update_hash_from_dict(obj_hash, object_): """Updates an existing hash object with another Hashable, list, set, tuple, dict or stringifyable object :param obj_hash: The hash object (see Python hashlib documentation) :param object_: The value that should be added to the hash (can be another Hashable or a dictionary) """ if isinstance(object_, Hashable): object_.update_hash(obj_hash) elif isinstance(object_, (list, set, tuple)): if isinstance(object_, set): # A set is not ordered object_ = sorted(object_) for element in object_: Hashable.update_hash_from_dict(obj_hash, element) elif isinstance(object_, dict): for key in sorted(object_.keys()): # A dict is not ordered Hashable.update_hash_from_dict(obj_hash, key) Hashable.update_hash_from_dict(obj_hash, object_[key]) else: obj_hash.update(Hashable.get_object_hash_string(object_))
python
def update_hash_from_dict(obj_hash, object_): """Updates an existing hash object with another Hashable, list, set, tuple, dict or stringifyable object :param obj_hash: The hash object (see Python hashlib documentation) :param object_: The value that should be added to the hash (can be another Hashable or a dictionary) """ if isinstance(object_, Hashable): object_.update_hash(obj_hash) elif isinstance(object_, (list, set, tuple)): if isinstance(object_, set): # A set is not ordered object_ = sorted(object_) for element in object_: Hashable.update_hash_from_dict(obj_hash, element) elif isinstance(object_, dict): for key in sorted(object_.keys()): # A dict is not ordered Hashable.update_hash_from_dict(obj_hash, key) Hashable.update_hash_from_dict(obj_hash, object_[key]) else: obj_hash.update(Hashable.get_object_hash_string(object_))
[ "def", "update_hash_from_dict", "(", "obj_hash", ",", "object_", ")", ":", "if", "isinstance", "(", "object_", ",", "Hashable", ")", ":", "object_", ".", "update_hash", "(", "obj_hash", ")", "elif", "isinstance", "(", "object_", ",", "(", "list", ",", "set...
Updates an existing hash object with another Hashable, list, set, tuple, dict or stringifyable object :param obj_hash: The hash object (see Python hashlib documentation) :param object_: The value that should be added to the hash (can be another Hashable or a dictionary)
[ "Updates", "an", "existing", "hash", "object", "with", "another", "Hashable", "list", "set", "tuple", "dict", "or", "stringifyable", "object" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/hashable.py#L21-L39
train
40,417
DLR-RM/RAFCON
source/rafcon/utils/log_helpers.py
LoggingViewHandler.emit
def emit(self, record): """Logs a new record If a logging view is given, it is used to log the new record to. The code is partially copied from the StreamHandler class. :param record: :return: """ try: # Shorten the source name of the record (remove rafcon.) if sys.version_info >= (2, 7): record.__setattr__("name", record.name.replace("rafcon.", "")) msg = self.format(record) fs = "%s" try: ufs = u'%s' try: entry = ufs % msg except UnicodeEncodeError: entry = fs % msg except UnicodeError: entry = fs % msg for logging_view in self._logging_views.values(): logging_view.print_message(entry, record.levelno) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record)
python
def emit(self, record): """Logs a new record If a logging view is given, it is used to log the new record to. The code is partially copied from the StreamHandler class. :param record: :return: """ try: # Shorten the source name of the record (remove rafcon.) if sys.version_info >= (2, 7): record.__setattr__("name", record.name.replace("rafcon.", "")) msg = self.format(record) fs = "%s" try: ufs = u'%s' try: entry = ufs % msg except UnicodeEncodeError: entry = fs % msg except UnicodeError: entry = fs % msg for logging_view in self._logging_views.values(): logging_view.print_message(entry, record.levelno) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record)
[ "def", "emit", "(", "self", ",", "record", ")", ":", "try", ":", "# Shorten the source name of the record (remove rafcon.)", "if", "sys", ".", "version_info", ">=", "(", "2", ",", "7", ")", ":", "record", ".", "__setattr__", "(", "\"name\"", ",", "record", "...
Logs a new record If a logging view is given, it is used to log the new record to. The code is partially copied from the StreamHandler class. :param record: :return:
[ "Logs", "a", "new", "record" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/log_helpers.py#L60-L89
train
40,418
DLR-RM/RAFCON
source/rafcon/gui/models/meta.py
MetaModel.get_meta_data_editor
def get_meta_data_editor(self, for_gaphas=True): """Returns the editor for the specified editor This method should be used instead of accessing the meta data of an editor directly. It return the meta data of the editor available (with priority to the one specified by `for_gaphas`) and converts it if needed. :param bool for_gaphas: True (default) if the meta data is required for gaphas, False if for OpenGL :return: Meta data for the editor :rtype: Vividict """ meta_gaphas = self.meta['gui']['editor_gaphas'] meta_opengl = self.meta['gui']['editor_opengl'] assert isinstance(meta_gaphas, Vividict) and isinstance(meta_opengl, Vividict) # Use meta data of editor with more keys (typically one of the editors has zero keys) # TODO check if the magic length condition in the next line can be improved (consistent behavior getter/setter?) parental_conversion_from_opengl = self._parent and self._parent().temp['conversion_from_opengl'] from_gaphas = len(meta_gaphas) > len(meta_opengl) or (len(meta_gaphas) == len(meta_opengl) and for_gaphas and not parental_conversion_from_opengl) # Convert meta data if meta data target and origin differ if from_gaphas and not for_gaphas: self.meta['gui']['editor_opengl'] = self._meta_data_editor_gaphas2opengl(meta_gaphas) elif not from_gaphas and for_gaphas: self.meta['gui']['editor_gaphas'] = self._meta_data_editor_opengl2gaphas(meta_opengl) # only keep meta data for one editor del self.meta['gui']['editor_opengl' if for_gaphas else 'editor_gaphas'] return self.meta['gui']['editor_gaphas'] if for_gaphas else self.meta['gui']['editor_opengl']
python
def get_meta_data_editor(self, for_gaphas=True): """Returns the editor for the specified editor This method should be used instead of accessing the meta data of an editor directly. It return the meta data of the editor available (with priority to the one specified by `for_gaphas`) and converts it if needed. :param bool for_gaphas: True (default) if the meta data is required for gaphas, False if for OpenGL :return: Meta data for the editor :rtype: Vividict """ meta_gaphas = self.meta['gui']['editor_gaphas'] meta_opengl = self.meta['gui']['editor_opengl'] assert isinstance(meta_gaphas, Vividict) and isinstance(meta_opengl, Vividict) # Use meta data of editor with more keys (typically one of the editors has zero keys) # TODO check if the magic length condition in the next line can be improved (consistent behavior getter/setter?) parental_conversion_from_opengl = self._parent and self._parent().temp['conversion_from_opengl'] from_gaphas = len(meta_gaphas) > len(meta_opengl) or (len(meta_gaphas) == len(meta_opengl) and for_gaphas and not parental_conversion_from_opengl) # Convert meta data if meta data target and origin differ if from_gaphas and not for_gaphas: self.meta['gui']['editor_opengl'] = self._meta_data_editor_gaphas2opengl(meta_gaphas) elif not from_gaphas and for_gaphas: self.meta['gui']['editor_gaphas'] = self._meta_data_editor_opengl2gaphas(meta_opengl) # only keep meta data for one editor del self.meta['gui']['editor_opengl' if for_gaphas else 'editor_gaphas'] return self.meta['gui']['editor_gaphas'] if for_gaphas else self.meta['gui']['editor_opengl']
[ "def", "get_meta_data_editor", "(", "self", ",", "for_gaphas", "=", "True", ")", ":", "meta_gaphas", "=", "self", ".", "meta", "[", "'gui'", "]", "[", "'editor_gaphas'", "]", "meta_opengl", "=", "self", ".", "meta", "[", "'gui'", "]", "[", "'editor_opengl'...
Returns the editor for the specified editor This method should be used instead of accessing the meta data of an editor directly. It return the meta data of the editor available (with priority to the one specified by `for_gaphas`) and converts it if needed. :param bool for_gaphas: True (default) if the meta data is required for gaphas, False if for OpenGL :return: Meta data for the editor :rtype: Vividict
[ "Returns", "the", "editor", "for", "the", "specified", "editor" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/meta.py#L59-L86
train
40,419
DLR-RM/RAFCON
source/rafcon/gui/models/meta.py
MetaModel.set_meta_data_editor
def set_meta_data_editor(self, key, meta_data, from_gaphas=True): """Sets the meta data for a specific key of the desired editor :param str key: The meta data key, separated by dots if it is nested :param meta_data: The value to be set :param bool from_gaphas: If the data comes from a gaphas editor """ self.do_convert_meta_data_if_no_data(from_gaphas) meta_gui = self.meta['gui'] meta_gui = meta_gui['editor_gaphas'] if from_gaphas else meta_gui['editor_opengl'] key_path = key.split('.') for key in key_path: if isinstance(meta_gui, list): meta_gui[int(key)] = meta_data break if key == key_path[-1]: meta_gui[key] = meta_data else: meta_gui = meta_gui[key] return self.get_meta_data_editor(for_gaphas=from_gaphas)
python
def set_meta_data_editor(self, key, meta_data, from_gaphas=True): """Sets the meta data for a specific key of the desired editor :param str key: The meta data key, separated by dots if it is nested :param meta_data: The value to be set :param bool from_gaphas: If the data comes from a gaphas editor """ self.do_convert_meta_data_if_no_data(from_gaphas) meta_gui = self.meta['gui'] meta_gui = meta_gui['editor_gaphas'] if from_gaphas else meta_gui['editor_opengl'] key_path = key.split('.') for key in key_path: if isinstance(meta_gui, list): meta_gui[int(key)] = meta_data break if key == key_path[-1]: meta_gui[key] = meta_data else: meta_gui = meta_gui[key] return self.get_meta_data_editor(for_gaphas=from_gaphas)
[ "def", "set_meta_data_editor", "(", "self", ",", "key", ",", "meta_data", ",", "from_gaphas", "=", "True", ")", ":", "self", ".", "do_convert_meta_data_if_no_data", "(", "from_gaphas", ")", "meta_gui", "=", "self", ".", "meta", "[", "'gui'", "]", "meta_gui", ...
Sets the meta data for a specific key of the desired editor :param str key: The meta data key, separated by dots if it is nested :param meta_data: The value to be set :param bool from_gaphas: If the data comes from a gaphas editor
[ "Sets", "the", "meta", "data", "for", "a", "specific", "key", "of", "the", "desired", "editor" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/meta.py#L94-L115
train
40,420
DLR-RM/RAFCON
source/rafcon/gui/models/meta.py
MetaModel.meta_data_hash
def meta_data_hash(self, obj_hash=None): """Creates a hash with the meta data of the model :param obj_hash: The hash object (see Python hashlib) :return: The updated hash object """ if obj_hash is None: obj_hash = hashlib.sha256() self.update_meta_data_hash(obj_hash) return obj_hash
python
def meta_data_hash(self, obj_hash=None): """Creates a hash with the meta data of the model :param obj_hash: The hash object (see Python hashlib) :return: The updated hash object """ if obj_hash is None: obj_hash = hashlib.sha256() self.update_meta_data_hash(obj_hash) return obj_hash
[ "def", "meta_data_hash", "(", "self", ",", "obj_hash", "=", "None", ")", ":", "if", "obj_hash", "is", "None", ":", "obj_hash", "=", "hashlib", ".", "sha256", "(", ")", "self", ".", "update_meta_data_hash", "(", "obj_hash", ")", "return", "obj_hash" ]
Creates a hash with the meta data of the model :param obj_hash: The hash object (see Python hashlib) :return: The updated hash object
[ "Creates", "a", "hash", "with", "the", "meta", "data", "of", "the", "model" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/meta.py#L117-L126
train
40,421
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_draw_helper.py
limit_value_string_length
def limit_value_string_length(value): """This method limits the string representation of the value to MAX_VALUE_LABEL_TEXT_LENGTH + 3 characters. :param value: Value to limit string representation :return: String holding the value with a maximum length of MAX_VALUE_LABEL_TEXT_LENGTH + 3 """ if isinstance(value, string_types) and len(value) > constants.MAX_VALUE_LABEL_TEXT_LENGTH: value = value[:constants.MAX_VALUE_LABEL_TEXT_LENGTH] + "..." final_string = " " + value + " " elif isinstance(value, (dict, list)) and len(str(value)) > constants.MAX_VALUE_LABEL_TEXT_LENGTH: value_text = str(value)[:constants.MAX_VALUE_LABEL_TEXT_LENGTH] + "..." final_string = " " + value_text + " " else: final_string = " " + str(value) + " " return final_string
python
def limit_value_string_length(value): """This method limits the string representation of the value to MAX_VALUE_LABEL_TEXT_LENGTH + 3 characters. :param value: Value to limit string representation :return: String holding the value with a maximum length of MAX_VALUE_LABEL_TEXT_LENGTH + 3 """ if isinstance(value, string_types) and len(value) > constants.MAX_VALUE_LABEL_TEXT_LENGTH: value = value[:constants.MAX_VALUE_LABEL_TEXT_LENGTH] + "..." final_string = " " + value + " " elif isinstance(value, (dict, list)) and len(str(value)) > constants.MAX_VALUE_LABEL_TEXT_LENGTH: value_text = str(value)[:constants.MAX_VALUE_LABEL_TEXT_LENGTH] + "..." final_string = " " + value_text + " " else: final_string = " " + str(value) + " " return final_string
[ "def", "limit_value_string_length", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "string_types", ")", "and", "len", "(", "value", ")", ">", "constants", ".", "MAX_VALUE_LABEL_TEXT_LENGTH", ":", "value", "=", "value", "[", ":", "constants", ...
This method limits the string representation of the value to MAX_VALUE_LABEL_TEXT_LENGTH + 3 characters. :param value: Value to limit string representation :return: String holding the value with a maximum length of MAX_VALUE_LABEL_TEXT_LENGTH + 3
[ "This", "method", "limits", "the", "string", "representation", "of", "the", "value", "to", "MAX_VALUE_LABEL_TEXT_LENGTH", "+", "3", "characters", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_draw_helper.py#L33-L48
train
40,422
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_draw_helper.py
get_col_rgba
def get_col_rgba(color, transparency=None, opacity=None): """This class converts a Gdk.Color into its r, g, b parts and adds an alpha according to needs If both transparency and opacity is None, alpha is set to 1 => opaque :param Gdk.Color color: Color to extract r, g and b from :param float | None transparency: Value between 0 (opaque) and 1 (transparent) or None if opacity is to be used :param float | None opacity: Value between 0 (transparent) and 1 (opaque) or None if transparency is to be used :return: Red, Green, Blue and Alpha value (all between 0.0 - 1.0) """ r, g, b = color.red, color.green, color.blue # Convert from 0-6535 to 0-1 r /= 65535. g /= 65535. b /= 65535. if transparency is not None or opacity is None: transparency = 0 if transparency is None else transparency # default value if transparency < 0 or transparency > 1: raise ValueError("Transparency must be between 0 and 1") alpha = 1 - transparency else: if opacity < 0 or opacity > 1: raise ValueError("Opacity must be between 0 and 1") alpha = opacity return r, g, b, alpha
python
def get_col_rgba(color, transparency=None, opacity=None): """This class converts a Gdk.Color into its r, g, b parts and adds an alpha according to needs If both transparency and opacity is None, alpha is set to 1 => opaque :param Gdk.Color color: Color to extract r, g and b from :param float | None transparency: Value between 0 (opaque) and 1 (transparent) or None if opacity is to be used :param float | None opacity: Value between 0 (transparent) and 1 (opaque) or None if transparency is to be used :return: Red, Green, Blue and Alpha value (all between 0.0 - 1.0) """ r, g, b = color.red, color.green, color.blue # Convert from 0-6535 to 0-1 r /= 65535. g /= 65535. b /= 65535. if transparency is not None or opacity is None: transparency = 0 if transparency is None else transparency # default value if transparency < 0 or transparency > 1: raise ValueError("Transparency must be between 0 and 1") alpha = 1 - transparency else: if opacity < 0 or opacity > 1: raise ValueError("Opacity must be between 0 and 1") alpha = opacity return r, g, b, alpha
[ "def", "get_col_rgba", "(", "color", ",", "transparency", "=", "None", ",", "opacity", "=", "None", ")", ":", "r", ",", "g", ",", "b", "=", "color", ".", "red", ",", "color", ".", "green", ",", "color", ".", "blue", "# Convert from 0-6535 to 0-1", "r",...
This class converts a Gdk.Color into its r, g, b parts and adds an alpha according to needs If both transparency and opacity is None, alpha is set to 1 => opaque :param Gdk.Color color: Color to extract r, g and b from :param float | None transparency: Value between 0 (opaque) and 1 (transparent) or None if opacity is to be used :param float | None opacity: Value between 0 (transparent) and 1 (opaque) or None if transparency is to be used :return: Red, Green, Blue and Alpha value (all between 0.0 - 1.0)
[ "This", "class", "converts", "a", "Gdk", ".", "Color", "into", "its", "r", "g", "b", "parts", "and", "adds", "an", "alpha", "according", "to", "needs" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_draw_helper.py#L51-L77
train
40,423
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_draw_helper.py
get_side_length_of_resize_handle
def get_side_length_of_resize_handle(view, item): """Calculate the side length of a resize handle :param rafcon.gui.mygaphas.view.ExtendedGtkView view: View :param rafcon.gui.mygaphas.items.state.StateView item: StateView :return: side length :rtype: float """ from rafcon.gui.mygaphas.items.state import StateView, NameView if isinstance(item, StateView): return item.border_width * view.get_zoom_factor() / 1.5 elif isinstance(item, NameView): return item.parent.border_width * view.get_zoom_factor() / 2.5 return 0
python
def get_side_length_of_resize_handle(view, item): """Calculate the side length of a resize handle :param rafcon.gui.mygaphas.view.ExtendedGtkView view: View :param rafcon.gui.mygaphas.items.state.StateView item: StateView :return: side length :rtype: float """ from rafcon.gui.mygaphas.items.state import StateView, NameView if isinstance(item, StateView): return item.border_width * view.get_zoom_factor() / 1.5 elif isinstance(item, NameView): return item.parent.border_width * view.get_zoom_factor() / 2.5 return 0
[ "def", "get_side_length_of_resize_handle", "(", "view", ",", "item", ")", ":", "from", "rafcon", ".", "gui", ".", "mygaphas", ".", "items", ".", "state", "import", "StateView", ",", "NameView", "if", "isinstance", "(", "item", ",", "StateView", ")", ":", "...
Calculate the side length of a resize handle :param rafcon.gui.mygaphas.view.ExtendedGtkView view: View :param rafcon.gui.mygaphas.items.state.StateView item: StateView :return: side length :rtype: float
[ "Calculate", "the", "side", "length", "of", "a", "resize", "handle" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_draw_helper.py#L80-L93
train
40,424
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_draw_helper.py
draw_data_value_rect
def draw_data_value_rect(cairo_context, color, value_size, name_size, pos, port_side): """This method draws the containing rect for the data port value, depending on the side and size of the label. :param cairo_context: Draw Context :param color: Background color of value part :param value_size: Size (width, height) of label holding the value :param name_size: Size (width, height) of label holding the name :param pos: Position of name label start point (upper left corner of label) :param port_side: Side on which the value part should be drawn :return: Rotation Angle (to rotate value accordingly), X-Position of value label start point, Y-Position of value label start point """ c = cairo_context rot_angle = .0 move_x = 0. move_y = 0. if port_side is SnappedSide.RIGHT: move_x = pos[0] + name_size[0] move_y = pos[1] c.rectangle(move_x, move_y, value_size[0], value_size[1]) elif port_side is SnappedSide.BOTTOM: move_x = pos[0] - value_size[1] move_y = pos[1] + name_size[0] rot_angle = pi / 2. c.rectangle(move_x, move_y, value_size[1], value_size[0]) elif port_side is SnappedSide.LEFT: move_x = pos[0] - value_size[0] move_y = pos[1] c.rectangle(move_x, move_y, value_size[0], value_size[1]) elif port_side is SnappedSide.TOP: move_x = pos[0] - value_size[1] move_y = pos[1] - value_size[0] rot_angle = -pi / 2. c.rectangle(move_x, move_y, value_size[1], value_size[0]) c.set_source_rgba(*color) c.fill_preserve() c.set_source_rgb(*gui_config.gtk_colors['BLACK'].to_floats()) c.stroke() return rot_angle, move_x, move_y
python
def draw_data_value_rect(cairo_context, color, value_size, name_size, pos, port_side): """This method draws the containing rect for the data port value, depending on the side and size of the label. :param cairo_context: Draw Context :param color: Background color of value part :param value_size: Size (width, height) of label holding the value :param name_size: Size (width, height) of label holding the name :param pos: Position of name label start point (upper left corner of label) :param port_side: Side on which the value part should be drawn :return: Rotation Angle (to rotate value accordingly), X-Position of value label start point, Y-Position of value label start point """ c = cairo_context rot_angle = .0 move_x = 0. move_y = 0. if port_side is SnappedSide.RIGHT: move_x = pos[0] + name_size[0] move_y = pos[1] c.rectangle(move_x, move_y, value_size[0], value_size[1]) elif port_side is SnappedSide.BOTTOM: move_x = pos[0] - value_size[1] move_y = pos[1] + name_size[0] rot_angle = pi / 2. c.rectangle(move_x, move_y, value_size[1], value_size[0]) elif port_side is SnappedSide.LEFT: move_x = pos[0] - value_size[0] move_y = pos[1] c.rectangle(move_x, move_y, value_size[0], value_size[1]) elif port_side is SnappedSide.TOP: move_x = pos[0] - value_size[1] move_y = pos[1] - value_size[0] rot_angle = -pi / 2. c.rectangle(move_x, move_y, value_size[1], value_size[0]) c.set_source_rgba(*color) c.fill_preserve() c.set_source_rgb(*gui_config.gtk_colors['BLACK'].to_floats()) c.stroke() return rot_angle, move_x, move_y
[ "def", "draw_data_value_rect", "(", "cairo_context", ",", "color", ",", "value_size", ",", "name_size", ",", "pos", ",", "port_side", ")", ":", "c", "=", "cairo_context", "rot_angle", "=", ".0", "move_x", "=", "0.", "move_y", "=", "0.", "if", "port_side", ...
This method draws the containing rect for the data port value, depending on the side and size of the label. :param cairo_context: Draw Context :param color: Background color of value part :param value_size: Size (width, height) of label holding the value :param name_size: Size (width, height) of label holding the name :param pos: Position of name label start point (upper left corner of label) :param port_side: Side on which the value part should be drawn :return: Rotation Angle (to rotate value accordingly), X-Position of value label start point, Y-Position of value label start point
[ "This", "method", "draws", "the", "containing", "rect", "for", "the", "data", "port", "value", "depending", "on", "the", "side", "and", "size", "of", "the", "label", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_draw_helper.py#L96-L142
train
40,425
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/utils/gap_draw_helper.py
draw_label_path
def draw_label_path(context, width, height, arrow_height, distance_to_port, port_offset): """Draws the path for an upright label :param context: The Cairo context :param float width: Width of the label :param float height: Height of the label :param float distance_to_port: Distance to the port related to the label :param float port_offset: Distance from the port center to its border :param bool draw_connection_to_port: Whether to draw a line from the tip of the label to the port """ c = context # The current point is the port position # Mover to outer border of state c.rel_move_to(0, port_offset) # Draw line to arrow tip of label c.rel_line_to(0, distance_to_port) # Line to upper left corner c.rel_line_to(-width / 2., arrow_height) # Line to lower left corner c.rel_line_to(0, height - arrow_height) # Line to lower right corner c.rel_line_to(width, 0) # Line to upper right corner c.rel_line_to(0, -(height - arrow_height)) # Line to center top (tip of label) c.rel_line_to(-width / 2., -arrow_height) # Close path c.close_path()
python
def draw_label_path(context, width, height, arrow_height, distance_to_port, port_offset): """Draws the path for an upright label :param context: The Cairo context :param float width: Width of the label :param float height: Height of the label :param float distance_to_port: Distance to the port related to the label :param float port_offset: Distance from the port center to its border :param bool draw_connection_to_port: Whether to draw a line from the tip of the label to the port """ c = context # The current point is the port position # Mover to outer border of state c.rel_move_to(0, port_offset) # Draw line to arrow tip of label c.rel_line_to(0, distance_to_port) # Line to upper left corner c.rel_line_to(-width / 2., arrow_height) # Line to lower left corner c.rel_line_to(0, height - arrow_height) # Line to lower right corner c.rel_line_to(width, 0) # Line to upper right corner c.rel_line_to(0, -(height - arrow_height)) # Line to center top (tip of label) c.rel_line_to(-width / 2., -arrow_height) # Close path c.close_path()
[ "def", "draw_label_path", "(", "context", ",", "width", ",", "height", ",", "arrow_height", ",", "distance_to_port", ",", "port_offset", ")", ":", "c", "=", "context", "# The current point is the port position", "# Mover to outer border of state", "c", ".", "rel_move_to...
Draws the path for an upright label :param context: The Cairo context :param float width: Width of the label :param float height: Height of the label :param float distance_to_port: Distance to the port related to the label :param float port_offset: Distance from the port center to its border :param bool draw_connection_to_port: Whether to draw a line from the tip of the label to the port
[ "Draws", "the", "path", "for", "an", "upright", "label" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/utils/gap_draw_helper.py#L416-L445
train
40,426
DLR-RM/RAFCON
source/rafcon/gui/models/library_state.py
LibraryStateModel._load_income_model
def _load_income_model(self): """Reloads the income model directly from the state""" if not self.state_copy_initialized: return self.income = None income_m = deepcopy(self.state_copy.income) income_m.parent = self income_m.income = income_m.income self.income = income_m
python
def _load_income_model(self): """Reloads the income model directly from the state""" if not self.state_copy_initialized: return self.income = None income_m = deepcopy(self.state_copy.income) income_m.parent = self income_m.income = income_m.income self.income = income_m
[ "def", "_load_income_model", "(", "self", ")", ":", "if", "not", "self", ".", "state_copy_initialized", ":", "return", "self", ".", "income", "=", "None", "income_m", "=", "deepcopy", "(", "self", ".", "state_copy", ".", "income", ")", "income_m", ".", "pa...
Reloads the income model directly from the state
[ "Reloads", "the", "income", "model", "directly", "from", "the", "state" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/library_state.py#L164-L172
train
40,427
DLR-RM/RAFCON
source/rafcon/gui/models/library_state.py
LibraryStateModel._load_outcome_models
def _load_outcome_models(self): """Reloads the outcome models directly from the state""" if not self.state_copy_initialized: return self.outcomes = [] for outcome_m in self.state_copy.outcomes: new_oc_m = deepcopy(outcome_m) new_oc_m.parent = self new_oc_m.outcome = outcome_m.outcome self.outcomes.append(new_oc_m)
python
def _load_outcome_models(self): """Reloads the outcome models directly from the state""" if not self.state_copy_initialized: return self.outcomes = [] for outcome_m in self.state_copy.outcomes: new_oc_m = deepcopy(outcome_m) new_oc_m.parent = self new_oc_m.outcome = outcome_m.outcome self.outcomes.append(new_oc_m)
[ "def", "_load_outcome_models", "(", "self", ")", ":", "if", "not", "self", ".", "state_copy_initialized", ":", "return", "self", ".", "outcomes", "=", "[", "]", "for", "outcome_m", "in", "self", ".", "state_copy", ".", "outcomes", ":", "new_oc_m", "=", "de...
Reloads the outcome models directly from the state
[ "Reloads", "the", "outcome", "models", "directly", "from", "the", "state" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/library_state.py#L174-L183
train
40,428
DLR-RM/RAFCON
source/rafcon/gui/models/state_element.py
StateElementModel.model_changed
def model_changed(self, model, prop_name, info): """This method notifies the parent state about changes made to the state element """ if self.parent is not None: self.parent.model_changed(model, prop_name, info)
python
def model_changed(self, model, prop_name, info): """This method notifies the parent state about changes made to the state element """ if self.parent is not None: self.parent.model_changed(model, prop_name, info)
[ "def", "model_changed", "(", "self", ",", "model", ",", "prop_name", ",", "info", ")", ":", "if", "self", ".", "parent", "is", "not", "None", ":", "self", ".", "parent", ".", "model_changed", "(", "model", ",", "prop_name", ",", "info", ")" ]
This method notifies the parent state about changes made to the state element
[ "This", "method", "notifies", "the", "parent", "state", "about", "changes", "made", "to", "the", "state", "element" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/state_element.py#L128-L132
train
40,429
DLR-RM/RAFCON
source/rafcon/gui/controllers/execution_ticker.py
ExecutionTickerController.disable
def disable(self): """ Relieve all state machines that have no active execution and hide the widget """ self.ticker_text_label.hide() if self.current_observed_sm_m: self.stop_sm_m_observation(self.current_observed_sm_m)
python
def disable(self): """ Relieve all state machines that have no active execution and hide the widget """ self.ticker_text_label.hide() if self.current_observed_sm_m: self.stop_sm_m_observation(self.current_observed_sm_m)
[ "def", "disable", "(", "self", ")", ":", "self", ".", "ticker_text_label", ".", "hide", "(", ")", "if", "self", ".", "current_observed_sm_m", ":", "self", ".", "stop_sm_m_observation", "(", "self", ".", "current_observed_sm_m", ")" ]
Relieve all state machines that have no active execution and hide the widget
[ "Relieve", "all", "state", "machines", "that", "have", "no", "active", "execution", "and", "hide", "the", "widget" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/execution_ticker.py#L90-L95
train
40,430
DLR-RM/RAFCON
source/rafcon/gui/controllers/execution_ticker.py
ExecutionTickerController.on_state_execution_status_changed_after
def on_state_execution_status_changed_after(self, model, prop_name, info): """ Show current execution status in the widget This function specifies what happens if the state machine execution status of a state changes :param model: the model of the state that has changed (most likely its execution status) :param prop_name: property name that has been changed :param info: notification info dictionary :return: """ from rafcon.gui.utils.notification_overview import NotificationOverview from rafcon.core.states.state import State def name_and_next_state(state): assert isinstance(state, State) if state.is_root_state_of_library: return state.parent.parent, state.parent.name else: return state.parent, state.name def create_path(state, n=3, separator='/'): next_parent, name = name_and_next_state(state) path = separator + name n -= 1 while n > 0 and isinstance(next_parent, State): next_parent, name = name_and_next_state(next_parent) path = separator + name + path n -= 1 if isinstance(next_parent, State): path = separator + '..' + path return path if 'kwargs' in info and 'method_name' in info['kwargs']: overview = NotificationOverview(info) if overview['method_name'][-1] == 'state_execution_status': active_state = overview['model'][-1].state assert isinstance(active_state, State) path_depth = rafcon.gui.singleton.global_gui_config.get_config_value("EXECUTION_TICKER_PATH_DEPTH", 3) message = self._fix_text_of_label + create_path(active_state, path_depth) if rafcon.gui.singleton.main_window_controller.view is not None: self.ticker_text_label.set_text(message) else: logger.warn("Not initialized yet")
python
def on_state_execution_status_changed_after(self, model, prop_name, info): """ Show current execution status in the widget This function specifies what happens if the state machine execution status of a state changes :param model: the model of the state that has changed (most likely its execution status) :param prop_name: property name that has been changed :param info: notification info dictionary :return: """ from rafcon.gui.utils.notification_overview import NotificationOverview from rafcon.core.states.state import State def name_and_next_state(state): assert isinstance(state, State) if state.is_root_state_of_library: return state.parent.parent, state.parent.name else: return state.parent, state.name def create_path(state, n=3, separator='/'): next_parent, name = name_and_next_state(state) path = separator + name n -= 1 while n > 0 and isinstance(next_parent, State): next_parent, name = name_and_next_state(next_parent) path = separator + name + path n -= 1 if isinstance(next_parent, State): path = separator + '..' + path return path if 'kwargs' in info and 'method_name' in info['kwargs']: overview = NotificationOverview(info) if overview['method_name'][-1] == 'state_execution_status': active_state = overview['model'][-1].state assert isinstance(active_state, State) path_depth = rafcon.gui.singleton.global_gui_config.get_config_value("EXECUTION_TICKER_PATH_DEPTH", 3) message = self._fix_text_of_label + create_path(active_state, path_depth) if rafcon.gui.singleton.main_window_controller.view is not None: self.ticker_text_label.set_text(message) else: logger.warn("Not initialized yet")
[ "def", "on_state_execution_status_changed_after", "(", "self", ",", "model", ",", "prop_name", ",", "info", ")", ":", "from", "rafcon", ".", "gui", ".", "utils", ".", "notification_overview", "import", "NotificationOverview", "from", "rafcon", ".", "core", ".", ...
Show current execution status in the widget This function specifies what happens if the state machine execution status of a state changes :param model: the model of the state that has changed (most likely its execution status) :param prop_name: property name that has been changed :param info: notification info dictionary :return:
[ "Show", "current", "execution", "status", "in", "the", "widget" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/execution_ticker.py#L105-L149
train
40,431
DLR-RM/RAFCON
source/rafcon/gui/controllers/execution_ticker.py
ExecutionTickerController.execution_engine_model_changed
def execution_engine_model_changed(self, model, prop_name, info): """Active observation of state machine and show and hide widget. """ if not self._view_initialized: return active_sm_id = rafcon.gui.singleton.state_machine_manager_model.state_machine_manager.active_state_machine_id if active_sm_id is None: # relieve all state machines that have no active execution and hide the widget self.disable() else: # observe all state machines that have an active execution and show the widget self.check_configuration()
python
def execution_engine_model_changed(self, model, prop_name, info): """Active observation of state machine and show and hide widget. """ if not self._view_initialized: return active_sm_id = rafcon.gui.singleton.state_machine_manager_model.state_machine_manager.active_state_machine_id if active_sm_id is None: # relieve all state machines that have no active execution and hide the widget self.disable() else: # observe all state machines that have an active execution and show the widget self.check_configuration()
[ "def", "execution_engine_model_changed", "(", "self", ",", "model", ",", "prop_name", ",", "info", ")", ":", "if", "not", "self", ".", "_view_initialized", ":", "return", "active_sm_id", "=", "rafcon", ".", "gui", ".", "singleton", ".", "state_machine_manager_mo...
Active observation of state machine and show and hide widget.
[ "Active", "observation", "of", "state", "machine", "and", "show", "and", "hide", "widget", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/execution_ticker.py#L163-L174
train
40,432
DLR-RM/RAFCON
share/examples/plugins/templates/core_template_observer.py
ExecutionEngineObserver.register_observer
def register_observer(self): """ Register all observable which are of interest """ self.execution_engine.add_observer(self, "start", notify_before_function=self.on_start) self.execution_engine.add_observer(self, "pause", notify_before_function=self.on_pause) self.execution_engine.add_observer(self, "stop", notify_before_function=self.on_stop)
python
def register_observer(self): """ Register all observable which are of interest """ self.execution_engine.add_observer(self, "start", notify_before_function=self.on_start) self.execution_engine.add_observer(self, "pause", notify_before_function=self.on_pause) self.execution_engine.add_observer(self, "stop", notify_before_function=self.on_stop)
[ "def", "register_observer", "(", "self", ")", ":", "self", ".", "execution_engine", ".", "add_observer", "(", "self", ",", "\"start\"", ",", "notify_before_function", "=", "self", ".", "on_start", ")", "self", ".", "execution_engine", ".", "add_observer", "(", ...
Register all observable which are of interest
[ "Register", "all", "observable", "which", "are", "of", "interest" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/share/examples/plugins/templates/core_template_observer.py#L17-L22
train
40,433
DLR-RM/RAFCON
source/rafcon/gui/views/main_window.py
MainWindowView.rotate_and_detach_tab_labels
def rotate_and_detach_tab_labels(self): """Rotates tab labels of a given notebook by 90 degrees and makes them detachable. :param notebook: GTK Notebook container, whose tab labels are to be rotated and made detachable """ icons = {'Libraries': constants.SIGN_LIB, 'States Tree': constants.ICON_TREE, 'Global Variables': constants.ICON_GLOB, 'Modification History': constants.ICON_HIST, 'Execution History': constants.ICON_EHIST, 'network': constants.ICON_NET} for notebook in self.left_bar_notebooks: for i in range(notebook.get_n_pages()): child = notebook.get_nth_page(i) tab_label = notebook.get_tab_label(child) tab_label_text = tab_label.get_text() notebook.set_tab_label(child, gui_helper_label.create_tab_header_label(tab_label_text, icons)) notebook.set_tab_reorderable(child, True) notebook.set_tab_detachable(child, True)
python
def rotate_and_detach_tab_labels(self): """Rotates tab labels of a given notebook by 90 degrees and makes them detachable. :param notebook: GTK Notebook container, whose tab labels are to be rotated and made detachable """ icons = {'Libraries': constants.SIGN_LIB, 'States Tree': constants.ICON_TREE, 'Global Variables': constants.ICON_GLOB, 'Modification History': constants.ICON_HIST, 'Execution History': constants.ICON_EHIST, 'network': constants.ICON_NET} for notebook in self.left_bar_notebooks: for i in range(notebook.get_n_pages()): child = notebook.get_nth_page(i) tab_label = notebook.get_tab_label(child) tab_label_text = tab_label.get_text() notebook.set_tab_label(child, gui_helper_label.create_tab_header_label(tab_label_text, icons)) notebook.set_tab_reorderable(child, True) notebook.set_tab_detachable(child, True)
[ "def", "rotate_and_detach_tab_labels", "(", "self", ")", ":", "icons", "=", "{", "'Libraries'", ":", "constants", ".", "SIGN_LIB", ",", "'States Tree'", ":", "constants", ".", "ICON_TREE", ",", "'Global Variables'", ":", "constants", ".", "ICON_GLOB", ",", "'Mod...
Rotates tab labels of a given notebook by 90 degrees and makes them detachable. :param notebook: GTK Notebook container, whose tab labels are to be rotated and made detachable
[ "Rotates", "tab", "labels", "of", "a", "given", "notebook", "by", "90", "degrees", "and", "makes", "them", "detachable", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/main_window.py#L225-L240
train
40,434
DLR-RM/RAFCON
source/rafcon/gui/views/main_window.py
MainWindowView.bring_tab_to_the_top
def bring_tab_to_the_top(self, tab_label): """Find tab with label tab_label in list of notebooks and set it to the current page. :param tab_label: String containing the label of the tab to be focused """ found = False for notebook in self.left_bar_notebooks: for i in range(notebook.get_n_pages()): if gui_helper_label.get_notebook_tab_title(notebook, i) == gui_helper_label.get_widget_title(tab_label): found = True break if found: notebook.set_current_page(i) break
python
def bring_tab_to_the_top(self, tab_label): """Find tab with label tab_label in list of notebooks and set it to the current page. :param tab_label: String containing the label of the tab to be focused """ found = False for notebook in self.left_bar_notebooks: for i in range(notebook.get_n_pages()): if gui_helper_label.get_notebook_tab_title(notebook, i) == gui_helper_label.get_widget_title(tab_label): found = True break if found: notebook.set_current_page(i) break
[ "def", "bring_tab_to_the_top", "(", "self", ",", "tab_label", ")", ":", "found", "=", "False", "for", "notebook", "in", "self", ".", "left_bar_notebooks", ":", "for", "i", "in", "range", "(", "notebook", ".", "get_n_pages", "(", ")", ")", ":", "if", "gui...
Find tab with label tab_label in list of notebooks and set it to the current page. :param tab_label: String containing the label of the tab to be focused
[ "Find", "tab", "with", "label", "tab_label", "in", "list", "of", "notebooks", "and", "set", "it", "to", "the", "current", "page", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/views/main_window.py#L242-L255
train
40,435
DLR-RM/RAFCON
source/rafcon/gui/helpers/utility.py
add_transitions_from_selected_state_to_parent
def add_transitions_from_selected_state_to_parent(): """ Generates the default success transition of a state to its parent success port :return: """ task_string = "create transition" sub_task_string = "to parent state" selected_state_m, msg = get_selected_single_state_model_and_check_for_its_parent() if selected_state_m is None: logger.warning("Can not {0} {1}: {2}".format(task_string, sub_task_string, msg)) return logger.debug("Check to {0} {1} ...".format(task_string, sub_task_string)) state = selected_state_m.state parent_state = state.parent # find all possible from outcomes from_outcomes = get_all_outcomes_except_of_abort_and_preempt(state) # find lowest valid outcome id possible_oc_ids = [oc_id for oc_id in state.parent.outcomes.keys() if oc_id >= 0] possible_oc_ids.sort() to_outcome = state.parent.outcomes[possible_oc_ids[0]] oc_connected_to_parent = [oc for oc in from_outcomes if is_outcome_connect_to_state(oc, parent_state.state_id)] oc_not_connected = [oc for oc in from_outcomes if not state.parent.get_transition_for_outcome(state, oc)] if all(oc in oc_connected_to_parent for oc in from_outcomes): logger.info("Remove transition {0} because all outcomes are connected to it.".format(sub_task_string)) for from_outcome in oc_connected_to_parent: transition = parent_state.get_transition_for_outcome(state, from_outcome) parent_state.remove(transition) elif oc_not_connected: logger.debug("Create transition {0} ... ".format(sub_task_string)) for from_outcome in from_outcomes: parent_state.add_transition(state.state_id, from_outcome.outcome_id, parent_state.state_id, to_outcome.outcome_id) else: if remove_transitions_if_target_is_the_same(from_outcomes): logger.info("Removed transitions origin from outcomes of selected state {0}" "because all point to the same target.".format(sub_task_string)) return add_transitions_from_selected_state_to_parent() logger.info("Will not create transition {0}: Not clear situation of connected transitions." "There will be no transitions to other states be touched.".format(sub_task_string)) return True
python
def add_transitions_from_selected_state_to_parent(): """ Generates the default success transition of a state to its parent success port :return: """ task_string = "create transition" sub_task_string = "to parent state" selected_state_m, msg = get_selected_single_state_model_and_check_for_its_parent() if selected_state_m is None: logger.warning("Can not {0} {1}: {2}".format(task_string, sub_task_string, msg)) return logger.debug("Check to {0} {1} ...".format(task_string, sub_task_string)) state = selected_state_m.state parent_state = state.parent # find all possible from outcomes from_outcomes = get_all_outcomes_except_of_abort_and_preempt(state) # find lowest valid outcome id possible_oc_ids = [oc_id for oc_id in state.parent.outcomes.keys() if oc_id >= 0] possible_oc_ids.sort() to_outcome = state.parent.outcomes[possible_oc_ids[0]] oc_connected_to_parent = [oc for oc in from_outcomes if is_outcome_connect_to_state(oc, parent_state.state_id)] oc_not_connected = [oc for oc in from_outcomes if not state.parent.get_transition_for_outcome(state, oc)] if all(oc in oc_connected_to_parent for oc in from_outcomes): logger.info("Remove transition {0} because all outcomes are connected to it.".format(sub_task_string)) for from_outcome in oc_connected_to_parent: transition = parent_state.get_transition_for_outcome(state, from_outcome) parent_state.remove(transition) elif oc_not_connected: logger.debug("Create transition {0} ... ".format(sub_task_string)) for from_outcome in from_outcomes: parent_state.add_transition(state.state_id, from_outcome.outcome_id, parent_state.state_id, to_outcome.outcome_id) else: if remove_transitions_if_target_is_the_same(from_outcomes): logger.info("Removed transitions origin from outcomes of selected state {0}" "because all point to the same target.".format(sub_task_string)) return add_transitions_from_selected_state_to_parent() logger.info("Will not create transition {0}: Not clear situation of connected transitions." "There will be no transitions to other states be touched.".format(sub_task_string)) return True
[ "def", "add_transitions_from_selected_state_to_parent", "(", ")", ":", "task_string", "=", "\"create transition\"", "sub_task_string", "=", "\"to parent state\"", "selected_state_m", ",", "msg", "=", "get_selected_single_state_model_and_check_for_its_parent", "(", ")", "if", "s...
Generates the default success transition of a state to its parent success port :return:
[ "Generates", "the", "default", "success", "transition", "of", "a", "state", "to", "its", "parent", "success", "port" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/utility.py#L61-L105
train
40,436
DLR-RM/RAFCON
source/rafcon/gui/helpers/utility.py
add_transitions_to_closest_sibling_state_from_selected_state
def add_transitions_to_closest_sibling_state_from_selected_state(): """ Generates the outcome transitions from outcomes with positive outcome_id to the closest next state :return: """ task_string = "create transition" sub_task_string = "to closest sibling state" selected_state_m, msg = get_selected_single_state_model_and_check_for_its_parent() if selected_state_m is None: logger.warning("Can not {0} {1}: {2}".format(task_string, sub_task_string, msg)) return logger.debug("Check to {0} {1} ...".format(task_string, sub_task_string)) state = selected_state_m.state parent_state = state.parent # find closest other state to connect to -> to_state closest_sibling_state_tuple = gui_helper_meta_data.get_closest_sibling_state(selected_state_m, 'outcome') if closest_sibling_state_tuple is None: logger.info("Can not {0} {1}: There is no other sibling state.".format(task_string, sub_task_string)) return distance, sibling_state_m = closest_sibling_state_tuple to_state = sibling_state_m.state # find all possible from outcomes from_outcomes = get_all_outcomes_except_of_abort_and_preempt(state) from_oc_not_connected = [oc for oc in from_outcomes if not state.parent.get_transition_for_outcome(state, oc)] # all ports not connected connect to next state income if from_oc_not_connected: logger.debug("Create transition {0} ...".format(sub_task_string)) for from_outcome in from_oc_not_connected: parent_state.add_transition(state.state_id, from_outcome.outcome_id, to_state.state_id, None) # no transitions are removed if not all connected to the same other state else: target = remove_transitions_if_target_is_the_same(from_outcomes) if target: target_state_id, _ = target if not target_state_id == to_state.state_id: logger.info("Removed transitions from outcomes {0} " "because all point to the same target.".format(sub_task_string.replace('closest ', ''))) add_transitions_to_closest_sibling_state_from_selected_state() else: logger.info("Removed transitions from outcomes {0} " "because all point to the same target.".format(sub_task_string)) return True logger.info("Will not {0} {1}: Not clear situation of connected transitions." "There will be no transitions to other states be touched.".format(task_string, sub_task_string)) return True
python
def add_transitions_to_closest_sibling_state_from_selected_state(): """ Generates the outcome transitions from outcomes with positive outcome_id to the closest next state :return: """ task_string = "create transition" sub_task_string = "to closest sibling state" selected_state_m, msg = get_selected_single_state_model_and_check_for_its_parent() if selected_state_m is None: logger.warning("Can not {0} {1}: {2}".format(task_string, sub_task_string, msg)) return logger.debug("Check to {0} {1} ...".format(task_string, sub_task_string)) state = selected_state_m.state parent_state = state.parent # find closest other state to connect to -> to_state closest_sibling_state_tuple = gui_helper_meta_data.get_closest_sibling_state(selected_state_m, 'outcome') if closest_sibling_state_tuple is None: logger.info("Can not {0} {1}: There is no other sibling state.".format(task_string, sub_task_string)) return distance, sibling_state_m = closest_sibling_state_tuple to_state = sibling_state_m.state # find all possible from outcomes from_outcomes = get_all_outcomes_except_of_abort_and_preempt(state) from_oc_not_connected = [oc for oc in from_outcomes if not state.parent.get_transition_for_outcome(state, oc)] # all ports not connected connect to next state income if from_oc_not_connected: logger.debug("Create transition {0} ...".format(sub_task_string)) for from_outcome in from_oc_not_connected: parent_state.add_transition(state.state_id, from_outcome.outcome_id, to_state.state_id, None) # no transitions are removed if not all connected to the same other state else: target = remove_transitions_if_target_is_the_same(from_outcomes) if target: target_state_id, _ = target if not target_state_id == to_state.state_id: logger.info("Removed transitions from outcomes {0} " "because all point to the same target.".format(sub_task_string.replace('closest ', ''))) add_transitions_to_closest_sibling_state_from_selected_state() else: logger.info("Removed transitions from outcomes {0} " "because all point to the same target.".format(sub_task_string)) return True logger.info("Will not {0} {1}: Not clear situation of connected transitions." "There will be no transitions to other states be touched.".format(task_string, sub_task_string)) return True
[ "def", "add_transitions_to_closest_sibling_state_from_selected_state", "(", ")", ":", "task_string", "=", "\"create transition\"", "sub_task_string", "=", "\"to closest sibling state\"", "selected_state_m", ",", "msg", "=", "get_selected_single_state_model_and_check_for_its_parent", ...
Generates the outcome transitions from outcomes with positive outcome_id to the closest next state :return:
[ "Generates", "the", "outcome", "transitions", "from", "outcomes", "with", "positive", "outcome_id", "to", "the", "closest", "next", "state" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/helpers/utility.py#L108-L156
train
40,437
openego/eTraGo
etrago/tools/plot.py
add_coordinates
def add_coordinates(network): """ Add coordinates to nodes based on provided geom Parameters ---------- network : PyPSA network container Returns ------- Altered PyPSA network container ready for plotting """ for idx, row in network.buses.iterrows(): wkt_geom = to_shape(row['geom']) network.buses.loc[idx, 'x'] = wkt_geom.x network.buses.loc[idx, 'y'] = wkt_geom.y return network
python
def add_coordinates(network): """ Add coordinates to nodes based on provided geom Parameters ---------- network : PyPSA network container Returns ------- Altered PyPSA network container ready for plotting """ for idx, row in network.buses.iterrows(): wkt_geom = to_shape(row['geom']) network.buses.loc[idx, 'x'] = wkt_geom.x network.buses.loc[idx, 'y'] = wkt_geom.y return network
[ "def", "add_coordinates", "(", "network", ")", ":", "for", "idx", ",", "row", "in", "network", ".", "buses", ".", "iterrows", "(", ")", ":", "wkt_geom", "=", "to_shape", "(", "row", "[", "'geom'", "]", ")", "network", ".", "buses", ".", "loc", "[", ...
Add coordinates to nodes based on provided geom Parameters ---------- network : PyPSA network container Returns ------- Altered PyPSA network container ready for plotting
[ "Add", "coordinates", "to", "nodes", "based", "on", "provided", "geom" ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/plot.py#L52-L69
train
40,438
openego/eTraGo
etrago/tools/plot.py
plot_residual_load
def plot_residual_load(network): """ Plots residual load summed of all exisiting buses. Parameters ---------- network : PyPSA network containter """ renewables = network.generators[ network.generators.carrier.isin(['wind_onshore', 'wind_offshore', 'solar', 'run_of_river', 'wind'])] renewables_t = network.generators.p_nom[renewables.index] * \ network.generators_t.p_max_pu[renewables.index].mul( network.snapshot_weightings, axis=0) load = network.loads_t.p_set.mul(network.snapshot_weightings, axis=0).\ sum(axis=1) all_renew = renewables_t.sum(axis=1) residual_load = load - all_renew plot = residual_load.plot( title = 'Residual load', drawstyle='steps', lw=2, color='red', legend=False) plot.set_ylabel("MW") # sorted curve sorted_residual_load = residual_load.sort_values( ascending=False).reset_index() plot1 = sorted_residual_load.plot( title='Sorted residual load', drawstyle='steps', lw=2, color='red', legend=False) plot1.set_ylabel("MW")
python
def plot_residual_load(network): """ Plots residual load summed of all exisiting buses. Parameters ---------- network : PyPSA network containter """ renewables = network.generators[ network.generators.carrier.isin(['wind_onshore', 'wind_offshore', 'solar', 'run_of_river', 'wind'])] renewables_t = network.generators.p_nom[renewables.index] * \ network.generators_t.p_max_pu[renewables.index].mul( network.snapshot_weightings, axis=0) load = network.loads_t.p_set.mul(network.snapshot_weightings, axis=0).\ sum(axis=1) all_renew = renewables_t.sum(axis=1) residual_load = load - all_renew plot = residual_load.plot( title = 'Residual load', drawstyle='steps', lw=2, color='red', legend=False) plot.set_ylabel("MW") # sorted curve sorted_residual_load = residual_load.sort_values( ascending=False).reset_index() plot1 = sorted_residual_load.plot( title='Sorted residual load', drawstyle='steps', lw=2, color='red', legend=False) plot1.set_ylabel("MW")
[ "def", "plot_residual_load", "(", "network", ")", ":", "renewables", "=", "network", ".", "generators", "[", "network", ".", "generators", ".", "carrier", ".", "isin", "(", "[", "'wind_onshore'", ",", "'wind_offshore'", ",", "'solar'", ",", "'run_of_river'", "...
Plots residual load summed of all exisiting buses. Parameters ---------- network : PyPSA network containter
[ "Plots", "residual", "load", "summed", "of", "all", "exisiting", "buses", "." ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/plot.py#L792-L827
train
40,439
openego/eTraGo
etrago/tools/plot.py
plot_stacked_gen
def plot_stacked_gen(network, bus=None, resolution='GW', filename=None): """ Plot stacked sum of generation grouped by carrier type Parameters ---------- network : PyPSA network container bus: string Plot all generators at one specific bus. If none, sum is calulated for all buses resolution: string Unit for y-axis. Can be either GW/MW/KW Returns ------- Plot """ if resolution == 'GW': reso_int = 1e3 elif resolution == 'MW': reso_int = 1 elif resolution == 'KW': reso_int = 0.001 # sum for all buses if bus is None: p_by_carrier = pd.concat([network.generators_t.p[network.generators [network.generators.control != 'Slack'].index], network.generators_t.p.mul( network.snapshot_weightings, axis=0) [network.generators[network.generators.control == 'Slack'].index] .iloc[:, 0].apply(lambda x: x if x > 0 else 0)], axis=1)\ .groupby(network.generators.carrier, axis=1).sum() load = network.loads_t.p.sum(axis=1) if hasattr(network, 'foreign_trade'): trade_sum = network.foreign_trade.sum(axis=1) p_by_carrier['imports'] = trade_sum[trade_sum > 0] p_by_carrier['imports'] = p_by_carrier['imports'].fillna(0) # sum for a single bus elif bus is not None: filtered_gens = network.generators[network.generators['bus'] == bus] p_by_carrier = network.generators_t.p.mul(network.snapshot_weightings, axis=0).groupby(filtered_gens.carrier, axis=1).abs().sum() filtered_load = network.loads[network.loads['bus'] == bus] load = network.loads_t.p.mul(network.snapshot_weightings, axis=0)\ [filtered_load.index] colors = coloring() # TODO: column reordering based on available columns fig, ax = plt.subplots(1, 1) fig.set_size_inches(12, 6) colors = [colors[col] for col in p_by_carrier.columns] if len(colors) == 1: colors = colors[0] (p_by_carrier / reso_int).plot(kind="area", ax=ax, linewidth=0, color=colors) (load / reso_int).plot(ax=ax, legend='load', lw=2, color='darkgrey', style='--') ax.legend(ncol=4, loc="upper left") ax.set_ylabel(resolution) ax.set_xlabel("") matplotlib.rcParams.update({'font.size': 22}) if filename is None: plt.show() else: plt.savefig(filename) plt.close()
python
def plot_stacked_gen(network, bus=None, resolution='GW', filename=None): """ Plot stacked sum of generation grouped by carrier type Parameters ---------- network : PyPSA network container bus: string Plot all generators at one specific bus. If none, sum is calulated for all buses resolution: string Unit for y-axis. Can be either GW/MW/KW Returns ------- Plot """ if resolution == 'GW': reso_int = 1e3 elif resolution == 'MW': reso_int = 1 elif resolution == 'KW': reso_int = 0.001 # sum for all buses if bus is None: p_by_carrier = pd.concat([network.generators_t.p[network.generators [network.generators.control != 'Slack'].index], network.generators_t.p.mul( network.snapshot_weightings, axis=0) [network.generators[network.generators.control == 'Slack'].index] .iloc[:, 0].apply(lambda x: x if x > 0 else 0)], axis=1)\ .groupby(network.generators.carrier, axis=1).sum() load = network.loads_t.p.sum(axis=1) if hasattr(network, 'foreign_trade'): trade_sum = network.foreign_trade.sum(axis=1) p_by_carrier['imports'] = trade_sum[trade_sum > 0] p_by_carrier['imports'] = p_by_carrier['imports'].fillna(0) # sum for a single bus elif bus is not None: filtered_gens = network.generators[network.generators['bus'] == bus] p_by_carrier = network.generators_t.p.mul(network.snapshot_weightings, axis=0).groupby(filtered_gens.carrier, axis=1).abs().sum() filtered_load = network.loads[network.loads['bus'] == bus] load = network.loads_t.p.mul(network.snapshot_weightings, axis=0)\ [filtered_load.index] colors = coloring() # TODO: column reordering based on available columns fig, ax = plt.subplots(1, 1) fig.set_size_inches(12, 6) colors = [colors[col] for col in p_by_carrier.columns] if len(colors) == 1: colors = colors[0] (p_by_carrier / reso_int).plot(kind="area", ax=ax, linewidth=0, color=colors) (load / reso_int).plot(ax=ax, legend='load', lw=2, color='darkgrey', style='--') ax.legend(ncol=4, loc="upper left") ax.set_ylabel(resolution) ax.set_xlabel("") matplotlib.rcParams.update({'font.size': 22}) if filename is None: plt.show() else: plt.savefig(filename) plt.close()
[ "def", "plot_stacked_gen", "(", "network", ",", "bus", "=", "None", ",", "resolution", "=", "'GW'", ",", "filename", "=", "None", ")", ":", "if", "resolution", "==", "'GW'", ":", "reso_int", "=", "1e3", "elif", "resolution", "==", "'MW'", ":", "reso_int"...
Plot stacked sum of generation grouped by carrier type Parameters ---------- network : PyPSA network container bus: string Plot all generators at one specific bus. If none, sum is calulated for all buses resolution: string Unit for y-axis. Can be either GW/MW/KW Returns ------- Plot
[ "Plot", "stacked", "sum", "of", "generation", "grouped", "by", "carrier", "type" ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/plot.py#L831-L908
train
40,440
openego/eTraGo
etrago/tools/plot.py
plot_gen_diff
def plot_gen_diff( networkA, networkB, leave_out_carriers=[ 'geothermal', 'oil', 'other_non_renewable', 'reservoir', 'waste']): """ Plot difference in generation between two networks grouped by carrier type Parameters ---------- networkA : PyPSA network container with switches networkB : PyPSA network container without switches leave_out_carriers : list of carriers to leave out (default to all small carriers) Returns ------- Plot """ def gen_by_c(network): gen = pd.concat([network.generators_t.p.mul( network.snapshot_weightings, axis=0)[network.generators [network.generators.control != 'Slack'].index], network.generators_t.p.mul( network.snapshot_weightings, axis=0)[network.generators [network. generators.control == 'Slack'].index] .iloc[:, 0].apply(lambda x: x if x > 0 else 0)], axis=1)\ .groupby(network.generators.carrier,axis=1).sum() return gen gen = gen_by_c(networkB) gen_switches = gen_by_c(networkA) diff = gen_switches - gen colors = coloring() diff.drop(leave_out_carriers, axis=1, inplace=True) colors = [colors[col] for col in diff.columns] plot = diff.plot(kind='line', color=colors, use_index=False) plot.legend(loc='upper left', ncol=5, prop={'size': 8}) x = [] for i in range(0, len(diff)): x.append(i) plt.xticks(x, x) plot.set_xlabel('Timesteps') plot.set_ylabel('Difference in Generation in MW') plot.set_title('Difference in Generation') plt.tight_layout()
python
def plot_gen_diff( networkA, networkB, leave_out_carriers=[ 'geothermal', 'oil', 'other_non_renewable', 'reservoir', 'waste']): """ Plot difference in generation between two networks grouped by carrier type Parameters ---------- networkA : PyPSA network container with switches networkB : PyPSA network container without switches leave_out_carriers : list of carriers to leave out (default to all small carriers) Returns ------- Plot """ def gen_by_c(network): gen = pd.concat([network.generators_t.p.mul( network.snapshot_weightings, axis=0)[network.generators [network.generators.control != 'Slack'].index], network.generators_t.p.mul( network.snapshot_weightings, axis=0)[network.generators [network. generators.control == 'Slack'].index] .iloc[:, 0].apply(lambda x: x if x > 0 else 0)], axis=1)\ .groupby(network.generators.carrier,axis=1).sum() return gen gen = gen_by_c(networkB) gen_switches = gen_by_c(networkA) diff = gen_switches - gen colors = coloring() diff.drop(leave_out_carriers, axis=1, inplace=True) colors = [colors[col] for col in diff.columns] plot = diff.plot(kind='line', color=colors, use_index=False) plot.legend(loc='upper left', ncol=5, prop={'size': 8}) x = [] for i in range(0, len(diff)): x.append(i) plt.xticks(x, x) plot.set_xlabel('Timesteps') plot.set_ylabel('Difference in Generation in MW') plot.set_title('Difference in Generation') plt.tight_layout()
[ "def", "plot_gen_diff", "(", "networkA", ",", "networkB", ",", "leave_out_carriers", "=", "[", "'geothermal'", ",", "'oil'", ",", "'other_non_renewable'", ",", "'reservoir'", ",", "'waste'", "]", ")", ":", "def", "gen_by_c", "(", "network", ")", ":", "gen", ...
Plot difference in generation between two networks grouped by carrier type Parameters ---------- networkA : PyPSA network container with switches networkB : PyPSA network container without switches leave_out_carriers : list of carriers to leave out (default to all small carriers) Returns ------- Plot
[ "Plot", "difference", "in", "generation", "between", "two", "networks", "grouped", "by", "carrier", "type" ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/plot.py#L911-L964
train
40,441
openego/eTraGo
etrago/tools/plot.py
plot_voltage
def plot_voltage(network, boundaries=[]): """ Plot voltage at buses as hexbin Parameters ---------- network : PyPSA network container boundaries: list of 2 values, setting the lower and upper bound of colorbar Returns ------- Plot """ x = np.array(network.buses['x']) y = np.array(network.buses['y']) alpha = np.array(network.buses_t.v_mag_pu.loc[network.snapshots[0]]) fig, ax = plt.subplots(1, 1) fig.set_size_inches(6, 4) cmap = plt.cm.jet if not boundaries: plt.hexbin(x, y, C=alpha, cmap=cmap, gridsize=100) cb = plt.colorbar() elif boundaries: v = np.linspace(boundaries[0], boundaries[1], 101) norm = matplotlib.colors.BoundaryNorm(v, cmap.N) plt.hexbin(x, y, C=alpha, cmap=cmap, gridsize=100, norm=norm) cb = plt.colorbar(boundaries=v, ticks=v[0:101:10], norm=norm) cb.set_clim(vmin=boundaries[0], vmax=boundaries[1]) cb.set_label('Voltage Magnitude per unit of v_nom') network.plot( ax=ax, line_widths=pd.Series(0.5, network.lines.index), bus_sizes=0) plt.show()
python
def plot_voltage(network, boundaries=[]): """ Plot voltage at buses as hexbin Parameters ---------- network : PyPSA network container boundaries: list of 2 values, setting the lower and upper bound of colorbar Returns ------- Plot """ x = np.array(network.buses['x']) y = np.array(network.buses['y']) alpha = np.array(network.buses_t.v_mag_pu.loc[network.snapshots[0]]) fig, ax = plt.subplots(1, 1) fig.set_size_inches(6, 4) cmap = plt.cm.jet if not boundaries: plt.hexbin(x, y, C=alpha, cmap=cmap, gridsize=100) cb = plt.colorbar() elif boundaries: v = np.linspace(boundaries[0], boundaries[1], 101) norm = matplotlib.colors.BoundaryNorm(v, cmap.N) plt.hexbin(x, y, C=alpha, cmap=cmap, gridsize=100, norm=norm) cb = plt.colorbar(boundaries=v, ticks=v[0:101:10], norm=norm) cb.set_clim(vmin=boundaries[0], vmax=boundaries[1]) cb.set_label('Voltage Magnitude per unit of v_nom') network.plot( ax=ax, line_widths=pd.Series(0.5, network.lines.index), bus_sizes=0) plt.show()
[ "def", "plot_voltage", "(", "network", ",", "boundaries", "=", "[", "]", ")", ":", "x", "=", "np", ".", "array", "(", "network", ".", "buses", "[", "'x'", "]", ")", "y", "=", "np", ".", "array", "(", "network", ".", "buses", "[", "'y'", "]", ")...
Plot voltage at buses as hexbin Parameters ---------- network : PyPSA network container boundaries: list of 2 values, setting the lower and upper bound of colorbar Returns ------- Plot
[ "Plot", "voltage", "at", "buses", "as", "hexbin" ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/plot.py#L967-L1003
train
40,442
openego/eTraGo
etrago/tools/plot.py
curtailment
def curtailment(network, carrier='solar', filename=None): """ Plot curtailment of selected carrier Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis carrier: str Plot curtailemt of this carrier filename: str or None Save figure in this direction Returns ------- Plot """ p_by_carrier = network.generators_t.p.groupby\ (network.generators.carrier, axis=1).sum() capacity = network.generators.groupby("carrier").sum().at[carrier, "p_nom"] p_available = network.generators_t.p_max_pu.multiply( network.generators["p_nom"]) p_available_by_carrier = p_available.groupby( network.generators.carrier, axis=1).sum() p_curtailed_by_carrier = p_available_by_carrier - p_by_carrier print(p_curtailed_by_carrier.sum()) p_df = pd.DataFrame({carrier + " available": p_available_by_carrier[carrier], carrier + " dispatched": p_by_carrier[carrier], carrier + " curtailed": p_curtailed_by_carrier[carrier]}) p_df[carrier + " capacity"] = capacity p_df[carrier + " curtailed"][p_df[carrier + " curtailed"] < 0.] = 0. fig, ax = plt.subplots(1, 1) fig.set_size_inches(12, 6) p_df[[carrier + " dispatched", carrier + " curtailed"] ].plot(kind="area", ax=ax, linewidth=3) p_df[[carrier + " available", carrier + " capacity"] ].plot(ax=ax, linewidth=3) ax.set_xlabel("") ax.set_ylabel("Power [MW]") ax.set_ylim([0, capacity * 1.1]) ax.legend() if filename is None: plt.show() else: plt.savefig(filename) plt.close()
python
def curtailment(network, carrier='solar', filename=None): """ Plot curtailment of selected carrier Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis carrier: str Plot curtailemt of this carrier filename: str or None Save figure in this direction Returns ------- Plot """ p_by_carrier = network.generators_t.p.groupby\ (network.generators.carrier, axis=1).sum() capacity = network.generators.groupby("carrier").sum().at[carrier, "p_nom"] p_available = network.generators_t.p_max_pu.multiply( network.generators["p_nom"]) p_available_by_carrier = p_available.groupby( network.generators.carrier, axis=1).sum() p_curtailed_by_carrier = p_available_by_carrier - p_by_carrier print(p_curtailed_by_carrier.sum()) p_df = pd.DataFrame({carrier + " available": p_available_by_carrier[carrier], carrier + " dispatched": p_by_carrier[carrier], carrier + " curtailed": p_curtailed_by_carrier[carrier]}) p_df[carrier + " capacity"] = capacity p_df[carrier + " curtailed"][p_df[carrier + " curtailed"] < 0.] = 0. fig, ax = plt.subplots(1, 1) fig.set_size_inches(12, 6) p_df[[carrier + " dispatched", carrier + " curtailed"] ].plot(kind="area", ax=ax, linewidth=3) p_df[[carrier + " available", carrier + " capacity"] ].plot(ax=ax, linewidth=3) ax.set_xlabel("") ax.set_ylabel("Power [MW]") ax.set_ylim([0, capacity * 1.1]) ax.legend() if filename is None: plt.show() else: plt.savefig(filename) plt.close()
[ "def", "curtailment", "(", "network", ",", "carrier", "=", "'solar'", ",", "filename", "=", "None", ")", ":", "p_by_carrier", "=", "network", ".", "generators_t", ".", "p", ".", "groupby", "(", "network", ".", "generators", ".", "carrier", ",", "axis", "...
Plot curtailment of selected carrier Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis carrier: str Plot curtailemt of this carrier filename: str or None Save figure in this direction Returns ------- Plot
[ "Plot", "curtailment", "of", "selected", "carrier" ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/plot.py#L1006-L1058
train
40,443
openego/eTraGo
etrago/tools/plot.py
storage_distribution
def storage_distribution(network, scaling=1, filename=None): """ Plot storage distribution as circles on grid nodes Displays storage size and distribution in network. Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis filename : str Specify filename If not given, figure will be show directly """ stores = network.storage_units storage_distribution = network.storage_units.p_nom_opt[stores.index]\ .groupby(network.storage_units.bus)\ .sum().reindex(network.buses.index, fill_value=0.) fig, ax = plt.subplots(1, 1) fig.set_size_inches(6, 6) msd_max = storage_distribution.max() msd_median = storage_distribution[storage_distribution != 0].median() msd_min = storage_distribution[storage_distribution > 1].min() if msd_max != 0: LabelVal = int(log10(msd_max)) else: LabelVal = 0 if LabelVal < 0: LabelUnit = 'kW' msd_max, msd_median, msd_min = msd_max * \ 1000, msd_median * 1000, msd_min * 1000 storage_distribution = storage_distribution * 1000 elif LabelVal < 3: LabelUnit = 'MW' else: LabelUnit = 'GW' msd_max, msd_median, msd_min = msd_max / \ 1000, msd_median / 1000, msd_min / 1000 storage_distribution = storage_distribution / 1000 if sum(storage_distribution) == 0: network.plot(bus_sizes=0, ax=ax, title="No storages") else: network.plot( bus_sizes=storage_distribution * scaling, ax=ax, line_widths=0.3, title="Storage distribution") # Here we create a legend: # we'll plot empty lists with the desired size and label for area in [msd_max, msd_median, msd_min]: plt.scatter([], [], c='white', s=area * scaling, label='= ' + str(round(area, 0)) + LabelUnit + ' ') plt.legend(scatterpoints=1, labelspacing=1, title='Storage size') if filename is None: plt.show() else: plt.savefig(filename) plt.close()
python
def storage_distribution(network, scaling=1, filename=None): """ Plot storage distribution as circles on grid nodes Displays storage size and distribution in network. Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis filename : str Specify filename If not given, figure will be show directly """ stores = network.storage_units storage_distribution = network.storage_units.p_nom_opt[stores.index]\ .groupby(network.storage_units.bus)\ .sum().reindex(network.buses.index, fill_value=0.) fig, ax = plt.subplots(1, 1) fig.set_size_inches(6, 6) msd_max = storage_distribution.max() msd_median = storage_distribution[storage_distribution != 0].median() msd_min = storage_distribution[storage_distribution > 1].min() if msd_max != 0: LabelVal = int(log10(msd_max)) else: LabelVal = 0 if LabelVal < 0: LabelUnit = 'kW' msd_max, msd_median, msd_min = msd_max * \ 1000, msd_median * 1000, msd_min * 1000 storage_distribution = storage_distribution * 1000 elif LabelVal < 3: LabelUnit = 'MW' else: LabelUnit = 'GW' msd_max, msd_median, msd_min = msd_max / \ 1000, msd_median / 1000, msd_min / 1000 storage_distribution = storage_distribution / 1000 if sum(storage_distribution) == 0: network.plot(bus_sizes=0, ax=ax, title="No storages") else: network.plot( bus_sizes=storage_distribution * scaling, ax=ax, line_widths=0.3, title="Storage distribution") # Here we create a legend: # we'll plot empty lists with the desired size and label for area in [msd_max, msd_median, msd_min]: plt.scatter([], [], c='white', s=area * scaling, label='= ' + str(round(area, 0)) + LabelUnit + ' ') plt.legend(scatterpoints=1, labelspacing=1, title='Storage size') if filename is None: plt.show() else: plt.savefig(filename) plt.close()
[ "def", "storage_distribution", "(", "network", ",", "scaling", "=", "1", ",", "filename", "=", "None", ")", ":", "stores", "=", "network", ".", "storage_units", "storage_distribution", "=", "network", ".", "storage_units", ".", "p_nom_opt", "[", "stores", ".",...
Plot storage distribution as circles on grid nodes Displays storage size and distribution in network. Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis filename : str Specify filename If not given, figure will be show directly
[ "Plot", "storage", "distribution", "as", "circles", "on", "grid", "nodes" ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/plot.py#L1061-L1125
train
40,444
DLR-RM/RAFCON
source/rafcon/gui/controllers/modification_history.py
ModificationHistoryTreeController.undo
def undo(self, key_value, modifier_mask): """Undo for selected state-machine if no state-source-editor is open and focused in states-editor-controller. :return: True if a undo was performed, False if focus on source-editor. :rtype: bool """ # TODO re-organize as request to controller which holds source-editor-view or any parent to it for key, tab in gui_singletons.main_window_controller.get_controller('states_editor_ctrl').tabs.items(): if tab['controller'].get_controller('source_ctrl') is not None and \ react_to_event(self.view, tab['controller'].get_controller('source_ctrl').view.textview, (key_value, modifier_mask)) or \ tab['controller'].get_controller('description_ctrl') is not None and \ react_to_event(self.view, tab['controller'].get_controller('description_ctrl').view.textview, (key_value, modifier_mask)): return False if self._selected_sm_model is not None: self._selected_sm_model.history.undo() return True else: logger.debug("Undo is not possible now as long as no state_machine is selected.")
python
def undo(self, key_value, modifier_mask): """Undo for selected state-machine if no state-source-editor is open and focused in states-editor-controller. :return: True if a undo was performed, False if focus on source-editor. :rtype: bool """ # TODO re-organize as request to controller which holds source-editor-view or any parent to it for key, tab in gui_singletons.main_window_controller.get_controller('states_editor_ctrl').tabs.items(): if tab['controller'].get_controller('source_ctrl') is not None and \ react_to_event(self.view, tab['controller'].get_controller('source_ctrl').view.textview, (key_value, modifier_mask)) or \ tab['controller'].get_controller('description_ctrl') is not None and \ react_to_event(self.view, tab['controller'].get_controller('description_ctrl').view.textview, (key_value, modifier_mask)): return False if self._selected_sm_model is not None: self._selected_sm_model.history.undo() return True else: logger.debug("Undo is not possible now as long as no state_machine is selected.")
[ "def", "undo", "(", "self", ",", "key_value", ",", "modifier_mask", ")", ":", "# TODO re-organize as request to controller which holds source-editor-view or any parent to it", "for", "key", ",", "tab", "in", "gui_singletons", ".", "main_window_controller", ".", "get_controlle...
Undo for selected state-machine if no state-source-editor is open and focused in states-editor-controller. :return: True if a undo was performed, False if focus on source-editor. :rtype: bool
[ "Undo", "for", "selected", "state", "-", "machine", "if", "no", "state", "-", "source", "-", "editor", "is", "open", "and", "focused", "in", "states", "-", "editor", "-", "controller", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/modification_history.py#L179-L198
train
40,445
Cog-Creators/Red-Lavalink
lavalink/rest_api.py
LoadResult.exception_message
def exception_message(self) -> Union[str, None]: """ On Lavalink V3, if there was an exception during a load or get tracks call this property will be populated with the error message. If there was no error this property will be ``None``. """ if self.has_error: exception_data = self._raw.get("exception", {}) return exception_data.get("message") return None
python
def exception_message(self) -> Union[str, None]: """ On Lavalink V3, if there was an exception during a load or get tracks call this property will be populated with the error message. If there was no error this property will be ``None``. """ if self.has_error: exception_data = self._raw.get("exception", {}) return exception_data.get("message") return None
[ "def", "exception_message", "(", "self", ")", "->", "Union", "[", "str", ",", "None", "]", ":", "if", "self", ".", "has_error", ":", "exception_data", "=", "self", ".", "_raw", ".", "get", "(", "\"exception\"", ",", "{", "}", ")", "return", "exception_...
On Lavalink V3, if there was an exception during a load or get tracks call this property will be populated with the error message. If there was no error this property will be ``None``.
[ "On", "Lavalink", "V3", "if", "there", "was", "an", "exception", "during", "a", "load", "or", "get", "tracks", "call", "this", "property", "will", "be", "populated", "with", "the", "error", "message", ".", "If", "there", "was", "no", "error", "this", "pr...
5b3fc6eb31ee5db8bd2b633a523cf69749957111
https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/rest_api.py#L102-L111
train
40,446
Cog-Creators/Red-Lavalink
lavalink/rest_api.py
RESTClient.load_tracks
async def load_tracks(self, query) -> LoadResult: """ Executes a loadtracks request. Only works on Lavalink V3. Parameters ---------- query : str Returns ------- LoadResult """ self.__check_node_ready() url = self._uri + quote(str(query)) data = await self._get(url) if isinstance(data, dict): return LoadResult(data) elif isinstance(data, list): modified_data = { "loadType": LoadType.V2_COMPAT, "tracks": data } return LoadResult(modified_data)
python
async def load_tracks(self, query) -> LoadResult: """ Executes a loadtracks request. Only works on Lavalink V3. Parameters ---------- query : str Returns ------- LoadResult """ self.__check_node_ready() url = self._uri + quote(str(query)) data = await self._get(url) if isinstance(data, dict): return LoadResult(data) elif isinstance(data, list): modified_data = { "loadType": LoadType.V2_COMPAT, "tracks": data } return LoadResult(modified_data)
[ "async", "def", "load_tracks", "(", "self", ",", "query", ")", "->", "LoadResult", ":", "self", ".", "__check_node_ready", "(", ")", "url", "=", "self", ".", "_uri", "+", "quote", "(", "str", "(", "query", ")", ")", "data", "=", "await", "self", ".",...
Executes a loadtracks request. Only works on Lavalink V3. Parameters ---------- query : str Returns ------- LoadResult
[ "Executes", "a", "loadtracks", "request", ".", "Only", "works", "on", "Lavalink", "V3", "." ]
5b3fc6eb31ee5db8bd2b633a523cf69749957111
https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/rest_api.py#L164-L188
train
40,447
Cog-Creators/Red-Lavalink
lavalink/rest_api.py
RESTClient.get_tracks
async def get_tracks(self, query) -> Tuple[Track, ...]: """ Gets tracks from lavalink. Parameters ---------- query : str Returns ------- Tuple[Track, ...] """ if not self._warned: log.warn("get_tracks() is now deprecated. Please switch to using load_tracks().") self._warned = True result = await self.load_tracks(query) return result.tracks
python
async def get_tracks(self, query) -> Tuple[Track, ...]: """ Gets tracks from lavalink. Parameters ---------- query : str Returns ------- Tuple[Track, ...] """ if not self._warned: log.warn("get_tracks() is now deprecated. Please switch to using load_tracks().") self._warned = True result = await self.load_tracks(query) return result.tracks
[ "async", "def", "get_tracks", "(", "self", ",", "query", ")", "->", "Tuple", "[", "Track", ",", "...", "]", ":", "if", "not", "self", ".", "_warned", ":", "log", ".", "warn", "(", "\"get_tracks() is now deprecated. Please switch to using load_tracks().\"", ")", ...
Gets tracks from lavalink. Parameters ---------- query : str Returns ------- Tuple[Track, ...]
[ "Gets", "tracks", "from", "lavalink", "." ]
5b3fc6eb31ee5db8bd2b633a523cf69749957111
https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/rest_api.py#L190-L206
train
40,448
DLR-RM/RAFCON
source/rafcon/utils/installation.py
get_data_files_tuple
def get_data_files_tuple(*rel_path, **kwargs): """Return a tuple which can be used for setup.py's data_files :param tuple path: List of path elements pointing to a file or a directory of files :param dict kwargs: Set path_to_file to True is `path` points to a file :return: tuple of install directory and list of source files :rtype: tuple(str, [str]) """ rel_path = os.path.join(*rel_path) target_path = os.path.join("share", *rel_path.split(os.sep)[1:]) # remove source/ (package_dir) if "path_to_file" in kwargs and kwargs["path_to_file"]: source_files = [rel_path] target_path = os.path.dirname(target_path) else: source_files = [os.path.join(rel_path, filename) for filename in os.listdir(rel_path)] return target_path, source_files
python
def get_data_files_tuple(*rel_path, **kwargs): """Return a tuple which can be used for setup.py's data_files :param tuple path: List of path elements pointing to a file or a directory of files :param dict kwargs: Set path_to_file to True is `path` points to a file :return: tuple of install directory and list of source files :rtype: tuple(str, [str]) """ rel_path = os.path.join(*rel_path) target_path = os.path.join("share", *rel_path.split(os.sep)[1:]) # remove source/ (package_dir) if "path_to_file" in kwargs and kwargs["path_to_file"]: source_files = [rel_path] target_path = os.path.dirname(target_path) else: source_files = [os.path.join(rel_path, filename) for filename in os.listdir(rel_path)] return target_path, source_files
[ "def", "get_data_files_tuple", "(", "*", "rel_path", ",", "*", "*", "kwargs", ")", ":", "rel_path", "=", "os", ".", "path", ".", "join", "(", "*", "rel_path", ")", "target_path", "=", "os", ".", "path", ".", "join", "(", "\"share\"", ",", "*", "rel_p...
Return a tuple which can be used for setup.py's data_files :param tuple path: List of path elements pointing to a file or a directory of files :param dict kwargs: Set path_to_file to True is `path` points to a file :return: tuple of install directory and list of source files :rtype: tuple(str, [str])
[ "Return", "a", "tuple", "which", "can", "be", "used", "for", "setup", ".", "py", "s", "data_files" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/installation.py#L210-L225
train
40,449
DLR-RM/RAFCON
source/rafcon/utils/installation.py
get_data_files_recursively
def get_data_files_recursively(*rel_root_path, **kwargs): """ Adds all files of the specified path to a data_files compatible list :param tuple rel_root_path: List of path elements pointing to a directory of files :return: list of tuples of install directory and list of source files :rtype: list(tuple(str, [str])) """ result_list = list() rel_root_dir = os.path.join(*rel_root_path) share_target_root = os.path.join("share", kwargs.get("share_target_root", "rafcon")) distutils.log.debug("recursively generating data files for folder '{}' ...".format( rel_root_dir)) for dir_, _, files in os.walk(rel_root_dir): relative_directory = os.path.relpath(dir_, rel_root_dir) file_list = list() for fileName in files: rel_file_path = os.path.join(relative_directory, fileName) abs_file_path = os.path.join(rel_root_dir, rel_file_path) file_list.append(abs_file_path) if len(file_list) > 0: # this is a valid path in ~/.local folder: e.g. share/rafcon/libraries/generic/wait target_path = os.path.join(share_target_root, relative_directory) result_list.append((target_path, file_list)) return result_list
python
def get_data_files_recursively(*rel_root_path, **kwargs): """ Adds all files of the specified path to a data_files compatible list :param tuple rel_root_path: List of path elements pointing to a directory of files :return: list of tuples of install directory and list of source files :rtype: list(tuple(str, [str])) """ result_list = list() rel_root_dir = os.path.join(*rel_root_path) share_target_root = os.path.join("share", kwargs.get("share_target_root", "rafcon")) distutils.log.debug("recursively generating data files for folder '{}' ...".format( rel_root_dir)) for dir_, _, files in os.walk(rel_root_dir): relative_directory = os.path.relpath(dir_, rel_root_dir) file_list = list() for fileName in files: rel_file_path = os.path.join(relative_directory, fileName) abs_file_path = os.path.join(rel_root_dir, rel_file_path) file_list.append(abs_file_path) if len(file_list) > 0: # this is a valid path in ~/.local folder: e.g. share/rafcon/libraries/generic/wait target_path = os.path.join(share_target_root, relative_directory) result_list.append((target_path, file_list)) return result_list
[ "def", "get_data_files_recursively", "(", "*", "rel_root_path", ",", "*", "*", "kwargs", ")", ":", "result_list", "=", "list", "(", ")", "rel_root_dir", "=", "os", ".", "path", ".", "join", "(", "*", "rel_root_path", ")", "share_target_root", "=", "os", "....
Adds all files of the specified path to a data_files compatible list :param tuple rel_root_path: List of path elements pointing to a directory of files :return: list of tuples of install directory and list of source files :rtype: list(tuple(str, [str]))
[ "Adds", "all", "files", "of", "the", "specified", "path", "to", "a", "data_files", "compatible", "list" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/installation.py#L228-L252
train
40,450
DLR-RM/RAFCON
source/rafcon/utils/installation.py
generate_data_files
def generate_data_files(): """ Generate the data_files list used in the setup function :return: list of tuples of install directory and list of source files :rtype: list(tuple(str, [str])) """ assets_folder = path.join('source', 'rafcon', 'gui', 'assets') share_folder = path.join(assets_folder, 'share') themes_folder = path.join(share_folder, 'themes', 'RAFCON') examples_folder = path.join('share', 'examples') libraries_folder = path.join('share', 'libraries') gui_data_files = [ get_data_files_tuple(assets_folder, 'splashscreens'), get_data_files_tuple(assets_folder, 'fonts', 'FontAwesome'), get_data_files_tuple(assets_folder, 'fonts', 'Source Sans Pro'), get_data_files_tuple(themes_folder, 'gtk-3.0', 'gtk.css', path_to_file=True), get_data_files_tuple(themes_folder, 'gtk-3.0', 'gtk-dark.css', path_to_file=True), get_data_files_tuple(themes_folder, 'assets'), get_data_files_tuple(themes_folder, 'sass'), get_data_files_tuple(themes_folder, 'gtk-sourceview'), get_data_files_tuple(themes_folder, 'colors.json', path_to_file=True), get_data_files_tuple(themes_folder, 'colors-dark.json', path_to_file=True) ] # print("gui_data_files", gui_data_files) icon_data_files = get_data_files_recursively(path.join(share_folder, 'icons'), share_target_root="icons") # print("icon_data_files", icon_data_files) locale_data_files = create_mo_files() # example tuple # locale_data_files = [('share/rafcon/locale/de/LC_MESSAGES', ['source/rafcon/locale/de/LC_MESSAGES/rafcon.mo'])] # print("locale_data_files", locale_data_files) version_data_file = [("./", ["VERSION"])] desktop_data_file = [("share/applications", [path.join('share', 'applications', 'de.dlr.rm.RAFCON.desktop')])] examples_data_files = get_data_files_recursively(examples_folder, share_target_root=path.join("rafcon", "examples")) libraries_data_files = get_data_files_recursively(libraries_folder, share_target_root=path.join("rafcon", "libraries")) generated_data_files = gui_data_files + icon_data_files + locale_data_files + version_data_file + \ desktop_data_file + examples_data_files + libraries_data_files # for elem in generated_data_files: # print(elem) return generated_data_files
python
def generate_data_files(): """ Generate the data_files list used in the setup function :return: list of tuples of install directory and list of source files :rtype: list(tuple(str, [str])) """ assets_folder = path.join('source', 'rafcon', 'gui', 'assets') share_folder = path.join(assets_folder, 'share') themes_folder = path.join(share_folder, 'themes', 'RAFCON') examples_folder = path.join('share', 'examples') libraries_folder = path.join('share', 'libraries') gui_data_files = [ get_data_files_tuple(assets_folder, 'splashscreens'), get_data_files_tuple(assets_folder, 'fonts', 'FontAwesome'), get_data_files_tuple(assets_folder, 'fonts', 'Source Sans Pro'), get_data_files_tuple(themes_folder, 'gtk-3.0', 'gtk.css', path_to_file=True), get_data_files_tuple(themes_folder, 'gtk-3.0', 'gtk-dark.css', path_to_file=True), get_data_files_tuple(themes_folder, 'assets'), get_data_files_tuple(themes_folder, 'sass'), get_data_files_tuple(themes_folder, 'gtk-sourceview'), get_data_files_tuple(themes_folder, 'colors.json', path_to_file=True), get_data_files_tuple(themes_folder, 'colors-dark.json', path_to_file=True) ] # print("gui_data_files", gui_data_files) icon_data_files = get_data_files_recursively(path.join(share_folder, 'icons'), share_target_root="icons") # print("icon_data_files", icon_data_files) locale_data_files = create_mo_files() # example tuple # locale_data_files = [('share/rafcon/locale/de/LC_MESSAGES', ['source/rafcon/locale/de/LC_MESSAGES/rafcon.mo'])] # print("locale_data_files", locale_data_files) version_data_file = [("./", ["VERSION"])] desktop_data_file = [("share/applications", [path.join('share', 'applications', 'de.dlr.rm.RAFCON.desktop')])] examples_data_files = get_data_files_recursively(examples_folder, share_target_root=path.join("rafcon", "examples")) libraries_data_files = get_data_files_recursively(libraries_folder, share_target_root=path.join("rafcon", "libraries")) generated_data_files = gui_data_files + icon_data_files + locale_data_files + version_data_file + \ desktop_data_file + examples_data_files + libraries_data_files # for elem in generated_data_files: # print(elem) return generated_data_files
[ "def", "generate_data_files", "(", ")", ":", "assets_folder", "=", "path", ".", "join", "(", "'source'", ",", "'rafcon'", ",", "'gui'", ",", "'assets'", ")", "share_folder", "=", "path", ".", "join", "(", "assets_folder", ",", "'share'", ")", "themes_folder"...
Generate the data_files list used in the setup function :return: list of tuples of install directory and list of source files :rtype: list(tuple(str, [str]))
[ "Generate", "the", "data_files", "list", "used", "in", "the", "setup", "function" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/utils/installation.py#L255-L299
train
40,451
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/tools.py
ToolChain.handle
def handle(self, event): """ Handle the event by calling each tool until the event is handled or grabbed. If a tool is returning True on a button press event, the motion and button release events are also passed to this """ # Allow to handle a subset of events while having a grabbed tool (between a button press & release event) suppressed_grabbed_tool = None if event.type in (Gdk.EventType.SCROLL, Gdk.EventType.KEY_PRESS, Gdk.EventType.KEY_RELEASE): suppressed_grabbed_tool = self._grabbed_tool self._grabbed_tool = None rt = super(ToolChain, self).handle(event) if suppressed_grabbed_tool: self._grabbed_tool = suppressed_grabbed_tool return rt
python
def handle(self, event): """ Handle the event by calling each tool until the event is handled or grabbed. If a tool is returning True on a button press event, the motion and button release events are also passed to this """ # Allow to handle a subset of events while having a grabbed tool (between a button press & release event) suppressed_grabbed_tool = None if event.type in (Gdk.EventType.SCROLL, Gdk.EventType.KEY_PRESS, Gdk.EventType.KEY_RELEASE): suppressed_grabbed_tool = self._grabbed_tool self._grabbed_tool = None rt = super(ToolChain, self).handle(event) if suppressed_grabbed_tool: self._grabbed_tool = suppressed_grabbed_tool return rt
[ "def", "handle", "(", "self", ",", "event", ")", ":", "# Allow to handle a subset of events while having a grabbed tool (between a button press & release event)", "suppressed_grabbed_tool", "=", "None", "if", "event", ".", "type", "in", "(", "Gdk", ".", "EventType", ".", ...
Handle the event by calling each tool until the event is handled or grabbed. If a tool is returning True on a button press event, the motion and button release events are also passed to this
[ "Handle", "the", "event", "by", "calling", "each", "tool", "until", "the", "event", "is", "handled", "or", "grabbed", ".", "If", "a", "tool", "is", "returning", "True", "on", "a", "button", "press", "event", "the", "motion", "and", "button", "release", "...
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/tools.py#L46-L64
train
40,452
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/tools.py
MoveItemTool.on_button_release
def on_button_release(self, event): """Write back changes If one or more items have been moved, the new position are stored in the corresponding meta data and a signal notifying the change is emitted. :param event: The button event """ affected_models = {} for inmotion in self._movable_items: inmotion.move((event.x, event.y)) rel_pos = gap_helper.calc_rel_pos_to_parent(self.view.canvas, inmotion.item, inmotion.item.handles()[NW]) if isinstance(inmotion.item, StateView): state_v = inmotion.item state_m = state_v.model self.view.canvas.request_update(state_v) if state_m.get_meta_data_editor()['rel_pos'] != rel_pos: state_m.set_meta_data_editor('rel_pos', rel_pos) affected_models[state_m] = ("position", True, state_v) elif isinstance(inmotion.item, NameView): state_v = inmotion.item state_m = self.view.canvas.get_parent(state_v).model self.view.canvas.request_update(state_v) if state_m.get_meta_data_editor()['name']['rel_pos'] != rel_pos: state_m.set_meta_data_editor('name.rel_pos', rel_pos) affected_models[state_m] = ("name_position", False, state_v) elif isinstance(inmotion.item, TransitionView): transition_v = inmotion.item transition_m = transition_v.model self.view.canvas.request_update(transition_v) current_waypoints = gap_helper.get_relative_positions_of_waypoints(transition_v) old_waypoints = transition_m.get_meta_data_editor()['waypoints'] if current_waypoints != old_waypoints: transition_m.set_meta_data_editor('waypoints', current_waypoints) affected_models[transition_m] = ("waypoints", False, transition_v) if len(affected_models) == 1: model = next(iter(affected_models)) change, affects_children, view = affected_models[model] self.view.graphical_editor.emit('meta_data_changed', model, change, affects_children) elif len(affected_models) > 1: # if more than one item has been moved, we need to call the meta_data_changed signal on a common parent common_parents = None for change, affects_children, view in affected_models.values(): parents_of_view = set(self.view.canvas.get_ancestors(view)) if common_parents is None: common_parents = parents_of_view else: common_parents = common_parents.intersection(parents_of_view) assert len(common_parents) > 0, "The selected elements do not have common parent element" for state_v in common_parents: # Find most nested state_v children_of_state_v = self.view.canvas.get_all_children(state_v) if any(common_parent in children_of_state_v for common_parent in common_parents): continue self.view.graphical_editor.emit('meta_data_changed', state_v.model, "positions", True) break if not affected_models and self._old_selection is not None: # The selection is handled differently depending on whether states were moved or not # If no move operation was performed, we reset the selection to that is was before the button-press event # and let the state machine selection handle the selection self.view.unselect_all() self.view.select_item(self._old_selection) self.view.handle_new_selection(self._item) self._move_name_v = False self._old_selection = None return super(MoveItemTool, self).on_button_release(event)
python
def on_button_release(self, event): """Write back changes If one or more items have been moved, the new position are stored in the corresponding meta data and a signal notifying the change is emitted. :param event: The button event """ affected_models = {} for inmotion in self._movable_items: inmotion.move((event.x, event.y)) rel_pos = gap_helper.calc_rel_pos_to_parent(self.view.canvas, inmotion.item, inmotion.item.handles()[NW]) if isinstance(inmotion.item, StateView): state_v = inmotion.item state_m = state_v.model self.view.canvas.request_update(state_v) if state_m.get_meta_data_editor()['rel_pos'] != rel_pos: state_m.set_meta_data_editor('rel_pos', rel_pos) affected_models[state_m] = ("position", True, state_v) elif isinstance(inmotion.item, NameView): state_v = inmotion.item state_m = self.view.canvas.get_parent(state_v).model self.view.canvas.request_update(state_v) if state_m.get_meta_data_editor()['name']['rel_pos'] != rel_pos: state_m.set_meta_data_editor('name.rel_pos', rel_pos) affected_models[state_m] = ("name_position", False, state_v) elif isinstance(inmotion.item, TransitionView): transition_v = inmotion.item transition_m = transition_v.model self.view.canvas.request_update(transition_v) current_waypoints = gap_helper.get_relative_positions_of_waypoints(transition_v) old_waypoints = transition_m.get_meta_data_editor()['waypoints'] if current_waypoints != old_waypoints: transition_m.set_meta_data_editor('waypoints', current_waypoints) affected_models[transition_m] = ("waypoints", False, transition_v) if len(affected_models) == 1: model = next(iter(affected_models)) change, affects_children, view = affected_models[model] self.view.graphical_editor.emit('meta_data_changed', model, change, affects_children) elif len(affected_models) > 1: # if more than one item has been moved, we need to call the meta_data_changed signal on a common parent common_parents = None for change, affects_children, view in affected_models.values(): parents_of_view = set(self.view.canvas.get_ancestors(view)) if common_parents is None: common_parents = parents_of_view else: common_parents = common_parents.intersection(parents_of_view) assert len(common_parents) > 0, "The selected elements do not have common parent element" for state_v in common_parents: # Find most nested state_v children_of_state_v = self.view.canvas.get_all_children(state_v) if any(common_parent in children_of_state_v for common_parent in common_parents): continue self.view.graphical_editor.emit('meta_data_changed', state_v.model, "positions", True) break if not affected_models and self._old_selection is not None: # The selection is handled differently depending on whether states were moved or not # If no move operation was performed, we reset the selection to that is was before the button-press event # and let the state machine selection handle the selection self.view.unselect_all() self.view.select_item(self._old_selection) self.view.handle_new_selection(self._item) self._move_name_v = False self._old_selection = None return super(MoveItemTool, self).on_button_release(event)
[ "def", "on_button_release", "(", "self", ",", "event", ")", ":", "affected_models", "=", "{", "}", "for", "inmotion", "in", "self", ".", "_movable_items", ":", "inmotion", ".", "move", "(", "(", "event", ".", "x", ",", "event", ".", "y", ")", ")", "r...
Write back changes If one or more items have been moved, the new position are stored in the corresponding meta data and a signal notifying the change is emitted. :param event: The button event
[ "Write", "back", "changes" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/tools.py#L178-L248
train
40,453
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/tools.py
HoverItemTool._filter_library_state
def _filter_library_state(self, items): """Filters out child elements of library state when they cannot be hovered Checks if hovered item is within a LibraryState * if not, the list is returned unfiltered * if so, STATE_SELECTION_INSIDE_LIBRARY_STATE_ENABLED is checked * if enabled, the library is selected (instead of the state copy) * if not, the upper most library is selected :param list items: Sorted list of items beneath the cursor :return: filtered items :rtype: list """ if not items: return items top_most_item = items[0] # If the hovered item is e.g. a connection, we need to get the parental state top_most_state_v = top_most_item if isinstance(top_most_item, StateView) else top_most_item.parent state = top_most_state_v.model.state global_gui_config = gui_helper_state_machine.global_gui_config if global_gui_config.get_config_value('STATE_SELECTION_INSIDE_LIBRARY_STATE_ENABLED'): # select the library state instead of the library_root_state because it is hidden if state.is_root_state_of_library: new_topmost_item = self.view.canvas.get_view_for_core_element(state.parent) return self.dismiss_upper_items(items, new_topmost_item) return items else: # Find state_copy of uppermost LibraryState library_root_state = state.get_uppermost_library_root_state() # If the hovered element is a child of a library, make the library the hovered_item if library_root_state: library_state = library_root_state.parent library_state_v = self.view.canvas.get_view_for_core_element(library_state) return self.dismiss_upper_items(items, library_state_v) return items
python
def _filter_library_state(self, items): """Filters out child elements of library state when they cannot be hovered Checks if hovered item is within a LibraryState * if not, the list is returned unfiltered * if so, STATE_SELECTION_INSIDE_LIBRARY_STATE_ENABLED is checked * if enabled, the library is selected (instead of the state copy) * if not, the upper most library is selected :param list items: Sorted list of items beneath the cursor :return: filtered items :rtype: list """ if not items: return items top_most_item = items[0] # If the hovered item is e.g. a connection, we need to get the parental state top_most_state_v = top_most_item if isinstance(top_most_item, StateView) else top_most_item.parent state = top_most_state_v.model.state global_gui_config = gui_helper_state_machine.global_gui_config if global_gui_config.get_config_value('STATE_SELECTION_INSIDE_LIBRARY_STATE_ENABLED'): # select the library state instead of the library_root_state because it is hidden if state.is_root_state_of_library: new_topmost_item = self.view.canvas.get_view_for_core_element(state.parent) return self.dismiss_upper_items(items, new_topmost_item) return items else: # Find state_copy of uppermost LibraryState library_root_state = state.get_uppermost_library_root_state() # If the hovered element is a child of a library, make the library the hovered_item if library_root_state: library_state = library_root_state.parent library_state_v = self.view.canvas.get_view_for_core_element(library_state) return self.dismiss_upper_items(items, library_state_v) return items
[ "def", "_filter_library_state", "(", "self", ",", "items", ")", ":", "if", "not", "items", ":", "return", "items", "top_most_item", "=", "items", "[", "0", "]", "# If the hovered item is e.g. a connection, we need to get the parental state", "top_most_state_v", "=", "to...
Filters out child elements of library state when they cannot be hovered Checks if hovered item is within a LibraryState * if not, the list is returned unfiltered * if so, STATE_SELECTION_INSIDE_LIBRARY_STATE_ENABLED is checked * if enabled, the library is selected (instead of the state copy) * if not, the upper most library is selected :param list items: Sorted list of items beneath the cursor :return: filtered items :rtype: list
[ "Filters", "out", "child", "elements", "of", "library", "state", "when", "they", "cannot", "be", "hovered" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/tools.py#L263-L300
train
40,454
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/tools.py
HoverItemTool._filter_hovered_items
def _filter_hovered_items(self, items, event): """Filters out items that cannot be hovered :param list items: Sorted list of items beneath the cursor :param Gtk.Event event: Motion event :return: filtered items :rtype: list """ items = self._filter_library_state(items) if not items: return items top_most_item = items[0] second_top_most_item = items[1] if len(items) > 1 else None # States/Names take precedence over connections if the connections are on the same hierarchy and if there is # a port beneath the cursor first_state_v = next(filter(lambda item: isinstance(item, (NameView, StateView)), items)) first_state_v = first_state_v.parent if isinstance(first_state_v, NameView) else first_state_v if first_state_v: # There can be several connections above the state/name skip those and find the first non-connection-item for item in items: if isinstance(item, ConnectionView): # connection is on the same hierarchy level as the state/name, thus we dismiss it if self.view.canvas.get_parent(top_most_item) is not first_state_v: continue break # Connections are only dismissed, if there is a port beneath the cursor. Search for ports here: port_beneath_cursor = False state_ports = first_state_v.get_all_ports() position = self.view.get_matrix_v2i(first_state_v).transform_point(event.x, event.y) i2v_matrix = self.view.get_matrix_i2v(first_state_v) for port_v in state_ports: item_distance = port_v.port.glue(position)[1] view_distance = i2v_matrix.transform_distance(item_distance, 0)[0] if view_distance == 0: port_beneath_cursor = True break if port_beneath_cursor: items = self.dismiss_upper_items(items, item) top_most_item = items[0] second_top_most_item = items[1] if len(items) > 1 else None # NameView can only be hovered if it or its parent state is selected if isinstance(top_most_item, NameView): state_v = second_top_most_item # second item in the list must be the parent state of the NameView if state_v not in self.view.selected_items and top_most_item not in self.view.selected_items: items = items[1:] return items
python
def _filter_hovered_items(self, items, event): """Filters out items that cannot be hovered :param list items: Sorted list of items beneath the cursor :param Gtk.Event event: Motion event :return: filtered items :rtype: list """ items = self._filter_library_state(items) if not items: return items top_most_item = items[0] second_top_most_item = items[1] if len(items) > 1 else None # States/Names take precedence over connections if the connections are on the same hierarchy and if there is # a port beneath the cursor first_state_v = next(filter(lambda item: isinstance(item, (NameView, StateView)), items)) first_state_v = first_state_v.parent if isinstance(first_state_v, NameView) else first_state_v if first_state_v: # There can be several connections above the state/name skip those and find the first non-connection-item for item in items: if isinstance(item, ConnectionView): # connection is on the same hierarchy level as the state/name, thus we dismiss it if self.view.canvas.get_parent(top_most_item) is not first_state_v: continue break # Connections are only dismissed, if there is a port beneath the cursor. Search for ports here: port_beneath_cursor = False state_ports = first_state_v.get_all_ports() position = self.view.get_matrix_v2i(first_state_v).transform_point(event.x, event.y) i2v_matrix = self.view.get_matrix_i2v(first_state_v) for port_v in state_ports: item_distance = port_v.port.glue(position)[1] view_distance = i2v_matrix.transform_distance(item_distance, 0)[0] if view_distance == 0: port_beneath_cursor = True break if port_beneath_cursor: items = self.dismiss_upper_items(items, item) top_most_item = items[0] second_top_most_item = items[1] if len(items) > 1 else None # NameView can only be hovered if it or its parent state is selected if isinstance(top_most_item, NameView): state_v = second_top_most_item # second item in the list must be the parent state of the NameView if state_v not in self.view.selected_items and top_most_item not in self.view.selected_items: items = items[1:] return items
[ "def", "_filter_hovered_items", "(", "self", ",", "items", ",", "event", ")", ":", "items", "=", "self", ".", "_filter_library_state", "(", "items", ")", "if", "not", "items", ":", "return", "items", "top_most_item", "=", "items", "[", "0", "]", "second_to...
Filters out items that cannot be hovered :param list items: Sorted list of items beneath the cursor :param Gtk.Event event: Motion event :return: filtered items :rtype: list
[ "Filters", "out", "items", "that", "cannot", "be", "hovered" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/tools.py#L302-L352
train
40,455
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/tools.py
MultiSelectionTool.on_button_release
def on_button_release(self, event): """Select or deselect rubber banded groups of items The selection of elements is prior and never items are selected or deselected at the same time. """ self.queue_draw(self.view) x0, y0, x1, y1 = self.x0, self.y0, self.x1, self.y1 rectangle = (min(x0, x1), min(y0, y1), abs(x1 - x0), abs(y1 - y0)) selected_items = self.view.get_items_in_rectangle(rectangle, intersect=False) self.view.handle_new_selection(selected_items) return True
python
def on_button_release(self, event): """Select or deselect rubber banded groups of items The selection of elements is prior and never items are selected or deselected at the same time. """ self.queue_draw(self.view) x0, y0, x1, y1 = self.x0, self.y0, self.x1, self.y1 rectangle = (min(x0, x1), min(y0, y1), abs(x1 - x0), abs(y1 - y0)) selected_items = self.view.get_items_in_rectangle(rectangle, intersect=False) self.view.handle_new_selection(selected_items) return True
[ "def", "on_button_release", "(", "self", ",", "event", ")", ":", "self", ".", "queue_draw", "(", "self", ".", "view", ")", "x0", ",", "y0", ",", "x1", ",", "y1", "=", "self", ".", "x0", ",", "self", ".", "y0", ",", "self", ".", "x1", ",", "self...
Select or deselect rubber banded groups of items The selection of elements is prior and never items are selected or deselected at the same time.
[ "Select", "or", "deselect", "rubber", "banded", "groups", "of", "items" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/tools.py#L453-L464
train
40,456
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/tools.py
ConnectionTool._set_motion_handle
def _set_motion_handle(self, event): """Sets motion handle to currently grabbed handle """ item = self.grabbed_item handle = self.grabbed_handle pos = event.x, event.y self.motion_handle = HandleInMotion(item, handle, self.view) self.motion_handle.GLUE_DISTANCE = self._parent_state_v.border_width self.motion_handle.start_move(pos)
python
def _set_motion_handle(self, event): """Sets motion handle to currently grabbed handle """ item = self.grabbed_item handle = self.grabbed_handle pos = event.x, event.y self.motion_handle = HandleInMotion(item, handle, self.view) self.motion_handle.GLUE_DISTANCE = self._parent_state_v.border_width self.motion_handle.start_move(pos)
[ "def", "_set_motion_handle", "(", "self", ",", "event", ")", ":", "item", "=", "self", ".", "grabbed_item", "handle", "=", "self", ".", "grabbed_handle", "pos", "=", "event", ".", "x", ",", "event", ".", "y", "self", ".", "motion_handle", "=", "HandleInM...
Sets motion handle to currently grabbed handle
[ "Sets", "motion", "handle", "to", "currently", "grabbed", "handle" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/tools.py#L579-L587
train
40,457
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/tools.py
ConnectionTool._create_temporary_connection
def _create_temporary_connection(self): """Creates a placeholder connection view :return: New placeholder connection :rtype: rafcon.gui.mygaphas.items.connection.ConnectionPlaceholderView """ if self._is_transition: self._connection_v = TransitionPlaceholderView(self._parent_state_v.hierarchy_level) else: self._connection_v = DataFlowPlaceholderView(self._parent_state_v.hierarchy_level) self.view.canvas.add(self._connection_v, self._parent_state_v)
python
def _create_temporary_connection(self): """Creates a placeholder connection view :return: New placeholder connection :rtype: rafcon.gui.mygaphas.items.connection.ConnectionPlaceholderView """ if self._is_transition: self._connection_v = TransitionPlaceholderView(self._parent_state_v.hierarchy_level) else: self._connection_v = DataFlowPlaceholderView(self._parent_state_v.hierarchy_level) self.view.canvas.add(self._connection_v, self._parent_state_v)
[ "def", "_create_temporary_connection", "(", "self", ")", ":", "if", "self", ".", "_is_transition", ":", "self", ".", "_connection_v", "=", "TransitionPlaceholderView", "(", "self", ".", "_parent_state_v", ".", "hierarchy_level", ")", "else", ":", "self", ".", "_...
Creates a placeholder connection view :return: New placeholder connection :rtype: rafcon.gui.mygaphas.items.connection.ConnectionPlaceholderView
[ "Creates", "a", "placeholder", "connection", "view" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/tools.py#L589-L599
train
40,458
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/tools.py
ConnectionTool._handle_temporary_connection
def _handle_temporary_connection(self, old_sink, new_sink, of_target=True): """Connect connection to new_sink If new_sink is set, the connection origin or target will be set to new_sink. The connection to old_sink is being removed. :param gaphas.aspect.ConnectionSink old_sink: Old sink (if existing) :param gaphas.aspect.ConnectionSink new_sink: New sink (if existing) :param bool of_target: Whether the origin or target will be reconnected :return: """ def sink_set_and_differs(sink_a, sink_b): if not sink_a: return False if not sink_b: return True if sink_a.port != sink_b.port: return True return False if sink_set_and_differs(old_sink, new_sink): sink_port_v = old_sink.port.port_v self._disconnect_temporarily(sink_port_v, target=of_target) if sink_set_and_differs(new_sink, old_sink): sink_port_v = new_sink.port.port_v self._connect_temporarily(sink_port_v, target=of_target)
python
def _handle_temporary_connection(self, old_sink, new_sink, of_target=True): """Connect connection to new_sink If new_sink is set, the connection origin or target will be set to new_sink. The connection to old_sink is being removed. :param gaphas.aspect.ConnectionSink old_sink: Old sink (if existing) :param gaphas.aspect.ConnectionSink new_sink: New sink (if existing) :param bool of_target: Whether the origin or target will be reconnected :return: """ def sink_set_and_differs(sink_a, sink_b): if not sink_a: return False if not sink_b: return True if sink_a.port != sink_b.port: return True return False if sink_set_and_differs(old_sink, new_sink): sink_port_v = old_sink.port.port_v self._disconnect_temporarily(sink_port_v, target=of_target) if sink_set_and_differs(new_sink, old_sink): sink_port_v = new_sink.port.port_v self._connect_temporarily(sink_port_v, target=of_target)
[ "def", "_handle_temporary_connection", "(", "self", ",", "old_sink", ",", "new_sink", ",", "of_target", "=", "True", ")", ":", "def", "sink_set_and_differs", "(", "sink_a", ",", "sink_b", ")", ":", "if", "not", "sink_a", ":", "return", "False", "if", "not", ...
Connect connection to new_sink If new_sink is set, the connection origin or target will be set to new_sink. The connection to old_sink is being removed. :param gaphas.aspect.ConnectionSink old_sink: Old sink (if existing) :param gaphas.aspect.ConnectionSink new_sink: New sink (if existing) :param bool of_target: Whether the origin or target will be reconnected :return:
[ "Connect", "connection", "to", "new_sink" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/tools.py#L601-L628
train
40,459
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/tools.py
ConnectionTool._connect_temporarily
def _connect_temporarily(self, port_v, target=True): """Set a connection between the current connection and the given port :param rafcon.gui.mygaphas.items.ports.PortView port_v: The port to be connected :param bool target: Whether the connection origin or target should be connected """ if target: handle = self._connection_v.to_handle() else: handle = self._connection_v.from_handle() port_v.add_connected_handle(handle, self._connection_v, moving=True) port_v.tmp_connect(handle, self._connection_v) self._connection_v.set_port_for_handle(port_v, handle) # Redraw state of port to make hover state visible self._redraw_port(port_v)
python
def _connect_temporarily(self, port_v, target=True): """Set a connection between the current connection and the given port :param rafcon.gui.mygaphas.items.ports.PortView port_v: The port to be connected :param bool target: Whether the connection origin or target should be connected """ if target: handle = self._connection_v.to_handle() else: handle = self._connection_v.from_handle() port_v.add_connected_handle(handle, self._connection_v, moving=True) port_v.tmp_connect(handle, self._connection_v) self._connection_v.set_port_for_handle(port_v, handle) # Redraw state of port to make hover state visible self._redraw_port(port_v)
[ "def", "_connect_temporarily", "(", "self", ",", "port_v", ",", "target", "=", "True", ")", ":", "if", "target", ":", "handle", "=", "self", ".", "_connection_v", ".", "to_handle", "(", ")", "else", ":", "handle", "=", "self", ".", "_connection_v", ".", ...
Set a connection between the current connection and the given port :param rafcon.gui.mygaphas.items.ports.PortView port_v: The port to be connected :param bool target: Whether the connection origin or target should be connected
[ "Set", "a", "connection", "between", "the", "current", "connection", "and", "the", "given", "port" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/tools.py#L630-L644
train
40,460
DLR-RM/RAFCON
source/rafcon/gui/mygaphas/tools.py
ConnectionTool._disconnect_temporarily
def _disconnect_temporarily(self, port_v, target=True): """Removes a connection between the current connection and the given port :param rafcon.gui.mygaphas.items.ports.PortView port_v: The port that was connected :param bool target: Whether the connection origin or target should be disconnected """ if target: handle = self._connection_v.to_handle() else: handle = self._connection_v.from_handle() port_v.remove_connected_handle(handle) port_v.tmp_disconnect() self._connection_v.reset_port_for_handle(handle) # Redraw state of port to make hover state visible self._redraw_port(port_v)
python
def _disconnect_temporarily(self, port_v, target=True): """Removes a connection between the current connection and the given port :param rafcon.gui.mygaphas.items.ports.PortView port_v: The port that was connected :param bool target: Whether the connection origin or target should be disconnected """ if target: handle = self._connection_v.to_handle() else: handle = self._connection_v.from_handle() port_v.remove_connected_handle(handle) port_v.tmp_disconnect() self._connection_v.reset_port_for_handle(handle) # Redraw state of port to make hover state visible self._redraw_port(port_v)
[ "def", "_disconnect_temporarily", "(", "self", ",", "port_v", ",", "target", "=", "True", ")", ":", "if", "target", ":", "handle", "=", "self", ".", "_connection_v", ".", "to_handle", "(", ")", "else", ":", "handle", "=", "self", ".", "_connection_v", "....
Removes a connection between the current connection and the given port :param rafcon.gui.mygaphas.items.ports.PortView port_v: The port that was connected :param bool target: Whether the connection origin or target should be disconnected
[ "Removes", "a", "connection", "between", "the", "current", "connection", "and", "the", "given", "port" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/tools.py#L646-L660
train
40,461
DLR-RM/RAFCON
source/rafcon/core/library_manager.py
LibraryManager.initialize
def initialize(self): """Initializes the library manager It searches through all library paths given in the config file for libraries, and loads the states. This cannot be done in the __init__ function as the library_manager can be compiled and executed by singleton.py before the state*.pys are loaded """ logger.debug("Initializing LibraryManager: Loading libraries ... ") self._libraries = {} self._library_root_paths = {} self._replaced_libraries = {} self._skipped_states = [] self._skipped_library_roots = [] # 1. Load libraries from config.yaml for library_root_key, library_root_path in config.global_config.get_config_value("LIBRARY_PATHS").items(): library_root_path = self._clean_path(library_root_path) if os.path.exists(library_root_path): logger.debug("Adding library root key '{0}' from path '{1}'".format( library_root_key, library_root_path)) self._load_libraries_from_root_path(library_root_key, library_root_path) else: logger.warning("Configured path for library root key '{}' does not exist: {}".format( library_root_key, library_root_path)) # 2. Load libraries from RAFCON_LIBRARY_PATH library_path_env = os.environ.get('RAFCON_LIBRARY_PATH', '') library_paths = set(library_path_env.split(os.pathsep)) for library_root_path in library_paths: if not library_root_path: continue library_root_path = self._clean_path(library_root_path) if not os.path.exists(library_root_path): logger.warning("The library specified in RAFCON_LIBRARY_PATH does not exist: {}".format(library_root_path)) continue _, library_root_key = os.path.split(library_root_path) if library_root_key in self._libraries: if os.path.realpath(self._library_root_paths[library_root_key]) == os.path.realpath(library_root_path): logger.info("The library root key '{}' and root path '{}' exists multiple times in your environment" " and will be skipped.".format(library_root_key, library_root_path)) else: logger.warning("The library '{}' is already existing and will be overridden with '{}'".format( library_root_key, library_root_path)) self._load_libraries_from_root_path(library_root_key, library_root_path) else: self._load_libraries_from_root_path(library_root_key, library_root_path) logger.debug("Adding library '{1}' from {0}".format(library_root_path, library_root_key)) self._libraries = OrderedDict(sorted(self._libraries.items())) logger.debug("Initialization of LibraryManager done")
python
def initialize(self): """Initializes the library manager It searches through all library paths given in the config file for libraries, and loads the states. This cannot be done in the __init__ function as the library_manager can be compiled and executed by singleton.py before the state*.pys are loaded """ logger.debug("Initializing LibraryManager: Loading libraries ... ") self._libraries = {} self._library_root_paths = {} self._replaced_libraries = {} self._skipped_states = [] self._skipped_library_roots = [] # 1. Load libraries from config.yaml for library_root_key, library_root_path in config.global_config.get_config_value("LIBRARY_PATHS").items(): library_root_path = self._clean_path(library_root_path) if os.path.exists(library_root_path): logger.debug("Adding library root key '{0}' from path '{1}'".format( library_root_key, library_root_path)) self._load_libraries_from_root_path(library_root_key, library_root_path) else: logger.warning("Configured path for library root key '{}' does not exist: {}".format( library_root_key, library_root_path)) # 2. Load libraries from RAFCON_LIBRARY_PATH library_path_env = os.environ.get('RAFCON_LIBRARY_PATH', '') library_paths = set(library_path_env.split(os.pathsep)) for library_root_path in library_paths: if not library_root_path: continue library_root_path = self._clean_path(library_root_path) if not os.path.exists(library_root_path): logger.warning("The library specified in RAFCON_LIBRARY_PATH does not exist: {}".format(library_root_path)) continue _, library_root_key = os.path.split(library_root_path) if library_root_key in self._libraries: if os.path.realpath(self._library_root_paths[library_root_key]) == os.path.realpath(library_root_path): logger.info("The library root key '{}' and root path '{}' exists multiple times in your environment" " and will be skipped.".format(library_root_key, library_root_path)) else: logger.warning("The library '{}' is already existing and will be overridden with '{}'".format( library_root_key, library_root_path)) self._load_libraries_from_root_path(library_root_key, library_root_path) else: self._load_libraries_from_root_path(library_root_key, library_root_path) logger.debug("Adding library '{1}' from {0}".format(library_root_path, library_root_key)) self._libraries = OrderedDict(sorted(self._libraries.items())) logger.debug("Initialization of LibraryManager done")
[ "def", "initialize", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Initializing LibraryManager: Loading libraries ... \"", ")", "self", ".", "_libraries", "=", "{", "}", "self", ".", "_library_root_paths", "=", "{", "}", "self", ".", "_replaced_libraries"...
Initializes the library manager It searches through all library paths given in the config file for libraries, and loads the states. This cannot be done in the __init__ function as the library_manager can be compiled and executed by singleton.py before the state*.pys are loaded
[ "Initializes", "the", "library", "manager" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/library_manager.py#L75-L125
train
40,462
DLR-RM/RAFCON
source/rafcon/core/library_manager.py
LibraryManager._clean_path
def _clean_path(path): """Create a fully fissile absolute system path with no symbolic links and environment variables""" path = path.replace('"', '') path = path.replace("'", '') # Replace ~ with /home/user path = os.path.expanduser(path) # Replace environment variables path = os.path.expandvars(path) # If the path is relative, assume it is relative to the config file directory if not os.path.isabs(path): path = os.path.join(config.global_config.path, path) # Clean path, e.g. replace /./ with / path = os.path.abspath(path) # Eliminate symbolic links path = os.path.realpath(path) return path
python
def _clean_path(path): """Create a fully fissile absolute system path with no symbolic links and environment variables""" path = path.replace('"', '') path = path.replace("'", '') # Replace ~ with /home/user path = os.path.expanduser(path) # Replace environment variables path = os.path.expandvars(path) # If the path is relative, assume it is relative to the config file directory if not os.path.isabs(path): path = os.path.join(config.global_config.path, path) # Clean path, e.g. replace /./ with / path = os.path.abspath(path) # Eliminate symbolic links path = os.path.realpath(path) return path
[ "def", "_clean_path", "(", "path", ")", ":", "path", "=", "path", ".", "replace", "(", "'\"'", ",", "''", ")", "path", "=", "path", ".", "replace", "(", "\"'\"", ",", "''", ")", "# Replace ~ with /home/user", "path", "=", "os", ".", "path", ".", "exp...
Create a fully fissile absolute system path with no symbolic links and environment variables
[ "Create", "a", "fully", "fissile", "absolute", "system", "path", "with", "no", "symbolic", "links", "and", "environment", "variables" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/library_manager.py#L128-L143
train
40,463
DLR-RM/RAFCON
source/rafcon/core/library_manager.py
LibraryManager._load_nested_libraries
def _load_nested_libraries(self, library_path, target_dict): """Recursively load libraries within path Adds all libraries specified in a given path and stores them into the provided library dictionary. The library entries in the dictionary consist only of the path to the library in the file system. :param library_path: the path to add all libraries from :param target_dict: the target dictionary to store all loaded libraries to """ for library_name in os.listdir(library_path): library_folder_path, library_name = self.check_clean_path_of_library(library_path, library_name) full_library_path = os.path.join(library_path, library_name) if os.path.isdir(full_library_path) and library_name[0] != '.': if os.path.exists(os.path.join(full_library_path, storage.STATEMACHINE_FILE)) \ or os.path.exists(os.path.join(full_library_path, storage.STATEMACHINE_FILE_OLD)): target_dict[library_name] = full_library_path else: target_dict[library_name] = {} self._load_nested_libraries(full_library_path, target_dict[library_name]) target_dict[library_name] = OrderedDict(sorted(target_dict[library_name].items()))
python
def _load_nested_libraries(self, library_path, target_dict): """Recursively load libraries within path Adds all libraries specified in a given path and stores them into the provided library dictionary. The library entries in the dictionary consist only of the path to the library in the file system. :param library_path: the path to add all libraries from :param target_dict: the target dictionary to store all loaded libraries to """ for library_name in os.listdir(library_path): library_folder_path, library_name = self.check_clean_path_of_library(library_path, library_name) full_library_path = os.path.join(library_path, library_name) if os.path.isdir(full_library_path) and library_name[0] != '.': if os.path.exists(os.path.join(full_library_path, storage.STATEMACHINE_FILE)) \ or os.path.exists(os.path.join(full_library_path, storage.STATEMACHINE_FILE_OLD)): target_dict[library_name] = full_library_path else: target_dict[library_name] = {} self._load_nested_libraries(full_library_path, target_dict[library_name]) target_dict[library_name] = OrderedDict(sorted(target_dict[library_name].items()))
[ "def", "_load_nested_libraries", "(", "self", ",", "library_path", ",", "target_dict", ")", ":", "for", "library_name", "in", "os", ".", "listdir", "(", "library_path", ")", ":", "library_folder_path", ",", "library_name", "=", "self", ".", "check_clean_path_of_li...
Recursively load libraries within path Adds all libraries specified in a given path and stores them into the provided library dictionary. The library entries in the dictionary consist only of the path to the library in the file system. :param library_path: the path to add all libraries from :param target_dict: the target dictionary to store all loaded libraries to
[ "Recursively", "load", "libraries", "within", "path" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/library_manager.py#L162-L181
train
40,464
DLR-RM/RAFCON
source/rafcon/core/library_manager.py
LibraryManager._get_library_os_path_from_library_dict_tree
def _get_library_os_path_from_library_dict_tree(self, library_path, library_name): """Hand verified library os path from libraries dictionary tree.""" if library_path is None or library_name is None: return None path_list = library_path.split(os.sep) target_lib_dict = self.libraries # go down the path to the correct library for path_element in path_list: if path_element not in target_lib_dict: # Library cannot be found target_lib_dict = None break target_lib_dict = target_lib_dict[path_element] return None if target_lib_dict is None or library_name not in target_lib_dict else target_lib_dict[library_name]
python
def _get_library_os_path_from_library_dict_tree(self, library_path, library_name): """Hand verified library os path from libraries dictionary tree.""" if library_path is None or library_name is None: return None path_list = library_path.split(os.sep) target_lib_dict = self.libraries # go down the path to the correct library for path_element in path_list: if path_element not in target_lib_dict: # Library cannot be found target_lib_dict = None break target_lib_dict = target_lib_dict[path_element] return None if target_lib_dict is None or library_name not in target_lib_dict else target_lib_dict[library_name]
[ "def", "_get_library_os_path_from_library_dict_tree", "(", "self", ",", "library_path", ",", "library_name", ")", ":", "if", "library_path", "is", "None", "or", "library_name", "is", "None", ":", "return", "None", "path_list", "=", "library_path", ".", "split", "(...
Hand verified library os path from libraries dictionary tree.
[ "Hand", "verified", "library", "os", "path", "from", "libraries", "dictionary", "tree", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/library_manager.py#L312-L324
train
40,465
DLR-RM/RAFCON
source/rafcon/core/library_manager.py
LibraryManager._get_library_root_key_for_os_path
def _get_library_root_key_for_os_path(self, path): """Return library root key if path is within library root paths""" path = os.path.realpath(path) library_root_key = None for library_root_key, library_root_path in self._library_root_paths.items(): rel_path = os.path.relpath(path, library_root_path) if rel_path.startswith('..'): library_root_key = None continue else: break return library_root_key
python
def _get_library_root_key_for_os_path(self, path): """Return library root key if path is within library root paths""" path = os.path.realpath(path) library_root_key = None for library_root_key, library_root_path in self._library_root_paths.items(): rel_path = os.path.relpath(path, library_root_path) if rel_path.startswith('..'): library_root_key = None continue else: break return library_root_key
[ "def", "_get_library_root_key_for_os_path", "(", "self", ",", "path", ")", ":", "path", "=", "os", ".", "path", ".", "realpath", "(", "path", ")", "library_root_key", "=", "None", "for", "library_root_key", ",", "library_root_path", "in", "self", ".", "_librar...
Return library root key if path is within library root paths
[ "Return", "library", "root", "key", "if", "path", "is", "within", "library", "root", "paths" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/library_manager.py#L326-L337
train
40,466
DLR-RM/RAFCON
source/rafcon/core/library_manager.py
LibraryManager.get_library_path_and_name_for_os_path
def get_library_path_and_name_for_os_path(self, path): """Generate valid library_path and library_name The method checks if the given os path is in the list of loaded library root paths and use respective library root key/mounting point to concatenate the respective library_path and separate respective library_name. :param str path: A library os path a library is situated in. :return: library path library name :rtype: str, str """ library_path = None library_name = None library_root_key = self._get_library_root_key_for_os_path(path) if library_root_key is not None: library_root_path = self._library_root_paths[library_root_key] path_elements_without_library_root = path[len(library_root_path)+1:].split(os.sep) library_name = path_elements_without_library_root[-1] sub_library_path = '' if len(path_elements_without_library_root[:-1]): sub_library_path = os.sep + os.sep.join(path_elements_without_library_root[:-1]) library_path = library_root_key + sub_library_path return library_path, library_name
python
def get_library_path_and_name_for_os_path(self, path): """Generate valid library_path and library_name The method checks if the given os path is in the list of loaded library root paths and use respective library root key/mounting point to concatenate the respective library_path and separate respective library_name. :param str path: A library os path a library is situated in. :return: library path library name :rtype: str, str """ library_path = None library_name = None library_root_key = self._get_library_root_key_for_os_path(path) if library_root_key is not None: library_root_path = self._library_root_paths[library_root_key] path_elements_without_library_root = path[len(library_root_path)+1:].split(os.sep) library_name = path_elements_without_library_root[-1] sub_library_path = '' if len(path_elements_without_library_root[:-1]): sub_library_path = os.sep + os.sep.join(path_elements_without_library_root[:-1]) library_path = library_root_key + sub_library_path return library_path, library_name
[ "def", "get_library_path_and_name_for_os_path", "(", "self", ",", "path", ")", ":", "library_path", "=", "None", "library_name", "=", "None", "library_root_key", "=", "self", ".", "_get_library_root_key_for_os_path", "(", "path", ")", "if", "library_root_key", "is", ...
Generate valid library_path and library_name The method checks if the given os path is in the list of loaded library root paths and use respective library root key/mounting point to concatenate the respective library_path and separate respective library_name. :param str path: A library os path a library is situated in. :return: library path library name :rtype: str, str
[ "Generate", "valid", "library_path", "and", "library_name" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/library_manager.py#L346-L367
train
40,467
DLR-RM/RAFCON
source/rafcon/core/library_manager.py
LibraryManager.get_library_instance
def get_library_instance(self, library_path, library_name): """Generate a Library instance from within libraries dictionary tree.""" if self.is_library_in_libraries(library_path, library_name): from rafcon.core.states.library_state import LibraryState return LibraryState(library_path, library_name, "0.1") else: logger.warning("Library manager will not create a library instance which is not in the mounted libraries.")
python
def get_library_instance(self, library_path, library_name): """Generate a Library instance from within libraries dictionary tree.""" if self.is_library_in_libraries(library_path, library_name): from rafcon.core.states.library_state import LibraryState return LibraryState(library_path, library_name, "0.1") else: logger.warning("Library manager will not create a library instance which is not in the mounted libraries.")
[ "def", "get_library_instance", "(", "self", ",", "library_path", ",", "library_name", ")", ":", "if", "self", ".", "is_library_in_libraries", "(", "library_path", ",", "library_name", ")", ":", "from", "rafcon", ".", "core", ".", "states", ".", "library_state", ...
Generate a Library instance from within libraries dictionary tree.
[ "Generate", "a", "Library", "instance", "from", "within", "libraries", "dictionary", "tree", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/library_manager.py#L369-L375
train
40,468
DLR-RM/RAFCON
source/rafcon/core/library_manager.py
LibraryManager.get_library_state_copy_instance
def get_library_state_copy_instance(self, lib_os_path): """ A method to get a state copy of the library specified via the lib_os_path. :param lib_os_path: the location of the library to get a copy for :return: """ # originally libraries were called like this; DO NOT DELETE; interesting for performance tests # state_machine = storage.load_state_machine_from_path(lib_os_path) # return state_machine.version, state_machine.root_state # TODO observe changes on file system and update data if lib_os_path in self._loaded_libraries: # this list can also be taken to open library state machines TODO -> implement it -> because faster state_machine = self._loaded_libraries[lib_os_path] # logger.info("Take copy of {0}".format(lib_os_path)) # as long as the a library state root state is never edited so the state first has to be copied here state_copy = copy.deepcopy(state_machine.root_state) return state_machine.version, state_copy else: state_machine = storage.load_state_machine_from_path(lib_os_path) self._loaded_libraries[lib_os_path] = state_machine if config.global_config.get_config_value("NO_PROGRAMMATIC_CHANGE_OF_LIBRARY_STATES_PERFORMED", False): return state_machine.version, state_machine.root_state else: state_copy = copy.deepcopy(state_machine.root_state) return state_machine.version, state_copy
python
def get_library_state_copy_instance(self, lib_os_path): """ A method to get a state copy of the library specified via the lib_os_path. :param lib_os_path: the location of the library to get a copy for :return: """ # originally libraries were called like this; DO NOT DELETE; interesting for performance tests # state_machine = storage.load_state_machine_from_path(lib_os_path) # return state_machine.version, state_machine.root_state # TODO observe changes on file system and update data if lib_os_path in self._loaded_libraries: # this list can also be taken to open library state machines TODO -> implement it -> because faster state_machine = self._loaded_libraries[lib_os_path] # logger.info("Take copy of {0}".format(lib_os_path)) # as long as the a library state root state is never edited so the state first has to be copied here state_copy = copy.deepcopy(state_machine.root_state) return state_machine.version, state_copy else: state_machine = storage.load_state_machine_from_path(lib_os_path) self._loaded_libraries[lib_os_path] = state_machine if config.global_config.get_config_value("NO_PROGRAMMATIC_CHANGE_OF_LIBRARY_STATES_PERFORMED", False): return state_machine.version, state_machine.root_state else: state_copy = copy.deepcopy(state_machine.root_state) return state_machine.version, state_copy
[ "def", "get_library_state_copy_instance", "(", "self", ",", "lib_os_path", ")", ":", "# originally libraries were called like this; DO NOT DELETE; interesting for performance tests", "# state_machine = storage.load_state_machine_from_path(lib_os_path)", "# return state_machine.version, state_mac...
A method to get a state copy of the library specified via the lib_os_path. :param lib_os_path: the location of the library to get a copy for :return:
[ "A", "method", "to", "get", "a", "state", "copy", "of", "the", "library", "specified", "via", "the", "lib_os_path", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/library_manager.py#L377-L403
train
40,469
DLR-RM/RAFCON
source/rafcon/core/library_manager.py
LibraryManager.remove_library_from_file_system
def remove_library_from_file_system(self, library_path, library_name): """Remove library from hard disk.""" library_file_system_path = self.get_os_path_to_library(library_path, library_name)[0] shutil.rmtree(library_file_system_path) self.refresh_libraries()
python
def remove_library_from_file_system(self, library_path, library_name): """Remove library from hard disk.""" library_file_system_path = self.get_os_path_to_library(library_path, library_name)[0] shutil.rmtree(library_file_system_path) self.refresh_libraries()
[ "def", "remove_library_from_file_system", "(", "self", ",", "library_path", ",", "library_name", ")", ":", "library_file_system_path", "=", "self", ".", "get_os_path_to_library", "(", "library_path", ",", "library_name", ")", "[", "0", "]", "shutil", ".", "rmtree", ...
Remove library from hard disk.
[ "Remove", "library", "from", "hard", "disk", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/library_manager.py#L405-L409
train
40,470
openego/eTraGo
etrago/tools/utilities.py
buses_grid_linked
def buses_grid_linked(network, voltage_level): """ Get bus-ids of a given voltage level connected to the grid. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA voltage_level: list Returns ------- list List containing bus-ids. """ mask = ((network.buses.index.isin(network.lines.bus0) | (network.buses.index.isin(network.lines.bus1))) & (network.buses.v_nom.isin(voltage_level))) df = network.buses[mask] return df.index
python
def buses_grid_linked(network, voltage_level): """ Get bus-ids of a given voltage level connected to the grid. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA voltage_level: list Returns ------- list List containing bus-ids. """ mask = ((network.buses.index.isin(network.lines.bus0) | (network.buses.index.isin(network.lines.bus1))) & (network.buses.v_nom.isin(voltage_level))) df = network.buses[mask] return df.index
[ "def", "buses_grid_linked", "(", "network", ",", "voltage_level", ")", ":", "mask", "=", "(", "(", "network", ".", "buses", ".", "index", ".", "isin", "(", "network", ".", "lines", ".", "bus0", ")", "|", "(", "network", ".", "buses", ".", "index", "....
Get bus-ids of a given voltage level connected to the grid. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA voltage_level: list Returns ------- list List containing bus-ids.
[ "Get", "bus", "-", "ids", "of", "a", "given", "voltage", "level", "connected", "to", "the", "grid", "." ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/utilities.py#L78-L99
train
40,471
openego/eTraGo
etrago/tools/utilities.py
clip_foreign
def clip_foreign(network): """ Delete all components and timelines located outside of Germany. Add transborder flows divided by country of origin as network.foreign_trade. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- network : :class:`pypsa.Network Overall container of PyPSA """ # get foreign buses by country foreign_buses = network.buses[network.buses.country_code != 'DE'] network.buses = network.buses.drop( network.buses.loc[foreign_buses.index].index) # identify transborder lines (one bus foreign, one bus not) and the country # it is coming from """transborder_lines = pd.DataFrame(index=network.lines[ ((network.lines['bus0'].isin(network.buses.index) == False) & (network.lines['bus1'].isin(network.buses.index) == True)) | ((network.lines['bus0'].isin(network.buses.index) == True) & (network.lines['bus1'].isin(network.buses.index) == False))].index) transborder_lines['bus0'] = network.lines['bus0'] transborder_lines['bus1'] = network.lines['bus1'] transborder_lines['country'] = "" for i in range(0, len(transborder_lines)): if transborder_lines.iloc[i, 0] in foreign_buses.index: transborder_lines['country'][i] = foreign_buses[str( transborder_lines.iloc[i, 0])] else: transborder_lines['country'][i] = foreign_buses[str( transborder_lines.iloc[i, 1])] # identify amount of flows per line and group to get flow per country transborder_flows = network.lines_t.p0[transborder_lines.index] for i in transborder_flows.columns: if network.lines.loc[str(i)]['bus1'] in foreign_buses.index: transborder_flows.loc[:, str( i)] = transborder_flows.loc[:, str(i)]*-1 network.foreign_trade = transborder_flows.\ groupby(transborder_lines['country'], axis=1).sum()""" # drop foreign components network.lines = network.lines.drop(network.lines[ (network.lines['bus0'].isin(network.buses.index) == False) | (network.lines['bus1'].isin(network.buses.index) == False)].index) network.links = network.links.drop(network.links[ (network.links['bus0'].isin(network.buses.index) == False) | (network.links['bus1'].isin(network.buses.index) == False)].index) network.transformers = network.transformers.drop(network.transformers[ (network.transformers['bus0'].isin(network.buses.index) == False) | (network.transformers['bus1'].isin(network. buses.index) == False)].index) network.generators = network.generators.drop(network.generators[ (network.generators['bus'].isin(network.buses.index) == False)].index) network.loads = network.loads.drop(network.loads[ (network.loads['bus'].isin(network.buses.index) == False)].index) network.storage_units = network.storage_units.drop(network.storage_units[ (network.storage_units['bus'].isin(network. buses.index) == False)].index) components = ['loads', 'generators', 'lines', 'buses', 'transformers', 'links'] for g in components: # loads_t h = g + '_t' nw = getattr(network, h) # network.loads_t for i in nw.keys(): # network.loads_t.p cols = [j for j in getattr( nw, i).columns if j not in getattr(network, g).index] for k in cols: del getattr(nw, i)[k] return network
python
def clip_foreign(network): """ Delete all components and timelines located outside of Germany. Add transborder flows divided by country of origin as network.foreign_trade. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- network : :class:`pypsa.Network Overall container of PyPSA """ # get foreign buses by country foreign_buses = network.buses[network.buses.country_code != 'DE'] network.buses = network.buses.drop( network.buses.loc[foreign_buses.index].index) # identify transborder lines (one bus foreign, one bus not) and the country # it is coming from """transborder_lines = pd.DataFrame(index=network.lines[ ((network.lines['bus0'].isin(network.buses.index) == False) & (network.lines['bus1'].isin(network.buses.index) == True)) | ((network.lines['bus0'].isin(network.buses.index) == True) & (network.lines['bus1'].isin(network.buses.index) == False))].index) transborder_lines['bus0'] = network.lines['bus0'] transborder_lines['bus1'] = network.lines['bus1'] transborder_lines['country'] = "" for i in range(0, len(transborder_lines)): if transborder_lines.iloc[i, 0] in foreign_buses.index: transborder_lines['country'][i] = foreign_buses[str( transborder_lines.iloc[i, 0])] else: transborder_lines['country'][i] = foreign_buses[str( transborder_lines.iloc[i, 1])] # identify amount of flows per line and group to get flow per country transborder_flows = network.lines_t.p0[transborder_lines.index] for i in transborder_flows.columns: if network.lines.loc[str(i)]['bus1'] in foreign_buses.index: transborder_flows.loc[:, str( i)] = transborder_flows.loc[:, str(i)]*-1 network.foreign_trade = transborder_flows.\ groupby(transborder_lines['country'], axis=1).sum()""" # drop foreign components network.lines = network.lines.drop(network.lines[ (network.lines['bus0'].isin(network.buses.index) == False) | (network.lines['bus1'].isin(network.buses.index) == False)].index) network.links = network.links.drop(network.links[ (network.links['bus0'].isin(network.buses.index) == False) | (network.links['bus1'].isin(network.buses.index) == False)].index) network.transformers = network.transformers.drop(network.transformers[ (network.transformers['bus0'].isin(network.buses.index) == False) | (network.transformers['bus1'].isin(network. buses.index) == False)].index) network.generators = network.generators.drop(network.generators[ (network.generators['bus'].isin(network.buses.index) == False)].index) network.loads = network.loads.drop(network.loads[ (network.loads['bus'].isin(network.buses.index) == False)].index) network.storage_units = network.storage_units.drop(network.storage_units[ (network.storage_units['bus'].isin(network. buses.index) == False)].index) components = ['loads', 'generators', 'lines', 'buses', 'transformers', 'links'] for g in components: # loads_t h = g + '_t' nw = getattr(network, h) # network.loads_t for i in nw.keys(): # network.loads_t.p cols = [j for j in getattr( nw, i).columns if j not in getattr(network, g).index] for k in cols: del getattr(nw, i)[k] return network
[ "def", "clip_foreign", "(", "network", ")", ":", "# get foreign buses by country", "foreign_buses", "=", "network", ".", "buses", "[", "network", ".", "buses", ".", "country_code", "!=", "'DE'", "]", "network", ".", "buses", "=", "network", ".", "buses", ".", ...
Delete all components and timelines located outside of Germany. Add transborder flows divided by country of origin as network.foreign_trade. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- network : :class:`pypsa.Network Overall container of PyPSA
[ "Delete", "all", "components", "and", "timelines", "located", "outside", "of", "Germany", ".", "Add", "transborder", "flows", "divided", "by", "country", "of", "origin", "as", "network", ".", "foreign_trade", "." ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/utilities.py#L311-L395
train
40,472
openego/eTraGo
etrago/tools/utilities.py
connected_grid_lines
def connected_grid_lines(network, busids): """ Get grid lines connected to given buses. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA busids : list List containing bus-ids. Returns ------- :class:`pandas.DataFrame PyPSA lines. """ mask = network.lines.bus1.isin(busids) |\ network.lines.bus0.isin(busids) return network.lines[mask]
python
def connected_grid_lines(network, busids): """ Get grid lines connected to given buses. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA busids : list List containing bus-ids. Returns ------- :class:`pandas.DataFrame PyPSA lines. """ mask = network.lines.bus1.isin(busids) |\ network.lines.bus0.isin(busids) return network.lines[mask]
[ "def", "connected_grid_lines", "(", "network", ",", "busids", ")", ":", "mask", "=", "network", ".", "lines", ".", "bus1", ".", "isin", "(", "busids", ")", "|", "network", ".", "lines", ".", "bus0", ".", "isin", "(", "busids", ")", "return", "network",...
Get grid lines connected to given buses. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA busids : list List containing bus-ids. Returns ------- :class:`pandas.DataFrame PyPSA lines.
[ "Get", "grid", "lines", "connected", "to", "given", "buses", "." ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/utilities.py#L475-L494
train
40,473
openego/eTraGo
etrago/tools/utilities.py
connected_transformer
def connected_transformer(network, busids): """ Get transformer connected to given buses. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA busids : list List containing bus-ids. Returns ------- :class:`pandas.DataFrame PyPSA transformer. """ mask = (network.transformers.bus0.isin(busids)) return network.transformers[mask]
python
def connected_transformer(network, busids): """ Get transformer connected to given buses. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA busids : list List containing bus-ids. Returns ------- :class:`pandas.DataFrame PyPSA transformer. """ mask = (network.transformers.bus0.isin(busids)) return network.transformers[mask]
[ "def", "connected_transformer", "(", "network", ",", "busids", ")", ":", "mask", "=", "(", "network", ".", "transformers", ".", "bus0", ".", "isin", "(", "busids", ")", ")", "return", "network", ".", "transformers", "[", "mask", "]" ]
Get transformer connected to given buses. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA busids : list List containing bus-ids. Returns ------- :class:`pandas.DataFrame PyPSA transformer.
[ "Get", "transformer", "connected", "to", "given", "buses", "." ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/utilities.py#L497-L515
train
40,474
openego/eTraGo
etrago/tools/utilities.py
data_manipulation_sh
def data_manipulation_sh(network): """ Adds missing components to run calculations with SH scenarios. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA """ from shapely.geometry import Point, LineString, MultiLineString from geoalchemy2.shape import from_shape, to_shape # add connection from Luebeck to Siems new_bus = str(network.buses.index.astype(np.int64).max() + 1) new_trafo = str(network.transformers.index.astype(np.int64).max() + 1) new_line = str(network.lines.index.astype(np.int64).max() + 1) network.add("Bus", new_bus, carrier='AC', v_nom=220, x=10.760835, y=53.909745) network.add("Transformer", new_trafo, bus0="25536", bus1=new_bus, x=1.29960, tap_ratio=1, s_nom=1600) network.add("Line", new_line, bus0="26387", bus1=new_bus, x=0.0001, s_nom=1600) network.lines.loc[new_line, 'cables'] = 3.0 # bus geom point_bus1 = Point(10.760835, 53.909745) network.buses.set_value(new_bus, 'geom', from_shape(point_bus1, 4326)) # line geom/topo network.lines.set_value(new_line, 'geom', from_shape(MultiLineString( [LineString([to_shape(network. buses.geom['26387']), point_bus1])]), 4326)) network.lines.set_value(new_line, 'topo', from_shape(LineString( [to_shape(network.buses.geom['26387']), point_bus1]), 4326)) # trafo geom/topo network.transformers.set_value(new_trafo, 'geom', from_shape(MultiLineString( [LineString( [to_shape(network .buses.geom['25536']), point_bus1])]), 4326)) network.transformers.set_value(new_trafo, 'topo', from_shape( LineString([to_shape(network.buses.geom['25536']), point_bus1]), 4326)) return
python
def data_manipulation_sh(network): """ Adds missing components to run calculations with SH scenarios. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA """ from shapely.geometry import Point, LineString, MultiLineString from geoalchemy2.shape import from_shape, to_shape # add connection from Luebeck to Siems new_bus = str(network.buses.index.astype(np.int64).max() + 1) new_trafo = str(network.transformers.index.astype(np.int64).max() + 1) new_line = str(network.lines.index.astype(np.int64).max() + 1) network.add("Bus", new_bus, carrier='AC', v_nom=220, x=10.760835, y=53.909745) network.add("Transformer", new_trafo, bus0="25536", bus1=new_bus, x=1.29960, tap_ratio=1, s_nom=1600) network.add("Line", new_line, bus0="26387", bus1=new_bus, x=0.0001, s_nom=1600) network.lines.loc[new_line, 'cables'] = 3.0 # bus geom point_bus1 = Point(10.760835, 53.909745) network.buses.set_value(new_bus, 'geom', from_shape(point_bus1, 4326)) # line geom/topo network.lines.set_value(new_line, 'geom', from_shape(MultiLineString( [LineString([to_shape(network. buses.geom['26387']), point_bus1])]), 4326)) network.lines.set_value(new_line, 'topo', from_shape(LineString( [to_shape(network.buses.geom['26387']), point_bus1]), 4326)) # trafo geom/topo network.transformers.set_value(new_trafo, 'geom', from_shape(MultiLineString( [LineString( [to_shape(network .buses.geom['25536']), point_bus1])]), 4326)) network.transformers.set_value(new_trafo, 'topo', from_shape( LineString([to_shape(network.buses.geom['25536']), point_bus1]), 4326)) return
[ "def", "data_manipulation_sh", "(", "network", ")", ":", "from", "shapely", ".", "geometry", "import", "Point", ",", "LineString", ",", "MultiLineString", "from", "geoalchemy2", ".", "shape", "import", "from_shape", ",", "to_shape", "# add connection from Luebeck to S...
Adds missing components to run calculations with SH scenarios. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA
[ "Adds", "missing", "components", "to", "run", "calculations", "with", "SH", "scenarios", "." ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/utilities.py#L557-L604
train
40,475
openego/eTraGo
etrago/tools/utilities.py
results_to_csv
def results_to_csv(network, args, pf_solution=None): """ Function the writes the calaculation results in csv-files in the desired directory. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA args: dict Contains calculation settings of appl.py pf_solution: pandas.Dataframe or None If pf was calculated, df containing information of convergence else None. """ path = args['csv_export'] if path == False: return None if not os.path.exists(path): os.makedirs(path, exist_ok=True) network.export_to_csv_folder(path) data = pd.read_csv(os.path.join(path, 'network.csv')) data['time'] = network.results['Solver'].Time data = data.apply(_enumerate_row, axis=1) data.to_csv(os.path.join(path, 'network.csv'), index=False) with open(os.path.join(path, 'args.json'), 'w') as fp: json.dump(args, fp) if not isinstance(pf_solution, type(None)): pf_solution.to_csv(os.path.join(path, 'pf_solution.csv'), index=True) if hasattr(network, 'Z'): file = [i for i in os.listdir( path.strip('0123456789')) if i == 'Z.csv'] if file: print('Z already calculated') else: network.Z.to_csv(path.strip('0123456789') + '/Z.csv', index=False) return
python
def results_to_csv(network, args, pf_solution=None): """ Function the writes the calaculation results in csv-files in the desired directory. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA args: dict Contains calculation settings of appl.py pf_solution: pandas.Dataframe or None If pf was calculated, df containing information of convergence else None. """ path = args['csv_export'] if path == False: return None if not os.path.exists(path): os.makedirs(path, exist_ok=True) network.export_to_csv_folder(path) data = pd.read_csv(os.path.join(path, 'network.csv')) data['time'] = network.results['Solver'].Time data = data.apply(_enumerate_row, axis=1) data.to_csv(os.path.join(path, 'network.csv'), index=False) with open(os.path.join(path, 'args.json'), 'w') as fp: json.dump(args, fp) if not isinstance(pf_solution, type(None)): pf_solution.to_csv(os.path.join(path, 'pf_solution.csv'), index=True) if hasattr(network, 'Z'): file = [i for i in os.listdir( path.strip('0123456789')) if i == 'Z.csv'] if file: print('Z already calculated') else: network.Z.to_csv(path.strip('0123456789') + '/Z.csv', index=False) return
[ "def", "results_to_csv", "(", "network", ",", "args", ",", "pf_solution", "=", "None", ")", ":", "path", "=", "args", "[", "'csv_export'", "]", "if", "path", "==", "False", ":", "return", "None", "if", "not", "os", ".", "path", ".", "exists", "(", "p...
Function the writes the calaculation results in csv-files in the desired directory. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA args: dict Contains calculation settings of appl.py pf_solution: pandas.Dataframe or None If pf was calculated, df containing information of convergence else None.
[ "Function", "the", "writes", "the", "calaculation", "results", "in", "csv", "-", "files", "in", "the", "desired", "directory", "." ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/utilities.py#L612-L655
train
40,476
openego/eTraGo
etrago/tools/utilities.py
parallelisation
def parallelisation(network, args, group_size, extra_functionality=None): """ Function that splits problem in selected number of snapshot groups and runs optimization successive for each group. Not useful for calculations with storage untis or extension. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA args: dict Contains calculation settings of appl.py Returns ------- network : :class:`pypsa.Network Overall container of PyPSA """ print("Performing linear OPF, {} snapshot(s) at a time:". format(group_size)) t = time.time() for i in range(int((args['end_snapshot'] - args['start_snapshot'] + 1) / group_size)): if i > 0: network.storage_units.state_of_charge_initial = network.\ storage_units_t.state_of_charge.loc[ network.snapshots[group_size * i - 1]] network.lopf(network.snapshots[ group_size * i:group_size * i + group_size], solver_name=args['solver_name'], solver_options=args['solver_options'], extra_functionality=extra_functionality) network.lines.s_nom = network.lines.s_nom_opt print(time.time() - t / 60) return
python
def parallelisation(network, args, group_size, extra_functionality=None): """ Function that splits problem in selected number of snapshot groups and runs optimization successive for each group. Not useful for calculations with storage untis or extension. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA args: dict Contains calculation settings of appl.py Returns ------- network : :class:`pypsa.Network Overall container of PyPSA """ print("Performing linear OPF, {} snapshot(s) at a time:". format(group_size)) t = time.time() for i in range(int((args['end_snapshot'] - args['start_snapshot'] + 1) / group_size)): if i > 0: network.storage_units.state_of_charge_initial = network.\ storage_units_t.state_of_charge.loc[ network.snapshots[group_size * i - 1]] network.lopf(network.snapshots[ group_size * i:group_size * i + group_size], solver_name=args['solver_name'], solver_options=args['solver_options'], extra_functionality=extra_functionality) network.lines.s_nom = network.lines.s_nom_opt print(time.time() - t / 60) return
[ "def", "parallelisation", "(", "network", ",", "args", ",", "group_size", ",", "extra_functionality", "=", "None", ")", ":", "print", "(", "\"Performing linear OPF, {} snapshot(s) at a time:\"", ".", "format", "(", "group_size", ")", ")", "t", "=", "time", ".", ...
Function that splits problem in selected number of snapshot groups and runs optimization successive for each group. Not useful for calculations with storage untis or extension. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA args: dict Contains calculation settings of appl.py Returns ------- network : :class:`pypsa.Network Overall container of PyPSA
[ "Function", "that", "splits", "problem", "in", "selected", "number", "of", "snapshot", "groups", "and", "runs", "optimization", "successive", "for", "each", "group", ".", "Not", "useful", "for", "calculations", "with", "storage", "untis", "or", "extension", "." ...
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/utilities.py#L658-L697
train
40,477
openego/eTraGo
etrago/tools/utilities.py
set_slack
def set_slack(network): """ Function that chosses the bus with the maximum installed power as slack Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- network : :class:`pypsa.Network Overall container of PyPSA """ old_slack = network.generators.index[network. generators.control == 'Slack'][0] # check if old slack was PV or PQ control: if network.generators.p_nom[old_slack] > 50 and network.generators.\ carrier[old_slack] in ('solar', 'wind'): old_control = 'PQ' elif network.generators.p_nom[old_slack] > 50 and network.generators.\ carrier[old_slack] not in ('solar', 'wind'): old_control = 'PV' elif network.generators.p_nom[old_slack] < 50: old_control = 'PQ' old_gens = network.generators gens_summed = network.generators_t.p.sum() old_gens['p_summed'] = gens_summed max_gen_buses_index = old_gens.groupby(['bus']).agg( {'p_summed': np.sum}).p_summed.sort_values().index for bus_iter in range(1, len(max_gen_buses_index) - 1): if old_gens[(network. generators['bus'] == max_gen_buses_index[-bus_iter]) & (network.generators['control'] == 'PV')].empty: continue else: new_slack_bus = max_gen_buses_index[-bus_iter] break network.generators = network.generators.drop('p_summed', 1) new_slack_gen = network.generators.\ p_nom[(network.generators['bus'] == new_slack_bus) & ( network.generators['control'] == 'PV')].sort_values().index[-1] network.generators = network.generators.set_value( old_slack, 'control', old_control) network.generators = network.generators.set_value( new_slack_gen, 'control', 'Slack') return network
python
def set_slack(network): """ Function that chosses the bus with the maximum installed power as slack Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- network : :class:`pypsa.Network Overall container of PyPSA """ old_slack = network.generators.index[network. generators.control == 'Slack'][0] # check if old slack was PV or PQ control: if network.generators.p_nom[old_slack] > 50 and network.generators.\ carrier[old_slack] in ('solar', 'wind'): old_control = 'PQ' elif network.generators.p_nom[old_slack] > 50 and network.generators.\ carrier[old_slack] not in ('solar', 'wind'): old_control = 'PV' elif network.generators.p_nom[old_slack] < 50: old_control = 'PQ' old_gens = network.generators gens_summed = network.generators_t.p.sum() old_gens['p_summed'] = gens_summed max_gen_buses_index = old_gens.groupby(['bus']).agg( {'p_summed': np.sum}).p_summed.sort_values().index for bus_iter in range(1, len(max_gen_buses_index) - 1): if old_gens[(network. generators['bus'] == max_gen_buses_index[-bus_iter]) & (network.generators['control'] == 'PV')].empty: continue else: new_slack_bus = max_gen_buses_index[-bus_iter] break network.generators = network.generators.drop('p_summed', 1) new_slack_gen = network.generators.\ p_nom[(network.generators['bus'] == new_slack_bus) & ( network.generators['control'] == 'PV')].sort_values().index[-1] network.generators = network.generators.set_value( old_slack, 'control', old_control) network.generators = network.generators.set_value( new_slack_gen, 'control', 'Slack') return network
[ "def", "set_slack", "(", "network", ")", ":", "old_slack", "=", "network", ".", "generators", ".", "index", "[", "network", ".", "generators", ".", "control", "==", "'Slack'", "]", "[", "0", "]", "# check if old slack was PV or PQ control:", "if", "network", "...
Function that chosses the bus with the maximum installed power as slack Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- network : :class:`pypsa.Network Overall container of PyPSA
[ "Function", "that", "chosses", "the", "bus", "with", "the", "maximum", "installed", "power", "as", "slack" ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/utilities.py#L699-L754
train
40,478
openego/eTraGo
etrago/tools/utilities.py
ramp_limits
def ramp_limits(network): """ Add ramping constraints to thermal power plants. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- """ carrier = ['coal', 'biomass', 'gas', 'oil', 'waste', 'lignite', 'uranium', 'geothermal'] data = {'start_up_cost':[77, 57, 42, 57, 57, 77, 50, 57], #€/MW 'start_up_fuel':[4.3, 2.8, 1.45, 2.8, 2.8, 4.3, 16.7, 2.8], #MWh/MW 'min_up_time':[5, 2, 3, 2, 2, 5, 12, 2], 'min_down_time':[7, 2, 2, 2, 2, 7, 17, 2], # ============================================================================= # 'ramp_limit_start_up':[0.4, 0.4, 0.4, 0.4, 0.4, 0.6, 0.5, 0.4], # 'ramp_limit_shut_down':[0.4, 0.4, 0.4, 0.4, 0.4, 0.6, 0.5, 0.4] # ============================================================================= 'p_min_pu':[0.33, 0.38, 0.4, 0.38, 0.38, 0.5, 0.45, 0.38] } df = pd.DataFrame(data, index=carrier) fuel_costs = network.generators.marginal_cost.groupby( network.generators.carrier).mean()[carrier] df['start_up_fuel'] = df['start_up_fuel'] * fuel_costs df['start_up_cost'] = df['start_up_cost'] + df['start_up_fuel'] df.drop('start_up_fuel', axis=1, inplace=True) for tech in df.index: for limit in df.columns: network.generators.loc[network.generators.carrier == tech, limit] = df.loc[tech, limit] network.generators.start_up_cost = network.generators.start_up_cost\ *network.generators.p_nom network.generators.committable = True
python
def ramp_limits(network): """ Add ramping constraints to thermal power plants. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- """ carrier = ['coal', 'biomass', 'gas', 'oil', 'waste', 'lignite', 'uranium', 'geothermal'] data = {'start_up_cost':[77, 57, 42, 57, 57, 77, 50, 57], #€/MW 'start_up_fuel':[4.3, 2.8, 1.45, 2.8, 2.8, 4.3, 16.7, 2.8], #MWh/MW 'min_up_time':[5, 2, 3, 2, 2, 5, 12, 2], 'min_down_time':[7, 2, 2, 2, 2, 7, 17, 2], # ============================================================================= # 'ramp_limit_start_up':[0.4, 0.4, 0.4, 0.4, 0.4, 0.6, 0.5, 0.4], # 'ramp_limit_shut_down':[0.4, 0.4, 0.4, 0.4, 0.4, 0.6, 0.5, 0.4] # ============================================================================= 'p_min_pu':[0.33, 0.38, 0.4, 0.38, 0.38, 0.5, 0.45, 0.38] } df = pd.DataFrame(data, index=carrier) fuel_costs = network.generators.marginal_cost.groupby( network.generators.carrier).mean()[carrier] df['start_up_fuel'] = df['start_up_fuel'] * fuel_costs df['start_up_cost'] = df['start_up_cost'] + df['start_up_fuel'] df.drop('start_up_fuel', axis=1, inplace=True) for tech in df.index: for limit in df.columns: network.generators.loc[network.generators.carrier == tech, limit] = df.loc[tech, limit] network.generators.start_up_cost = network.generators.start_up_cost\ *network.generators.p_nom network.generators.committable = True
[ "def", "ramp_limits", "(", "network", ")", ":", "carrier", "=", "[", "'coal'", ",", "'biomass'", ",", "'gas'", ",", "'oil'", ",", "'waste'", ",", "'lignite'", ",", "'uranium'", ",", "'geothermal'", "]", "data", "=", "{", "'start_up_cost'", ":", "[", "77"...
Add ramping constraints to thermal power plants. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns -------
[ "Add", "ramping", "constraints", "to", "thermal", "power", "plants", "." ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/utilities.py#L1535-L1571
train
40,479
openego/eTraGo
etrago/tools/utilities.py
get_args_setting
def get_args_setting(args, jsonpath='scenario_setting.json'): """ Get and open json file with scenaio settings of eTraGo ``args``. The settings incluedes all eTraGo specific settings of arguments and parameters for a reproducible calculation. Parameters ---------- json_file : str Default: ``scenario_setting.json`` Name of scenario setting json file Returns ------- args : dict Dictionary of json file """ if not jsonpath == None: with open(jsonpath) as f: args = json.load(f) return args
python
def get_args_setting(args, jsonpath='scenario_setting.json'): """ Get and open json file with scenaio settings of eTraGo ``args``. The settings incluedes all eTraGo specific settings of arguments and parameters for a reproducible calculation. Parameters ---------- json_file : str Default: ``scenario_setting.json`` Name of scenario setting json file Returns ------- args : dict Dictionary of json file """ if not jsonpath == None: with open(jsonpath) as f: args = json.load(f) return args
[ "def", "get_args_setting", "(", "args", ",", "jsonpath", "=", "'scenario_setting.json'", ")", ":", "if", "not", "jsonpath", "==", "None", ":", "with", "open", "(", "jsonpath", ")", "as", "f", ":", "args", "=", "json", ".", "load", "(", "f", ")", "retur...
Get and open json file with scenaio settings of eTraGo ``args``. The settings incluedes all eTraGo specific settings of arguments and parameters for a reproducible calculation. Parameters ---------- json_file : str Default: ``scenario_setting.json`` Name of scenario setting json file Returns ------- args : dict Dictionary of json file
[ "Get", "and", "open", "json", "file", "with", "scenaio", "settings", "of", "eTraGo", "args", ".", "The", "settings", "incluedes", "all", "eTraGo", "specific", "settings", "of", "arguments", "and", "parameters", "for", "a", "reproducible", "calculation", "." ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/utilities.py#L1574-L1597
train
40,480
openego/eTraGo
etrago/tools/utilities.py
set_line_country_tags
def set_line_country_tags(network): """ Set country tag for AC- and DC-lines. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA """ transborder_lines_0 = network.lines[network.lines['bus0'].isin( network.buses.index[network.buses['country_code'] != 'DE'])].index transborder_lines_1 = network.lines[network.lines['bus1'].isin( network.buses.index[network.buses['country_code']!= 'DE'])].index #set country tag for lines network.lines.loc[transborder_lines_0, 'country'] = \ network.buses.loc[network.lines.loc[transborder_lines_0, 'bus0']\ .values, 'country_code'].values network.lines.loc[transborder_lines_1, 'country'] = \ network.buses.loc[network.lines.loc[transborder_lines_1, 'bus1']\ .values, 'country_code'].values network.lines['country'].fillna('DE', inplace=True) doubles = list(set(transborder_lines_0.intersection(transborder_lines_1))) for line in doubles: c_bus0 = network.buses.loc[network.lines.loc[line, 'bus0'], 'country'] c_bus1 = network.buses.loc[network.lines.loc[line, 'bus1'], 'country'] network.lines.loc[line, 'country'] = '{}{}'.format(c_bus0, c_bus1) transborder_links_0 = network.links[network.links['bus0'].isin( network.buses.index[network.buses['country_code']!= 'DE'])].index transborder_links_1 = network.links[network.links['bus1'].isin( network.buses.index[network.buses['country_code'] != 'DE'])].index #set country tag for links network.links.loc[transborder_links_0, 'country'] = \ network.buses.loc[network.links.loc[transborder_links_0, 'bus0']\ .values, 'country_code'].values network.links.loc[transborder_links_1, 'country'] = \ network.buses.loc[network.links.loc[transborder_links_1, 'bus1']\ .values, 'country_code'].values network.links['country'].fillna('DE', inplace=True) doubles = list(set(transborder_links_0.intersection(transborder_links_1))) for link in doubles: c_bus0 = network.buses.loc[network.links.loc[link, 'bus0'], 'country'] c_bus1 = network.buses.loc[network.links.loc[link, 'bus1'], 'country'] network.links.loc[link, 'country'] = '{}{}'.format(c_bus0, c_bus1)
python
def set_line_country_tags(network): """ Set country tag for AC- and DC-lines. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA """ transborder_lines_0 = network.lines[network.lines['bus0'].isin( network.buses.index[network.buses['country_code'] != 'DE'])].index transborder_lines_1 = network.lines[network.lines['bus1'].isin( network.buses.index[network.buses['country_code']!= 'DE'])].index #set country tag for lines network.lines.loc[transborder_lines_0, 'country'] = \ network.buses.loc[network.lines.loc[transborder_lines_0, 'bus0']\ .values, 'country_code'].values network.lines.loc[transborder_lines_1, 'country'] = \ network.buses.loc[network.lines.loc[transborder_lines_1, 'bus1']\ .values, 'country_code'].values network.lines['country'].fillna('DE', inplace=True) doubles = list(set(transborder_lines_0.intersection(transborder_lines_1))) for line in doubles: c_bus0 = network.buses.loc[network.lines.loc[line, 'bus0'], 'country'] c_bus1 = network.buses.loc[network.lines.loc[line, 'bus1'], 'country'] network.lines.loc[line, 'country'] = '{}{}'.format(c_bus0, c_bus1) transborder_links_0 = network.links[network.links['bus0'].isin( network.buses.index[network.buses['country_code']!= 'DE'])].index transborder_links_1 = network.links[network.links['bus1'].isin( network.buses.index[network.buses['country_code'] != 'DE'])].index #set country tag for links network.links.loc[transborder_links_0, 'country'] = \ network.buses.loc[network.links.loc[transborder_links_0, 'bus0']\ .values, 'country_code'].values network.links.loc[transborder_links_1, 'country'] = \ network.buses.loc[network.links.loc[transborder_links_1, 'bus1']\ .values, 'country_code'].values network.links['country'].fillna('DE', inplace=True) doubles = list(set(transborder_links_0.intersection(transborder_links_1))) for link in doubles: c_bus0 = network.buses.loc[network.links.loc[link, 'bus0'], 'country'] c_bus1 = network.buses.loc[network.links.loc[link, 'bus1'], 'country'] network.links.loc[link, 'country'] = '{}{}'.format(c_bus0, c_bus1)
[ "def", "set_line_country_tags", "(", "network", ")", ":", "transborder_lines_0", "=", "network", ".", "lines", "[", "network", ".", "lines", "[", "'bus0'", "]", ".", "isin", "(", "network", ".", "buses", ".", "index", "[", "network", ".", "buses", "[", "...
Set country tag for AC- and DC-lines. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA
[ "Set", "country", "tag", "for", "AC", "-", "and", "DC", "-", "lines", "." ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/utilities.py#L1600-L1649
train
40,481
openego/eTraGo
etrago/tools/utilities.py
max_line_ext
def max_line_ext(network, snapshots, share=1.01): """ Sets maximal share of overall network extension as extra functionality in LOPF Parameters ---------- share: float Maximal share of network extension in p.u. """ lines_snom = network.lines.s_nom.sum() links_pnom = network.links.p_nom.sum() def _rule(m): lines_opt = sum(m.passive_branch_s_nom[index] for index in m.passive_branch_s_nom_index) links_opt = sum(m.link_p_nom[index] for index in m.link_p_nom_index) return (lines_opt + links_opt) <= (lines_snom + links_pnom) * share network.model.max_line_ext = Constraint(rule=_rule)
python
def max_line_ext(network, snapshots, share=1.01): """ Sets maximal share of overall network extension as extra functionality in LOPF Parameters ---------- share: float Maximal share of network extension in p.u. """ lines_snom = network.lines.s_nom.sum() links_pnom = network.links.p_nom.sum() def _rule(m): lines_opt = sum(m.passive_branch_s_nom[index] for index in m.passive_branch_s_nom_index) links_opt = sum(m.link_p_nom[index] for index in m.link_p_nom_index) return (lines_opt + links_opt) <= (lines_snom + links_pnom) * share network.model.max_line_ext = Constraint(rule=_rule)
[ "def", "max_line_ext", "(", "network", ",", "snapshots", ",", "share", "=", "1.01", ")", ":", "lines_snom", "=", "network", ".", "lines", ".", "s_nom", ".", "sum", "(", ")", "links_pnom", "=", "network", ".", "links", ".", "p_nom", ".", "sum", "(", "...
Sets maximal share of overall network extension as extra functionality in LOPF Parameters ---------- share: float Maximal share of network extension in p.u.
[ "Sets", "maximal", "share", "of", "overall", "network", "extension", "as", "extra", "functionality", "in", "LOPF" ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/utilities.py#L1794-L1820
train
40,482
openego/eTraGo
etrago/tools/utilities.py
min_renewable_share
def min_renewable_share(network, snapshots, share=0.72): """ Sets minimal renewable share of generation as extra functionality in LOPF Parameters ---------- share: float Minimal share of renewable generation in p.u. """ renewables = ['wind_onshore', 'wind_offshore', 'biomass', 'solar', 'run_of_river'] res = list(network.generators.index[ network.generators.carrier.isin(renewables)]) total = list(network.generators.index) snapshots = network.snapshots def _rule(m): """ """ renewable_production = sum(m.generator_p[gen, sn] for gen in res for sn in snapshots) total_production = sum(m.generator_p[gen, sn] for gen in total for sn in snapshots) return (renewable_production >= total_production * share) network.model.min_renewable_share = Constraint(rule=_rule)
python
def min_renewable_share(network, snapshots, share=0.72): """ Sets minimal renewable share of generation as extra functionality in LOPF Parameters ---------- share: float Minimal share of renewable generation in p.u. """ renewables = ['wind_onshore', 'wind_offshore', 'biomass', 'solar', 'run_of_river'] res = list(network.generators.index[ network.generators.carrier.isin(renewables)]) total = list(network.generators.index) snapshots = network.snapshots def _rule(m): """ """ renewable_production = sum(m.generator_p[gen, sn] for gen in res for sn in snapshots) total_production = sum(m.generator_p[gen, sn] for gen in total for sn in snapshots) return (renewable_production >= total_production * share) network.model.min_renewable_share = Constraint(rule=_rule)
[ "def", "min_renewable_share", "(", "network", ",", "snapshots", ",", "share", "=", "0.72", ")", ":", "renewables", "=", "[", "'wind_onshore'", ",", "'wind_offshore'", ",", "'biomass'", ",", "'solar'", ",", "'run_of_river'", "]", "res", "=", "list", "(", "net...
Sets minimal renewable share of generation as extra functionality in LOPF Parameters ---------- share: float Minimal share of renewable generation in p.u.
[ "Sets", "minimal", "renewable", "share", "of", "generation", "as", "extra", "functionality", "in", "LOPF" ]
2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/utilities.py#L1822-L1852
train
40,483
Cog-Creators/Red-Lavalink
lavalink/node.py
get_node
def get_node(guild_id: int, ignore_ready_status: bool = False) -> Node: """ Gets a node based on a guild ID, useful for noding separation. If the guild ID does not already have a node association, the least used node is returned. Skips over nodes that are not yet ready. Parameters ---------- guild_id : int ignore_ready_status : bool Returns ------- Node """ guild_count = 1e10 least_used = None for node in _nodes: guild_ids = node.player_manager.guild_ids if ignore_ready_status is False and not node.ready.is_set(): continue elif len(guild_ids) < guild_count: guild_count = len(guild_ids) least_used = node if guild_id in guild_ids: return node if least_used is None: raise IndexError("No nodes found.") return least_used
python
def get_node(guild_id: int, ignore_ready_status: bool = False) -> Node: """ Gets a node based on a guild ID, useful for noding separation. If the guild ID does not already have a node association, the least used node is returned. Skips over nodes that are not yet ready. Parameters ---------- guild_id : int ignore_ready_status : bool Returns ------- Node """ guild_count = 1e10 least_used = None for node in _nodes: guild_ids = node.player_manager.guild_ids if ignore_ready_status is False and not node.ready.is_set(): continue elif len(guild_ids) < guild_count: guild_count = len(guild_ids) least_used = node if guild_id in guild_ids: return node if least_used is None: raise IndexError("No nodes found.") return least_used
[ "def", "get_node", "(", "guild_id", ":", "int", ",", "ignore_ready_status", ":", "bool", "=", "False", ")", "->", "Node", ":", "guild_count", "=", "1e10", "least_used", "=", "None", "for", "node", "in", "_nodes", ":", "guild_ids", "=", "node", ".", "play...
Gets a node based on a guild ID, useful for noding separation. If the guild ID does not already have a node association, the least used node is returned. Skips over nodes that are not yet ready. Parameters ---------- guild_id : int ignore_ready_status : bool Returns ------- Node
[ "Gets", "a", "node", "based", "on", "a", "guild", "ID", "useful", "for", "noding", "separation", ".", "If", "the", "guild", "ID", "does", "not", "already", "have", "a", "node", "association", "the", "least", "used", "node", "is", "returned", ".", "Skips"...
5b3fc6eb31ee5db8bd2b633a523cf69749957111
https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/node.py#L335-L368
train
40,484
Cog-Creators/Red-Lavalink
lavalink/node.py
join_voice
async def join_voice(guild_id: int, channel_id: int): """ Joins a voice channel by ID's. Parameters ---------- guild_id : int channel_id : int """ node = get_node(guild_id) voice_ws = node.get_voice_ws(guild_id) await voice_ws.voice_state(guild_id, channel_id)
python
async def join_voice(guild_id: int, channel_id: int): """ Joins a voice channel by ID's. Parameters ---------- guild_id : int channel_id : int """ node = get_node(guild_id) voice_ws = node.get_voice_ws(guild_id) await voice_ws.voice_state(guild_id, channel_id)
[ "async", "def", "join_voice", "(", "guild_id", ":", "int", ",", "channel_id", ":", "int", ")", ":", "node", "=", "get_node", "(", "guild_id", ")", "voice_ws", "=", "node", ".", "get_voice_ws", "(", "guild_id", ")", "await", "voice_ws", ".", "voice_state", ...
Joins a voice channel by ID's. Parameters ---------- guild_id : int channel_id : int
[ "Joins", "a", "voice", "channel", "by", "ID", "s", "." ]
5b3fc6eb31ee5db8bd2b633a523cf69749957111
https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/node.py#L371-L382
train
40,485
Cog-Creators/Red-Lavalink
lavalink/node.py
Node.connect
async def connect(self, timeout=None): """ Connects to the Lavalink player event websocket. Parameters ---------- timeout : int Time after which to timeout on attempting to connect to the Lavalink websocket, ``None`` is considered never, but the underlying code may stop trying past a certain point. Raises ------ asyncio.TimeoutError If the websocket failed to connect after the given time. """ self._is_shutdown = False combo_uri = "ws://{}:{}".format(self.host, self.rest) uri = "ws://{}:{}".format(self.host, self.port) log.debug( "Lavalink WS connecting to %s or %s with headers %s", combo_uri, uri, self.headers ) tasks = tuple({self._multi_try_connect(u) for u in (combo_uri, uri)}) for task in asyncio.as_completed(tasks, timeout=timeout): with contextlib.suppress(Exception): if await cast(Awaitable[Optional[websockets.WebSocketClientProtocol]], task): break else: raise asyncio.TimeoutError log.debug("Creating Lavalink WS listener.") self._listener_task = self.loop.create_task(self.listener()) for data in self._queue: await self.send(data) self.ready.set() self.update_state(NodeState.READY)
python
async def connect(self, timeout=None): """ Connects to the Lavalink player event websocket. Parameters ---------- timeout : int Time after which to timeout on attempting to connect to the Lavalink websocket, ``None`` is considered never, but the underlying code may stop trying past a certain point. Raises ------ asyncio.TimeoutError If the websocket failed to connect after the given time. """ self._is_shutdown = False combo_uri = "ws://{}:{}".format(self.host, self.rest) uri = "ws://{}:{}".format(self.host, self.port) log.debug( "Lavalink WS connecting to %s or %s with headers %s", combo_uri, uri, self.headers ) tasks = tuple({self._multi_try_connect(u) for u in (combo_uri, uri)}) for task in asyncio.as_completed(tasks, timeout=timeout): with contextlib.suppress(Exception): if await cast(Awaitable[Optional[websockets.WebSocketClientProtocol]], task): break else: raise asyncio.TimeoutError log.debug("Creating Lavalink WS listener.") self._listener_task = self.loop.create_task(self.listener()) for data in self._queue: await self.send(data) self.ready.set() self.update_state(NodeState.READY)
[ "async", "def", "connect", "(", "self", ",", "timeout", "=", "None", ")", ":", "self", ".", "_is_shutdown", "=", "False", "combo_uri", "=", "\"ws://{}:{}\"", ".", "format", "(", "self", ".", "host", ",", "self", ".", "rest", ")", "uri", "=", "\"ws://{}...
Connects to the Lavalink player event websocket. Parameters ---------- timeout : int Time after which to timeout on attempting to connect to the Lavalink websocket, ``None`` is considered never, but the underlying code may stop trying past a certain point. Raises ------ asyncio.TimeoutError If the websocket failed to connect after the given time.
[ "Connects", "to", "the", "Lavalink", "player", "event", "websocket", "." ]
5b3fc6eb31ee5db8bd2b633a523cf69749957111
https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/node.py#L92-L133
train
40,486
Cog-Creators/Red-Lavalink
lavalink/node.py
Node.listener
async def listener(self): """ Listener task for receiving ops from Lavalink. """ while self._ws.open and self._is_shutdown is False: try: data = json.loads(await self._ws.recv()) except websockets.ConnectionClosed: break raw_op = data.get("op") try: op = LavalinkIncomingOp(raw_op) except ValueError: socket_log.debug("Received unknown op: %s", data) else: socket_log.debug("Received known op: %s", data) self.loop.create_task(self._handle_op(op, data)) self.ready.clear() log.debug("Listener exited: ws %s SHUTDOWN %s.", self._ws.open, self._is_shutdown) self.loop.create_task(self._reconnect())
python
async def listener(self): """ Listener task for receiving ops from Lavalink. """ while self._ws.open and self._is_shutdown is False: try: data = json.loads(await self._ws.recv()) except websockets.ConnectionClosed: break raw_op = data.get("op") try: op = LavalinkIncomingOp(raw_op) except ValueError: socket_log.debug("Received unknown op: %s", data) else: socket_log.debug("Received known op: %s", data) self.loop.create_task(self._handle_op(op, data)) self.ready.clear() log.debug("Listener exited: ws %s SHUTDOWN %s.", self._ws.open, self._is_shutdown) self.loop.create_task(self._reconnect())
[ "async", "def", "listener", "(", "self", ")", ":", "while", "self", ".", "_ws", ".", "open", "and", "self", ".", "_is_shutdown", "is", "False", ":", "try", ":", "data", "=", "json", ".", "loads", "(", "await", "self", ".", "_ws", ".", "recv", "(", ...
Listener task for receiving ops from Lavalink.
[ "Listener", "task", "for", "receiving", "ops", "from", "Lavalink", "." ]
5b3fc6eb31ee5db8bd2b633a523cf69749957111
https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/node.py#L164-L185
train
40,487
Cog-Creators/Red-Lavalink
lavalink/node.py
Node.join_voice_channel
async def join_voice_channel(self, guild_id, channel_id): """ Alternative way to join a voice channel if node is known. """ voice_ws = self.get_voice_ws(guild_id) await voice_ws.voice_state(guild_id, channel_id)
python
async def join_voice_channel(self, guild_id, channel_id): """ Alternative way to join a voice channel if node is known. """ voice_ws = self.get_voice_ws(guild_id) await voice_ws.voice_state(guild_id, channel_id)
[ "async", "def", "join_voice_channel", "(", "self", ",", "guild_id", ",", "channel_id", ")", ":", "voice_ws", "=", "self", ".", "get_voice_ws", "(", "guild_id", ")", "await", "voice_ws", ".", "voice_state", "(", "guild_id", ",", "channel_id", ")" ]
Alternative way to join a voice channel if node is known.
[ "Alternative", "way", "to", "join", "a", "voice", "channel", "if", "node", "is", "known", "." ]
5b3fc6eb31ee5db8bd2b633a523cf69749957111
https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/node.py#L249-L254
train
40,488
Cog-Creators/Red-Lavalink
lavalink/node.py
Node.disconnect
async def disconnect(self): """ Shuts down and disconnects the websocket. """ self._is_shutdown = True self.ready.clear() self.update_state(NodeState.DISCONNECTING) await self.player_manager.disconnect() if self._ws is not None and self._ws.open: await self._ws.close() if self._listener_task is not None and not self.loop.is_closed(): self._listener_task.cancel() self._state_handlers = [] _nodes.remove(self) log.debug("Shutdown Lavalink WS.")
python
async def disconnect(self): """ Shuts down and disconnects the websocket. """ self._is_shutdown = True self.ready.clear() self.update_state(NodeState.DISCONNECTING) await self.player_manager.disconnect() if self._ws is not None and self._ws.open: await self._ws.close() if self._listener_task is not None and not self.loop.is_closed(): self._listener_task.cancel() self._state_handlers = [] _nodes.remove(self) log.debug("Shutdown Lavalink WS.")
[ "async", "def", "disconnect", "(", "self", ")", ":", "self", ".", "_is_shutdown", "=", "True", "self", ".", "ready", ".", "clear", "(", ")", "self", ".", "update_state", "(", "NodeState", ".", "DISCONNECTING", ")", "await", "self", ".", "player_manager", ...
Shuts down and disconnects the websocket.
[ "Shuts", "down", "and", "disconnects", "the", "websocket", "." ]
5b3fc6eb31ee5db8bd2b633a523cf69749957111
https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/node.py#L256-L276
train
40,489
DLR-RM/RAFCON
source/rafcon/core/states/barrier_concurrency_state.py
BarrierConcurrencyState.run
def run(self): """ This defines the sequence of actions that are taken when the barrier concurrency state is executed :return: """ logger.debug("Starting execution of {0}{1}".format(self, " (backwards)" if self.backward_execution else "")) self.setup_run() # data to be accessed by the decider state child_errors = {} final_outcomes_dict = {} decider_state = self.states[UNIQUE_DECIDER_STATE_ID] try: concurrency_history_item = self.setup_forward_or_backward_execution() self.start_child_states(concurrency_history_item, decider_state) # print("bcs1") ####################################################### # wait for all child threads to finish ####################################################### for history_index, state in enumerate(self.states.values()): # skip the decider state if state is not decider_state: self.join_state(state, history_index, concurrency_history_item) self.add_state_execution_output_to_scoped_data(state.output_data, state) self.update_scoped_variables_with_output_dictionary(state.output_data, state) # save the errors of the child state executions for the decider state if 'error' in state.output_data: child_errors[state.state_id] = (state.name, state.output_data['error']) final_outcomes_dict[state.state_id] = (state.name, state.final_outcome) # print("bcs2") ####################################################### # handle backward execution case ####################################################### if self.backward_execution: # print("bcs2.1.") return self.finalize_backward_execution() else: # print("bcs2.2.") self.backward_execution = False # print("bcs3") ####################################################### # execute decider state ####################################################### decider_state_error = self.run_decider_state(decider_state, child_errors, final_outcomes_dict) # print("bcs4") ####################################################### # handle no transition ####################################################### transition = self.get_transition_for_outcome(decider_state, decider_state.final_outcome) if transition is None: # final outcome is set here transition = self.handle_no_transition(decider_state) # if the transition is still None, then the child_state was preempted or aborted, in this case return decider_state.state_execution_status = StateExecutionStatus.INACTIVE # print("bcs5") if transition is None: self.output_data["error"] = RuntimeError("state aborted") else: if decider_state_error: self.output_data["error"] = decider_state_error self.final_outcome = self.outcomes[transition.to_outcome] # print("bcs6") return self.finalize_concurrency_state(self.final_outcome) except Exception as e: logger.error("{0} had an internal error: {1}\n{2}".format(self, str(e), str(traceback.format_exc()))) self.output_data["error"] = e self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE return self.finalize(Outcome(-1, "aborted"))
python
def run(self): """ This defines the sequence of actions that are taken when the barrier concurrency state is executed :return: """ logger.debug("Starting execution of {0}{1}".format(self, " (backwards)" if self.backward_execution else "")) self.setup_run() # data to be accessed by the decider state child_errors = {} final_outcomes_dict = {} decider_state = self.states[UNIQUE_DECIDER_STATE_ID] try: concurrency_history_item = self.setup_forward_or_backward_execution() self.start_child_states(concurrency_history_item, decider_state) # print("bcs1") ####################################################### # wait for all child threads to finish ####################################################### for history_index, state in enumerate(self.states.values()): # skip the decider state if state is not decider_state: self.join_state(state, history_index, concurrency_history_item) self.add_state_execution_output_to_scoped_data(state.output_data, state) self.update_scoped_variables_with_output_dictionary(state.output_data, state) # save the errors of the child state executions for the decider state if 'error' in state.output_data: child_errors[state.state_id] = (state.name, state.output_data['error']) final_outcomes_dict[state.state_id] = (state.name, state.final_outcome) # print("bcs2") ####################################################### # handle backward execution case ####################################################### if self.backward_execution: # print("bcs2.1.") return self.finalize_backward_execution() else: # print("bcs2.2.") self.backward_execution = False # print("bcs3") ####################################################### # execute decider state ####################################################### decider_state_error = self.run_decider_state(decider_state, child_errors, final_outcomes_dict) # print("bcs4") ####################################################### # handle no transition ####################################################### transition = self.get_transition_for_outcome(decider_state, decider_state.final_outcome) if transition is None: # final outcome is set here transition = self.handle_no_transition(decider_state) # if the transition is still None, then the child_state was preempted or aborted, in this case return decider_state.state_execution_status = StateExecutionStatus.INACTIVE # print("bcs5") if transition is None: self.output_data["error"] = RuntimeError("state aborted") else: if decider_state_error: self.output_data["error"] = decider_state_error self.final_outcome = self.outcomes[transition.to_outcome] # print("bcs6") return self.finalize_concurrency_state(self.final_outcome) except Exception as e: logger.error("{0} had an internal error: {1}\n{2}".format(self, str(e), str(traceback.format_exc()))) self.output_data["error"] = e self.state_execution_status = StateExecutionStatus.WAIT_FOR_NEXT_STATE return self.finalize(Outcome(-1, "aborted"))
[ "def", "run", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Starting execution of {0}{1}\"", ".", "format", "(", "self", ",", "\" (backwards)\"", "if", "self", ".", "backward_execution", "else", "\"\"", ")", ")", "self", ".", "setup_run", "(", ")", ...
This defines the sequence of actions that are taken when the barrier concurrency state is executed :return:
[ "This", "defines", "the", "sequence", "of", "actions", "that", "are", "taken", "when", "the", "barrier", "concurrency", "state", "is", "executed" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/barrier_concurrency_state.py#L100-L181
train
40,490
DLR-RM/RAFCON
source/rafcon/core/states/barrier_concurrency_state.py
BarrierConcurrencyState.run_decider_state
def run_decider_state(self, decider_state, child_errors, final_outcomes_dict): """ Runs the decider state of the barrier concurrency state. The decider state decides on which outcome the barrier concurrency is left. :param decider_state: the decider state of the barrier concurrency state :param child_errors: error of the concurrent branches :param final_outcomes_dict: dictionary of all outcomes of the concurrent branches :return: """ decider_state.state_execution_status = StateExecutionStatus.ACTIVE # forward the decider specific data decider_state.child_errors = child_errors decider_state.final_outcomes_dict = final_outcomes_dict # standard state execution decider_state.input_data = self.get_inputs_for_state(decider_state) decider_state.output_data = self.create_output_dictionary_for_state(decider_state) decider_state.start(self.execution_history, backward_execution=False) decider_state.join() decider_state_error = None if decider_state.final_outcome.outcome_id == -1: if 'error' in decider_state.output_data: decider_state_error = decider_state.output_data['error'] # standard output data processing self.add_state_execution_output_to_scoped_data(decider_state.output_data, decider_state) self.update_scoped_variables_with_output_dictionary(decider_state.output_data, decider_state) return decider_state_error
python
def run_decider_state(self, decider_state, child_errors, final_outcomes_dict): """ Runs the decider state of the barrier concurrency state. The decider state decides on which outcome the barrier concurrency is left. :param decider_state: the decider state of the barrier concurrency state :param child_errors: error of the concurrent branches :param final_outcomes_dict: dictionary of all outcomes of the concurrent branches :return: """ decider_state.state_execution_status = StateExecutionStatus.ACTIVE # forward the decider specific data decider_state.child_errors = child_errors decider_state.final_outcomes_dict = final_outcomes_dict # standard state execution decider_state.input_data = self.get_inputs_for_state(decider_state) decider_state.output_data = self.create_output_dictionary_for_state(decider_state) decider_state.start(self.execution_history, backward_execution=False) decider_state.join() decider_state_error = None if decider_state.final_outcome.outcome_id == -1: if 'error' in decider_state.output_data: decider_state_error = decider_state.output_data['error'] # standard output data processing self.add_state_execution_output_to_scoped_data(decider_state.output_data, decider_state) self.update_scoped_variables_with_output_dictionary(decider_state.output_data, decider_state) return decider_state_error
[ "def", "run_decider_state", "(", "self", ",", "decider_state", ",", "child_errors", ",", "final_outcomes_dict", ")", ":", "decider_state", ".", "state_execution_status", "=", "StateExecutionStatus", ".", "ACTIVE", "# forward the decider specific data", "decider_state", ".",...
Runs the decider state of the barrier concurrency state. The decider state decides on which outcome the barrier concurrency is left. :param decider_state: the decider state of the barrier concurrency state :param child_errors: error of the concurrent branches :param final_outcomes_dict: dictionary of all outcomes of the concurrent branches :return:
[ "Runs", "the", "decider", "state", "of", "the", "barrier", "concurrency", "state", ".", "The", "decider", "state", "decides", "on", "which", "outcome", "the", "barrier", "concurrency", "is", "left", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/barrier_concurrency_state.py#L183-L208
train
40,491
DLR-RM/RAFCON
source/rafcon/core/states/barrier_concurrency_state.py
BarrierConcurrencyState._check_transition_validity
def _check_transition_validity(self, check_transition): """ Transition of BarrierConcurrencyStates must least fulfill the condition of a ContainerState. Start transitions are forbidden in the ConcurrencyState. :param check_transition: the transition to check for validity :return: """ valid, message = super(BarrierConcurrencyState, self)._check_transition_validity(check_transition) if not valid: return False, message # Only the following transitions are allowed in barrier concurrency states: # - Transitions from the decider state to the parent state\n" # - Transitions from not-decider states to the decider state\n" # - Transitions from not_decider states from aborted/preempted outcomes to the # aborted/preempted outcome of the parent from_state_id = check_transition.from_state to_state_id = check_transition.to_state from_outcome_id = check_transition.from_outcome to_outcome_id = check_transition.to_outcome if from_state_id == UNIQUE_DECIDER_STATE_ID: if to_state_id != self.state_id: return False, "Transition from the decider state must go to the parent state" else: if to_state_id != UNIQUE_DECIDER_STATE_ID: if from_outcome_id not in [-2, -1] or to_outcome_id not in [-2, -1]: return False, "Transition from this state must go to the decider state. The only exception are " \ "transition from aborted/preempted to the parent aborted/preempted outcomes" return True, message
python
def _check_transition_validity(self, check_transition): """ Transition of BarrierConcurrencyStates must least fulfill the condition of a ContainerState. Start transitions are forbidden in the ConcurrencyState. :param check_transition: the transition to check for validity :return: """ valid, message = super(BarrierConcurrencyState, self)._check_transition_validity(check_transition) if not valid: return False, message # Only the following transitions are allowed in barrier concurrency states: # - Transitions from the decider state to the parent state\n" # - Transitions from not-decider states to the decider state\n" # - Transitions from not_decider states from aborted/preempted outcomes to the # aborted/preempted outcome of the parent from_state_id = check_transition.from_state to_state_id = check_transition.to_state from_outcome_id = check_transition.from_outcome to_outcome_id = check_transition.to_outcome if from_state_id == UNIQUE_DECIDER_STATE_ID: if to_state_id != self.state_id: return False, "Transition from the decider state must go to the parent state" else: if to_state_id != UNIQUE_DECIDER_STATE_ID: if from_outcome_id not in [-2, -1] or to_outcome_id not in [-2, -1]: return False, "Transition from this state must go to the decider state. The only exception are " \ "transition from aborted/preempted to the parent aborted/preempted outcomes" return True, message
[ "def", "_check_transition_validity", "(", "self", ",", "check_transition", ")", ":", "valid", ",", "message", "=", "super", "(", "BarrierConcurrencyState", ",", "self", ")", ".", "_check_transition_validity", "(", "check_transition", ")", "if", "not", "valid", ":"...
Transition of BarrierConcurrencyStates must least fulfill the condition of a ContainerState. Start transitions are forbidden in the ConcurrencyState. :param check_transition: the transition to check for validity :return:
[ "Transition", "of", "BarrierConcurrencyStates", "must", "least", "fulfill", "the", "condition", "of", "a", "ContainerState", ".", "Start", "transitions", "are", "forbidden", "in", "the", "ConcurrencyState", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/barrier_concurrency_state.py#L210-L241
train
40,492
DLR-RM/RAFCON
source/rafcon/core/states/barrier_concurrency_state.py
BarrierConcurrencyState.add_state
def add_state(self, state, storage_load=False): """Overwrite the parent class add_state method Add automatic transition generation for the decider_state. :param state: The state to be added :return: """ state_id = super(BarrierConcurrencyState, self).add_state(state) if not storage_load and not self.__init_running and not state.state_id == UNIQUE_DECIDER_STATE_ID: # the transitions must only be created for the initial add_state call and not during each load procedure for o_id, o in list(state.outcomes.items()): if not o_id == -1 and not o_id == -2: self.add_transition(state.state_id, o_id, self.states[UNIQUE_DECIDER_STATE_ID].state_id, None) return state_id
python
def add_state(self, state, storage_load=False): """Overwrite the parent class add_state method Add automatic transition generation for the decider_state. :param state: The state to be added :return: """ state_id = super(BarrierConcurrencyState, self).add_state(state) if not storage_load and not self.__init_running and not state.state_id == UNIQUE_DECIDER_STATE_ID: # the transitions must only be created for the initial add_state call and not during each load procedure for o_id, o in list(state.outcomes.items()): if not o_id == -1 and not o_id == -2: self.add_transition(state.state_id, o_id, self.states[UNIQUE_DECIDER_STATE_ID].state_id, None) return state_id
[ "def", "add_state", "(", "self", ",", "state", ",", "storage_load", "=", "False", ")", ":", "state_id", "=", "super", "(", "BarrierConcurrencyState", ",", "self", ")", ".", "add_state", "(", "state", ")", "if", "not", "storage_load", "and", "not", "self", ...
Overwrite the parent class add_state method Add automatic transition generation for the decider_state. :param state: The state to be added :return:
[ "Overwrite", "the", "parent", "class", "add_state", "method" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/barrier_concurrency_state.py#L244-L258
train
40,493
DLR-RM/RAFCON
source/rafcon/core/states/barrier_concurrency_state.py
BarrierConcurrencyState.states
def states(self, states): """ Overwrite the setter of the container state base class as special handling for the decider state is needed. :param states: the dictionary of new states :raises exceptions.TypeError: if the states parameter is not of type dict """ # First safely remove all existing states (recursively!), as they will be replaced state_ids = list(self.states.keys()) for state_id in state_ids: # Do not remove decider state, if teh new list of states doesn't contain an alternative one if state_id == UNIQUE_DECIDER_STATE_ID and UNIQUE_DECIDER_STATE_ID not in states: continue self.remove_state(state_id) if states is not None: if not isinstance(states, dict): raise TypeError("states must be of type dict") # Ensure that the decider state is added first, as transition to this states will automatically be # created when adding further states decider_state = states.pop(UNIQUE_DECIDER_STATE_ID, None) if decider_state is not None: self.add_state(decider_state) for state in states.values(): self.add_state(state)
python
def states(self, states): """ Overwrite the setter of the container state base class as special handling for the decider state is needed. :param states: the dictionary of new states :raises exceptions.TypeError: if the states parameter is not of type dict """ # First safely remove all existing states (recursively!), as they will be replaced state_ids = list(self.states.keys()) for state_id in state_ids: # Do not remove decider state, if teh new list of states doesn't contain an alternative one if state_id == UNIQUE_DECIDER_STATE_ID and UNIQUE_DECIDER_STATE_ID not in states: continue self.remove_state(state_id) if states is not None: if not isinstance(states, dict): raise TypeError("states must be of type dict") # Ensure that the decider state is added first, as transition to this states will automatically be # created when adding further states decider_state = states.pop(UNIQUE_DECIDER_STATE_ID, None) if decider_state is not None: self.add_state(decider_state) for state in states.values(): self.add_state(state)
[ "def", "states", "(", "self", ",", "states", ")", ":", "# First safely remove all existing states (recursively!), as they will be replaced", "state_ids", "=", "list", "(", "self", ".", "states", ".", "keys", "(", ")", ")", "for", "state_id", "in", "state_ids", ":", ...
Overwrite the setter of the container state base class as special handling for the decider state is needed. :param states: the dictionary of new states :raises exceptions.TypeError: if the states parameter is not of type dict
[ "Overwrite", "the", "setter", "of", "the", "container", "state", "base", "class", "as", "special", "handling", "for", "the", "decider", "state", "is", "needed", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/barrier_concurrency_state.py#L263-L285
train
40,494
DLR-RM/RAFCON
source/rafcon/core/states/barrier_concurrency_state.py
BarrierConcurrencyState.remove_state
def remove_state(self, state_id, recursive=True, force=False, destroy=True): """ Overwrite the parent class remove state method by checking if the user tries to delete the decider state :param state_id: the id of the state to remove :param recursive: a flag to indicate a recursive disassembling of all substates :param force: a flag to indicate forcefully deletion of all states (important of the decider state in the barrier concurrency state) :param destroy: a flag which indicates if the state should not only be disconnected from the state but also destroyed, including all its state elements :raises exceptions.AttributeError: if the state_id parameter is the decider state """ if state_id == UNIQUE_DECIDER_STATE_ID and force is False: raise AttributeError("You are not allowed to delete the decider state.") else: return ContainerState.remove_state(self, state_id, recursive=recursive, force=force, destroy=destroy)
python
def remove_state(self, state_id, recursive=True, force=False, destroy=True): """ Overwrite the parent class remove state method by checking if the user tries to delete the decider state :param state_id: the id of the state to remove :param recursive: a flag to indicate a recursive disassembling of all substates :param force: a flag to indicate forcefully deletion of all states (important of the decider state in the barrier concurrency state) :param destroy: a flag which indicates if the state should not only be disconnected from the state but also destroyed, including all its state elements :raises exceptions.AttributeError: if the state_id parameter is the decider state """ if state_id == UNIQUE_DECIDER_STATE_ID and force is False: raise AttributeError("You are not allowed to delete the decider state.") else: return ContainerState.remove_state(self, state_id, recursive=recursive, force=force, destroy=destroy)
[ "def", "remove_state", "(", "self", ",", "state_id", ",", "recursive", "=", "True", ",", "force", "=", "False", ",", "destroy", "=", "True", ")", ":", "if", "state_id", "==", "UNIQUE_DECIDER_STATE_ID", "and", "force", "is", "False", ":", "raise", "Attribut...
Overwrite the parent class remove state method by checking if the user tries to delete the decider state :param state_id: the id of the state to remove :param recursive: a flag to indicate a recursive disassembling of all substates :param force: a flag to indicate forcefully deletion of all states (important of the decider state in the barrier concurrency state) :param destroy: a flag which indicates if the state should not only be disconnected from the state but also destroyed, including all its state elements :raises exceptions.AttributeError: if the state_id parameter is the decider state
[ "Overwrite", "the", "parent", "class", "remove", "state", "method", "by", "checking", "if", "the", "user", "tries", "to", "delete", "the", "decider", "state" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/barrier_concurrency_state.py#L287-L301
train
40,495
DLR-RM/RAFCON
source/rafcon/core/states/barrier_concurrency_state.py
DeciderState.get_outcome_for_state_name
def get_outcome_for_state_name(self, name): """ Returns the final outcome of the child state specified by name. Note: This is utility function that is used by the programmer to make a decision based on the final outcome of its child states. A state is not uniquely specified by the name, but as the programmer normally does not want to use state-ids in his code this utility function was defined. :param name: The name of the state to get the final outcome for. :return: """ return_value = None for state_id, name_outcome_tuple in self.final_outcomes_dict.items(): if name_outcome_tuple[0] == name: return_value = name_outcome_tuple[1] break return return_value
python
def get_outcome_for_state_name(self, name): """ Returns the final outcome of the child state specified by name. Note: This is utility function that is used by the programmer to make a decision based on the final outcome of its child states. A state is not uniquely specified by the name, but as the programmer normally does not want to use state-ids in his code this utility function was defined. :param name: The name of the state to get the final outcome for. :return: """ return_value = None for state_id, name_outcome_tuple in self.final_outcomes_dict.items(): if name_outcome_tuple[0] == name: return_value = name_outcome_tuple[1] break return return_value
[ "def", "get_outcome_for_state_name", "(", "self", ",", "name", ")", ":", "return_value", "=", "None", "for", "state_id", ",", "name_outcome_tuple", "in", "self", ".", "final_outcomes_dict", ".", "items", "(", ")", ":", "if", "name_outcome_tuple", "[", "0", "]"...
Returns the final outcome of the child state specified by name. Note: This is utility function that is used by the programmer to make a decision based on the final outcome of its child states. A state is not uniquely specified by the name, but as the programmer normally does not want to use state-ids in his code this utility function was defined. :param name: The name of the state to get the final outcome for. :return:
[ "Returns", "the", "final", "outcome", "of", "the", "child", "state", "specified", "by", "name", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/barrier_concurrency_state.py#L352-L367
train
40,496
DLR-RM/RAFCON
source/rafcon/core/states/barrier_concurrency_state.py
DeciderState.get_outcome_for_state_id
def get_outcome_for_state_id(self, state_id): """ Returns the final outcome of the child state specified by the state_id. :param state_id: The id of the state to get the final outcome for. :return: """ return_value = None for s_id, name_outcome_tuple in self.final_outcomes_dict.items(): if s_id == state_id: return_value = name_outcome_tuple[1] break return return_value
python
def get_outcome_for_state_id(self, state_id): """ Returns the final outcome of the child state specified by the state_id. :param state_id: The id of the state to get the final outcome for. :return: """ return_value = None for s_id, name_outcome_tuple in self.final_outcomes_dict.items(): if s_id == state_id: return_value = name_outcome_tuple[1] break return return_value
[ "def", "get_outcome_for_state_id", "(", "self", ",", "state_id", ")", ":", "return_value", "=", "None", "for", "s_id", ",", "name_outcome_tuple", "in", "self", ".", "final_outcomes_dict", ".", "items", "(", ")", ":", "if", "s_id", "==", "state_id", ":", "ret...
Returns the final outcome of the child state specified by the state_id. :param state_id: The id of the state to get the final outcome for. :return:
[ "Returns", "the", "final", "outcome", "of", "the", "child", "state", "specified", "by", "the", "state_id", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/barrier_concurrency_state.py#L369-L380
train
40,497
DLR-RM/RAFCON
source/rafcon/core/states/barrier_concurrency_state.py
DeciderState.get_errors_for_state_name
def get_errors_for_state_name(self, name): """ Returns the error message of the child state specified by name. Note: This is utility function that is used by the programmer to make a decision based on the final outcome of its child states. A state is not uniquely specified by the name, but as the programmer normally does not want to use state-ids in his code this utility function was defined. :param name: The name of the state to get the error message for :return: """ return_value = None for state_id, name_outcome_tuple in self.child_errors.items(): if name_outcome_tuple[0] == name: return_value = name_outcome_tuple[1] break return return_value
python
def get_errors_for_state_name(self, name): """ Returns the error message of the child state specified by name. Note: This is utility function that is used by the programmer to make a decision based on the final outcome of its child states. A state is not uniquely specified by the name, but as the programmer normally does not want to use state-ids in his code this utility function was defined. :param name: The name of the state to get the error message for :return: """ return_value = None for state_id, name_outcome_tuple in self.child_errors.items(): if name_outcome_tuple[0] == name: return_value = name_outcome_tuple[1] break return return_value
[ "def", "get_errors_for_state_name", "(", "self", ",", "name", ")", ":", "return_value", "=", "None", "for", "state_id", ",", "name_outcome_tuple", "in", "self", ".", "child_errors", ".", "items", "(", ")", ":", "if", "name_outcome_tuple", "[", "0", "]", "=="...
Returns the error message of the child state specified by name. Note: This is utility function that is used by the programmer to make a decision based on the final outcome of its child states. A state is not uniquely specified by the name, but as the programmer normally does not want to use state-ids in his code this utility function was defined. :param name: The name of the state to get the error message for :return:
[ "Returns", "the", "error", "message", "of", "the", "child", "state", "specified", "by", "name", "." ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/barrier_concurrency_state.py#L382-L397
train
40,498
DLR-RM/RAFCON
source/rafcon/gui/controllers/utils/extended_controller.py
ExtendedController.add_controller
def add_controller(self, key, controller): """Add child controller The passed controller is registered as child of self. The register_actions method of the child controller is called, allowing the child controller to register shortcut callbacks. :param key: Name of the controller (unique within self), to later access it again :param ExtendedController controller: Controller to be added as child """ assert isinstance(controller, ExtendedController) controller.parent = self self.__child_controllers[key] = controller if self.__shortcut_manager is not None and controller not in self.__action_registered_controllers: controller.register_actions(self.__shortcut_manager) self.__action_registered_controllers.append(controller)
python
def add_controller(self, key, controller): """Add child controller The passed controller is registered as child of self. The register_actions method of the child controller is called, allowing the child controller to register shortcut callbacks. :param key: Name of the controller (unique within self), to later access it again :param ExtendedController controller: Controller to be added as child """ assert isinstance(controller, ExtendedController) controller.parent = self self.__child_controllers[key] = controller if self.__shortcut_manager is not None and controller not in self.__action_registered_controllers: controller.register_actions(self.__shortcut_manager) self.__action_registered_controllers.append(controller)
[ "def", "add_controller", "(", "self", ",", "key", ",", "controller", ")", ":", "assert", "isinstance", "(", "controller", ",", "ExtendedController", ")", "controller", ".", "parent", "=", "self", "self", ".", "__child_controllers", "[", "key", "]", "=", "con...
Add child controller The passed controller is registered as child of self. The register_actions method of the child controller is called, allowing the child controller to register shortcut callbacks. :param key: Name of the controller (unique within self), to later access it again :param ExtendedController controller: Controller to be added as child
[ "Add", "child", "controller" ]
24942ef1a904531f49ab8830a1dbb604441be498
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/utils/extended_controller.py#L51-L65
train
40,499