Instruction:
Implement a Python 3 function for
calculating the Brier Skill Score

Response:
def brier_skill_score(self):
        """
        Calculate the Brier Skill Score
        """
        reliability, resolution, uncertainty = self.brier_score_components()
        return (resolution - reliability) / uncertainty


Instruction:
Implement a Python 3 function for
updating the statistics with the forecasts and observations.

Response:
def update(self, forecasts, observations):
        """
        Update the statistics with forecasts and observations.

        Args:
            forecasts: The discrete Cumulative Distribution Functions of
            observations:
        """
        if len(observations.shape) == 1:
            obs_cdfs = np.zeros((observations.size, self.thresholds.size))
            for o, observation in enumerate(observations):
                obs_cdfs[o, self.thresholds >= observation] = 1
        else:
            obs_cdfs = observations
        self.errors["F_2"] += np.sum(forecasts ** 2, axis=0)
        self.errors["F_O"] += np.sum(forecasts * obs_cdfs, axis=0)
        self.errors["O_2"] += np.sum(obs_cdfs ** 2, axis=0)
        self.errors["O"] += np.sum(obs_cdfs, axis=0)
        self.num_forecasts += forecasts.shape[0]


Instruction:
Can you create a Python 3 function that
calculates the continuous ranked probability score.

Response:
def crps(self):
        """
        Calculates the continuous ranked probability score.
        """
        return np.sum(self.errors["F_2"].values - self.errors["F_O"].values * 2.0 + self.errors["O_2"].values) / \
            (self.thresholds.size * self.num_forecasts)


Instruction:
Can you create a Python 3 function that
calculates the climatological CRPS.

Response:
def crps_climo(self):
        """
        Calculate the climatological CRPS.
        """
        o_bar = self.errors["O"].values / float(self.num_forecasts)
        crps_c = np.sum(self.num_forecasts * (o_bar ** 2) - o_bar * self.errors["O"].values * 2.0 +
                        self.errors["O_2"].values) / float(self.thresholds.size * self.num_forecasts)
        return crps_c


Instruction:
Can you tell what is the following Python 3 function doing
def crpss(self):
        crps_f = self.crps()
        crps_c = self.crps_climo()
        return 1.0 - float(crps_f) / float(crps_c)

Response: Calculate the continous ranked probability skill score from existing data.


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

    resposta = cliente_sat.consultar_status_operacional()
    alertas = []
    for classe_alerta in AlertaOperacao.alertas_registrados:
        alerta = classe_alerta(resposta)
        if alerta.checar():
            alertas.append(alerta)
    return alertas

Response: Checar um listos os alertas registrados.


Instruction:
Can you create a Python 3 function that
returns True if the metadata value for the given key exists in the current language.

Response:
def has_metadata_value(metadata_source, key: str) -> bool:
    """Return whether the metadata value for the given key exists.

    There are a set of predefined keys that, when used, will be type checked and be interoperable with other
    applications. Please consult reference documentation for valid keys.

    If using a custom key, we recommend structuring your keys in the '<group>.<attribute>' format followed
    by the predefined keys. e.g. 'session.instrument' or 'camera.binning'.

    Also note that some predefined keys map to the metadata ``dict`` but others do not. For this reason, prefer
    using the ``metadata_value`` methods over directly accessing ``metadata``.
    """
    desc = session_key_map.get(key)
    if desc is not None:
        d = getattr(metadata_source, "session_metadata", dict())
        for k in desc['path'][:-1]:
            d =  d.setdefault(k, dict()) if d is not None else None
        if d is not None:
            return desc['path'][-1] in d
    desc = key_map.get(key)
    if desc is not None:
        d = getattr(metadata_source, "metadata", dict())
        for k in desc['path'][:-1]:
            d =  d.setdefault(k, dict()) if d is not None else None
        if d is not None:
            return desc['path'][-1] in d
    raise False


Instruction:
How would you code a function in Python 3 to
get the metadata value for the given key.

Response:
def get_metadata_value(metadata_source, key: str) -> typing.Any:
    """Get the metadata value for the given key.

    There are a set of predefined keys that, when used, will be type checked and be interoperable with other
    applications. Please consult reference documentation for valid keys.

    If using a custom key, we recommend structuring your keys in the '<group>.<attribute>' format followed
    by the predefined keys. e.g. 'session.instrument' or 'camera.binning'.

    Also note that some predefined keys map to the metadata ``dict`` but others do not. For this reason, prefer
    using the ``metadata_value`` methods over directly accessing ``metadata``.
    """
    desc = session_key_map.get(key)
    if desc is not None:
        v = getattr(metadata_source, "session_metadata", dict())
        for k in desc['path']:
            v =  v.get(k) if v is not None else None
        return v
    desc = key_map.get(key)
    if desc is not None:
        v = getattr(metadata_source, "metadata", dict())
        for k in desc['path']:
            v =  v.get(k) if v is not None else None
        return v
    raise KeyError()


Instruction:
Create a Python 3 function to
set the metadata value for the given key.

Response:
def set_metadata_value(metadata_source, key: str, value: typing.Any) -> None:
    """Set the metadata value for the given key.

    There are a set of predefined keys that, when used, will be type checked and be interoperable with other
    applications. Please consult reference documentation for valid keys.

    If using a custom key, we recommend structuring your keys in the '<group>.<attribute>' format followed
    by the predefined keys. e.g. 'session.instrument' or 'camera.binning'.

    Also note that some predefined keys map to the metadata ``dict`` but others do not. For this reason, prefer
    using the ``metadata_value`` methods over directly accessing ``metadata``.
    """
    desc = session_key_map.get(key)
    if desc is not None:
        d0 = getattr(metadata_source, "session_metadata", dict())
        d = d0
        for k in desc['path'][:-1]:
            d =  d.setdefault(k, dict()) if d is not None else None
        if d is not None:
            d[desc['path'][-1]] = value
            metadata_source.session_metadata = d0
            return
    desc = key_map.get(key)
    if desc is not None:
        d0 = getattr(metadata_source, "metadata", dict())
        d = d0
        for k in desc['path'][:-1]:
            d =  d.setdefault(k, dict()) if d is not None else None
        if d is not None:
            d[desc['path'][-1]] = value
            metadata_source.metadata = d0
            return
    raise KeyError()


Instruction:
Can you write a function in Python 3 where it
deletes the metadata value for the given key.

Response:
def delete_metadata_value(metadata_source, key: str) -> None:
    """Delete the metadata value for the given key.

    There are a set of predefined keys that, when used, will be type checked and be interoperable with other
    applications. Please consult reference documentation for valid keys.

    If using a custom key, we recommend structuring your keys in the '<dotted>.<group>.<attribute>' format followed
    by the predefined keys. e.g. 'stem.session.instrument' or 'stm.camera.binning'.

    Also note that some predefined keys map to the metadata ``dict`` but others do not. For this reason, prefer
    using the ``metadata_value`` methods over directly accessing ``metadata``.
    """
    desc = session_key_map.get(key)
    if desc is not None:
        d0 = getattr(metadata_source, "session_metadata", dict())
        d = d0
        for k in desc['path'][:-1]:
            d =  d.setdefault(k, dict()) if d is not None else None
        if d is not None and desc['path'][-1] in d:
            d.pop(desc['path'][-1], None)
            metadata_source.session_metadata = d0
            return
    desc = key_map.get(key)
    if desc is not None:
        d0 = getattr(metadata_source, "metadata", dict())
        d = d0
        for k in desc['path'][:-1]:
            d =  d.setdefault(k, dict()) if d is not None else None
        if d is not None and desc['path'][-1] in d:
            d.pop(desc['path'][-1], None)
            metadata_source.metadata = d0
            return


Instruction:
How would you code a function in Python 3 to
calculate the y - axis items dependent on the plot height.

Response:
def calculate_y_ticks(self, plot_height):
        """Calculate the y-axis items dependent on the plot height."""

        calibrated_data_min = self.calibrated_data_min
        calibrated_data_max = self.calibrated_data_max
        calibrated_data_range = calibrated_data_max - calibrated_data_min

        ticker = self.y_ticker
        y_ticks = list()
        for tick_value, tick_label in zip(ticker.values, ticker.labels):
            if calibrated_data_range != 0.0:
                y_tick = plot_height - plot_height * (tick_value - calibrated_data_min) / calibrated_data_range
            else:
                y_tick = plot_height - plot_height * 0.5
            if y_tick >= 0 and y_tick <= plot_height:
                y_ticks.append((y_tick, tick_label))

        return y_ticks


Instruction:
Here you have a function in Python 3, explain what it does
def calculate_x_ticks(self, plot_width):

        x_calibration = self.x_calibration

        uncalibrated_data_left = self.__uncalibrated_left_channel
        uncalibrated_data_right = self.__uncalibrated_right_channel

        calibrated_data_left = x_calibration.convert_to_calibrated_value(uncalibrated_data_left) if x_calibration is not None else uncalibrated_data_left
        calibrated_data_right = x_calibration.convert_to_calibrated_value(uncalibrated_data_right) if x_calibration is not None else uncalibrated_data_right
        calibrated_data_left, calibrated_data_right = min(calibrated_data_left, calibrated_data_right), max(calibrated_data_left, calibrated_data_right)

        graph_left, graph_right, tick_values, division, precision = Geometry.make_pretty_range(calibrated_data_left, calibrated_data_right)

        drawn_data_width = self.drawn_right_channel - self.drawn_left_channel

        x_ticks = list()
        if drawn_data_width > 0.0:
            for tick_value in tick_values:
                label = nice_label(tick_value, precision)
                data_tick = x_calibration.convert_from_calibrated_value(tick_value) if x_calibration else tick_value
                x_tick = plot_width * (data_tick - self.drawn_left_channel) / drawn_data_width
                if x_tick >= 0 and x_tick <= plot_width:
                    x_ticks.append((x_tick, label))

        return x_ticks

Response: Calculate the x - axis items dependent on the plot width.


Instruction:
How would you explain what the following Python 3 function does
def size_to_content(self):
        new_sizing = self.copy_sizing()
        new_sizing.minimum_height = 0
        new_sizing.maximum_height = 0
        axes = self.__axes
        if axes and axes.is_valid:
            if axes.x_calibration and axes.x_calibration.units:
                new_sizing.minimum_height = self.font_size + 4
                new_sizing.maximum_height = self.font_size + 4
        self.update_sizing(new_sizing)

Response: Size the canvas item to the proper height.


Instruction:
Create a Python 3 function to
size the canvas item to the proper width the maximum of any label.

