Instruction:
Write a Python 3 script to
call when the dock widget that this pane contains become visible.

Response:
def dockVisibilityChanged(self, visible):
        """ Slot to be called when the dock widget that this pane contains become (in)visible.
            Is used to (dis)connect the pane from its repo tree view and so prevent unnecessary
            and potentially costly updates when the pane is hidden.
        """
        logger.debug("dockVisibilityChanged of {!r}: visible={}".format(self, visible))

        if visible:
            self._repoTreeView.sigRepoItemChanged.connect(self.repoItemChanged)
            self._isConnected = True

            currentRepoItem, _currentIndex = self._repoTreeView.getCurrentItem()
            self.repoItemChanged(currentRepoItem)
        else:
            # At start-up the pane be be hidden but the signals are not connected.
            # A disconnect would fail in that case so we test for isConnected == True.
            if self.isConnected:
                self._repoTreeView.sigRepoItemChanged.disconnect(self.repoItemChanged)

            self._isConnected = False
            self.errorWidget.setError(msg="Contents disabled", title="Error")
            self.setCurrentIndex(self.ERROR_PAGE_IDX)


Instruction:
Write a Python 3 function for
updating the content when the current repo tree item changes.

Response:
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)


Instruction:
Write a Python 3 script for
adding the given set - inspector actions to the given inspector menu.

Response:
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


Instruction:
Can you create a Python 3 function that
updates the label and menuButton from the full name of the InspectorRegItem

Response:
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)


Instruction:
Implement a function in Python 3 to
create a StringCtiEditor object.

Response:
def createEditor(self, delegate, parent, option):
        """ Creates a StringCtiEditor.
            For the parameters see the AbstractCti constructor documentation.
        """
        return StringCtiEditor(self, delegate, parent=parent)


Instruction:
How would you implement a function in Python 3 that
sets the Y range on the histogram plot. This disables auto - scaling.

Response:
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)


Instruction:
Here you have a function in Python 3, explain what it does
def setImageItem(self, img):
        self.imageItem = weakref.ref(img)
        img.sigImageChanged.connect(self.imageChanged)
        img.setLookupTable(self.getLookupTable)  ## send function pointer, not the result
        #self.gradientChanged()
        self.regionChanged()
        self.imageChanged(autoLevel=True)

Response: Set an ImageItem to have its levels automatically controlledby this HistogramLUTItem.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def getLookupTable(self, img=None, n=None, alpha=None):
        if n is None:
            if img.dtype == np.uint8:
                n = 256
            else:
                n = 512
        if self.lut is None:
            self.lut = self.gradient.getLookupTable(n, alpha=alpha)
        return self.lut

Response: Return a lookup table from the color gradient defined by thisHistogramLUTItem.


Instruction:
Can you create a Python 3 function that
sets the auto - range of the axis on.

Response:
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)


Instruction:
Create a Python 3 function for
closing the resources used by this instance.

Response:
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()


Instruction:
Write a Python 3 script for
clearing the contents of the inspector widget.

Response:
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', '')


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _drawContents(self, reason=None, initiator=None):
        self.slicedArray = self.collector.getSlicedArray()

        if not self._hasValidData():
            self._clearContents()
            raise InvalidDataError("No data available or it does not contain real numbers")

        # -- Valid plot data from here on --

        # PyQtGraph doesn't handle masked arrays so we convert the masked values to Nans (missing
        # data values are replaced by NaNs). The PyQtGraph line plot omits the Nans, which is great.
        self.slicedArray.replaceMaskedValueWithNan()  # will convert data to float if int

        self.plotItem.clear()

        # Reset the axes ranges (via the config)
        if (reason == UpdateReason.RTI_CHANGED or
            reason == UpdateReason.COLLECTOR_COMBO_BOX):

            # self.config.yAxisRangeCti.setAutoRangeOn() doesn't work as refreshBlocked is True
            # TODO: can refreshBlocked maybe only block the signals to prevent loops?
            self.config.xAxisRangeCti.autoRangeCti.data = True
            self.config.yAxisRangeCti.autoRangeCti.data = True

        self.titleLabel.setText(self.configValue('title').format(**self.collector.rtiInfo))

        connected = np.isfinite(self.slicedArray.data)
        if is_an_array(self.slicedArray.mask):
            connected = np.logical_and(connected, ~self.slicedArray.mask)
        else:
            connected = np.zeros_like(self.slicedArray.data) if self.slicedArray.mask else connected

        plotDataItem = self.config.plotDataItemCti.createPlotDataItem()
        plotDataItem.setData(self.slicedArray.data, connect=connected)

        self.plotItem.addItem(plotDataItem)

        if self.config.probeCti.configValue:
            self.probeLabel.setVisible(True)
            self.plotItem.addItem(self.crossLineVerShadow, ignoreBounds=True)
            self.plotItem.addItem(self.crossLineVertical, ignoreBounds=True)
            self.plotItem.addItem(self.probeDataItem, ignoreBounds=True)
            self.probeDataItem.setSymbolBrush(QtGui.QBrush(self.config.plotDataItemCti.penColor))
            self.probeDataItem.setSymbolSize(10)
        else:
            self.probeLabel.setVisible(False)

        # Update the config tree from the (possibly) new state of the PgLinePlot1d inspector,
        # e.g. the axis range may have changed while drawing.
        self.config.updateTarget()

Response: Draw the contents of the collected repo tree item.


Instruction:
Write a Python 3 script to
update the probe text with the values under the cursor.

Response:
def mouseMoved(self, viewPos):
        """ Updates the probe text with the values under the cursor.
            Draws a vertical line and a symbol at the position of the probe.
        """
        try:
            check_class(viewPos, QtCore.QPointF)
            self.crossLineVerShadow.setVisible(False)
            self.crossLineVertical.setVisible(False)
            self.probeLabel.setText("")
            self.probeDataItem.clear()

            if (self._hasValidData() and self.config.probeCti.configValue and
                self.viewBox.sceneBoundingRect().contains(viewPos)):

                scenePos = self.viewBox.mapSceneToView(viewPos)
                index = int(scenePos.x())
                data = self.slicedArray.data

                if not 0 <= index < len(data):
                    txt = "no data at cursor"
                    self.probeLabel.setText(txt)
                else:
                    valueStr = to_string(data[index], masked=self.slicedArray.maskAt(index),
                                         maskFormat='<masked>')
                    self.probeLabel.setText("pos = {!r}, value = {}".format(index, valueStr))
                    if np.isfinite(data[index]):
                        self.crossLineVerShadow.setVisible(True)
                        self.crossLineVerShadow.setPos(index)
                        self.crossLineVertical.setVisible(True)
                        self.crossLineVertical.setPos(index)
                        if data[index] > 0 or self.config.yLogCti.configValue == False:
                            self.probeDataItem.setData((index,), (data[index],))

        except Exception as ex:
            # In contrast to _drawContents, this function is a slot and thus must not throw
            # exceptions. The exception is logged. Perhaps we should clear the cross plots, but
            # this could, in turn, raise exceptions.
            if DEBUGGING:
                raise
            else:
                logger.exception(ex)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def environment_var_to_bool(env_var):

    # Try to see if env_var can be converted to an int
    try:
        env_var = int(env_var)
    except ValueError:
        pass

    if isinstance(env_var, numbers.Number):
        return bool(env_var)
    elif is_a_string(env_var):
        env_var = env_var.lower().strip()
        if env_var in "false":
            return False
        else:
            return True
    else:
        return bool(env_var)

Response: Converts an environment variable to a boolean.


Instruction:
Given the following Python 3 function, write the documentation
def fill_values_to_nan(masked_array):
    if masked_array is not None and masked_array.dtype.kind == 'f':
        check_class(masked_array, ma.masked_array)
        logger.debug("Replacing fill_values by NaNs")
        masked_array[:] = ma.filled(masked_array, np.nan)
        masked_array.set_fill_value(np.nan)
    else:
        return masked_array

Response: Replaces the fill_values of the masked array by NaNs.


Instruction:
Given the following Python 3 function, write the documentation
def setting_str_to_bool(s):
    if isinstance(s, six.string_types):
        s = s.lower()
        if s == 'true':
            return True
        elif s == 'false':
            return False
        else:
            return ValueError('Invalid boolean representation: {!r}'.format(s))
    else:
        return s

Response: Converts a string to a boolean representation.


Instruction:
Can you create a Python 3 function that
converts a variable to a Python string or unicode string.

Response:
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


Instruction:
Make a summary of the following Python 3 code
def is_a_string(var, allow_none=False):
    return isinstance(var, six.string_types) or (var is None and allow_none)

Response: Returns True if var is a string.


Instruction:
Can you tell what is the following Python 3 function doing
def check_is_a_string(var, allow_none=False):
    if not is_a_string(var, allow_none=allow_none):
        raise TypeError("var must be a string, however type(var) is {}"
                        .format(type(var)))

Response: Checks if a variable is a string.


Instruction:
Here you have a function in Python 3, explain what it does
def is_text(var, allow_none=False):
    return isinstance(var, six.text_type) or (var is None and allow_none)

Response: Returns True if var is a unicode text object.


Instruction:
How would you explain what the following Python 3 function does
def is_binary(var, allow_none=False):
    return isinstance(var, six.binary_type) or (var is None and allow_none)

Response: Returns True if var is a binary object.


Instruction:
Can you create a Python 3 function that
returns True if var is a list or tuple.

Response:
def is_a_sequence(var, allow_none=False):
    """ Returns True if var is a list or a tuple (but not a string!)
    """
    return isinstance(var, (list, tuple)) or (var is None and allow_none)


Instruction:
Implement a Python 3 function for
checking if a variable is a sequence.

Response:
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)))


Instruction:
Can you tell what is the following Python 3 function doing
def check_is_a_mapping(var, allow_none=False):
    if not is_a_mapping(var, allow_none=allow_none):
        raise TypeError("var must be a dict, however type(var) is {}"
                        .format(type(var)))

Response: Checks if a dict is a mapping.


Instruction:
Can you generate the documentation for the following Python 3 function
def is_an_array(var, allow_none=False):
    return isinstance(var, np.ndarray) or (var is None and allow_none)

Response: Returns True if var is a numpy array.


Instruction:
How would you implement a function in Python 3 that
checks if the given variable is a NumPy array.

