code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
for combobox in self._comboBoxes:
if self._comboBoxDimensionIndex(combobox) == dimNr:
return True
return False | def _dimensionSelectedInComboBox(self, dimNr) | Returns True if the dimension is selected in one of the combo boxes. | 5.104626 | 3.679329 | 1.387379 |
assert len(self._spinBoxes) == 0, "Spinbox list not empty. Call _deleteSpinBoxes first"
if not self.rtiIsSliceable:
return
logger.debug("_createSpinBoxes, array shape: {}".format(self._rti.arrayShape))
self._setColumnCountForContents()
tree = self.tree
... | def _createSpinBoxes(self, row) | Creates a spinBox for each dimension that is not selected in a combo box. | 4.447173 | 4.265311 | 1.042637 |
tree = self.tree
model = self.tree.model()
for col, spinBox in enumerate(self._spinBoxes, self.COL_FIRST_COMBO + self.maxCombos):
spinBox.valueChanged[int].disconnect(self._spinboxValueChanged)
tree.setIndexWidget(model.index(row, col), None)
self._spinB... | def _deleteSpinBoxes(self, row) | Removes all spinboxes | 6.037704 | 6.114686 | 0.98741 |
if comboBox is None:
comboBox = self.sender()
assert comboBox, "comboBox not defined and not the sender"
blocked = self.blockChildrenSignals(True)
# If one of the other combo boxes has the same value, set it to the fake dimension
curDimIdx = self._comboBoxD... | def _comboBoxActivated(self, index, comboBox=None) | Is called when a combo box value was changed by the user.
Updates the spin boxes and sets other combo boxes having the same index to
the fake dimension of length 1. | 6.849362 | 6.13301 | 1.116803 |
if spinBox is None:
spinBox = self.sender()
assert spinBox, "spinBox not defined and not the sender"
logger.debug("{} sigContentsChanged signal (spinBox)"
.format("Blocked" if self.signalsBlocked() else "Emitting"))
self.sigContentsChanged.emit... | def _spinboxValueChanged(self, index, spinBox=None) | Is called when a spin box value was changed.
Updates the spin boxes and sets other combo boxes having the same index to
the fake dimension of length 1. | 11.131674 | 12.047002 | 0.92402 |
#logger.debug("getSlicedArray() called")
if not self.rtiIsSliceable:
return None
# The dimensions that are selected in the combo boxes will be set to slice(None),
# the values from the spin boxes will be set as a single integer value
nDims = self.rti.nDims
... | def getSlicedArray(self, copy=True) | Slice the rti using a tuple of slices made from the values of the combo and spin boxes.
:param copy: If True (the default), a copy is made so that inspectors cannot
accidentally modify the underlying of the RTIs. You can set copy=False as a
potential optimization, but only i... | 5.239001 | 4.756894 | 1.101349 |
if not self.rtiIsSliceable:
return ''
# The dimensions that are selected in the combo boxes will be set to slice(None),
# the values from the spin boxes will be set as a single integer value
nDims = self.rti.nDims
sliceList = [':'] * nDims
for spinB... | def getSlicesString(self) | Returns a string representation of the slices that are used to get the sliced array.
For example returns '[:, 5]' if the combo box selects dimension 0 and the spin box 5. | 10.955744 | 8.899034 | 1.231116 |
logger.debug("Updating self._rtiInfo")
# Info about the dependent dimension
rti = self.rti
if rti is None:
info = {'slices': '',
'name': '',
'path': '',
'file-name': '',
'dir-name': '',
... | def _updateRtiInfo(self) | Updates the _rtiInfo property when a new RTI is set or the comboboxes value change. | 3.723839 | 3.558309 | 1.046519 |
if is_a_sequence(obj):
return SequenceRti(obj, *args, **kwargs)
elif is_a_mapping(obj):
return MappingRti(obj, *args, **kwargs)
elif is_an_array(obj):
return ArrayRti(obj, *args, **kwargs)
elif isinstance(obj, bytearray):
return ArrayRti(np.array(obj), *args, **kwarg... | def _createFromObject(obj, *args, **kwargs) | Creates an RTI given an object. Auto-detects which RTI class to return.
The *args and **kwargs parameters are passed to the RTI constructor.
It is therefor important that all memory RTIs accept the same parameters in the
constructor (with exception of the FieldRti which is not auto-detected). | 2.106174 | 2.070326 | 1.017315 |
fieldName = self.nodeName
fieldDtype = self._array.dtype.fields[fieldName][0]
return fieldDtype.shape | def _subArrayShape(self) | Returns the shape of the sub-array.
An empty tuple is returned for regular fields, which have no sub array. | 11.029213 | 10.201675 | 1.081118 |
if self._array is None:
return super(FieldRti, self).elementTypeName
else:
fieldName = self.nodeName
return str(self._array.dtype.fields[fieldName][0]) | def elementTypeName(self) | String representation of the element type. | 9.083935 | 8.62244 | 1.053522 |
mainArrayDims = ['Dim{}'.format(dimNr) for dimNr in range(self._array.ndim)]
nSubDims = len(self._subArrayShape)
subArrayDims = ['SubDim{}'.format(dimNr) for dimNr in range(nSubDims)]
return mainArrayDims + subArrayDims | def dimensionNames(self) | Returns a list with the dimension names of the underlying NCDF variable | 4.453795 | 4.407245 | 1.010562 |
value = getMissingDataValue(self._array)
fieldNames = self._array.dtype.names
# If the missing value attibute is a list with the same length as the number of fields,
# return the missing value for field that equals the self.nodeName.
if hasattr(value, '__len__') and le... | def missingDataValue(self) | Returns the value to indicate missing data. | 5.350122 | 5.272839 | 1.014657 |
if self._array is None:
return super(ArrayRti, self).elementTypeName
else:
dtype = self._array.dtype
return '<structured>' if dtype.names else str(dtype) | def elementTypeName(self) | String representation of the element type. | 8.19128 | 8.146762 | 1.005465 |
assert self.canFetchChildren(), "canFetchChildren must be True"
childItems = []
# Add fields in case of an array of structured type.
if self._isStructured:
for fieldName in self._array.dtype.names:
childItem = FieldRti(self._array, nodeName=fieldNam... | def _fetchAllChildren(self) | Fetches all fields that this variable contains.
Only variables with a structured data type can have fields. | 8.154385 | 7.006623 | 1.163811 |
arr = self._fun()
check_is_an_array(arr)
self._array = arr | def _openResources(self) | Evaluates the function to result an array | 22.62554 | 12.606034 | 1.794818 |
childItems = []
for nr, elem in enumerate(self._sequence):
childItem = _createFromObject(elem, "elem-{}".format(nr), self.fileName)
childItem._iconColor = self.iconColor
childItems.append(childItem)
return childItems | def _fetchAllChildren(self) | Adds a child item for each column | 8.16272 | 7.772384 | 1.050221 |
childItems = []
logger.debug("{!r} _fetchAllChildren {!r}".format(self, self.fileName))
if self.hasChildren():
for key, value in sorted(self._dictionary.items()):
# TODO: pass the attributes to the children? (probably not)
childItem = _create... | def _fetchAllChildren(self) | Adds a child item for each item | 6.201726 | 5.896808 | 1.051709 |
return ("enabled = {}, min = {}, max = {}, step = {}, specVal = {}"
.format(self.enabled, self.minValue, self.maxValue, self.stepSize, self.specialValueText)) | def debugInfo(self) | Returns the string with debugging information | 6.115381 | 5.80693 | 1.053118 |
return IntCtiEditor(self, delegate, parent=parent) | def createEditor(self, delegate, parent, option) | Creates a IntCtiEditor.
For the parameters see the AbstractCti constructor documentation. | 35.77285 | 5.414421 | 6.606958 |
self.spinBox.valueChanged.disconnect(self.commitChangedValue)
super(IntCtiEditor, self).finalize() | def finalize(self) | Called at clean up. Is used to disconnect signals. | 16.327261 | 12.641091 | 1.291602 |
logger.debug("Finalizing: {}".format(self))
# Disconnect signals
self.collector.sigContentsChanged.disconnect(self.collectorContentsChanged)
self._configTreeModel.sigItemChanged.disconnect(self.configContentsChanged)
self.sigInspectorChanged.disconnect(self.inspectorSel... | def finalize(self) | Is called before destruction (when closing).
Can be used to clean-up resources. | 9.479268 | 9.586329 | 0.988832 |
self._collector = Collector(self.windowNumber)
self.configWidget = ConfigWidget(self._configTreeModel)
self.repoWidget = RepoWidget(self.argosApplication.repo, self.collector)
# self._configTreeModel.insertItem(self.repoWidget.repoTreeView.config) # No configurable items yet
... | def __setupViews(self) | Creates the UI widgets. | 6.94876 | 6.775928 | 1.025507 |
actionGroup = QtWidgets.QActionGroup(parent)
actionGroup.setExclusive(True)
sortedItems = sorted(self.argosApplication.inspectorRegistry.items,
key=lambda item: item.identifier)
shortCutNr = 1
for item in sortedItems:
logger.debu... | def __createInspectorActionGroup(self, parent) | Creates an action group with 'set inspector' actions for all installed inspector. | 3.943451 | 3.705227 | 1.064294 |
#self.dockWidget(self.currentInspectorPane, "Current Inspector", Qt.LeftDockWidgetArea)
self.inspectorSelectionPane = InspectorSelectionPane(self.execInspectorDialogAction,
self.inspectorActionGroup)
self.sigInspectorChanged.... | def __setupDockWidgets(self) | Sets up the dock widgets. Must be called after the menu is setup. | 4.805629 | 4.715144 | 1.01919 |
for action in self.windowMenu.actions():
self.windowMenu.removeAction(action)
for action in actionGroup.actions():
self.windowMenu.addAction(action) | def repopulateWinowMenu(self, actionGroup) | Clear the window menu and fills it with the actions of the actionGroup | 2.208887 | 1.892334 | 1.167282 |
contextMenu = QtWidgets.QMenu()
addInspectorActionsToMenu(contextMenu, self.execInspectorDialogAction,
self.inspectorActionGroup)
contextMenu.exec_(self.mapToGlobal(pos)) | def showContextMenu(self, pos) | Shows the context menu at position pos. | 7.513358 | 7.090253 | 1.059674 |
assert widget.parent() is None, "Widget already has a parent"
dockWidget = QtWidgets.QDockWidget(title, parent=self)
dockWidget.setObjectName("dock_" + string_to_identifier(title))
dockWidget.setWidget(widget)
# Prevent parent context menu (with e.g. 'set inspector" op... | def dockWidget(self, widget, title, area) | Adds a widget as a docked widget.
Returns the added dockWidget | 4.538813 | 4.613119 | 0.983892 |
title = detailPane.classLabel() if title is None else title
area = Qt.LeftDockWidgetArea if area is None else area
dockWidget = self.dockWidget(detailPane, title, area)
# TODO: undockDetailPane to disconnect
dockWidget.visibilityChanged.connect(detailPane.dockVisibilityC... | def dockDetailPane(self, detailPane, title=None, area=None) | Creates a dockWidget and add the detailPane with a default title.
By default the detail widget is added to the Qt.LeftDockWidgetArea. | 3.194612 | 3.090431 | 1.033711 |
self.setWindowTitle("{} #{} | {}-{}".format(self.inspectorName, self.windowNumber,
PROJECT_NAME, self.argosApplication.profile))
#self.activateWindowAction.setText("{} window".format(self.inspectorName, self.windowNumber))
self.activat... | def updateWindowTitle(self) | Updates the window title frm the window number, inspector, etc
Also updates the Window Menu | 7.797974 | 6.768819 | 1.152043 |
dialog = OpenInspectorDialog(self.argosApplication.inspectorRegistry, parent=self)
dialog.setCurrentInspectorRegItem(self.inspectorRegItem)
dialog.exec_()
if dialog.result():
inspectorRegItem = dialog.getCurrentInspectorRegItem()
if inspectorRegItem is no... | def execInspectorDialog(self) | Opens the inspector dialog box to let the user change the current inspector. | 5.809156 | 5.538274 | 1.048911 |
for action in self.inspectorActionGroup.actions():
if action.data() == identifier:
return action
raise KeyError("No action found with ID: {!r}".format(identifier)) | def getInspectorActionById(self, identifier) | Sets the inspector and draw the contents
Triggers the corresponding action so that it is checked in the menus. | 4.358668 | 4.9575 | 0.879207 |
self.setInspectorById(identifier)
# Show dialog box if import was unsuccessful.
regItem = self.inspectorRegItem
if regItem and not regItem.successfullyImported:
msg = "Unable to import {} inspector.\n{}".format(regItem.identifier, regItem.exception)
QtWi... | def setAndDrawInspectorById(self, identifier) | Sets the inspector and draw the contents.
Does NOT trigger any actions, so the check marks in the menus are not updated. To
achieve this, the user must update the actions by hand (or call
getInspectorActionById(identifier).trigger() instead). | 6.204658 | 6.269413 | 0.989671 |
logger.info("Setting inspector: {}".format(identifier))
# Use the identifier to find a registered inspector and set self.inspectorRegItem.
# Then create an inspector object from it.
oldInspectorRegItem = self.inspectorRegItem
oldInspector = self.inspector
if n... | def setInspectorById(self, identifier) | Sets the central inspector widget given a inspector ID.
If identifier is None, the inspector will be unset. Otherwise it will lookup the
inspector class in the registry. It will raise a KeyError if the ID is not found there.
It will do an import of the inspector code if it's loaded... | 5.222035 | 4.926698 | 1.059946 |
if inspectorRegItem and inspector:
key = inspectorRegItem.identifier
logger.debug("_updateNonDefaultsForInspector: {} {}"
.format(key, type(inspector)))
self._inspectorsNonDefaults[key] = inspector.config.getNonDefaultsDict()
else:
... | def _updateNonDefaultsForInspector(self, inspectorRegItem, inspector) | Store the (non-default) config values for the current inspector in a local dictionary.
This dictionary is later used to store value for persistence.
This function must be called after the inspector was drawn because that may update
some derived config values (e.g. ranges) | 4.341362 | 4.011372 | 1.082264 |
pluginsDialog = PluginsDialog(parent=self,
inspectorRegistry=self.argosApplication.inspectorRegistry,
rtiRegistry=self.argosApplication.rtiRegistry)
pluginsDialog.exec_() | def execPluginsDialog(self) | Shows the plugins dialog with the registered plugins | 8.070632 | 7.980752 | 1.011262 |
logger.debug("configContentsChanged: {}".format(configTreeItem))
self.drawInspectorContents(reason=UpdateReason.CONFIG_CHANGED,
origin=configTreeItem) | def configContentsChanged(self, configTreeItem) | Slot is called when an item has been changed by setData of the ConfigTreeModel.
Will draw the window contents. | 12.231357 | 11.717623 | 1.043843 |
logger.debug("")
logger.debug("-------- Drawing inspector of window: {} --------".format(self.windowTitle()))
if self.inspector:
self.inspector.updateContents(reason=reason, initiator=origin)
else:
logger.debug("No inspector selected")
logger.debu... | def drawInspectorContents(self, reason, origin=None) | Draws all contents of this window's inspector.
The reason and origin parameters are passed on to the inspector's updateContents method.
:param reason: string describing the reason for the redraw.
Should preferably be one of the UpdateReason enumeration class, but new values may
... | 6.289961 | 6.368058 | 0.987736 |
if fileNames is None:
dialog = QtWidgets.QFileDialog(self, caption=caption)
if rtiRegItem is None:
nameFilter = 'All files (*);;' # Default show all files.
nameFilter += self.argosApplication.rtiRegistry.getFileDialogFilter()
else:
... | def openFiles(self, fileNames=None, rtiRegItem=None, caption=None, fileMode=None) | Lets the user select on or more files and opens it.
:param fileNames: If None an open-file dialog allows the user to select files,
otherwise the files are opened directly.
:param rtiRegItem: Open the files as this type of registered RTI. None=autodetect.
:param capti... | 3.239057 | 3.240747 | 0.999478 |
try:
lastItem, lastIndex = self.repoWidget.repoTreeView.expandPath(path)
self.repoWidget.repoTreeView.setCurrentIndex(lastIndex)
return lastItem, lastIndex
except Exception as ex:
logger.warn("Unable to select {!r} because: {}".format(path, ex))
... | def trySelectRtiByPath(self, path) | Selects a repository tree item given a path, expanding nodes if along the way if needed.
Returns (item, index) if the path was selected successfully, else a warning is logged
and (None, None) is returned. | 5.162362 | 4.287915 | 1.203933 |
settings = QtCore.QSettings()
logger.debug("Reading settings from: {}".format(settings.group()))
self.restoreGeometry(settings.value("geometry"))
self.restoreState(settings.value("state"))
self.repoWidget.repoTreeView.readViewSettings('repo_tree/header_state', settings)
... | def readViewSettings(self, settings=None): # TODO: rename to readProfile?
if settings is None | Reads the persistent program settings
:param settings: optional QSettings object which can have a group already opened.
:returns: True if the header state was restored, otherwise returns False | 5.454812 | 5.271951 | 1.034686 |
self._updateNonDefaultsForInspector(self.inspectorRegItem, self.inspector)
if settings is None:
settings = QtCore.QSettings()
logger.debug("Writing settings to: {}".format(settings.group()))
settings.beginGroup('cfg_inspectors')
try:
for key, no... | def saveProfile(self, settings=None) | Writes the view settings to the persistent store | 5.385024 | 5.349771 | 1.00659 |
# Save current window settings.
settings = QtCore.QSettings()
settings.beginGroup(self.argosApplication.windowGroupName(self.windowNumber))
try:
self.saveProfile(settings)
# Create new window with the freshly baked settings of the current window.
... | def cloneWindow(self) | Opens a new window with the same inspector as the current window. | 6.166539 | 5.908935 | 1.043596 |
logger.debug("Activate and raising window: {}".format(self.windowNumber))
self.activateWindow()
self.raise_() | def activateAndRaise(self) | Activates and raises the window. | 7.130419 | 6.346696 | 1.123485 |
if ev.type() == QtCore.QEvent.WindowActivate:
logger.debug("Window activated: {}".format(self.windowNumber))
self.activateWindowAction.setChecked(True)
return super(MainWindow, self).event(ev); | def event(self, ev) | Detects the WindowActivate event. Pass all event through to the super class. | 4.749875 | 4.186682 | 1.13452 |
logger.debug("closeEvent")
self.argosApplication.saveSettingsIfNeeded()
self.finalize()
self.argosApplication.removeMainWindow(self)
event.accept()
logger.debug("closeEvent accepted") | def closeEvent(self, event) | Called when closing this window. | 7.589273 | 6.893005 | 1.101011 |
aboutDialog = AboutDialog(parent=self)
aboutDialog.show()
aboutDialog.addDependencyInfo() | def about(self) | Shows the about message window. | 10.707199 | 11.176165 | 0.958039 |
profile = profile if profile else self.profile
profGroupName = '_debug_' if DEBUGGING else ''
profGroupName += string_to_identifier(profile)
return profGroupName | def profileGroupName(self, profile=None) | Returns the name of the QSetting group for the profile.
Converts to lower case and removes whitespace, interpunction, etc.
Prepends _debug_ if the debugging flag is set
:param profile: profile name. If None the current profile is used. | 9.792669 | 9.801048 | 0.999145 |
return "{}/window-{:02d}".format(self.profileGroupName(profile=profile), windowNumber) | def windowGroupName(self, windowNumber, profile=None) | Returns the name of the QSetting group for this window in the this profile.
:param windowNumber: int
:param profile: profile name. If None the current profile is used. | 7.462134 | 14.506739 | 0.514391 |
profGroupName = self.profileGroupName(profile)
logger.debug("Resetting profile settings: {}".format(profGroupName))
settings = QtCore.QSettings()
settings.remove(profGroupName) | def deleteProfile(self, profile) | Removes a profile from the persistent settings | 7.257217 | 6.509919 | 1.114794 |
settings = QtCore.QSettings()
for profGroupName in QtCore.QSettings().childGroups():
settings.remove(profGroupName) | def deleteAllProfiles(self) | Returns a list of all profiles | 7.958664 | 8.862465 | 0.898019 |
settings = QtCore.QSettings()
logger.info("Reading profile {!r} from: {}".format(profile, settings.fileName()))
self._profile = profile
profGroupName = self.profileGroupName(profile)
# Instantiate windows from groups
settings.beginGroup(profGroupName)
t... | def loadProfile(self, profile, inspectorFullName=None) | Reads the persistent program settings for the current profile.
If inspectorFullName is given, a window with this inspector will be created if it wasn't
already created in the profile. All windows with this inspector will be raised. | 3.317325 | 3.090991 | 1.073224 |
if not self.profile:
logger.warning("No profile defined (no settings saved)")
return
settings = QtCore.QSettings()
logger.debug("Writing settings to: {}".format(settings.fileName()))
profGroupName = self.profileGroupName()
settings.remove(profGr... | def saveProfile(self) | Writes the current profile settings to the persistent store | 4.694393 | 4.523751 | 1.037721 |
try:
self.saveProfile()
except Exception as ex:
# Continue, even if saving the settings fails.
logger.warn(ex)
if DEBUGGING:
raise
finally:
self._settingsSaved = True | def saveSettings(self) | Saves the persistent settings. Only saves the profile. | 8.054119 | 6.798635 | 1.184667 |
for fileName in fileNames:
self.repo.loadFile(fileName, rtiClass=rtiClass) | def loadFiles(self, fileNames, rtiClass=None) | Loads files into the repository as repo tree items of class rtiClass.
Auto-detects using the extensions when rtiClass is None | 3.698089 | 3.276922 | 1.128525 |
mainWindow = MainWindow(self)
self.mainWindows.append(mainWindow)
self.windowActionGroup.addAction(mainWindow.activateWindowAction)
self.repopulateAllWindowMenus()
if settings:
mainWindow.readViewSettings(settings)
if inspectorFullName:
... | def addNewMainWindow(self, settings=None, inspectorFullName=None) | Creates and shows a new MainWindow.
If inspectorFullName is set, it will set the identifier from that name.
If the inspector identifier is not found in the registry, a KeyError is raised. | 6.187287 | 6.061422 | 1.020765 |
logger.debug("removeMainWindow called")
self.windowActionGroup.removeAction(mainWindow.activateWindowAction)
self.repopulateAllWindowMenus()
self.mainWindows.remove(mainWindow) | def removeMainWindow(self, mainWindow) | Removes the mainWindow from the list of windows. Saves the settings | 7.266462 | 7.276584 | 0.998609 |
logger.debug("raiseAllWindows called")
for mainWindow in self.mainWindows:
logger.debug("Raising {}".format(mainWindow._instanceNr))
mainWindow.raise_() | def raiseAllWindows(self) | Raises all application windows. | 6.184633 | 6.072196 | 1.018517 |
logger.debug("ArgosApplication.quit called")
assert len(self.mainWindows) == 0, \
"Bug: still {} windows present at application quit!".format(len(self.mainWindows))
self.qApplication.quit() | def quit(self) | Quits the application (called when the last window is closed) | 10.584928 | 9.589869 | 1.103761 |
logger.info("Starting Argos event loop...")
exitCode = self.qApplication.exec_()
logger.info("Argos event loop finished with exit code: {}".format(exitCode))
return exitCode | def execute(self) | Executes all main windows by starting the Qt main application | 6.898284 | 5.68255 | 1.213942 |
with Image.open(self._fileName) as image:
self._array = np.asarray(image)
self._bands = image.getbands()
# Fill attributes. For now assume that the info item are not overridden by
# the Image items.
self._attributes = dict(image.info)
... | def _openResources(self) | Uses open the underlying file | 4.364055 | 4.231295 | 1.031376 |
bands = self._bands
if len(bands) != self._array.shape[-1]:
logger.warn("No bands added, bands != last_dim_lenght ({} !: {})"
.format(len(bands), self._array.shape[-1]))
return []
childItems = []
for bandNr, band in enumerate(band... | def _fetchAllChildren(self) | Adds the bands as separate fields so they can be inspected easily. | 7.534155 | 6.455735 | 1.167048 |
if self._array is None:
return []
if self._array.ndim == 2:
return ['Y', 'X']
elif self._array.ndim == 3:
return ['Y', 'X', 'Band']
else:
# Defensive programming: fall back on default names
msg = "Expected 3D image. Go... | def dimensionNames(self) | Returns ['Y', 'X', 'Band'].
The underlying array is expected to be 3-dimensional. If this is not the case we fall
back on the default dimension names ['Dim-0', 'Dim-1', ...] | 4.83281 | 3.873492 | 1.247662 |
return UntypedCtiEditor(self, delegate, parent=parent) | def createEditor(self, delegate, parent, option) | Creates an UntypedCtiEditor.
For the parameters see the AbstractCti constructor documentation.
Note: since the item is not editable this will never be called. | 38.361099 | 5.292436 | 7.248288 |
# The Qt source shows that fontMetrics().size calls fontMetrics().boundingRect with
# the TextLongestVariant included in the flags. TextLongestVariant is an internal flag
# which is used to force selecting the longest string in a multi-length string.
# See: http://stackoverflow.com/a/8638114/625350... | def labelTextWidth(label) | Returns the width of label text of the label in pixels.
IMPORTANT: does not work when the labels are styled using style sheets.
Unfortunately it is possible to retrieve the settings (e.g. padding) that were set by the
style sheet without parsing the style sheet as text. | 4.91867 | 4.965437 | 0.990581 |
if width is None:
width = labelsMaxTextWidth(labels)
for label in labels:
#label.setFixedWidth(width)
label.setMinimumWidth(width) | def harmonizeLabelsTextWidth(labels, width=None) | Sets the the maximum width of the labels
If width is None, the maximum width is calculated using labelsMaxTextWidth() | 3.552646 | 3.306687 | 1.074382 |
if '_class_'in dct:
full_class_name = dct['_class_'] # TODO: how to handle the full_class_name?
cls = import_symbol(full_class_name)
return cls.createFromJsonDict(dct)
else:
return dct | def jsonAsCti(dct) | Config tree item JSON decoding function. Returns a CTI given a dictionary of attributes.
The full class name of desired CTI class should be in dct['_class_'']. | 5.256507 | 4.813202 | 1.092102 |
self.enabled = enabled
for child in self.childItems:
child.enableBranch(enabled) | def enableBranch(self, enabled) | Sets the enabled member to True or False for a node and all it's children | 4.824782 | 3.992913 | 1.208336 |
self.data = self.defaultData
if resetChildren:
for child in self.childItems:
child.resetToDefault(resetChildren=True) | def resetToDefault(self, resetChildren=True) | Resets the data to the default data. By default the children will be reset as well | 3.225081 | 2.984117 | 1.080749 |
if self.getRefreshBlocked():
logger.debug("_refreshNodeFromTarget blocked")
return
if False and level == 0:
logger.debug("refreshFromTarget: {}".format(self.nodePath))
self._refreshNodeFromTarget()
for child in self.childItems:
c... | def refreshFromTarget(self, level=0) | Refreshes the configuration tree from the target it monitors (if present).
Recursively call _refreshNodeFromTarget for itself and all children. Subclasses should
typically override _refreshNodeFromTarget instead of this function.
During updateTarget's execution refreshFromTarget is b... | 5.24587 | 3.916648 | 1.339377 |
#if level == 0:
# logger.debug("updateTarget: {}".format(self.nodePath))
self._updateTargetFromNode()
for child in self.childItems:
child.updateTarget(level = level + 1) | def updateTarget(self, level=0) | Applies the configuration to the target it monitors (if present).
Recursively call _updateTargetFromNode for itself and all children. Subclasses should
typically override _updateTargetFromNode instead of this function.
:param level: the level of recursion. | 5.497243 | 4.34361 | 1.265593 |
dct = {}
isEditable = bool(int(self.valueColumnItemFlags) and Qt.ItemIsEditable)
if (self.data != self.defaultData and self.enabled and isEditable):
dct['data'] = self.data
return dct | def _nodeGetNonDefaultsDict(self) | Retrieves this nodes` values as a dictionary to be used for persistence.
A dictionary with the data value will be returned if the data is not equal to the
defaultData, the node is enabled and the node is editable. Otherwise and empty
dictionary is returned.
Non-recursive... | 10.750606 | 7.509267 | 1.431645 |
dct = self._nodeGetNonDefaultsDict()
childList = []
for childCti in self.childItems:
childDct = childCti.getNonDefaultsDict()
if childDct:
childList.append(childDct)
if childList:
dct['childItems'] = childList
if dct:... | def getNonDefaultsDict(self) | Recursively retrieves values as a dictionary to be used for persistence.
Does not save defaultData and other properties, only stores values if they differ from
the defaultData. If the CTI and none of its children differ from their default, a
completely empty dictionary is returned. T... | 3.668668 | 2.860311 | 1.282611 |
if 'nodeName' not in dct:
return
nodeName = dct['nodeName']
if nodeName != self.nodeName:
msg = "nodeName mismatch: expected {!r}, got {!r}".format(self.nodeName, nodeName)
if DEBUGGING:
raise ValueError(msg)
else:
... | def setValuesFromDict(self, dct) | Recursively sets values from a dictionary created by getNonDefaultsDict.
Does not raise exceptions (logs warnings instead) so that we can remove/rename node
names in future Argos versions (or remove them) without breaking the application.
Typically descendants should override _node... | 3.640667 | 3.329286 | 1.093528 |
for subEditor in self._subEditors:
self.removeSubEditor(subEditor)
self.cti.model.sigItemChanged.disconnect(self.modelItemChanged)
self.resetButton.clicked.disconnect(self.resetEditorValue)
self.cti = None # just to make sure it's not used again.
self.delega... | def finalize(self) | Called at clean up, when the editor is closed. Can be used to disconnect signals.
This is often called after the client (e.g. the inspector) is updated. If you want to
take action before the update, override prepareCommit instead.
Be sure to call the finalize of the super class if yo... | 7.14545 | 6.513077 | 1.097093 |
self.hBoxLayout.insertWidget(len(self._subEditors), subEditor)
self._subEditors.append(subEditor)
subEditor.installEventFilter(self)
subEditor.setFocusPolicy(Qt.StrongFocus)
if isFocusProxy:
self.setFocusProxy(subEditor)
return subEditor | def addSubEditor(self, subEditor, isFocusProxy=False) | Adds a sub editor to the layout (at the right but before the reset button)
Will add the necessary event filter to handle tabs and sets the strong focus so
that events will not propagate to the tree view.
If isFocusProxy is True the sub editor will be the focus proxy of the CTI. | 2.78993 | 2.931015 | 0.951865 |
if subEditor is self.focusProxy():
self.setFocusProxy(None)
subEditor.removeEventFilter(self)
self._subEditors.remove(subEditor)
self.hBoxLayout.removeWidget(subEditor) | def removeSubEditor(self, subEditor) | Removes the subEditor from the layout and removes the event filter. | 4.796749 | 3.908841 | 1.227154 |
if event.type() == QtCore.QEvent.KeyPress:
key = event.key()
if key in (Qt.Key_Tab, Qt.Key_Backtab):
self.commitAndClose()
return True
else:
return False
return super(AbstractCtiEditor, self).eventFilter(watche... | def eventFilter(self, watchedObject, event) | Calls commitAndClose when the tab and back-tab are pressed.
This is necessary because, normally the event filter of QStyledItemDelegate does this
for us. However, that event filter works on this object, not on the sub editor. | 3.111351 | 2.45138 | 1.269224 |
if cti is not self.cti:
logger.debug("Another config tree item has changed: {}. Closing editor for {}"
.format(cti, self.cti))
self.delegate.closeEditor.emit(self, QtWidgets.QAbstractItemDelegate.NoHint) # CLOSES SELF!
else:
logger.de... | def modelItemChanged(self, cti) | Called when the an Config Tree Item (CTI) in the model has changed.
If the CTI is a different one than the CTI that belongs to this editor, the editor
is closed. This can happen if the user has checked a checkbox. Qt does not close other
editors in the view in that case, so this is ... | 6.092426 | 4.762082 | 1.279362 |
if self.delegate:
self.delegate.commitData.emit(self)
self.delegate.closeEditor.emit(self, QtWidgets.QAbstractItemDelegate.NoHint) # CLOSES SELF!
else:
# QAbstractItemView.closeEditor is sometimes called directly, without the
# QAbstractItemDelega... | def commitAndClose(self) | Commits the data of the sub editor and instructs the delegate to close this ctiEditor.
The delegate will emit the closeEditor signal which is connected to the closeEditor
method of the ConfigTreeView class. This, in turn will, call the finalize method of
this object so that signals ... | 11.52108 | 10.07765 | 1.143231 |
# Block all signals to prevent duplicate inspector updates.
# No need to restore, the editors will be deleted after the reset.
for subEditor in self._subEditors:
subEditor.blockSignals(True)
self.cti.resetToDefault(resetChildren=True)
# This will commit the ... | def resetEditorValue(self, checked=False) | Resets the editor to the default value. Also resets the children. | 12.098302 | 11.011948 | 1.098652 |
opt = QtWidgets.QStyleOption()
opt.initFrom(self)
painter = QtGui.QPainter(self)
self.style().drawPrimitive(QtWidgets.QStyle.PE_Widget, opt, painter, self)
painter.end() | def paintEvent(self, event) | Reimplementation of paintEvent to allow for style sheets
See: http://qt-project.org/wiki/How_to_Change_the_Background_Color_of_QWidget | 1.968571 | 1.915964 | 1.027457 |
if msg is not None:
self.messageLabel.setText(msg)
if title is not None:
self.titleLabel.setText(title) | def setError(self, msg=None, title=None) | Shows and error message | 2.592168 | 2.580692 | 1.004447 |
for idx in range(header.length()):
header.resizeSection(idx, sectionSize) | def resizeAllSections(header, sectionSize) | Sets all sections (columns or rows) of a header to the same section size.
:param header: a QHeaderView
:param sectionSize: the new size of the header section in pixels | 4.924617 | 9.364707 | 0.52587 |
check_is_a_string(formatSpec)
check_is_a_string(altFormatSpec)
fmt = altFormatSpec if not formatSpec else formatSpec
if is_quoted(fmt):
fmt = fmt[1:-1] # remove quotes
else:
if fmt and ':' not in fmt and '!' not in fmt:
fmt = ':' + fmt
fmt = '{' + fmt + '}'
... | def makeReplacementField(formatSpec, altFormatSpec='', testValue=None) | Prepends a colon and wraps the formatSpec in curly braces to yield a replacement field.
The format specification is part of a replacement field, which can be used in new-style
string formatting. See:
https://docs.python.org/3/library/string.html#format-string-syntax
https://docs... | 3.580881 | 3.653631 | 0.980088 |
tableModel = self.tableInspector.model
# Disable row height and column with settings for large headers (too slow otherwise)
if tableModel.rowCount() >= RESET_HEADERS_AT_SIZE:
self.autoRowHeightCti.data = False
self.model.emitDataChanged(self.autoRowHeightCti)
... | def _refreshNodeFromTarget(self) | Refreshes the TableInspectorCti from the TableInspector target it monitors.
Disables auto-sizing of the header sizes for very large headers (> 10000 elements).
Otherwise the resizing may take to long and the program will hang. | 4.583111 | 3.6439 | 1.257749 |
self.beginResetModel()
try:
# The sliced array can be a masked array or a (regular) numpy array.
# The table works fine with masked arrays, no need to replace the masked values.
self._slicedArray = slicedArray
if slicedArray is None:
... | def updateState(self, slicedArray, rtiInfo, separateFields) | Sets the slicedArray and rtiInfo and other members. This will reset the model.
Will be called from the tableInspector._drawContents. | 3.626615 | 3.561066 | 1.018407 |
row = index.row()
col = index.column()
if (row < 0 or row >= self.rowCount() or col < 0 or col >= self.columnCount()):
return None
# The check above should have returned None if the sliced array is None
assert self._slicedArray is not None, "Sanity check fai... | def _cellValue(self, index) | Returns the data value of the cell at the index (without any string conversion) | 3.450026 | 3.367166 | 1.024608 |
row = index.row()
col = index.column()
if (row < 0 or row >= self.rowCount() or col < 0 or col >= self.columnCount()):
return None
# The check above should have returned None if the sliced array is None
assert self._slicedArray is not None, "Sanity check fai... | def _cellMask(self, index) | Returns the data mask of the cell at the index (without any string conversion) | 3.82276 | 3.703928 | 1.032083 |
try:
if role == Qt.DisplayRole:
return to_string(self._cellValue(index), masked=self._cellMask(index),
decode_bytes=self.encoding, maskFormat=self.maskFormat,
strFormat=self.strFormat, intFormat=self.intFormat... | def data(self, index, role = Qt.DisplayRole) | Returns the data at an index for a certain role | 4.319738 | 4.354799 | 0.991949 |
if role == Qt.DisplayRole:
if self._separateFieldOrientation == orientation:
nFields = len(self._fieldNames)
varNr = section // nFields
fieldNr = section % nFields
header = str(varNr) + ' : ' if self._numbersInHeader else ''
... | def headerData(self, section, orientation, role) | Returns the header for a section (row or column depending on orientation).
Reimplemented from QAbstractTableModel to make the headers start at 0. | 4.822702 | 4.652312 | 1.036625 |
if self._separateFieldOrientation == Qt.Vertical:
return self._nRows * len(self._fieldNames)
else:
return self._nRows | def rowCount(self, parent=None) | The number of rows of the sliced array.
The 'parent' parameter can be a QModelIndex. It is ignored since the number of
rows does not depend on the parent. | 8.48684 | 8.685419 | 0.977137 |
if self._separateFieldOrientation == Qt.Horizontal:
return self._nCols * len(self._fieldNames)
else:
return self._nCols | def columnCount(self, parent=None) | The number of columns of the sliced array.
The 'parent' parameter can be a QModelIndex. It is ignored since the number of
columns does not depend on the parent. | 9.095717 | 9.298319 | 0.978211 |
check_class(font, QtGui.QFont, allow_none=True)
self._font = font | def setFont(self, font) | Sets the font that will be returned when data() is called with the Qt.FontRole.
Can be a QFont or None if no font is set. | 7.888584 | 7.142106 | 1.104518 |
rect = viewBox.childrenBoundingRect() # taken from viewBox.autoRange()
if rect is not None:
if axisNumber == X_AXIS:
return rect.left(), rect.right()
elif axisNumber == Y_AXIS:
return rect.bottom(), rect.top()
else:
raise ValueError("axisNumber sh... | def viewBoxAxisRange(viewBox, axisNumber) | Calculates the range of an axis of a viewBox. | 5.458824 | 5.630847 | 0.96945 |
logger.debug("Discarding {}% from id: {}".format(percentage, id(inspector.slicedArray)))
return maskedNanPercentile(inspector.slicedArray, (percentage, 100-percentage) ) | def inspectorDataRange(inspector, percentage) | Calculates the range from the inspectors' sliced array. Discards percentage of the minimum
and percentage of the maximum values of the inspector.slicedArray
Meant to be used with functools.partial for filling the autorange methods combobox.
The first parameter is an inspector, it's not an array... | 18.37772 | 13.553397 | 1.355949 |
rangeFunctions = OrderedDict({} if intialItems is None else intialItems)
rangeFunctions['use all data'] = partial(inspectorDataRange, inspector, 0.0)
for percentage in [0.1, 0.2, 0.5, 1, 2, 5, 10, 20]:
label = "discard {}%".format(percentage)
rangeFunctions[label] = partial(inspectorDat... | def defaultAutoRangeMethods(inspector, intialItems=None) | Creates an ordered dict with default autorange methods for an inspector.
:param inspector: the range methods will work on (the sliced array) of this inspector.
:param intialItems: will be passed on to the OrderedDict constructor. | 3.931236 | 4.850704 | 0.810446 |
assert axisNumber in VALID_AXIS_NUMBERS, \
"Axis number should be one of {}, got {}".format(VALID_AXIS_NUMBERS, axisNumber)
logger.debug("setXYAxesAutoRangeOn, axisNumber: {}".format(axisNumber))
if axisNumber == X_AXIS or axisNumber == BOTH_AXES:
xAxisRangeCti.autoRangeCti.data = True... | def setXYAxesAutoRangeOn(commonCti, xAxisRangeCti, yAxisRangeCti, axisNumber) | Turns on the auto range of an X and Y axis simultaneously.
It sets the autoRangeCti.data of the xAxisRangeCti and yAxisRangeCti to True.
After that, it emits the sigItemChanged signal of the commonCti.
Can be used with functools.partial to make a slot that atomically resets the X and Y axis.
... | 2.660048 | 2.347416 | 1.133181 |
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():
... | def _refreshNodeFromTarget(self) | Updates the config settings | 4.928644 | 4.756112 | 1.036276 |
if self.methodCti:
return self.methodCti.configValue
else:
assert len(self._rangeFunctions) == 1, \
"Assumed only one _rangeFunctions. Got: {}".format(self._rangeFunctions)
return list(self._rangeFunctions.keys())[0] | def autoRangeMethod(self) | The currently selected auto range method.
If there is no method child CTI, there will be only one method (which will be returned). | 6.904232 | 5.249636 | 1.315183 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.