Response:
def size_to_content(self, get_font_metrics_fn):
        """ Size the canvas item to the proper width, the maximum of any label. """
        new_sizing = self.copy_sizing()

        new_sizing.minimum_width = 0
        new_sizing.maximum_width = 0

        axes = self.__axes
        if axes and axes.is_valid:

            # calculate the width based on the label lengths
            font = "{0:d}px".format(self.font_size)

            max_width = 0
            y_range = axes.calibrated_data_max - axes.calibrated_data_min
            label = axes.y_ticker.value_label(axes.calibrated_data_max + y_range * 5)
            max_width = max(max_width, get_font_metrics_fn(font, label).width)
            label = axes.y_ticker.value_label(axes.calibrated_data_min - y_range * 5)
            max_width = max(max_width, get_font_metrics_fn(font, label).width)

            new_sizing.minimum_width = max_width
            new_sizing.maximum_width = max_width

        self.update_sizing(new_sizing)


Instruction:
How would you implement a function in Python 3 that
sizes the canvas item to the proper width.

Response:
def size_to_content(self):
        """ Size the canvas item to the proper width. """
        new_sizing = self.copy_sizing()
        new_sizing.minimum_width = 0
        new_sizing.maximum_width = 0
        axes = self.__axes
        if axes and axes.is_valid:
            if axes.y_calibration and axes.y_calibration.units:
                new_sizing.minimum_width = self.font_size + 4
                new_sizing.maximum_width = self.font_size + 4
        self.update_sizing(new_sizing)


Instruction:
Write a Python 3 function that can
load the content of a snippet file in SNIPPETS_ROOT

Response:
def get_snippet_content(snippet_name, **format_kwargs):
    """ Load the content from a snippet file which exists in SNIPPETS_ROOT """
    filename = snippet_name + '.snippet'
    snippet_file = os.path.join(SNIPPETS_ROOT, filename)
    if not os.path.isfile(snippet_file):
        raise ValueError('could not find snippet with name ' + filename)
    ret = helpers.get_file_content(snippet_file)
    if format_kwargs:
        ret = ret.format(**format_kwargs)
    return ret


Instruction:
Make a summary of the following Python 3 code
def update_display_properties(self, display_calibration_info, display_properties: typing.Mapping, display_layers: typing.Sequence[typing.Mapping]) -> None:

        # may be called from thread; prevent a race condition with closing.
        with self.__closing_lock:
            if self.__closed:
                return

            displayed_dimensional_scales = display_calibration_info.displayed_dimensional_scales
            displayed_dimensional_calibrations = display_calibration_info.displayed_dimensional_calibrations
            self.__data_scale = displayed_dimensional_scales[-1] if len(displayed_dimensional_scales) > 0 else 1
            self.__displayed_dimensional_calibration = displayed_dimensional_calibrations[-1] if len(displayed_dimensional_calibrations) > 0 else Calibration.Calibration(scale=displayed_dimensional_scales[-1])
            self.__intensity_calibration = display_calibration_info.displayed_intensity_calibration
            self.__calibration_style = display_calibration_info.calibration_style
            self.__y_min = display_properties.get("y_min")
            self.__y_max = display_properties.get("y_max")
            self.__y_style = display_properties.get("y_style", "linear")
            self.__left_channel = display_properties.get("left_channel")
            self.__right_channel = display_properties.get("right_channel")
            self.__legend_position = display_properties.get("legend_position")
            self.__display_layers = display_layers

            if self.__display_values_list and len(self.__display_values_list) > 0:
                self.__xdata_list = [display_values.display_data_and_metadata if display_values else None for display_values in self.__display_values_list]
                xdata0 = self.__xdata_list[0]
                if xdata0:
                    self.__update_frame(xdata0.metadata)
            else:
                self.__xdata_list = list()

            # update the cursor info
            self.__update_cursor_info()

            # mark for update. prepare display will mark children for update if necesssary.
            self.update()

Response: Updates the display properties of the items in the canvas item.


Instruction:
Can you create a Python 3 function that
changes the view to encompass the channels and data represented by the given intervals.

Response:
def __view_to_intervals(self, data_and_metadata: DataAndMetadata.DataAndMetadata, intervals: typing.List[typing.Tuple[float, float]]) -> None:
        """Change the view to encompass the channels and data represented by the given intervals."""
        left = None
        right = None
        for interval in intervals:
            left = min(left, interval[0]) if left is not None else interval[0]
            right = max(right, interval[1]) if right is not None else interval[1]
        left = left if left is not None else 0.0
        right = right if right is not None else 1.0
        left_channel = int(max(0.0, left) * data_and_metadata.data_shape[-1])
        right_channel = int(min(1.0, right) * data_and_metadata.data_shape[-1])
        data_min = numpy.amin(data_and_metadata.data[..., left_channel:right_channel])
        data_max = numpy.amax(data_and_metadata.data[..., left_channel:right_channel])
        if data_min > 0 and data_max > 0:
            y_min = 0.0
            y_max = data_max * 1.2
        elif data_min < 0 and data_max < 0:
            y_min = data_min * 1.2
            y_max = 0.0
        else:
            y_min = data_min * 1.2
            y_max = data_max * 1.2
        extra = (right - left) * 0.5
        display_left_channel = int(max(0.0, left - extra) * data_and_metadata.data_shape[-1])
        display_right_channel = int(min(1.0, right + extra) * data_and_metadata.data_shape[-1])
        # command = self.delegate.create_change_display_command()
        self.delegate.update_display_properties({"left_channel": display_left_channel, "right_channel": display_right_channel, "y_min": y_min, "y_max": y_max})


Instruction:
Can you write a function in Python 3 where it
changes the view to encompass the selected graphic intervals.

Response:
def __view_to_selected_graphics(self, data_and_metadata: DataAndMetadata.DataAndMetadata) -> None:
        """Change the view to encompass the selected graphic intervals."""
        all_graphics = self.__graphics
        graphics = [graphic for graphic_index, graphic in enumerate(all_graphics) if self.__graphic_selection.contains(graphic_index)]
        intervals = list()
        for graphic in graphics:
            if isinstance(graphic, Graphics.IntervalGraphic):
                intervals.append(graphic.interval)
        self.__view_to_intervals(data_and_metadata, intervals)


Instruction:
Can you implement a function in Python 3 that
prepares the display. This method gets called by the canvas layout/draw engine after being triggered by a call to `update`. When data or display parameters change, the internal state of the line plot gets updated. This method takes that internal state and updates the child canvas items. This method is always run on a thread and should be fast but doesn't need to be instant.

Response:
def prepare_display(self):
        """Prepare the display.

        This method gets called by the canvas layout/draw engine after being triggered by a call to `update`.

        When data or display parameters change, the internal state of the line plot gets updated. This method takes
        that internal state and updates the child canvas items.

        This method is always run on a thread and should be fast but doesn't need to be instant.
        """
        displayed_dimensional_calibration = self.__displayed_dimensional_calibration
        intensity_calibration = self.__intensity_calibration
        calibration_style = self.__calibration_style
        y_min = self.__y_min
        y_max = self.__y_max
        y_style = self.__y_style
        left_channel = self.__left_channel
        right_channel = self.__right_channel

        scalar_xdata_list = None

        def calculate_scalar_xdata(xdata_list):
            scalar_xdata_list = list()
            for xdata in xdata_list:
                if xdata:
                    scalar_data = Image.scalar_from_array(xdata.data)
                    scalar_data = Image.convert_to_grayscale(scalar_data)
                    scalar_intensity_calibration = calibration_style.get_intensity_calibration(xdata)
                    scalar_dimensional_calibrations = calibration_style.get_dimensional_calibrations(xdata.dimensional_shape, xdata.dimensional_calibrations)
                    if displayed_dimensional_calibration.units == scalar_dimensional_calibrations[-1].units and intensity_calibration.units == scalar_intensity_calibration.units:
                        # the data needs to have an intensity scale matching intensity_calibration. convert the data to use the common scale.
                        scale = scalar_intensity_calibration.scale / intensity_calibration.scale
                        offset = (scalar_intensity_calibration.offset - intensity_calibration.offset) / intensity_calibration.scale
                        scalar_data = scalar_data * scale + offset
                        scalar_xdata_list.append(DataAndMetadata.new_data_and_metadata(scalar_data, scalar_intensity_calibration, scalar_dimensional_calibrations))
                else:
                    scalar_xdata_list.append(None)
            return scalar_xdata_list

        data_scale = self.__data_scale
        xdata_list = self.__xdata_list

        if data_scale is not None:
            # update the line graph data
            left_channel = left_channel if left_channel is not None else 0
            right_channel = right_channel if right_channel is not None else data_scale
            left_channel, right_channel = min(left_channel, right_channel), max(left_channel, right_channel)

            scalar_data_list = None
            if y_min is None or y_max is None and len(xdata_list) > 0:
                scalar_xdata_list = calculate_scalar_xdata(xdata_list)
                scalar_data_list = [xdata.data if xdata else None for xdata in scalar_xdata_list]
            calibrated_data_min, calibrated_data_max, y_ticker = LineGraphCanvasItem.calculate_y_axis(scalar_data_list, y_min, y_max, intensity_calibration, y_style)
            axes = LineGraphCanvasItem.LineGraphAxes(data_scale, calibrated_data_min, calibrated_data_max, left_channel, right_channel, displayed_dimensional_calibration, intensity_calibration, y_style, y_ticker)

            if scalar_xdata_list is None:
                if len(xdata_list) > 0:
                    scalar_xdata_list = calculate_scalar_xdata(xdata_list)
                else:
                    scalar_xdata_list = list()

            if self.__display_frame_rate_id:
                Utility.fps_tick("prepare_"+self.__display_frame_rate_id)

            colors = ('#1E90FF', "#F00", "#0F0", "#00F", "#FF0", "#0FF", "#F0F", "#888", "#800", "#080", "#008", "#CCC", "#880", "#088", "#808", "#964B00")

            display_layers = self.__display_layers

            if len(display_layers) == 0:
                index = 0
                for scalar_index, scalar_xdata in enumerate(scalar_xdata_list):
                    if scalar_xdata and scalar_xdata.is_data_1d:
                        if index < 16:
                            display_layers.append({"fill_color": colors[index] if index == 0 else None, "stroke_color": colors[index] if index > 0 else None, "data_index": scalar_index})
                            index += 1
                    if scalar_xdata and scalar_xdata.is_data_2d:
                        for row in range(min(scalar_xdata.data_shape[-1], 16)):
                            if index < 16:
                                display_layers.append({"fill_color": colors[index] if index == 0 else None, "stroke_color": colors[index] if index > 0 else None, "data_index": scalar_index, "data_row": row})
                                index += 1

            display_layer_count = len(display_layers)

            self.___has_valid_drawn_graph_data = False

            for index, display_layer in enumerate(display_layers):
                if index < 16:
                    fill_color = display_layer.get("fill_color")
                    stroke_color = display_layer.get("stroke_color")
                    data_index = display_layer.get("data_index", 0)
                    data_row = display_layer.get("data_row", 0)
                    if 0 <= data_index < len(scalar_xdata_list):
                        scalar_xdata = scalar_xdata_list[data_index]
                        if scalar_xdata:
                            data_row = max(0, min(scalar_xdata.dimensional_shape[0] - 1, data_row))
                            intensity_calibration = scalar_xdata.intensity_calibration
                            displayed_dimensional_calibration = scalar_xdata.dimensional_calibrations[-1]
                            if scalar_xdata.is_data_2d:
                                scalar_data = scalar_xdata.data[data_row:data_row + 1, :].reshape((scalar_xdata.dimensional_shape[-1],))
                                scalar_xdata = DataAndMetadata.new_data_and_metadata(scalar_data, intensity_calibration, [displayed_dimensional_calibration])
                        line_graph_canvas_item = self.__line_graph_stack.canvas_items[display_layer_count - (index + 1)]
                        line_graph_canvas_item.set_fill_color(fill_color)
                        line_graph_canvas_item.set_stroke_color(stroke_color)
                        line_graph_canvas_item.set_axes(axes)
                        line_graph_canvas_item.set_uncalibrated_xdata(scalar_xdata)
                        self.___has_valid_drawn_graph_data = scalar_xdata is not None

            for index in range(len(display_layers), 16):
                line_graph_canvas_item = self.__line_graph_stack.canvas_items[index]
                line_graph_canvas_item.set_axes(None)
                line_graph_canvas_item.set_uncalibrated_xdata(None)

            legend_position = self.__legend_position
            LegendEntry = collections.namedtuple("LegendEntry", ["label", "fill_color", "stroke_color"])
            legend_entries = list()
            for index, display_layer in enumerate(self.__display_layers):
                data_index = display_layer.get("data_index", None)
                data_row = display_layer.get("data_row", None)
                label = display_layer.get("label", str())
                if not label:
                    if data_index is not None and data_row is not None:
                        label = "Data {}:{}".format(data_index, data_row)
                    elif data_index is not None:
                        label = "Data {}".format(data_index)
                    else:
                        label = "Unknown"
                fill_color = display_layer.get("fill_color")
                stroke_color = display_layer.get("stroke_color")
                legend_entries.append(LegendEntry(label, fill_color, stroke_color))

            self.__update_canvas_items(axes, legend_position, legend_entries)
        else:
            for line_graph_canvas_item in self.__line_graph_stack.canvas_items:
                line_graph_canvas_item.set_axes(None)
                line_graph_canvas_item.set_uncalibrated_xdata(None)
            self.__line_graph_xdata_list = list()
            self.__update_canvas_items(LineGraphCanvasItem.LineGraphAxes(), None, None)