Response:
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)))


Instruction:
How would you code a function in Python 3 to
return True if the array contains real numbers.

Response:
def array_has_real_numbers(array):
    """ Uses the dtype kind of the numpy array to determine if it represents real numbers.

        That is, the array kind should be one of: i u f

        Possible dtype.kind values.
            b 	boolean
            i 	signed integer
            u 	unsigned integer
            f 	floating-point
            c 	complex floating-point
            m 	timedelta
            M 	datetime
            O 	object
            S 	(byte-)string
            U 	Unicode
            V 	void
    """
    kind = array.dtype.kind
    assert kind in 'biufcmMOSUV', "Unexpected array kind: {}".format(kind)
    return kind in 'iuf'


Instruction:
Can you generate the documentation for the following Python 3 function
def check_class(obj, target_class, allow_none = False):
    if not isinstance(obj, target_class):
        if not (allow_none and obj is None):
            raise TypeError("obj must be a of type {}, got: {}"
                            .format(target_class, type(obj)))

Response: Checks that the obj is a sub type of target_class. Raises a TypeError if this is not the case.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def import_symbol(full_symbol_name):
    parts = full_symbol_name.rsplit('.', 1)
    if len(parts) == 2:
        module_name, symbol_name = parts
        module_name = str(module_name) # convert from possible unicode
        symbol_name = str(symbol_name)
        #logger.debug("From module {} importing {!r}".format(module_name, symbol_name))
        module = __import__(module_name, fromlist=[symbol_name])
        cls = getattr(module, symbol_name)
        return cls
    elif len(parts) == 1:
        # No module part, only a class name. If you want to create a class
        # by using name without module, you should use globals()[symbol_name]
        # We cannot do this here because globals is of the module that defines
        # this function, not of the modules where this function is called.
        raise ImportError("full_symbol_name should contain a module")
    else:
        assert False, "Bug: parts should have 1 or elements: {}".format(parts)

Response: Imports a symbol from a dot separated name.


Instruction:
Write a Python 3 function for
creating a ChoiceCti with Qt PenStyles.

Response:
def createPenStyleCti(nodeName, defaultData=0, includeNone=False):
    """ Creates a ChoiceCti with Qt PenStyles.
        If includeEmtpy is True, the first option will be None.
    """
    displayValues=PEN_STYLE_DISPLAY_VALUES
    configValues=PEN_STYLE_CONFIG_VALUES
    if includeNone:
        displayValues = [''] + list(displayValues)
        configValues = [None] + list(configValues)
    return ChoiceCti(nodeName, defaultData,
                     displayValues=displayValues, configValues=configValues)


Instruction:
Implement a Python 3 function for
creating a FloatCti with defaults for configuring a QPen width.

Response:
def createPenWidthCti(nodeName, defaultData=1.0, zeroValueText=None):
    """ Creates a FloatCti with defaults for configuring a QPen width.

        If specialValueZero is set, this string will be displayed when 0.0 is selected.
        If specialValueZero is None, the minValue will be 0.1
    """
    # A pen line width of zero indicates a cosmetic pen. This means that the pen width is
    # always drawn one pixel wide, independent of the transformation set on the painter.
    # Note that line widths other than 1 may be slow when anti aliasing is on.
    return FloatCti(nodeName, defaultData=defaultData, specialValueText=zeroValueText,
                    minValue=0.1 if zeroValueText is None else 0.0,
                    maxValue=100, stepSize=0.1, decimals=1)


Instruction:
Here you have a function in Python 3, explain what it does
def fontFamilyIndex(qFont, families):
    try:
        return families.index(qFont.family())
    except ValueError:
        if False and DEBUGGING:
            raise
        else:
            logger.warn("{} not found in font families, using default.".format(qFont.family()))
            return families.index(qFont.defaultFamily())

Response: Returns the index of the qFont. family in the list.


Instruction:
Can you tell what is the following Python 3 function doing
def fontWeightIndex(qFont, weights):
    try:
        return weights.index(qFont.weight())
    except ValueError:
        if False and DEBUGGING:
            raise
        else:
            logger.warn("{} not found in font weights, using normal.".format(qFont.weight()))
            return weights.index(QtGui.QFont.Normal)

Response: Returns the index of the first element in the list of font weights.


Instruction:
Can you write a function in Python 3 where it
converts to str so that this CTI always stores that type.

Response:
def _enforceDataType(self, data):
        """ Converts to str so that this CTI always stores that type.
        """
        qColor = QtGui.QColor(data)    # TODO: store a RGB string?
        if not qColor.isValid():
            raise ValueError("Invalid color specification: {!r}".format(data))
        return qColor


Instruction:
How would you implement a function in Python 3 that
returns this nodes values as a dictionary to be used for persistence. getNonDefaultsDict

Response:
def _nodeGetNonDefaultsDict(self):
        """ Retrieves this nodes` values as a dictionary to be used for persistence.
            Non-recursive auxiliary function for getNonDefaultsDict
        """
        dct = {}
        if self.data != self.defaultData:
            dct['data'] = self.data.name()
        return dct


Instruction:
How would you code a function in Python 3 to
create a ColorCtiEditor object for the given delegate and parent.

Response:
def createEditor(self, delegate, parent, option):
        """ Creates a ColorCtiEditor.
            For the parameters see the AbstractCti constructor documentation.
        """
        return ColorCtiEditor(self, delegate, parent=parent)


Instruction:
Can you write a function in Python 3 where it
calls when the editor is closed. Disconnects signals.

Response:
def finalize(self):
        """ Is called when the editor is closed. Disconnect signals.
        """
        self.pickButton.clicked.disconnect(self.openColorDialog)
        super(ColorCtiEditor, self).finalize()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def openColorDialog(self):
        try:
            currentColor = self.getData()
        except InvalidInputError:
            currentColor = self.cti.data

        qColor = QtWidgets.QColorDialog.getColor(currentColor, self)

        if qColor.isValid():
            self.setData(qColor)
            self.commitAndClose()

Response: Opens a QColorDialog for the user


Instruction:
Write a Python 3 function that can
get data from the editor widget.

Response:
def getData(self):
        """ Gets data from the editor widget.
        """
        text = self.lineEditor.text()
        if not text.startswith('#'):
            text = '#' + text

        validator = self.lineEditor.validator()
        if validator is not None:
            state, text, _ = validator.validate(text, 0)
            if state != QtGui.QValidator.Acceptable:
                raise InvalidInputError("Invalid input: {!r}".format(text))

        return  QtGui.QColor(text)


Instruction:
Given the following Python 3 function, write the documentation
def data(self, data):
        self._data = self._enforceDataType(data) # Enforce self._data to be a QFont
        self.familyCti.data = fontFamilyIndex(self.data, list(self.familyCti.iterConfigValues))
        self.pointSizeCti.data = self.data.pointSize()
        self.weightCti.data = fontWeightIndex(self.data, list(self.weightCti.iterConfigValues))
        self.italicCti.data = self.data.italic()

Response: Sets the font data of this item.


Instruction:
Can you tell what is the following Python 3 function doing
def defaultData(self, defaultData):
        self._defaultData = self._enforceDataType(defaultData) # Enforce to be a QFont
        self.familyCti.defaultData = fontFamilyIndex(self.defaultData,
                                                     list(self.familyCti.iterConfigValues))
        self.pointSizeCti.defaultData = self.defaultData.pointSize()
        self.weightCti.defaultData = self.defaultData.weight()
        self.italicCti.defaultData = self.defaultData.italic()

Response: Sets the data of this item.


Instruction:
Can you implement a function in Python 3 that
updates the target widget s font based on the config values.

Response:
def _updateTargetFromNode(self):
        """ Applies the font config settings to the target widget's font.

            That is the targetWidget.setFont() is called with a font create from the config values.
        """
        font = self.data
        if self.familyCti.configValue:
            font.setFamily(self.familyCti.configValue)
        else:
            font.setFamily(QtGui.QFont().family()) # default family
        font.setPointSize(self.pointSizeCti.configValue)
        font.setWeight(self.weightCti.configValue)
        font.setItalic(self.italicCti.configValue)
        self._targetWidget.setFont(font)


Instruction:
Can you tell what is the following Python 3 function doing
def _nodeGetNonDefaultsDict(self):
        dct = {}
        if self.data != self.defaultData:
            dct['data'] = self.data.toString() # calls QFont.toString()
        return dct

Response: Returns this nodes values as a dictionary to be used for persistence. getNonDefaultsDict


Instruction:
Here you have a function in Python 3, explain what it does
def _nodeSetValuesFromDict(self, dct):
        if 'data' in dct:
            qFont = QtGui.QFont()
            success = qFont.fromString(dct['data'])
            if not success:
                msg = "Unable to create QFont from string {!r}".format(dct['data'])
                logger.warn(msg)
                if DEBUGGING:
                    raise ValueError(msg)
            self.data = qFont

Response: Sets values from a dictionary in the current node.


Instruction:
Make a summary of the following Python 3 code
def createEditor(self, delegate, parent, option):
        return FontCtiEditor(self, delegate, parent=parent)

Response: Creates a FontCtiEditor object.


Instruction:
How would you code a function in Python 3 to
disconnect signals and closes the editor.

Response:
def finalize(self):
        """ Is called when the editor is closed. Disconnect signals.
        """
        self.pickButton.clicked.disconnect(self.execFontDialog)
        super(FontCtiEditor, self).finalize()


Instruction:
Implement a function in Python 3 to
open a QColorDialog for the user and sets the font to the new font.

Response:
def execFontDialog(self):
        """ Opens a QColorDialog for the user
        """
        currentFont = self.getData()
        newFont, ok = QtGui.QFontDialog.getFont(currentFont, self)
        if ok:
            self.setData(newFont)
        else:
            self.setData(currentFont)
        self.commitAndClose()


Instruction:
Create a Python 3 function to
create a FontChoiceCtiEditor object.

Response:
def createEditor(self, delegate, parent, option):
        """ Creates a ChoiceCtiEditor.
            For the parameters see the AbstractCti constructor documentation.
        """
        return FontChoiceCtiEditor(self, delegate, parent=parent)


Instruction:
Can you tell what is the following Python 3 function doing
def finalize(self):
        self.comboBox.activated.disconnect(self.comboBoxActivated)
        super(FontChoiceCtiEditor, self).finalize()

