repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
titusjan/argos
argos/config/configtreemodel.py
ConfigTreeModel.insertTopLevelGroup
def insertTopLevelGroup(self, groupName, position=None): """ Inserts a top level group tree item. Used to group all config nodes of (for instance) the current inspector, Returns the newly created CTI """ groupCti = GroupCti(groupName) return self._invisibleRootItem.insertChild(groupCti, position=position)
python
def insertTopLevelGroup(self, groupName, position=None): """ Inserts a top level group tree item. Used to group all config nodes of (for instance) the current inspector, Returns the newly created CTI """ groupCti = GroupCti(groupName) return self._invisibleRootItem.insertChild(groupCti, position=position)
Inserts a top level group tree item. Used to group all config nodes of (for instance) the current inspector, Returns the newly created CTI
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configtreemodel.py#L86-L92
titusjan/argos
argos/config/configtreemodel.py
ConfigTreeModel.itemData
def itemData(self, treeItem, column, role=Qt.DisplayRole): """ Returns the data stored under the given role for the item. """ if role == Qt.DisplayRole: if column == self.COL_NODE_NAME: return treeItem.nodeName elif column == self.COL_NODE_PATH: return treeItem.nodePath elif column == self.COL_VALUE: return treeItem.displayValue elif column == self.COL_DEF_VALUE: return treeItem.displayDefaultValue elif column == self.COL_CTI_TYPE: return type_name(treeItem) elif column == self.COL_DEBUG: return treeItem.debugInfo else: raise ValueError("Invalid column: {}".format(column)) elif role == Qt.EditRole: if column == self.COL_VALUE: return treeItem.data else: raise ValueError("Invalid column: {}".format(column)) elif role == Qt.ToolTipRole: if column == self.COL_NODE_NAME or column == self.COL_NODE_PATH: return treeItem.nodePath elif column == self.COL_VALUE: # Give Access to exact values. In particular in scientific-notation spin boxes return repr(treeItem.configValue) elif column == self.COL_DEF_VALUE: return treeItem.displayDefaultValue elif column == self.COL_CTI_TYPE: return type_name(treeItem) elif column == self.COL_DEBUG: return treeItem.debugInfo else: return None elif role == Qt.CheckStateRole: if column != self.COL_VALUE: # The CheckStateRole is called for each cell so return None here. return None else: return treeItem.checkState else: return super(ConfigTreeModel, self).itemData(treeItem, column, role=role)
python
def itemData(self, treeItem, column, role=Qt.DisplayRole): """ Returns the data stored under the given role for the item. """ if role == Qt.DisplayRole: if column == self.COL_NODE_NAME: return treeItem.nodeName elif column == self.COL_NODE_PATH: return treeItem.nodePath elif column == self.COL_VALUE: return treeItem.displayValue elif column == self.COL_DEF_VALUE: return treeItem.displayDefaultValue elif column == self.COL_CTI_TYPE: return type_name(treeItem) elif column == self.COL_DEBUG: return treeItem.debugInfo else: raise ValueError("Invalid column: {}".format(column)) elif role == Qt.EditRole: if column == self.COL_VALUE: return treeItem.data else: raise ValueError("Invalid column: {}".format(column)) elif role == Qt.ToolTipRole: if column == self.COL_NODE_NAME or column == self.COL_NODE_PATH: return treeItem.nodePath elif column == self.COL_VALUE: # Give Access to exact values. In particular in scientific-notation spin boxes return repr(treeItem.configValue) elif column == self.COL_DEF_VALUE: return treeItem.displayDefaultValue elif column == self.COL_CTI_TYPE: return type_name(treeItem) elif column == self.COL_DEBUG: return treeItem.debugInfo else: return None elif role == Qt.CheckStateRole: if column != self.COL_VALUE: # The CheckStateRole is called for each cell so return None here. return None else: return treeItem.checkState else: return super(ConfigTreeModel, self).itemData(treeItem, column, role=role)
Returns the data stored under the given role for the item.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configtreemodel.py#L95-L142
titusjan/argos
argos/config/configtreemodel.py
ConfigTreeModel.setItemData
def setItemData(self, treeItem, column, value, role=Qt.EditRole): """ Sets the role data for the item at index to value. """ if role == Qt.CheckStateRole: if column != self.COL_VALUE: return False else: logger.debug("Setting check state (col={}): {!r}".format(column, value)) treeItem.checkState = value return True elif role == Qt.EditRole: if column != self.COL_VALUE: return False else: logger.debug("Set Edit value (col={}): {!r}".format(column, value)) treeItem.data = value return True else: raise ValueError("Unexpected edit role: {}".format(role))
python
def setItemData(self, treeItem, column, value, role=Qt.EditRole): """ Sets the role data for the item at index to value. """ if role == Qt.CheckStateRole: if column != self.COL_VALUE: return False else: logger.debug("Setting check state (col={}): {!r}".format(column, value)) treeItem.checkState = value return True elif role == Qt.EditRole: if column != self.COL_VALUE: return False else: logger.debug("Set Edit value (col={}): {!r}".format(column, value)) treeItem.data = value return True else: raise ValueError("Unexpected edit role: {}".format(role))
Sets the role data for the item at index to value.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configtreemodel.py#L145-L164
titusjan/argos
argos/config/configtreemodel.py
ConfigTreeModel.setExpanded
def setExpanded(self, index, expanded): """ Expands the model item specified by the index. Overridden from QTreeView to make it persistent (between inspector changes). """ if index.isValid(): item = self.getItem(index) item.expanded = expanded
python
def setExpanded(self, index, expanded): """ Expands the model item specified by the index. Overridden from QTreeView to make it persistent (between inspector changes). """ if index.isValid(): item = self.getItem(index) item.expanded = expanded
Expands the model item specified by the index. Overridden from QTreeView to make it persistent (between inspector changes).
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configtreemodel.py#L167-L173
titusjan/argos
argos/config/configtreemodel.py
ConfigTreeModel.indexTupleFromItem
def indexTupleFromItem(self, treeItem): # TODO: move to BaseTreeItem? """ Return (first column model index, last column model index) tuple for a configTreeItem """ if not treeItem: return (QtCore.QModelIndex(), QtCore.QModelIndex()) if not treeItem.parentItem: # TODO: only necessary because of childNumber? return (QtCore.QModelIndex(), QtCore.QModelIndex()) # Is there a bug in Qt in QStandardItemModel::indexFromItem? # It passes the parent in createIndex. TODO: investigate row = treeItem.childNumber() return (self.createIndex(row, 0, treeItem), self.createIndex(row, self.columnCount() - 1, treeItem))
python
def indexTupleFromItem(self, treeItem): # TODO: move to BaseTreeItem? """ Return (first column model index, last column model index) tuple for a configTreeItem """ if not treeItem: return (QtCore.QModelIndex(), QtCore.QModelIndex()) if not treeItem.parentItem: # TODO: only necessary because of childNumber? return (QtCore.QModelIndex(), QtCore.QModelIndex()) # Is there a bug in Qt in QStandardItemModel::indexFromItem? # It passes the parent in createIndex. TODO: investigate row = treeItem.childNumber() return (self.createIndex(row, 0, treeItem), self.createIndex(row, self.columnCount() - 1, treeItem))
Return (first column model index, last column model index) tuple for a configTreeItem
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configtreemodel.py#L191-L205
titusjan/argos
argos/config/configtreemodel.py
ConfigTreeModel.emitDataChanged
def emitDataChanged(self, treeItem): # TODO: move to BaseTreeItem? """ Emits the data changed for the model indices (all columns) for this treeItem """ indexLeft, indexRight = self.indexTupleFromItem(treeItem) checkItem = self.getItem(indexLeft) assert checkItem is treeItem, "{} != {}".format(checkItem, treeItem) # TODO: remove self.dataChanged.emit(indexLeft, indexRight)
python
def emitDataChanged(self, treeItem): # TODO: move to BaseTreeItem? """ Emits the data changed for the model indices (all columns) for this treeItem """ indexLeft, indexRight = self.indexTupleFromItem(treeItem) checkItem = self.getItem(indexLeft) assert checkItem is treeItem, "{} != {}".format(checkItem, treeItem) # TODO: remove self.dataChanged.emit(indexLeft, indexRight)
Emits the data changed for the model indices (all columns) for this treeItem
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configtreemodel.py#L208-L214
titusjan/argos
argos/config/configtreemodel.py
ConfigTreeModel.setRefreshBlocked
def setRefreshBlocked(self, blocked): """ Set to True to indicate that set the configuration should not be updated. This setting is part of the model so that is shared by all CTIs. Returns the old value. """ wasBlocked = self._refreshBlocked logger.debug("Setting refreshBlocked from {} to {}".format(wasBlocked, blocked)) self._refreshBlocked = blocked return wasBlocked
python
def setRefreshBlocked(self, blocked): """ Set to True to indicate that set the configuration should not be updated. This setting is part of the model so that is shared by all CTIs. Returns the old value. """ wasBlocked = self._refreshBlocked logger.debug("Setting refreshBlocked from {} to {}".format(wasBlocked, blocked)) self._refreshBlocked = blocked return wasBlocked
Set to True to indicate that set the configuration should not be updated. This setting is part of the model so that is shared by all CTIs. Returns the old value.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configtreemodel.py#L224-L232
titusjan/argos
argos/repo/rtiplugins/numpyio.py
NumpyBinaryFileRti._openResources
def _openResources(self): """ Uses numpy.load to open the underlying file """ arr = np.load(self._fileName, allow_pickle=ALLOW_PICKLE) check_is_an_array(arr) self._array = arr
python
def _openResources(self): """ Uses numpy.load to open the underlying file """ arr = np.load(self._fileName, allow_pickle=ALLOW_PICKLE) check_is_an_array(arr) self._array = arr
Uses numpy.load to open the underlying file
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/numpyio.py#L113-L118
titusjan/argos
argos/repo/rtiplugins/numpyio.py
NumpyCompressedFileRti._openResources
def _openResources(self): """ Uses numpy.load to open the underlying file """ dct = np.load(self._fileName, allow_pickle=ALLOW_PICKLE) check_class(dct, NpzFile) self._dictionary = dct
python
def _openResources(self): """ Uses numpy.load to open the underlying file """ dct = np.load(self._fileName, allow_pickle=ALLOW_PICKLE) check_class(dct, NpzFile) self._dictionary = dct
Uses numpy.load to open the underlying file
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/rtiplugins/numpyio.py#L154-L159
titusjan/argos
argos/config/boolcti.py
BoolCti.data
def data(self, data): """ Sets the data of this item. Does type conversion to ensure data is always of the correct type. """ # Descendants should convert the data to the desired type here self._data = self._enforceDataType(data) #logger.debug("BoolCti.setData: {} for {}".format(data, self)) enabled = self.enabled self.enableBranch(enabled and self.data != self.childrenDisabledValue) self.enabled = enabled
python
def data(self, data): """ Sets the data of this item. Does type conversion to ensure data is always of the correct type. """ # Descendants should convert the data to the desired type here self._data = self._enforceDataType(data) #logger.debug("BoolCti.setData: {} for {}".format(data, self)) enabled = self.enabled self.enableBranch(enabled and self.data != self.childrenDisabledValue) self.enabled = enabled
Sets the data of this item. Does type conversion to ensure data is always of the correct type.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/boolcti.py#L69-L79
titusjan/argos
argos/config/boolcti.py
BoolCti.insertChild
def insertChild(self, childItem, position=None): """ Inserts a child item to the current item. Overridden from BaseTreeItem. """ childItem = super(BoolCti, self).insertChild(childItem, position=None) enableChildren = self.enabled and self.data != self.childrenDisabledValue #logger.debug("BoolCti.insertChild: {} enableChildren={}".format(childItem, enableChildren)) childItem.enableBranch(enableChildren) childItem.enabled = enableChildren return childItem
python
def insertChild(self, childItem, position=None): """ Inserts a child item to the current item. Overridden from BaseTreeItem. """ childItem = super(BoolCti, self).insertChild(childItem, position=None) enableChildren = self.enabled and self.data != self.childrenDisabledValue #logger.debug("BoolCti.insertChild: {} enableChildren={}".format(childItem, enableChildren)) childItem.enableBranch(enableChildren) childItem.enabled = enableChildren return childItem
Inserts a child item to the current item. Overridden from BaseTreeItem.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/boolcti.py#L89-L100
titusjan/argos
argos/config/boolcti.py
BoolCti.checkState
def checkState(self): """ Returns Qt.Checked or Qt.Unchecked. """ if self.data is True: return Qt.Checked elif self.data is False: return Qt.Unchecked else: raise ValueError("Unexpected data: {!r}".format(self.data))
python
def checkState(self): """ Returns Qt.Checked or Qt.Unchecked. """ if self.data is True: return Qt.Checked elif self.data is False: return Qt.Unchecked else: raise ValueError("Unexpected data: {!r}".format(self.data))
Returns Qt.Checked or Qt.Unchecked.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/boolcti.py#L112-L120
titusjan/argos
argos/config/boolcti.py
BoolCti.checkState
def checkState(self, checkState): """ Sets the data to given a Qt.CheckState (Qt.Checked or Qt.Unchecked). """ if checkState == Qt.Checked: logger.debug("BoolCti.checkState setting to True") self.data = True elif checkState == Qt.Unchecked: logger.debug("BoolCti.checkState setting to False") self.data = False else: raise ValueError("Unexpected check state: {!r}".format(checkState))
python
def checkState(self, checkState): """ Sets the data to given a Qt.CheckState (Qt.Checked or Qt.Unchecked). """ if checkState == Qt.Checked: logger.debug("BoolCti.checkState setting to True") self.data = True elif checkState == Qt.Unchecked: logger.debug("BoolCti.checkState setting to False") self.data = False else: raise ValueError("Unexpected check state: {!r}".format(checkState))
Sets the data to given a Qt.CheckState (Qt.Checked or Qt.Unchecked).
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/boolcti.py#L124-L134
titusjan/argos
argos/config/boolcti.py
BoolCti.enableBranch
def enableBranch(self, enabled): """ Sets the enabled member to True or False for a node and all it's children """ self.enabled = enabled # Disabled children and further descendants enabled = enabled and self.data != self.childrenDisabledValue for child in self.childItems: child.enableBranch(enabled)
python
def enableBranch(self, enabled): """ Sets the enabled member to True or False for a node and all it's children """ self.enabled = enabled # Disabled children and further descendants enabled = enabled and self.data != self.childrenDisabledValue for child in self.childItems: child.enableBranch(enabled)
Sets the enabled member to True or False for a node and all it's children
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/boolcti.py#L137-L146
titusjan/argos
argos/config/boolcti.py
BoolGroupCti.checkState
def checkState(self): """ Returns Qt.Checked or Qt.Unchecked if all children are checked or unchecked, else returns Qt.PartiallyChecked """ #commonData = self.childItems[0].data if self.childItems else Qt.PartiallyChecked commonData = None for child in self.childItems: if isinstance(child, BoolCti): if commonData is not None and child.data != commonData: return Qt.PartiallyChecked commonData = child.data if commonData is True: return Qt.Checked elif commonData is False: return Qt.Unchecked else: raise AssertionError("Please report this bug: commonData: {!r}".format(commonData))
python
def checkState(self): """ Returns Qt.Checked or Qt.Unchecked if all children are checked or unchecked, else returns Qt.PartiallyChecked """ #commonData = self.childItems[0].data if self.childItems else Qt.PartiallyChecked commonData = None for child in self.childItems: if isinstance(child, BoolCti): if commonData is not None and child.data != commonData: return Qt.PartiallyChecked commonData = child.data if commonData is True: return Qt.Checked elif commonData is False: return Qt.Unchecked else: raise AssertionError("Please report this bug: commonData: {!r}".format(commonData))
Returns Qt.Checked or Qt.Unchecked if all children are checked or unchecked, else returns Qt.PartiallyChecked
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/boolcti.py#L195-L213
titusjan/argos
argos/config/boolcti.py
BoolGroupCti.checkState
def checkState(self, checkState): """ Sets the data to given a Qt.CheckState (Qt.Checked or Qt.Unchecked). """ logger.debug("checkState setter: {}".format(checkState)) if checkState == Qt.Checked: commonData = True elif checkState == Qt.Unchecked: commonData = False elif checkState == Qt.PartiallyChecked: commonData = None # This never occurs, see remarks above in the classes' docstring assert False, "This never happens. Please report if it does." else: raise ValueError("Unexpected check state: {!r}".format(checkState)) for child in self.childItems: if isinstance(child, BoolCti): child.data = commonData
python
def checkState(self, checkState): """ Sets the data to given a Qt.CheckState (Qt.Checked or Qt.Unchecked). """ logger.debug("checkState setter: {}".format(checkState)) if checkState == Qt.Checked: commonData = True elif checkState == Qt.Unchecked: commonData = False elif checkState == Qt.PartiallyChecked: commonData = None # This never occurs, see remarks above in the classes' docstring assert False, "This never happens. Please report if it does." else: raise ValueError("Unexpected check state: {!r}".format(checkState)) for child in self.childItems: if isinstance(child, BoolCti): child.data = commonData
Sets the data to given a Qt.CheckState (Qt.Checked or Qt.Unchecked).
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/boolcti.py#L217-L234
titusjan/argos
argos/repo/baserti.py
BaseRti.createFromFileName
def createFromFileName(cls, fileName): """ Creates a BaseRti (or descendant), given a file name. """ # See https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods #logger.debug("Trying to create object of class: {!r}".format(cls)) basename = os.path.basename(os.path.realpath(fileName)) # strips trailing slashes return cls(nodeName=basename, fileName=fileName)
python
def createFromFileName(cls, fileName): """ Creates a BaseRti (or descendant), given a file name. """ # See https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods #logger.debug("Trying to create object of class: {!r}".format(cls)) basename = os.path.basename(os.path.realpath(fileName)) # strips trailing slashes return cls(nodeName=basename, fileName=fileName)
Creates a BaseRti (or descendant), given a file name.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/baserti.py#L60-L66
titusjan/argos
argos/repo/baserti.py
BaseRti.open
def open(self): """ Opens underlying resources and sets isOpen flag. It calls _openResources. Descendants should usually override the latter function instead of this one. """ self.clearException() try: if self._isOpen: logger.warn("Resources already open. Closing them first before opening.") self._closeResources() self._isOpen = False assert not self._isOpen, "Sanity check failed: _isOpen should be false" logger.debug("Opening {}".format(self)) self._openResources() self._isOpen = True if self.model: self.model.sigItemChanged.emit(self) else: logger.warning("Model not set yet: {}".format(self)) except Exception as ex: if DEBUGGING: raise logger.exception("Error during tree item open: {}".format(ex)) self.setException(ex)
python
def open(self): """ Opens underlying resources and sets isOpen flag. It calls _openResources. Descendants should usually override the latter function instead of this one. """ self.clearException() try: if self._isOpen: logger.warn("Resources already open. Closing them first before opening.") self._closeResources() self._isOpen = False assert not self._isOpen, "Sanity check failed: _isOpen should be false" logger.debug("Opening {}".format(self)) self._openResources() self._isOpen = True if self.model: self.model.sigItemChanged.emit(self) else: logger.warning("Model not set yet: {}".format(self)) except Exception as ex: if DEBUGGING: raise logger.exception("Error during tree item open: {}".format(ex)) self.setException(ex)
Opens underlying resources and sets isOpen flag. It calls _openResources. Descendants should usually override the latter function instead of this one.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/baserti.py#L92-L118
titusjan/argos
argos/repo/baserti.py
BaseRti.close
def close(self): """ Closes underlying resources and un-sets the isOpen flag. Any exception that occurs is caught and put in the exception property. This method calls _closeResources, which does the actual resource cleanup. Descendants should typically override the latter instead of this one. """ self.clearException() try: if self._isOpen: logger.debug("Closing {}".format(self)) self._closeResources() self._isOpen = False else: logger.debug("Resources already closed (ignored): {}".format(self)) if self.model: self.model.sigItemChanged.emit(self) else: logger.warning("Model not set yet: {}".format(self)) except Exception as ex: if DEBUGGING: raise logger.error("Error during tree item close: {}".format(ex)) self.setException(ex)
python
def close(self): """ Closes underlying resources and un-sets the isOpen flag. Any exception that occurs is caught and put in the exception property. This method calls _closeResources, which does the actual resource cleanup. Descendants should typically override the latter instead of this one. """ self.clearException() try: if self._isOpen: logger.debug("Closing {}".format(self)) self._closeResources() self._isOpen = False else: logger.debug("Resources already closed (ignored): {}".format(self)) if self.model: self.model.sigItemChanged.emit(self) else: logger.warning("Model not set yet: {}".format(self)) except Exception as ex: if DEBUGGING: raise logger.error("Error during tree item close: {}".format(ex)) self.setException(ex)
Closes underlying resources and un-sets the isOpen flag. Any exception that occurs is caught and put in the exception property. This method calls _closeResources, which does the actual resource cleanup. Descendants should typically override the latter instead of this one.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/baserti.py#L129-L153
titusjan/argos
argos/repo/baserti.py
BaseRti._checkFileExists
def _checkFileExists(self): """ Verifies that the underlying file exists and sets the _exception attribute if not Returns True if the file exists. If self._fileName is None, nothing is checked and True is returned. """ if self._fileName and not os.path.exists(self._fileName): msg = "File not found: {}".format(self._fileName) logger.error(msg) self.setException(IOError(msg)) return False else: return True
python
def _checkFileExists(self): """ Verifies that the underlying file exists and sets the _exception attribute if not Returns True if the file exists. If self._fileName is None, nothing is checked and True is returned. """ if self._fileName and not os.path.exists(self._fileName): msg = "File not found: {}".format(self._fileName) logger.error(msg) self.setException(IOError(msg)) return False else: return True
Verifies that the underlying file exists and sets the _exception attribute if not Returns True if the file exists. If self._fileName is None, nothing is checked and True is returned.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/baserti.py#L164-L175
titusjan/argos
argos/repo/baserti.py
BaseRti.fetchChildren
def fetchChildren(self): """ Creates child items and returns them. Opens the tree item first if it's not yet open. """ assert self._canFetchChildren, "canFetchChildren must be True" try: self.clearException() if not self.isOpen: self.open() # Will set self._exception in case of failure if not self.isOpen: logger.warn("Opening item failed during fetch (aborted)") return [] # no need to continue if opening failed. childItems = [] try: childItems = self._fetchAllChildren() assert is_a_sequence(childItems), "ChildItems must be a sequence" except Exception as ex: # This can happen, for example, when a NCDF/HDF5 file contains data types that # are not supported by the Python library that is used to read them. if DEBUGGING: raise logger.error("Unable fetch tree item children: {}".format(ex)) self.setException(ex) return childItems finally: self._canFetchChildren = False
python
def fetchChildren(self): """ Creates child items and returns them. Opens the tree item first if it's not yet open. """ assert self._canFetchChildren, "canFetchChildren must be True" try: self.clearException() if not self.isOpen: self.open() # Will set self._exception in case of failure if not self.isOpen: logger.warn("Opening item failed during fetch (aborted)") return [] # no need to continue if opening failed. childItems = [] try: childItems = self._fetchAllChildren() assert is_a_sequence(childItems), "ChildItems must be a sequence" except Exception as ex: # This can happen, for example, when a NCDF/HDF5 file contains data types that # are not supported by the Python library that is used to read them. if DEBUGGING: raise logger.error("Unable fetch tree item children: {}".format(ex)) self.setException(ex) return childItems finally: self._canFetchChildren = False
Creates child items and returns them. Opens the tree item first if it's not yet open.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/baserti.py#L196-L226
titusjan/argos
argos/repo/baserti.py
BaseRti.decoration
def decoration(self): """ The displayed icon. Shows open icon when node was visited (children are fetched). This allows users for instance to collapse a directory node but still see that it was visited, which may be useful if there is a huge list of directories. """ rtiIconFactory = RtiIconFactory.singleton() if self._exception: return rtiIconFactory.getIcon(rtiIconFactory.ERROR, isOpen=False, color=rtiIconFactory.COLOR_ERROR) else: return rtiIconFactory.getIcon(self.iconGlyph, isOpen=not self.canFetchChildren(), color=self.iconColor)
python
def decoration(self): """ The displayed icon. Shows open icon when node was visited (children are fetched). This allows users for instance to collapse a directory node but still see that it was visited, which may be useful if there is a huge list of directories. """ rtiIconFactory = RtiIconFactory.singleton() if self._exception: return rtiIconFactory.getIcon(rtiIconFactory.ERROR, isOpen=False, color=rtiIconFactory.COLOR_ERROR) else: return rtiIconFactory.getIcon(self.iconGlyph, isOpen=not self.canFetchChildren(), color=self.iconColor)
The displayed icon. Shows open icon when node was visited (children are fetched). This allows users for instance to collapse a directory node but still see that it was visited, which may be useful if there is a huge list of directories.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/baserti.py#L261-L275
titusjan/argos
argos/repo/detailplugins/dim.py
DimensionsPane._drawContents
def _drawContents(self, currentRti=None): """ Draws the attributes of the currentRTI """ table = self.table table.setUpdatesEnabled(False) sizeAlignment = Qt.AlignRight | Qt.AlignVCenter try: table.clearContents() verticalHeader = table.verticalHeader() verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.Fixed) if currentRti is None or not currentRti.isSliceable: return nDims = currentRti.nDims dimNames = currentRti.dimensionNames dimGroups = currentRti.dimensionGroupPaths dimSizes = currentRti.arrayShape # Sanity check assert len(dimNames) == nDims, "dimNames size {} != {}".format(len(dimNames), nDims) assert len(dimGroups) == nDims, "dimGroups size {} != {}".format(len(dimGroups), nDims) assert len(dimSizes) == nDims, "dimSizes size {} != {}".format(len(dimSizes), nDims) table.setRowCount(nDims) for row, (dimName, dimSize, dimGroup) in enumerate(zip(dimNames, dimSizes, dimGroups)): table.setItem(row, self.COL_NAME, QtWidgets.QTableWidgetItem(dimName)) table.setItem(row, self.COL_SIZE, QtWidgets.QTableWidgetItem(str(dimSize))) table.item(row, self.COL_SIZE).setTextAlignment(sizeAlignment) table.setItem(row, self.COL_GROUP, QtWidgets.QTableWidgetItem(str(dimGroup))) table.resizeRowToContents(row) verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents) finally: table.setUpdatesEnabled(True)
python
def _drawContents(self, currentRti=None): """ Draws the attributes of the currentRTI """ table = self.table table.setUpdatesEnabled(False) sizeAlignment = Qt.AlignRight | Qt.AlignVCenter try: table.clearContents() verticalHeader = table.verticalHeader() verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.Fixed) if currentRti is None or not currentRti.isSliceable: return nDims = currentRti.nDims dimNames = currentRti.dimensionNames dimGroups = currentRti.dimensionGroupPaths dimSizes = currentRti.arrayShape # Sanity check assert len(dimNames) == nDims, "dimNames size {} != {}".format(len(dimNames), nDims) assert len(dimGroups) == nDims, "dimGroups size {} != {}".format(len(dimGroups), nDims) assert len(dimSizes) == nDims, "dimSizes size {} != {}".format(len(dimSizes), nDims) table.setRowCount(nDims) for row, (dimName, dimSize, dimGroup) in enumerate(zip(dimNames, dimSizes, dimGroups)): table.setItem(row, self.COL_NAME, QtWidgets.QTableWidgetItem(dimName)) table.setItem(row, self.COL_SIZE, QtWidgets.QTableWidgetItem(str(dimSize))) table.item(row, self.COL_SIZE).setTextAlignment(sizeAlignment) table.setItem(row, self.COL_GROUP, QtWidgets.QTableWidgetItem(str(dimGroup))) table.resizeRowToContents(row) verticalHeader.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents) finally: table.setUpdatesEnabled(True)
Draws the attributes of the currentRTI
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/detailplugins/dim.py#L54-L91
titusjan/argos
argos/qt/scientificspinbox.py
format_float
def format_float(value): # not used """Modified form of the 'g' format specifier. """ string = "{:g}".format(value).replace("e+", "e") string = re.sub("e(-?)0*(\d+)", r"e\1\2", string) return string
python
def format_float(value): # not used """Modified form of the 'g' format specifier. """ string = "{:g}".format(value).replace("e+", "e") string = re.sub("e(-?)0*(\d+)", r"e\1\2", string) return string
Modified form of the 'g' format specifier.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/scientificspinbox.py#L21-L26
titusjan/argos
argos/qt/scientificspinbox.py
ScientificDoubleSpinBox.smallStepsPerLargeStep
def smallStepsPerLargeStep(self, smallStepsPerLargeStep): """ Sets the number of small steps that go in a large one. """ self._smallStepsPerLargeStep = smallStepsPerLargeStep self._smallStepFactor = np.power(self.largeStepFactor, 1.0 / smallStepsPerLargeStep)
python
def smallStepsPerLargeStep(self, smallStepsPerLargeStep): """ Sets the number of small steps that go in a large one. """ self._smallStepsPerLargeStep = smallStepsPerLargeStep self._smallStepFactor = np.power(self.largeStepFactor, 1.0 / smallStepsPerLargeStep)
Sets the number of small steps that go in a large one.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/scientificspinbox.py#L137-L142
titusjan/argos
argos/qt/scientificspinbox.py
ScientificDoubleSpinBox.stepBy
def stepBy(self, steps): """ Function that is called whenever the user triggers a step. The steps parameter indicates how many steps were taken, e.g. Pressing Qt::Key_Down will trigger a call to stepBy(-1), whereas pressing Qt::Key_Prior will trigger a call to stepBy(10). """ oldValue = self.value() if oldValue == 0: newValue = steps elif steps == 1: newValue = self.value() * self.smallStepFactor elif steps == -1: newValue = self.value() / self.smallStepFactor elif steps == 10: newValue = self.value() * self.largeStepFactor elif steps == -10: newValue = self.value() / self.largeStepFactor else: raise ValueError("Invalid step size: {!r}, value={}".format(steps, oldValue)) newValue = float(newValue) if newValue < self.minimum(): newValue = self.minimum() if newValue > self.maximum(): newValue = self.maximum() #logger.debug("stepBy {}: {} -> {}".format(steps, oldValue, newValue)) try: self.setValue(newValue) except Exception: # TODO: does this ever happen? Better validation (e.g. catch underflows) logger.warn("Unable to set spinbox to: {!r}".format(newValue)) self.setValue(oldValue)
python
def stepBy(self, steps): """ Function that is called whenever the user triggers a step. The steps parameter indicates how many steps were taken, e.g. Pressing Qt::Key_Down will trigger a call to stepBy(-1), whereas pressing Qt::Key_Prior will trigger a call to stepBy(10). """ oldValue = self.value() if oldValue == 0: newValue = steps elif steps == 1: newValue = self.value() * self.smallStepFactor elif steps == -1: newValue = self.value() / self.smallStepFactor elif steps == 10: newValue = self.value() * self.largeStepFactor elif steps == -10: newValue = self.value() / self.largeStepFactor else: raise ValueError("Invalid step size: {!r}, value={}".format(steps, oldValue)) newValue = float(newValue) if newValue < self.minimum(): newValue = self.minimum() if newValue > self.maximum(): newValue = self.maximum() #logger.debug("stepBy {}: {} -> {}".format(steps, oldValue, newValue)) try: self.setValue(newValue) except Exception: # TODO: does this ever happen? Better validation (e.g. catch underflows) logger.warn("Unable to set spinbox to: {!r}".format(newValue)) self.setValue(oldValue)
Function that is called whenever the user triggers a step. The steps parameter indicates how many steps were taken, e.g. Pressing Qt::Key_Down will trigger a call to stepBy(-1), whereas pressing Qt::Key_Prior will trigger a call to stepBy(10).
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/scientificspinbox.py#L145-L179
titusjan/argos
argos/utils/moduleinfo.py
ImportedModuleInfo.tryImportModule
def tryImportModule(self, name): """ Imports the module and sets version information If the module cannot be imported, the version is set to empty values. """ self._name = name try: import importlib self._module = importlib.import_module(name) except ImportError: self._module = None self._version = '' self._packagePath = '' else: if self._versionAttribute: self._version = getattr(self._module, self._versionAttribute, '???') if self._pathAttribute: self._packagePath = getattr(self._module, self._pathAttribute, '???')
python
def tryImportModule(self, name): """ Imports the module and sets version information If the module cannot be imported, the version is set to empty values. """ self._name = name try: import importlib self._module = importlib.import_module(name) except ImportError: self._module = None self._version = '' self._packagePath = '' else: if self._versionAttribute: self._version = getattr(self._module, self._versionAttribute, '???') if self._pathAttribute: self._packagePath = getattr(self._module, self._pathAttribute, '???')
Imports the module and sets version information If the module cannot be imported, the version is set to empty values.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/moduleinfo.py#L136-L152
titusjan/argos
argos/inspector/pgplugins/__init__.py
setPgConfigOptions
def setPgConfigOptions(**kwargs): """ Sets the PyQtGraph config options and emits a log message """ for key, value in kwargs.items(): logger.debug("Setting PyQtGraph config option: {} = {}".format(key, value)) pg.setConfigOptions(**kwargs)
python
def setPgConfigOptions(**kwargs): """ Sets the PyQtGraph config options and emits a log message """ for key, value in kwargs.items(): logger.debug("Setting PyQtGraph config option: {} = {}".format(key, value)) pg.setConfigOptions(**kwargs)
Sets the PyQtGraph config options and emits a log message
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/__init__.py#L35-L41
titusjan/argos
argos/qt/treeitems.py
BaseTreeItem.model
def model(self): """ Returns the ConfigTreeModel this item belongs to. If the model is None (not set), it will use and cache the parent's model. Therefore make sure that an ancestor node has a reference to the model! Typically by setting the model property of the invisible root item in the model constructor. """ if self._model is None and self.parentItem is not None: self._model = self.parentItem.model return self._model
python
def model(self): """ Returns the ConfigTreeModel this item belongs to. If the model is None (not set), it will use and cache the parent's model. Therefore make sure that an ancestor node has a reference to the model! Typically by setting the model property of the invisible root item in the model constructor. """ if self._model is None and self.parentItem is not None: self._model = self.parentItem.model return self._model
Returns the ConfigTreeModel this item belongs to. If the model is None (not set), it will use and cache the parent's model. Therefore make sure that an ancestor node has a reference to the model! Typically by setting the model property of the invisible root item in the model constructor.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L47-L55
titusjan/argos
argos/qt/treeitems.py
BaseTreeItem.nodeName
def nodeName(self, nodeName): """ The node name. Is used to construct the nodePath""" assert '/' not in nodeName, "nodeName may not contain slashes" self._nodeName = nodeName self._recursiveSetNodePath(self._constructNodePath())
python
def nodeName(self, nodeName): """ The node name. Is used to construct the nodePath""" assert '/' not in nodeName, "nodeName may not contain slashes" self._nodeName = nodeName self._recursiveSetNodePath(self._constructNodePath())
The node name. Is used to construct the nodePath
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L119-L123
titusjan/argos
argos/qt/treeitems.py
BaseTreeItem._recursiveSetNodePath
def _recursiveSetNodePath(self, nodePath): """ Sets the nodePath property and updates it for all children. """ self._nodePath = nodePath for childItem in self.childItems: childItem._recursiveSetNodePath(nodePath + '/' + childItem.nodeName)
python
def _recursiveSetNodePath(self, nodePath): """ Sets the nodePath property and updates it for all children. """ self._nodePath = nodePath for childItem in self.childItems: childItem._recursiveSetNodePath(nodePath + '/' + childItem.nodeName)
Sets the nodePath property and updates it for all children.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L137-L142
titusjan/argos
argos/qt/treeitems.py
BaseTreeItem.parentItem
def parentItem(self, value): """ The parent item """ self._parentItem = value self._recursiveSetNodePath(self._constructNodePath())
python
def parentItem(self, value): """ The parent item """ self._parentItem = value self._recursiveSetNodePath(self._constructNodePath())
The parent item
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L150-L153
titusjan/argos
argos/qt/treeitems.py
BaseTreeItem.childByNodeName
def childByNodeName(self, nodeName): """ Gets first (direct) child that has the nodeName. """ assert '/' not in nodeName, "nodeName can not contain slashes" for child in self.childItems: if child.nodeName == nodeName: return child raise IndexError("No child item found having nodeName: {}".format(nodeName))
python
def childByNodeName(self, nodeName): """ Gets first (direct) child that has the nodeName. """ assert '/' not in nodeName, "nodeName can not contain slashes" for child in self.childItems: if child.nodeName == nodeName: return child raise IndexError("No child item found having nodeName: {}".format(nodeName))
Gets first (direct) child that has the nodeName.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L179-L187
titusjan/argos
argos/qt/treeitems.py
BaseTreeItem.findByNodePath
def findByNodePath(self, nodePath): """ Recursively searches for the child having the nodePath. Starts at self. """ def _auxGetByPath(parts, item): "Aux function that does the actual recursive search" #logger.debug("_auxGetByPath item={}, parts={}".format(item, parts)) if len(parts) == 0: return item head, tail = parts[0], parts[1:] if head == '': # Two consecutive slashes. Just go one level deeper. return _auxGetByPath(tail, item) else: childItem = item.childByNodeName(head) return _auxGetByPath(tail, childItem) # The actual body of findByNodePath starts here check_is_a_string(nodePath) assert not nodePath.startswith('/'), "nodePath may not start with a slash" if not nodePath: raise IndexError("Item not found: {!r}".format(nodePath)) return _auxGetByPath(nodePath.split('/'), self)
python
def findByNodePath(self, nodePath): """ Recursively searches for the child having the nodePath. Starts at self. """ def _auxGetByPath(parts, item): "Aux function that does the actual recursive search" #logger.debug("_auxGetByPath item={}, parts={}".format(item, parts)) if len(parts) == 0: return item head, tail = parts[0], parts[1:] if head == '': # Two consecutive slashes. Just go one level deeper. return _auxGetByPath(tail, item) else: childItem = item.childByNodeName(head) return _auxGetByPath(tail, childItem) # The actual body of findByNodePath starts here check_is_a_string(nodePath) assert not nodePath.startswith('/'), "nodePath may not start with a slash" if not nodePath: raise IndexError("Item not found: {!r}".format(nodePath)) return _auxGetByPath(nodePath.split('/'), self)
Recursively searches for the child having the nodePath. Starts at self.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L190-L216
titusjan/argos
argos/qt/treeitems.py
BaseTreeItem.insertChild
def insertChild(self, childItem, position=None): """ Inserts a child item to the current item. The childItem must not yet have a parent (it will be set by this function). IMPORTANT: this does not let the model know that items have been added. Use BaseTreeModel.insertItem instead. param childItem: a BaseTreeItem that will be added param position: integer position before which the item will be added. If position is None (default) the item will be appended at the end. Returns childItem so that calls may be chained. """ if position is None: position = self.nChildren() assert childItem.parentItem is None, "childItem already has a parent: {}".format(childItem) assert childItem._model is None, "childItem already has a model: {}".format(childItem) childItem.parentItem = self childItem.model = self.model self.childItems.insert(position, childItem) return childItem
python
def insertChild(self, childItem, position=None): """ Inserts a child item to the current item. The childItem must not yet have a parent (it will be set by this function). IMPORTANT: this does not let the model know that items have been added. Use BaseTreeModel.insertItem instead. param childItem: a BaseTreeItem that will be added param position: integer position before which the item will be added. If position is None (default) the item will be appended at the end. Returns childItem so that calls may be chained. """ if position is None: position = self.nChildren() assert childItem.parentItem is None, "childItem already has a parent: {}".format(childItem) assert childItem._model is None, "childItem already has a model: {}".format(childItem) childItem.parentItem = self childItem.model = self.model self.childItems.insert(position, childItem) return childItem
Inserts a child item to the current item. The childItem must not yet have a parent (it will be set by this function). IMPORTANT: this does not let the model know that items have been added. Use BaseTreeModel.insertItem instead. param childItem: a BaseTreeItem that will be added param position: integer position before which the item will be added. If position is None (default) the item will be appended at the end. Returns childItem so that calls may be chained.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L228-L250
titusjan/argos
argos/qt/treeitems.py
BaseTreeItem.removeChild
def removeChild(self, position): """ Removes the child at the position 'position' Calls the child item finalize to close its resources before removing it. """ assert 0 <= position <= len(self.childItems), \ "position should be 0 < {} <= {}".format(position, len(self.childItems)) self.childItems[position].finalize() self.childItems.pop(position)
python
def removeChild(self, position): """ Removes the child at the position 'position' Calls the child item finalize to close its resources before removing it. """ assert 0 <= position <= len(self.childItems), \ "position should be 0 < {} <= {}".format(position, len(self.childItems)) self.childItems[position].finalize() self.childItems.pop(position)
Removes the child at the position 'position' Calls the child item finalize to close its resources before removing it.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L253-L261
titusjan/argos
argos/qt/treeitems.py
BaseTreeItem.logBranch
def logBranch(self, indent=0, level=logging.DEBUG): """ Logs the item and all descendants, one line per child """ if 0: print(indent * " " + str(self)) else: logger.log(level, indent * " " + str(self)) for childItems in self.childItems: childItems.logBranch(indent + 1, level=level)
python
def logBranch(self, indent=0, level=logging.DEBUG): """ Logs the item and all descendants, one line per child """ if 0: print(indent * " " + str(self)) else: logger.log(level, indent * " " + str(self)) for childItems in self.childItems: childItems.logBranch(indent + 1, level=level)
Logs the item and all descendants, one line per child
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L273-L281
titusjan/argos
argos/qt/treeitems.py
AbstractLazyLoadTreeItem.fetchChildren
def fetchChildren(self): """ Fetches children. The actual work is done by _fetchAllChildren. Descendant classes should typically override that method instead of this one. """ assert self._canFetchChildren, "canFetchChildren must be True" try: childItems = self._fetchAllChildren() finally: self._canFetchChildren = False # Set to True, even if tried and failed. return childItems
python
def fetchChildren(self): """ Fetches children. The actual work is done by _fetchAllChildren. Descendant classes should typically override that method instead of this one. """ assert self._canFetchChildren, "canFetchChildren must be True" try: childItems = self._fetchAllChildren() finally: self._canFetchChildren = False # Set to True, even if tried and failed. return childItems
Fetches children. The actual work is done by _fetchAllChildren. Descendant classes should typically override that method instead of this one.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L309-L321
titusjan/argos
argos/inspector/registry.py
InspectorRegItem.create
def create(self, collector, tryImport=True): """ Creates an inspector of the registered and passes the collector to the constructor. Tries to import the class if tryImport is True. Raises ImportError if the class could not be imported. """ cls = self.getClass(tryImport=tryImport) if not self.successfullyImported: raise ImportError("Class not successfully imported: {}".format(self.exception)) return cls(collector)
python
def create(self, collector, tryImport=True): """ Creates an inspector of the registered and passes the collector to the constructor. Tries to import the class if tryImport is True. Raises ImportError if the class could not be imported. """ cls = self.getClass(tryImport=tryImport) if not self.successfullyImported: raise ImportError("Class not successfully imported: {}".format(self.exception)) return cls(collector)
Creates an inspector of the registered and passes the collector to the constructor. Tries to import the class if tryImport is True. Raises ImportError if the class could not be imported.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/registry.py#L55-L63
titusjan/argos
argos/inspector/registry.py
InspectorRegistry.registerInspector
def registerInspector(self, fullName, fullClassName, pythonPath=''): """ Registers an Inspector class. """ regInspector = InspectorRegItem(fullName, fullClassName, pythonPath=pythonPath) self.registerItem(regInspector)
python
def registerInspector(self, fullName, fullClassName, pythonPath=''): """ Registers an Inspector class. """ regInspector = InspectorRegItem(fullName, fullClassName, pythonPath=pythonPath) self.registerItem(regInspector)
Registers an Inspector class.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/registry.py#L77-L81
titusjan/argos
argos/inspector/registry.py
InspectorRegistry.getDefaultItems
def getDefaultItems(self): """ Returns a list with the default plugins in the inspector registry. """ plugins = [ InspectorRegItem(DEFAULT_INSPECTOR, 'argos.inspector.qtplugins.table.TableInspector'), InspectorRegItem('Qt/Text', 'argos.inspector.qtplugins.text.TextInspector'), InspectorRegItem('PyQtGraph/1D Line Plot', 'argos.inspector.pgplugins.lineplot1d.PgLinePlot1d'), InspectorRegItem('PyQtGraph/2D Image Plot', 'argos.inspector.pgplugins.imageplot2d.PgImagePlot2d'), ] if DEBUGGING: plugins.append(InspectorRegItem('Debug Inspector', 'argos.inspector.debug.DebugInspector')) return plugins
python
def getDefaultItems(self): """ Returns a list with the default plugins in the inspector registry. """ plugins = [ InspectorRegItem(DEFAULT_INSPECTOR, 'argos.inspector.qtplugins.table.TableInspector'), InspectorRegItem('Qt/Text', 'argos.inspector.qtplugins.text.TextInspector'), InspectorRegItem('PyQtGraph/1D Line Plot', 'argos.inspector.pgplugins.lineplot1d.PgLinePlot1d'), InspectorRegItem('PyQtGraph/2D Image Plot', 'argos.inspector.pgplugins.imageplot2d.PgImagePlot2d'), ] if DEBUGGING: plugins.append(InspectorRegItem('Debug Inspector', 'argos.inspector.debug.DebugInspector')) return plugins
Returns a list with the default plugins in the inspector registry.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/registry.py#L84-L100
titusjan/argos
argos/inspector/debug.py
DebugInspector._createConfig
def _createConfig(self): """ Creates a config tree item (CTI) hierarchy containing default children. """ rootItem = MainGroupCti('debug inspector') if DEBUGGING: # Some test config items. import numpy as np from argos.config.untypedcti import UntypedCti from argos.config.stringcti import StringCti from argos.config.intcti import IntCti from argos.config.floatcti import FloatCti, SnFloatCti from argos.config.boolcti import BoolCti, BoolGroupCti from argos.config.choicecti import ChoiceCti from argos.config.qtctis import PenCti grpItem = GroupCti("group") rootItem.insertChild(grpItem) lcItem = UntypedCti('line color', 123) grpItem.insertChild(lcItem) disabledItem = rootItem.insertChild(StringCti('disabled', "Can't touch me")) disabledItem.enabled=False grpItem.insertChild(IntCti('line-1 color', 7, minValue = -5, stepSize=2, prefix="@", suffix="%", specialValueText="I'm special")) rootItem.insertChild(StringCti('letter', 'aa', maxLength = 1)) grpItem.insertChild(FloatCti('width', 2, minValue =5, stepSize=0.45, decimals=3, prefix="@", suffix="%", specialValueText="so very special")) grpItem.insertChild(SnFloatCti('scientific', defaultData=-np.inf)) gridItem = rootItem.insertChild(BoolGroupCti('grid', True)) gridItem.insertChild(BoolCti('X-Axis', True)) gridItem.insertChild(BoolCti('Y-Axis', False)) rootItem.insertChild(ChoiceCti('hobbit', 2, editable=True, configValues=['Frodo', 'Sam', 'Pippin', 'Merry'])) myPen = QtGui.QPen(QtGui.QColor('#1C8857')) myPen.setWidth(2) myPen.setStyle(Qt.DashDotDotLine) rootItem.insertChild(PenCti('line', False, resetTo=myPen)) return rootItem
python
def _createConfig(self): """ Creates a config tree item (CTI) hierarchy containing default children. """ rootItem = MainGroupCti('debug inspector') if DEBUGGING: # Some test config items. import numpy as np from argos.config.untypedcti import UntypedCti from argos.config.stringcti import StringCti from argos.config.intcti import IntCti from argos.config.floatcti import FloatCti, SnFloatCti from argos.config.boolcti import BoolCti, BoolGroupCti from argos.config.choicecti import ChoiceCti from argos.config.qtctis import PenCti grpItem = GroupCti("group") rootItem.insertChild(grpItem) lcItem = UntypedCti('line color', 123) grpItem.insertChild(lcItem) disabledItem = rootItem.insertChild(StringCti('disabled', "Can't touch me")) disabledItem.enabled=False grpItem.insertChild(IntCti('line-1 color', 7, minValue = -5, stepSize=2, prefix="@", suffix="%", specialValueText="I'm special")) rootItem.insertChild(StringCti('letter', 'aa', maxLength = 1)) grpItem.insertChild(FloatCti('width', 2, minValue =5, stepSize=0.45, decimals=3, prefix="@", suffix="%", specialValueText="so very special")) grpItem.insertChild(SnFloatCti('scientific', defaultData=-np.inf)) gridItem = rootItem.insertChild(BoolGroupCti('grid', True)) gridItem.insertChild(BoolCti('X-Axis', True)) gridItem.insertChild(BoolCti('Y-Axis', False)) rootItem.insertChild(ChoiceCti('hobbit', 2, editable=True, configValues=['Frodo', 'Sam', 'Pippin', 'Merry'])) myPen = QtGui.QPen(QtGui.QColor('#1C8857')) myPen.setWidth(2) myPen.setStyle(Qt.DashDotDotLine) rootItem.insertChild(PenCti('line', False, resetTo=myPen)) return rootItem
Creates a config tree item (CTI) hierarchy containing default children.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/debug.py#L52-L95
titusjan/argos
argos/inspector/debug.py
DebugInspector._drawContents
def _drawContents(self, reason=None, initiator=None): """ Draws the table contents from the sliced array of the collected repo tree item. The reason and initiator parameters are ignored. See AbstractInspector.updateContents for their description. """ logger.debug("DebugInspector._drawContents: {}".format(self)) slicedArray = self.collector.getSlicedArray() if slicedArray is None: text = "<None>" else: text = ("data = {!r}, masked = {!r}, fill_value = {!r} (?= {}: {})" .format(slicedArray.data, slicedArray.mask, slicedArray.fill_value, slicedArray.data.item(), slicedArray.data.item() == slicedArray.fill_value)) logger.debug("_drawContents: {}".format(text)) logger.debug("_drawContents: {!r}".format(slicedArray)) if DEBUGGING: self.label.setText(text)
python
def _drawContents(self, reason=None, initiator=None): """ Draws the table contents from the sliced array of the collected repo tree item. The reason and initiator parameters are ignored. See AbstractInspector.updateContents for their description. """ logger.debug("DebugInspector._drawContents: {}".format(self)) slicedArray = self.collector.getSlicedArray() if slicedArray is None: text = "<None>" else: text = ("data = {!r}, masked = {!r}, fill_value = {!r} (?= {}: {})" .format(slicedArray.data, slicedArray.mask, slicedArray.fill_value, slicedArray.data.item(), slicedArray.data.item() == slicedArray.fill_value)) logger.debug("_drawContents: {}".format(text)) logger.debug("_drawContents: {!r}".format(slicedArray)) if DEBUGGING: self.label.setText(text)
Draws the table contents from the sliced array of the collected repo tree item. The reason and initiator parameters are ignored. See AbstractInspector.updateContents for their description.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/debug.py#L98-L119
titusjan/argos
argos/qt/treemodels.py
BaseTreeModel.data
def data(self, index, role=Qt.DisplayRole): """ Returns the data stored under the given role for the item referred to by the index. Calls self.itemData for valid items. Descendants should typically override itemData instead of this function. """ try: if index.isValid(): item = self.getItem(index, altItem=self.invisibleRootItem) return self.itemData(item, index.column(), role=role) else: return None except Exception as ex: # This Qt slot is called directly from the event loop so uncaught exception make the # application crash (exceptions can come from plugins here). Instead of crashing we # show the error message in the table/tree and hope the users report the error. if not DEBUGGING and role in (Qt.DisplayRole, Qt.EditRole, Qt.ToolTipRole, Qt.StatusTipRole, Qt.WhatsThisRole): return repr(ex) else: raise
python
def data(self, index, role=Qt.DisplayRole): """ Returns the data stored under the given role for the item referred to by the index. Calls self.itemData for valid items. Descendants should typically override itemData instead of this function. """ try: if index.isValid(): item = self.getItem(index, altItem=self.invisibleRootItem) return self.itemData(item, index.column(), role=role) else: return None except Exception as ex: # This Qt slot is called directly from the event loop so uncaught exception make the # application crash (exceptions can come from plugins here). Instead of crashing we # show the error message in the table/tree and hope the users report the error. if not DEBUGGING and role in (Qt.DisplayRole, Qt.EditRole, Qt.ToolTipRole, Qt.StatusTipRole, Qt.WhatsThisRole): return repr(ex) else: raise
Returns the data stored under the given role for the item referred to by the index. Calls self.itemData for valid items. Descendants should typically override itemData instead of this function.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L82-L102
titusjan/argos
argos/qt/treemodels.py
BaseTreeModel.itemData
def itemData(self, item, column, role=Qt.DisplayRole): """ Returns the data stored under the given role for the item. O The column parameter may be used to differentiate behavior per column. The default implementation does nothing. Descendants should typically override this function instead of data() Note: If you do not have a value to return, return an invalid QVariant instead of returning 0. (This means returning None in Python) """ if role == Qt.DecorationRole: if column == self.COL_DECORATION: return item.decoration elif role == Qt.FontRole: return item.font elif role == Qt.ForegroundRole: return item.foregroundBrush elif role == Qt.BackgroundRole: return item.backgroundBrush elif role == Qt.SizeHintRole: return self.cellSizeHint if item.sizeHint is None else item.sizeHint return None
python
def itemData(self, item, column, role=Qt.DisplayRole): """ Returns the data stored under the given role for the item. O The column parameter may be used to differentiate behavior per column. The default implementation does nothing. Descendants should typically override this function instead of data() Note: If you do not have a value to return, return an invalid QVariant instead of returning 0. (This means returning None in Python) """ if role == Qt.DecorationRole: if column == self.COL_DECORATION: return item.decoration elif role == Qt.FontRole: return item.font elif role == Qt.ForegroundRole: return item.foregroundBrush elif role == Qt.BackgroundRole: return item.backgroundBrush elif role == Qt.SizeHintRole: return self.cellSizeHint if item.sizeHint is None else item.sizeHint return None
Returns the data stored under the given role for the item. O The column parameter may be used to differentiate behavior per column. The default implementation does nothing. Descendants should typically override this function instead of data() Note: If you do not have a value to return, return an invalid QVariant instead of returning 0. (This means returning None in Python)
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L105-L131
titusjan/argos
argos/qt/treemodels.py
BaseTreeModel.index
def index(self, row, column, parentIndex=QtCore.QModelIndex()): """ Returns the index of the item in the model specified by the given row, column and parent index. Since each item contains information for an entire row of data, we create a model index to uniquely identify it by calling createIndex() it with the row and column numbers and a pointer to the item. (In the data() function, we will use the item pointer and column number to access the data associated with the model index; in this model, the row number is not needed to identify data.) When reimplementing this function in a subclass, call createIndex() to generate model indexes that other components can use to refer to items in your model. """ # logger.debug(" called index({}, {}, {}) {}" # .format(parentIndex.row(), parentIndex.column(), parentIndex.isValid(), # parentIndex.isValid() and parentIndex.column() != 0)) parentItem = self.getItem(parentIndex, altItem=self.invisibleRootItem) #logger.debug(" Getting row {} from parentItem: {}".format(row, parentItem)) if not (0 <= row < parentItem.nChildren()): # Can happen when deleting the last child. #logger.warn("Index row {} invalid for parent item: {}".format(row, parentItem)) return QtCore.QModelIndex() if not (0 <= column < self.columnCount()): #logger.warn("Index column {} invalid for parent item: {}".format(column, parentItem)) return QtCore.QModelIndex() childItem = parentItem.child(row) if childItem: return self.createIndex(row, column, childItem) else: logger.warn("No child item found at row {} for parent item: {}".format(row, parentItem)) return QtCore.QModelIndex()
python
def index(self, row, column, parentIndex=QtCore.QModelIndex()): """ Returns the index of the item in the model specified by the given row, column and parent index. Since each item contains information for an entire row of data, we create a model index to uniquely identify it by calling createIndex() it with the row and column numbers and a pointer to the item. (In the data() function, we will use the item pointer and column number to access the data associated with the model index; in this model, the row number is not needed to identify data.) When reimplementing this function in a subclass, call createIndex() to generate model indexes that other components can use to refer to items in your model. """ # logger.debug(" called index({}, {}, {}) {}" # .format(parentIndex.row(), parentIndex.column(), parentIndex.isValid(), # parentIndex.isValid() and parentIndex.column() != 0)) parentItem = self.getItem(parentIndex, altItem=self.invisibleRootItem) #logger.debug(" Getting row {} from parentItem: {}".format(row, parentItem)) if not (0 <= row < parentItem.nChildren()): # Can happen when deleting the last child. #logger.warn("Index row {} invalid for parent item: {}".format(row, parentItem)) return QtCore.QModelIndex() if not (0 <= column < self.columnCount()): #logger.warn("Index column {} invalid for parent item: {}".format(column, parentItem)) return QtCore.QModelIndex() childItem = parentItem.child(row) if childItem: return self.createIndex(row, column, childItem) else: logger.warn("No child item found at row {} for parent item: {}".format(row, parentItem)) return QtCore.QModelIndex()
Returns the index of the item in the model specified by the given row, column and parent index. Since each item contains information for an entire row of data, we create a model index to uniquely identify it by calling createIndex() it with the row and column numbers and a pointer to the item. (In the data() function, we will use the item pointer and column number to access the data associated with the model index; in this model, the row number is not needed to identify data.) When reimplementing this function in a subclass, call createIndex() to generate model indexes that other components can use to refer to items in your model.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L159-L193
titusjan/argos
argos/qt/treemodels.py
BaseTreeModel.parent
def parent(self, index): """ Returns the parent of the model item with the given index. If the item has no parent, an invalid QModelIndex is returned. A common convention used in models that expose tree data structures is that only items in the first column have children. For that case, when reimplementing this function in a subclass the column of the returned QModelIndex would be 0. (This is done here.) When reimplementing this function in a subclass, be careful to avoid calling QModelIndex member functions, such as QModelIndex.parent(), since indexes belonging to your model will simply call your implementation, leading to infinite recursion. """ if not index.isValid(): return QtCore.QModelIndex() childItem = self.getItem(index, altItem=self.invisibleRootItem) parentItem = childItem.parentItem if parentItem == self.invisibleRootItem: return QtCore.QModelIndex() return self.createIndex(parentItem.childNumber(), 0, parentItem)
python
def parent(self, index): """ Returns the parent of the model item with the given index. If the item has no parent, an invalid QModelIndex is returned. A common convention used in models that expose tree data structures is that only items in the first column have children. For that case, when reimplementing this function in a subclass the column of the returned QModelIndex would be 0. (This is done here.) When reimplementing this function in a subclass, be careful to avoid calling QModelIndex member functions, such as QModelIndex.parent(), since indexes belonging to your model will simply call your implementation, leading to infinite recursion. """ if not index.isValid(): return QtCore.QModelIndex() childItem = self.getItem(index, altItem=self.invisibleRootItem) parentItem = childItem.parentItem if parentItem == self.invisibleRootItem: return QtCore.QModelIndex() return self.createIndex(parentItem.childNumber(), 0, parentItem)
Returns the parent of the model item with the given index. If the item has no parent, an invalid QModelIndex is returned. A common convention used in models that expose tree data structures is that only items in the first column have children. For that case, when reimplementing this function in a subclass the column of the returned QModelIndex would be 0. (This is done here.) When reimplementing this function in a subclass, be careful to avoid calling QModelIndex member functions, such as QModelIndex.parent(), since indexes belonging to your model will simply call your implementation, leading to infinite recursion.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L196-L217
titusjan/argos
argos/qt/treemodels.py
BaseTreeModel.rowCount
def rowCount(self, parentIndex=QtCore.QModelIndex()): """ Returns the number of rows under the given parent. When the parent is valid it means that rowCount is returning the number of children of parent. Note: When implementing a table based model, rowCount() should return 0 when the parent is valid. """ parentItem = self.getItem(parentIndex, altItem=self.invisibleRootItem) return parentItem.nChildren()
python
def rowCount(self, parentIndex=QtCore.QModelIndex()): """ Returns the number of rows under the given parent. When the parent is valid it means that rowCount is returning the number of children of parent. Note: When implementing a table based model, rowCount() should return 0 when the parent is valid. """ parentItem = self.getItem(parentIndex, altItem=self.invisibleRootItem) return parentItem.nChildren()
Returns the number of rows under the given parent. When the parent is valid it means that rowCount is returning the number of children of parent. Note: When implementing a table based model, rowCount() should return 0 when the parent is valid.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L220-L228
titusjan/argos
argos/qt/treemodels.py
BaseTreeModel.hasChildren
def hasChildren(self, parentIndex=QtCore.QModelIndex()): """ Returns true if parent has any children; otherwise returns false. Use rowCount() on the parent to find out the number of children. """ parentItem = self.getItem(parentIndex, altItem=self.invisibleRootItem) return parentItem.hasChildren()
python
def hasChildren(self, parentIndex=QtCore.QModelIndex()): """ Returns true if parent has any children; otherwise returns false. Use rowCount() on the parent to find out the number of children. """ parentItem = self.getItem(parentIndex, altItem=self.invisibleRootItem) return parentItem.hasChildren()
Returns true if parent has any children; otherwise returns false. Use rowCount() on the parent to find out the number of children.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L231-L236
titusjan/argos
argos/qt/treemodels.py
BaseTreeModel.setData
def setData(self, index, value, role=Qt.EditRole): """ Sets the role data for the item at index to value. Returns true if successful; otherwise returns false. The dataChanged and sigItemChanged signals will be emitted if the data was successfully set. Descendants should typically override setItemData function instead of setData() """ if role != Qt.CheckStateRole and role != Qt.EditRole: return False treeItem = self.getItem(index, altItem=self.invisibleRootItem) try: result = self.setItemData(treeItem, index.column(), value, role=role) if result: # Emit dataChanged to update the tree view # TODO, update the entire tree? # A check box can have a tristate checkbox as parent which state depends # on the state of this child check box. Therefore we update the parentIndex # and the descendants. self.emitDataChanged(treeItem) # Emit sigItemChanged to update other widgets. self.sigItemChanged.emit(treeItem) return result except Exception as ex: # When does this still happen? Can we remove it? logger.warn("Unable to set data: {}".format(ex)) if DEBUGGING: raise return False
python
def setData(self, index, value, role=Qt.EditRole): """ Sets the role data for the item at index to value. Returns true if successful; otherwise returns false. The dataChanged and sigItemChanged signals will be emitted if the data was successfully set. Descendants should typically override setItemData function instead of setData() """ if role != Qt.CheckStateRole and role != Qt.EditRole: return False treeItem = self.getItem(index, altItem=self.invisibleRootItem) try: result = self.setItemData(treeItem, index.column(), value, role=role) if result: # Emit dataChanged to update the tree view # TODO, update the entire tree? # A check box can have a tristate checkbox as parent which state depends # on the state of this child check box. Therefore we update the parentIndex # and the descendants. self.emitDataChanged(treeItem) # Emit sigItemChanged to update other widgets. self.sigItemChanged.emit(treeItem) return result except Exception as ex: # When does this still happen? Can we remove it? logger.warn("Unable to set data: {}".format(ex)) if DEBUGGING: raise return False
Sets the role data for the item at index to value. Returns true if successful; otherwise returns false. The dataChanged and sigItemChanged signals will be emitted if the data was successfully set. Descendants should typically override setItemData function instead of setData()
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L239-L271
titusjan/argos
argos/qt/treemodels.py
BaseTreeModel.getItem
def getItem(self, index, altItem=None): """ Returns the TreeItem for the given index. Returns the altItem if the index is invalid. """ if index.isValid(): item = index.internalPointer() if item: return item #return altItem if altItem is not None else self.invisibleRootItem # TODO: remove return altItem
python
def getItem(self, index, altItem=None): """ Returns the TreeItem for the given index. Returns the altItem if the index is invalid. """ if index.isValid(): item = index.internalPointer() if item: return item #return altItem if altItem is not None else self.invisibleRootItem # TODO: remove return altItem
Returns the TreeItem for the given index. Returns the altItem if the index is invalid.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L305-L314
titusjan/argos
argos/qt/treemodels.py
BaseTreeModel.insertItem
def insertItem(self, childItem, position=None, parentIndex=None): """ Inserts a childItem before row 'position' under the parent index. If position is None the child will be appended as the last child of the parent. Returns the index of the new inserted child. """ if parentIndex is None: parentIndex=QtCore.QModelIndex() parentItem = self.getItem(parentIndex, altItem=self.invisibleRootItem) nChildren = parentItem.nChildren() if position is None: position = nChildren assert 0 <= position <= nChildren, \ "position should be 0 < {} <= {}".format(position, nChildren) self.beginInsertRows(parentIndex, position, position) try: parentItem.insertChild(childItem, position) finally: self.endInsertRows() childIndex = self.index(position, 0, parentIndex) assert childIndex.isValid(), "Sanity check failed: childIndex not valid" return childIndex
python
def insertItem(self, childItem, position=None, parentIndex=None): """ Inserts a childItem before row 'position' under the parent index. If position is None the child will be appended as the last child of the parent. Returns the index of the new inserted child. """ if parentIndex is None: parentIndex=QtCore.QModelIndex() parentItem = self.getItem(parentIndex, altItem=self.invisibleRootItem) nChildren = parentItem.nChildren() if position is None: position = nChildren assert 0 <= position <= nChildren, \ "position should be 0 < {} <= {}".format(position, nChildren) self.beginInsertRows(parentIndex, position, position) try: parentItem.insertChild(childItem, position) finally: self.endInsertRows() childIndex = self.index(position, 0, parentIndex) assert childIndex.isValid(), "Sanity check failed: childIndex not valid" return childIndex
Inserts a childItem before row 'position' under the parent index. If position is None the child will be appended as the last child of the parent. Returns the index of the new inserted child.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L317-L343
titusjan/argos
argos/qt/treemodels.py
BaseTreeModel.removeAllChildrenAtIndex
def removeAllChildrenAtIndex(self, parentIndex): """ Removes all children of the item at the parentIndex. The children's finalize method is called before removing them to give them a chance to close their resources """ if not parentIndex.isValid(): logger.debug("No valid item selected for deletion (ignored).") return parentItem = self.getItem(parentIndex, None) logger.debug("Removing children of {!r}".format(parentItem)) assert parentItem, "parentItem not found" #firstChildRow = self.index(0, 0, parentIndex).row() #lastChildRow = self.index(parentItem.nChildren()-1, 0, parentIndex).row() #logger.debug("Removing rows: {} to {}".format(firstChildRow, lastChildRow)) #self.beginRemoveRows(parentIndex, firstChildRow, lastChildRow) self.beginRemoveRows(parentIndex, 0, parentItem.nChildren()-1) try: parentItem.removeAllChildren() finally: self.endRemoveRows() logger.debug("removeAllChildrenAtIndex completed")
python
def removeAllChildrenAtIndex(self, parentIndex): """ Removes all children of the item at the parentIndex. The children's finalize method is called before removing them to give them a chance to close their resources """ if not parentIndex.isValid(): logger.debug("No valid item selected for deletion (ignored).") return parentItem = self.getItem(parentIndex, None) logger.debug("Removing children of {!r}".format(parentItem)) assert parentItem, "parentItem not found" #firstChildRow = self.index(0, 0, parentIndex).row() #lastChildRow = self.index(parentItem.nChildren()-1, 0, parentIndex).row() #logger.debug("Removing rows: {} to {}".format(firstChildRow, lastChildRow)) #self.beginRemoveRows(parentIndex, firstChildRow, lastChildRow) self.beginRemoveRows(parentIndex, 0, parentItem.nChildren()-1) try: parentItem.removeAllChildren() finally: self.endRemoveRows() logger.debug("removeAllChildrenAtIndex completed")
Removes all children of the item at the parentIndex. The children's finalize method is called before removing them to give them a chance to close their resources
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L346-L370
titusjan/argos
argos/qt/treemodels.py
BaseTreeModel.deleteItemAtIndex
def deleteItemAtIndex(self, itemIndex): """ Removes the item at the itemIndex. The item's finalize method is called before removing so it can close its resources. """ if not itemIndex.isValid(): logger.debug("No valid item selected for deletion (ignored).") return item = self.getItem(itemIndex, "<no item>") logger.debug("deleteItemAtIndex: removing {}".format(item)) parentIndex = itemIndex.parent() parentItem = self.getItem(parentIndex, altItem=self.invisibleRootItem) row = itemIndex.row() self.beginRemoveRows(parentIndex, row, row) try: parentItem.removeChild(row) finally: self.endRemoveRows() logger.debug("deleteItemAtIndex completed")
python
def deleteItemAtIndex(self, itemIndex): """ Removes the item at the itemIndex. The item's finalize method is called before removing so it can close its resources. """ if not itemIndex.isValid(): logger.debug("No valid item selected for deletion (ignored).") return item = self.getItem(itemIndex, "<no item>") logger.debug("deleteItemAtIndex: removing {}".format(item)) parentIndex = itemIndex.parent() parentItem = self.getItem(parentIndex, altItem=self.invisibleRootItem) row = itemIndex.row() self.beginRemoveRows(parentIndex, row, row) try: parentItem.removeChild(row) finally: self.endRemoveRows() logger.debug("deleteItemAtIndex completed")
Removes the item at the itemIndex. The item's finalize method is called before removing so it can close its resources.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L373-L393
titusjan/argos
argos/qt/treemodels.py
BaseTreeModel.replaceItemAtIndex
def replaceItemAtIndex(self, newItem, oldItemIndex): """ Removes the item at the itemIndex and insert a new item instead. """ oldItem = self.getItem(oldItemIndex) childNumber = oldItem.childNumber() parentIndex = oldItemIndex.parent() self.deleteItemAtIndex(oldItemIndex) insertedIndex = self.insertItem(newItem, position=childNumber, parentIndex=parentIndex) return insertedIndex
python
def replaceItemAtIndex(self, newItem, oldItemIndex): """ Removes the item at the itemIndex and insert a new item instead. """ oldItem = self.getItem(oldItemIndex) childNumber = oldItem.childNumber() parentIndex = oldItemIndex.parent() self.deleteItemAtIndex(oldItemIndex) insertedIndex = self.insertItem(newItem, position=childNumber, parentIndex=parentIndex) return insertedIndex
Removes the item at the itemIndex and insert a new item instead.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L396-L404
titusjan/argos
argos/qt/treemodels.py
BaseTreeModel.findTopLevelItemIndex
def findTopLevelItemIndex(self, childIndex): """ Traverses the tree upwards from childItem until its top level ancestor item is found. Top level items are items that are direct children of the (invisible) root item. This function therefore raises an exception when called with the root item. """ if self.isTopLevelIndex(childIndex): return childIndex else: return self.findTopLevelItemIndex(childIndex.parent())
python
def findTopLevelItemIndex(self, childIndex): """ Traverses the tree upwards from childItem until its top level ancestor item is found. Top level items are items that are direct children of the (invisible) root item. This function therefore raises an exception when called with the root item. """ if self.isTopLevelIndex(childIndex): return childIndex else: return self.findTopLevelItemIndex(childIndex.parent())
Traverses the tree upwards from childItem until its top level ancestor item is found. Top level items are items that are direct children of the (invisible) root item. This function therefore raises an exception when called with the root item.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L431-L439
titusjan/argos
argos/qt/treemodels.py
BaseTreeModel.findItemAndIndexPath
def findItemAndIndexPath(self, path, startIndex=None): """ Searches all the model recursively (starting at startIndex) for an item where item.nodePath == path. Returns list of (item, itemIndex) tuples from the start index to that node. Raises IndexError if the item cannot be found. If startIndex is None, or path starts with a slash, searching begins at the (invisible) root item. """ def _getIndexAndItemByName(nodeName, parentItem, parentIndex): """ Searches the parent for a direct child having the nodeName. Returns (item, itemIndex) tuple. Raises IndexError if the item cannot be found. """ if self.canFetchMore(parentIndex): self.fetchMore(parentIndex) for rowNr, childItem in enumerate(parentItem.childItems): if childItem.nodeName == nodeName: childIndex = self.index(rowNr, 0, parentIndex=parentIndex) return (childItem, childIndex) raise IndexError("Item not found: {!r}".format(path)) def _auxGetByPath(parts, item, index): "Aux function that does the actual recursive search" #logger.debug("_auxGetByPath item={}, parts={}".format(item, parts)) if len(parts) == 0: return [(item, index)] head, tail = parts[0], parts[1:] if head == '': # Two consecutive slashes. Just go one level deeper. return _auxGetByPath(tail, item, index) else: childItem, childIndex = _getIndexAndItemByName(head, item, index) return [(item, index)] + _auxGetByPath(tail, childItem, childIndex) # The actual body of findItemAndIndexPath starts here check_is_a_string(path) if not path: raise IndexError("Item not found: {!r}".format(path)) if startIndex is None or path.startswith('/'): startIndex = QtCore.QModelIndex() startItem = self.invisibleRootItem else: startItem = self.getItem(startIndex, None) if not startItem: raise IndexError("Item not found: {!r}. No start item!".format(path)) return _auxGetByPath(path.split('/'), startItem, startIndex)
python
def findItemAndIndexPath(self, path, startIndex=None): """ Searches all the model recursively (starting at startIndex) for an item where item.nodePath == path. Returns list of (item, itemIndex) tuples from the start index to that node. Raises IndexError if the item cannot be found. If startIndex is None, or path starts with a slash, searching begins at the (invisible) root item. """ def _getIndexAndItemByName(nodeName, parentItem, parentIndex): """ Searches the parent for a direct child having the nodeName. Returns (item, itemIndex) tuple. Raises IndexError if the item cannot be found. """ if self.canFetchMore(parentIndex): self.fetchMore(parentIndex) for rowNr, childItem in enumerate(parentItem.childItems): if childItem.nodeName == nodeName: childIndex = self.index(rowNr, 0, parentIndex=parentIndex) return (childItem, childIndex) raise IndexError("Item not found: {!r}".format(path)) def _auxGetByPath(parts, item, index): "Aux function that does the actual recursive search" #logger.debug("_auxGetByPath item={}, parts={}".format(item, parts)) if len(parts) == 0: return [(item, index)] head, tail = parts[0], parts[1:] if head == '': # Two consecutive slashes. Just go one level deeper. return _auxGetByPath(tail, item, index) else: childItem, childIndex = _getIndexAndItemByName(head, item, index) return [(item, index)] + _auxGetByPath(tail, childItem, childIndex) # The actual body of findItemAndIndexPath starts here check_is_a_string(path) if not path: raise IndexError("Item not found: {!r}".format(path)) if startIndex is None or path.startswith('/'): startIndex = QtCore.QModelIndex() startItem = self.invisibleRootItem else: startItem = self.getItem(startIndex, None) if not startItem: raise IndexError("Item not found: {!r}. No start item!".format(path)) return _auxGetByPath(path.split('/'), startItem, startIndex)
Searches all the model recursively (starting at startIndex) for an item where item.nodePath == path. Returns list of (item, itemIndex) tuples from the start index to that node. Raises IndexError if the item cannot be found. If startIndex is None, or path starts with a slash, searching begins at the (invisible) root item.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L442-L496
titusjan/argos
argos/qt/treemodels.py
BaseTreeModel.logItems
def logItems(self, level=logging.DEBUG): """ rootItem """ rootItem = self.rootItem() if rootItem is None: logger.debug("No items in: {}".format(self)) else: rootItem.logBranch(level=level)
python
def logItems(self, level=logging.DEBUG): """ rootItem """ rootItem = self.rootItem() if rootItem is None: logger.debug("No items in: {}".format(self)) else: rootItem.logBranch(level=level)
rootItem
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L508-L515
titusjan/argos
argos/qt/togglecolumn.py
ToggleColumnMixIn.addHeaderContextMenu
def addHeaderContextMenu(self, checked = None, checkable = None, enabled = None): """ Adds the context menu from using header information checked can be a header_name -> boolean dictionary. If given, headers with the key name will get the checked value from the dictionary. The corresponding column will be hidden if checked is False. checkable can be a header_name -> boolean dictionary. If given, header actions with the key name will get the checkable value from the dictionary. (Default True) enabled can be a header_name -> boolean dictionary. If given, header actions with the key name will get the enabled value from the dictionary. (Default True) """ checked = checked if checked is not None else {} checkable = checkable if checkable is not None else {} enabled = enabled if enabled is not None else {} horizontal_header = self.horizontalHeader() horizontal_header.setContextMenuPolicy(Qt.ActionsContextMenu) self.toggle_column_actions_group = QtWidgets.QActionGroup(self) self.toggle_column_actions_group.setExclusive(False) self.__toggle_functions = [] # for keeping references for col in range(horizontal_header.count()): column_label = self.model().headerData(col, Qt.Horizontal, Qt.DisplayRole) #logger.debug("Adding: col {}: {}".format(col, column_label)) action = QtWidgets.QAction(str(column_label), self.toggle_column_actions_group, checkable = checkable.get(column_label, True), enabled = enabled.get(column_label, True), toolTip = "Shows or hides the {} column".format(column_label)) func = self.__makeShowColumnFunction(col) self.__toggle_functions.append(func) # keep reference horizontal_header.addAction(action) is_checked = checked.get(column_label, not horizontal_header.isSectionHidden(col)) horizontal_header.setSectionHidden(col, not is_checked) action.setChecked(is_checked) action.toggled.connect(func)
python
def addHeaderContextMenu(self, checked = None, checkable = None, enabled = None): """ Adds the context menu from using header information checked can be a header_name -> boolean dictionary. If given, headers with the key name will get the checked value from the dictionary. The corresponding column will be hidden if checked is False. checkable can be a header_name -> boolean dictionary. If given, header actions with the key name will get the checkable value from the dictionary. (Default True) enabled can be a header_name -> boolean dictionary. If given, header actions with the key name will get the enabled value from the dictionary. (Default True) """ checked = checked if checked is not None else {} checkable = checkable if checkable is not None else {} enabled = enabled if enabled is not None else {} horizontal_header = self.horizontalHeader() horizontal_header.setContextMenuPolicy(Qt.ActionsContextMenu) self.toggle_column_actions_group = QtWidgets.QActionGroup(self) self.toggle_column_actions_group.setExclusive(False) self.__toggle_functions = [] # for keeping references for col in range(horizontal_header.count()): column_label = self.model().headerData(col, Qt.Horizontal, Qt.DisplayRole) #logger.debug("Adding: col {}: {}".format(col, column_label)) action = QtWidgets.QAction(str(column_label), self.toggle_column_actions_group, checkable = checkable.get(column_label, True), enabled = enabled.get(column_label, True), toolTip = "Shows or hides the {} column".format(column_label)) func = self.__makeShowColumnFunction(col) self.__toggle_functions.append(func) # keep reference horizontal_header.addAction(action) is_checked = checked.get(column_label, not horizontal_header.isSectionHidden(col)) horizontal_header.setSectionHidden(col, not is_checked) action.setChecked(is_checked) action.toggled.connect(func)
Adds the context menu from using header information checked can be a header_name -> boolean dictionary. If given, headers with the key name will get the checked value from the dictionary. The corresponding column will be hidden if checked is False. checkable can be a header_name -> boolean dictionary. If given, header actions with the key name will get the checkable value from the dictionary. (Default True) enabled can be a header_name -> boolean dictionary. If given, header actions with the key name will get the enabled value from the dictionary. (Default True)
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/togglecolumn.py#L41-L79
titusjan/argos
argos/qt/togglecolumn.py
ToggleColumnMixIn.__makeShowColumnFunction
def __makeShowColumnFunction(self, column_idx): """ Creates a function that shows or hides a column.""" show_column = lambda checked: self.setColumnHidden(column_idx, not checked) return show_column
python
def __makeShowColumnFunction(self, column_idx): """ Creates a function that shows or hides a column.""" show_column = lambda checked: self.setColumnHidden(column_idx, not checked) return show_column
Creates a function that shows or hides a column.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/togglecolumn.py#L88-L91
titusjan/argos
argos/qt/togglecolumn.py
ToggleColumnMixIn.readViewSettings
def readViewSettings(self, key, settings=None): """ Reads the persistent program settings :param key: key where the setting will be read from :param settings: optional QSettings object which can have a group already opened. :returns: True if the header state was restored, otherwise returns False """ #logger.debug("Reading view settings for: {}".format(key)) if settings is None: settings = QtCore.QSettings() horizontal_header = self.horizontalHeader() header_restored = horizontal_header.restoreState(settings.value(key)) # update actions for col, action in enumerate(horizontal_header.actions()): is_checked = not horizontal_header.isSectionHidden(col) action.setChecked(is_checked) return header_restored
python
def readViewSettings(self, key, settings=None): """ Reads the persistent program settings :param key: key where the setting will be read from :param settings: optional QSettings object which can have a group already opened. :returns: True if the header state was restored, otherwise returns False """ #logger.debug("Reading view settings for: {}".format(key)) if settings is None: settings = QtCore.QSettings() horizontal_header = self.horizontalHeader() header_restored = horizontal_header.restoreState(settings.value(key)) # update actions for col, action in enumerate(horizontal_header.actions()): is_checked = not horizontal_header.isSectionHidden(col) action.setChecked(is_checked) return header_restored
Reads the persistent program settings :param key: key where the setting will be read from :param settings: optional QSettings object which can have a group already opened. :returns: True if the header state was restored, otherwise returns False
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/togglecolumn.py#L94-L113
titusjan/argos
argos/qt/togglecolumn.py
ToggleColumnMixIn.saveProfile
def saveProfile(self, key, settings=None): """ Writes the view settings to the persistent store :param key: key where the setting will be read from :param settings: optional QSettings object which can have a group already opened. """ #logger.debug("Writing view settings for: {}".format(key)) if settings is None: settings = QtCore.QSettings() settings.setValue(key, self.horizontalHeader().saveState())
python
def saveProfile(self, key, settings=None): """ Writes the view settings to the persistent store :param key: key where the setting will be read from :param settings: optional QSettings object which can have a group already opened. """ #logger.debug("Writing view settings for: {}".format(key)) if settings is None: settings = QtCore.QSettings() settings.setValue(key, self.horizontalHeader().saveState())
Writes the view settings to the persistent store :param key: key where the setting will be read from :param settings: optional QSettings object which can have a group already opened.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/togglecolumn.py#L115-L123
titusjan/argos
argos/qt/registry.py
ClassRegItem.descriptionHtml
def descriptionHtml(self): """ HTML help describing the class. For use in the detail editor. """ if self.cls is None: return None elif hasattr(self.cls, 'descriptionHtml'): return self.cls.descriptionHtml() else: return ''
python
def descriptionHtml(self): """ HTML help describing the class. For use in the detail editor. """ if self.cls is None: return None elif hasattr(self.cls, 'descriptionHtml'): return self.cls.descriptionHtml() else: return ''
HTML help describing the class. For use in the detail editor.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registry.py#L152-L160
titusjan/argos
argos/qt/registry.py
ClassRegItem.tryImportClass
def tryImportClass(self): """ Tries to import the registered class. Will set the exception property if and error occurred. """ logger.info("Importing: {}".format(self.fullClassName)) self._triedImport = True self._exception = None self._cls = None try: for pyPath in self.pythonPath.split(':'): if pyPath and pyPath not in sys.path: logger.debug("Appending {!r} to the PythonPath.".format(pyPath)) sys.path.append(pyPath) self._cls = import_symbol(self.fullClassName) # TODO: check class? except Exception as ex: self._exception = ex logger.warn("Unable to import {!r}: {}".format(self.fullClassName, ex)) if DEBUGGING: raise
python
def tryImportClass(self): """ Tries to import the registered class. Will set the exception property if and error occurred. """ logger.info("Importing: {}".format(self.fullClassName)) self._triedImport = True self._exception = None self._cls = None try: for pyPath in self.pythonPath.split(':'): if pyPath and pyPath not in sys.path: logger.debug("Appending {!r} to the PythonPath.".format(pyPath)) sys.path.append(pyPath) self._cls = import_symbol(self.fullClassName) # TODO: check class? except Exception as ex: self._exception = ex logger.warn("Unable to import {!r}: {}".format(self.fullClassName, ex)) if DEBUGGING: raise
Tries to import the registered class. Will set the exception property if and error occurred.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registry.py#L187-L205
titusjan/argos
argos/qt/registry.py
ClassRegItem.getClass
def getClass(self, tryImport=True): """ Gets the underlying class. Tries to import if tryImport is True (the default). Returns None if the import has failed (the exception property will contain the reason) """ if not self.triedImport and tryImport: self.tryImportClass() return self._cls
python
def getClass(self, tryImport=True): """ Gets the underlying class. Tries to import if tryImport is True (the default). Returns None if the import has failed (the exception property will contain the reason) """ if not self.triedImport and tryImport: self.tryImportClass() return self._cls
Gets the underlying class. Tries to import if tryImport is True (the default). Returns None if the import has failed (the exception property will contain the reason)
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registry.py#L208-L215
titusjan/argos
argos/qt/registry.py
ClassRegistry.registerItem
def registerItem(self, regItem): """ Adds a ClassRegItem object to the registry. """ check_class(regItem, ClassRegItem) if regItem.identifier in self._index: oldRegItem = self._index[regItem.identifier] logger.warn("Class key {!r} already registered as {}. Removing old regItem." .format(regItem.identifier, oldRegItem.fullClassName)) self.removeItem(oldRegItem) logger.info("Registering {!r} with {}".format(regItem.identifier, regItem.fullClassName)) self._items.append(regItem) self._index[regItem.identifier] = regItem
python
def registerItem(self, regItem): """ Adds a ClassRegItem object to the registry. """ check_class(regItem, ClassRegItem) if regItem.identifier in self._index: oldRegItem = self._index[regItem.identifier] logger.warn("Class key {!r} already registered as {}. Removing old regItem." .format(regItem.identifier, oldRegItem.fullClassName)) self.removeItem(oldRegItem) logger.info("Registering {!r} with {}".format(regItem.identifier, regItem.fullClassName)) self._items.append(regItem) self._index[regItem.identifier] = regItem
Adds a ClassRegItem object to the registry.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registry.py#L281-L293
titusjan/argos
argos/qt/registry.py
ClassRegistry.removeItem
def removeItem(self, regItem): """ Removes a ClassRegItem object to the registry. Will raise a KeyError if the regItem is not registered. """ check_class(regItem, ClassRegItem) logger.info("Removing {!r} containing {}".format(regItem.identifier, regItem.fullClassName)) del self._index[regItem.identifier] idx = self._items.index(regItem) del self._items[idx]
python
def removeItem(self, regItem): """ Removes a ClassRegItem object to the registry. Will raise a KeyError if the regItem is not registered. """ check_class(regItem, ClassRegItem) logger.info("Removing {!r} containing {}".format(regItem.identifier, regItem.fullClassName)) del self._index[regItem.identifier] idx = self._items.index(regItem) del self._items[idx]
Removes a ClassRegItem object to the registry. Will raise a KeyError if the regItem is not registered.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registry.py#L296-L305
titusjan/argos
argos/qt/registry.py
ClassRegistry.loadOrInitSettings
def loadOrInitSettings(self, groupName=None): """ Reads the registry items from the persistent settings store, falls back on the default plugins if there are no settings in the store for this registry. """ groupName = groupName if groupName else self.settingsGroupName settings = QtCore.QSettings() #for key in sorted(settings.allKeys()): # print(key) if containsSettingsGroup(groupName, settings): self.loadSettings(groupName) else: logger.info("Group {!r} not found, falling back on default settings".format(groupName)) for item in self.getDefaultItems(): self.registerItem(item) self.saveSettings(groupName) assert containsSettingsGroup(groupName, settings), \ "Sanity check failed. {} not found".format(groupName)
python
def loadOrInitSettings(self, groupName=None): """ Reads the registry items from the persistent settings store, falls back on the default plugins if there are no settings in the store for this registry. """ groupName = groupName if groupName else self.settingsGroupName settings = QtCore.QSettings() #for key in sorted(settings.allKeys()): # print(key) if containsSettingsGroup(groupName, settings): self.loadSettings(groupName) else: logger.info("Group {!r} not found, falling back on default settings".format(groupName)) for item in self.getDefaultItems(): self.registerItem(item) self.saveSettings(groupName) assert containsSettingsGroup(groupName, settings), \ "Sanity check failed. {} not found".format(groupName)
Reads the registry items from the persistent settings store, falls back on the default plugins if there are no settings in the store for this registry.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registry.py#L308-L326
titusjan/argos
argos/qt/registry.py
ClassRegistry.loadSettings
def loadSettings(self, groupName=None): """ Reads the registry items from the persistent settings store. """ groupName = groupName if groupName else self.settingsGroupName settings = QtCore.QSettings() logger.info("Reading {!r} from: {}".format(groupName, settings.fileName())) settings.beginGroup(groupName) self.clear() try: for key in settings.childKeys(): if key.startswith('item'): dct = ast.literal_eval(settings.value(key)) regItem = self._itemClass.createFromDict(dct) self.registerItem(regItem) finally: settings.endGroup()
python
def loadSettings(self, groupName=None): """ Reads the registry items from the persistent settings store. """ groupName = groupName if groupName else self.settingsGroupName settings = QtCore.QSettings() logger.info("Reading {!r} from: {}".format(groupName, settings.fileName())) settings.beginGroup(groupName) self.clear() try: for key in settings.childKeys(): if key.startswith('item'): dct = ast.literal_eval(settings.value(key)) regItem = self._itemClass.createFromDict(dct) self.registerItem(regItem) finally: settings.endGroup()
Reads the registry items from the persistent settings store.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registry.py#L329-L345
titusjan/argos
argos/qt/registry.py
ClassRegistry.saveSettings
def saveSettings(self, groupName=None): """ Writes the registry items into the persistent settings store. """ groupName = groupName if groupName else self.settingsGroupName settings = QtCore.QSettings() logger.info("Saving {} to: {}".format(groupName, settings.fileName())) settings.remove(groupName) # start with a clean slate settings.beginGroup(groupName) try: for itemNr, item in enumerate(self.items): key = "item-{:03d}".format(itemNr) value = repr(item.asDict()) settings.setValue(key, value) finally: settings.endGroup()
python
def saveSettings(self, groupName=None): """ Writes the registry items into the persistent settings store. """ groupName = groupName if groupName else self.settingsGroupName settings = QtCore.QSettings() logger.info("Saving {} to: {}".format(groupName, settings.fileName())) settings.remove(groupName) # start with a clean slate settings.beginGroup(groupName) try: for itemNr, item in enumerate(self.items): key = "item-{:03d}".format(itemNr) value = repr(item.asDict()) settings.setValue(key, value) finally: settings.endGroup()
Writes the registry items into the persistent settings store.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registry.py#L348-L363
titusjan/argos
argos/qt/registry.py
ClassRegistry.deleteSettings
def deleteSettings(self, groupName=None): """ Deletes registry items from the persistent store. """ groupName = groupName if groupName else self.settingsGroupName settings = QtCore.QSettings() logger.info("Deleting {} from: {}".format(groupName, settings.fileName())) removeSettingsGroup(groupName)
python
def deleteSettings(self, groupName=None): """ Deletes registry items from the persistent store. """ groupName = groupName if groupName else self.settingsGroupName settings = QtCore.QSettings() logger.info("Deleting {} from: {}".format(groupName, settings.fileName())) removeSettingsGroup(groupName)
Deletes registry items from the persistent store.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registry.py#L366-L372
titusjan/argos
argos/repo/detailpanes.py
DetailBasePane.dockVisibilityChanged
def dockVisibilityChanged(self, visible): """ Slot to be called when the dock widget that this pane contains become (in)visible. Is used to (dis)connect the pane from its repo tree view and so prevent unnecessary and potentially costly updates when the pane is hidden. """ logger.debug("dockVisibilityChanged of {!r}: visible={}".format(self, visible)) if visible: self._repoTreeView.sigRepoItemChanged.connect(self.repoItemChanged) self._isConnected = True currentRepoItem, _currentIndex = self._repoTreeView.getCurrentItem() self.repoItemChanged(currentRepoItem) else: # At start-up the pane be be hidden but the signals are not connected. # A disconnect would fail in that case so we test for isConnected == True. if self.isConnected: self._repoTreeView.sigRepoItemChanged.disconnect(self.repoItemChanged) self._isConnected = False self.errorWidget.setError(msg="Contents disabled", title="Error") self.setCurrentIndex(self.ERROR_PAGE_IDX)
python
def dockVisibilityChanged(self, visible): """ Slot to be called when the dock widget that this pane contains become (in)visible. Is used to (dis)connect the pane from its repo tree view and so prevent unnecessary and potentially costly updates when the pane is hidden. """ logger.debug("dockVisibilityChanged of {!r}: visible={}".format(self, visible)) if visible: self._repoTreeView.sigRepoItemChanged.connect(self.repoItemChanged) self._isConnected = True currentRepoItem, _currentIndex = self._repoTreeView.getCurrentItem() self.repoItemChanged(currentRepoItem) else: # At start-up the pane be be hidden but the signals are not connected. # A disconnect would fail in that case so we test for isConnected == True. if self.isConnected: self._repoTreeView.sigRepoItemChanged.disconnect(self.repoItemChanged) self._isConnected = False self.errorWidget.setError(msg="Contents disabled", title="Error") self.setCurrentIndex(self.ERROR_PAGE_IDX)
Slot to be called when the dock widget that this pane contains become (in)visible. Is used to (dis)connect the pane from its repo tree view and so prevent unnecessary and potentially costly updates when the pane is hidden.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/detailpanes.py#L85-L106
titusjan/argos
argos/repo/detailpanes.py
DetailBasePane.repoItemChanged
def repoItemChanged(self, rti): """ Updates the content when the current repo tree item changes. The rti parameter can be None when no RTI is selected in the repository tree. """ check_class(rti, (BaseRti, int), allow_none=True) assert type(rti) != int, "rti: {}".format(rti) try: self._drawContents(rti) self.setCurrentIndex(self.CONTENTS_PAGE_IDX) except Exception as ex: if DEBUGGING: raise logger.exception(ex) self.errorWidget.setError(msg=str(ex), title=get_class_name(ex)) self.setCurrentIndex(self.ERROR_PAGE_IDX)
python
def repoItemChanged(self, rti): """ Updates the content when the current repo tree item changes. The rti parameter can be None when no RTI is selected in the repository tree. """ check_class(rti, (BaseRti, int), allow_none=True) assert type(rti) != int, "rti: {}".format(rti) try: self._drawContents(rti) self.setCurrentIndex(self.CONTENTS_PAGE_IDX) except Exception as ex: if DEBUGGING: raise logger.exception(ex) self.errorWidget.setError(msg=str(ex), title=get_class_name(ex)) self.setCurrentIndex(self.ERROR_PAGE_IDX)
Updates the content when the current repo tree item changes. The rti parameter can be None when no RTI is selected in the repository tree.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/detailpanes.py#L109-L123
titusjan/argos
argos/inspector/selectionpane.py
addInspectorActionsToMenu
def addInspectorActionsToMenu(inspectorMenu, execInspectorDialogAction, inspectorActionGroup): """ Adds menu items to the inpsectorMenu for the given set-inspector actions. :param inspectorMenu: inspector menu that will be modified :param execInspectorDialogAction: the "Browse Inspectors..." actions :param inspectorActionGroup: action group with actions for selecting a new inspector :return: the inspectorMenu, which has been modified. """ inspectorMenu.addAction(execInspectorDialogAction) inspectorMenu.addSeparator() for action in inspectorActionGroup.actions(): inspectorMenu.addAction(action) return inspectorMenu
python
def addInspectorActionsToMenu(inspectorMenu, execInspectorDialogAction, inspectorActionGroup): """ Adds menu items to the inpsectorMenu for the given set-inspector actions. :param inspectorMenu: inspector menu that will be modified :param execInspectorDialogAction: the "Browse Inspectors..." actions :param inspectorActionGroup: action group with actions for selecting a new inspector :return: the inspectorMenu, which has been modified. """ inspectorMenu.addAction(execInspectorDialogAction) inspectorMenu.addSeparator() for action in inspectorActionGroup.actions(): inspectorMenu.addAction(action) return inspectorMenu
Adds menu items to the inpsectorMenu for the given set-inspector actions. :param inspectorMenu: inspector menu that will be modified :param execInspectorDialogAction: the "Browse Inspectors..." actions :param inspectorActionGroup: action group with actions for selecting a new inspector :return: the inspectorMenu, which has been modified.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/selectionpane.py#L31-L45
titusjan/argos
argos/inspector/selectionpane.py
InspectorSelectionPane.updateFromInspectorRegItem
def updateFromInspectorRegItem(self, inspectorRegItem): """ Updates the label from the full name of the InspectorRegItem """ library, name = inspectorRegItem.splitName() label = "{} ({})".format(name, library) if library else name #self.label.setText(label) self.menuButton.setText(label)
python
def updateFromInspectorRegItem(self, inspectorRegItem): """ Updates the label from the full name of the InspectorRegItem """ library, name = inspectorRegItem.splitName() label = "{} ({})".format(name, library) if library else name #self.label.setText(label) self.menuButton.setText(label)
Updates the label from the full name of the InspectorRegItem
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/selectionpane.py#L74-L80
titusjan/argos
argos/config/stringcti.py
StringCti.createEditor
def createEditor(self, delegate, parent, option): """ Creates a StringCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return StringCtiEditor(self, delegate, parent=parent)
python
def createEditor(self, delegate, parent, option): """ Creates a StringCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return StringCtiEditor(self, delegate, parent=parent)
Creates a StringCtiEditor. For the parameters see the AbstractCti constructor documentation.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/stringcti.py#L54-L58
titusjan/argos
argos/inspector/pgplugins/pghistlutitem.py
HistogramLUTItem.setHistogramRange
def setHistogramRange(self, mn, mx, padding=0.1): """Set the Y range on the histogram plot. This disables auto-scaling.""" self.vb.enableAutoRange(self.vb.YAxis, False) self.vb.setYRange(mn, mx, padding)
python
def setHistogramRange(self, mn, mx, padding=0.1): """Set the Y range on the histogram plot. This disables auto-scaling.""" self.vb.enableAutoRange(self.vb.YAxis, False) self.vb.setYRange(mn, mx, padding)
Set the Y range on the histogram plot. This disables auto-scaling.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pghistlutitem.py#L113-L116
titusjan/argos
argos/inspector/pgplugins/pghistlutitem.py
HistogramLUTItem.setImageItem
def setImageItem(self, img): """Set an ImageItem to have its levels and LUT automatically controlled by this HistogramLUTItem. """ self.imageItem = weakref.ref(img) img.sigImageChanged.connect(self.imageChanged) img.setLookupTable(self.getLookupTable) ## send function pointer, not the result #self.gradientChanged() self.regionChanged() self.imageChanged(autoLevel=True)
python
def setImageItem(self, img): """Set an ImageItem to have its levels and LUT automatically controlled by this HistogramLUTItem. """ self.imageItem = weakref.ref(img) img.sigImageChanged.connect(self.imageChanged) img.setLookupTable(self.getLookupTable) ## send function pointer, not the result #self.gradientChanged() self.regionChanged() self.imageChanged(autoLevel=True)
Set an ImageItem to have its levels and LUT automatically controlled by this HistogramLUTItem.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pghistlutitem.py#L141-L150
titusjan/argos
argos/inspector/pgplugins/pghistlutitem.py
HistogramLUTItem.getLookupTable
def getLookupTable(self, img=None, n=None, alpha=None): """Return a lookup table from the color gradient defined by this HistogramLUTItem. """ if n is None: if img.dtype == np.uint8: n = 256 else: n = 512 if self.lut is None: self.lut = self.gradient.getLookupTable(n, alpha=alpha) return self.lut
python
def getLookupTable(self, img=None, n=None, alpha=None): """Return a lookup table from the color gradient defined by this HistogramLUTItem. """ if n is None: if img.dtype == np.uint8: n = 256 else: n = 512 if self.lut is None: self.lut = self.gradient.getLookupTable(n, alpha=alpha) return self.lut
Return a lookup table from the color gradient defined by this HistogramLUTItem.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pghistlutitem.py#L168-L179
titusjan/argos
argos/inspector/pgplugins/lineplot1d.py
PgLinePlot1dCti.setAutoRangeOn
def setAutoRangeOn(self, axisNumber): """ Sets the auto-range of the axis on. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes). """ setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.yAxisRangeCti, axisNumber)
python
def setAutoRangeOn(self, axisNumber): """ Sets the auto-range of the axis on. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes). """ setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.yAxisRangeCti, axisNumber)
Sets the auto-range of the axis on. :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/lineplot1d.py#L106-L111
titusjan/argos
argos/inspector/pgplugins/lineplot1d.py
PgLinePlot1d.finalize
def finalize(self): """ Is called before destruction. Can be used to clean-up resources """ logger.debug("Finalizing: {}".format(self)) self.plotItem.scene().sigMouseMoved.disconnect(self.mouseMoved) self.plotItem.close() self.graphicsLayoutWidget.close()
python
def finalize(self): """ Is called before destruction. Can be used to clean-up resources """ logger.debug("Finalizing: {}".format(self)) self.plotItem.scene().sigMouseMoved.disconnect(self.mouseMoved) self.plotItem.close() self.graphicsLayoutWidget.close()
Is called before destruction. Can be used to clean-up resources
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/lineplot1d.py#L153-L159
titusjan/argos
argos/inspector/pgplugins/lineplot1d.py
PgLinePlot1d._clearContents
def _clearContents(self): """ Clears the the inspector widget when no valid input is available. """ self.titleLabel.setText('') self.plotItem.clear() self.plotItem.setLabel('left', '') self.plotItem.setLabel('bottom', '')
python
def _clearContents(self): """ Clears the the inspector widget when no valid input is available. """ self.titleLabel.setText('') self.plotItem.clear() self.plotItem.setLabel('left', '') self.plotItem.setLabel('bottom', '')
Clears the the inspector widget when no valid input is available.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/lineplot1d.py#L176-L182
titusjan/argos
argos/inspector/pgplugins/lineplot1d.py
PgLinePlot1d._drawContents
def _drawContents(self, reason=None, initiator=None): """ Draws the plot contents from the sliced array of the collected repo tree item. The reason parameter is used to determine if the axes will be reset (the initiator parameter is ignored). See AbstractInspector.updateContents for their description. """ self.slicedArray = self.collector.getSlicedArray() if not self._hasValidData(): self._clearContents() raise InvalidDataError("No data available or it does not contain real numbers") # -- Valid plot data from here on -- # PyQtGraph doesn't handle masked arrays so we convert the masked values to Nans (missing # data values are replaced by NaNs). The PyQtGraph line plot omits the Nans, which is great. self.slicedArray.replaceMaskedValueWithNan() # will convert data to float if int self.plotItem.clear() # Reset the axes ranges (via the config) if (reason == UpdateReason.RTI_CHANGED or reason == UpdateReason.COLLECTOR_COMBO_BOX): # self.config.yAxisRangeCti.setAutoRangeOn() doesn't work as refreshBlocked is True # TODO: can refreshBlocked maybe only block the signals to prevent loops? self.config.xAxisRangeCti.autoRangeCti.data = True self.config.yAxisRangeCti.autoRangeCti.data = True self.titleLabel.setText(self.configValue('title').format(**self.collector.rtiInfo)) connected = np.isfinite(self.slicedArray.data) if is_an_array(self.slicedArray.mask): connected = np.logical_and(connected, ~self.slicedArray.mask) else: connected = np.zeros_like(self.slicedArray.data) if self.slicedArray.mask else connected plotDataItem = self.config.plotDataItemCti.createPlotDataItem() plotDataItem.setData(self.slicedArray.data, connect=connected) self.plotItem.addItem(plotDataItem) if self.config.probeCti.configValue: self.probeLabel.setVisible(True) self.plotItem.addItem(self.crossLineVerShadow, ignoreBounds=True) self.plotItem.addItem(self.crossLineVertical, ignoreBounds=True) self.plotItem.addItem(self.probeDataItem, ignoreBounds=True) self.probeDataItem.setSymbolBrush(QtGui.QBrush(self.config.plotDataItemCti.penColor)) self.probeDataItem.setSymbolSize(10) else: self.probeLabel.setVisible(False) # Update the config tree from the (possibly) new state of the PgLinePlot1d inspector, # e.g. the axis range may have changed while drawing. self.config.updateTarget()
python
def _drawContents(self, reason=None, initiator=None): """ Draws the plot contents from the sliced array of the collected repo tree item. The reason parameter is used to determine if the axes will be reset (the initiator parameter is ignored). See AbstractInspector.updateContents for their description. """ self.slicedArray = self.collector.getSlicedArray() if not self._hasValidData(): self._clearContents() raise InvalidDataError("No data available or it does not contain real numbers") # -- Valid plot data from here on -- # PyQtGraph doesn't handle masked arrays so we convert the masked values to Nans (missing # data values are replaced by NaNs). The PyQtGraph line plot omits the Nans, which is great. self.slicedArray.replaceMaskedValueWithNan() # will convert data to float if int self.plotItem.clear() # Reset the axes ranges (via the config) if (reason == UpdateReason.RTI_CHANGED or reason == UpdateReason.COLLECTOR_COMBO_BOX): # self.config.yAxisRangeCti.setAutoRangeOn() doesn't work as refreshBlocked is True # TODO: can refreshBlocked maybe only block the signals to prevent loops? self.config.xAxisRangeCti.autoRangeCti.data = True self.config.yAxisRangeCti.autoRangeCti.data = True self.titleLabel.setText(self.configValue('title').format(**self.collector.rtiInfo)) connected = np.isfinite(self.slicedArray.data) if is_an_array(self.slicedArray.mask): connected = np.logical_and(connected, ~self.slicedArray.mask) else: connected = np.zeros_like(self.slicedArray.data) if self.slicedArray.mask else connected plotDataItem = self.config.plotDataItemCti.createPlotDataItem() plotDataItem.setData(self.slicedArray.data, connect=connected) self.plotItem.addItem(plotDataItem) if self.config.probeCti.configValue: self.probeLabel.setVisible(True) self.plotItem.addItem(self.crossLineVerShadow, ignoreBounds=True) self.plotItem.addItem(self.crossLineVertical, ignoreBounds=True) self.plotItem.addItem(self.probeDataItem, ignoreBounds=True) self.probeDataItem.setSymbolBrush(QtGui.QBrush(self.config.plotDataItemCti.penColor)) self.probeDataItem.setSymbolSize(10) else: self.probeLabel.setVisible(False) # Update the config tree from the (possibly) new state of the PgLinePlot1d inspector, # e.g. the axis range may have changed while drawing. self.config.updateTarget()
Draws the plot contents from the sliced array of the collected repo tree item. The reason parameter is used to determine if the axes will be reset (the initiator parameter is ignored). See AbstractInspector.updateContents for their description.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/lineplot1d.py#L185-L239
titusjan/argos
argos/inspector/pgplugins/lineplot1d.py
PgLinePlot1d.mouseMoved
def mouseMoved(self, viewPos): """ Updates the probe text with the values under the cursor. Draws a vertical line and a symbol at the position of the probe. """ try: check_class(viewPos, QtCore.QPointF) self.crossLineVerShadow.setVisible(False) self.crossLineVertical.setVisible(False) self.probeLabel.setText("") self.probeDataItem.clear() if (self._hasValidData() and self.config.probeCti.configValue and self.viewBox.sceneBoundingRect().contains(viewPos)): scenePos = self.viewBox.mapSceneToView(viewPos) index = int(scenePos.x()) data = self.slicedArray.data if not 0 <= index < len(data): txt = "<span style='color: grey'>no data at cursor</span>" self.probeLabel.setText(txt) else: valueStr = to_string(data[index], masked=self.slicedArray.maskAt(index), maskFormat='&lt;masked&gt;') self.probeLabel.setText("pos = {!r}, value = {}".format(index, valueStr)) if np.isfinite(data[index]): self.crossLineVerShadow.setVisible(True) self.crossLineVerShadow.setPos(index) self.crossLineVertical.setVisible(True) self.crossLineVertical.setPos(index) if data[index] > 0 or self.config.yLogCti.configValue == False: self.probeDataItem.setData((index,), (data[index],)) except Exception as ex: # In contrast to _drawContents, this function is a slot and thus must not throw # exceptions. The exception is logged. Perhaps we should clear the cross plots, but # this could, in turn, raise exceptions. if DEBUGGING: raise else: logger.exception(ex)
python
def mouseMoved(self, viewPos): """ Updates the probe text with the values under the cursor. Draws a vertical line and a symbol at the position of the probe. """ try: check_class(viewPos, QtCore.QPointF) self.crossLineVerShadow.setVisible(False) self.crossLineVertical.setVisible(False) self.probeLabel.setText("") self.probeDataItem.clear() if (self._hasValidData() and self.config.probeCti.configValue and self.viewBox.sceneBoundingRect().contains(viewPos)): scenePos = self.viewBox.mapSceneToView(viewPos) index = int(scenePos.x()) data = self.slicedArray.data if not 0 <= index < len(data): txt = "<span style='color: grey'>no data at cursor</span>" self.probeLabel.setText(txt) else: valueStr = to_string(data[index], masked=self.slicedArray.maskAt(index), maskFormat='&lt;masked&gt;') self.probeLabel.setText("pos = {!r}, value = {}".format(index, valueStr)) if np.isfinite(data[index]): self.crossLineVerShadow.setVisible(True) self.crossLineVerShadow.setPos(index) self.crossLineVertical.setVisible(True) self.crossLineVertical.setPos(index) if data[index] > 0 or self.config.yLogCti.configValue == False: self.probeDataItem.setData((index,), (data[index],)) except Exception as ex: # In contrast to _drawContents, this function is a slot and thus must not throw # exceptions. The exception is logged. Perhaps we should clear the cross plots, but # this could, in turn, raise exceptions. if DEBUGGING: raise else: logger.exception(ex)
Updates the probe text with the values under the cursor. Draws a vertical line and a symbol at the position of the probe.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/lineplot1d.py#L243-L283
titusjan/argos
argos/utils/cls.py
environment_var_to_bool
def environment_var_to_bool(env_var): """ Converts an environment variable to a boolean Returns False if the environment variable is False, 0 or a case-insenstive string "false" or "0". """ # Try to see if env_var can be converted to an int try: env_var = int(env_var) except ValueError: pass if isinstance(env_var, numbers.Number): return bool(env_var) elif is_a_string(env_var): env_var = env_var.lower().strip() if env_var in "false": return False else: return True else: return bool(env_var)
python
def environment_var_to_bool(env_var): """ Converts an environment variable to a boolean Returns False if the environment variable is False, 0 or a case-insenstive string "false" or "0". """ # Try to see if env_var can be converted to an int try: env_var = int(env_var) except ValueError: pass if isinstance(env_var, numbers.Number): return bool(env_var) elif is_a_string(env_var): env_var = env_var.lower().strip() if env_var in "false": return False else: return True else: return bool(env_var)
Converts an environment variable to a boolean Returns False if the environment variable is False, 0 or a case-insenstive string "false" or "0".
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L84-L106
titusjan/argos
argos/utils/cls.py
fill_values_to_nan
def fill_values_to_nan(masked_array): """ Replaces the fill_values of the masked array by NaNs If the array is None or it does not contain floating point values, it cannot contain NaNs. In that case the original array is returned. """ if masked_array is not None and masked_array.dtype.kind == 'f': check_class(masked_array, ma.masked_array) logger.debug("Replacing fill_values by NaNs") masked_array[:] = ma.filled(masked_array, np.nan) masked_array.set_fill_value(np.nan) else: return masked_array
python
def fill_values_to_nan(masked_array): """ Replaces the fill_values of the masked array by NaNs If the array is None or it does not contain floating point values, it cannot contain NaNs. In that case the original array is returned. """ if masked_array is not None and masked_array.dtype.kind == 'f': check_class(masked_array, ma.masked_array) logger.debug("Replacing fill_values by NaNs") masked_array[:] = ma.filled(masked_array, np.nan) masked_array.set_fill_value(np.nan) else: return masked_array
Replaces the fill_values of the masked array by NaNs If the array is None or it does not contain floating point values, it cannot contain NaNs. In that case the original array is returned.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L109-L121
titusjan/argos
argos/utils/cls.py
setting_str_to_bool
def setting_str_to_bool(s): """ Converts 'true' to True and 'false' to False if s is a string """ if isinstance(s, six.string_types): s = s.lower() if s == 'true': return True elif s == 'false': return False else: return ValueError('Invalid boolean representation: {!r}'.format(s)) else: return s
python
def setting_str_to_bool(s): """ Converts 'true' to True and 'false' to False if s is a string """ if isinstance(s, six.string_types): s = s.lower() if s == 'true': return True elif s == 'false': return False else: return ValueError('Invalid boolean representation: {!r}'.format(s)) else: return s
Converts 'true' to True and 'false' to False if s is a string
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L127-L139
titusjan/argos
argos/utils/cls.py
to_string
def to_string(var, masked=None, decode_bytes='utf-8', maskFormat='', strFormat='{}', intFormat='{}', numFormat=DEFAULT_NUM_FORMAT, noneFormat='{!r}', otherFormat='{}'): """ Converts var to a python string or unicode string so Qt widgets can display them. If var consists of bytes, the decode_bytes is used to decode the bytes. If var consists of a numpy.str_, the result will be converted to a regular Python string. This is necessary to display the string in Qt widgets. For the possible format string (replacement fields) see: https://docs.python.org/3/library/string.html#format-string-syntax :param masked: if True, the element is masked. The maskFormat is used. :param decode_bytes': string containing the expected encoding when var is of type bytes :param strFormat' : new style format string used to format strings :param intFormat' : new style format string used to format integers :param numFormat' : new style format string used to format all numbers except integers. :param noneFormat': new style format string used to format Nones. :param maskFormat': override with this format used if masked is True. If the maskFormat is empty, the format is never overriden. :param otherFormat': new style format string used to format all other types """ #logger.debug("to_string: {!r} ({})".format(var, type(var))) # Decode and select correct format specifier. if is_binary(var): fmt = strFormat try: decodedVar = var.decode(decode_bytes, 'replace') except LookupError as ex: # Add URL to exception message. raise LookupError("{}\n\nFor a list of encodings in Python see: {}" .format(ex, URL_PYTHON_ENCODINGS_DOC)) elif is_text(var): fmt = strFormat decodedVar = six.text_type(var) elif is_a_string(var): fmt = strFormat decodedVar = str(var) elif isinstance(var, numbers.Integral): fmt = intFormat decodedVar = var elif isinstance(var, numbers.Number): fmt = numFormat decodedVar = var elif var is None: fmt = noneFormat decodedVar = var else: fmt = otherFormat decodedVar = var if maskFormat != '{}': try: allMasked = all(masked) except TypeError as ex: allMasked = bool(masked) if allMasked: fmt = maskFormat try: result = fmt.format(decodedVar) except Exception: result = "Invalid format {!r} for: {!r}".format(fmt, decodedVar) #if masked: # logger.debug("to_string (fmt={}): {!r} ({}) -> result = {!r}".format(maskFormat, var, type(var), result)) return result
python
def to_string(var, masked=None, decode_bytes='utf-8', maskFormat='', strFormat='{}', intFormat='{}', numFormat=DEFAULT_NUM_FORMAT, noneFormat='{!r}', otherFormat='{}'): """ Converts var to a python string or unicode string so Qt widgets can display them. If var consists of bytes, the decode_bytes is used to decode the bytes. If var consists of a numpy.str_, the result will be converted to a regular Python string. This is necessary to display the string in Qt widgets. For the possible format string (replacement fields) see: https://docs.python.org/3/library/string.html#format-string-syntax :param masked: if True, the element is masked. The maskFormat is used. :param decode_bytes': string containing the expected encoding when var is of type bytes :param strFormat' : new style format string used to format strings :param intFormat' : new style format string used to format integers :param numFormat' : new style format string used to format all numbers except integers. :param noneFormat': new style format string used to format Nones. :param maskFormat': override with this format used if masked is True. If the maskFormat is empty, the format is never overriden. :param otherFormat': new style format string used to format all other types """ #logger.debug("to_string: {!r} ({})".format(var, type(var))) # Decode and select correct format specifier. if is_binary(var): fmt = strFormat try: decodedVar = var.decode(decode_bytes, 'replace') except LookupError as ex: # Add URL to exception message. raise LookupError("{}\n\nFor a list of encodings in Python see: {}" .format(ex, URL_PYTHON_ENCODINGS_DOC)) elif is_text(var): fmt = strFormat decodedVar = six.text_type(var) elif is_a_string(var): fmt = strFormat decodedVar = str(var) elif isinstance(var, numbers.Integral): fmt = intFormat decodedVar = var elif isinstance(var, numbers.Number): fmt = numFormat decodedVar = var elif var is None: fmt = noneFormat decodedVar = var else: fmt = otherFormat decodedVar = var if maskFormat != '{}': try: allMasked = all(masked) except TypeError as ex: allMasked = bool(masked) if allMasked: fmt = maskFormat try: result = fmt.format(decodedVar) except Exception: result = "Invalid format {!r} for: {!r}".format(fmt, decodedVar) #if masked: # logger.debug("to_string (fmt={}): {!r} ({}) -> result = {!r}".format(maskFormat, var, type(var), result)) return result
Converts var to a python string or unicode string so Qt widgets can display them. If var consists of bytes, the decode_bytes is used to decode the bytes. If var consists of a numpy.str_, the result will be converted to a regular Python string. This is necessary to display the string in Qt widgets. For the possible format string (replacement fields) see: https://docs.python.org/3/library/string.html#format-string-syntax :param masked: if True, the element is masked. The maskFormat is used. :param decode_bytes': string containing the expected encoding when var is of type bytes :param strFormat' : new style format string used to format strings :param intFormat' : new style format string used to format integers :param numFormat' : new style format string used to format all numbers except integers. :param noneFormat': new style format string used to format Nones. :param maskFormat': override with this format used if masked is True. If the maskFormat is empty, the format is never overriden. :param otherFormat': new style format string used to format all other types
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L151-L220
titusjan/argos
argos/utils/cls.py
is_a_string
def is_a_string(var, allow_none=False): """ Returns True if var is a string (ascii or unicode) Result py-2 py-3 ----------------- ----- ----- b'bytes literal' True False 'string literal' True True u'unicode literal' True True Also returns True if the var is a numpy string (numpy.string_, numpy.unicode_). """ return isinstance(var, six.string_types) or (var is None and allow_none)
python
def is_a_string(var, allow_none=False): """ Returns True if var is a string (ascii or unicode) Result py-2 py-3 ----------------- ----- ----- b'bytes literal' True False 'string literal' True True u'unicode literal' True True Also returns True if the var is a numpy string (numpy.string_, numpy.unicode_). """ return isinstance(var, six.string_types) or (var is None and allow_none)
Returns True if var is a string (ascii or unicode) Result py-2 py-3 ----------------- ----- ----- b'bytes literal' True False 'string literal' True True u'unicode literal' True True Also returns True if the var is a numpy string (numpy.string_, numpy.unicode_).
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L223-L234
titusjan/argos
argos/utils/cls.py
check_is_a_string
def check_is_a_string(var, allow_none=False): """ Calls is_a_string and raises a type error if the check fails. """ if not is_a_string(var, allow_none=allow_none): raise TypeError("var must be a string, however type(var) is {}" .format(type(var)))
python
def check_is_a_string(var, allow_none=False): """ Calls is_a_string and raises a type error if the check fails. """ if not is_a_string(var, allow_none=allow_none): raise TypeError("var must be a string, however type(var) is {}" .format(type(var)))
Calls is_a_string and raises a type error if the check fails.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L237-L242
titusjan/argos
argos/utils/cls.py
is_text
def is_text(var, allow_none=False): """ Returns True if var is a unicode text Result py-2 py-3 ----------------- ----- ----- b'bytes literal' False False 'string literal' False True u'unicode literal' True True Also works with the corresponding numpy types. """ return isinstance(var, six.text_type) or (var is None and allow_none)
python
def is_text(var, allow_none=False): """ Returns True if var is a unicode text Result py-2 py-3 ----------------- ----- ----- b'bytes literal' False False 'string literal' False True u'unicode literal' True True Also works with the corresponding numpy types. """ return isinstance(var, six.text_type) or (var is None and allow_none)
Returns True if var is a unicode text Result py-2 py-3 ----------------- ----- ----- b'bytes literal' False False 'string literal' False True u'unicode literal' True True Also works with the corresponding numpy types.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L245-L256
titusjan/argos
argos/utils/cls.py
is_binary
def is_binary(var, allow_none=False): """ Returns True if var is a binary (bytes) objects Result py-2 py-3 ----------------- ----- ----- b'bytes literal' True True 'string literal' True False u'unicode literal' False False Also works with the corresponding numpy types. """ return isinstance(var, six.binary_type) or (var is None and allow_none)
python
def is_binary(var, allow_none=False): """ Returns True if var is a binary (bytes) objects Result py-2 py-3 ----------------- ----- ----- b'bytes literal' True True 'string literal' True False u'unicode literal' False False Also works with the corresponding numpy types. """ return isinstance(var, six.binary_type) or (var is None and allow_none)
Returns True if var is a binary (bytes) objects Result py-2 py-3 ----------------- ----- ----- b'bytes literal' True True 'string literal' True False u'unicode literal' False False Also works with the corresponding numpy types.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L267-L278
titusjan/argos
argos/utils/cls.py
is_a_sequence
def is_a_sequence(var, allow_none=False): """ Returns True if var is a list or a tuple (but not a string!) """ return isinstance(var, (list, tuple)) or (var is None and allow_none)
python
def is_a_sequence(var, allow_none=False): """ Returns True if var is a list or a tuple (but not a string!) """ return isinstance(var, (list, tuple)) or (var is None and allow_none)
Returns True if var is a list or a tuple (but not a string!)
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L302-L305
titusjan/argos
argos/utils/cls.py
check_is_a_sequence
def check_is_a_sequence(var, allow_none=False): """ Calls is_a_sequence and raises a type error if the check fails. """ if not is_a_sequence(var, allow_none=allow_none): raise TypeError("var must be a list or tuple, however type(var) is {}" .format(type(var)))
python
def check_is_a_sequence(var, allow_none=False): """ Calls is_a_sequence and raises a type error if the check fails. """ if not is_a_sequence(var, allow_none=allow_none): raise TypeError("var must be a list or tuple, however type(var) is {}" .format(type(var)))
Calls is_a_sequence and raises a type error if the check fails.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L308-L313
titusjan/argos
argos/utils/cls.py
check_is_a_mapping
def check_is_a_mapping(var, allow_none=False): """ Calls is_a_mapping and raises a type error if the check fails. """ if not is_a_mapping(var, allow_none=allow_none): raise TypeError("var must be a dict, however type(var) is {}" .format(type(var)))
python
def check_is_a_mapping(var, allow_none=False): """ Calls is_a_mapping and raises a type error if the check fails. """ if not is_a_mapping(var, allow_none=allow_none): raise TypeError("var must be a dict, however type(var) is {}" .format(type(var)))
Calls is_a_mapping and raises a type error if the check fails.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L322-L327
titusjan/argos
argos/utils/cls.py
is_an_array
def is_an_array(var, allow_none=False): """ Returns True if var is a numpy array. """ return isinstance(var, np.ndarray) or (var is None and allow_none)
python
def is_an_array(var, allow_none=False): """ Returns True if var is a numpy array. """ return isinstance(var, np.ndarray) or (var is None and allow_none)
Returns True if var is a numpy array.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L330-L333
titusjan/argos
argos/utils/cls.py
check_is_an_array
def check_is_an_array(var, allow_none=False): """ Calls is_an_array and raises a type error if the check fails. """ if not is_an_array(var, allow_none=allow_none): raise TypeError("var must be a NumPy array, however type(var) is {}" .format(type(var)))
python
def check_is_an_array(var, allow_none=False): """ Calls is_an_array and raises a type error if the check fails. """ if not is_an_array(var, allow_none=allow_none): raise TypeError("var must be a NumPy array, however type(var) is {}" .format(type(var)))
Calls is_an_array and raises a type error if the check fails.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L336-L341
titusjan/argos
argos/utils/cls.py
array_has_real_numbers
def array_has_real_numbers(array): """ Uses the dtype kind of the numpy array to determine if it represents real numbers. That is, the array kind should be one of: i u f Possible dtype.kind values. b boolean i signed integer u unsigned integer f floating-point c complex floating-point m timedelta M datetime O object S (byte-)string U Unicode V void """ kind = array.dtype.kind assert kind in 'biufcmMOSUV', "Unexpected array kind: {}".format(kind) return kind in 'iuf'
python
def array_has_real_numbers(array): """ Uses the dtype kind of the numpy array to determine if it represents real numbers. That is, the array kind should be one of: i u f Possible dtype.kind values. b boolean i signed integer u unsigned integer f floating-point c complex floating-point m timedelta M datetime O object S (byte-)string U Unicode V void """ kind = array.dtype.kind assert kind in 'biufcmMOSUV', "Unexpected array kind: {}".format(kind) return kind in 'iuf'
Uses the dtype kind of the numpy array to determine if it represents real numbers. That is, the array kind should be one of: i u f Possible dtype.kind values. b boolean i signed integer u unsigned integer f floating-point c complex floating-point m timedelta M datetime O object S (byte-)string U Unicode V void
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L350-L370
titusjan/argos
argos/utils/cls.py
check_class
def check_class(obj, target_class, allow_none = False): """ Checks that the obj is a (sub)type of target_class. Raises a TypeError if this is not the case. :param obj: object whos type is to be checked :type obj: any type :param target_class: target type/class :type target_class: any class or type :param allow_none: if true obj may be None :type allow_none: boolean """ if not isinstance(obj, target_class): if not (allow_none and obj is None): raise TypeError("obj must be a of type {}, got: {}" .format(target_class, type(obj)))
python
def check_class(obj, target_class, allow_none = False): """ Checks that the obj is a (sub)type of target_class. Raises a TypeError if this is not the case. :param obj: object whos type is to be checked :type obj: any type :param target_class: target type/class :type target_class: any class or type :param allow_none: if true obj may be None :type allow_none: boolean """ if not isinstance(obj, target_class): if not (allow_none and obj is None): raise TypeError("obj must be a of type {}, got: {}" .format(target_class, type(obj)))
Checks that the obj is a (sub)type of target_class. Raises a TypeError if this is not the case. :param obj: object whos type is to be checked :type obj: any type :param target_class: target type/class :type target_class: any class or type :param allow_none: if true obj may be None :type allow_none: boolean
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L373-L387
titusjan/argos
argos/utils/cls.py
import_symbol
def import_symbol(full_symbol_name): """ Imports a symbol (e.g. class, variable, etc) from a dot separated name. Can be used to create a class whose type is only known at run-time. The full_symbol_name must contain packages and module, e.g.: 'argos.plugins.rti.ncdf.NcdfFileRti' If the module doesn't exist an ImportError is raised. If the class doesn't exist an AttributeError is raised. """ parts = full_symbol_name.rsplit('.', 1) if len(parts) == 2: module_name, symbol_name = parts module_name = str(module_name) # convert from possible unicode symbol_name = str(symbol_name) #logger.debug("From module {} importing {!r}".format(module_name, symbol_name)) module = __import__(module_name, fromlist=[symbol_name]) cls = getattr(module, symbol_name) return cls elif len(parts) == 1: # No module part, only a class name. If you want to create a class # by using name without module, you should use globals()[symbol_name] # We cannot do this here because globals is of the module that defines # this function, not of the modules where this function is called. raise ImportError("full_symbol_name should contain a module") else: assert False, "Bug: parts should have 1 or elements: {}".format(parts)
python
def import_symbol(full_symbol_name): """ Imports a symbol (e.g. class, variable, etc) from a dot separated name. Can be used to create a class whose type is only known at run-time. The full_symbol_name must contain packages and module, e.g.: 'argos.plugins.rti.ncdf.NcdfFileRti' If the module doesn't exist an ImportError is raised. If the class doesn't exist an AttributeError is raised. """ parts = full_symbol_name.rsplit('.', 1) if len(parts) == 2: module_name, symbol_name = parts module_name = str(module_name) # convert from possible unicode symbol_name = str(symbol_name) #logger.debug("From module {} importing {!r}".format(module_name, symbol_name)) module = __import__(module_name, fromlist=[symbol_name]) cls = getattr(module, symbol_name) return cls elif len(parts) == 1: # No module part, only a class name. If you want to create a class # by using name without module, you should use globals()[symbol_name] # We cannot do this here because globals is of the module that defines # this function, not of the modules where this function is called. raise ImportError("full_symbol_name should contain a module") else: assert False, "Bug: parts should have 1 or elements: {}".format(parts)
Imports a symbol (e.g. class, variable, etc) from a dot separated name. Can be used to create a class whose type is only known at run-time. The full_symbol_name must contain packages and module, e.g.: 'argos.plugins.rti.ncdf.NcdfFileRti' If the module doesn't exist an ImportError is raised. If the class doesn't exist an AttributeError is raised.
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L419-L445