Instruction:
Write a Python 3 script to
map the mouse to the 1 - d position within the line graph.

Response:
def __update_cursor_info(self):
        """ Map the mouse to the 1-d position within the line graph. """

        if not self.delegate:  # allow display to work without delegate
            return

        if self.__mouse_in and self.__last_mouse:
            pos_1d = None
            axes = self.__axes
            line_graph_canvas_item = self.line_graph_canvas_item
            if axes and axes.is_valid and line_graph_canvas_item:
                mouse = self.map_to_canvas_item(self.__last_mouse, line_graph_canvas_item)
                plot_rect = line_graph_canvas_item.canvas_bounds
                if plot_rect.contains_point(mouse):
                    mouse = mouse - plot_rect.origin
                    x = float(mouse.x) / plot_rect.width
                    px = axes.drawn_left_channel + x * (axes.drawn_right_channel - axes.drawn_left_channel)
                    pos_1d = px,
            self.delegate.cursor_changed(pos_1d)


Instruction:
Can you generate the documentation for the following Python 3 function
def find_model_patch_tracks(self):
        self.model_grid.load_data()
        tracked_model_objects = []
        model_objects = []
        if self.model_grid.data is None:
            print("No model output found")
            return tracked_model_objects
        min_orig = self.model_ew.min_thresh
        max_orig = self.model_ew.max_thresh
        data_increment_orig = self.model_ew.data_increment
        self.model_ew.min_thresh = 0
        self.model_ew.data_increment = 1
        self.model_ew.max_thresh = 100
        for h, hour in enumerate(self.hours):
            # Identify storms at each time step and apply size filter
            print("Finding {0} objects for run {1} Hour: {2:02d}".format(self.ensemble_member,
                                                                         self.run_date.strftime("%Y%m%d%H"), hour))
            if self.mask is not None:
                model_data = self.model_grid.data[h] * self.mask
            else:
                model_data = self.model_grid.data[h]
            model_data[:self.patch_radius] = 0
            model_data[-self.patch_radius:] = 0
            model_data[:, :self.patch_radius] = 0
            model_data[:, -self.patch_radius:] = 0
            scaled_data = np.array(rescale_data(model_data, min_orig, max_orig))
            hour_labels = label_storm_objects(scaled_data, "ew",
                                              self.model_ew.min_thresh, self.model_ew.max_thresh,
                                              min_area=self.size_filter, max_area=self.model_ew.max_size,
                                              max_range=self.model_ew.delta, increment=self.model_ew.data_increment,
                                              gaussian_sd=self.gaussian_window)
            model_objects.extend(extract_storm_patches(hour_labels, model_data, self.model_grid.x,
                                                       self.model_grid.y, [hour],
                                                       dx=self.model_grid.dx,
                                                       patch_radius=self.patch_radius))
            for model_obj in model_objects[-1]:
                dims = model_obj.timesteps[-1].shape
                if h > 0:
                    model_obj.estimate_motion(hour, self.model_grid.data[h-1], dims[1], dims[0])
            del scaled_data
            del model_data
            del hour_labels
        tracked_model_objects.extend(track_storms(model_objects, self.hours,
                                                  self.object_matcher.cost_function_components,
                                                  self.object_matcher.max_values,
                                                  self.object_matcher.weights))
        self.model_ew.min_thresh = min_orig
        self.model_ew.max_thresh = max_orig
        self.model_ew.data_increment = data_increment_orig
        return tracked_model_objects

Response: Finds all model patches in the gridded model output and extracts uniform sized patches around the storm centers of mass.


Instruction:
How would you explain what the following Python 3 function does
def find_model_tracks(self):
        self.model_grid.load_data()
        model_objects = []
        tracked_model_objects = []
        if self.model_grid.data is None:
            print("No model output found")
            return tracked_model_objects
        for h, hour in enumerate(self.hours):
            # Identify storms at each time step and apply size filter
            print("Finding {0} objects for run {1} Hour: {2:02d}".format(self.ensemble_member,
                                                                         self.run_date.strftime("%Y%m%d%H"), hour))
            if self.mask is not None:
                model_data = self.model_grid.data[h] * self.mask
            else:
                model_data = self.model_grid.data[h]

            # remember orig values
            min_orig = self.model_ew.min_thresh
            max_orig = self.model_ew.max_thresh
            data_increment_orig = self.model_ew.data_increment
            # scale to int 0-100.
            scaled_data = np.array(rescale_data( self.model_grid.data[h], min_orig, max_orig))
            self.model_ew.min_thresh = 0
            self.model_ew.data_increment = 1
            self.model_ew.max_thresh = 100
            hour_labels = self.model_ew.label(gaussian_filter(scaled_data, self.gaussian_window))
            hour_labels[model_data < self.model_ew.min_thresh] = 0
            hour_labels = self.model_ew.size_filter(hour_labels, self.size_filter)
            # Return to orig values
            self.model_ew.min_thresh = min_orig
            self.model_ew.max_thresh = max_orig
            self.model_ew.data_increment = data_increment_orig
            obj_slices = find_objects(hour_labels)

            num_slices = len(obj_slices)
            model_objects.append([])
            if num_slices > 0:
                for s, sl in enumerate(obj_slices):
                    model_objects[-1].append(STObject(self.model_grid.data[h][sl],
                                                      np.where(hour_labels[sl] == s + 1, 1, 0),
                                                      self.model_grid.x[sl],
                                                      self.model_grid.y[sl],
                                                      self.model_grid.i[sl],
                                                      self.model_grid.j[sl],
                                                      hour,
                                                      hour,
                                                      dx=self.model_grid.dx))
                    if h > 0:
                        dims = model_objects[-1][-1].timesteps[0].shape
                        model_objects[-1][-1].estimate_motion(hour, self.model_grid.data[h-1], dims[1], dims[0])
            del hour_labels
            del scaled_data
            del model_data
        for h, hour in enumerate(self.hours):
            past_time_objs = []
            for obj in tracked_model_objects:
                # Potential trackable objects are identified
                if obj.end_time == hour - 1:
                    past_time_objs.append(obj)
            # If no objects existed in the last time step, then consider objects in current time step all new
            if len(past_time_objs) == 0:
                tracked_model_objects.extend(model_objects[h])
            # Match from previous time step with current time step
            elif len(past_time_objs) > 0 and len(model_objects[h]) > 0:
                assignments = self.object_matcher.match_objects(past_time_objs, model_objects[h], hour - 1, hour)
                unpaired = list(range(len(model_objects[h])))
                for pair in assignments:
                    past_time_objs[pair[0]].extend(model_objects[h][pair[1]])
                    unpaired.remove(pair[1])
                if len(unpaired) > 0:
                    for up in unpaired:
                        tracked_model_objects.append(model_objects[h][up])
            print("Tracked Model Objects: {0:03d} Hour: {1:02d}".format(len(tracked_model_objects), hour))

        return tracked_model_objects

Response: Finds model tracks at each model time step and links them together with object matching.


Instruction:
Write a Python 3 script for
finding MESH tracks from MRMS timesteps and links them together with object matching.