Response: Is called when the editor is closed. Disconnect signals.


Instruction:
Can you write a function in Python 3 where it
creates a QPen made of the children s config values.

Response:
def configValue(self):
        """ Creates a QPen made of the children's config values.
        """
        if not self.data:
            return None
        else:
            pen = QtGui.QPen()
            pen.setCosmetic(True)
            pen.setColor(self.colorCti.configValue)
            style = self.styleCti.configValue
            if style is not None:
                pen.setStyle(style)
            pen.setWidthF(self.widthCti.configValue)
            return pen


Instruction:
Given the following Python 3 function, write the documentation
def createPen(self, altStyle=None, altWidth=None):
        pen = self.configValue
        if pen is not None:

            style = self.findByNodePath('style').configValue
            if style is None and altStyle is not None:
                pen.setStyle(altStyle)

            width = self.findByNodePath('width').configValue
            if width == 0.0 and altWidth is not None:
                #logger.debug("Setting altWidth = {!r}".format(altWidth))
                pen.setWidthF(altWidth)

        return pen

Response: Creates a pen from the config values with the style overridden by altStyle and the width overridden by altWidth.


Instruction:
Write a Python 3 function that can
replace values where the mask is True with the replacement value.

Response:
def replaceMaskedValue(data, mask, replacementValue, copyOnReplace=True):
    """ Replaces values where the mask is True with the replacement value.

        :copyOnReplace makeCopy: If True (the default) it makes a copy if data is replaced.
    """
    if mask is False:
        result = data
    elif mask is True:
        result = np.copy(data) if copyOnReplace else data
        result[:] = replacementValue
    else:
        #logger.debug("############ count_nonzero: {}".format(np.count_nonzero(mask)))
        if copyOnReplace and np.any(mask):
            #logger.debug("Making copy")
            result = np.copy(data)
        else:
            result = data

        result[mask] = replacementValue

    return result


Instruction:
Explain what the following Python 3 code does
def replaceMaskedValueWithFloat(data, mask, replacementValue, copyOnReplace=True):
    kind = data.dtype.kind
    if kind == 'i' or kind == 'u': # signed/unsigned int
        data = data.astype(np.float, casting='safe')

    if data.dtype.kind != 'f':
        return # only replace for floats
    else:
        return replaceMaskedValue(data, mask, replacementValue, copyOnReplace=copyOnReplace)

Response: Replaces values where the mask is True with the replacement value.


Instruction:
Given the following Python 3 function, write the documentation
def maskedNanPercentile(maskedArray, percentiles, *args, **kwargs):

    #https://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html#accessing-the-data
    awm = ArrayWithMask.createFromMaskedArray(maskedArray)

    maskIdx = awm.maskIndex()
    validData = awm.data[~maskIdx]

    if len(validData) >= 1:
        result = np.nanpercentile(validData, percentiles, *args, **kwargs)
    else:
        # If np.nanpercentile on an empty list only returns a single Nan. We correct this here.
        result = len(percentiles) * [np.nan]

    assert len(result) == len(percentiles), \
        "shape mismatch: {} != {}".format(len(result), len(percentiles))

    return result

Response: Calculates np. nanpercentile on the masked array


Instruction:
Create a Python 3 function to
mask an array where equal to a given value.

Response:
def maskedEqual(array, missingValue):
    """ Mask an array where equal to a given (missing)value.

        Unfortunately ma.masked_equal does not work with structured arrays. See:
        https://mail.scipy.org/pipermail/numpy-discussion/2011-July/057669.html

        If the data is a structured array the mask is applied for every field (i.e. forming a
        logical-and). Otherwise ma.masked_equal is called.
    """
    if array_is_structured(array):
        # Enforce the array to be masked
        if not isinstance(array, ma.MaskedArray):
            array = ma.MaskedArray(array)

        # Set the mask separately per field
        for nr, field in enumerate(array.dtype.names):
            if hasattr(missingValue, '__len__'):
                fieldMissingValue = missingValue[nr]
            else:
                fieldMissingValue = missingValue

            array[field] = ma.masked_equal(array[field], fieldMissingValue)

        check_class(array, ma.MaskedArray) # post-condition check
        return array
    else:
        # masked_equal works with missing is None
        result = ma.masked_equal(array, missingValue, copy=False)
        check_class(result, ma.MaskedArray) # post-condition check
        return result


Instruction:
Can you generate a brief explanation for the following Python 3 code
def checkIsConsistent(self):
        if is_an_array(self.mask) and self.mask.shape != self.data.shape:
            raise ConsistencyError("Shape mismatch mask={}, data={}"
                                   .format(self.mask.shape != self.data.shape))

Response: Raises a ConsistencyError if the mask has an incorrect shape.


Instruction:
Create a Python 3 function for
creating an ArrayWithMask object from a masked array.

Response:
def createFromMaskedArray(cls, masked_arr):
        """ Creates an ArrayWithMak

            :param masked_arr: a numpy MaskedArray or numpy array
            :return: ArrayWithMask
        """
        if isinstance(masked_arr, ArrayWithMask):
            return masked_arr

        check_class(masked_arr, (np.ndarray, ma.MaskedArray))

        # A MaskedConstant (i.e. masked) is a special case of MaskedArray. It does not seem to have
        # a fill_value so we use None to use the default.
        # https://docs.scipy.org/doc/numpy/reference/maskedarray.baseclass.html#numpy.ma.masked
        fill_value = getattr(masked_arr, 'fill_value', None)

        return cls(masked_arr.data, masked_arr.mask, fill_value)


Instruction:
How would you implement a function in Python 3 that
creates converts to a masked array

Response:
def asMaskedArray(self):
        """ Creates converts to a masked array
        """
        return ma.masked_array(data=self.data, mask=self.mask, fill_value=self.fill_value)


Instruction:
Can you write a function in Python 3 where it
returns the mask at the index.

Response:
def maskAt(self, index):
        """ Returns the mask at the index.

            It the mask is a boolean it is returned since this boolean representes the mask for
            all array elements.
        """
        if isinstance(self.mask, bool):
            return self.mask
        else:
            return self.mask[index]


Instruction:
Can you tell what is the following Python 3 function doing
def maskIndex(self):
        if isinstance(self.mask, bool):
            return np.full(self.data.shape, self.mask, dtype=np.bool)
        else:
            return self.mask

Response: Returns a boolean index with True if the value is masked.


Instruction:
How would you code a function in Python 3 to
transpose the array and mask separately

Response:
def transpose(self, *args, **kwargs):
        """ Transposes the array and mask separately

            :param awm: ArrayWithMask
            :return: copy/view with transposed
        """
        tdata = np.transpose(self.data, *args, **kwargs)
        tmask = np.transpose(self.mask, *args, **kwargs) if is_an_array(self.mask) else self.mask
        return ArrayWithMask(tdata, tmask, self.fill_value)


Instruction:
Here you have a function in Python 3, explain what it does
def replaceMaskedValue(self, replacementValue):
        if self.mask is False:
            pass
        elif self.mask is True:
            self.data[:] = replacementValue
        else:
            self.data[self.mask] = replacementValue

Response: Replaces the value in the data array with the replacement value.


Instruction:
Write a Python 3 script for
replacing values where the mask is True with the replacement value.

Response:
def replaceMaskedValueWithNan(self):
        """ Replaces values where the mask is True with the replacement value.

            Will change the data type to float if the data is an integer.
            If the data is not a float (or int) the function does nothing.
        """
        kind = self.data.dtype.kind
        if kind == 'i' or kind == 'u': # signed/unsigned int
            self.data = self.data.astype(np.float, casting='safe')

        if self.data.dtype.kind != 'f':
            return # only replace for floats

        if self.mask is False:
            pass
        elif self.mask is True:
            self.data[:] = np.NaN
        else:
            self.data[self.mask] = np.NaN


Instruction:
Implement a Python 3 function for
importing the regItem into the statusLabel

Response:
def importRegItem(self, regItem):
        """ Imports the regItem
            Writes this in the statusLabel while the import is in progress.
        """
        self.statusLabel.setText("Importing {}...".format(regItem.fullName))
        QtWidgets.qApp.processEvents()
        regItem.tryImportClass()
        self.tableView.model().emitDataChanged(regItem)
        self.statusLabel.setText("")
        QtWidgets.qApp.processEvents()


Instruction:
Write a Python 3 script to
try to import all underlying plugin classes

Response:
def tryImportAllPlugins(self):
        """ Tries to import all underlying plugin classes
        """
        for regItem in self.registeredItems:
            if not regItem.triedImport:
                self.importRegItem(regItem)

        logger.debug("Importing finished.")


Instruction:
Create a Python 3 function for
setting the current item to the regItem

Response:
def setCurrentRegItem(self, regItem):
        """ Sets the current item to the regItem
        """
        check_class(regItem, ClassRegItem, allow_none=True)
        self.tableView.setCurrentRegItem(regItem)


Instruction:
Write a Python 3 script for
updating the description text widget when the user clicks on a selector in the table.

Response:
def currentItemChanged(self, _currentIndex=None, _previousIndex=None):
        """ Updates the description text widget when the user clicks on a selector in the table.
            The _currentIndex and _previousIndex parameters are ignored.
        """
        self.editor.clear()
        self.editor.setTextColor(QCOLOR_REGULAR)

        regItem = self.getCurrentRegItem()

        if regItem is None:
            return

        if self._importOnSelect and regItem.successfullyImported is None:
            self.importRegItem(regItem)

        if regItem.successfullyImported is None:
            self.editor.setTextColor(QCOLOR_NOT_IMPORTED)
            self.editor.setPlainText('<plugin not yet imported>')
        elif regItem.successfullyImported is False:
            self.editor.setTextColor(QCOLOR_ERROR)
            self.editor.setPlainText(str(regItem.exception))
        elif regItem.descriptionHtml:
            self.editor.setHtml(regItem.descriptionHtml)
        else:
            self.editor.setPlainText(regItem.docString)


Instruction:
Can you create a Python 3 function that
refreshes the tables of all tables by importing the underlying classes

