Helper method to add debug layers to QGIS from impact function.

    :param impact_function: The impact function used.
    :type impact_function: ImpactFunction
969970
def add_debug_layers_to_canvas(impact_function):
    
    name = 'DEBUG %s' % impact_function.name
    root = QgsProject.instance().layerTreeRoot()
    group_debug = root.insertGroup(0, name)
    group_debug.setItemVisibilityChecked(False)
    group_debug.setExpanded(False)
    hazard_keywords = impact_function.provenance['hazard_keywords']
    exposure_keywords = impact_function.provenance['exposure_keywords']

    # Let's style the hazard class in each layers.
    # noinspection PyBroadException
    try:
        classification = active_classification(
            hazard_keywords, exposure_keywords['exposure'])
        classification = definition(classification)

        classes = OrderedDict()
        for f in reversed(classification['classes']):
            classes[f['key']] = (f['color'], f['name'])
        hazard_class = hazard_class_field['key']
    except BaseException:
        # We might not have a classification. But this is the debug group so
        # let's not raise a new exception.
        classification = None

    datastore = impact_function.datastore
    for layer in datastore.layers():
        qgis_layer = datastore.layer(layer)
        if not isinstance(qgis_layer, QgsMapLayer):
            continue
        QgsProject.instance().addMapLayer(
            qgis_layer, False)
        layer_node = group_debug.insertLayer(0, qgis_layer)
        layer_node.setItemVisibilityChecked(False)
        layer_node.setExpanded(False)

        # Let's style layers which have a geometry and have
        # hazard_class
        if qgis_layer.type() == QgsMapLayer.VectorLayer:
            if qgis_layer.geometryType() not in [
                        QgsWkbTypes.NullGeometry,
                        QgsWkbTypes.UnknownGeometry
                    ] and classification: # noqa
                if qgis_layer.keywords['inasafe_fields'].get(hazard_class):
                    hazard_class_style(qgis_layer, classes, True)
1321189
def save_function_effect(module):
    
    for intr in module.values():
        if isinstance(intr, dict):  # Submodule case
            save_function_effect(intr)
        else:
            fe = FunctionEffects(intr)
            IntrinsicArgumentEffects[intr] = fe
            if isinstance(intr, intrinsic.Class):
                save_function_effect(intr.fields)
274318
def layer(output_shape=None, new_parameters=None):
  """"""
  def layer_decorator(call):
    """Decorating the call function."""
    def output_shape_fun(self, input_shape):
      if output_shape is None:
        return input_shape
      kwargs = self._init_kwargs  # pylint: disable=protected-access
      return output_shape(input_shape, **kwargs)

    def new_parameters_fun(self, input_shape, rng):
      if new_parameters is None:
        return ()
      kwargs = self._init_kwargs  # pylint: disable=protected-access
      return new_parameters(input_shape, rng, **kwargs)

    def call_fun(self, x, params=(), **kwargs):
      """The call function of the created class, derived from call."""
      # Merge on-call kwargs with class-kwargs.
      call_kwargs = kwargs.copy()
      call_kwargs.update(self._init_kwargs)  # pylint: disable=protected-access
      # Call with the merged kwargs.
      return call(x, params=params, **call_kwargs)

    # Set doc for python help.
    call_fun.__doc__ = call.__doc__
    if output_shape is None:
      output_shape_fun.__doc__ = output_shape.__doc__
    if new_parameters is None:
      new_parameters_fun.__doc__ = new_parameters.__doc__

    # Create the class.
    cls = type(call.__name__, (Layer,),
               {'call': call_fun,
                'output_shape': output_shape_fun,
                'new_parameters': new_parameters_fun})

    return cls
  return layer_decorator
1323286
def _build_register_function(universe: bool, in_place: bool):  # noqa: D202
    

    def register(func):
        """Tag a transformation function.

        :param func: A function
        :return: The same function, with additional properties added
        """
        return _register_function(func.__name__, func, universe, in_place)

    return register
768384
def _set_debug_level(self, debug_level):
    
    mapping = {
        0: logging.ERROR,
        1: logging.INFO,
        2: logging.DEBUG,
    }

    self.setLevel(
        mapping[min(debug_level, 2)],
    )