Response:
def find_mrms_tracks(self):
        """
        Identify objects from MRMS timesteps and link them together with object matching.

        Returns:
            List of STObjects containing MESH track information.
        """
        obs_objects = []
        tracked_obs_objects = []
        if self.mrms_ew is not None:
            self.mrms_grid.load_data()

            if len(self.mrms_grid.data) != len(self.hours):
                print('Less than 24 hours of observation data found')

                return tracked_obs_objects

            for h, hour in enumerate(self.hours):
                mrms_data = np.zeros(self.mrms_grid.data[h].shape)
                mrms_data[:] = np.array(self.mrms_grid.data[h])
                mrms_data[mrms_data < 0] = 0
                hour_labels = self.mrms_ew.size_filter(self.mrms_ew.label(gaussian_filter(mrms_data,
                                                                                self.gaussian_window)),
                                                       self.size_filter)
                hour_labels[mrms_data < self.mrms_ew.min_thresh] = 0
                obj_slices = find_objects(hour_labels)
                num_slices = len(obj_slices)
                obs_objects.append([])
                if num_slices > 0:
                    for sl in obj_slices:
                        obs_objects[-1].append(STObject(mrms_data[sl],
                                                        np.where(hour_labels[sl] > 0, 1, 0),
                                                        self.model_grid.x[sl],
                                                        self.model_grid.y[sl],
                                                        self.model_grid.i[sl],
                                                        self.model_grid.j[sl],
                                                        hour,
                                                        hour,
                                                        dx=self.model_grid.dx))
                        if h > 0:
                            dims = obs_objects[-1][-1].timesteps[0].shape
                            obs_objects[-1][-1].estimate_motion(hour, self.mrms_grid.data[h-1], dims[1], dims[0])

            for h, hour in enumerate(self.hours):
                past_time_objs = []
                for obj in tracked_obs_objects:
                    if obj.end_time == hour - 1:
                        past_time_objs.append(obj)
                if len(past_time_objs) == 0:
                    tracked_obs_objects.extend(obs_objects[h])
                elif len(past_time_objs) > 0 and len(obs_objects[h]) > 0:
                    assignments = self.object_matcher.match_objects(past_time_objs, obs_objects[h], hour - 1, hour)
                    unpaired = list(range(len(obs_objects[h])))
                    for pair in assignments:
                        past_time_objs[pair[0]].extend(obs_objects[h][pair[1]])
                        unpaired.remove(pair[1])
                    if len(unpaired) > 0:
                        for up in unpaired:
                            tracked_obs_objects.append(obs_objects[h][up])
                print("Tracked Obs Objects: {0:03d} Hour: {1:02d}".format(len(tracked_obs_objects), hour))

        return tracked_obs_objects


Instruction:
How would you explain what the following Python 3 function does
def match_tracks(self, model_tracks, obs_tracks, unique_matches=True, closest_matches=False):
        if unique_matches:
            pairings = self.track_matcher.match_tracks(model_tracks, obs_tracks, closest_matches=closest_matches)
        else:
            pairings = self.track_matcher.neighbor_matches(model_tracks, obs_tracks)
        return pairings

Response: Match forecast and observed tracks.


Instruction:
Implement a function in Python 3 to
extract model attribute data for each model track.

Response:
def extract_model_attributes(self, tracked_model_objects, storm_variables, potential_variables,
                                 tendency_variables=None, future_variables=None):
        """
        Extract model attribute data for each model track. Storm variables are those that describe the model storm
        directly, such as radar reflectivity or updraft helicity. Potential variables describe the surrounding
        environmental conditions of the storm, and should be extracted from the timestep before the storm arrives to
        reduce the chance of the storm contaminating the environmental values. Examples of potential variables include
        CAPE, shear, temperature, and dewpoint. Future variables are fields that occur in the hour after the extracted
        field.

        Args:
            tracked_model_objects: List of STObjects describing each forecasted storm
            storm_variables: List of storm variable names
            potential_variables: List of potential variable names.
            tendency_variables: List of tendency variables
        """
        if tendency_variables is None:
            tendency_variables = []
        if future_variables is None:
            future_variables = []
        model_grids = {}
        for l_var in ["lon", "lat"]:
            for model_obj in tracked_model_objects:
                model_obj.extract_attribute_array(getattr(self.model_grid, l_var), l_var)
        for storm_var in storm_variables:
            print("Storm {0} {1} {2}".format(storm_var,self.ensemble_member, self.run_date.strftime("%Y%m%d")))
            model_grids[storm_var] = ModelOutput(self.ensemble_name, self.ensemble_member,
                                                 self.run_date, storm_var, self.start_date - timedelta(hours=1),
                                                 self.end_date + timedelta(hours=1),
                                                 self.model_path,self.model_map_file,
                                                 self.sector_ind_path,self.single_step)
            model_grids[storm_var].load_data()
            for model_obj in tracked_model_objects:
                model_obj.extract_attribute_grid(model_grids[storm_var])
            if storm_var not in potential_variables + tendency_variables + future_variables:
                del model_grids[storm_var]
        for potential_var in potential_variables:
            print("Potential {0} {1} {2}".format(potential_var,self.ensemble_member, self.run_date.strftime("%Y%m%d")))
            if potential_var not in model_grids.keys():
                model_grids[potential_var] = ModelOutput(self.ensemble_name, self.ensemble_member,
                                                         self.run_date, potential_var,
                                                         self.start_date - timedelta(hours=1),
                                                         self.end_date + timedelta(hours=1),
                                                         self.model_path, self.model_map_file,
                                                         self.sector_ind_path,self.single_step)
                model_grids[potential_var].load_data()
            for model_obj in tracked_model_objects:
                model_obj.extract_attribute_grid(model_grids[potential_var], potential=True)
            if potential_var not in tendency_variables + future_variables:
                del model_grids[potential_var]
        for future_var in future_variables:
            print("Future {0} {1} {2}".format(future_var, self.ensemble_member, self.run_date.strftime("%Y%m%d")))
            if future_var not in model_grids.keys():
                model_grids[future_var] = ModelOutput(self.ensemble_name, self.ensemble_member,
                                                         self.run_date, future_var,
                                                         self.start_date - timedelta(hours=1),
                                                         self.end_date + timedelta(hours=1),
                                                         self.model_path, self.model_map_file,
                                                         self.sector_ind_path,self.single_step)
                model_grids[future_var].load_data()
            for model_obj in tracked_model_objects:
                model_obj.extract_attribute_grid(model_grids[future_var], future=True)
            if future_var not in tendency_variables:
                del model_grids[future_var]
        for tendency_var in tendency_variables:
            print("Tendency {0} {1} {2}".format(tendency_var, self.ensemble_member, self.run_date.strftime("%Y%m%d")))
            if tendency_var not in model_grids.keys():
                model_grids[tendency_var] = ModelOutput(self.ensemble_name, self.ensemble_member,
                                                        self.run_date, tendency_var,
                                                        self.start_date - timedelta(hours=1),
                                                        self.end_date,
                                                        self.model_path, self.model_map_file,
                                                        self.sector_ind_path,self.single_step)
            for model_obj in tracked_model_objects:
                model_obj.extract_tendency_grid(model_grids[tendency_var])
            del model_grids[tendency_var]


Instruction:
Can you generate the documentation for the following Python 3 function
def match_hail_sizes(model_tracks, obs_tracks, track_pairings):
        unpaired = list(range(len(model_tracks)))
        for p, pair in enumerate(track_pairings):
            model_track = model_tracks[pair[0]]
            unpaired.remove(pair[0])
            obs_track = obs_tracks[pair[1]]
            obs_hail_sizes = np.array([step[obs_track.masks[t] == 1].max()
                                       for t, step in enumerate(obs_track.timesteps)])
            if obs_track.times.size > 1 and model_track.times.size > 1:
                normalized_obs_times = 1.0 / (obs_track.times.max() - obs_track.times.min())\
                    * (obs_track.times - obs_track.times.min())
                normalized_model_times = 1.0 / (model_track.times.max() - model_track.times.min())\
                    * (model_track.times - model_track.times.min())
                hail_interp = interp1d(normalized_obs_times, obs_hail_sizes, kind="nearest",
                                       bounds_error=False, fill_value=0)
                model_track.observations = hail_interp(normalized_model_times)
            elif obs_track.times.size == 1:
                model_track.observations = np.ones(model_track.times.shape) * obs_hail_sizes[0]
            elif model_track.times.size == 1:
                model_track.observations = np.array([obs_hail_sizes.max()])
            print(pair[0], "obs",  obs_hail_sizes)
            print(pair[0], "model", model_track.observations)
        for u in unpaired:
            model_tracks[u].observations = np.zeros(model_tracks[u].times.shape)

Response: This function matches the maximum hail sizes of the model and observed tracks.


Instruction:
How would you explain what the following Python 3 function does
def calc_track_errors(model_tracks, obs_tracks, track_pairings):
        columns = ['obs_track_id',
                   'translation_error_x',
                   'translation_error_y',
                   'start_time_difference',
                   'end_time_difference',
                   ]
        track_errors = pd.DataFrame(index=list(range(len(model_tracks))),
                                    columns=columns)
        for p, pair in enumerate(track_pairings):
            model_track = model_tracks[pair[0]]
            if type(pair[1]) in [int, np.int64]:
                obs_track = obs_tracks[pair[1]]
            else:
                obs_track = obs_tracks[pair[1][0]]
            model_com = model_track.center_of_mass(model_track.start_time)
            obs_com = obs_track.center_of_mass(obs_track.start_time)
            track_errors.loc[pair[0], 'obs_track_id'] = pair[1] if type(pair[1]) in [int, np.int64] else pair[1][0]
            track_errors.loc[pair[0], 'translation_error_x'] = model_com[0] - obs_com[0]
            track_errors.loc[pair[0], 'translation_error_y'] = model_com[1] - obs_com[1]
            track_errors.loc[pair[0], 'start_time_difference'] = model_track.start_time - obs_track.start_time
            track_errors.loc[pair[0], 'end_time_difference'] = model_track.end_time - obs_track.end_time
        return track_errors

Response:
Calculates spatial and temporal translation errors between matched
            forecast and observed tracks.


Instruction:
Can you implement a function in Python 3 that
overrides from PersistentObject. persistent_object_context_changed