Response:
def tryImportAllPlugins(self):
        """ Refreshes the tables of all tables by importing the underlying classes
        """
        logger.debug("Importing plugins: {}".format(self))
        for tabNr in range(self.tabWidget.count()):
            tab = self.tabWidget.widget(tabNr)
            tab.tryImportAllPlugins()


Instruction:
Create a Python 3 function to
construct the dimension names given a h5py dataset.

Response:
def dimNamesFromDataset(h5Dataset):
    """ Constructs the dimension names given a h5py dataset.

        First looks in the dataset's dimension scales to see if it refers to another
        dataset. In that case the referred dataset's name is used. If not, the label of the
        dimension scale is used. Finally, if this is empty, the dimension is numbered.
    """
    dimNames = [] # TODO: cache?
    for dimNr, dimScales in enumerate(h5Dataset.dims):
        if len(dimScales) == 0:
            dimNames.append('Dim{}'.format(dimNr))
        elif len(dimScales) == 1:
            dimScaleLabel, dimScaleDataset = dimScales.items()[0]
            path = dimScaleDataset.name
            if path:
                dimNames.append(os.path.basename(path))
            elif dimScaleLabel: # This could potentially be long so it's our second choice
                dimNames.append(dimScaleLabel)
            else:
                dimNames.append('Dim{}'.format(dimNr))
        else:
            # TODO: multiple scales for this dimension. What to do?
            logger.warn("More than one dimension scale found: {!r}".format(dimScales))
            dimNames.append('Dim{}'.format(dimNr)) # For now, just number them

    return dimNames


Instruction:
Write a Python 3 function for
returning a string describing the element type of the dataset

Response:
def dataSetElementType(h5Dataset):
    """ Returns a string describing the element type of the dataset
    """
    dtype =  h5Dataset.dtype

    if dtype.names:
        return '<structured>'
    else:
        if dtype.metadata and 'vlen' in dtype.metadata:
            vlen_type = dtype.metadata['vlen']
            try:
                return "<vlen {}>".format(vlen_type.__name__)  # when vlen_type is a type
            except AttributeError: #
                return "<vlen {}>".format(vlen_type.name)      # when vlen_type is a dtype

    return str(dtype)


Instruction:
How would you explain what the following Python 3 function does
def dataSetUnit(h5Dataset):
    attributes = h5Dataset.attrs
    if not attributes:
        return '' # a premature optimization :-)

    for key in ('unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'):
        if key in attributes:
            # In Python3 the attributes are byte strings so we must decode them
            # This a bug in h5py, see https://github.com/h5py/h5py/issues/379
            return to_string(attributes[key])
    # Not found
    return ''

Response: Returns the unit of the dataset


Instruction:
Can you generate the documentation for the following Python 3 function
def dataSetMissingValue(h5Dataset):
    attributes = h5Dataset.attrs
    if not attributes:
        return None # a premature optimization :-)

    for key in ('missing_value', 'MissingValue', 'missingValue', 'FillValue', '_FillValue'):
        if key in attributes:
            missingDataValue = attributes[key]
            if is_an_array(missingDataValue) and len(missingDataValue) == 1:
                return missingDataValue[0] # In case of HDF-EOS and NetCDF files
            else:
                return missingDataValue
    return None

Response: Returns the missingData given a HDF - 5 dataset


Instruction:
Write a Python 3 function for
returning the shape of the sub - array.

Response:
def _subArrayShape(self):
        """ Returns the shape of the sub-array
            An empty tuple is returned for regular fields, which have no sub array.
        """
        if self._h5Dataset.dtype.fields is None:
            return tuple() # regular field
        else:
            fieldName = self.nodeName
            fieldDtype = self._h5Dataset.dtype.fields[fieldName][0]
            return fieldDtype.shape


Instruction:
Given the following Python 3 function, write the documentation
def elementTypeName(self):
        fieldName = self.nodeName
        return str(self._h5Dataset.dtype.fields[fieldName][0])

Response: String representation of the element type.


Instruction:
Can you write a function in Python 3 where it
returns a list with the dimension names of the underlying NCDF variable

Response:
def dimensionNames(self):
        """ Returns a list with the dimension names of the underlying NCDF variable
        """
        nSubDims = len(self._subArrayShape)
        subArrayDims = ['SubDim{}'.format(dimNr) for dimNr in range(nSubDims)]
        return dimNamesFromDataset(self._h5Dataset) + subArrayDims


Instruction:
Given the following Python 3 function, write the documentation
def unit(self):
        unit = dataSetUnit(self._h5Dataset)
        fieldNames = self._h5Dataset.dtype.names

        # If the missing value attribute 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(unit, '__len__') and len(unit) == len(fieldNames):
            idx = fieldNames.index(self.nodeName)
            return unit[idx]
        else:
            return unit

Response: Returns the unit of the RTI by calling dataSetUnit on the underlying dataset


Instruction:
Can you generate the documentation for the following Python 3 function
def missingDataValue(self):
        value = dataSetMissingValue(self._h5Dataset)
        fieldNames = self._h5Dataset.dtype.names

        # If the missing value attribute 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 len(value) == len(fieldNames):
            idx = fieldNames.index(self.nodeName)
            return value[idx]
        else:
            return value

Response: Returns the value to indicate missing data. None is returned.


Instruction:
Write a Python 3 script to
show an Array icon for regular datasets but a dimension icon for dimension scales

Response:
def iconGlyph(self):
        """ Shows an Array icon for regular datasets but a dimension icon for dimension scales
        """
        if self._h5Dataset.attrs.get('CLASS', None) == b'DIMENSION_SCALE':
            return RtiIconFactory.DIMENSION
        else:
            return RtiIconFactory.ARRAY


Instruction:
Write a Python 3 script for
fetching all the children of this variable.

Response:
def _fetchAllChildren(self):
        """ Fetches all fields that this variable contains.
            Only variables with a structured data type can have fields.
        """
        assert self.canFetchChildren(), "canFetchChildren must be True"

        childItems = []

        # Add fields
        if self._isStructured:
            for fieldName in self._h5Dataset.dtype.names:
                childItems.append(H5pyFieldRti(self._h5Dataset, nodeName=fieldName,
                                               fileName=self.fileName))

        return childItems


Instruction:
Can you tell what is the following Python 3 function doing
def _fetchAllChildren(self):
        assert self._h5Group is not None, "dataset undefined (file not opened?)"
        assert self.canFetchChildren(), "canFetchChildren must be True"

        childItems = []

        for childName, h5Child in self._h5Group.items():
            if isinstance(h5Child, h5py.Group):
                childItems.append(H5pyGroupRti(h5Child, nodeName=childName,
                                               fileName=self.fileName))
            elif isinstance(h5Child, h5py.Dataset):
                if len(h5Child.shape) == 0:
                    childItems.append(H5pyScalarRti(h5Child, nodeName=childName,
                                                    fileName=self.fileName))
                else:
                    childItems.append(H5pyDatasetRti(h5Child, nodeName=childName,
                                                     fileName=self.fileName))

            elif isinstance(h5Child, h5py.Datatype):
                #logger.debug("Ignored DataType item: {}".format(childName))
                pass
            else:
                logger.warn("Ignored {}. It has an unexpected HDF-5 type: {}"
                            .format(childName, type(h5Child)))

        return childItems

Response: Fetches all sub - groups and variables that this group contains.


Instruction:
Explain what the following Python 3 code does
def _openResources(self):
        logger.info("Opening: {}".format(self._fileName))
        self._h5Group = h5py.File(self._fileName, 'r')

Response: Opens the root dataset.


Instruction:
Here you have a function in Python 3, explain what it does
def _closeResources(self):
        logger.info("Closing: {}".format(self._fileName))
        self._h5Group.close()
        self._h5Group = None

Response: Closes the root Dataset.


Instruction:
Create a Python 3 function for
calculating the range from the sliced array of the specified percentage and cross - hairs.

Response:
def calcPgImagePlot2dDataRange(pgImagePlot2d, percentage, crossPlot):
    """ Calculates the range from the inspectors' sliced array. Discards percentage of the minimum
        and percentage of the maximum values of the inspector.slicedArray

        :param pgImagePlot2d: the range methods will work on (the sliced array) of this inspector.
        :param percentage: percentage that will be discarded.
        :param crossPlot: if None, the range will be calculated from the entire sliced array,
            if "horizontal" or "vertical" the range will be calculated from the data under the
            horizontal or vertical cross hairs.
            If the cursor is outside the image, there is no valid data under the cross-hair and
            the range will be determined from the sliced array as a fall back.
    """
    check_class(pgImagePlot2d.slicedArray, ArrayWithMask) # sanity check

    if crossPlot is None:
        array = pgImagePlot2d.slicedArray  # the whole image

    elif crossPlot == 'horizontal':
        if pgImagePlot2d.crossPlotRow is not None:
            array = pgImagePlot2d.slicedArray.asMaskedArray()[pgImagePlot2d.crossPlotRow, :]
        else:
            array = pgImagePlot2d.slicedArray # fall back on complete sliced array

    elif crossPlot == 'vertical':
        if pgImagePlot2d.crossPlotCol is not None:
            array = pgImagePlot2d.slicedArray.asMaskedArray()[:, pgImagePlot2d.crossPlotCol]
        else:
            array = pgImagePlot2d.slicedArray # fall back on complete sliced array
    else:
        raise ValueError("crossPlot must be: None, 'horizontal' or 'vertical', got: {}"
                         .format(crossPlot))

    return maskedNanPercentile(array, (percentage, 100-percentage) )


Instruction:
Can you generate the documentation for the following Python 3 function
def crossPlotAutoRangeMethods(pgImagePlot2d, crossPlot, intialItems=None):
    rangeFunctions = OrderedDict({} if intialItems is None else intialItems)

    # If crossPlot is "horizontal" or "vertical" make functions that determine the range from the
    # data at the cross hair.
    if crossPlot:
        rangeFunctions['cross all data'] = partial(calcPgImagePlot2dDataRange, pgImagePlot2d,
                                                   0.0, crossPlot)
        for percentage in [0.1, 0.2, 0.5, 1, 2, 5, 10, 20]:
            label = "cross discard {}%".format(percentage)
            rangeFunctions[label] = partial(calcPgImagePlot2dDataRange, pgImagePlot2d,
                                            percentage, crossPlot)

    # Always add functions that determine the data from the complete sliced array.
    for percentage in [0.1, 0.2, 0.5, 1, 2, 5, 10, 20]:
        rangeFunctions['image all data'] = partial(calcPgImagePlot2dDataRange, pgImagePlot2d,
                                                   0.0, None)

        label = "image discard {}%".format(percentage)
        rangeFunctions[label] = partial(calcPgImagePlot2dDataRange, pgImagePlot2d,
                                        percentage, None)
    return rangeFunctions