223698
def impact_check_range(func):
    """"""
    @wraps(func)
    def impact_wrapper(*args,**kwargs):
        if isinstance(args[1],numpy.ndarray):
            out= numpy.zeros(len(args[1]))
            goodIndx= (args[1] < args[0]._deltaAngleTrackImpact)*(args[1] > 0.)
            out[goodIndx]= func(args[0],args[1][goodIndx])
            return out
        elif args[1] >= args[0]._deltaAngleTrackImpact or args[1] <= 0.:
            return 0.
        else:
            return func(*args,**kwargs)
    return impact_wrapper
338794
function addDebugLayers (node, tree) {
    for (let layer in node) {
        let counts = node[layer];
        addLayerDebugEntry(tree, layer, counts.features, counts.geoms, counts.styles, counts.base);
        if (counts.layers) {
            tree[layer].layers = tree[layer].layers || {};
            addDebugLayers(counts.layers, tree[layer].layers); // process child layers
        }
    }
}
575288
def debug(self, message, *args, **kwargs):
        
        self.system.debug(message, *args, **kwargs)
1264076
def add_callback(self, name, func):
        

        if name == 'on_scan':
            events = ['device_seen']
            def callback(_conn_string, _conn_id, _name, event):
                func(self.id, event, event.get('validity_period', 60))
        elif name == 'on_report':
            events = ['report', 'broadcast']
            def callback(_conn_string, conn_id, _name, event):
                func(conn_id, event)
        elif name == 'on_trace':
            events = ['trace']
            def callback(_conn_string, conn_id, _name, event):
                func(conn_id, event)
        elif name == 'on_disconnect':
            events = ['disconnection']
            def callback(_conn_string, conn_id, _name, _event):
                func(self.id, conn_id)
        else:
            raise ArgumentError("Unknown callback type {}".format(name))

        self._adapter.register_monitor([None], events, callback)
1103680
def on_pbnBack_released(self):
        
        current_step = self.get_current_step()
        if current_step.step_type == STEP_FC:
            new_step = self.impact_function_steps.pop()
        elif current_step.step_type == STEP_KW:
            try:
                new_step = self.keyword_steps.pop()
            except IndexError:
                new_step = self.impact_function_steps.pop()
        else:
            raise InvalidWizardStep

        # set focus to table widgets, as the inactive selection style is gray
        if new_step == self.step_fc_functions1:
            self.step_fc_functions1.tblFunctions1.setFocus()
        if new_step == self.step_fc_functions2:
            self.step_fc_functions2.tblFunctions2.setFocus()
        # Re-connect disconnected signals when coming back to the Extent step
        if new_step == self.step_fc_extent:
            self.step_fc_extent.set_widgets()
        # Set Next button label
        self.pbnNext.setText(tr('Next'))
        self.pbnNext.setEnabled(True)
        self.go_to_step(new_step)
355205
def validate_impact_function(self):
        """"""
        # Always set it to False
        self.btn_run.setEnabled(False)

        for combo in list(self.combos_exposures.values()):
            if combo.count() == 1:
                combo.setEnabled(False)

        hazard = layer_from_combo(self.cbx_hazard)
        aggregation = layer_from_combo(self.cbx_aggregation)
        exposures = []
        for combo in list(self.combos_exposures.values()):
            exposures.append(layer_from_combo(combo))
        exposures = [layer for layer in exposures if layer]

        multi_exposure_if = MultiExposureImpactFunction()
        multi_exposure_if.hazard = hazard
        multi_exposure_if.exposures = exposures
        multi_exposure_if.debug = False
        multi_exposure_if.callback = self.progress_callback
        if aggregation:
            multi_exposure_if.use_selected_features_only = (
                self.use_selected_only)
            multi_exposure_if.aggregation = aggregation
        else:
            multi_exposure_if.crs = (
                self.iface.mapCanvas().mapSettings().destinationCrs())
        if len(self.ordered_expected_layers()) != 0:
            self._multi_exposure_if.output_layers_ordered = (
                self.ordered_expected_layers())

        status, message = multi_exposure_if.prepare()
        if status == PREPARE_SUCCESS:
            self._multi_exposure_if = multi_exposure_if
            self.btn_run.setEnabled(True)
            send_static_message(self, ready_message())
            self.list_layers_in_map_report.clear()
            return
        else:
            disable_busy_cursor()
            send_error_message(self, message)
            self._multi_exposure_if = None