Response:
def persistent_object_context_changed(self):
        """ Override from PersistentObject. """
        super().persistent_object_context_changed()

        def register():
            if self.__source is not None and self.__target is not None:
                assert not self.__binding
                self.__binding = Binding.PropertyBinding(self.__source, self.source_property)
                self.__binding.target_setter = self.__set_target_from_source
                # while reading, the data item in the display data channel will not be connected;
                # we still set its value here. when the data item becomes valid, it will update.
                self.__binding.update_target_direct(self.__binding.get_target_value())

        def source_registered(source):
            self.__source = source
            register()

        def target_registered(target):
            self.__target = target

            def property_changed(target, property_name):
                if property_name == self.target_property:
                    self.__set_source_from_target(getattr(target, property_name))

            assert self.__target_property_changed_listener is None
            self.__target_property_changed_listener = target.property_changed_event.listen(functools.partial(property_changed, target))
            register()

        def unregistered(item=None):
            if not item or item == self.__source:
                self.__source = None
            if not item or item == self.__target:
                self.__target = None
            if self.__binding:
                self.__binding.close()
                self.__binding = None
            if self.__target_property_changed_listener:
                self.__target_property_changed_listener.close()
                self.__target_property_changed_listener = None

        def change_registration(registered_object, unregistered_object):
            if registered_object and registered_object.uuid == self.source_uuid:
                source_registered(registered_object)
            if registered_object and registered_object.uuid == self.target_uuid:
                target_registered(registered_object)
            if unregistered_object and unregistered_object in (self._source, self._target):
                unregistered(unregistered_object)

        if self.persistent_object_context:
            self.__registration_listener = self.persistent_object_context.registration_event.listen(change_registration)
            source = self.persistent_object_context.get_registered_object(self.source_uuid)
            target = self.persistent_object_context.get_registered_object(self.target_uuid)
            if source:
                source_registered(source)
            if target:
                target_registered(target)
        else:
            unregistered()


Instruction:
Implement a Python 3 function for
calling by the persistent object when the context of the current object has changed.

Response:
def persistent_object_context_changed(self):
        """ Override from PersistentObject. """
        super().persistent_object_context_changed()

        def detach():
            for listener in self.__interval_mutated_listeners:
                listener.close()
            self.__interval_mutated_listeners = list()

        def reattach():
            detach()
            interval_descriptors = list()
            if self.__source:
                for region in self.__source.graphics:
                    if isinstance(region, Graphics.IntervalGraphic):
                        interval_descriptor = {"interval": region.interval, "color": "#F00"}
                        interval_descriptors.append(interval_descriptor)
                        self.__interval_mutated_listeners.append(region.property_changed_event.listen(lambda k: reattach()))
            if self.__target:
                self.__target.interval_descriptors = interval_descriptors

        def item_inserted(key, value, before_index):
            if key == "graphics" and self.__target:
                reattach()

        def item_removed(key, value, index):
            if key == "graphics" and self.__target:
                reattach()

        def source_registered(source):
            self.__source = source
            self.__item_inserted_event_listener = self.__source.item_inserted_event.listen(item_inserted)
            self.__item_removed_event_listener = self.__source.item_removed_event.listen(item_removed)
            reattach()

        def target_registered(target):
            self.__target = target
            reattach()

        def unregistered(source=None):
            if self.__item_inserted_event_listener:
                self.__item_inserted_event_listener.close()
                self.__item_inserted_event_listener = None
            if self.__item_removed_event_listener:
                self.__item_removed_event_listener.close()
                self.__item_removed_event_listener = None

        if self.persistent_object_context:
            self.persistent_object_context.subscribe(self.source_uuid, source_registered, unregistered)
            self.persistent_object_context.subscribe(self.target_uuid, target_registered, unregistered)
        else:
            unregistered()


Instruction:
Make a summary of the following Python 3 code
def __display_for_tree_node(self, tree_node):
        keys = tree_node.keys
        if len(keys) == 1:
            return "{0} ({1})".format(tree_node.keys[-1], tree_node.count)
        elif len(keys) == 2:
            months = (_("January"), _("February"), _("March"), _("April"), _("May"), _("June"), _("July"), _("August"),
                      _("September"), _("October"), _("November"), _("December"))
            return "{0} ({1})".format(months[max(min(tree_node.keys[1]-1, 11), 0)], tree_node.count)
        else:
            weekdays = (_("Monday"), _("Tuesday"), _("Wednesday"), _("Thursday"), _("Friday"), _("Saturday"), _("Sunday"))
            date = datetime.date(tree_node.keys[0], tree_node.keys[1], tree_node.keys[2])
            return "{0} - {1} ({2})".format(tree_node.keys[2], weekdays[date.weekday()], tree_node.count)

Response: Return the text display for the given tree node.


Instruction:
Write a Python 3 script to
insert a new child node into the item model controller.

Response:
def __insert_child(self, parent_tree_node, index, tree_node):
        """
            Called from the root tree node when a new node is inserted into tree. This method creates properties
            to represent the node for display and inserts it into the item model controller.
        """
        # manage the item model
        parent_item = self.__mapping[id(parent_tree_node)]
        self.item_model_controller.begin_insert(index, index, parent_item.row, parent_item.id)
        properties = {
            "display": self.__display_for_tree_node(tree_node),
            "tree_node": tree_node  # used for removal and other lookup
        }
        item = self.item_model_controller.create_item(properties)
        parent_item.insert_child(index, item)
        self.__mapping[id(tree_node)] = item
        self.item_model_controller.end_insert()


Instruction:
Can you tell what is the following Python 3 function doing
def __remove_child(self, parent_tree_node, index):
        # get parent and item
        parent_item = self.__mapping[id(parent_tree_node)]
        # manage the item model
        self.item_model_controller.begin_remove(index, index, parent_item.row, parent_item.id)
        child_item = parent_item.children[index]
        parent_item.remove_child(child_item)
        self.__mapping.pop(id(child_item.data["tree_node"]))
        self.item_model_controller.end_remove()

Response: This method removes a child from the tree node.


Instruction:
Can you write a function in Python 3 where it
updates all tree item displays if needed. Usually for count updates.

Response:
def update_all_nodes(self):
        """ Update all tree item displays if needed. Usually for count updates. """
        item_model_controller = self.item_model_controller
        if item_model_controller:
            if self.__node_counts_dirty:
                for item in self.__mapping.values():
                    if "tree_node" in item.data:  # don't update the root node
                        tree_node = item.data["tree_node"]
                        item.data["display"] = self.__display_for_tree_node(tree_node)
                        item_model_controller.data_changed(item.row, item.parent.row, item.parent.id)
                self.__node_counts_dirty = False


Instruction:
Create a Python 3 function to
call by the browser when the selected items of the tree item is changed.

Response:
def date_browser_selection_changed(self, selected_indexes):
        """
            Called to handle selection changes in the tree widget.

            This method should be connected to the on_selection_changed event. This method builds a list
            of keys represented by all selected items. It then provides date_filter to filter data items
            based on the list of keys. It then sets the filter into the document controller.

            :param selected_indexes: The selected indexes
            :type selected_indexes: list of ints
        """
        partial_date_filters = list()

        for index, parent_row, parent_id in selected_indexes:
            item_model_controller = self.item_model_controller
            tree_node = item_model_controller.item_value("tree_node", index, parent_id)
            partial_date_filters.append(ListModel.PartialDateFilter("created_local", *tree_node.keys))

        if len(partial_date_filters) > 0:
            self.__date_filter = ListModel.OrFilter(partial_date_filters)
        else:
            self.__date_filter = None

        self.__update_filter()


Instruction:
How would you explain what the following Python 3 function does
def text_filter_changed(self, text):
        text = text.strip() if text else None

        if text is not None:
            self.__text_filter = ListModel.TextFilter("text_for_filter", text)
        else:
            self.__text_filter = None

        self.__update_filter()

Response: Called to handle changes to the text filter.


Instruction:
Create a Python 3 function to
update the display filter.

Response:
def __update_filter(self):
        """
            Create a combined filter. Set the resulting filter into the document controller.
        """
        filters = list()
        if self.__date_filter:
            filters.append(self.__date_filter)
        if self.__text_filter:
            filters.append(self.__text_filter)
        self.document_controller.display_filter = ListModel.AndFilter(filters)


Instruction:
Write a Python 3 function that can
return the keys associated with this node.

Response:
def __get_keys(self):
        """ Return the keys associated with this node by adding its key and then adding parent keys recursively. """
        keys = list()
        tree_node = self
        while tree_node is not None and tree_node.key is not None:
            keys.insert(0, tree_node.key)
            tree_node = tree_node.parent
        return keys


Instruction:
How would you explain what the following Python 3 function does
def insert_value(self, keys, value):
        self.count += 1
        if not self.key:
            self.__value_reverse_mapping[value] = keys
        if len(keys) == 0:
            self.values.append(value)
        else:
            key = keys[0]
            index = bisect.bisect_left(self.children, TreeNode(key, reversed=self.reversed))
            if index == len(self.children) or self.children[index].key != key:
                new_tree_node = TreeNode(key, list(), reversed=self.reversed)
                new_tree_node.child_inserted = self.child_inserted
                new_tree_node.child_removed = self.child_removed
                new_tree_node.tree_node_updated = self.tree_node_updated
                new_tree_node.__set_parent(self)
                self.children.insert(index, new_tree_node)
                if self.child_inserted:
                    self.child_inserted(self, index, new_tree_node)
            child = self.children[index]
            child.insert_value(keys[1:], value)
            if self.tree_node_updated:
                self.tree_node_updated(child)

Response: Insert a value into this tree node and its children.


Instruction:
How would you implement a function in Python 3 that
removes a value from this tree node and its children.

Response:
def remove_value(self, keys, value):
        """
            Remove a value (data item) from this tree node and its children.
            Also updates the tree node's cumulative child count.
        """
        self.count -= 1
        if not self.key:
            keys = self.__value_reverse_mapping[value]
            del self.__value_reverse_mapping[value]
        if len(keys) == 0:
            self.values.remove(value)
        else:
            key = keys[0]
            index = bisect.bisect_left(self.children, TreeNode(key, reversed=self.reversed))
            assert index != len(self.children) and self.children[index].key == key
            self.children[index].remove_value(keys[1:], value)
            if self.tree_node_updated:
                self.tree_node_updated(self.children[index])
            if self.children[index].count == 0:
                del self.children[index]
                if self.child_removed:
                    self.child_removed(self, index)


Instruction:
How would you implement a function in Python 3 that
gives the output of extract_storm_objects this method tracks storms through time and merges them into a single set of tracks.