Response: Returns an ordered dict with autorange methods for an object.


Instruction:
Can you generate the documentation for the following Python 3 function
def _closeResources(self):
        verCrossViewBox = self.pgImagePlot2d.verCrossPlotItem.getViewBox()
        verCrossViewBox.sigRangeChangedManually.disconnect(self.yAxisRangeCti.setAutoRangeOff)
        horCrossViewBox = self.pgImagePlot2d.horCrossPlotItem.getViewBox()
        horCrossViewBox.sigRangeChangedManually.disconnect(self.xAxisRangeCti.setAutoRangeOff)

        self.pgImagePlot2d.verCrossPlotItem.sigAxisReset.disconnect(self.setVerCrossPlotAutoRangeOn)
        self.pgImagePlot2d.horCrossPlotItem.sigAxisReset.disconnect(self.setHorCrossPlotAutoRangeOn)
        self.pgImagePlot2d.imagePlotItem.sigAxisReset.disconnect(self.setImagePlotAutoRangeOn)

Response:
Disconnects signals.
            Is called by self.finalize when the cti is deleted.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def setImagePlotAutoRangeOn(self, axisNumber):
        setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.yAxisRangeCti, axisNumber)

Response: Sets the image plot s auto - range on for the axis with number axisNumber.


Instruction:
Can you create a Python 3 function that
sets the horizontal cross - hair plot s auto - range on for the axis with number axisNumber.

Response:
def setHorCrossPlotAutoRangeOn(self, axisNumber):
        """ Sets the horizontal cross-hair plot's auto-range on for the axis with number axisNumber.

            :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).
        """
        setXYAxesAutoRangeOn(self, self.xAxisRangeCti, self.horCrossPlotRangeCti, axisNumber)


Instruction:
Write a Python 3 function for
setting the vertical cross - hair plot s auto - range on for the axis with number axisNumber.

Response:
def setVerCrossPlotAutoRangeOn(self, axisNumber):
        """ Sets the vertical cross-hair plot's auto-range on for the axis with number axisNumber.

            :param axisNumber: 0 (X-axis), 1 (Y-axis), 2, (Both X and Y axes).
        """
        setXYAxesAutoRangeOn(self, self.verCrossPlotRangeCti, self.yAxisRangeCti, axisNumber)


Instruction:
How would you code a function in Python 3 to
clear the contents when no valid data is available for the current locale.

Response:
def _clearContents(self):
        """ Clears the contents when no valid data is available
        """
        logger.debug("Clearing inspector contents")
        self.titleLabel.setText('')

        # Don't clear the imagePlotItem, the imageItem is only added in the constructor.
        self.imageItem.clear()
        self.imagePlotItem.setLabel('left', '')
        self.imagePlotItem.setLabel('bottom', '')

        # Set the histogram range and levels to finite values to prevent futher errors if this
        # function was called after an exception in self.drawContents
        self.histLutItem.setHistogramRange(0, 100)
        self.histLutItem.setLevels(0, 100)

        self.crossPlotRow, self.crossPlotCol = None, None

        self.probeLabel.setText('')
        self.crossLineHorizontal.setVisible(False)
        self.crossLineVertical.setVisible(False)
        self.crossLineHorShadow.setVisible(False)
        self.crossLineVerShadow.setVisible(False)

        self.horCrossPlotItem.clear()
        self.verCrossPlotItem.clear()


Instruction:
Make a summary of the following Python 3 code
def _drawContents(self, reason=None, initiator=None):
        self.crossPlotRow = None # reset because the sliced array shape may change
        self.crossPlotCol = None # idem dito

        gridLayout = self.graphicsLayoutWidget.ci.layout # A QGraphicsGridLayout

        if self.config.horCrossPlotCti.configValue:
            gridLayout.setRowStretchFactor(ROW_HOR_LINE, 1)
            if not self.horPlotAdded:
                self.graphicsLayoutWidget.addItem(self.horCrossPlotItem, ROW_HOR_LINE, COL_HOR_LINE)
                self.horPlotAdded = True
                gridLayout.activate()
        else:
            gridLayout.setRowStretchFactor(ROW_HOR_LINE, 0)
            if self.horPlotAdded:
                self.graphicsLayoutWidget.removeItem(self.horCrossPlotItem)
                self.horPlotAdded = False
                gridLayout.activate()

        if self.config.verCrossPlotCti.configValue:
            gridLayout.setColumnStretchFactor(COL_VER_LINE, 1)
            if not self.verPlotAdded:
                self.graphicsLayoutWidget.addItem(self.verCrossPlotItem, ROW_VER_LINE, COL_VER_LINE)
                self.verPlotAdded = True
                gridLayout.activate()
        else:
            gridLayout.setColumnStretchFactor(COL_VER_LINE, 0)
            if self.verPlotAdded:
                self.graphicsLayoutWidget.removeItem(self.verCrossPlotItem)
                self.verPlotAdded = False
                gridLayout.activate()

        self.slicedArray = self.collector.getSlicedArray()

        if not self._hasValidData():
            self._clearContents()
            raise InvalidDataError("No data available or it does not contain real numbers")

        # -- Valid plot data from here on --

        # PyQtGraph doesn't handle masked array so we convert the masked values to Nans. Missing
        # data values are replaced by NaNs. The PyQtGraph image plot shows this as the color at the
        # lowest end of the color scale. Unfortunately we cannot choose a missing-value color, but
        # at least the Nans do not influence for the histogram and color range.
        # We don't update self.slicedArray here because the data probe should still be able to
        # print the actual value.
        imageArray = replaceMaskedValueWithFloat(self.slicedArray.data, self.slicedArray.mask,
                                                 np.nan, copyOnReplace=True)

        # Replace infinite value with Nans because PyQtGraph fails on them. WNote that the CTIs of
        # the cross plots (e.g. horCrossPlotRangeCti) are still connected to self.slicedArray, so
        # if the cross section consists of only infs, they may not able to update the autorange.
        # A warning is issued in that case.
        # We don't update self.slicedArray here because the data probe should still be able to
        # print the actual value.
        imageArray = replaceMaskedValueWithFloat(imageArray, np.isinf(self.slicedArray.data),
                                                 np.nan, copyOnReplace=True)

        # Reset the axes ranges (via the config)
        if (reason == UpdateReason.RTI_CHANGED or
            reason == UpdateReason.COLLECTOR_COMBO_BOX):
            self.config.xAxisRangeCti.autoRangeCti.data = True
            self.config.yAxisRangeCti.autoRangeCti.data = True
            self.config.histColorRangeCti.autoRangeCti.data = True
            self.config.histRangeCti.autoRangeCti.data = True
            self.config.horCrossPlotRangeCti.autoRangeCti.data = True
            self.config.verCrossPlotRangeCti.autoRangeCti.data = True

        # PyQtGraph uses the following dimension order: T, X, Y, Color.
        # We need to transpose the slicedArray ourselves because axes = {'x':1, 'y':0}
        # doesn't seem to do anything.
        imageArray = imageArray.transpose()
        self.imageItem.setImage(imageArray, autoLevels=False)

        self.horCrossPlotItem.invertX(self.config.xFlippedCti.configValue)
        self.verCrossPlotItem.invertY(self.config.yFlippedCti.configValue)

        self.probeLabel.setVisible(self.config.probeCti.configValue)

        self.titleLabel.setText(self.configValue('title').format(**self.collector.rtiInfo))

        # Update the config tree from the (possibly) new state of the PgImagePlot2d inspector,
        # e.g. the axis range or color range may have changed while drawing.
        self.config.updateTarget()

Response: Draw the contents of the collected repo tree item.


Instruction:
Implement a Python 3 function for
updating the probe text with the values under the cursor.

