id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
5,800
titusjan/argos
argos/inspector/pgplugins/pgctis.py
ViewBoxDebugCti._refreshNodeFromTarget
def _refreshNodeFromTarget(self): """ Updates the config settings """ for key, value in self.viewBox.state.items(): if key != "limits": childItem = self.childByNodeName(key) childItem.data = value else: # limits contains a dictionary as well for limitKey, limitValue in value.items(): limitChildItem = self.limitsItem.childByNodeName(limitKey) limitChildItem.data = limitValue
python
def _refreshNodeFromTarget(self): for key, value in self.viewBox.state.items(): if key != "limits": childItem = self.childByNodeName(key) childItem.data = value else: # limits contains a dictionary as well for limitKey, limitValue in value.items(): limitChildItem = self.limitsItem.childByNodeName(limitKey) limitChildItem.data = limitValue
[ "def", "_refreshNodeFromTarget", "(", "self", ")", ":", "for", "key", ",", "value", "in", "self", ".", "viewBox", ".", "state", ".", "items", "(", ")", ":", "if", "key", "!=", "\"limits\"", ":", "childItem", "=", "self", ".", "childByNodeName", "(", "k...
Updates the config settings
[ "Updates", "the", "config", "settings" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L98-L109
5,801
titusjan/argos
argos/inspector/pgplugins/pgctis.py
AbstractRangeCti._forceRefreshMinMax
def _forceRefreshMinMax(self): """ Refreshes the min max config values from the axes' state. """ #logger.debug("_forceRefreshMinMax", stack_info=True) # Set the precision from by looking how many decimals are needed to show the difference # between the minimum and maximum, given the maximum. E.g. if min = 0.04 and max = 0.07, # we would only need zero decimals behind the point as we can write the range as # [4e-2, 7e-2]. However if min = 1.04 and max = 1.07, we need 2 decimals behind the point. # So, while the range is the same size we need more decimals because we are not zoomed in # around zero. rangeMin, rangeMax = self.getTargetRange() # [[xmin, xmax], [ymin, ymax]] maxOrder = np.log10(np.abs(max(rangeMax, rangeMin))) diffOrder = np.log10(np.abs(rangeMax - rangeMin)) extraDigits = 2 # add some extra digits to make each pan/zoom action show a new value. precisionF = np.clip(abs(maxOrder - diffOrder) + extraDigits, extraDigits + 1, 25) precision = int(precisionF) if np.isfinite(precisionF) else extraDigits + 1 #logger.debug("maxOrder: {}, diffOrder: {}, precision: {}" # .format(maxOrder, diffOrder, precision)) self.rangeMinCti.precision = precision self.rangeMaxCti.precision = precision self.rangeMinCti.data, self.rangeMaxCti.data = rangeMin, rangeMax # Update values in the tree self.model.emitDataChanged(self.rangeMinCti) self.model.emitDataChanged(self.rangeMaxCti)
python
def _forceRefreshMinMax(self): #logger.debug("_forceRefreshMinMax", stack_info=True) # Set the precision from by looking how many decimals are needed to show the difference # between the minimum and maximum, given the maximum. E.g. if min = 0.04 and max = 0.07, # we would only need zero decimals behind the point as we can write the range as # [4e-2, 7e-2]. However if min = 1.04 and max = 1.07, we need 2 decimals behind the point. # So, while the range is the same size we need more decimals because we are not zoomed in # around zero. rangeMin, rangeMax = self.getTargetRange() # [[xmin, xmax], [ymin, ymax]] maxOrder = np.log10(np.abs(max(rangeMax, rangeMin))) diffOrder = np.log10(np.abs(rangeMax - rangeMin)) extraDigits = 2 # add some extra digits to make each pan/zoom action show a new value. precisionF = np.clip(abs(maxOrder - diffOrder) + extraDigits, extraDigits + 1, 25) precision = int(precisionF) if np.isfinite(precisionF) else extraDigits + 1 #logger.debug("maxOrder: {}, diffOrder: {}, precision: {}" # .format(maxOrder, diffOrder, precision)) self.rangeMinCti.precision = precision self.rangeMaxCti.precision = precision self.rangeMinCti.data, self.rangeMaxCti.data = rangeMin, rangeMax # Update values in the tree self.model.emitDataChanged(self.rangeMinCti) self.model.emitDataChanged(self.rangeMaxCti)
[ "def", "_forceRefreshMinMax", "(", "self", ")", ":", "#logger.debug(\"_forceRefreshMinMax\", stack_info=True)", "# Set the precision from by looking how many decimals are needed to show the difference", "# between the minimum and maximum, given the maximum. E.g. if min = 0.04 and max = 0.07,", "# ...
Refreshes the min max config values from the axes' state.
[ "Refreshes", "the", "min", "max", "config", "values", "from", "the", "axes", "state", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L248-L275
5,802
titusjan/argos
argos/inspector/pgplugins/pgctis.py
AbstractRangeCti._forceRefreshAutoRange
def _forceRefreshAutoRange(self): """ The min and max config items will be disabled if auto range is on. """ enabled = self.autoRangeCti and self.autoRangeCti.configValue self.rangeMinCti.enabled = not enabled self.rangeMaxCti.enabled = not enabled self.model.emitDataChanged(self)
python
def _forceRefreshAutoRange(self): enabled = self.autoRangeCti and self.autoRangeCti.configValue self.rangeMinCti.enabled = not enabled self.rangeMaxCti.enabled = not enabled self.model.emitDataChanged(self)
[ "def", "_forceRefreshAutoRange", "(", "self", ")", ":", "enabled", "=", "self", ".", "autoRangeCti", "and", "self", ".", "autoRangeCti", ".", "configValue", "self", ".", "rangeMinCti", ".", "enabled", "=", "not", "enabled", "self", ".", "rangeMaxCti", ".", "...
The min and max config items will be disabled if auto range is on.
[ "The", "min", "and", "max", "config", "items", "will", "be", "disabled", "if", "auto", "range", "is", "on", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L289-L295
5,803
titusjan/argos
argos/inspector/pgplugins/pgctis.py
AbstractRangeCti.setAutoRangeOff
def setAutoRangeOff(self): """ Turns off the auto range checkbox. Calls _refreshNodeFromTarget, not _updateTargetFromNode, because setting auto range off does not require a redraw of the target. """ # TODO: catch exceptions. How? # /argos/hdf-eos/DeepBlue-SeaWiFS-1.0_L3_20100101_v002-20110527T191319Z.h5/aerosol_optical_thickness_stddev_ocean if self.getRefreshBlocked(): logger.debug("setAutoRangeOff blocked for {}".format(self.nodeName)) return if self.autoRangeCti: self.autoRangeCti.data = False self._forceRefreshAutoRange()
python
def setAutoRangeOff(self): # TODO: catch exceptions. How? # /argos/hdf-eos/DeepBlue-SeaWiFS-1.0_L3_20100101_v002-20110527T191319Z.h5/aerosol_optical_thickness_stddev_ocean if self.getRefreshBlocked(): logger.debug("setAutoRangeOff blocked for {}".format(self.nodeName)) return if self.autoRangeCti: self.autoRangeCti.data = False self._forceRefreshAutoRange()
[ "def", "setAutoRangeOff", "(", "self", ")", ":", "# TODO: catch exceptions. How?", "# /argos/hdf-eos/DeepBlue-SeaWiFS-1.0_L3_20100101_v002-20110527T191319Z.h5/aerosol_optical_thickness_stddev_ocean", "if", "self", ".", "getRefreshBlocked", "(", ")", ":", "logger", ".", "debug", "...
Turns off the auto range checkbox. Calls _refreshNodeFromTarget, not _updateTargetFromNode, because setting auto range off does not require a redraw of the target.
[ "Turns", "off", "the", "auto", "range", "checkbox", ".", "Calls", "_refreshNodeFromTarget", "not", "_updateTargetFromNode", "because", "setting", "auto", "range", "off", "does", "not", "require", "a", "redraw", "of", "the", "target", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L298-L312
5,804
titusjan/argos
argos/inspector/pgplugins/pgctis.py
AbstractRangeCti.setAutoRangeOn
def setAutoRangeOn(self): """ Turns on the auto range checkbox for the equivalent axes Emits the sigItemChanged signal so that the inspector may be updated. Use the setXYAxesAutoRangeOn stand-alone function if you want to set the autorange on for both axes of a viewport. """ if self.getRefreshBlocked(): logger.debug("Set autorange on blocked for {}".format(self.nodeName)) return if self.autoRangeCti: self.autoRangeCti.data = True self.model.sigItemChanged.emit(self)
python
def setAutoRangeOn(self): if self.getRefreshBlocked(): logger.debug("Set autorange on blocked for {}".format(self.nodeName)) return if self.autoRangeCti: self.autoRangeCti.data = True self.model.sigItemChanged.emit(self)
[ "def", "setAutoRangeOn", "(", "self", ")", ":", "if", "self", ".", "getRefreshBlocked", "(", ")", ":", "logger", ".", "debug", "(", "\"Set autorange on blocked for {}\"", ".", "format", "(", "self", ".", "nodeName", ")", ")", "return", "if", "self", ".", "...
Turns on the auto range checkbox for the equivalent axes Emits the sigItemChanged signal so that the inspector may be updated. Use the setXYAxesAutoRangeOn stand-alone function if you want to set the autorange on for both axes of a viewport.
[ "Turns", "on", "the", "auto", "range", "checkbox", "for", "the", "equivalent", "axes", "Emits", "the", "sigItemChanged", "signal", "so", "that", "the", "inspector", "may", "be", "updated", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L315-L328
5,805
titusjan/argos
argos/inspector/pgplugins/pgctis.py
AbstractRangeCti.calculateRange
def calculateRange(self): """ Calculates the range depending on the config settings. """ if not self.autoRangeCti or not self.autoRangeCti.configValue: return (self.rangeMinCti.data, self.rangeMaxCti.data) else: rangeFunction = self._rangeFunctions[self.autoRangeMethod] return rangeFunction()
python
def calculateRange(self): if not self.autoRangeCti or not self.autoRangeCti.configValue: return (self.rangeMinCti.data, self.rangeMaxCti.data) else: rangeFunction = self._rangeFunctions[self.autoRangeMethod] return rangeFunction()
[ "def", "calculateRange", "(", "self", ")", ":", "if", "not", "self", ".", "autoRangeCti", "or", "not", "self", ".", "autoRangeCti", ".", "configValue", ":", "return", "(", "self", ".", "rangeMinCti", ".", "data", ",", "self", ".", "rangeMaxCti", ".", "da...
Calculates the range depending on the config settings.
[ "Calculates", "the", "range", "depending", "on", "the", "config", "settings", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L331-L338
5,806
titusjan/argos
argos/inspector/pgplugins/pgctis.py
AbstractRangeCti._updateTargetFromNode
def _updateTargetFromNode(self): """ Applies the configuration to the target axis. """ if not self.autoRangeCti or not self.autoRangeCti.configValue: padding = 0 elif self.paddingCti.configValue == -1: # specialValueText # PyQtGraph dynamic padding: between 0.02 and 0.1 dep. on the size of the ViewBox padding = None else: padding = self.paddingCti.configValue / 100 targetRange = self.calculateRange() #logger.debug("axisRange: {}, padding={}".format(targetRange, padding)) if not np.all(np.isfinite(targetRange)): logger.warn("New target range is not finite. Plot range not updated") return self.setTargetRange(targetRange, padding=padding)
python
def _updateTargetFromNode(self): if not self.autoRangeCti or not self.autoRangeCti.configValue: padding = 0 elif self.paddingCti.configValue == -1: # specialValueText # PyQtGraph dynamic padding: between 0.02 and 0.1 dep. on the size of the ViewBox padding = None else: padding = self.paddingCti.configValue / 100 targetRange = self.calculateRange() #logger.debug("axisRange: {}, padding={}".format(targetRange, padding)) if not np.all(np.isfinite(targetRange)): logger.warn("New target range is not finite. Plot range not updated") return self.setTargetRange(targetRange, padding=padding)
[ "def", "_updateTargetFromNode", "(", "self", ")", ":", "if", "not", "self", ".", "autoRangeCti", "or", "not", "self", ".", "autoRangeCti", ".", "configValue", ":", "padding", "=", "0", "elif", "self", ".", "paddingCti", ".", "configValue", "==", "-", "1", ...
Applies the configuration to the target axis.
[ "Applies", "the", "configuration", "to", "the", "target", "axis", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L341-L358
5,807
titusjan/argos
argos/inspector/pgplugins/pgctis.py
PgAxisRangeCti.setTargetRange
def setTargetRange(self, targetRange, padding=None): """ Sets the range of the target. """ # viewBox.setRange doesn't accept an axis number :-( if self.axisNumber == X_AXIS: xRange, yRange = targetRange, None else: xRange, yRange = None, targetRange # Do not set disableAutoRange to True in setRange; it triggers 'one last' auto range. # This is why the viewBox' autorange must be False at construction. self.viewBox.setRange(xRange = xRange, yRange=yRange, padding=padding, update=False, disableAutoRange=False)
python
def setTargetRange(self, targetRange, padding=None): # viewBox.setRange doesn't accept an axis number :-( if self.axisNumber == X_AXIS: xRange, yRange = targetRange, None else: xRange, yRange = None, targetRange # Do not set disableAutoRange to True in setRange; it triggers 'one last' auto range. # This is why the viewBox' autorange must be False at construction. self.viewBox.setRange(xRange = xRange, yRange=yRange, padding=padding, update=False, disableAutoRange=False)
[ "def", "setTargetRange", "(", "self", ",", "targetRange", ",", "padding", "=", "None", ")", ":", "# viewBox.setRange doesn't accept an axis number :-(", "if", "self", ".", "axisNumber", "==", "X_AXIS", ":", "xRange", ",", "yRange", "=", "targetRange", ",", "None",...
Sets the range of the target.
[ "Sets", "the", "range", "of", "the", "target", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L428-L440
5,808
titusjan/argos
argos/inspector/pgplugins/pgctis.py
PgAxisLabelCti._updateTargetFromNode
def _updateTargetFromNode(self): """ Applies the configuration to the target axis it monitors. The axis label will be set to the configValue. If the configValue equals PgAxisLabelCti.NO_LABEL, the label will be hidden. """ rtiInfo = self.collector.rtiInfo self.plotItem.setLabel(self.axisPosition, self.configValue.format(**rtiInfo)) self.plotItem.showLabel(self.axisPosition, self.configValue != self.NO_LABEL)
python
def _updateTargetFromNode(self): rtiInfo = self.collector.rtiInfo self.plotItem.setLabel(self.axisPosition, self.configValue.format(**rtiInfo)) self.plotItem.showLabel(self.axisPosition, self.configValue != self.NO_LABEL)
[ "def", "_updateTargetFromNode", "(", "self", ")", ":", "rtiInfo", "=", "self", ".", "collector", ".", "rtiInfo", "self", ".", "plotItem", ".", "setLabel", "(", "self", ".", "axisPosition", ",", "self", ".", "configValue", ".", "format", "(", "*", "*", "r...
Applies the configuration to the target axis it monitors. The axis label will be set to the configValue. If the configValue equals PgAxisLabelCti.NO_LABEL, the label will be hidden.
[ "Applies", "the", "configuration", "to", "the", "target", "axis", "it", "monitors", ".", "The", "axis", "label", "will", "be", "set", "to", "the", "configValue", ".", "If", "the", "configValue", "equals", "PgAxisLabelCti", ".", "NO_LABEL", "the", "label", "w...
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L586-L593
5,809
titusjan/argos
argos/inspector/pgplugins/pgctis.py
PgGridCti._updateTargetFromNode
def _updateTargetFromNode(self): """ Applies the configuration to the grid of the plot item. """ self.plotItem.showGrid(x=self.xGridCti.configValue, y=self.yGridCti.configValue, alpha=self.alphaCti.configValue) self.plotItem.updateGrid()
python
def _updateTargetFromNode(self): self.plotItem.showGrid(x=self.xGridCti.configValue, y=self.yGridCti.configValue, alpha=self.alphaCti.configValue) self.plotItem.updateGrid()
[ "def", "_updateTargetFromNode", "(", "self", ")", ":", "self", ".", "plotItem", ".", "showGrid", "(", "x", "=", "self", ".", "xGridCti", ".", "configValue", ",", "y", "=", "self", ".", "yGridCti", ".", "configValue", ",", "alpha", "=", "self", ".", "al...
Applies the configuration to the grid of the plot item.
[ "Applies", "the", "configuration", "to", "the", "grid", "of", "the", "plot", "item", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L667-L672
5,810
titusjan/argos
argos/inspector/pgplugins/pgctis.py
PgPlotDataItemCti.createPlotDataItem
def createPlotDataItem(self): """ Creates a PyQtGraph PlotDataItem from the config values """ antialias = self.antiAliasCti.configValue color = self.penColor if self.lineCti.configValue: pen = QtGui.QPen() pen.setCosmetic(True) pen.setColor(color) pen.setWidthF(self.lineWidthCti.configValue) pen.setStyle(self.lineStyleCti.configValue) shadowCti = self.lineCti.findByNodePath('shadow') shadowPen = shadowCti.createPen(altStyle=pen.style(), altWidth=2.0 * pen.widthF()) else: pen = None shadowPen = None drawSymbols = self.symbolCti.configValue symbolShape = self.symbolShapeCti.configValue if drawSymbols else None symbolSize = self.symbolSizeCti.configValue if drawSymbols else 0.0 symbolPen = None # otherwise the symbols will also have dotted/solid line. symbolBrush = QtGui.QBrush(color) if drawSymbols else None plotDataItem = pg.PlotDataItem(antialias=antialias, pen=pen, shadowPen=shadowPen, symbol=symbolShape, symbolSize=symbolSize, symbolPen=symbolPen, symbolBrush=symbolBrush) return plotDataItem
python
def createPlotDataItem(self): antialias = self.antiAliasCti.configValue color = self.penColor if self.lineCti.configValue: pen = QtGui.QPen() pen.setCosmetic(True) pen.setColor(color) pen.setWidthF(self.lineWidthCti.configValue) pen.setStyle(self.lineStyleCti.configValue) shadowCti = self.lineCti.findByNodePath('shadow') shadowPen = shadowCti.createPen(altStyle=pen.style(), altWidth=2.0 * pen.widthF()) else: pen = None shadowPen = None drawSymbols = self.symbolCti.configValue symbolShape = self.symbolShapeCti.configValue if drawSymbols else None symbolSize = self.symbolSizeCti.configValue if drawSymbols else 0.0 symbolPen = None # otherwise the symbols will also have dotted/solid line. symbolBrush = QtGui.QBrush(color) if drawSymbols else None plotDataItem = pg.PlotDataItem(antialias=antialias, pen=pen, shadowPen=shadowPen, symbol=symbolShape, symbolSize=symbolSize, symbolPen=symbolPen, symbolBrush=symbolBrush) return plotDataItem
[ "def", "createPlotDataItem", "(", "self", ")", ":", "antialias", "=", "self", ".", "antiAliasCti", ".", "configValue", "color", "=", "self", ".", "penColor", "if", "self", ".", "lineCti", ".", "configValue", ":", "pen", "=", "QtGui", ".", "QPen", "(", ")...
Creates a PyQtGraph PlotDataItem from the config values
[ "Creates", "a", "PyQtGraph", "PlotDataItem", "from", "the", "config", "values" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pgctis.py#L721-L748
5,811
titusjan/argos
argos/repo/repotreemodel.py
RepoTreeModel.itemData
def itemData(self, treeItem, column, role=Qt.DisplayRole): """ Returns the data stored under the given role for the item. O """ 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_SHAPE: if treeItem.isSliceable: return " x ".join(str(elem) for elem in treeItem.arrayShape) else: return "" elif column == self.COL_IS_OPEN: # Only show for RTIs that actually open resources. # TODO: this must be clearer. Use CanFetchChildren? Set is Open to None by default? if treeItem.hasChildren(): return str(treeItem.isOpen) else: return "" elif column == self.COL_ELEM_TYPE: return treeItem.elementTypeName elif column == self.COL_FILE_NAME: return treeItem.fileName if hasattr(treeItem, 'fileName') else '' elif column == self.COL_UNIT: return treeItem.unit elif column == self.COL_MISSING_DATA: return to_string(treeItem.missingDataValue, noneFormat='') # empty str for Nones elif column == self.COL_RTI_TYPE: return type_name(treeItem) elif column == self.COL_EXCEPTION: return str(treeItem.exception) if treeItem.exception else '' else: raise ValueError("Invalid column: {}".format(column)) elif role == Qt.ToolTipRole: if treeItem.exception: return str(treeItem.exception) if column == self.COL_NODE_NAME: return treeItem.nodePath # Also path when hovering over the name elif column == self.COL_NODE_PATH: return treeItem.nodePath elif column == self.COL_SHAPE: if treeItem.isSliceable: return " x ".join(str(elem) for elem in treeItem.arrayShape) else: return "" elif column == self.COL_UNIT: return treeItem.unit elif column == self.COL_MISSING_DATA: return to_string(treeItem.missingDataValue, noneFormat='') # empty str for Nones elif column == self.COL_RTI_TYPE: return type_name(treeItem) elif column == self.COL_ELEM_TYPE: return treeItem.elementTypeName elif column == self.COL_FILE_NAME: return treeItem.fileName if hasattr(treeItem, 'fileName') else '' else: return None else: return super(RepoTreeModel, self).itemData(treeItem, column, role=role)
python
def itemData(self, treeItem, column, role=Qt.DisplayRole): 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_SHAPE: if treeItem.isSliceable: return " x ".join(str(elem) for elem in treeItem.arrayShape) else: return "" elif column == self.COL_IS_OPEN: # Only show for RTIs that actually open resources. # TODO: this must be clearer. Use CanFetchChildren? Set is Open to None by default? if treeItem.hasChildren(): return str(treeItem.isOpen) else: return "" elif column == self.COL_ELEM_TYPE: return treeItem.elementTypeName elif column == self.COL_FILE_NAME: return treeItem.fileName if hasattr(treeItem, 'fileName') else '' elif column == self.COL_UNIT: return treeItem.unit elif column == self.COL_MISSING_DATA: return to_string(treeItem.missingDataValue, noneFormat='') # empty str for Nones elif column == self.COL_RTI_TYPE: return type_name(treeItem) elif column == self.COL_EXCEPTION: return str(treeItem.exception) if treeItem.exception else '' else: raise ValueError("Invalid column: {}".format(column)) elif role == Qt.ToolTipRole: if treeItem.exception: return str(treeItem.exception) if column == self.COL_NODE_NAME: return treeItem.nodePath # Also path when hovering over the name elif column == self.COL_NODE_PATH: return treeItem.nodePath elif column == self.COL_SHAPE: if treeItem.isSliceable: return " x ".join(str(elem) for elem in treeItem.arrayShape) else: return "" elif column == self.COL_UNIT: return treeItem.unit elif column == self.COL_MISSING_DATA: return to_string(treeItem.missingDataValue, noneFormat='') # empty str for Nones elif column == self.COL_RTI_TYPE: return type_name(treeItem) elif column == self.COL_ELEM_TYPE: return treeItem.elementTypeName elif column == self.COL_FILE_NAME: return treeItem.fileName if hasattr(treeItem, 'fileName') else '' else: return None else: return super(RepoTreeModel, self).itemData(treeItem, column, role=role)
[ "def", "itemData", "(", "self", ",", "treeItem", ",", "column", ",", "role", "=", "Qt", ".", "DisplayRole", ")", ":", "if", "role", "==", "Qt", ".", "DisplayRole", ":", "if", "column", "==", "self", ".", "COL_NODE_NAME", ":", "return", "treeItem", ".",...
Returns the data stored under the given role for the item. O
[ "Returns", "the", "data", "stored", "under", "the", "given", "role", "for", "the", "item", ".", "O" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreemodel.py#L53-L113
5,812
titusjan/argos
argos/repo/repotreemodel.py
RepoTreeModel.canFetchMore
def canFetchMore(self, parentIndex): """ Returns true if there is more data available for parent; otherwise returns false. """ parentItem = self.getItem(parentIndex) if not parentItem: return False return parentItem.canFetchChildren()
python
def canFetchMore(self, parentIndex): parentItem = self.getItem(parentIndex) if not parentItem: return False return parentItem.canFetchChildren()
[ "def", "canFetchMore", "(", "self", ",", "parentIndex", ")", ":", "parentItem", "=", "self", ".", "getItem", "(", "parentIndex", ")", "if", "not", "parentItem", ":", "return", "False", "return", "parentItem", ".", "canFetchChildren", "(", ")" ]
Returns true if there is more data available for parent; otherwise returns false.
[ "Returns", "true", "if", "there", "is", "more", "data", "available", "for", "parent", ";", "otherwise", "returns", "false", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreemodel.py#L116-L123
5,813
titusjan/argos
argos/repo/repotreemodel.py
RepoTreeModel.fetchMore
def fetchMore(self, parentIndex): # TODO: Make LazyLoadRepoTreeModel? """ Fetches any available data for the items with the parent specified by the parent index. """ parentItem = self.getItem(parentIndex) if not parentItem: return if not parentItem.canFetchChildren(): return # TODO: implement InsertItems to optimize? for childItem in parentItem.fetchChildren(): self.insertItem(childItem, parentIndex=parentIndex) # Check that Rti implementation correctly sets canFetchChildren assert not parentItem.canFetchChildren(), \ "not all children fetched: {}".format(parentItem)
python
def fetchMore(self, parentIndex): # TODO: Make LazyLoadRepoTreeModel? parentItem = self.getItem(parentIndex) if not parentItem: return if not parentItem.canFetchChildren(): return # TODO: implement InsertItems to optimize? for childItem in parentItem.fetchChildren(): self.insertItem(childItem, parentIndex=parentIndex) # Check that Rti implementation correctly sets canFetchChildren assert not parentItem.canFetchChildren(), \ "not all children fetched: {}".format(parentItem)
[ "def", "fetchMore", "(", "self", ",", "parentIndex", ")", ":", "# TODO: Make LazyLoadRepoTreeModel?", "parentItem", "=", "self", ".", "getItem", "(", "parentIndex", ")", "if", "not", "parentItem", ":", "return", "if", "not", "parentItem", ".", "canFetchChildren", ...
Fetches any available data for the items with the parent specified by the parent index.
[ "Fetches", "any", "available", "data", "for", "the", "items", "with", "the", "parent", "specified", "by", "the", "parent", "index", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreemodel.py#L126-L142
5,814
titusjan/argos
argos/repo/repotreemodel.py
RepoTreeModel.findFileRtiIndex
def findFileRtiIndex(self, childIndex): """ Traverses the tree upwards from the item at childIndex until the tree item is found that represents the file the item at childIndex """ parentIndex = childIndex.parent() if not parentIndex.isValid(): return childIndex else: parentItem = self.getItem(parentIndex) childItem = self.getItem(childIndex) if parentItem.fileName == childItem.fileName: return self.findFileRtiIndex(parentIndex) else: return childIndex
python
def findFileRtiIndex(self, childIndex): parentIndex = childIndex.parent() if not parentIndex.isValid(): return childIndex else: parentItem = self.getItem(parentIndex) childItem = self.getItem(childIndex) if parentItem.fileName == childItem.fileName: return self.findFileRtiIndex(parentIndex) else: return childIndex
[ "def", "findFileRtiIndex", "(", "self", ",", "childIndex", ")", ":", "parentIndex", "=", "childIndex", ".", "parent", "(", ")", "if", "not", "parentIndex", ".", "isValid", "(", ")", ":", "return", "childIndex", "else", ":", "parentItem", "=", "self", ".", ...
Traverses the tree upwards from the item at childIndex until the tree item is found that represents the file the item at childIndex
[ "Traverses", "the", "tree", "upwards", "from", "the", "item", "at", "childIndex", "until", "the", "tree", "item", "is", "found", "that", "represents", "the", "file", "the", "item", "at", "childIndex" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreemodel.py#L145-L158
5,815
titusjan/argos
argos/repo/repotreemodel.py
RepoTreeModel.reloadFileAtIndex
def reloadFileAtIndex(self, itemIndex, rtiClass=None): """ Reloads the item at the index by removing the repo tree item and inserting a new one. The new item will have by of type rtiClass. If rtiClass is None (the default), the new rtiClass will be the same as the old one. """ fileRtiParentIndex = itemIndex.parent() fileRti = self.getItem(itemIndex) position = fileRti.childNumber() fileName = fileRti.fileName if rtiClass is None: rtiClass = type(fileRti) # Delete old RTI and Insert a new one instead. self.deleteItemAtIndex(itemIndex) # this will close the items resources. return self.loadFile(fileName, rtiClass, position=position, parentIndex=fileRtiParentIndex)
python
def reloadFileAtIndex(self, itemIndex, rtiClass=None): fileRtiParentIndex = itemIndex.parent() fileRti = self.getItem(itemIndex) position = fileRti.childNumber() fileName = fileRti.fileName if rtiClass is None: rtiClass = type(fileRti) # Delete old RTI and Insert a new one instead. self.deleteItemAtIndex(itemIndex) # this will close the items resources. return self.loadFile(fileName, rtiClass, position=position, parentIndex=fileRtiParentIndex)
[ "def", "reloadFileAtIndex", "(", "self", ",", "itemIndex", ",", "rtiClass", "=", "None", ")", ":", "fileRtiParentIndex", "=", "itemIndex", ".", "parent", "(", ")", "fileRti", "=", "self", ".", "getItem", "(", "itemIndex", ")", "position", "=", "fileRti", "...
Reloads the item at the index by removing the repo tree item and inserting a new one. The new item will have by of type rtiClass. If rtiClass is None (the default), the new rtiClass will be the same as the old one.
[ "Reloads", "the", "item", "at", "the", "index", "by", "removing", "the", "repo", "tree", "item", "and", "inserting", "a", "new", "one", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreemodel.py#L161-L177
5,816
titusjan/argos
argos/repo/repotreemodel.py
RepoTreeModel.loadFile
def loadFile(self, fileName, rtiClass=None, position=None, parentIndex=QtCore.QModelIndex()): """ Loads a file in the repository as a repo tree item of class rtiClass. Autodetects the RTI type if rtiClass is None. If position is None the child will be appended as the last child of the parent. Returns the index of the newly inserted RTI """ logger.info("Loading data from: {!r}".format(fileName)) if rtiClass is None: repoTreeItem = createRtiFromFileName(fileName) else: repoTreeItem = rtiClass.createFromFileName(fileName) assert repoTreeItem.parentItem is None, "repoTreeItem {!r}".format(repoTreeItem) return self.insertItem(repoTreeItem, position=position, parentIndex=parentIndex)
python
def loadFile(self, fileName, rtiClass=None, position=None, parentIndex=QtCore.QModelIndex()): logger.info("Loading data from: {!r}".format(fileName)) if rtiClass is None: repoTreeItem = createRtiFromFileName(fileName) else: repoTreeItem = rtiClass.createFromFileName(fileName) assert repoTreeItem.parentItem is None, "repoTreeItem {!r}".format(repoTreeItem) return self.insertItem(repoTreeItem, position=position, parentIndex=parentIndex)
[ "def", "loadFile", "(", "self", ",", "fileName", ",", "rtiClass", "=", "None", ",", "position", "=", "None", ",", "parentIndex", "=", "QtCore", ".", "QModelIndex", "(", ")", ")", ":", "logger", ".", "info", "(", "\"Loading data from: {!r}\"", ".", "format"...
Loads a file in the repository as a repo tree item of class rtiClass. Autodetects the RTI type if rtiClass is None. If position is None the child will be appended as the last child of the parent. Returns the index of the newly inserted RTI
[ "Loads", "a", "file", "in", "the", "repository", "as", "a", "repo", "tree", "item", "of", "class", "rtiClass", ".", "Autodetects", "the", "RTI", "type", "if", "rtiClass", "is", "None", ".", "If", "position", "is", "None", "the", "child", "will", "be", ...
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreemodel.py#L180-L193
5,817
titusjan/argos
argos/repo/repotreeview.py
RepoTreeView.finalize
def finalize(self): """ Disconnects signals and frees resources """ self.model().sigItemChanged.disconnect(self.repoTreeItemChanged) selectionModel = self.selectionModel() # need to store reference to prevent crash in PySide selectionModel.currentChanged.disconnect(self.currentItemChanged)
python
def finalize(self): self.model().sigItemChanged.disconnect(self.repoTreeItemChanged) selectionModel = self.selectionModel() # need to store reference to prevent crash in PySide selectionModel.currentChanged.disconnect(self.currentItemChanged)
[ "def", "finalize", "(", "self", ")", ":", "self", ".", "model", "(", ")", ".", "sigItemChanged", ".", "disconnect", "(", "self", ".", "repoTreeItemChanged", ")", "selectionModel", "=", "self", ".", "selectionModel", "(", ")", "# need to store reference to preven...
Disconnects signals and frees resources
[ "Disconnects", "signals", "and", "frees", "resources" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreeview.py#L127-L133
5,818
titusjan/argos
argos/repo/repotreeview.py
RepoTreeView.contextMenuEvent
def contextMenuEvent(self, event): """ Creates and executes the context menu for the tree view """ menu = QtWidgets.QMenu(self) for action in self.actions(): menu.addAction(action) openAsMenu = self.createOpenAsMenu(parent=menu) menu.insertMenu(self.closeItemAction, openAsMenu) menu.exec_(event.globalPos())
python
def contextMenuEvent(self, event): menu = QtWidgets.QMenu(self) for action in self.actions(): menu.addAction(action) openAsMenu = self.createOpenAsMenu(parent=menu) menu.insertMenu(self.closeItemAction, openAsMenu) menu.exec_(event.globalPos())
[ "def", "contextMenuEvent", "(", "self", ",", "event", ")", ":", "menu", "=", "QtWidgets", ".", "QMenu", "(", "self", ")", "for", "action", "in", "self", ".", "actions", "(", ")", ":", "menu", ".", "addAction", "(", "action", ")", "openAsMenu", "=", "...
Creates and executes the context menu for the tree view
[ "Creates", "and", "executes", "the", "context", "menu", "for", "the", "tree", "view" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreeview.py#L136-L147
5,819
titusjan/argos
argos/repo/repotreeview.py
RepoTreeView.createOpenAsMenu
def createOpenAsMenu(self, parent=None): """ Creates the submenu for the Open As choice """ openAsMenu = QtWidgets.QMenu(parent=parent) openAsMenu.setTitle("Open Item As") registry = globalRtiRegistry() for rtiRegItem in registry.items: #rtiRegItem.tryImportClass() def createTrigger(): """Function to create a closure with the regItem""" _rtiRegItem = rtiRegItem # keep reference in closure return lambda: self.reloadFileOfCurrentItem(_rtiRegItem) action = QtWidgets.QAction("{}".format(rtiRegItem.name), self, enabled=bool(rtiRegItem.successfullyImported is not False), triggered=createTrigger()) openAsMenu.addAction(action) return openAsMenu
python
def createOpenAsMenu(self, parent=None): openAsMenu = QtWidgets.QMenu(parent=parent) openAsMenu.setTitle("Open Item As") registry = globalRtiRegistry() for rtiRegItem in registry.items: #rtiRegItem.tryImportClass() def createTrigger(): """Function to create a closure with the regItem""" _rtiRegItem = rtiRegItem # keep reference in closure return lambda: self.reloadFileOfCurrentItem(_rtiRegItem) action = QtWidgets.QAction("{}".format(rtiRegItem.name), self, enabled=bool(rtiRegItem.successfullyImported is not False), triggered=createTrigger()) openAsMenu.addAction(action) return openAsMenu
[ "def", "createOpenAsMenu", "(", "self", ",", "parent", "=", "None", ")", ":", "openAsMenu", "=", "QtWidgets", ".", "QMenu", "(", "parent", "=", "parent", ")", "openAsMenu", ".", "setTitle", "(", "\"Open Item As\"", ")", "registry", "=", "globalRtiRegistry", ...
Creates the submenu for the Open As choice
[ "Creates", "the", "submenu", "for", "the", "Open", "As", "choice" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreeview.py#L150-L169
5,820
titusjan/argos
argos/repo/repotreeview.py
RepoTreeView.openCurrentItem
def openCurrentItem(self): """ Opens the current item in the repository. """ logger.debug("openCurrentItem") _currentItem, currentIndex = self.getCurrentItem() if not currentIndex.isValid(): return # Expanding the node will call indirectly call RepoTreeModel.fetchMore which will call # BaseRti.fetchChildren, which will call BaseRti.open and thus open the current RTI. # BaseRti.open will emit the self.model.sigItemChanged signal, which is connected to # RepoTreeView.onItemChanged. self.expand(currentIndex)
python
def openCurrentItem(self): logger.debug("openCurrentItem") _currentItem, currentIndex = self.getCurrentItem() if not currentIndex.isValid(): return # Expanding the node will call indirectly call RepoTreeModel.fetchMore which will call # BaseRti.fetchChildren, which will call BaseRti.open and thus open the current RTI. # BaseRti.open will emit the self.model.sigItemChanged signal, which is connected to # RepoTreeView.onItemChanged. self.expand(currentIndex)
[ "def", "openCurrentItem", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"openCurrentItem\"", ")", "_currentItem", ",", "currentIndex", "=", "self", ".", "getCurrentItem", "(", ")", "if", "not", "currentIndex", ".", "isValid", "(", ")", ":", "return",...
Opens the current item in the repository.
[ "Opens", "the", "current", "item", "in", "the", "repository", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreeview.py#L201-L213
5,821
titusjan/argos
argos/repo/repotreeview.py
RepoTreeView.closeCurrentItem
def closeCurrentItem(self): """ Closes the current item in the repository. All its children will be unfetched and closed. """ logger.debug("closeCurrentItem") currentItem, currentIndex = self.getCurrentItem() if not currentIndex.isValid(): return # First we remove all the children, this will close them as well. self.model().removeAllChildrenAtIndex(currentIndex) # Close the current item. BaseRti.close will emit the self.model.sigItemChanged signal, # which is connected to RepoTreeView.onItemChanged. currentItem.close() self.dataChanged(currentIndex, currentIndex) self.collapse(currentIndex)
python
def closeCurrentItem(self): logger.debug("closeCurrentItem") currentItem, currentIndex = self.getCurrentItem() if not currentIndex.isValid(): return # First we remove all the children, this will close them as well. self.model().removeAllChildrenAtIndex(currentIndex) # Close the current item. BaseRti.close will emit the self.model.sigItemChanged signal, # which is connected to RepoTreeView.onItemChanged. currentItem.close() self.dataChanged(currentIndex, currentIndex) self.collapse(currentIndex)
[ "def", "closeCurrentItem", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"closeCurrentItem\"", ")", "currentItem", ",", "currentIndex", "=", "self", ".", "getCurrentItem", "(", ")", "if", "not", "currentIndex", ".", "isValid", "(", ")", ":", "return"...
Closes the current item in the repository. All its children will be unfetched and closed.
[ "Closes", "the", "current", "item", "in", "the", "repository", ".", "All", "its", "children", "will", "be", "unfetched", "and", "closed", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreeview.py#L217-L233
5,822
titusjan/argos
argos/repo/repotreeview.py
RepoTreeView.removeCurrentItem
def removeCurrentItem(self): """ Removes the current item from the repository tree. """ logger.debug("removeCurrentFile") currentIndex = self.getRowCurrentIndex() if not currentIndex.isValid(): return self.model().deleteItemAtIndex(currentIndex)
python
def removeCurrentItem(self): logger.debug("removeCurrentFile") currentIndex = self.getRowCurrentIndex() if not currentIndex.isValid(): return self.model().deleteItemAtIndex(currentIndex)
[ "def", "removeCurrentItem", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"removeCurrentFile\"", ")", "currentIndex", "=", "self", ".", "getRowCurrentIndex", "(", ")", "if", "not", "currentIndex", ".", "isValid", "(", ")", ":", "return", "self", ".",...
Removes the current item from the repository tree.
[ "Removes", "the", "current", "item", "from", "the", "repository", "tree", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreeview.py#L253-L261
5,823
titusjan/argos
argos/repo/repotreeview.py
RepoTreeView.reloadFileOfCurrentItem
def reloadFileOfCurrentItem(self, rtiRegItem=None): """ Finds the repo tree item that holds the file of the current item and reloads it. Reloading is done by removing the repo tree item and inserting a new one. The new item will have by of type rtiRegItem.cls. If rtiRegItem is None (the default), the new rtiClass will be the same as the old one. The rtiRegItem.cls will be imported. If this fails the old class will be used, and a warning will be logged. """ logger.debug("reloadFileOfCurrentItem, rtiClass={}".format(rtiRegItem)) currentIndex = self.getRowCurrentIndex() if not currentIndex.isValid(): return currentItem, _ = self.getCurrentItem() oldPath = currentItem.nodePath fileRtiIndex = self.model().findFileRtiIndex(currentIndex) isExpanded = self.isExpanded(fileRtiIndex) if rtiRegItem is None: rtiClass = None else: rtiRegItem.tryImportClass() rtiClass = rtiRegItem.cls newRtiIndex = self.model().reloadFileAtIndex(fileRtiIndex, rtiClass=rtiClass) try: # Expand and select the name with the old path _lastItem, lastIndex = self.expandPath(oldPath) self.setCurrentIndex(lastIndex) return lastIndex except Exception as ex: # The old path may not exist anymore. In that case select file RTI logger.warning("Unable to select {!r} beause of: {}".format(oldPath, ex)) self.setExpanded(newRtiIndex, isExpanded) self.setCurrentIndex(newRtiIndex) return newRtiIndex
python
def reloadFileOfCurrentItem(self, rtiRegItem=None): logger.debug("reloadFileOfCurrentItem, rtiClass={}".format(rtiRegItem)) currentIndex = self.getRowCurrentIndex() if not currentIndex.isValid(): return currentItem, _ = self.getCurrentItem() oldPath = currentItem.nodePath fileRtiIndex = self.model().findFileRtiIndex(currentIndex) isExpanded = self.isExpanded(fileRtiIndex) if rtiRegItem is None: rtiClass = None else: rtiRegItem.tryImportClass() rtiClass = rtiRegItem.cls newRtiIndex = self.model().reloadFileAtIndex(fileRtiIndex, rtiClass=rtiClass) try: # Expand and select the name with the old path _lastItem, lastIndex = self.expandPath(oldPath) self.setCurrentIndex(lastIndex) return lastIndex except Exception as ex: # The old path may not exist anymore. In that case select file RTI logger.warning("Unable to select {!r} beause of: {}".format(oldPath, ex)) self.setExpanded(newRtiIndex, isExpanded) self.setCurrentIndex(newRtiIndex) return newRtiIndex
[ "def", "reloadFileOfCurrentItem", "(", "self", ",", "rtiRegItem", "=", "None", ")", ":", "logger", ".", "debug", "(", "\"reloadFileOfCurrentItem, rtiClass={}\"", ".", "format", "(", "rtiRegItem", ")", ")", "currentIndex", "=", "self", ".", "getRowCurrentIndex", "(...
Finds the repo tree item that holds the file of the current item and reloads it. Reloading is done by removing the repo tree item and inserting a new one. The new item will have by of type rtiRegItem.cls. If rtiRegItem is None (the default), the new rtiClass will be the same as the old one. The rtiRegItem.cls will be imported. If this fails the old class will be used, and a warning will be logged.
[ "Finds", "the", "repo", "tree", "item", "that", "holds", "the", "file", "of", "the", "current", "item", "and", "reloads", "it", ".", "Reloading", "is", "done", "by", "removing", "the", "repo", "tree", "item", "and", "inserting", "a", "new", "one", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreeview.py#L265-L305
5,824
titusjan/argos
argos/repo/repotreeview.py
RepoTreeView.currentRepoTreeItemChanged
def currentRepoTreeItemChanged(self): """ Called to update the GUI when a repo tree item has changed or a new one was selected. """ # When the model is empty the current index may be invalid and the currentItem may be None. currentItem, currentIndex = self.getCurrentItem() hasCurrent = currentIndex.isValid() assert hasCurrent == (currentItem is not None), \ "If current idex is valid, currentIndex may not be None" # sanity check # Set the item in the collector, will will subsequently update the inspector. if hasCurrent: logger.info("Adding rti to collector: {}".format(currentItem.nodePath)) self.collector.setRti(currentItem) #if rti.asArray is not None: # TODO: maybe later, first test how robust it is now # self.collector.setRti(rti) # Update context menus in the repo tree self.currentItemActionGroup.setEnabled(hasCurrent) isTopLevel = hasCurrent and self.model().isTopLevelIndex(currentIndex) self.topLevelItemActionGroup.setEnabled(isTopLevel) self.openItemAction.setEnabled(currentItem is not None and currentItem.hasChildren() and not currentItem.isOpen) self.closeItemAction.setEnabled(currentItem is not None and currentItem.hasChildren() and currentItem.isOpen) # Emit sigRepoItemChanged signal so that, for example, details panes can update. logger.debug("Emitting sigRepoItemChanged: {}".format(currentItem)) self.sigRepoItemChanged.emit(currentItem)
python
def currentRepoTreeItemChanged(self): # When the model is empty the current index may be invalid and the currentItem may be None. currentItem, currentIndex = self.getCurrentItem() hasCurrent = currentIndex.isValid() assert hasCurrent == (currentItem is not None), \ "If current idex is valid, currentIndex may not be None" # sanity check # Set the item in the collector, will will subsequently update the inspector. if hasCurrent: logger.info("Adding rti to collector: {}".format(currentItem.nodePath)) self.collector.setRti(currentItem) #if rti.asArray is not None: # TODO: maybe later, first test how robust it is now # self.collector.setRti(rti) # Update context menus in the repo tree self.currentItemActionGroup.setEnabled(hasCurrent) isTopLevel = hasCurrent and self.model().isTopLevelIndex(currentIndex) self.topLevelItemActionGroup.setEnabled(isTopLevel) self.openItemAction.setEnabled(currentItem is not None and currentItem.hasChildren() and not currentItem.isOpen) self.closeItemAction.setEnabled(currentItem is not None and currentItem.hasChildren() and currentItem.isOpen) # Emit sigRepoItemChanged signal so that, for example, details panes can update. logger.debug("Emitting sigRepoItemChanged: {}".format(currentItem)) self.sigRepoItemChanged.emit(currentItem)
[ "def", "currentRepoTreeItemChanged", "(", "self", ")", ":", "# When the model is empty the current index may be invalid and the currentItem may be None.", "currentItem", ",", "currentIndex", "=", "self", ".", "getCurrentItem", "(", ")", "hasCurrent", "=", "currentIndex", ".", ...
Called to update the GUI when a repo tree item has changed or a new one was selected.
[ "Called", "to", "update", "the", "GUI", "when", "a", "repo", "tree", "item", "has", "changed", "or", "a", "new", "one", "was", "selected", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/repotreeview.py#L335-L365
5,825
titusjan/argos
argos/qt/misc.py
initQApplication
def initQApplication(): """ Initializes the QtWidgets.QApplication instance. Creates one if it doesn't exist. Sets Argos specific attributes, such as the OrganizationName, so that the application persistent settings are read/written to the correct settings file/winreg. It is therefore important to call this function at startup. The ArgosApplication constructor does this. Returns the application. """ # PyQtGraph recommends raster graphics system for OS-X. if 'darwin' in sys.platform: graphicsSystem = "raster" # raster, native or opengl os.environ.setdefault('QT_GRAPHICSSYSTEM', graphicsSystem) logger.info("Setting QT_GRAPHICSSYSTEM to: {}".format(graphicsSystem)) app = QtWidgets.QApplication(sys.argv) initArgosApplicationSettings(app) return app
python
def initQApplication(): # PyQtGraph recommends raster graphics system for OS-X. if 'darwin' in sys.platform: graphicsSystem = "raster" # raster, native or opengl os.environ.setdefault('QT_GRAPHICSSYSTEM', graphicsSystem) logger.info("Setting QT_GRAPHICSSYSTEM to: {}".format(graphicsSystem)) app = QtWidgets.QApplication(sys.argv) initArgosApplicationSettings(app) return app
[ "def", "initQApplication", "(", ")", ":", "# PyQtGraph recommends raster graphics system for OS-X.", "if", "'darwin'", "in", "sys", ".", "platform", ":", "graphicsSystem", "=", "\"raster\"", "# raster, native or opengl", "os", ".", "environ", ".", "setdefault", "(", "'Q...
Initializes the QtWidgets.QApplication instance. Creates one if it doesn't exist. Sets Argos specific attributes, such as the OrganizationName, so that the application persistent settings are read/written to the correct settings file/winreg. It is therefore important to call this function at startup. The ArgosApplication constructor does this. Returns the application.
[ "Initializes", "the", "QtWidgets", ".", "QApplication", "instance", ".", "Creates", "one", "if", "it", "doesn", "t", "exist", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/misc.py#L116-L133
5,826
titusjan/argos
argos/qt/misc.py
removeSettingsGroup
def removeSettingsGroup(groupName, settings=None): """ Removes a group from the persistent settings """ logger.debug("Removing settings group: {}".format(groupName)) settings = QtCore.QSettings() if settings is None else settings settings.remove(groupName)
python
def removeSettingsGroup(groupName, settings=None): logger.debug("Removing settings group: {}".format(groupName)) settings = QtCore.QSettings() if settings is None else settings settings.remove(groupName)
[ "def", "removeSettingsGroup", "(", "groupName", ",", "settings", "=", "None", ")", ":", "logger", ".", "debug", "(", "\"Removing settings group: {}\"", ".", "format", "(", "groupName", ")", ")", "settings", "=", "QtCore", ".", "QSettings", "(", ")", "if", "s...
Removes a group from the persistent settings
[ "Removes", "a", "group", "from", "the", "persistent", "settings" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/misc.py#L217-L222
5,827
titusjan/argos
argos/qt/misc.py
containsSettingsGroup
def containsSettingsGroup(groupName, settings=None): """ Returns True if the settings contain a group with the name groupName. Works recursively when the groupName is a slash separated path. """ def _containsPath(path, settings): "Aux function for containsSettingsGroup. Does the actual recursive search." if len(path) == 0: return True else: head = path[0] tail = path[1:] if head not in settings.childGroups(): return False else: settings.beginGroup(head) try: return _containsPath(tail, settings) finally: settings.endGroup() # Body starts here path = os.path.split(groupName) logger.debug("Looking for path: {}".format(path)) settings = QtCore.QSettings() if settings is None else settings return _containsPath(path, settings)
python
def containsSettingsGroup(groupName, settings=None): def _containsPath(path, settings): "Aux function for containsSettingsGroup. Does the actual recursive search." if len(path) == 0: return True else: head = path[0] tail = path[1:] if head not in settings.childGroups(): return False else: settings.beginGroup(head) try: return _containsPath(tail, settings) finally: settings.endGroup() # Body starts here path = os.path.split(groupName) logger.debug("Looking for path: {}".format(path)) settings = QtCore.QSettings() if settings is None else settings return _containsPath(path, settings)
[ "def", "containsSettingsGroup", "(", "groupName", ",", "settings", "=", "None", ")", ":", "def", "_containsPath", "(", "path", ",", "settings", ")", ":", "\"Aux function for containsSettingsGroup. Does the actual recursive search.\"", "if", "len", "(", "path", ")", "=...
Returns True if the settings contain a group with the name groupName. Works recursively when the groupName is a slash separated path.
[ "Returns", "True", "if", "the", "settings", "contain", "a", "group", "with", "the", "name", "groupName", ".", "Works", "recursively", "when", "the", "groupName", "is", "a", "slash", "separated", "path", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/misc.py#L225-L249
5,828
titusjan/argos
argos/qt/misc.py
printChildren
def printChildren(obj, indent=""): """ Recursively prints the children of a QObject. Useful for debugging. """ children=obj.children() if children==None: return for child in children: try: childName = child.objectName() except AttributeError: childName = "<no-name>" #print ("{}{:10s}: {}".format(indent, childName, child.__class__)) print ("{}{!r}: {}".format(indent, childName, child.__class__)) printChildren(child, indent + " ")
python
def printChildren(obj, indent=""): children=obj.children() if children==None: return for child in children: try: childName = child.objectName() except AttributeError: childName = "<no-name>" #print ("{}{:10s}: {}".format(indent, childName, child.__class__)) print ("{}{!r}: {}".format(indent, childName, child.__class__)) printChildren(child, indent + " ")
[ "def", "printChildren", "(", "obj", ",", "indent", "=", "\"\"", ")", ":", "children", "=", "obj", ".", "children", "(", ")", "if", "children", "==", "None", ":", "return", "for", "child", "in", "children", ":", "try", ":", "childName", "=", "child", ...
Recursively prints the children of a QObject. Useful for debugging.
[ "Recursively", "prints", "the", "children", "of", "a", "QObject", ".", "Useful", "for", "debugging", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/misc.py#L255-L269
5,829
titusjan/argos
argos/qt/misc.py
widgetSubCheckBoxRect
def widgetSubCheckBoxRect(widget, option): """ Returns the rectangle of a check box drawn as a sub element of widget """ opt = QtWidgets.QStyleOption() opt.initFrom(widget) style = widget.style() return style.subElementRect(QtWidgets.QStyle.SE_ViewItemCheckIndicator, opt, widget)
python
def widgetSubCheckBoxRect(widget, option): opt = QtWidgets.QStyleOption() opt.initFrom(widget) style = widget.style() return style.subElementRect(QtWidgets.QStyle.SE_ViewItemCheckIndicator, opt, widget)
[ "def", "widgetSubCheckBoxRect", "(", "widget", ",", "option", ")", ":", "opt", "=", "QtWidgets", ".", "QStyleOption", "(", ")", "opt", ".", "initFrom", "(", "widget", ")", "style", "=", "widget", ".", "style", "(", ")", "return", "style", ".", "subElemen...
Returns the rectangle of a check box drawn as a sub element of widget
[ "Returns", "the", "rectangle", "of", "a", "check", "box", "drawn", "as", "a", "sub", "element", "of", "widget" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/misc.py#L286-L292
5,830
titusjan/argos
argos/inspector/abstract.py
UpdateReason.checkValid
def checkValid(cls, reason): """ Raises ValueError if the reason is not one of the valid enumerations """ if reason not in cls.__VALID_REASONS: raise ValueError("reason must be one of {}, got {}".format(cls.__VALID_REASONS, reason))
python
def checkValid(cls, reason): if reason not in cls.__VALID_REASONS: raise ValueError("reason must be one of {}, got {}".format(cls.__VALID_REASONS, reason))
[ "def", "checkValid", "(", "cls", ",", "reason", ")", ":", "if", "reason", "not", "in", "cls", ".", "__VALID_REASONS", ":", "raise", "ValueError", "(", "\"reason must be one of {}, got {}\"", ".", "format", "(", "cls", ".", "__VALID_REASONS", ",", "reason", ")"...
Raises ValueError if the reason is not one of the valid enumerations
[ "Raises", "ValueError", "if", "the", "reason", "is", "not", "one", "of", "the", "valid", "enumerations" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/abstract.py#L60-L64
5,831
titusjan/argos
argos/inspector/abstract.py
AbstractInspector.updateContents
def updateContents(self, reason=None, initiator=None): # TODO: reason mandatory? """ Tries to draw the widget contents with the updated RTI. Shows the error page in case an exception is raised while drawing the contents. Descendants should override _drawContents, not updateContents. During the call of _drawContents, the updating of the configuration tree is blocked to avoid circular effects. After that, a call to self.config.refreshFromTarget() is made to refresh the configuration tree with possible new values from the inspector (the inspector is the configuration's target, hence the name). The reason parameter is a string (one of the UpdateReason values) that indicates why the inspector contents whas updated. This can, for instance, be used to optimize drawing the inspector contents. Note that the reason may be undefined (None). The initiator may contain the object that initiated the updated. The type depends on the reason. At the moment the initiator is only implemented for the "config changed" reason. In this case the initiator will be the Config Tree Item (CTI that has changed). """ UpdateReason.checkValid(reason) logger.debug("---- Inspector updateContents, reason: {}, initiator: {}" .format(reason, initiator)) logger.debug("Inspector: {}".format(self)) logger.debug("RTI: {}".format(self.collector.rti)) try: self.setCurrentIndex(self.CONTENTS_PAGE_IDX) wasBlocked = self.config.model.setRefreshBlocked(True) try: self._drawContents(reason=reason, initiator=initiator) logger.debug("_drawContents finished successfully") # 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() # TODO: enable this here (instead of doing it in the inspector._drawContents when needed)? finally: self.config.model.setRefreshBlocked(wasBlocked) # Call refreshFromTarget in case the newly applied configuration resulted in a change # of the state of the configuration's target's (i.e. the inspector state) logger.debug("_drawContents finished successfully, calling refreshFromTarget...") self.config.refreshFromTarget() logger.debug("refreshFromTarget finished successfully") except InvalidDataError as ex: logger.info("Unable to draw the inspector contents: {}".format(ex)) except Exception as ex: if DEBUGGING: # TODO: enable raise logger.error("Error while drawing the inspector: {} ----".format(ex)) logger.exception(ex) self._clearContents() self.setCurrentIndex(self.ERROR_PAGE_IDX) self._showError(msg=str(ex), title=type_name(ex)) else: logger.debug("---- updateContents finished successfully")
python
def updateContents(self, reason=None, initiator=None): # TODO: reason mandatory? UpdateReason.checkValid(reason) logger.debug("---- Inspector updateContents, reason: {}, initiator: {}" .format(reason, initiator)) logger.debug("Inspector: {}".format(self)) logger.debug("RTI: {}".format(self.collector.rti)) try: self.setCurrentIndex(self.CONTENTS_PAGE_IDX) wasBlocked = self.config.model.setRefreshBlocked(True) try: self._drawContents(reason=reason, initiator=initiator) logger.debug("_drawContents finished successfully") # 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() # TODO: enable this here (instead of doing it in the inspector._drawContents when needed)? finally: self.config.model.setRefreshBlocked(wasBlocked) # Call refreshFromTarget in case the newly applied configuration resulted in a change # of the state of the configuration's target's (i.e. the inspector state) logger.debug("_drawContents finished successfully, calling refreshFromTarget...") self.config.refreshFromTarget() logger.debug("refreshFromTarget finished successfully") except InvalidDataError as ex: logger.info("Unable to draw the inspector contents: {}".format(ex)) except Exception as ex: if DEBUGGING: # TODO: enable raise logger.error("Error while drawing the inspector: {} ----".format(ex)) logger.exception(ex) self._clearContents() self.setCurrentIndex(self.ERROR_PAGE_IDX) self._showError(msg=str(ex), title=type_name(ex)) else: logger.debug("---- updateContents finished successfully")
[ "def", "updateContents", "(", "self", ",", "reason", "=", "None", ",", "initiator", "=", "None", ")", ":", "# TODO: reason mandatory?", "UpdateReason", ".", "checkValid", "(", "reason", ")", "logger", ".", "debug", "(", "\"---- Inspector updateContents, reason: {}, ...
Tries to draw the widget contents with the updated RTI. Shows the error page in case an exception is raised while drawing the contents. Descendants should override _drawContents, not updateContents. During the call of _drawContents, the updating of the configuration tree is blocked to avoid circular effects. After that, a call to self.config.refreshFromTarget() is made to refresh the configuration tree with possible new values from the inspector (the inspector is the configuration's target, hence the name). The reason parameter is a string (one of the UpdateReason values) that indicates why the inspector contents whas updated. This can, for instance, be used to optimize drawing the inspector contents. Note that the reason may be undefined (None). The initiator may contain the object that initiated the updated. The type depends on the reason. At the moment the initiator is only implemented for the "config changed" reason. In this case the initiator will be the Config Tree Item (CTI that has changed).
[ "Tries", "to", "draw", "the", "widget", "contents", "with", "the", "updated", "RTI", ".", "Shows", "the", "error", "page", "in", "case", "an", "exception", "is", "raised", "while", "drawing", "the", "contents", ".", "Descendants", "should", "override", "_dra...
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/abstract.py#L167-L222
5,832
titusjan/argos
argos/inspector/abstract.py
AbstractInspector._showError
def _showError(self, msg="", title="Error"): """ Shows an error message. """ self.errorWidget.setError(msg=msg, title=title)
python
def _showError(self, msg="", title="Error"): self.errorWidget.setError(msg=msg, title=title)
[ "def", "_showError", "(", "self", ",", "msg", "=", "\"\"", ",", "title", "=", "\"Error\"", ")", ":", "self", ".", "errorWidget", ".", "setError", "(", "msg", "=", "msg", ",", "title", "=", "title", ")" ]
Shows an error message.
[ "Shows", "an", "error", "message", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/abstract.py#L244-L247
5,833
titusjan/argos
argos/config/choicecti.py
ChoiceCti._enforceDataType
def _enforceDataType(self, data): """ Converts to int so that this CTI always stores that type. The data be set to a negative value, e.g. use -1 to select the last item by default. However, it will be converted to a positive by this method. """ idx = int(data) if idx < 0: idx += len(self._displayValues) assert 0 <= idx < len(self._displayValues), \ "Index should be >= 0 and < {}. Got {}".format(len(self._displayValues), idx) return idx
python
def _enforceDataType(self, data): idx = int(data) if idx < 0: idx += len(self._displayValues) assert 0 <= idx < len(self._displayValues), \ "Index should be >= 0 and < {}. Got {}".format(len(self._displayValues), idx) return idx
[ "def", "_enforceDataType", "(", "self", ",", "data", ")", ":", "idx", "=", "int", "(", "data", ")", "if", "idx", "<", "0", ":", "idx", "+=", "len", "(", "self", ".", "_displayValues", ")", "assert", "0", "<=", "idx", "<", "len", "(", "self", ".",...
Converts to int so that this CTI always stores that type. The data be set to a negative value, e.g. use -1 to select the last item by default. However, it will be converted to a positive by this method.
[ "Converts", "to", "int", "so", "that", "this", "CTI", "always", "stores", "that", "type", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/choicecti.py#L91-L102
5,834
titusjan/argos
argos/config/choicecti.py
ChoiceCti.insertValue
def insertValue(self, pos, configValue, displayValue=None): """ Will insert the configValue in the configValues and the displayValue in the displayValues list. If displayValue is None, the configValue is set in the displayValues as well """ self._configValues.insert(pos, configValue) self._displayValues.insert(pos, displayValue if displayValue is not None else configValue)
python
def insertValue(self, pos, configValue, displayValue=None): self._configValues.insert(pos, configValue) self._displayValues.insert(pos, displayValue if displayValue is not None else configValue)
[ "def", "insertValue", "(", "self", ",", "pos", ",", "configValue", ",", "displayValue", "=", "None", ")", ":", "self", ".", "_configValues", ".", "insert", "(", "pos", ",", "configValue", ")", "self", ".", "_displayValues", ".", "insert", "(", "pos", ","...
Will insert the configValue in the configValues and the displayValue in the displayValues list. If displayValue is None, the configValue is set in the displayValues as well
[ "Will", "insert", "the", "configValue", "in", "the", "configValues", "and", "the", "displayValue", "in", "the", "displayValues", "list", ".", "If", "displayValue", "is", "None", "the", "configValue", "is", "set", "in", "the", "displayValues", "as", "well" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/choicecti.py#L168-L174
5,835
titusjan/argos
argos/config/choicecti.py
ChoiceCtiEditor.comboBoxRowsInserted
def comboBoxRowsInserted(self, _parent, start, end): """ Called when the user has entered a new value in the combobox. Puts the combobox values back into the cti. """ assert start == end, "Bug, please report: more than one row inserted" configValue = self.comboBox.itemText(start) logger.debug("Inserting {!r} at position {} in {}" .format(configValue, start, self.cti.nodePath)) self.cti.insertValue(start, configValue)
python
def comboBoxRowsInserted(self, _parent, start, end): assert start == end, "Bug, please report: more than one row inserted" configValue = self.comboBox.itemText(start) logger.debug("Inserting {!r} at position {} in {}" .format(configValue, start, self.cti.nodePath)) self.cti.insertValue(start, configValue)
[ "def", "comboBoxRowsInserted", "(", "self", ",", "_parent", ",", "start", ",", "end", ")", ":", "assert", "start", "==", "end", ",", "\"Bug, please report: more than one row inserted\"", "configValue", "=", "self", ".", "comboBox", ".", "itemText", "(", "start", ...
Called when the user has entered a new value in the combobox. Puts the combobox values back into the cti.
[ "Called", "when", "the", "user", "has", "entered", "a", "new", "value", "in", "the", "combobox", ".", "Puts", "the", "combobox", "values", "back", "into", "the", "cti", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/choicecti.py#L250-L258
5,836
titusjan/argos
argos/config/choicecti.py
ChoiceCtiEditor.eventFilter
def eventFilter(self, watchedObject, event): """ Deletes an item from an editable combobox when the delete or backspace key is pressed in the list of items, or when ctrl-delete or ctrl-back space is pressed in the line-edit. When the combobox is not editable the filter does nothing. """ if self.comboBox.isEditable() and event.type() == QtCore.QEvent.KeyPress: key = event.key() if key in (Qt.Key_Delete, Qt.Key_Backspace): if (watchedObject == self._comboboxListView or (watchedObject == self.comboBox and event.modifiers() == Qt.ControlModifier)): index = self._comboboxListView.currentIndex() if index.isValid(): row = index.row() logger.debug("Removing item {} from the combobox: {}" .format(row, self._comboboxListView.model().data(index))) self.cti.removeValueByIndex(row) self.comboBox.removeItem(row) return True # Calling parent event filter, which may filter out other events. return super(ChoiceCtiEditor, self).eventFilter(watchedObject, event)
python
def eventFilter(self, watchedObject, event): if self.comboBox.isEditable() and event.type() == QtCore.QEvent.KeyPress: key = event.key() if key in (Qt.Key_Delete, Qt.Key_Backspace): if (watchedObject == self._comboboxListView or (watchedObject == self.comboBox and event.modifiers() == Qt.ControlModifier)): index = self._comboboxListView.currentIndex() if index.isValid(): row = index.row() logger.debug("Removing item {} from the combobox: {}" .format(row, self._comboboxListView.model().data(index))) self.cti.removeValueByIndex(row) self.comboBox.removeItem(row) return True # Calling parent event filter, which may filter out other events. return super(ChoiceCtiEditor, self).eventFilter(watchedObject, event)
[ "def", "eventFilter", "(", "self", ",", "watchedObject", ",", "event", ")", ":", "if", "self", ".", "comboBox", ".", "isEditable", "(", ")", "and", "event", ".", "type", "(", ")", "==", "QtCore", ".", "QEvent", ".", "KeyPress", ":", "key", "=", "even...
Deletes an item from an editable combobox when the delete or backspace key is pressed in the list of items, or when ctrl-delete or ctrl-back space is pressed in the line-edit. When the combobox is not editable the filter does nothing.
[ "Deletes", "an", "item", "from", "an", "editable", "combobox", "when", "the", "delete", "or", "backspace", "key", "is", "pressed", "in", "the", "list", "of", "items", "or", "when", "ctrl", "-", "delete", "or", "ctrl", "-", "back", "space", "is", "pressed...
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/choicecti.py#L261-L285
5,837
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): 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)
[ "def", "itemData", "(", "self", ",", "treeItem", ",", "column", ",", "role", "=", "Qt", ".", "DisplayRole", ")", ":", "if", "role", "==", "Qt", ".", "DisplayRole", ":", "if", "column", "==", "self", ".", "COL_NODE_NAME", ":", "return", "treeItem", ".",...
Returns the data stored under the given role for the item.
[ "Returns", "the", "data", "stored", "under", "the", "given", "role", "for", "the", "item", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configtreemodel.py#L95-L142
5,838
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): 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))
[ "def", "setItemData", "(", "self", ",", "treeItem", ",", "column", ",", "value", ",", "role", "=", "Qt", ".", "EditRole", ")", ":", "if", "role", "==", "Qt", ".", "CheckStateRole", ":", "if", "column", "!=", "self", ".", "COL_VALUE", ":", "return", "...
Sets the role data for the item at index to value.
[ "Sets", "the", "role", "data", "for", "the", "item", "at", "index", "to", "value", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configtreemodel.py#L145-L164
5,839
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): wasBlocked = self._refreshBlocked logger.debug("Setting refreshBlocked from {} to {}".format(wasBlocked, blocked)) self._refreshBlocked = blocked return wasBlocked
[ "def", "setRefreshBlocked", "(", "self", ",", "blocked", ")", ":", "wasBlocked", "=", "self", ".", "_refreshBlocked", "logger", ".", "debug", "(", "\"Setting refreshBlocked from {} to {}\"", ".", "format", "(", "wasBlocked", ",", "blocked", ")", ")", "self", "."...
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.
[ "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", ...
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/configtreemodel.py#L224-L232
5,840
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): # 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
[ "def", "data", "(", "self", ",", "data", ")", ":", "# Descendants should convert the data to the desired type here", "self", ".", "_data", "=", "self", ".", "_enforceDataType", "(", "data", ")", "#logger.debug(\"BoolCti.setData: {} for {}\".format(data, self))", "enabled", ...
Sets the data of this item. Does type conversion to ensure data is always of the correct type.
[ "Sets", "the", "data", "of", "this", "item", ".", "Does", "type", "conversion", "to", "ensure", "data", "is", "always", "of", "the", "correct", "type", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/boolcti.py#L69-L79
5,841
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): 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
[ "def", "insertChild", "(", "self", ",", "childItem", ",", "position", "=", "None", ")", ":", "childItem", "=", "super", "(", "BoolCti", ",", "self", ")", ".", "insertChild", "(", "childItem", ",", "position", "=", "None", ")", "enableChildren", "=", "sel...
Inserts a child item to the current item. Overridden from BaseTreeItem.
[ "Inserts", "a", "child", "item", "to", "the", "current", "item", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/boolcti.py#L89-L100
5,842
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): 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))
[ "def", "checkState", "(", "self", ")", ":", "if", "self", ".", "data", "is", "True", ":", "return", "Qt", ".", "Checked", "elif", "self", ".", "data", "is", "False", ":", "return", "Qt", ".", "Unchecked", "else", ":", "raise", "ValueError", "(", "\"U...
Returns Qt.Checked or Qt.Unchecked.
[ "Returns", "Qt", ".", "Checked", "or", "Qt", ".", "Unchecked", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/boolcti.py#L112-L120
5,843
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): #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))
[ "def", "checkState", "(", "self", ")", ":", "#commonData = self.childItems[0].data if self.childItems else Qt.PartiallyChecked", "commonData", "=", "None", "for", "child", "in", "self", ".", "childItems", ":", "if", "isinstance", "(", "child", ",", "BoolCti", ")", ":"...
Returns Qt.Checked or Qt.Unchecked if all children are checked or unchecked, else returns Qt.PartiallyChecked
[ "Returns", "Qt", ".", "Checked", "or", "Qt", ".", "Unchecked", "if", "all", "children", "are", "checked", "or", "unchecked", "else", "returns", "Qt", ".", "PartiallyChecked" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/boolcti.py#L195-L213
5,844
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): 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)
[ "def", "open", "(", "self", ")", ":", "self", ".", "clearException", "(", ")", "try", ":", "if", "self", ".", "_isOpen", ":", "logger", ".", "warn", "(", "\"Resources already open. Closing them first before opening.\"", ")", "self", ".", "_closeResources", "(", ...
Opens underlying resources and sets isOpen flag. It calls _openResources. Descendants should usually override the latter function instead of this one.
[ "Opens", "underlying", "resources", "and", "sets", "isOpen", "flag", ".", "It", "calls", "_openResources", ".", "Descendants", "should", "usually", "override", "the", "latter", "function", "instead", "of", "this", "one", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/baserti.py#L92-L118
5,845
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): 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)
[ "def", "close", "(", "self", ")", ":", "self", ".", "clearException", "(", ")", "try", ":", "if", "self", ".", "_isOpen", ":", "logger", ".", "debug", "(", "\"Closing {}\"", ".", "format", "(", "self", ")", ")", "self", ".", "_closeResources", "(", "...
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.
[ "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", ...
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/baserti.py#L129-L153
5,846
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): 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
[ "def", "_checkFileExists", "(", "self", ")", ":", "if", "self", ".", "_fileName", "and", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_fileName", ")", ":", "msg", "=", "\"File not found: {}\"", ".", "format", "(", "self", ".", "_fileName",...
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.
[ "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", ...
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/baserti.py#L164-L175
5,847
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): 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
[ "def", "fetchChildren", "(", "self", ")", ":", "assert", "self", ".", "_canFetchChildren", ",", "\"canFetchChildren must be True\"", "try", ":", "self", ".", "clearException", "(", ")", "if", "not", "self", ".", "isOpen", ":", "self", ".", "open", "(", ")", ...
Creates child items and returns them. Opens the tree item first if it's not yet open.
[ "Creates", "child", "items", "and", "returns", "them", ".", "Opens", "the", "tree", "item", "first", "if", "it", "s", "not", "yet", "open", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/baserti.py#L196-L226
5,848
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): 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)
[ "def", "decoration", "(", "self", ")", ":", "rtiIconFactory", "=", "RtiIconFactory", ".", "singleton", "(", ")", "if", "self", ".", "_exception", ":", "return", "rtiIconFactory", ".", "getIcon", "(", "rtiIconFactory", ".", "ERROR", ",", "isOpen", "=", "False...
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.
[ "The", "displayed", "icon", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/baserti.py#L261-L275
5,849
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 string = "{:g}".format(value).replace("e+", "e") string = re.sub("e(-?)0*(\d+)", r"e\1\2", string) return string
[ "def", "format_float", "(", "value", ")", ":", "# not used", "string", "=", "\"{:g}\"", ".", "format", "(", "value", ")", ".", "replace", "(", "\"e+\"", ",", "\"e\"", ")", "string", "=", "re", ".", "sub", "(", "\"e(-?)0*(\\d+)\"", ",", "r\"e\\1\\2\"", ",...
Modified form of the 'g' format specifier.
[ "Modified", "form", "of", "the", "g", "format", "specifier", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/scientificspinbox.py#L21-L26
5,850
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): self._smallStepsPerLargeStep = smallStepsPerLargeStep self._smallStepFactor = np.power(self.largeStepFactor, 1.0 / smallStepsPerLargeStep)
[ "def", "smallStepsPerLargeStep", "(", "self", ",", "smallStepsPerLargeStep", ")", ":", "self", ".", "_smallStepsPerLargeStep", "=", "smallStepsPerLargeStep", "self", ".", "_smallStepFactor", "=", "np", ".", "power", "(", "self", ".", "largeStepFactor", ",", "1.0", ...
Sets the number of small steps that go in a large one.
[ "Sets", "the", "number", "of", "small", "steps", "that", "go", "in", "a", "large", "one", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/scientificspinbox.py#L137-L142
5,851
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): 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, '???')
[ "def", "tryImportModule", "(", "self", ",", "name", ")", ":", "self", ".", "_name", "=", "name", "try", ":", "import", "importlib", "self", ".", "_module", "=", "importlib", ".", "import_module", "(", "name", ")", "except", "ImportError", ":", "self", "....
Imports the module and sets version information If the module cannot be imported, the version is set to empty values.
[ "Imports", "the", "module", "and", "sets", "version", "information", "If", "the", "module", "cannot", "be", "imported", "the", "version", "is", "set", "to", "empty", "values", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/moduleinfo.py#L136-L152
5,852
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): for key, value in kwargs.items(): logger.debug("Setting PyQtGraph config option: {} = {}".format(key, value)) pg.setConfigOptions(**kwargs)
[ "def", "setPgConfigOptions", "(", "*", "*", "kwargs", ")", ":", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "logger", ".", "debug", "(", "\"Setting PyQtGraph config option: {} = {}\"", ".", "format", "(", "key", ",", "value", "...
Sets the PyQtGraph config options and emits a log message
[ "Sets", "the", "PyQtGraph", "config", "options", "and", "emits", "a", "log", "message" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/__init__.py#L35-L41
5,853
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): assert '/' not in nodeName, "nodeName may not contain slashes" self._nodeName = nodeName self._recursiveSetNodePath(self._constructNodePath())
[ "def", "nodeName", "(", "self", ",", "nodeName", ")", ":", "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
[ "The", "node", "name", ".", "Is", "used", "to", "construct", "the", "nodePath" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L119-L123
5,854
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): self._nodePath = nodePath for childItem in self.childItems: childItem._recursiveSetNodePath(nodePath + '/' + childItem.nodeName)
[ "def", "_recursiveSetNodePath", "(", "self", ",", "nodePath", ")", ":", "self", ".", "_nodePath", "=", "nodePath", "for", "childItem", "in", "self", ".", "childItems", ":", "childItem", ".", "_recursiveSetNodePath", "(", "nodePath", "+", "'/'", "+", "childItem...
Sets the nodePath property and updates it for all children.
[ "Sets", "the", "nodePath", "property", "and", "updates", "it", "for", "all", "children", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L137-L142
5,855
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): self._parentItem = value self._recursiveSetNodePath(self._constructNodePath())
[ "def", "parentItem", "(", "self", ",", "value", ")", ":", "self", ".", "_parentItem", "=", "value", "self", ".", "_recursiveSetNodePath", "(", "self", ".", "_constructNodePath", "(", ")", ")" ]
The parent item
[ "The", "parent", "item" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L150-L153
5,856
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): 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)
[ "def", "findByNodePath", "(", "self", ",", "nodePath", ")", ":", "def", "_auxGetByPath", "(", "parts", ",", "item", ")", ":", "\"Aux function that does the actual recursive search\"", "#logger.debug(\"_auxGetByPath item={}, parts={}\".format(item, parts))", "if", "len", "(", ...
Recursively searches for the child having the nodePath. Starts at self.
[ "Recursively", "searches", "for", "the", "child", "having", "the", "nodePath", ".", "Starts", "at", "self", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L190-L216
5,857
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): assert 0 <= position <= len(self.childItems), \ "position should be 0 < {} <= {}".format(position, len(self.childItems)) self.childItems[position].finalize() self.childItems.pop(position)
[ "def", "removeChild", "(", "self", ",", "position", ")", ":", "assert", "0", "<=", "position", "<=", "len", "(", "self", ".", "childItems", ")", ",", "\"position should be 0 < {} <= {}\"", ".", "format", "(", "position", ",", "len", "(", "self", ".", "chil...
Removes the child at the position 'position' Calls the child item finalize to close its resources before removing it.
[ "Removes", "the", "child", "at", "the", "position", "position", "Calls", "the", "child", "item", "finalize", "to", "close", "its", "resources", "before", "removing", "it", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L253-L261
5,858
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): if 0: print(indent * " " + str(self)) else: logger.log(level, indent * " " + str(self)) for childItems in self.childItems: childItems.logBranch(indent + 1, level=level)
[ "def", "logBranch", "(", "self", ",", "indent", "=", "0", ",", "level", "=", "logging", ".", "DEBUG", ")", ":", "if", "0", ":", "print", "(", "indent", "*", "\" \"", "+", "str", "(", "self", ")", ")", "else", ":", "logger", ".", "log", "(", ...
Logs the item and all descendants, one line per child
[ "Logs", "the", "item", "and", "all", "descendants", "one", "line", "per", "child" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L273-L281
5,859
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): 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
[ "def", "fetchChildren", "(", "self", ")", ":", "assert", "self", ".", "_canFetchChildren", ",", "\"canFetchChildren must be True\"", "try", ":", "childItems", "=", "self", ".", "_fetchAllChildren", "(", ")", "finally", ":", "self", ".", "_canFetchChildren", "=", ...
Fetches children. The actual work is done by _fetchAllChildren. Descendant classes should typically override that method instead of this one.
[ "Fetches", "children", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treeitems.py#L309-L321
5,860
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): cls = self.getClass(tryImport=tryImport) if not self.successfullyImported: raise ImportError("Class not successfully imported: {}".format(self.exception)) return cls(collector)
[ "def", "create", "(", "self", ",", "collector", ",", "tryImport", "=", "True", ")", ":", "cls", "=", "self", ".", "getClass", "(", "tryImport", "=", "tryImport", ")", "if", "not", "self", ".", "successfullyImported", ":", "raise", "ImportError", "(", "\"...
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.
[ "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", "coul...
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/registry.py#L55-L63
5,861
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=''): regInspector = InspectorRegItem(fullName, fullClassName, pythonPath=pythonPath) self.registerItem(regInspector)
[ "def", "registerInspector", "(", "self", ",", "fullName", ",", "fullClassName", ",", "pythonPath", "=", "''", ")", ":", "regInspector", "=", "InspectorRegItem", "(", "fullName", ",", "fullClassName", ",", "pythonPath", "=", "pythonPath", ")", "self", ".", "reg...
Registers an Inspector class.
[ "Registers", "an", "Inspector", "class", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/registry.py#L77-L81
5,862
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): 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
[ "def", "getDefaultItems", "(", "self", ")", ":", "plugins", "=", "[", "InspectorRegItem", "(", "DEFAULT_INSPECTOR", ",", "'argos.inspector.qtplugins.table.TableInspector'", ")", ",", "InspectorRegItem", "(", "'Qt/Text'", ",", "'argos.inspector.qtplugins.text.TextInspector'", ...
Returns a list with the default plugins in the inspector registry.
[ "Returns", "a", "list", "with", "the", "default", "plugins", "in", "the", "inspector", "registry", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/registry.py#L84-L100
5,863
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): 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
[ "def", "itemData", "(", "self", ",", "item", ",", "column", ",", "role", "=", "Qt", ".", "DisplayRole", ")", ":", "if", "role", "==", "Qt", ".", "DecorationRole", ":", "if", "column", "==", "self", ".", "COL_DECORATION", ":", "return", "item", ".", "...
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)
[ "Returns", "the", "data", "stored", "under", "the", "given", "role", "for", "the", "item", ".", "O", "The", "column", "parameter", "may", "be", "used", "to", "differentiate", "behavior", "per", "column", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L105-L131
5,864
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()): # 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()
[ "def", "index", "(", "self", ",", "row", ",", "column", ",", "parentIndex", "=", "QtCore", ".", "QModelIndex", "(", ")", ")", ":", "# logger.debug(\" called index({}, {}, {}) {}\"", "# .format(parentIndex.row(), parentIndex.column(), parentIndex.isVa...
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.
[ "Returns", "the", "index", "of", "the", "item", "in", "the", "model", "specified", "by", "the", "given", "row", "column", "and", "parent", "index", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L159-L193
5,865
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): 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
[ "def", "setData", "(", "self", ",", "index", ",", "value", ",", "role", "=", "Qt", ".", "EditRole", ")", ":", "if", "role", "!=", "Qt", ".", "CheckStateRole", "and", "role", "!=", "Qt", ".", "EditRole", ":", "return", "False", "treeItem", "=", "self"...
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()
[ "Sets", "the", "role", "data", "for", "the", "item", "at", "index", "to", "value", ".", "Returns", "true", "if", "successful", ";", "otherwise", "returns", "false", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L239-L271
5,866
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): if index.isValid(): item = index.internalPointer() if item: return item #return altItem if altItem is not None else self.invisibleRootItem # TODO: remove return altItem
[ "def", "getItem", "(", "self", ",", "index", ",", "altItem", "=", "None", ")", ":", "if", "index", ".", "isValid", "(", ")", ":", "item", "=", "index", ".", "internalPointer", "(", ")", "if", "item", ":", "return", "item", "#return altItem if altItem is ...
Returns the TreeItem for the given index. Returns the altItem if the index is invalid.
[ "Returns", "the", "TreeItem", "for", "the", "given", "index", ".", "Returns", "the", "altItem", "if", "the", "index", "is", "invalid", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L305-L314
5,867
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): 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
[ "def", "insertItem", "(", "self", ",", "childItem", ",", "position", "=", "None", ",", "parentIndex", "=", "None", ")", ":", "if", "parentIndex", "is", "None", ":", "parentIndex", "=", "QtCore", ".", "QModelIndex", "(", ")", "parentItem", "=", "self", "....
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.
[ "Inserts", "a", "childItem", "before", "row", "position", "under", "the", "parent", "index", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L317-L343
5,868
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): 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")
[ "def", "removeAllChildrenAtIndex", "(", "self", ",", "parentIndex", ")", ":", "if", "not", "parentIndex", ".", "isValid", "(", ")", ":", "logger", ".", "debug", "(", "\"No valid item selected for deletion (ignored).\"", ")", "return", "parentItem", "=", "self", "....
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
[ "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" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L346-L370
5,869
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): 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")
[ "def", "deleteItemAtIndex", "(", "self", ",", "itemIndex", ")", ":", "if", "not", "itemIndex", ".", "isValid", "(", ")", ":", "logger", ".", "debug", "(", "\"No valid item selected for deletion (ignored).\"", ")", "return", "item", "=", "self", ".", "getItem", ...
Removes the item at the itemIndex. The item's finalize method is called before removing so it can close its resources.
[ "Removes", "the", "item", "at", "the", "itemIndex", ".", "The", "item", "s", "finalize", "method", "is", "called", "before", "removing", "so", "it", "can", "close", "its", "resources", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L373-L393
5,870
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): oldItem = self.getItem(oldItemIndex) childNumber = oldItem.childNumber() parentIndex = oldItemIndex.parent() self.deleteItemAtIndex(oldItemIndex) insertedIndex = self.insertItem(newItem, position=childNumber, parentIndex=parentIndex) return insertedIndex
[ "def", "replaceItemAtIndex", "(", "self", ",", "newItem", ",", "oldItemIndex", ")", ":", "oldItem", "=", "self", ".", "getItem", "(", "oldItemIndex", ")", "childNumber", "=", "oldItem", ".", "childNumber", "(", ")", "parentIndex", "=", "oldItemIndex", ".", "...
Removes the item at the itemIndex and insert a new item instead.
[ "Removes", "the", "item", "at", "the", "itemIndex", "and", "insert", "a", "new", "item", "instead", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/treemodels.py#L396-L404
5,871
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): 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)
[ "def", "addHeaderContextMenu", "(", "self", ",", "checked", "=", "None", ",", "checkable", "=", "None", ",", "enabled", "=", "None", ")", ":", "checked", "=", "checked", "if", "checked", "is", "not", "None", "else", "{", "}", "checkable", "=", "checkable...
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)
[ "Adds", "the", "context", "menu", "from", "using", "header", "information" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/togglecolumn.py#L41-L79
5,872
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): show_column = lambda checked: self.setColumnHidden(column_idx, not checked) return show_column
[ "def", "__makeShowColumnFunction", "(", "self", ",", "column_idx", ")", ":", "show_column", "=", "lambda", "checked", ":", "self", ".", "setColumnHidden", "(", "column_idx", ",", "not", "checked", ")", "return", "show_column" ]
Creates a function that shows or hides a column.
[ "Creates", "a", "function", "that", "shows", "or", "hides", "a", "column", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/togglecolumn.py#L88-L91
5,873
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): if self.cls is None: return None elif hasattr(self.cls, 'descriptionHtml'): return self.cls.descriptionHtml() else: return ''
[ "def", "descriptionHtml", "(", "self", ")", ":", "if", "self", ".", "cls", "is", "None", ":", "return", "None", "elif", "hasattr", "(", "self", ".", "cls", ",", "'descriptionHtml'", ")", ":", "return", "self", ".", "cls", ".", "descriptionHtml", "(", "...
HTML help describing the class. For use in the detail editor.
[ "HTML", "help", "describing", "the", "class", ".", "For", "use", "in", "the", "detail", "editor", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registry.py#L152-L160
5,874
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): 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
[ "def", "tryImportClass", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Importing: {}\"", ".", "format", "(", "self", ".", "fullClassName", ")", ")", "self", ".", "_triedImport", "=", "True", "self", ".", "_exception", "=", "None", "self", ".", "_...
Tries to import the registered class. Will set the exception property if and error occurred.
[ "Tries", "to", "import", "the", "registered", "class", ".", "Will", "set", "the", "exception", "property", "if", "and", "error", "occurred", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registry.py#L187-L205
5,875
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): 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]
[ "def", "removeItem", "(", "self", ",", "regItem", ")", ":", "check_class", "(", "regItem", ",", "ClassRegItem", ")", "logger", ".", "info", "(", "\"Removing {!r} containing {}\"", ".", "format", "(", "regItem", ".", "identifier", ",", "regItem", ".", "fullClas...
Removes a ClassRegItem object to the registry. Will raise a KeyError if the regItem is not registered.
[ "Removes", "a", "ClassRegItem", "object", "to", "the", "registry", ".", "Will", "raise", "a", "KeyError", "if", "the", "regItem", "is", "not", "registered", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registry.py#L296-L305
5,876
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): 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)
[ "def", "loadOrInitSettings", "(", "self", ",", "groupName", "=", "None", ")", ":", "groupName", "=", "groupName", "if", "groupName", "else", "self", ".", "settingsGroupName", "settings", "=", "QtCore", ".", "QSettings", "(", ")", "#for key in sorted(settings.allKe...
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.
[ "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", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registry.py#L308-L326
5,877
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): 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()
[ "def", "loadSettings", "(", "self", ",", "groupName", "=", "None", ")", ":", "groupName", "=", "groupName", "if", "groupName", "else", "self", ".", "settingsGroupName", "settings", "=", "QtCore", ".", "QSettings", "(", ")", "logger", ".", "info", "(", "\"R...
Reads the registry items from the persistent settings store.
[ "Reads", "the", "registry", "items", "from", "the", "persistent", "settings", "store", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registry.py#L329-L345
5,878
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): 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()
[ "def", "saveSettings", "(", "self", ",", "groupName", "=", "None", ")", ":", "groupName", "=", "groupName", "if", "groupName", "else", "self", ".", "settingsGroupName", "settings", "=", "QtCore", ".", "QSettings", "(", ")", "logger", ".", "info", "(", "\"S...
Writes the registry items into the persistent settings store.
[ "Writes", "the", "registry", "items", "into", "the", "persistent", "settings", "store", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registry.py#L348-L363
5,879
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): groupName = groupName if groupName else self.settingsGroupName settings = QtCore.QSettings() logger.info("Deleting {} from: {}".format(groupName, settings.fileName())) removeSettingsGroup(groupName)
[ "def", "deleteSettings", "(", "self", ",", "groupName", "=", "None", ")", ":", "groupName", "=", "groupName", "if", "groupName", "else", "self", ".", "settingsGroupName", "settings", "=", "QtCore", ".", "QSettings", "(", ")", "logger", ".", "info", "(", "\...
Deletes registry items from the persistent store.
[ "Deletes", "registry", "items", "from", "the", "persistent", "store", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/qt/registry.py#L366-L372
5,880
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): 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)
[ "def", "repoItemChanged", "(", "self", ",", "rti", ")", ":", "check_class", "(", "rti", ",", "(", "BaseRti", ",", "int", ")", ",", "allow_none", "=", "True", ")", "assert", "type", "(", "rti", ")", "!=", "int", ",", "\"rti: {}\"", ".", "format", "(",...
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.
[ "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", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/repo/detailpanes.py#L109-L123
5,881
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): inspectorMenu.addAction(execInspectorDialogAction) inspectorMenu.addSeparator() for action in inspectorActionGroup.actions(): inspectorMenu.addAction(action) return inspectorMenu
[ "def", "addInspectorActionsToMenu", "(", "inspectorMenu", ",", "execInspectorDialogAction", ",", "inspectorActionGroup", ")", ":", "inspectorMenu", ".", "addAction", "(", "execInspectorDialogAction", ")", "inspectorMenu", ".", "addSeparator", "(", ")", "for", "action", ...
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.
[ "Adds", "menu", "items", "to", "the", "inpsectorMenu", "for", "the", "given", "set", "-", "inspector", "actions", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/selectionpane.py#L31-L45
5,882
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): library, name = inspectorRegItem.splitName() label = "{} ({})".format(name, library) if library else name #self.label.setText(label) self.menuButton.setText(label)
[ "def", "updateFromInspectorRegItem", "(", "self", ",", "inspectorRegItem", ")", ":", "library", ",", "name", "=", "inspectorRegItem", ".", "splitName", "(", ")", "label", "=", "\"{} ({})\"", ".", "format", "(", "name", ",", "library", ")", "if", "library", "...
Updates the label from the full name of the InspectorRegItem
[ "Updates", "the", "label", "from", "the", "full", "name", "of", "the", "InspectorRegItem" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/selectionpane.py#L74-L80
5,883
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): return StringCtiEditor(self, delegate, parent=parent)
[ "def", "createEditor", "(", "self", ",", "delegate", ",", "parent", ",", "option", ")", ":", "return", "StringCtiEditor", "(", "self", ",", "delegate", ",", "parent", "=", "parent", ")" ]
Creates a StringCtiEditor. For the parameters see the AbstractCti constructor documentation.
[ "Creates", "a", "StringCtiEditor", ".", "For", "the", "parameters", "see", "the", "AbstractCti", "constructor", "documentation", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/stringcti.py#L54-L58
5,884
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): self.vb.enableAutoRange(self.vb.YAxis, False) self.vb.setYRange(mn, mx, padding)
[ "def", "setHistogramRange", "(", "self", ",", "mn", ",", "mx", ",", "padding", "=", "0.1", ")", ":", "self", ".", "vb", ".", "enableAutoRange", "(", "self", ".", "vb", ".", "YAxis", ",", "False", ")", "self", ".", "vb", ".", "setYRange", "(", "mn",...
Set the Y range on the histogram plot. This disables auto-scaling.
[ "Set", "the", "Y", "range", "on", "the", "histogram", "plot", ".", "This", "disables", "auto", "-", "scaling", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pghistlutitem.py#L113-L116
5,885
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): 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)
[ "def", "setImageItem", "(", "self", ",", "img", ")", ":", "self", ".", "imageItem", "=", "weakref", ".", "ref", "(", "img", ")", "img", ".", "sigImageChanged", ".", "connect", "(", "self", ".", "imageChanged", ")", "img", ".", "setLookupTable", "(", "s...
Set an ImageItem to have its levels and LUT automatically controlled by this HistogramLUTItem.
[ "Set", "an", "ImageItem", "to", "have", "its", "levels", "and", "LUT", "automatically", "controlled", "by", "this", "HistogramLUTItem", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pghistlutitem.py#L141-L150
5,886
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): 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
[ "def", "getLookupTable", "(", "self", ",", "img", "=", "None", ",", "n", "=", "None", ",", "alpha", "=", "None", ")", ":", "if", "n", "is", "None", ":", "if", "img", ".", "dtype", "==", "np", ".", "uint8", ":", "n", "=", "256", "else", ":", "...
Return a lookup table from the color gradient defined by this HistogramLUTItem.
[ "Return", "a", "lookup", "table", "from", "the", "color", "gradient", "defined", "by", "this", "HistogramLUTItem", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/pghistlutitem.py#L168-L179
5,887
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): setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.yAxisRangeCti, axisNumber)
[ "def", "setAutoRangeOn", "(", "self", ",", "axisNumber", ")", ":", "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).
[ "Sets", "the", "auto", "-", "range", "of", "the", "axis", "on", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/lineplot1d.py#L106-L111
5,888
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): logger.debug("Finalizing: {}".format(self)) self.plotItem.scene().sigMouseMoved.disconnect(self.mouseMoved) self.plotItem.close() self.graphicsLayoutWidget.close()
[ "def", "finalize", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Finalizing: {}\"", ".", "format", "(", "self", ")", ")", "self", ".", "plotItem", ".", "scene", "(", ")", ".", "sigMouseMoved", ".", "disconnect", "(", "self", ".", "mouseMoved", ...
Is called before destruction. Can be used to clean-up resources
[ "Is", "called", "before", "destruction", ".", "Can", "be", "used", "to", "clean", "-", "up", "resources" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/lineplot1d.py#L153-L159
5,889
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): self.titleLabel.setText('') self.plotItem.clear() self.plotItem.setLabel('left', '') self.plotItem.setLabel('bottom', '')
[ "def", "_clearContents", "(", "self", ")", ":", "self", ".", "titleLabel", ".", "setText", "(", "''", ")", "self", ".", "plotItem", ".", "clear", "(", ")", "self", ".", "plotItem", ".", "setLabel", "(", "'left'", ",", "''", ")", "self", ".", "plotIte...
Clears the the inspector widget when no valid input is available.
[ "Clears", "the", "the", "inspector", "widget", "when", "no", "valid", "input", "is", "available", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/inspector/pgplugins/lineplot1d.py#L176-L182
5,890
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): # 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)
[ "def", "environment_var_to_bool", "(", "env_var", ")", ":", "# 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", ".", ...
Converts an environment variable to a boolean Returns False if the environment variable is False, 0 or a case-insenstive string "false" or "0".
[ "Converts", "an", "environment", "variable", "to", "a", "boolean" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L84-L106
5,891
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): 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
[ "def", "fill_values_to_nan", "(", "masked_array", ")", ":", "if", "masked_array", "is", "not", "None", "and", "masked_array", ".", "dtype", ".", "kind", "==", "'f'", ":", "check_class", "(", "masked_array", ",", "ma", ".", "masked_array", ")", "logger", ".",...
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.
[ "Replaces", "the", "fill_values", "of", "the", "masked", "array", "by", "NaNs" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L109-L121
5,892
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): 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
[ "def", "setting_str_to_bool", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "six", ".", "string_types", ")", ":", "s", "=", "s", ".", "lower", "(", ")", "if", "s", "==", "'true'", ":", "return", "True", "elif", "s", "==", "'false'", ":", ...
Converts 'true' to True and 'false' to False if s is a string
[ "Converts", "true", "to", "True", "and", "false", "to", "False", "if", "s", "is", "a", "string" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L127-L139
5,893
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='{}'): #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
[ "def", "to_string", "(", "var", ",", "masked", "=", "None", ",", "decode_bytes", "=", "'utf-8'", ",", "maskFormat", "=", "''", ",", "strFormat", "=", "'{}'", ",", "intFormat", "=", "'{}'", ",", "numFormat", "=", "DEFAULT_NUM_FORMAT", ",", "noneFormat", "="...
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
[ "Converts", "var", "to", "a", "python", "string", "or", "unicode", "string", "so", "Qt", "widgets", "can", "display", "them", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L151-L220
5,894
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): if not is_a_string(var, allow_none=allow_none): raise TypeError("var must be a string, however type(var) is {}" .format(type(var)))
[ "def", "check_is_a_string", "(", "var", ",", "allow_none", "=", "False", ")", ":", "if", "not", "is_a_string", "(", "var", ",", "allow_none", "=", "allow_none", ")", ":", "raise", "TypeError", "(", "\"var must be a string, however type(var) is {}\"", ".", "format"...
Calls is_a_string and raises a type error if the check fails.
[ "Calls", "is_a_string", "and", "raises", "a", "type", "error", "if", "the", "check", "fails", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L237-L242
5,895
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): return isinstance(var, six.text_type) or (var is None and allow_none)
[ "def", "is_text", "(", "var", ",", "allow_none", "=", "False", ")", ":", "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.
[ "Returns", "True", "if", "var", "is", "a", "unicode", "text" ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L245-L256
5,896
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): 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)))
[ "def", "check_is_a_sequence", "(", "var", ",", "allow_none", "=", "False", ")", ":", "if", "not", "is_a_sequence", "(", "var", ",", "allow_none", "=", "allow_none", ")", ":", "raise", "TypeError", "(", "\"var must be a list or tuple, however type(var) is {}\"", ".",...
Calls is_a_sequence and raises a type error if the check fails.
[ "Calls", "is_a_sequence", "and", "raises", "a", "type", "error", "if", "the", "check", "fails", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L308-L313
5,897
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): if not is_a_mapping(var, allow_none=allow_none): raise TypeError("var must be a dict, however type(var) is {}" .format(type(var)))
[ "def", "check_is_a_mapping", "(", "var", ",", "allow_none", "=", "False", ")", ":", "if", "not", "is_a_mapping", "(", "var", ",", "allow_none", "=", "allow_none", ")", ":", "raise", "TypeError", "(", "\"var must be a dict, however type(var) is {}\"", ".", "format"...
Calls is_a_mapping and raises a type error if the check fails.
[ "Calls", "is_a_mapping", "and", "raises", "a", "type", "error", "if", "the", "check", "fails", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L322-L327
5,898
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): return isinstance(var, np.ndarray) or (var is None and allow_none)
[ "def", "is_an_array", "(", "var", ",", "allow_none", "=", "False", ")", ":", "return", "isinstance", "(", "var", ",", "np", ".", "ndarray", ")", "or", "(", "var", "is", "None", "and", "allow_none", ")" ]
Returns True if var is a numpy array.
[ "Returns", "True", "if", "var", "is", "a", "numpy", "array", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L330-L333
5,899
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): 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)))
[ "def", "check_is_an_array", "(", "var", ",", "allow_none", "=", "False", ")", ":", "if", "not", "is_an_array", "(", "var", ",", "allow_none", "=", "allow_none", ")", ":", "raise", "TypeError", "(", "\"var must be a NumPy array, however type(var) is {}\"", ".", "fo...
Calls is_an_array and raises a type error if the check fails.
[ "Calls", "is_an_array", "and", "raises", "a", "type", "error", "if", "the", "check", "fails", "." ]
20d0a3cae26c36ea789a5d219c02ca7df21279dd
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/cls.py#L336-L341