358568
def accept(self):
        """"""

        self.save_state()
        self.dock.show_busy()

        # The order of the components are matter.
        components = self.prepare_components()
        error_code, message = self.impact_function.generate_report(
            components, iface=self.iface)

        if error_code == ImpactReport.REPORT_GENERATION_FAILED:
            self.dock.hide_busy()
            LOGGER.info(tr(
                'The impact report could not be generated.'))
            send_error_message(self, message)
            LOGGER.info(message.to_text())
            return ANALYSIS_FAILED_BAD_CODE, message

        sender_name = self.sender().objectName()

        try:
            if sender_name == 'button_print_pdf':
                self.create_pdf = True
                self.open_as_pdf()
            else:
                self.create_pdf = False
                self.open_in_composer()
            self.dock.hide_busy()
        except Exception:
            self.dock.hide_busy()

        QtWidgets.QDialog.accept(self)
1367062
def sg_rnn_layer_func(func):
    
    """
    @wraps(func)
    def wrapper(tensor, **kwargs):
        r"""Manages arguments of `tf.sg_opt`.

        Args:
          tensor: automatically passed by decorator
          kwargs:
              in_dim: An integer. The size of input dimension, which is set to the last one by default.
              dim: An integer. The size of output dimension. Has the same value as in_dim by default.
              ln: Boolean. If True, layer normalization is applied.
              bias: Boolean. If True, biases are added. As a default, it is set to True
              name: A name for the layer. As a default, the function name is assigned.
              reuse: `True` or `None`; if `True`, we go into reuse mode for this `layer` scope
                as well as all sub-scopes; if `None`, we just inherit the parent scope reuse.
              summary: If True, summaries are added. The default is True.
        """

        # kwargs parsing
        opt = tf.sg_opt(kwargs) + sg_get_context()

        # set default argument
        try:
            shape = tensor.get_shape().as_list()
            # dropout off
            opt += tf.sg_opt(shape=shape, in_dim=shape[-1], dim=shape[-1], dout=0, summary=True)
            # disable bias when normalization on
            opt += tf.sg_opt(bias=not opt.ln)
        finally:
            pass

        # automatic layer naming
        if opt.name is None:

            # layer function name will be used as layer name
            opt.name = func.__name__.replace('sg_', '')

            # find existing layer names
            exist_layers = []
            for t in tf.global_variables():
                scope_name = tf.get_variable_scope().name
                prefix = scope_name + '/' if len(scope_name) > 0 else ''
                i = t.name.rfind(prefix + opt.name)
                if i >= 0:
                    exist_layers.append(t.name[i:].split('/')[-2])
            exist_layers = list(set(exist_layers))

            # layer name numbering
            if len(exist_layers) == 0:
                opt.name += '_1'
            else:
                opt.name += '_%d' % (max([int(n.split('_')[-1]) for n in exist_layers]) + 1)

        with tf.variable_scope(opt.name, reuse=opt.reuse) as scope:

            # call layer function
            out = func(tensor, opt)

            # apply dropout
            if opt.dout:
                out = tf.cond(_phase,
                              lambda: tf.nn.dropout(out, 1 - opt.dout),
                              lambda: out)

            # rename tensor
            out = tf.identity(out, 'out')

            # add final output summary
            if opt.summary:
                tf.sg_summary_activation(out)

            # save node info for reuse
            out._sugar = tf.sg_opt(func=func, arg=tf.sg_opt(kwargs) + sg_get_context(),
                                   prev=tensor, is_layer=True, name=opt.name)
            # inject reuse function
            out.sg_reuse = types.MethodType(sg_reuse, out)

        return out

    return wrapper
346171
def my_func(p1, p2,
            first_option='default_value',
            second_option=5,
            third_option=[4, 3],
            last_option=False):
    
    if last_option:
        raise RuntimeError("Test of DEBUG")
    print('%s %s %s %s %s %s' % (p1, p2, first_option, second_option, third_option, last_option))
112920
def set_widgets(self):
        """"""
        self.tblFunctions2.clear()
        hazard, exposure, _, _ = self.parent.\
            selected_impact_function_constraints()
        hazard_layer_geometries = get_allowed_geometries(
            layer_purpose_hazard['key'])
        exposure_layer_geometries = get_allowed_geometries(
            layer_purpose_exposure['key'])
        self.lblSelectFunction2.setText(
            select_function_constraints2_question % (
                hazard['name'], exposure['name']))
        self.tblFunctions2.setColumnCount(len(hazard_layer_geometries))
        self.tblFunctions2.setRowCount(len(exposure_layer_geometries))
        self.tblFunctions2.setHorizontalHeaderLabels(
            [i['name'].capitalize() for i in hazard_layer_geometries])
        for i in range(len(exposure_layer_geometries)):
            item = QtWidgets.QTableWidgetItem()
            item.setText(exposure_layer_geometries[i]['name'].capitalize())
            item.setTextAlignment(QtCore.Qt.AlignCenter)
            self.tblFunctions2.setVerticalHeaderItem(i, item)

        self.tblFunctions2.horizontalHeader().setSectionResizeMode(
            QtWidgets.QHeaderView.Stretch)
        self.tblFunctions2.verticalHeader().setSectionResizeMode(
            QtWidgets.QHeaderView.Stretch)

        active_items = []
        for column in range(len(hazard_layer_geometries)):
            for row in range(len(exposure_layer_geometries)):
                hazard_geometry = hazard_layer_geometries[column]
                exposure_geometry = exposure_layer_geometries[row]
                item = QtWidgets.QTableWidgetItem()

                hazard_geometry_allowed = hazard_geometry['key'] in hazard[
                    'allowed_geometries']
                exposure_geometry_allowed = (
                    exposure_geometry['key'] in exposure[
                        'allowed_geometries'])

                if hazard_geometry_allowed and exposure_geometry_allowed:
                    background_color = available_option_color
                    active_items += [item]
                else:
                    background_color = unavailable_option_color
                    item.setFlags(item.flags() & ~QtCore.Qt.ItemIsEnabled)
                    item.setFlags(item.flags() & ~QtCore.Qt.ItemIsSelectable)

                item.setBackground(QtGui.QBrush(background_color))
                item.setFont(big_font)
                item.setTextAlignment(
                    QtCore.Qt.AlignCenter | QtCore.Qt.AlignHCenter)
                item.setData(RoleHazard, hazard)
                item.setData(RoleExposure, exposure)
                item.setData(RoleHazardConstraint, hazard_geometry)
                item.setData(RoleExposureConstraint, exposure_geometry)
                self.tblFunctions2.setItem(row, column, item)
        # Automatically select one item...
        if len(active_items) == 1:
            active_items[0].setSelected(True)
            # set focus, as the inactive selection style is gray
            self.tblFunctions2.setFocus()
1049538
def show_print_dialog(self):
        """"""
        if not self.impact_function:
            # Now try to read the keywords and show them in the dock
            try:
                active_layer = self.iface.activeLayer()
                keywords = self.keyword_io.read_keywords(active_layer)

                provenances = keywords.get('provenance_data', {})
                extra_keywords = keywords.get('extra_keywords', {})
                is_multi_exposure = (
                    extra_keywords.get(extra_keyword_analysis_type['key']) == (
                        MULTI_EXPOSURE_ANALYSIS_FLAG))

                if provenances and is_multi_exposure:
                    self.impact_function = (
                        MultiExposureImpactFunction.load_from_output_metadata(
                            keywords))
                else:
                    self.impact_function = (
                        ImpactFunction.load_from_output_metadata(keywords))

            except (KeywordNotFoundError,
                    HashNotFoundError,
                    InvalidParameterError,
                    NoKeywordsFoundError,
                    MetadataReadError,
                    # AttributeError  This is hiding some real error. ET
                    ) as e:
                # Added this check in 3.2 for #1861
                active_layer = self.iface.activeLayer()
                LOGGER.debug(e)
                if active_layer is None:
                    if self.conflicting_plugin_detected:
                        send_static_message(self, conflicting_plugin_message())
                    else:
                        send_static_message(self, getting_started_message())
                else:
                    show_no_keywords_message(self)
            except Exception as e:  # pylint: disable=broad-except
                error_message = get_error_message(e)
                send_error_message(self, error_message)

        if self.impact_function:
            dialog = PrintReportDialog(
                self.impact_function, self.iface, dock=self, parent=self)
            dialog.show()
        else:
            display_critical_message_bar(
                "InaSAFE",
                self.tr('Please select a valid layer before printing. '
                        'No Impact Function found.'),
                iface_object=self
            )
1038336
def debug(self, msg, *args, **kwargs) -> Task:  # type: ignore
        
        return self._make_log_task(logging.DEBUG, msg, args, **kwargs)