Response:
def mouseMoved(self, viewPos):
        """ Updates the probe text with the values under the cursor.
            Draws a vertical line and a symbol at the position of the probe.
        """
        try:
            check_class(viewPos, QtCore.QPointF)
            show_data_point = False # shows the data point as a circle in the cross hair plots
            self.crossPlotRow, self.crossPlotCol = None, None

            self.probeLabel.setText("no data at cursor")
            self.crossLineHorizontal.setVisible(False)
            self.crossLineVertical.setVisible(False)
            self.crossLineHorShadow.setVisible(False)
            self.crossLineVerShadow.setVisible(False)

            self.horCrossPlotItem.clear()
            self.verCrossPlotItem.clear()

            if (self._hasValidData() and self.slicedArray is not None
                and self.viewBox.sceneBoundingRect().contains(viewPos)):

                # Calculate the row and column at the cursor. We use math.floor because the pixel
                # corners of the image lie at integer values (and not the centers of the pixels).
                scenePos = self.viewBox.mapSceneToView(viewPos)
                row, col = math.floor(scenePos.y()), math.floor(scenePos.x())
                row, col = int(row), int(col) # Needed in Python 2
                nRows, nCols = self.slicedArray.shape

                if (0 <= row < nRows) and (0 <= col < nCols):
                    self.viewBox.setCursor(Qt.CrossCursor)

                    self.crossPlotRow, self.crossPlotCol = row, col
                    index = tuple([row, col])
                    valueStr = to_string(self.slicedArray[index],
                                         masked=self.slicedArray.maskAt(index),
                                         maskFormat='<masked>')
                    txt = "pos = ({:d}, {:d}), value = {}".format(row, col, valueStr)
                    self.probeLabel.setText(txt)

                    # Show cross section at the cursor pos in the line plots
                    if self.config.horCrossPlotCti.configValue:
                        self.crossLineHorShadow.setVisible(True)
                        self.crossLineHorizontal.setVisible(True)
                        self.crossLineHorShadow.setPos(row)
                        self.crossLineHorizontal.setPos(row)

                        # Line plot of cross section row.
                        # First determine which points are connected or separated by masks/nans.
                        rowData = self.slicedArray.data[row, :]
                        connected = np.isfinite(rowData)
                        if is_an_array(self.slicedArray.mask):
                            connected = np.logical_and(connected, ~self.slicedArray.mask[row, :])
                        else:
                            connected = (np.zeros_like(rowData)
                                         if self.slicedArray.mask else connected)

                        # Replace infinite value with nans because PyQtGraph can't handle them
                        rowData = replaceMaskedValueWithFloat(rowData, np.isinf(rowData),
                                                              np.nan, copyOnReplace=True)

                        horPlotDataItem = self.config.crossPenCti.createPlotDataItem()
                        horPlotDataItem.setData(rowData, connect=connected)
                        self.horCrossPlotItem.addItem(horPlotDataItem)

                        # Vertical line in hor-cross plot
                        crossLineShadow90 = pg.InfiniteLine(angle=90, movable=False,
                                                            pen=self.crossShadowPen)
                        crossLineShadow90.setPos(col)
                        self.horCrossPlotItem.addItem(crossLineShadow90, ignoreBounds=True)
                        crossLine90 = pg.InfiniteLine(angle=90, movable=False, pen=self.crossPen)
                        crossLine90.setPos(col)
                        self.horCrossPlotItem.addItem(crossLine90, ignoreBounds=True)

                        if show_data_point:
                            crossPoint90 = pg.PlotDataItem(symbolPen=self.crossPen)
                            crossPoint90.setSymbolBrush(QtGui.QBrush(self.config.crossPenCti.penColor))
                            crossPoint90.setSymbolSize(10)
                            crossPoint90.setData((col,), (rowData[col],))
                            self.horCrossPlotItem.addItem(crossPoint90, ignoreBounds=True)

                        self.config.horCrossPlotRangeCti.updateTarget() # update auto range
                        del rowData # defensive programming

                    if self.config.verCrossPlotCti.configValue:
                        self.crossLineVerShadow.setVisible(True)
                        self.crossLineVertical.setVisible(True)
                        self.crossLineVerShadow.setPos(col)
                        self.crossLineVertical.setPos(col)

                        # Line plot of cross section row.
                        # First determine which points are connected or separated by masks/nans.
                        colData = self.slicedArray.data[:, col]
                        connected = np.isfinite(colData)
                        if is_an_array(self.slicedArray.mask):
                            connected = np.logical_and(connected, ~self.slicedArray.mask[:, col])
                        else:
                            connected = (np.zeros_like(colData)
                                         if self.slicedArray.mask else connected)

                        # Replace infinite value with nans because PyQtGraph can't handle them
                        colData = replaceMaskedValueWithFloat(colData, np.isinf(colData),
                                                              np.nan, copyOnReplace=True)

                        verPlotDataItem = self.config.crossPenCti.createPlotDataItem()
                        verPlotDataItem.setData(colData, np.arange(nRows), connect=connected)
                        self.verCrossPlotItem.addItem(verPlotDataItem)

                        # Horizontal line in ver-cross plot
                        crossLineShadow0 = pg.InfiniteLine(angle=0, movable=False,
                                                           pen=self.crossShadowPen)
                        crossLineShadow0.setPos(row)
                        self.verCrossPlotItem.addItem(crossLineShadow0, ignoreBounds=True)
                        crossLine0 = pg.InfiniteLine(angle=0, movable=False, pen=self.crossPen)
                        crossLine0.setPos(row)
                        self.verCrossPlotItem.addItem(crossLine0, ignoreBounds=True)

                        if show_data_point:
                            crossPoint0 = pg.PlotDataItem(symbolPen=self.crossPen)
                            crossPoint0.setSymbolBrush(QtGui.QBrush(self.config.crossPenCti.penColor))
                            crossPoint0.setSymbolSize(10)
                            crossPoint0.setData((colData[row],), (row,))
                            self.verCrossPlotItem.addItem(crossPoint0, ignoreBounds=True)

                        self.config.verCrossPlotRangeCti.updateTarget() # update auto range
                        del colData # defensive programming

        except Exception as ex:
            # In contrast to _drawContents, this function is a slot and thus must not throw
            # exceptions. The exception is logged. Perhaps we should clear the cross plots, but
            # this could, in turn, raise exceptions.
            if DEBUGGING:
                raise
            else:
                logger.exception(ex)


Instruction:
Create a Python 3 function to
return a string that can be used to construct file dialogs filters for example

Response:
def getFileDialogFilter(self):
        """ Returns a filters that can be used to construct file dialogs filters,
            for example: 'Text File (*.txt;*.text)'
        """
        extStr = ';'.join(['*' + ext for ext in self.extensions])
        return '{} ({})'.format(self.name, extStr)


Instruction:
Write a Python 3 function for
returning a dictionary for serialization.

Response:
def asDict(self):
        """ Returns a dictionary for serialization.
        """
        dct = super(RtiRegItem, self).asDict()
        dct['extensions'] = self.extensions
        return dct


Instruction:
Here you have a function in Python 3, explain what it does
def _registerExtension(self, extension, rtiRegItem):
        check_is_a_string(extension)
        check_class(rtiRegItem, RtiRegItem)

        logger.debug("  Registering extension {!r} for {}".format(extension, rtiRegItem))

        # TODO: type checking
        if extension in self._extensionMap:
            logger.info("Overriding extension {!r}: old={}, new={}"
                        .format(extension, self._extensionMap[extension], rtiRegItem))
        self._extensionMap[extension] = rtiRegItem

Response: Adds an extension to the repository tree item.


Instruction:
Write a Python 3 script for
adding a ClassRegItem object to the registry.

Response:
def registerItem(self, regItem):
        """ Adds a ClassRegItem object to the registry.
        """
        super(RtiRegistry, self).registerItem(regItem)

        for ext in regItem.extensions:
            self._registerExtension(ext, regItem)


Instruction:
How would you explain what the following Python 3 function does
def registerRti(self, fullName, fullClassName, extensions=None, pythonPath=''):
        check_is_a_sequence(extensions)
        extensions = extensions if extensions is not None else []
        extensions = [prepend_point_to_extension(ext) for ext in extensions]

        regRti = RtiRegItem(fullName, fullClassName, extensions, pythonPath=pythonPath)
        self.registerItem(regRti)

Response: Register a new RTI with the registry.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def getFileDialogFilter(self):
        filters = []
        for regRti in self.items:
            filters.append(regRti.getFileDialogFilter())
        return ';;'.join(filters)

Response: Returns a filter that can be used in open file dialogs for example


Instruction:
Create a Python 3 function to
return a list with the default plugins in the repo tree item registry.

Response:
def getDefaultItems(self):
        """ Returns a list with the default plugins in the repo tree item registry.
        """
        return [
            RtiRegItem('HDF-5 file',
                       'argos.repo.rtiplugins.hdf5.H5pyFileRti',
                       extensions=['hdf5', 'h5', 'h5e', 'he5', 'nc']), # hdf extension is for HDF-4

            RtiRegItem('MATLAB file',
                       'argos.repo.rtiplugins.scipyio.MatlabFileRti',
                       extensions=['mat']),

            RtiRegItem('NetCDF file',
                       'argos.repo.rtiplugins.ncdf.NcdfFileRti',
                       #extensions=['nc', 'nc3', 'nc4']),
                       extensions=['nc', 'nc4']),
                       #extensions=[]),

            RtiRegItem('NumPy binary file',
                       'argos.repo.rtiplugins.numpyio.NumpyBinaryFileRti',
                       extensions=['npy']),

            RtiRegItem('NumPy compressed file',
                       'argos.repo.rtiplugins.numpyio.NumpyCompressedFileRti',
                       extensions=['npz']),

            RtiRegItem('NumPy text file',
                       'argos.repo.rtiplugins.numpyio.NumpyTextFileRti',
                       #extensions=['txt', 'text']),
                       extensions=['dat']),

            RtiRegItem('IDL save file',
                       'argos.repo.rtiplugins.scipyio.IdlSaveFileRti',
                       extensions=['sav']),

            RtiRegItem('Pandas CSV file',
                       'argos.repo.rtiplugins.pandasio.PandasCsvFileRti',
                        extensions=['csv']),

            RtiRegItem('Pillow image',
                       'argos.repo.rtiplugins.pillowio.PillowFileRti',
                        extensions=['bmp', 'eps', 'im', 'gif', 'jpg', 'jpeg', 'msp', 'pcx',
                                    'png', 'ppm', 'spi', 'tif', 'tiff', 'xbm', 'xv']),

            RtiRegItem('Wav file',
                       'argos.repo.rtiplugins.scipyio.WavFileRti',
                       extensions=['wav'])]


Instruction:
Can you generate the documentation for the following Python 3 function
def _addModuleInfo(self, moduleInfo):
        if is_a_string(moduleInfo):
            moduleInfo = mi.ImportedModuleInfo(moduleInfo)

        line = "{:15s}: {}".format(moduleInfo.name, moduleInfo.verboseVersion)
        self.editor.appendPlainText(line)
        QtWidgets.QApplication.instance().processEvents()

Response: Adds a line with module info to the editor


Instruction:
Make a summary of the following Python 3 code
def addDependencyInfo(self):
        logger.debug("Adding dependency info to the AboutDialog")
        self.progressLabel.setText("Retrieving package info...")
        self.editor.clear()

        self._addModuleInfo(mi.PythonModuleInfo())
        self._addModuleInfo(mi.QtModuleInfo())

        modules = ['numpy', 'scipy', 'pandas', 'pyqtgraph']
        for module in modules:
            self._addModuleInfo(module)

        self._addModuleInfo(mi.PillowInfo())
        self._addModuleInfo(mi.H5pyModuleInfo())
        self._addModuleInfo(mi.NetCDF4ModuleInfo())

        self.progressLabel.setText("")
        logger.debug("Finished adding dependency info to the AboutDialog")

Response: Adds version info about the installed dependencies to the AboutDialog


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _enforceDataType(self, data):
        value = float(data)
        if math.isnan(value):
            raise ValueError("FloatCti can't store NaNs")

        if math.isinf(value):
            if value > 0:
                logger.warn("Replacing inf by the largest representable float")
                value = sys.float_info.max
            else:
                logger.warn("Replacing -inf by the smallest representable float")
                value = -sys.float_info.max

        return value