Response:
def track_storms(storm_objects, times, distance_components, distance_maxima, distance_weights, tracked_objects=None):
    """
    Given the output of extract_storm_objects, this method tracks storms through time and merges individual
    STObjects into a set of tracks.

    Args:
        storm_objects: list of list of STObjects that have not been tracked.
        times: List of times associated with each set of STObjects
        distance_components: list of function objects that make up components of distance function
        distance_maxima: array of maximum values for each distance for normalization purposes
        distance_weights: weight given to each component of the distance function. Should add to 1.
        tracked_objects: List of STObjects that have already been tracked.
    Returns:
        tracked_objects:
    """
    obj_matcher = ObjectMatcher(distance_components, distance_weights, distance_maxima)
    if tracked_objects is None:
        tracked_objects = []
    for t, time in enumerate(times):
        past_time_objects = []
        for obj in tracked_objects:
            if obj.end_time == time - obj.step:
                past_time_objects.append(obj)
        if len(past_time_objects) == 0:
            tracked_objects.extend(storm_objects[t])
        elif len(past_time_objects) > 0 and len(storm_objects[t]) > 0:
            assignments = obj_matcher.match_objects(past_time_objects, storm_objects[t], times[t-1], times[t])
            unpaired = list(range(len(storm_objects[t])))
            for pair in assignments:
                past_time_objects[pair[0]].extend(storm_objects[t][pair[1]])
                unpaired.remove(pair[1])
            if len(unpaired) > 0:
                for up in unpaired:
                    tracked_objects.append(storm_objects[t][up])
    return tracked_objects


Instruction:
Make a summary of the following Python 3 code
def peirce_skill_score(self):
        n = float(self.table.sum())
        nf = self.table.sum(axis=1)
        no = self.table.sum(axis=0)
        correct = float(self.table.trace())
        return (correct / n - (nf * no).sum() / n ** 2) / (1 - (no * no).sum() / n ** 2)

Response: Multiclass Peirce Skill Score


Instruction:
Can you tell what is the following Python 3 function doing
def shifted_centroid_distance(item_a, time_a, item_b, time_b, max_value):
    ax, ay = item_a.center_of_mass(time_a)
    bx, by = item_b.center_of_mass(time_b)
    if time_a < time_b:
        bx = bx - item_b.u
        by = by - item_b.v
    else:
        ax = ax - item_a.u
        ay = ay - item_a.v
    return np.minimum(np.sqrt((ax - bx) ** 2 + (ay - by) ** 2), max_value) / float(max_value)

Response: Calculate the shifted centroid distance between two objects.


Instruction:
Explain what the following Python 3 code does
def ellipse_distance(item_a, time_a, item_b, time_b, max_value):
    ts = np.array([0, np.pi])
    ell_a = item_a.get_ellipse_model(time_a)
    ell_b = item_b.get_ellipse_model(time_b)
    ends_a = ell_a.predict_xy(ts)
    ends_b = ell_b.predict_xy(ts)
    distances = np.sqrt((ends_a[:, 0:1] - ends_b[:, 0:1].T) ** 2 + (ends_a[:, 1:] - ends_b[:, 1:].T) ** 2)
    return np.minimum(distances[0, 1], max_value) / float(max_value)

Response: Calculates the distance between two objects in the object matcher.


Instruction:
Write a Python 3 function for
returning the percentage of pixels in each object that do not overlap with the other object

Response:
def nonoverlap(item_a, time_a, item_b, time_b, max_value):
    """
    Percentage of pixels in each object that do not overlap with the other object

    Args:
        item_a: STObject from the first set in ObjectMatcher
        time_a: Time integer being evaluated
        item_b: STObject from the second set in ObjectMatcher
        time_b: Time integer being evaluated
        max_value: Maximum distance value used as scaling value and upper constraint.

    Returns:
        Distance value between 0 and 1.
    """
    return np.minimum(1 - item_a.count_overlap(time_a, item_b, time_b), max_value) / float(max_value)


Instruction:
Can you tell what is the following Python 3 function doing
def max_intensity(item_a, time_a, item_b, time_b, max_value):
    intensity_a = item_a.max_intensity(time_a)
    intensity_b = item_b.max_intensity(time_b)
    diff = np.sqrt((intensity_a - intensity_b) ** 2)
    return np.minimum(diff, max_value) / float(max_value)

Response: Function that calculates the RMS difference in maximum intensity between two objects.


Instruction:
Explain what the following Python 3 code does
def mean_min_time_distance(item_a, item_b, max_value):
    times_a = item_a.times.reshape((item_a.times.size, 1))
    times_b = item_b.times.reshape((1, item_b.times.size))
    distance_matrix = (times_a - times_b) ** 2
    mean_min_distances = np.sqrt(distance_matrix.min(axis=0).mean() + distance_matrix.min(axis=1).mean())
    return np.minimum(mean_min_distances, max_value) / float(max_value)

Response: Calculate the mean time difference among the time steps in each object.


Instruction:
Can you implement a function in Python 3 that
returns the distance between the centroids of the first step in each object.

Response:
def start_centroid_distance(item_a, item_b, max_value):
    """
    Distance between the centroids of the first step in each object.

    Args:
        item_a: STObject from the first set in TrackMatcher
        item_b: STObject from the second set in TrackMatcher
        max_value: Maximum distance value used as scaling value and upper constraint.

    Returns:
        Distance value between 0 and 1.
    """
    start_a = item_a.center_of_mass(item_a.times[0])
    start_b = item_b.center_of_mass(item_b.times[0])
    start_distance = np.sqrt((start_a[0] - start_b[0]) ** 2 + (start_a[1] - start_b[1]) ** 2)
    return np.minimum(start_distance, max_value) / float(max_value)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def start_time_distance(item_a, item_b, max_value):
    start_time_diff = np.abs(item_a.times[0] - item_b.times[0])
    return np.minimum(start_time_diff, max_value) / float(max_value)

Response: Absolute difference between the starting times of each item.


Instruction:
Can you tell what is the following Python 3 function doing
def duration_distance(item_a, item_b, max_value):
    duration_a = item_a.times.size
    duration_b = item_b.times.size
    return np.minimum(np.abs(duration_a - duration_b), max_value) / float(max_value)

Response: Absolute difference in the duration of two items


Instruction:
Write a Python 3 script to
match two sets of STObjects at particular times.

Response:
def match_objects(self, set_a, set_b, time_a, time_b):
        """
        Match two sets of objects at particular times.

        Args:
            set_a: list of STObjects
            set_b: list of STObjects
            time_a: time at which set_a is being evaluated for matching
            time_b: time at which set_b is being evaluated for matching

        Returns:
            List of tuples containing (set_a index, set_b index) for each match
        """
        costs = self.cost_matrix(set_a, set_b, time_a, time_b) * 100
        min_row_costs = costs.min(axis=1)
        min_col_costs = costs.min(axis=0)
        good_rows = np.where(min_row_costs < 100)[0]
        good_cols = np.where(min_col_costs < 100)[0]
        assignments = []
        if len(good_rows) > 0 and len(good_cols) > 0:
            munk = Munkres()
            initial_assignments = munk.compute(costs[tuple(np.meshgrid(good_rows, good_cols, indexing='ij'))].tolist())
            initial_assignments = [(good_rows[x[0]], good_cols[x[1]]) for x in initial_assignments]
            for a in initial_assignments:
                if costs[a[0], a[1]] < 100:
                    assignments.append(a)
        return assignments


Instruction:
Explain what the following Python 3 code does
def cost_matrix(self, set_a, set_b, time_a, time_b):
        costs = np.zeros((len(set_a), len(set_b)))
        for a, item_a in enumerate(set_a):
            for b, item_b in enumerate(set_b):
                costs[a, b] = self.total_cost_function(item_a, item_b, time_a, time_b)
        return costs

Response: Calculates the cost matrix between the items in set a and set b at the specified times.


Instruction:
Create a Python 3 function for
calculating total cost function between two items.

Response:
def total_cost_function(self, item_a, item_b, time_a, time_b):
        """
        Calculate total cost function between two items.

        Args:
            item_a: STObject
            item_b: STObject
            time_a: Timestep in item_a at which cost function is evaluated
            time_b: Timestep in item_b at which cost function is evaluated

        Returns:
            The total weighted distance between item_a and item_b
        """
        distances = np.zeros(len(self.weights))
        for c, component in enumerate(self.cost_function_components):
            distances[c] = component(item_a, time_a, item_b, time_b, self.max_values[c])
        total_distance = np.sum(self.weights * distances)
        return total_distance


Instruction:
Can you generate a brief explanation for the following Python 3 code
def match_tracks(self, set_a, set_b, closest_matches=False):
        costs = self.track_cost_matrix(set_a, set_b) * 100
        min_row_costs = costs.min(axis=1)
        min_col_costs = costs.min(axis=0)
        good_rows = np.where(min_row_costs < 100)[0]
        good_cols = np.where(min_col_costs < 100)[0]
        assignments = []
        if len(good_rows) > 0 and len(good_cols) > 0:
            if closest_matches:
                b_matches = costs[np.meshgrid(good_rows, good_cols, indexing='ij')].argmin(axis=1)
                a_matches = np.arange(b_matches.size)
                initial_assignments = [(good_rows[a_matches[x]], good_cols[b_matches[x]])
                                       for x in range(b_matches.size)]
            else:
                munk = Munkres()
                initial_assignments = munk.compute(costs[np.meshgrid(good_rows, good_cols, indexing='ij')].tolist())
                initial_assignments = [(good_rows[x[0]], good_cols[x[1]]) for x in initial_assignments]
            for a in initial_assignments:
                if costs[a[0], a[1]] < 100:
                    assignments.append(a)
        return assignments

Response: This function finds the optimal set of matching assignments between set a and set b.


Instruction:
Make a summary of the following Python 3 code
def match(self, set_a, set_b):
        track_step_matches = [[] * len(set_a)]

        costs = self.cost_matrix(set_a, set_b)
        valid_costs = np.all(costs < 1, axis=2)
        set_a_matches, set_b_matches = np.where(valid_costs)
        s = 0
        track_pairings = pd.DataFrame(index=np.arange(costs.shape[0]),
                                      columns=["Track", "Step", "Time", "Matched", "Pairings"], dtype=object)
        set_b_info = []
        for trb, track_b in enumerate(set_b):
            for t, time in enumerate(track_b.times):
                set_b_info.append((trb, t))
        set_b_info_arr = np.array(set_b_info, dtype=int)
        for tr, track_a in enumerate(set_a):
            for t, time in enumerate(track_a.times):
                track_pairings.loc[s, ["Track", "Step", "Time"]] = [tr, t, time]
                track_pairings.loc[s, "Matched"] = 1 if np.count_nonzero(set_a_matches == s) > 0 else 0
                if track_pairings.loc[s, "Matched"] == 1:
                    track_pairings.loc[s, "Pairings"] = set_b_info_arr[set_b_matches[set_a_matches == s]]
                else:
                    track_pairings.loc[s, "Pairings"] = np.array([])
                s += 1
        return track_pairings

