_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q5800
ViewBoxDebugCti._refreshNodeFromTarget
train
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
{ "resource": "" }
q5801
AbstractRangeCti._forceRefreshMinMax
train
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
{ "resource": "" }
q5802
AbstractRangeCti._forceRefreshAutoRange
train
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
{ "resource": "" }
q5803
AbstractRangeCti.setAutoRangeOff
train
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
{ "resource": "" }
q5804
AbstractRangeCti.setAutoRangeOn
train
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
{ "resource": "" }
q5805
AbstractRangeCti.calculateRange
train
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
{ "resource": "" }
q5806
AbstractRangeCti._updateTargetFromNode
train
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
{ "resource": "" }
q5807
PgAxisRangeCti.setTargetRange
train
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
{ "resource": "" }
q5808
PgAxisLabelCti._updateTargetFromNode
train
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
{ "resource": "" }
q5809
PgGridCti._updateTargetFromNode
train
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
{ "resource": "" }
q5810
PgPlotDataItemCti.createPlotDataItem
train
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
{ "resource": "" }
q5811
RepoTreeModel.itemData
train
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
{ "resource": "" }
q5812
RepoTreeModel.canFetchMore
train
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
{ "resource": "" }
q5813
RepoTreeModel.fetchMore
train
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
{ "resource": "" }
q5814
RepoTreeModel.findFileRtiIndex
train
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
{ "resource": "" }
q5815
RepoTreeModel.reloadFileAtIndex
train
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
{ "resource": "" }
q5816
RepoTreeModel.loadFile
train
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
{ "resource": "" }
q5817
RepoTreeView.finalize
train
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
{ "resource": "" }
q5818
RepoTreeView.contextMenuEvent
train
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
{ "resource": "" }
q5819
RepoTreeView.createOpenAsMenu
train
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
{ "resource": "" }
q5820
RepoTreeView.openCurrentItem
train
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
{ "resource": "" }
q5821
RepoTreeView.closeCurrentItem
train
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
{ "resource": "" }
q5822
RepoTreeView.removeCurrentItem
train
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
{ "resource": "" }
q5823
RepoTreeView.reloadFileOfCurrentItem
train
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
{ "resource": "" }
q5824
RepoTreeView.currentRepoTreeItemChanged
train
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
{ "resource": "" }
q5825
initQApplication
train
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
{ "resource": "" }
q5826
removeSettingsGroup
train
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
{ "resource": "" }
q5827
containsSettingsGroup
train
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
{ "resource": "" }
q5828
printChildren
train
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
{ "resource": "" }
q5829
widgetSubCheckBoxRect
train
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
{ "resource": "" }
q5830
UpdateReason.checkValid
train
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
{ "resource": "" }
q5831
AbstractInspector.updateContents
train
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
{ "resource": "" }
q5832
AbstractInspector._showError
train
def _showError(self, msg="", title="Error"): """ Shows an error message. """ self.errorWidget.setError(msg=msg, title=title)
python
{ "resource": "" }
q5833
ChoiceCti._enforceDataType
train
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
{ "resource": "" }
q5834
ChoiceCti.insertValue
train
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
{ "resource": "" }
q5835
ChoiceCtiEditor.comboBoxRowsInserted
train
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
{ "resource": "" }
q5836
ChoiceCtiEditor.eventFilter
train
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
{ "resource": "" }
q5837
ConfigTreeModel.itemData
train
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
{ "resource": "" }
q5838
ConfigTreeModel.setItemData
train
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
{ "resource": "" }
q5839
ConfigTreeModel.setRefreshBlocked
train
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
{ "resource": "" }
q5840
BoolCti.data
train
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
{ "resource": "" }
q5841
BoolCti.insertChild
train
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
{ "resource": "" }
q5842
BoolCti.checkState
train
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
{ "resource": "" }
q5843
BoolGroupCti.checkState
train
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
{ "resource": "" }
q5844
BaseRti.open
train
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
{ "resource": "" }
q5845
BaseRti.close
train
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
{ "resource": "" }
q5846
BaseRti._checkFileExists
train
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
{ "resource": "" }
q5847
BaseRti.fetchChildren
train
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
{ "resource": "" }
q5848
BaseRti.decoration
train
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
{ "resource": "" }
q5849
format_float
train
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
{ "resource": "" }
q5850
ScientificDoubleSpinBox.smallStepsPerLargeStep
train
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
{ "resource": "" }
q5851
ImportedModuleInfo.tryImportModule
train
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
{ "resource": "" }
q5852
setPgConfigOptions
train
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
{ "resource": "" }
q5853
BaseTreeItem.nodeName
train
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
{ "resource": "" }
q5854
BaseTreeItem._recursiveSetNodePath
train
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
{ "resource": "" }
q5855
BaseTreeItem.parentItem
train
def parentItem(self, value): """ The parent item """ self._parentItem = value self._recursiveSetNodePath(self._constructNodePath())
python
{ "resource": "" }
q5856
BaseTreeItem.findByNodePath
train
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
{ "resource": "" }
q5857
BaseTreeItem.removeChild
train
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
{ "resource": "" }
q5858
BaseTreeItem.logBranch
train
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
{ "resource": "" }
q5859
AbstractLazyLoadTreeItem.fetchChildren
train
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
{ "resource": "" }
q5860
InspectorRegItem.create
train
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
{ "resource": "" }
q5861
InspectorRegistry.registerInspector
train
def registerInspector(self, fullName, fullClassName, pythonPath=''): """ Registers an Inspector class. """ regInspector = InspectorRegItem(fullName, fullClassName, pythonPath=pythonPath) self.registerItem(regInspector)
python
{ "resource": "" }
q5862
InspectorRegistry.getDefaultItems
train
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
{ "resource": "" }
q5863
BaseTreeModel.itemData
train
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
{ "resource": "" }
q5864
BaseTreeModel.index
train
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
{ "resource": "" }
q5865
BaseTreeModel.setData
train
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
{ "resource": "" }
q5866
BaseTreeModel.getItem
train
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
{ "resource": "" }
q5867
BaseTreeModel.insertItem
train
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
{ "resource": "" }
q5868
BaseTreeModel.removeAllChildrenAtIndex
train
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
{ "resource": "" }
q5869
BaseTreeModel.deleteItemAtIndex
train
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
{ "resource": "" }
q5870
BaseTreeModel.replaceItemAtIndex
train
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
{ "resource": "" }
q5871
ToggleColumnMixIn.addHeaderContextMenu
train
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
{ "resource": "" }
q5872
ToggleColumnMixIn.__makeShowColumnFunction
train
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
{ "resource": "" }
q5873
ClassRegItem.descriptionHtml
train
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
{ "resource": "" }
q5874
ClassRegItem.tryImportClass
train
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
{ "resource": "" }
q5875
ClassRegistry.removeItem
train
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
{ "resource": "" }
q5876
ClassRegistry.loadOrInitSettings
train
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
{ "resource": "" }
q5877
ClassRegistry.loadSettings
train
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
{ "resource": "" }
q5878
ClassRegistry.saveSettings
train
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
{ "resource": "" }
q5879
ClassRegistry.deleteSettings
train
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
{ "resource": "" }
q5880
DetailBasePane.repoItemChanged
train
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
{ "resource": "" }
q5881
addInspectorActionsToMenu
train
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
{ "resource": "" }
q5882
InspectorSelectionPane.updateFromInspectorRegItem
train
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
{ "resource": "" }
q5883
StringCti.createEditor
train
def createEditor(self, delegate, parent, option): """ Creates a StringCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return StringCtiEditor(self, delegate, parent=parent)
python
{ "resource": "" }
q5884
HistogramLUTItem.setHistogramRange
train
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
{ "resource": "" }
q5885
HistogramLUTItem.setImageItem
train
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
{ "resource": "" }
q5886
HistogramLUTItem.getLookupTable
train
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
{ "resource": "" }
q5887
PgLinePlot1dCti.setAutoRangeOn
train
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
{ "resource": "" }
q5888
PgLinePlot1d.finalize
train
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
{ "resource": "" }
q5889
PgLinePlot1d._clearContents
train
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
{ "resource": "" }
q5890
environment_var_to_bool
train
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
{ "resource": "" }
q5891
fill_values_to_nan
train
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
{ "resource": "" }
q5892
setting_str_to_bool
train
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
{ "resource": "" }
q5893
to_string
train
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
{ "resource": "" }
q5894
check_is_a_string
train
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
{ "resource": "" }
q5895
is_text
train
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
{ "resource": "" }
q5896
check_is_a_sequence
train
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
{ "resource": "" }
q5897
check_is_a_mapping
train
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
{ "resource": "" }
q5898
is_an_array
train
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
{ "resource": "" }
q5899
check_is_an_array
train
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
{ "resource": "" }