Response: Converts the CTI data to a float so that this CTI always stores that type.


Instruction:
Create a Python 3 function for
converting the data to the display value.

Response:
def _dataToString(self, data):
        """ Conversion function used to convert the (default)data to the display value.
        """
        if self.specialValueText is not None and data == self.minValue:
            return self.specialValueText
        else:
            return "{}{:.{}f}{}".format(self.prefix, data, self.decimals, self.suffix)


Instruction:
Can you write a function in Python 3 where it
returns the string with debugging information about the current object.

Response:
def debugInfo(self):
        """ Returns the string with debugging information
        """
        return ("min = {}, max = {}, step = {}, decimals = {}, specVal = {}"
                .format(self.minValue, self.maxValue, self.stepSize,
                        self.decimals, self.specialValueText))


Instruction:
Implement a Python 3 function for
creating a FloatCtiEditor object.

Response:
def createEditor(self, delegate, parent, option):
        """ Creates a FloatCtiEditor.
            For the parameters see the AbstractCti constructor documentation.
        """
        return FloatCtiEditor(self, delegate, parent=parent)


Instruction:
Here you have a function in Python 3, explain what it does
def finalize(self):
        self.spinBox.valueChanged.disconnect(self.commitChangedValue)
        super(FloatCtiEditor, self).finalize()

Response: Called at clean up.


Instruction:
Can you generate the documentation for the following Python 3 function
def debugInfo(self):
        return ("enabled = {}, min = {}, max = {}, precision = {}, specVal = {}"
                .format(self.enabled, self.minValue, self.maxValue,
                        self.precision, self.specialValueText))

Response: Returns the string with debugging information about the current resource.


Instruction:
Implement a function in Python 3 to
create a FloatCtiEditor object.

Response:
def createEditor(self, delegate, parent, option):
        """ Creates a FloatCtiEditor.
            For the parameters see the AbstractCti constructor documentation.
        """
        return SnFloatCtiEditor(self, delegate, self.precision, parent=parent)


Instruction:
Can you tell what is the following Python 3 function doing
def finalize(self):
        self.spinBox.valueChanged.disconnect(self.commitChangedValue)
        super(SnFloatCtiEditor, self).finalize()

Response: Called at clean up.


Instruction:
Implement a Python 3 function for
detecting the type of RepoTreeItem to use given a file name.

Response:
def detectRtiFromFileName(fileName):
    """ Determines the type of RepoTreeItem to use given a file name.
        Uses a DirectoryRti for directories and an UnknownFileRti if the file
        extension doesn't match one of the registered RTI extensions.

        Returns (cls, regItem) tuple. Both the cls ond the regItem can be None.
        If the file is a directory, (DirectoryRti, None) is returned.
        If the file extension is not in the registry, (UnknownFileRti, None) is returned.
        If the cls cannot be imported (None, regItem) returned. regItem.exception will be set.
        Otherwise (cls, regItem) will be returned.
    """
    _, extension = os.path.splitext(fileName)
    if os.path.isdir(fileName):
        rtiRegItem = None
        cls = DirectoryRti
    else:
        try:
            rtiRegItem = globalRtiRegistry().getRtiRegItemByExtension(extension)
        except (KeyError):
            logger.debug("No file RTI registered for extension: {}".format(extension))
            rtiRegItem = None
            cls = UnknownFileRti
        else:
            cls = rtiRegItem.getClass(tryImport=True) # cls can be None

    return cls, rtiRegItem


Instruction:
Make a summary of the following Python 3 code
def createRtiFromFileName(fileName):
    cls, rtiRegItem = detectRtiFromFileName(fileName)
    if cls is None:
        logger.warn("Unable to import plugin {}: {}"
                    .format(rtiRegItem.fullName, rtiRegItem.exception))
        rti = UnknownFileRti.createFromFileName(fileName)
        rti.setException(rtiRegItem.exception)
    else:
        rti = cls.createFromFileName(fileName)

    assert rti, "Sanity check failed (createRtiFromFileName). Please report this bug."
    return rti

Response: Determines the type of RepoTreeItem to use given a file name and creates it.


Instruction:
Write a Python 3 function for
getting all sub directories and files within the current directory.

Response:
def _fetchAllChildren(self):
        """ Gets all sub directories and files within the current directory.
            Does not fetch hidden files.
        """
        childItems = []
        fileNames = os.listdir(self._fileName)
        absFileNames = [os.path.join(self._fileName, fn) for fn in fileNames]

        # Add subdirectories
        for fileName, absFileName in zip(fileNames, absFileNames):
            if os.path.isdir(absFileName) and not fileName.startswith('.'):
                childItems.append(DirectoryRti(fileName=absFileName, nodeName=fileName))

        # Add regular files
        for fileName, absFileName in zip(fileNames, absFileNames):
            if os.path.isfile(absFileName) and not fileName.startswith('.'):
                childItem = createRtiFromFileName(absFileName)
                childItems.append(childItem)

        return childItems


Instruction:
Explain what the following Python 3 code does
def resizeColumnsToContents(self, startCol=None, stopCol=None):
        numCols = self.model().columnCount()
        startCol = 0 if startCol is None else max(startCol, 0)
        stopCol  = numCols if stopCol is None else min(stopCol, numCols)

        row = 0
        for col in range(startCol, stopCol):
            indexWidget = self.indexWidget(self.model().index(row, col))

            if indexWidget:
                contentsWidth = indexWidget.sizeHint().width()
            else:
                contentsWidth = self.header().sectionSizeHint(col)

            self.header().resizeSection(col, contentsWidth)

Response: Resizes all columns to the contents


Instruction:
Can you write a function in Python 3 where it
returns the size of the collector containing the current entry.

Response:
def sizeHint(self):
        """ Reimplemented from the C++ Qt source of QAbstractSpinBox.sizeHint, but without
            truncating to a maximum of 18 characters.
        """
        # The cache is invalid after the prefix, postfix and other properties
        # have been set. I disabled it because sizeHint isn't called that often.
        #if self._cachedSizeHint is not None:
        #    return self._cachedSizeHint

        orgSizeHint = super(CollectorSpinBox, self).sizeHint()

        self.ensurePolished()
        d = self
        fm = QtGui.QFontMetrics(self.fontMetrics())

        # This was h = d.edit.sizeHint().height(), but that didn't work. In the end we set the
        # height to the height calculated from the parent.
        h = orgSizeHint.height()
        w = 0

        # QLatin1Char seems not to be implemented.
        # Using regular string literals and hope for the best
        s = d.prefix() + d.textFromValue(d.minimum()) + d.suffix() + ' '

        # We disabled truncating the string here!!
        #s = s[:18]
        w = max(w, fm.width(s))

        s = d.prefix() + d.textFromValue(d.maximum()) + d.suffix() + ' '

        # We disabled truncating the string here!!
        #s = s[:18]
        w = max(w, fm.width(s))
        if len(d.specialValueText()):
            s = d.specialValueText()
            w = max(w, fm.width(s))

        w += 2 # cursor blinking space

        opt = QtWidgets.QStyleOptionSpinBox()
        self.initStyleOption(opt)
        hint = QtCore.QSize(w, h)
        extra = QtCore.QSize(35, 6)

        opt.rect.setSize(hint + extra)
        extra += hint - self.style().subControlRect(QtWidgets.QStyle.CC_SpinBox, opt,
                                                    QtWidgets.QStyle.SC_SpinBoxEditField, self).size()

        # get closer to final result by repeating the calculation
        opt.rect.setSize(hint + extra)
        extra += hint - self.style().subControlRect(QtWidgets.QStyle.CC_SpinBox, opt,
                                                    QtWidgets.QStyle.SC_SpinBoxEditField, self).size()
        hint += extra

        opt.rect = self.rect()
        result = (self.style().sizeFromContents(QtWidgets.QStyle.CT_SpinBox, opt, hint, self)
                  .expandedTo(QtWidgets.QApplication.globalStrut()))
        self._cachedSizeHint = result

        # Use the height ancestor's sizeHint
        result.setHeight(orgSizeHint.height())

        return result


Instruction:
Write a Python 3 script for
creating an editor for the item at the given index.

Response:
def createEditor(self, parent, option, index):
        """ Returns the widget used to change data from the model and can be reimplemented to
            customize editing behavior.

            Reimplemented from QStyledItemDelegate.
        """
        logger.debug("ConfigItemDelegate.createEditor, parent: {!r}".format(parent.objectName()))
        assert index.isValid(), "sanity check failed: invalid index"

        cti = index.model().getItem(index)
        editor = cti.createEditor(self, parent, option)
        return editor


Instruction:
Implement a function in Python 3 to
provide the widget with data to manipulate.

Response:
def setEditorData(self, editor, index):
        """ Provides the widget with data to manipulate.
            Calls the setEditorValue of the config tree item at the index.

            :type editor: QWidget
            :type index: QModelIndex

            Reimplemented from QStyledItemDelegate.
        """
        # We take the config value via the model to be consistent with setModelData
        data = index.model().data(index, Qt.EditRole)
        editor.setData(data)


Instruction:
Make a summary of the following Python 3 code
def setModelData(self, editor, model, index):
        try:
            data = editor.getData()
        except InvalidInputError as ex:
            logger.warn(ex)
        else:
            # The value is set via the model so that signals are emitted
            logger.debug("ConfigItemDelegate.setModelData: {}".format(data))
            model.setData(index, data, Qt.EditRole)

Response: Sets the data in the specified model at the given index.


Instruction:
Implement a Python 3 function for
updating the editor geometry with the current option.

Response:
def updateEditorGeometry(self, editor, option, index):
        """ Ensures that the editor is displayed correctly with respect to the item view.
        """
        cti = index.model().getItem(index)
        if cti.checkState is None:
            displayRect = option.rect
        else:
            checkBoxRect = widgetSubCheckBoxRect(editor, option)
            offset = checkBoxRect.x() + checkBoxRect.width()
            displayRect = option.rect
            displayRect.adjust(offset, 0, 0, 0)

        editor.setGeometry(displayRect)


Instruction:
Can you write a function in Python 3 where it
finalizes closes and releases the given editor.