Response:
Returns a pandas. DataFrame representing the number of steps in each track from set_a that meet all the cost function criteria

       .


Instruction:
Write a Python 3 function for
returning the variable specifier for this variable.

Response:
def variable_specifier(self) -> dict:
        """Return the variable specifier for this variable.

        The specifier can be used to lookup the value of this variable in a computation context.
        """
        if self.value_type is not None:
            return {"type": "variable", "version": 1, "uuid": str(self.uuid), "x-name": self.name, "x-value": self.value}
        else:
            return self.specifier


Instruction:
Make a summary of the following Python 3 code
def bound_variable(self):
        class BoundVariable:
            def __init__(self, variable):
                self.__variable = variable
                self.changed_event = Event.Event()
                self.needs_rebind_event = Event.Event()
                def property_changed(key):
                    if key == "value":
                        self.changed_event.fire()
                self.__variable_property_changed_listener = variable.property_changed_event.listen(property_changed)
            @property
            def value(self):
                return self.__variable.value
            def close(self):
                self.__variable_property_changed_listener.close()
                self.__variable_property_changed_listener = None

        return BoundVariable(self)

Response: Return an object with a value property and a changed_event.


Instruction:
Here you have a function in Python 3, explain what it does
def resolve_object_specifier(self, object_specifier, secondary_specifier=None, property_name=None, objects_model=None):
        variable = self.__computation().resolve_variable(object_specifier)
        if not variable:
            return self.__context.resolve_object_specifier(object_specifier, secondary_specifier, property_name, objects_model)
        elif variable.specifier is None:
            return variable.bound_variable
        return None

Response: Resolve the object specifier.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def parse_names(cls, expression):
        names = set()
        try:
            ast_node = ast.parse(expression, "ast")

            class Visitor(ast.NodeVisitor):
                def visit_Name(self, node):
                    names.add(node.id)

            Visitor().visit(ast_node)
        except Exception:
            pass
        return names

Response: Return the list of identifiers used in the expression.


Instruction:
Can you implement a function in Python 3 that
binds a context to this computation.

Response:
def bind(self, context) -> None:
        """Bind a context to this computation.

        The context allows the computation to convert object specifiers to actual objects.
        """

        # make a computation context based on the enclosing context.
        self.__computation_context = ComputationContext(self, context)

        # re-bind is not valid. be careful to set the computation after the data item is already in document.
        for variable in self.variables:
            assert variable.bound_item is None
        for result in self.results:
            assert result.bound_item is None

        # bind the variables
        for variable in self.variables:
            self.__bind_variable(variable)

        # bind the results
        for result in self.results:
            self.__bind_result(result)


Instruction:
Can you generate the documentation for the following Python 3 function
def enviar_dados_venda(self, dados_venda):
        retorno = super(ClienteSATLocal, self).enviar_dados_venda(dados_venda)
        return RespostaEnviarDadosVenda.analisar(retorno)

Response: Sobreza o requisição do base.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def consultar_sat(self):
        retorno = super(ClienteSATLocal, self).consultar_sat()
        return RespostaSAT.consultar_sat(retorno)

Response: Consultar a setar un objeto RespostaSAT.


Instruction:
Make a summary of the following Python 3 code
def consultar_numero_sessao(self, numero_sessao):
        retorno = super(ClienteSATLocal, self).\
                consultar_numero_sessao(numero_sessao)
        return RespostaConsultarNumeroSessao.analisar(retorno)

Response:
Sobrepõe :meth:`~satcfe.base.FuncoesSAT.consultar_numero_sessao`.

        :return: Uma resposta SAT que irá depender da sessão consultada.
        :rtype: satcfe.resposta.padrao.RespostaSAT


Instruction:
Explain what the following Python 3 code does
def configurar_interface_de_rede(self, configuracao):
        retorno = super(ClienteSATLocal, self).\
                configurar_interface_de_rede(configuracao)
        return RespostaSAT.configurar_interface_de_rede(retorno)

Response: Sobreza o configurar interface de rede.


Instruction:
Make a summary of the following Python 3 code
def associar_assinatura(self, sequencia_cnpj, assinatura_ac):
        retorno = super(ClienteSATLocal, self).\
                associar_assinatura(sequencia_cnpj, assinatura_ac)
        # (!) resposta baseada na redação com efeitos até 31-12-2016
        return RespostaSAT.associar_assinatura(retorno)

Response: Sobreve uma resposta SAT padrão.


Instruction:
Explain what the following Python 3 code does
def atualizar_software_sat(self):
        retorno = super(ClienteSATLocal, self).atualizar_software_sat()
        return RespostaSAT.atualizar_software_sat(retorno)

Response: Sobreve uma resposta SAT para o atualizar avec o tag.


Instruction:
Make a summary of the following Python 3 code
def desbloquear_sat(self):
        retorno = super(ClienteSATLocal, self).desbloquear_sat()
        return RespostaSAT.desbloquear_sat(retorno)

Response: Desbloquear un objeto SAT.


Instruction:
Write a Python 3 function that can
result no documento XML como string que pode ou não incluir a XML no início do documento.

Response:
def documento(self, *args, **kwargs):
        """Resulta no documento XML como string, que pode ou não incluir a
        declaração XML no início do documento.
        """
        forcar_unicode = kwargs.pop('forcar_unicode', False)
        incluir_xml_decl = kwargs.pop('incluir_xml_decl', True)
        doc = ET.tostring(self._xml(*args, **kwargs),
                encoding='utf-8').decode('utf-8')
        if forcar_unicode:
            if incluir_xml_decl:
                doc = u'{}\n{}'.format(constantes.XML_DECL_UNICODE, doc)
        else:
            if incluir_xml_decl:
                doc = '{}\n{}'.format(constantes.XML_DECL, unidecode(doc))
            else:
                doc = unidecode(doc)
        return doc


Instruction:
Explain what the following Python 3 code does
def start(self, skip_choose=False, fixed_workspace_dir=None):
        logging.getLogger("migration").setLevel(logging.INFO)
        if fixed_workspace_dir:
            workspace_dir = fixed_workspace_dir
        else:
            documents_dir = self.ui.get_document_location()
            workspace_dir = os.path.join(documents_dir, "Nion Swift Libraries")
            workspace_dir = self.ui.get_persistent_string("workspace_location", workspace_dir)
        welcome_message_enabled = fixed_workspace_dir is None
        profile, is_created = Profile.create_profile(pathlib.Path(workspace_dir), welcome_message_enabled, skip_choose)
        if not profile:
            self.choose_library()
            return True
        self.workspace_dir = workspace_dir
        DocumentModel.DocumentModel.computation_min_period = 0.1
        document_model = DocumentModel.DocumentModel(profile=profile)
        document_model.create_default_data_groups()
        document_model.start_dispatcher()
        # parse the hardware aliases file
        alias_path = os.path.join(self.workspace_dir, "aliases.ini")
        HardwareSource.parse_hardware_aliases_config_file(alias_path)
        # create the document controller
        document_controller = self.create_document_controller(document_model, "library")
        if self.__resources_path is not None:
            document_model.create_sample_images(self.__resources_path)
        workspace_history = self.ui.get_persistent_object("workspace_history", list())
        if workspace_dir in workspace_history:
            workspace_history.remove(workspace_dir)
        workspace_history.insert(0, workspace_dir)
        self.ui.set_persistent_object("workspace_history", workspace_history)
        self.ui.set_persistent_string("workspace_location", workspace_dir)
        if welcome_message_enabled:
            logging.info("Welcome to Nion Swift.")
        if is_created and len(document_model.display_items) > 0:
            document_controller.selected_display_panel.set_display_panel_display_item(document_model.display_items[0])
            document_controller.selected_display_panel.perform_action("set_fill_mode")
        return True

Response:
Start the application.

            Looks for workspace_location persistent string. If it doesn't find it, uses a default
            workspace location.

            Then checks to see if that workspace exists. If not and if skip_choose has not been
            set to True, asks the user for a workspace location. User may choose new folder or
            existing location. This works by putting up the dialog which will either call start
            again or exit.

            Creates workspace in location if it doesn't exist.

            Migrates database to latest version.

            Creates document model, resources path, etc.


Instruction:
Create a Python 3 function to
return a copy of this library item with any dynamic behavior made static.

Response:
def snapshot(self):
        """Return a new library item which is a copy of this one with any dynamic behavior made static."""
        data_item = self.__class__()
        # data format (temporary until moved to buffered data source)
        data_item.large_format = self.large_format
        data_item.set_data_and_metadata(copy.deepcopy(self.data_and_metadata), self.data_modified)
        # metadata
        data_item.created = self.created
        data_item.timezone = self.timezone
        data_item.timezone_offset = self.timezone_offset
        data_item.metadata = self.metadata
        data_item.title = self.title
        data_item.caption = self.caption
        data_item.description = self.description
        data_item.session_id = self.session_id
        data_item.session_data = copy.deepcopy(self.session_data)
        return data_item


Instruction:
Here you have a function in Python 3, explain what it does
def set_r_value(self, r_var: str, *, notify_changed=True) -> None:
        self.r_var = r_var
        self._description_changed()
        if notify_changed:  # set to False to set the r-value at startup; avoid marking it as a change
            self.__notify_description_changed()

Response: Used to signal changes to the ref var which are kept in document controller. ugh.


Instruction:
Can you create a Python 3 function that
sets the underlying data and metadata to the data_and_metadata.

Response:
def set_data_and_metadata(self, data_and_metadata, data_modified=None):
        """Sets the underlying data and data-metadata to the data_and_metadata.

        Note: this does not make a copy of the data.
        """
        self.increment_data_ref_count()
        try:
            if data_and_metadata:
                data = data_and_metadata.data
                data_shape_and_dtype = data_and_metadata.data_shape_and_dtype
                intensity_calibration = data_and_metadata.intensity_calibration
                dimensional_calibrations = data_and_metadata.dimensional_calibrations
                metadata = data_and_metadata.metadata
                timestamp = data_and_metadata.timestamp
                data_descriptor = data_and_metadata.data_descriptor
                timezone = data_and_metadata.timezone or Utility.get_local_timezone()
                timezone_offset = data_and_metadata.timezone_offset or Utility.TimezoneMinutesToStringConverter().convert(Utility.local_utcoffset_minutes())
                new_data_and_metadata = DataAndMetadata.DataAndMetadata(self.__load_data, data_shape_and_dtype, intensity_calibration, dimensional_calibrations, metadata, timestamp, data, data_descriptor, timezone, timezone_offset)
            else:
                new_data_and_metadata = None
            self.__set_data_metadata_direct(new_data_and_metadata, data_modified)
            if self.__data_and_metadata is not None:
                if self.persistent_object_context and not self.persistent_object_context.is_write_delayed(self):
                    self.persistent_object_context.write_external_data(self, "data", self.__data_and_metadata.data)
                    self.__data_and_metadata.unloadable = True
        finally:
            self.decrement_data_ref_count()