Response:
def closeEditor(self, editor, hint):
        """ Finalizes, closes and releases the given editor.
        """
        # It would be nicer if this method was part of ConfigItemDelegate since createEditor also
        # lives there. However, QAbstractItemView.closeEditor is sometimes called directly,
        # without the QAbstractItemDelegate.closeEditor signal begin emitted, e.g when the
        # currentItem changes. Therefore we cannot connect the QAbstractItemDelegate.closeEditor
        # signal to a slot in the ConfigItemDelegate.
        configItemDelegate = self.itemDelegate()
        configItemDelegate.finalizeEditor(editor)

        super(ConfigTreeView, self).closeEditor(editor, hint)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def expandBranch(self, index=None, expanded=None):
        configModel = self.model()
        if index is None:
            #index = configTreeModel.createIndex()
            index = QtCore.QModelIndex()

        if index.isValid():
            if expanded is None:
                item = configModel.getItem(index)
                self.setExpanded(index, item.expanded)
            else:
                self.setExpanded(index, expanded)

        for rowNr in range(configModel.rowCount(index)):
            childIndex = configModel.index(rowNr, configModel.COL_NODE_NAME, parentIndex=index)
            self.expandBranch(index=childIndex, expanded=expanded)

Response: Expands or collapses the node at the index and all its descendants.


Instruction:
How would you explain what the following Python 3 function does
def ncVarAttributes(ncVar):
    try:
        return ncVar.__dict__
    except Exception as ex:
        # Due to some internal error netCDF4 may raise an AttributeError or KeyError,
        # depending on its version.
        logger.warn("Unable to read the attributes from {}. Reason: {}"
                    .format(ncVar.name, ex))
        return {}

Response: Returns the attributes of the ncdf variable


Instruction:
Can you tell what is the following Python 3 function doing
def ncVarUnit(ncVar):
    attributes = ncVarAttributes(ncVar)
    if not attributes:
        return '' # a premature optimization :-)

    for key in ('unit', 'units', 'Unit', 'Units', 'UNIT', 'UNITS'):
        if key in attributes:
            # In Python3 the attribures are byte strings so we must decode them
            # This a bug in h5py, see https://github.com/h5py/h5py/issues/379
            return attributes[key]
    else:
        return ''

Response: Returns the unit of the ncVar in the order they appear.


Instruction:
How would you code a function in Python 3 to
return the missingData given a NetCDF variable

Response:
def variableMissingValue(ncVar):
    """ Returns the missingData given a NetCDF variable

        Looks for one of the following attributes: _FillValue, missing_value, MissingValue,
        missingValue. Returns None if these attributes are not found.
    """
    attributes = ncVarAttributes(ncVar)
    if not attributes:
        return None # a premature optimization :-)

    for key in ('missing_value', 'MissingValue', 'missingValue', 'FillValue', '_FillValue'):
        if key in attributes:
            missingDataValue = attributes[key]
            return missingDataValue
    return None


Instruction:
Can you generate a brief explanation for the following Python 3 code
def elementTypeName(self):
        fieldName = self.nodeName
        return str(self._ncVar.dtype.fields[fieldName][0])

Response: String representation of the element type.


Instruction:
Write a Python 3 function for
returning the unit attribute of the underlying ncdf variable.

Response:
def unit(self):
        """ Returns the unit attribute of the underlying ncdf variable.

            If the units has a length (e.g is a list) and has precisely one element per field,
            the unit for this field is returned.
        """
        unit = ncVarUnit(self._ncVar)
        fieldNames = self._ncVar.dtype.names

        # If the missing value attribute 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(unit, '__len__') and len(unit) == len(fieldNames):
            idx = fieldNames.index(self.nodeName)
            return unit[idx]
        else:
            return unit


Instruction:
How would you code a function in Python 3 to
return a list with the dimension names of the underlying NCDF variable

Response:
def dimensionNames(self):
        """ Returns a list with the dimension names of the underlying NCDF variable
        """
        nSubDims = len(self._subArrayShape)
        subArrayDims = ['SubDim{}'.format(dimNr) for dimNr in range(nSubDims)]
        return list(self._ncVar.dimensions + tuple(subArrayDims))


Instruction:
Create a Python 3 function for
returning the value to indicate missing data. None is returned.

Response:
def missingDataValue(self):
        """ Returns the value to indicate missing data. None if no missing-data value is specified.
        """
        value = variableMissingValue(self._ncVar)
        fieldNames = self._ncVar.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 len(value) == len(fieldNames):
            idx = fieldNames.index(self.nodeName)
            return value[idx]
        else:
            return value


Instruction:
Here you have a function in Python 3, explain what it does
def elementTypeName(self):
        dtype =  self._ncVar.dtype
        if type(dtype) == type:
            # Handle the unexpected case that dtype is a regular Python type
            # (happens e.g. in the /PROCESSOR/processing_configuration of the Trop LX files)
            return dtype.__name__

        return '<structured>' if dtype.names else str(dtype)

Response: String representation of the element type.


Instruction:
Make a summary of the following Python 3 code
def _fetchAllChildren(self):
        assert self.canFetchChildren(), "canFetchChildren must be True"

        childItems = []

        # Add fields
        if self._isStructured:
            for fieldName in self._ncVar.dtype.names:
                childItems.append(NcdfFieldRti(self._ncVar, nodeName=fieldName, fileName=self.fileName))

        return childItems

Response: Fetches all the children of this variable.


Instruction:
Write a Python 3 script to
fetch all sub groups and variables that this group contains.

Response:
def _fetchAllChildren(self):
        """ Fetches all sub groups and variables that this group contains.
        """
        assert self._ncGroup is not None, "dataset undefined (file not opened?)"
        assert self.canFetchChildren(), "canFetchChildren must be True"

        childItems = []

        # Add dimensions
        for dimName, ncDim in self._ncGroup.dimensions.items():
            childItems.append(NcdfDimensionRti(ncDim, nodeName=dimName, fileName=self.fileName))

        # Add groups
        for groupName, ncGroup in self._ncGroup.groups.items():
            childItems.append(NcdfGroupRti(ncGroup, nodeName=groupName, fileName=self.fileName))

        # Add variables
        for varName, ncVar in self._ncGroup.variables.items():
            childItems.append(NcdfVariableRti(ncVar, nodeName=varName, fileName=self.fileName))

        return childItems


Instruction:
Write a Python 3 function for
opening the root Dataset.

Response:
def _openResources(self):
        """ Opens the root Dataset.
        """
        logger.info("Opening: {}".format(self._fileName))
        self._ncGroup = Dataset(self._fileName)


Instruction:
Implement a function in Python 3 to
close the root Dataset.

Response:
def _closeResources(self):
        """ Closes the root Dataset.
        """
        logger.info("Closing: {}".format(self._fileName))
        self._ncGroup.close()
        self._ncGroup = None


Instruction:
Write a Python 3 script for
opening the underlying file and sets the rate attribute.

Response:
def _openResources(self):
        """ Uses numpy.loadtxt to open the underlying file.
        """
        try:
            rate, data = scipy.io.wavfile.read(self._fileName, mmap=True)
        except Exception as ex:
            logger.warning(ex)
            logger.warning("Unable to read wav with memmory mapping. Trying without now.")
            rate, data = scipy.io.wavfile.read(self._fileName, mmap=False)

        self._array = data
        self.attributes['rate'] = rate


Instruction:
Explain what the following Python 3 code does
def _fetchAllChildren(self):
        childItems = []
        if self._array.ndim == 2:
            _nRows, nCols = self._array.shape if self._array is not None else (0, 0)
            for col in range(nCols):
                colItem = SliceRti(self._array[:, col], nodeName="channel-{}".format(col),
                                   fileName=self.fileName, iconColor=self.iconColor,
                                   attributes=self.attributes)
                childItems.append(colItem)
        return childItems

Response: Adds an ArrayRti per column as children so that they can be inspected easily.


Instruction:
Explain what the following Python 3 code does
def _drawContents(self, reason=None, initiator=None):
        logger.debug("TextInspector._drawContents: {}".format(self))
        self._clearContents()

        slicedArray = self.collector.getSlicedArray()

        if slicedArray is None:
            return

        # Sanity check, the slicedArray should be zero-dimensional. It can be used as a scalar.
        # In fact, using an index (e.g. slicedArray[0]) will raise an exception.
        assert slicedArray.data.ndim == 0, \
            "Expected zero-dimensional array. Got: {}".format(slicedArray.ndim)

        # Valid data from here...
        maskedArr = slicedArray.asMaskedArray() # So that we call mask[()] for boolean masks
        slicedScalar = maskedArr[()] # Convert to Numpy scalar
        isMasked = maskedArr.mask[()]

        text = to_string(slicedScalar, masked=isMasked, maskFormat='--',
                         decode_bytes=self.config.encodingCti.configValue)
        self.editor.setPlainText(text)
        self.editor.setWordWrapMode(self.config.wordWrapCti.configValue)

        # Update the editor font from the font config item (will call self.editor.setFont)
        self.config.updateTarget()

Response: Draws the contents of the current item in the text editor.


Instruction:
How would you implement a function in Python 3 that
emits sigAxisReset when the middle mouse button is clicked on an axis of the plot item.

Response:
def middleMouseClickEvent(argosPgPlotItem, axisNumber, mouseClickEvent):
    """ Emits sigAxisReset when the middle mouse button is clicked on an axis of the the plot item.
    """
    if mouseClickEvent.button() == QtCore.Qt.MiddleButton:
        mouseClickEvent.accept()
        argosPgPlotItem.emitResetAxisSignal(axisNumber)


Instruction:
Write a Python 3 function that can
close the resources of this object.

Response:
def close(self):
        """ Is called before destruction. Can be used to clean-up resources
            Could be called 'finalize' but PlotItem already has a close so we reuse that.
        """
        logger.debug("Finalizing: {}".format(self))
        super(ArgosPgPlotItem, self).close()


Instruction:
How would you code a function in Python 3 to
show the context menu at the cursor position

Response:
def contextMenuEvent(self, event):
        """ Shows the context menu at the cursor position

            We need to take the event-based approach because ArgosPgPlotItem does derives from
            QGraphicsWidget, and not from QWidget, and therefore doesn't have the
            customContextMenuRequested signal.
        """
        contextMenu = QtWidgets.QMenu()
        for action in self.actions():
            contextMenu.addAction(action)
        contextMenu.exec_(event.screenPos())