Instruction:
Write a Python 3 function that can
return the color map data as a uint8 ndarray with shape 256 and 3.

Response:
def color_map_data(self) -> typing.Optional[numpy.ndarray]:
        """Return the color map data as a uint8 ndarray with shape (256, 3)."""
        if self.display_data_shape is None:  # is there display data?
            return None
        else:
            return self.__color_map_data if self.__color_map_data is not None else ColorMaps.get_color_map_data_by_id("grayscale")


Instruction:
How would you code a function in Python 3 to
return the display values calculated for this item.

Response:
def get_calculated_display_values(self, immediate: bool=False) -> DisplayValues:
        """Return the display values.

        Return the current (possibly uncalculated) display values unless 'immediate' is specified.

        If 'immediate', return the existing (calculated) values if they exist. Using the 'immediate' values
        avoids calculation except in cases where the display values haven't already been calculated.
        """
        if not immediate or not self.__is_master or not self.__last_display_values:
            if not self.__current_display_values and self.__data_item:
                self.__current_display_values = DisplayValues(self.__data_item.xdata, self.sequence_index, self.collection_index, self.slice_center, self.slice_width, self.display_limits, self.complex_display_type, self.__color_map_data)

                def finalize(display_values):
                    self.__last_display_values = display_values
                    self.display_values_changed_event.fire()

                self.__current_display_values.on_finalize = finalize
            return self.__current_display_values
        return self.__last_display_values


Instruction:
Explain what the following Python 3 code does
def increment_display_ref_count(self, amount: int=1):
        display_ref_count = self.__display_ref_count
        self.__display_ref_count += amount
        if display_ref_count == 0:
            self.__is_master = True
        if self.__data_item:
            for _ in range(amount):
                self.__data_item.increment_data_ref_count()

Response: Increment the display reference count to indicate this library item is currently displayed.


Instruction:
Make a summary of the following Python 3 code
def decrement_display_ref_count(self, amount: int=1):
        assert not self._closed
        self.__display_ref_count -= amount
        if self.__display_ref_count == 0:
            self.__is_master = False
        if self.__data_item:
            for _ in range(amount):
                self.__data_item.decrement_data_ref_count()

Response: Decrement the display reference count to indicate this library item is no longer displayed.


Instruction:
Explain what the following Python 3 code does
def auto_display_limits(self):
        display_data_and_metadata = self.get_calculated_display_values(True).display_data_and_metadata
        data = display_data_and_metadata.data if display_data_and_metadata else None
        if data is not None:
            # The old algorithm was a problem during EELS where the signal data
            # is a small percentage of the overall data and was falling outside
            # the included range. This is the new simplified algorithm. Future
            # feature may allow user to select more complex algorithms.
            mn, mx = numpy.nanmin(data), numpy.nanmax(data)
            self.display_limits = mn, mx

Response: Calculate best display limits and set them.


Instruction:
How would you explain what the following Python 3 function does
def snapshot(self):
        display_item = self.__class__()
        display_item.display_type = self.display_type
        # metadata
        display_item._set_persistent_property_value("title", self._get_persistent_property_value("title"))
        display_item._set_persistent_property_value("caption", self._get_persistent_property_value("caption"))
        display_item._set_persistent_property_value("description", self._get_persistent_property_value("description"))
        display_item._set_persistent_property_value("session_id", self._get_persistent_property_value("session_id"))
        display_item._set_persistent_property_value("calibration_style_id", self._get_persistent_property_value("calibration_style_id"))
        display_item._set_persistent_property_value("display_properties", self._get_persistent_property_value("display_properties"))
        display_item.created = self.created
        for graphic in self.graphics:
            display_item.add_graphic(copy.deepcopy(graphic))
        for display_data_channel in self.display_data_channels:
            display_item.append_display_data_channel(copy.deepcopy(display_data_channel))
        # this goes after the display data channels so that the layers don't get adjusted
        display_item._set_persistent_property_value("display_layers", self._get_persistent_property_value("display_layers"))
        return display_item

Response: Return a copy of this library item with any dynamic behavior made static.


Instruction:
Can you write a function in Python 3 where it
increments the display reference count to indicate this library item is currently displayed.

Response:
def increment_display_ref_count(self, amount: int=1):
        """Increment display reference count to indicate this library item is currently displayed."""
        display_ref_count = self.__display_ref_count
        self.__display_ref_count += amount
        for display_data_channel in self.display_data_channels:
            display_data_channel.increment_display_ref_count(amount)


Instruction:
Can you tell what is the following Python 3 function doing
def decrement_display_ref_count(self, amount: int=1):
        assert not self._closed
        self.__display_ref_count -= amount
        for display_data_channel in self.display_data_channels:
            display_data_channel.decrement_display_ref_count(amount)

Response: Decrement the display reference count to indicate this library item is no longer displayed.


Instruction:
Create a Python 3 function for
removing a graphic from the container.

Response:
def remove_graphic(self, graphic: Graphics.Graphic, *, safe: bool=False) -> typing.Optional[typing.Sequence]:
        """Remove a graphic, but do it through the container, so dependencies can be tracked."""
        return self.remove_model_item(self, "graphics", graphic, safe=safe)


Instruction:
How would you code a function in Python 3 to
shape of the underlying data and metadata.

Response:
def dimensional_shape(self) -> typing.Optional[typing.Tuple[int, ...]]:
        """Shape of the underlying data, if only one."""
        if not self.__data_and_metadata:
            return None
        return self.__data_and_metadata.dimensional_shape


Instruction:
Create a Python 3 function to
change the view to encompass the channels and data represented by the given intervals.

Response:
def view_to_intervals(self, data_and_metadata: DataAndMetadata.DataAndMetadata, intervals: typing.List[typing.Tuple[float, float]]) -> None:
        """Change the view to encompass the channels and data represented by the given intervals."""
        left = None
        right = None
        for interval in intervals:
            left = min(left, interval[0]) if left is not None else interval[0]
            right = max(right, interval[1]) if right is not None else interval[1]
        left = left if left is not None else 0.0
        right = right if right is not None else 1.0
        extra = (right - left) * 0.5
        left_channel = int(max(0.0, left - extra) * data_and_metadata.data_shape[-1])
        right_channel = int(min(1.0, right + extra) * data_and_metadata.data_shape[-1])
        self.set_display_property("left_channel", left_channel)
        self.set_display_property("right_channel", right_channel)
        data_min = numpy.amin(data_and_metadata.data[..., left_channel:right_channel])
        data_max = numpy.amax(data_and_metadata.data[..., left_channel:right_channel])
        if data_min > 0 and data_max > 0:
            self.set_display_property("y_min", 0.0)
            self.set_display_property("y_max", data_max * 1.2)
        elif data_min < 0 and data_max < 0:
            self.set_display_property("y_min", data_min * 1.2)
            self.set_display_property("y_max", 0.0)
        else:
            self.set_display_property("y_min", data_min * 1.2)
            self.set_display_property("y_max", data_max * 1.2)


Instruction:
How would you explain what the following Python 3 function does
def write_local_file(fp, name_bytes, writer, dt):
    fp.write(struct.pack('I', 0x04034b50))  # local file header
    fp.write(struct.pack('H', 10))          # extract version (default)
    fp.write(struct.pack('H', 0))           # general purpose bits
    fp.write(struct.pack('H', 0))           # compression method
    msdos_date = int(dt.year - 1980) << 9 | int(dt.month) << 5 | int(dt.day)
    msdos_time = int(dt.hour) << 11 | int(dt.minute) << 5 | int(dt.second)
    fp.write(struct.pack('H', msdos_time))  # extract version (default)
    fp.write(struct.pack('H', msdos_date))  # extract version (default)
    crc32_pos = fp.tell()
    fp.write(struct.pack('I', 0))           # crc32 placeholder
    data_len_pos = fp.tell()
    fp.write(struct.pack('I', 0))           # compressed length placeholder
    fp.write(struct.pack('I', 0))           # uncompressed length placeholder
    fp.write(struct.pack('H', len(name_bytes)))   # name length
    fp.write(struct.pack('H', 0))           # extra length
    fp.write(name_bytes)
    data_start_pos = fp.tell()
    crc32 = writer(fp)
    data_end_pos = fp.tell()
    data_len = data_end_pos - data_start_pos
    fp.seek(crc32_pos)
    fp.write(struct.pack('I', crc32))       # crc32
    fp.seek(data_len_pos)
    fp.write(struct.pack('I', data_len))    # compressed length placeholder
    fp.write(struct.pack('I', data_len))    # uncompressed length placeholder
    fp.seek(data_end_pos)
    return data_len, crc32

Response: Writes a zip file containing the local file header structure at the current position.


Instruction:
Make a summary of the following Python 3 code
def write_directory_data(fp, offset, name_bytes, data_len, crc32, dt):
    fp.write(struct.pack('I', 0x02014b50))  # central directory header
    fp.write(struct.pack('H', 10))          # made by version (default)
    fp.write(struct.pack('H', 10))          # extract version (default)
    fp.write(struct.pack('H', 0))           # general purpose bits
    fp.write(struct.pack('H', 0))           # compression method
    msdos_date = int(dt.year - 1980) << 9 | int(dt.month) << 5 | int(dt.day)
    msdos_time = int(dt.hour) << 11 | int(dt.minute) << 5 | int(dt.second)
    fp.write(struct.pack('H', msdos_time))  # extract version (default)
    fp.write(struct.pack('H', msdos_date))  # extract version (default)
    fp.write(struct.pack('I', crc32))       # crc32
    fp.write(struct.pack('I', data_len))    # compressed length
    fp.write(struct.pack('I', data_len))    # uncompressed length
    fp.write(struct.pack('H', len(name_bytes)))   # name length
    fp.write(struct.pack('H', 0))           # extra length
    fp.write(struct.pack('H', 0))           # comments length
    fp.write(struct.pack('H', 0))           # disk number
    fp.write(struct.pack('H', 0))           # internal file attributes
    fp.write(struct.pack('I', 0))           # external file attributes
    fp.write(struct.pack('I', offset))      # relative offset of file header
    fp.write(name_bytes)

Response: Writes the data to the archive as a zip fie directory entry.