Exemplo n.º 1
0
    def basic_new_prices(self, dialog=None):
        """ Button 303: Price generator """
        
        # Close previous dialog
        if dialog is not None:
            self.close_dialog(dialog)
        self.dlg_new_campaign = NewPrices()
        self.load_settings(self.dlg_new_campaign)

        # Set default dates
        current_year = QDate.currentDate().year()
        start_date = QDate.fromString(str(int(current_year)) + '/11/01', 'yyyy/MM/dd')
        self.dlg_new_campaign.start_date.setDate(start_date)
        end_date = QDate.fromString(str(int(current_year)+1) + '/10/31', 'yyyy/MM/dd')
        self.dlg_new_campaign.end_date.setDate(end_date)

        table_name = 'cat_campaign'
        field_id = 'id'
        field_name = 'name'
        self.dlg_new_campaign.rejected.connect(partial(self.close_dialog, self.dlg_new_campaign))
        self.dlg_new_campaign.btn_cancel.clicked.connect(partial(self.close_dialog, self.dlg_new_campaign))
        self.dlg_new_campaign.btn_accept.clicked.connect(partial(self.manage_new_price_catalog))
        
        self.populate_cmb_years(table_name, field_id, field_name,  self.dlg_new_campaign.cbx_years)
        self.set_completer_object(table_name, self.dlg_new_campaign.txt_campaign, field_name)
        
        if self.rows_cmb_poda_type is None:
            self.update_cmb_poda_type()     


        if self.rows_cmb_builder is None:
            self.update_cmb_builder()

        self.open_dialog(self.dlg_new_campaign)
Exemplo n.º 2
0
    def month_selector(self):
        
        month_selector = MonthSelector()
        
        self.load_settings(month_selector)
        month_selector.all_rows.setSelectionBehavior(QAbstractItemView.SelectRows)
        month_selector.selected_rows.setSelectionBehavior(QAbstractItemView.SelectRows)
        month_selector.setWindowTitle("Planificador mensual")

        # Set label with selected text from previus dialog
        month_selector.lbl_plan_code.setText(self.plan_code)
        month_selector.lbl_year.setText(self.planned_camp_name)

        sql = (f"SELECT start_date, end_date FROM cat_campaign "
               f" WHERE id ='{self.planned_camp_id}'")
        row = self.controller.get_row(sql)
        if row is not None:
            start_date = QDate.fromString(str(row[0]), 'yyyy-MM-dd')
            end_date = QDate.fromString(str(row[1]), 'yyyy-MM-dd')
        else:
            start_date = QDate.currentDate()
            end_date = QDate.currentDate().addYears(1)

        utils_giswater.setCalendarDate(month_selector, month_selector.date_inici, start_date)
        utils_giswater.setCalendarDate(month_selector, month_selector.date_fi, end_date)

        view_name = 'v_plan_mu_year'
        tableleft = 'planning'
        id_table_left = 'mu_id'

        # Left QTableView
        expr = " AND ( plan_code is NULL OR plan_code = '')"

        self.fill_table_planned_month(month_selector.all_rows, month_selector.txt_search, view_name, expr)
        month_selector.txt_search.textChanged.connect(
            partial(self.fill_table_planned_month, month_selector.all_rows, month_selector.txt_search, view_name, expr, QTableView.NoEditTriggers))
        month_selector.btn_select.clicked.connect(
            partial(self.month_selector_row, month_selector, id_table_left, tableleft, view_name))
        self.set_table_columns(month_selector, month_selector.all_rows, view_name, 'basic_month_left')

        # Right QTableView
        expr = " AND plan_code = '" + self.plan_code + "'"

        self.fill_table_planned_month(month_selector.selected_rows, month_selector.txt_selected_filter, view_name, expr)
        month_selector.txt_selected_filter.textChanged.connect(
            partial(self.fill_table_planned_month, month_selector.selected_rows, month_selector.txt_selected_filter, view_name, expr, QTableView.NoEditTriggers))
        month_selector.btn_unselect.clicked.connect(
            partial(self.month_unselector_row, month_selector, id_table_left, tableleft, view_name))
        self.set_table_columns(month_selector, month_selector.selected_rows, view_name, 'basic_month_right')

        self.calculate_total_price(month_selector, self.planned_camp_id)

        month_selector.btn_close.clicked.connect(partial(self.close_dialog, month_selector))
        month_selector.rejected.connect(partial(self.close_dialog, month_selector))

        month_selector.exec_()
Exemplo n.º 3
0
def set_calendar(dialog, widget, date, default_current_date=True):

    if type(widget) is str or type(widget) is str:
        widget = dialog.findChild(QWidget, widget)
    if not widget:
        return

    if global_vars.date_format in ("dd/MM/yyyy", "dd-MM-yyyy", "yyyy/MM/dd",
                                   "yyyy-MM-dd"):
        widget.setDisplayFormat(global_vars.date_format)
    if type(widget) is QDateEdit \
            or (type(widget) is QgsDateTimeEdit and widget.displayFormat() in
                ('dd/MM/yyyy', 'yyyy/MM/dd', 'dd-MM-yyyy', 'yyyy-MM-dd')):
        if date is None:
            if default_current_date:
                date = QDate.currentDate()
            else:
                date = QDate.fromString('01-01-2000', 'dd-MM-yyyy')
        widget.setDate(date)
    elif type(widget) is QDateTimeEdit \
            or (type(widget) is QgsDateTimeEdit and widget.displayFormat() in
                ('dd/MM/yyyy hh:mm:ss', 'yyyy/MM/dd hh:mm:ss', 'dd-MM-yyyy hh:mm:ss', 'yyyy-MM-dd hh:mm:ss')):
        if date is None:
            date = QDateTime.currentDateTime()
        widget.setDateTime(date)
Exemplo n.º 4
0
    def update_lwc_releases(self, released_versions: dict):
        """ Update labels about latest releases. """
        template = (
            '<a href="https://github.com/3liz/lizmap-web-client/releases/tag/{tag}">'
            '{tag}   -    {date}'
            '</a>')

        i = 0
        for json_version in released_versions:
            qdate = QDate.fromString(
                json_version['latest_release_date'],
                "yyyy-MM-dd")
            date_string = qdate.toString(QLocale().dateFormat(QLocale.ShortFormat))
            if json_version['maintained']:
                if i == 0:
                    text = template.format(
                        tag=json_version['latest_release_version'],
                        date=date_string,
                    )
                    self.dialog.lwc_version_latest.setText(text)
                elif i == 1:
                    text = template.format(
                        tag=json_version['latest_release_version'],
                        date=date_string,
                    )
                    self.dialog.lwc_version_oldest.setText(text)
                i += 1
    def set_data(self, md=None):
        if md is None:
            return None
        if self.scope != SCOPES.SERVICES:
            common = md.identification
        else:
            common = md.serviceidentification
        if common is None:
            return
        for date in common.date:
            if date.type == 'creation':
                self.creationdate.setDateTime(
                    qcore.QDateTime.fromString(date.date, cons.DATE_FORMAT))
            elif date.type == 'revision':
                self.revisiondate.setDateTime(
                    qcore.QDateTime.fromString(date.date, cons.DATE_FORMAT))
            elif date.type == 'publication':
                self.publicationdate.model().addNewRow(
                    QDate.fromString(date.date, cons.DATE_FORMAT))

        for extent in common.extent:
            if hasattr(extent,
                       'beginposition') and extent.beginposition is not None:
                self.begindate.set_dateTime(
                    qcore.QDateTime.fromString(
                        extent.beginposition.replace("T", " "),
                        cons.DATE_TIME_FORMAT))
                self.enddate.set_dateTime(
                    qcore.QDateTime.fromString(
                        extent.endposition.replace("T", " "),
                        cons.DATE_TIME_FORMAT))
Exemplo n.º 6
0
    def to_mdp_feature(self, event: dict, fields: QgsFields) -> QgsFeature:
        """
        Converts results to a MDP feature
        """
        f = QgsFeature(fields)
        for k, v in event.items():
            try:
                if fields[fields.lookupField(k)].type() == QVariant.DateTime:
                    v = v.replace('--', '00')
                    v = QDateTime.fromString(v, Qt.ISODate)
                elif fields[fields.lookupField(k)].type() == QVariant.Date:
                    v = QDate.fromString(v, Qt.ISODate)
                elif fields[fields.lookupField(k)].type() == QVariant.Time:
                    v = QTime.fromString(v, Qt.ISODate)
                elif fields[fields.lookupField(k)].type() == QVariant.Double:
                    v = float(v)
                elif fields[fields.lookupField(k)].type() == QVariant.Int:
                    v = int(v)
            except Exception:  # pylint: disable=broad-except
                v = NULL

            f[k] = v

        if event.get('ReferenceLatitude') and event.get('ReferenceLongitude'):
            geom = QgsPoint(x=float(event['ReferenceLongitude']),
                            y=float(event['ReferenceLatitude']))
            f.setGeometry(QgsGeometry(geom))

        return f
Exemplo n.º 7
0
    def to_station_feature(self, station: dict,
                           fields: QgsFields) -> QgsFeature:
        """
        Creates a station feature
        """
        f = QgsFeature(fields)
        for k, v in station.items():
            try:
                if fields[fields.lookupField(k)].type() == QVariant.DateTime:
                    v = v.replace('--', '00')
                    v = QDateTime.fromString(v, Qt.ISODate)
                elif fields[fields.lookupField(k)].type() == QVariant.Date:
                    v = QDate.fromString(v, Qt.ISODate)
                elif fields[fields.lookupField(k)].type() == QVariant.Time:
                    v = QTime.fromString(v, Qt.ISODate)
                elif fields[fields.lookupField(k)].type() == QVariant.Double:
                    v = float(v)
                elif fields[fields.lookupField(k)].type() == QVariant.Int:
                    v = int(v)
            except Exception:  # pylint: disable=broad-except
                v = NULL

            f[k] = v

        if station.get('Latitude') and station.get('Longitude'):
            geom = QgsPoint(x=float(station['Longitude']),
                            y=float(station['Latitude']))
            f.setGeometry(QgsGeometry(geom))

        return f
Exemplo n.º 8
0
	def _getXYvalues(self, ts_layer, dateField, valueField):
		# utility function used to get the X and Y values
		x, y = [], []

		# get indexes of date (x) and value (y) fields
		dateIdx, valueIdx = None, None
		for idx, fld in enumerate(ts_layer.dataProvider().fields()):
			if fld.name().lower() == dateField:
				dateIdx = idx
			elif fld.name().lower() == valueField:
				valueIdx = idx

		if dateIdx is None or valueIdx is None:
			QgsMessageLog.logMessage("field %s -> index %s, field %s -> index %s. Exiting" % (dateField, dateIdx, valueField, valueIdx), "PSTimeSeriesViewer")
			return

		# fetch and loop through all the features
		request = QgsFeatureRequest()
		request.setSubsetOfAttributes([dateIdx, valueIdx])
		for f in ts_layer.getFeatures( request ):
			# get x and y values
			a = f.attributes()
			x.append( QDate.fromString( a[ dateIdx ], "yyyyMMdd" ).toPyDate() )
			y.append( float(a[ valueIdx ]) )

		return x, y
Exemplo n.º 9
0
    def _getXYvalues(self, ts_layer, dateField, valueField):
        # utility function used to get the X and Y values
        x, y = [], []

        # get indexes of date (x) and value (y) fields
        dateIdx, valueIdx = None, None
        for idx, fld in enumerate(ts_layer.dataProvider().fields()):
            if fld.name().lower() == dateField:
                dateIdx = idx
            elif fld.name().lower() == valueField:
                valueIdx = idx

        if dateIdx is None or valueIdx is None:
            QgsMessageLog.logMessage(
                "field %s -> index %s, field %s -> index %s. Exiting" %
                (dateField, dateIdx, valueField, valueIdx),
                "PSTimeSeriesViewer")
            return

        # fetch and loop through all the features
        request = QgsFeatureRequest()
        request.setSubsetOfAttributes([dateIdx, valueIdx])
        for f in ts_layer.getFeatures(request):
            # get x and y values
            a = f.attributes()
            x.append(QDate.fromString(a[dateIdx], "yyyyMMdd").toPyDate())
            y.append(float(a[valueIdx]))

        return x, y
Exemplo n.º 10
0
    def test_value_date(self):
        test_property = DateProperty('test name', QDate.currentDate(),
                                     'gco:Date')

        test_property.value = QDate.fromString('2015-06-07')

        with self.assertRaises(TypeError):
            test_property.value = 20150607
Exemplo n.º 11
0
    def set_value(self, data):
        data = data if data else None
        data = json.loads(data) if isinstance(data, str) else data

        if data is None:
            self.date_start.clear()
            self.date_end.clear()

            self._start = None
            self._end = None
        else:
            # data[-1] is in case a single value is passed. Set both dates to that value
            self.date_start.setDate(QDate.fromString(data[0],
                                                     self._dateformat))
            self.date_end.setDate(QDate.fromString(data[-1], self._dateformat))

            self._start = data[0]
            self._end = data[-1]
 def global_settings_defaults(self):
     """Global settings defaults."""
     defaults = {
         "id": 1,
         "advection_1d": 1,
         "advection_2d": 1,
         "control_group_id": None,
         "dem_file": None,
         "dem_obstacle_detection": 0,
         "dem_obstacle_height": None,
         "dist_calc_points": 1000.0,
         "embedded_cutoff_threshold": 0.05,
         "epsg_code": None,
         "flooding_threshold": 0.0001,
         "frict_avg": 0,
         "frict_coef": None,
         "frict_coef_file": None,
         "frict_type": None,
         "grid_space": 0.0,
         "groundwater_settings_id": None,
         "initial_groundwater_level": None,
         "initial_groundwater_level_file": None,
         "initial_groundwater_level_type": None,
         "initial_waterlevel": -99.0,
         "initial_waterlevel_file": None,
         "interflow_settings_id": None,
         "interception_global": None,
         "interception_file": None,
         "max_interception": None,
         "max_interception_file": None,
         "kmax": 1,
         "manhole_storage_area": None,
         "max_angle_1d_advection": 90.0,
         "maximum_sim_time_step": None,
         "minimum_sim_time_step": 0.01,
         "name": "default",
         "nr_timesteps": 9999,
         "numerical_settings_id": 1,
         "output_time_step": None,
         "sim_time_step": None,
         "simple_infiltration_settings_id": None,
         "start_date": QDate.fromString("2000-01-01", "yyyy-MM-dd"),
         "start_time": QTime.fromString("00:00:00", "HH:MM:SS"),
         "table_step_size": 0.01,
         "table_step_size_1d": 0.01,
         "table_step_size_volume_2d": None,
         "timestep_plus": 0,
         "use_0d_inflow": None,
         "use_1d_flow": None,
         "use_2d_flow": None,
         "use_2d_rain": None,
         "water_level_ini_type": None,
         "wind_shielding_file": None,
     }
     return defaults
Exemplo n.º 13
0
 def set_calendars(self, dialog, widget, table_name, value, parameter):
     """ Executes query and set QDateEdit """
     
     sql = (f"SELECT {value} FROM {table_name}"
            f" WHERE parameter = '{parameter}' AND cur_user = current_user")
     row = self.controller.get_row(sql)
     if row:
         date = QDate.fromString(row[0], 'yyyy-MM-dd')
     else:
         date = QDate.currentDate()
     utils_giswater.setCalendarDate(dialog, widget, date)
Exemplo n.º 14
0
    def test_value_date(self):
        test_property = DateProperty(
            'test name',
            QDate.currentDate(),
            'gco:Date'
        )

        test_property.value = QDate.fromString('2015-06-07')

        with self.assertRaises(TypeError):
            test_property.value = 20150607
def set_calendars(dialog, widget, table_name, value, parameter):
    """ Executes query and set QDateEdit """

    sql = (f"SELECT {value} FROM {table_name}"
           f" WHERE parameter = '{parameter}' AND cur_user = current_user")
    row = global_vars.controller.get_row(sql)
    if row:
        if row[0]:
            row[0] = row[0].replace('/', '-')
        date = QDate.fromString(row[0], 'yyyy-MM-dd')
    else:
        date = QDate.currentDate()
    qt_tools.setCalendarDate(dialog, widget, date)
Exemplo n.º 16
0
 def nextBlock(text, i):
     name, datestamp = text[i].split(' - ')
     date = QDate.fromString(datestamp, 'yyyy-MM-dd')
     filenames = list()
     bands = list()
     i += 1
     while text[i].strip() != '':
         tmp = text[i].split(' (')
         filename = tmp[0].strip()
         band = int(tmp[1].replace(')', '').strip())
         filenames.append(filename)
         bands.append(band)
         i += 1
     return name, date, filenames, bands, i + 1
Exemplo n.º 17
0
    def contextDateString(self, date):
        if date in self.contextDateStrings:
            return self.contextDateStrings[date]

        if date == datetime.today().strftime('%Y-%m-%d'):
            self.contextDateStrings[date] = self.tr('Today')
        else:
            interval_days = (datetime.today() - datetime.strptime(date, '%Y-%m-%d')).days
            if interval_days == 1:
                self.contextDateStrings[date] = self.tr('Yesterday')
            elif interval_days < 8:
                self.contextDateStrings[date] = self.tr('Last 7 days')
            else:
                self.contextDateStrings[date] = QDate.fromString(date, 'yyyy-MM-dd').toString('MMMM yyyy')
        return self.contextDateString(date)
Exemplo n.º 18
0
def getDateRapideye(name, feature, parent):
    """
  <h4>Return</h4>QDate from file name of Rapideye
  <p><h4>Syntax</h4>getDateRapideye(name_rapideye)</p>
  <p><h4>Argument</h4>File name of Rapideye</p>
  <p><h4>Example</h4>getDateRapideye('2227625_2012-12-26T142009_RE1_3A-NAC_14473192_171826.tif')</p>
    """
    msgError = f"Enter with Rapideye name (ex. '2227625_2012-12-26T142009_RE1_3A-NAC_14473192_171826'). Value = '{name}'."
    try:
        v_date = QDate.fromString(name.split('_')[1][:10], "yyyy-MM-dd")
    except:
        raise Exception(msgError)
    if not v_date.isValid():
        raise Exception(msgError)
    return v_date
Exemplo n.º 19
0
def getDateSentinel1(name, feature, parent):
    """
  <h4>Return</h4>QDate from file name of Sentinel1
  <p><h4>Syntax</h4>getDateSentinel1(name_sentinel)</p>
  <p><h4>Argument</h4>File name of Sentinel1</p>
  <p><h4>Example</h4>getDateSentinel1('s1a-ew-grd-hh-20141031t223708-20141031t223811-003079-003869-001.tif')</p>
    """
    msgError = f"Enter with Sentinel1 name (ex. 's1a-ew-grd-hh-20141031t223708-20141031t223811-003079-003869-001'). Value = '{name}'."
    try:
        v_date = QDate.fromString(name.split('-')[5][:8], "yyyyMMdd")
    except:
        raise Exception(msgError)
    if not v_date.isValid():
        raise Exception(msgError)
    return v_date
Exemplo n.º 20
0
def getDateSentinel2(name, feature, parent):
    """
  <h4>Return</h4>QDate from file name of Sentinel2
  <p><h4>Syntax</h4>getDateSentinel2(name_sentinel)</p>
  <p><h4>Argument</h4>File name of Sentinel2</p>
  <p><h4>Example</h4>getDateSentinel2('S2A_MSIL1C_20170105T013442_N0204_R031_T53NMJ_20170105T013443.tif')</p>
    """
    msgError = f"Enter with Sentinel2 name (ex. 'S2A_MSIL1C_20170105T013442_N0204_R031_T53NMJ_20170105T013443'). Value = '{name}'."
    try:
        v_date = QDate.fromString(name.split('_')[2][:8], "yyyyMMdd")
    except:
        raise Exception(msgError)
    if not v_date.isValid():
        raise Exception(msgError)
    return v_date
Exemplo n.º 21
0
def getDatePlanetScope(name, feature, parent):
    """
  <h4>Return</h4>QDate from file name of PlanetScope
  <p><h4>Syntax</h4>getDatePlanetScope(name_planetscope)</p>
  <p><h4>Argument</h4>File name of PlanetScope</p>
  <p><h4>Example</h4>getDatePlanetScope('PSScene4Band_20190310_131656_0f4a.tif')</p>
    """
    msgError = f"Enter with PlanetScope name (ex. 'PSScene4Band_20190310_131656_0f4a'). Value = '{name}'."
    try:
        v_date = QDate.fromString(name.split('_')[1], "yyyyMMdd")
    except:
        raise Exception(msgError)
    if not v_date.isValid():
        raise Exception(msgError)
    return v_date
Exemplo n.º 22
0
        def to_datetime(val):
            if not val:
                return NULL
            if 'T' in val:
                if '.' not in val:
                    val += '.000'
                if val[-1].upper() == 'Z':
                    val = val[:-1]
                dt = QDateTime.fromString((val + '000')[:23],
                                          'yyyy-MM-ddThh:mm:ss.zzz')
                dt.setTimeSpec(Qt.UTC)
                return dt

            dt = QDateTime(QDate.fromString(val, 'yyyy-MM-dd'), QTime())
            dt.setTimeSpec(Qt.UTC)
            return dt
Exemplo n.º 23
0
    def go2epa_options_get_data(self, tablename, dialog):
        """ Get data from selected table """

        sql = f"SELECT * FROM {tablename}"
        row = self.controller.get_row(sql)
        if not row:
            message = "Any data found in table"
            self.controller.show_warning(message, parameter=tablename)
            return None

        # Iterate over all columns and populate its corresponding widget
        columns = []
        for i in range(0, len(row)):
            column_name = self.dao.get_column_name(i)
            widget = dialog.findChild(QWidget, column_name)
            widget_type = utils_giswater.getWidgetType(dialog, widget)
            if row[column_name] is not None:
                if widget_type is QCheckBox:
                    utils_giswater.setChecked(dialog, widget, row[column_name])
                elif widget_type is QComboBox:
                    utils_giswater.set_combo_itemData(widget, row[column_name],
                                                      0)
                elif widget_type is QDateEdit:
                    dateaux = row[column_name].replace('/', '-')
                    date = QDate.fromString(dateaux, 'dd-MM-yyyy')
                    utils_giswater.setCalendarDate(dialog, widget, date)
                elif widget_type is QTimeEdit:
                    timeparts = str(row[column_name]).split(':')
                    if len(timeparts) < 3:
                        timeparts.append("0")
                    days = int(timeparts[0]) / 24
                    hours = int(timeparts[0]) % 24
                    minuts = int(timeparts[1])
                    seconds = int(timeparts[2])
                    time = QTime(hours, minuts, seconds)
                    utils_giswater.setTimeEdit(dialog, widget, time)
                    utils_giswater.setText(dialog, column_name + "_day", days)
                else:
                    utils_giswater.setWidgetText(dialog, widget,
                                                 str(row[column_name]))

            columns.append(column_name)

        return columns
Exemplo n.º 24
0
def set_widgets_parameters(main_widget, find_combobox_text=True, **widget_parameters):
    """Set widget children values based on derived parameters."""
    for name, value in widget_parameters.items():
        widget = getattr(main_widget, name, None)
        if widget is None:
            continue
        if isinstance(widget, QLineEdit):
            widget.setText(value)
        elif isinstance(widget, (QCheckBox, QRadioButton)):
            widget.setChecked(value)
        elif isinstance(widget, QComboBox):
            idx = widget.findText(value) if find_combobox_text else value
            widget.setCurrentIndex(idx)
        elif isinstance(widget, QDateEdit):
            widget.setDate(QDate.fromString(value, "yyyy-MM-dd"))
        elif isinstance(widget, QTimeEdit):
            widget.setTime(QTime.fromString(value, "H:m"))
        elif isinstance(widget, (QSpinBox, QDoubleSpinBox)):
            widget.setValue(value)
def setCalendarDate(dialog, widget, date, default_current_date=True):

    if type(widget) is str or type(widget) is str:
        widget = dialog.findChild(QWidget, widget)
    if not widget:
        return
    if type(widget) is QDateEdit \
        or (type(widget) is QgsDateTimeEdit and widget.displayFormat() in ('dd/MM/yyyy', 'yyyy/MM/dd')):
        if date is None:
            if default_current_date:
                date = QDate.currentDate()
            else:
                date = QDate.fromString('01/01/2000', 'dd/MM/yyyy')
        widget.setDate(date)
    elif type(widget) is QDateTimeEdit \
            or (type(widget) is QgsDateTimeEdit and widget.displayFormat() in ('dd/MM/yyyy hh:mm:ss', 'yyyy/MM/dd hh:mm:ss')):
        if date is None:
            date = QDateTime.currentDateTime()
        widget.setDateTime(date)
Exemplo n.º 26
0
    def to_event_feature(self, event: dict, fields: QgsFields) -> QgsFeature:  # pylint: disable=too-many-branches
        """
        Converts an event to a feature
        """
        f = QgsFeature(fields)
        for k, v in event.items():

            if k == 'Depth/km' and self.depth_unit == QgsUnitTypes.DistanceMeters:
                k = 'DepthMeters'
            elif k == 'Depth/km':
                k = 'DepthKm'

            try:
                if fields[fields.lookupField(k)].type() == QVariant.DateTime:
                    v = v.replace('--', '00')
                    v = QDateTime.fromString(v, Qt.ISODate)
                elif fields[fields.lookupField(k)].type() == QVariant.Date:
                    v = QDate.fromString(v, Qt.ISODate)
                elif fields[fields.lookupField(k)].type() == QVariant.Time:
                    v = QTime.fromString(v, Qt.ISODate)
                elif fields[fields.lookupField(k)].type() == QVariant.Double:
                    v = float(v)
                elif fields[fields.lookupField(k)].type() == QVariant.Int:
                    v = int(v)
                elif fields[fields.lookupField(k)].type() == QVariant.String:
                    v = v.replace('--', '')
            except Exception:  # pylint: disable=broad-except
                v = NULL

            if k in ('DepthKm', 'DepthMeters') and v != NULL:
                if self.depth_unit == QgsUnitTypes.DistanceMeters:
                    v *= 1000
                if self.convert_negative_depths:
                    v = -v
            f[k] = v

        if event.get('Latitude') and event.get('Longitude'):
            geom = QgsPoint(x=float(event['Longitude']),
                            y=float(event['Latitude']))
            f.setGeometry(QgsGeometry(geom))

        return f
Exemplo n.º 27
0
    def _deriveFromTimeseriesDomainMetadata(cls, metadata):
        def toArray(s, dtype=str):
            if s is None:
                return None
            else:
                return [
                    dtype(v.strip())
                    for v in s.replace('{', '').replace('}', '').split(',')
                ]

        if metadata.get('dates') is None:
            return None
        if metadata.get('names') is None:
            return None

        dates_ = [
            QDate.fromString(datestamp, 'yyyy-MM-dd')
            for datestamp in toArray(metadata['dates'], dtype=str)
        ]
        names_ = toArray(metadata['names'])

        wavelengths_ = metadata.get('wavelength')
        if wavelengths_ is None:
            wavelengths_ = [None] * len(names_)
        else:
            wavelengths_ = toArray(wavelengths_, float)

        # convert into redundant format
        dates = [
            dates_[i] for i in range(len(dates_)) for _ in range(len(names_))
        ]
        names = names_ * len(dates_)
        wavelengths = wavelengths_ * len(dates_)
        units = ['Nanometers'] * len(wavelengths)

        return dates, names, wavelengths, units
Exemplo n.º 28
0
	def _onPointClicked(self, ps_layer, point):
		# get the id of the point feature under the mouse click
		from .MapTools import FeatureFinder
		fid = FeatureFinder.findAtPoint(ps_layer, point, canvas=self.iface.mapCanvas(), onlyTheClosestOne=True, onlyIds=True)
		if fid is None:
			return

		# get the attribute map of the selected feature
		feat = QgsFeature()
		feats = ps_layer.getFeatures( QgsFeatureRequest(fid) )
		feats.nextFeature(feat)
		attrs = feat.attributes()

		x, y = [], []	# lists containg x,y values
		infoFields = {}	# hold the index->name of the fields containing info to be displayed

		ps_source = ps_layer.source()
		ps_fields = ps_layer.dataProvider().fields()

		providerType = ps_layer.providerType()
		uri = ps_source
		subset = ""

		if providerType == 'ogr' and ps_source.lower().endswith( ".shp" ):
			# Shapefile
			for idx, fld in enumerate(ps_fields):
				if QRegExp( "D\\d{8}", Qt.CaseInsensitive ).indexIn( fld.name() ) < 0:
					# info fields are all except those containing dates
					infoFields[ idx ] = fld
				else:
					x.append( QDate.fromString( fld.name()[1:], "yyyyMMdd" ).toPyDate() )
					y.append( float(attrs[ idx ]) )

		elif providerType == 'ogr' and (ps_source.upper().startswith("OCI:") or ps_source.lower().endswith(".vrt")):	# Oracle Spatial

			# fields containing values
			dateField = "data_misura"
			valueField = "spost_rel_mm"
			infoFields = dict(enumerate(ps_fields))

			# search for the id_dataset and code_target fields needed to join
			# PS and TS tables
			idDataset = codeTarget = None
			for idx, fld in enumerate(ps_fields):
				if fld.name().lower() == "id_dataset":
					idDataset = attrs[ idx ]
				if fld.name().lower() == "code_target":
					codeTarget = attrs[ idx ]

			if idDataset is None or codeTarget is None:
				QgsMessageLog.logMessage( "idDataset is %s, codeTarget is %s. Exiting" % (idDataset, codeTarget), "PSTimeSeriesViewer" )
				return
			subset = "id_dataset='%s' AND code_target='%s'" % (idDataset, codeTarget)

			# create the uri
			if ps_source.upper().startswith( "OCI:" ):
				default_tbl_name = "RISKNAT.RNAT_TARGET_SSTO"
			elif ps_source.lower().endswith(".vrt"):
				default_tbl_name = "rnat_target_sso.vrt"
			else:
				default_tbl_name = ""
			if not self._askTStablename( ps_layer,  default_tbl_name ):
				return

			if ps_source.upper().startswith( "OCI:" ):
				# uri is like OCI:userid/password@database:table
				pos = uri.indexOf(':', 4)
				if pos >= 0:
					uri = uri[0:pos]
				uri = "%s:%s" % (uri, self.ts_tablename)
			else:
				# it's a VRT file
				uri = "%s/%s" % (QFileInfo(ps_source).path(), self.ts_tablename)
				uri = QDir.toNativeSeparators( uri )

			# load the layer containing time series
			ts_layer = self._createTSlayer( uri, providerType, subset )
			if ts_layer is None:
				return

			# get time series X and Y values
			try:
				x, y = self._getXYvalues( ts_layer, dateField, valueField )
			finally:
				ts_layer.deleteLater()
				del ts_layer

		elif providerType in ['postgres', 'spatialite']:# either PostGIS or SpatiaLite

			# fields containing values
			dateField = "dataripresa"
			valueField = "valore"
			infoFields = dict(enumerate(ps_fields))

			# search for the id_dataset and code_target fields needed to join
			# PS and TS tables
			code = None
			for idx, fld in enumerate( ps_fields ):
				if fld.name().lower() == "code":
					code = attrs[ idx ]

			if code is None:
				QgsMessageLog.logMessage( "code is None. Exiting" % code, "PSTimeSeriesViewer" )
				return
			subset = "code='%s'" % code

			# create the uri
			dsuri = QgsDataSourceUri( ps_layer.source() )
			default_tbl_name = "ts_%s" % dsuri.table()
			if not self._askTStablename( ps_layer,  default_tbl_name ):
				return
			dsuri.setDataSource( dsuri.schema(), self.ts_tablename, None ) # None or "" ? check during tests
			dsuri.setWkbType(QgsWkbTypes.Unknown)
			dsuri.setSrid(None)
			uri = dsuri.uri()

			# load the layer containing time series
			ts_layer = self._createTSlayer( uri, providerType, subset )
			if ts_layer is None:
				return

			# get time series X and Y values
			try:
				x, y = self._getXYvalues( ts_layer, dateField, valueField )
			finally:
				ts_layer.deleteLater()
				del ts_layer

		if len(x) * len(y) <= 0:
			QMessageBox.warning( self.iface.mainWindow(),
					"PS Time Series Viewer",
					"No time series values found for the selected point." )
			QgsMessageLog.logMessage( "provider: %s - uri: %s\nsubset: %s" % (providerType, uri, subset), "PSTimeSeriesViewer" )
			return

		# display the plot dialog
		from .pstimeseries_dlg import PSTimeSeries_Dlg
		dlg = PSTimeSeries_Dlg( ps_layer, infoFields )
		dlg.setFeatureId( fid )
		dlg.setData( x, y )
		return dlg
Exemplo n.º 29
0
    def processAlgorithm(self, feedback):
        inLayer = dataobjects.getObjectFromUri(
            self.getParameterValue(self.INPUT))
        boundary = self.getParameterValue(self.MODE) == self.MODE_BOUNDARY
        smallestArea = self.getParameterValue(
            self.MODE) == self.MODE_SMALLEST_AREA
        keepSelection = self.getParameterValue(self.KEEPSELECTION)
        processLayer = vector.duplicateInMemory(inLayer)

        if not keepSelection:
            # Make a selection with the values provided
            attribute = self.getParameterValue(self.ATTRIBUTE)
            comparison = self.comparisons[self.getParameterValue(
                self.COMPARISON)]
            comparisonvalue = self.getParameterValue(self.COMPARISONVALUE)

            selectindex = vector.resolveFieldIndex(processLayer, attribute)
            selectType = processLayer.fields()[selectindex].type()
            selectionError = False

            if selectType in [
                    QVariant.Int, QVariant.LongLong, QVariant.UInt,
                    QVariant.ULongLong
            ]:
                try:
                    y = int(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to integer' %
                                  str(comparisonvalue))
            elif selectType == QVariant.Double:
                try:
                    y = float(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to float' %
                                  str(comparisonvalue))
            elif selectType == QVariant.String:
                # 10: string, boolean
                try:
                    y = str(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to Unicode' %
                                  str(comparisonvalue))
            elif selectType == QVariant.Date:
                # date
                dateAndFormat = comparisonvalue.split(' ')

                if len(dateAndFormat) == 1:
                    # QDate object
                    y = QLocale.system().toDate(dateAndFormat[0])

                    if y.isNull():
                        msg = self.tr(
                            'Cannot convert "%s" to date with system date format %s'
                            % (str(dateAndFormat),
                               QLocale.system().dateFormat()))
                elif len(dateAndFormat) == 2:
                    y = QDate.fromString(dateAndFormat[0], dateAndFormat[1])

                    if y.isNull():
                        msg = self.tr(
                            'Cannot convert "%s" to date with format string "%s"'
                            % (str(dateAndFormat[0]), dateAndFormat[1]))
                else:
                    y = QDate()
                    msg = ''

                if y.isNull():
                    # Conversion was unsuccessful
                    selectionError = True
                    msg += self.tr(
                        'Enter the date and the date format, e.g. "07.26.2011" "MM.dd.yyyy".'
                    )

            if (comparison == 'begins with' or comparison == 'contains') \
               and selectType != QVariant.String:
                selectionError = True
                msg = self.tr('"%s" can only be used with string fields' %
                              comparison)

            selected = []

            if selectionError:
                raise GeoAlgorithmExecutionException(
                    self.tr('Error in selection input: %s' % msg))
            else:
                for feature in processLayer.getFeatures():
                    aValue = feature.attributes()[selectindex]

                    if aValue is None:
                        continue

                    if selectType in [
                            QVariant.Int, QVariant.LongLong, QVariant.UInt,
                            QVariant.ULongLong
                    ]:
                        x = int(aValue)
                    elif selectType == QVariant.Double:
                        x = float(aValue)
                    elif selectType == QVariant.String:
                        # 10: string, boolean
                        x = str(aValue)
                    elif selectType == QVariant.Date:
                        # date
                        x = aValue  # should be date

                    match = False

                    if comparison == '==':
                        match = x == y
                    elif comparison == '!=':
                        match = x != y
                    elif comparison == '>':
                        match = x > y
                    elif comparison == '>=':
                        match = x >= y
                    elif comparison == '<':
                        match = x < y
                    elif comparison == '<=':
                        match = x <= y
                    elif comparison == 'begins with':
                        match = x.startswith(y)
                    elif comparison == 'contains':
                        match = x.find(y) >= 0

                    if match:
                        selected.append(feature.id())

            processLayer.selectByIds(selected)

        if processLayer.selectedFeatureCount() == 0:
            ProcessingLog.addToLog(
                ProcessingLog.LOG_WARNING,
                self.tr('%s: (No selection in input layer "%s")' %
                        (self.commandLineName(),
                         self.getParameterValue(self.INPUT))))

        # Keep references to the features to eliminate
        featToEliminate = []
        for aFeat in processLayer.selectedFeatures():
            featToEliminate.append(aFeat)

        # Delete all features to eliminate in processLayer (we won't save this)
        processLayer.startEditing()
        processLayer.deleteSelectedFeatures()

        # ANALYZE
        if len(featToEliminate) > 0:  # Prevent zero division
            start = 20.00
            add = 80.00 / len(featToEliminate)
        else:
            start = 100

        feedback.setProgress(start)
        madeProgress = True

        # We go through the list and see if we find any polygons we can
        # merge the selected with. If we have no success with some we
        # merge and then restart the whole story.
        while madeProgress:  # Check if we made any progress
            madeProgress = False
            featNotEliminated = []

            # Iterate over the polygons to eliminate
            for i in range(len(featToEliminate)):
                feat = featToEliminate.pop()
                geom2Eliminate = feat.geometry()
                bbox = geom2Eliminate.boundingBox()
                fit = processLayer.getFeatures(
                    QgsFeatureRequest().setFilterRect(
                        bbox).setSubsetOfAttributes([]))
                mergeWithFid = None
                mergeWithGeom = None
                max = 0
                min = -1
                selFeat = QgsFeature()

                # use prepared geometries for faster intersection tests
                engine = QgsGeometry.createGeometryEngine(
                    geom2Eliminate.geometry())
                engine.prepareGeometry()

                while fit.nextFeature(selFeat):
                    selGeom = selFeat.geometry()

                    if engine.intersects(selGeom.geometry()):
                        # We have a candidate
                        iGeom = geom2Eliminate.intersection(selGeom)

                        if not iGeom:
                            continue

                        if boundary:
                            selValue = iGeom.length()
                        else:
                            # area. We need a common boundary in
                            # order to merge
                            if 0 < iGeom.length():
                                selValue = selGeom.area()
                            else:
                                selValue = -1

                        if -1 != selValue:
                            useThis = True

                            if smallestArea:
                                if -1 == min:
                                    min = selValue
                                else:
                                    if selValue < min:
                                        min = selValue
                                    else:
                                        useThis = False
                            else:
                                if selValue > max:
                                    max = selValue
                                else:
                                    useThis = False

                            if useThis:
                                mergeWithFid = selFeat.id()
                                mergeWithGeom = QgsGeometry(selGeom)
                # End while fit

                if mergeWithFid is not None:
                    # A successful candidate
                    newGeom = mergeWithGeom.combine(geom2Eliminate)

                    if processLayer.changeGeometry(mergeWithFid, newGeom):
                        madeProgress = True
                    else:
                        raise GeoAlgorithmExecutionException(
                            self.
                            tr('Could not replace geometry of feature with id %s'
                               % mergeWithFid))

                    start = start + add
                    feedback.setProgress(start)
                else:
                    featNotEliminated.append(feat)

            # End for featToEliminate

            featToEliminate = featNotEliminated

        # End while

        # Create output
        output = self.getOutputFromName(self.OUTPUT)
        writer = output.getVectorWriter(processLayer.fields(),
                                        processLayer.wkbType(),
                                        processLayer.crs())

        # Write all features that are left over to output layer
        iterator = processLayer.getFeatures()
        for feature in iterator:
            writer.addFeature(feature)

        # Leave processLayer untouched
        processLayer.rollBack()

        for feature in featNotEliminated:
            writer.addFeature(feature)
Exemplo n.º 30
0
    def processAlgorithm(self, feedback):
        inLayer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT))
        boundary = self.getParameterValue(self.MODE) == self.MODE_BOUNDARY
        smallestArea = self.getParameterValue(self.MODE) == self.MODE_SMALLEST_AREA
        keepSelection = self.getParameterValue(self.KEEPSELECTION)
        processLayer = vector.duplicateInMemory(inLayer)

        if not keepSelection:
            # Make a selection with the values provided
            attribute = self.getParameterValue(self.ATTRIBUTE)
            comparison = self.comparisons[self.getParameterValue(self.COMPARISON)]
            comparisonvalue = self.getParameterValue(self.COMPARISONVALUE)

            selectindex = vector.resolveFieldIndex(processLayer, attribute)
            selectType = processLayer.fields()[selectindex].type()
            selectionError = False

            if selectType in [QVariant.Int, QVariant.LongLong, QVariant.UInt, QVariant.ULongLong]:
                try:
                    y = int(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to integer' % str(comparisonvalue))
            elif selectType == QVariant.Double:
                try:
                    y = float(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to float' % str(comparisonvalue))
            elif selectType == QVariant.String:
                # 10: string, boolean
                try:
                    y = str(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to Unicode' % str(comparisonvalue))
            elif selectType == QVariant.Date:
                # date
                dateAndFormat = comparisonvalue.split(' ')

                if len(dateAndFormat) == 1:
                    # QDate object
                    y = QLocale.system().toDate(dateAndFormat[0])

                    if y.isNull():
                        msg = self.tr('Cannot convert "%s" to date with system date format %s' % (str(dateAndFormat), QLocale.system().dateFormat()))
                elif len(dateAndFormat) == 2:
                    y = QDate.fromString(dateAndFormat[0], dateAndFormat[1])

                    if y.isNull():
                        msg = self.tr('Cannot convert "%s" to date with format string "%s"' % (str(dateAndFormat[0]), dateAndFormat[1]))
                else:
                    y = QDate()
                    msg = ''

                if y.isNull():
                    # Conversion was unsuccessful
                    selectionError = True
                    msg += self.tr('Enter the date and the date format, e.g. "07.26.2011" "MM.dd.yyyy".')

            if (comparison == 'begins with' or comparison == 'contains') \
               and selectType != QVariant.String:
                selectionError = True
                msg = self.tr('"%s" can only be used with string fields' % comparison)

            selected = []

            if selectionError:
                raise GeoAlgorithmExecutionException(
                    self.tr('Error in selection input: %s' % msg))
            else:
                for feature in processLayer.getFeatures():
                    aValue = feature.attributes()[selectindex]

                    if aValue is None:
                        continue

                    if selectType in [QVariant.Int, QVariant.LongLong, QVariant.UInt, QVariant.ULongLong]:
                        x = int(aValue)
                    elif selectType == QVariant.Double:
                        x = float(aValue)
                    elif selectType == QVariant.String:
                        # 10: string, boolean
                        x = str(aValue)
                    elif selectType == QVariant.Date:
                        # date
                        x = aValue  # should be date

                    match = False

                    if comparison == '==':
                        match = x == y
                    elif comparison == '!=':
                        match = x != y
                    elif comparison == '>':
                        match = x > y
                    elif comparison == '>=':
                        match = x >= y
                    elif comparison == '<':
                        match = x < y
                    elif comparison == '<=':
                        match = x <= y
                    elif comparison == 'begins with':
                        match = x.startswith(y)
                    elif comparison == 'contains':
                        match = x.find(y) >= 0

                    if match:
                        selected.append(feature.id())

            processLayer.selectByIds(selected)

        if processLayer.selectedFeatureCount() == 0:
            ProcessingLog.addToLog(ProcessingLog.LOG_WARNING,
                                   self.tr('%s: (No selection in input layer "%s")' % (self.commandLineName(), self.getParameterValue(self.INPUT))))

        # Keep references to the features to eliminate
        featToEliminate = []
        for aFeat in processLayer.selectedFeatures():
            featToEliminate.append(aFeat)

        # Delete all features to eliminate in processLayer (we won't save this)
        processLayer.startEditing()
        processLayer.deleteSelectedFeatures()

        # ANALYZE
        if len(featToEliminate) > 0:  # Prevent zero division
            start = 20.00
            add = 80.00 / len(featToEliminate)
        else:
            start = 100

        feedback.setProgress(start)
        madeProgress = True

        # We go through the list and see if we find any polygons we can
        # merge the selected with. If we have no success with some we
        # merge and then restart the whole story.
        while madeProgress:  # Check if we made any progress
            madeProgress = False
            featNotEliminated = []

            # Iterate over the polygons to eliminate
            for i in range(len(featToEliminate)):
                feat = featToEliminate.pop()
                geom2Eliminate = feat.geometry()
                bbox = geom2Eliminate.boundingBox()
                fit = processLayer.getFeatures(
                    QgsFeatureRequest().setFilterRect(bbox).setSubsetOfAttributes([]))
                mergeWithFid = None
                mergeWithGeom = None
                max = 0
                min = -1
                selFeat = QgsFeature()

                # use prepared geometries for faster intersection tests
                engine = QgsGeometry.createGeometryEngine(geom2Eliminate.geometry())
                engine.prepareGeometry()

                while fit.nextFeature(selFeat):
                    selGeom = selFeat.geometry()

                    if engine.intersects(selGeom.geometry()):
                        # We have a candidate
                        iGeom = geom2Eliminate.intersection(selGeom)

                        if not iGeom:
                            continue

                        if boundary:
                            selValue = iGeom.length()
                        else:
                            # area. We need a common boundary in
                            # order to merge
                            if 0 < iGeom.length():
                                selValue = selGeom.area()
                            else:
                                selValue = -1

                        if -1 != selValue:
                            useThis = True

                            if smallestArea:
                                if -1 == min:
                                    min = selValue
                                else:
                                    if selValue < min:
                                        min = selValue
                                    else:
                                        useThis = False
                            else:
                                if selValue > max:
                                    max = selValue
                                else:
                                    useThis = False

                            if useThis:
                                mergeWithFid = selFeat.id()
                                mergeWithGeom = QgsGeometry(selGeom)
                # End while fit

                if mergeWithFid is not None:
                    # A successful candidate
                    newGeom = mergeWithGeom.combine(geom2Eliminate)

                    if processLayer.changeGeometry(mergeWithFid, newGeom):
                        madeProgress = True
                    else:
                        raise GeoAlgorithmExecutionException(
                            self.tr('Could not replace geometry of feature with id %s' % mergeWithFid))

                    start = start + add
                    feedback.setProgress(start)
                else:
                    featNotEliminated.append(feat)

            # End for featToEliminate

            featToEliminate = featNotEliminated

        # End while

        # Create output
        output = self.getOutputFromName(self.OUTPUT)
        writer = output.getVectorWriter(processLayer.fields(),
                                        processLayer.wkbType(), processLayer.crs())

        # Write all features that are left over to output layer
        iterator = processLayer.getFeatures()
        for feature in iterator:
            writer.addFeature(feature)

        # Leave processLayer untouched
        processLayer.rollBack()

        for feature in featNotEliminated:
            writer.addFeature(feature)
Exemplo n.º 31
0
    def construct_form_param_system(self, row, pos):

        widget = None
        for field in row[pos]['fields']:
            if field['label']:
                lbl = QLabel()
                lbl.setObjectName('lbl' + field['widgetname'])
                lbl.setText(field['label'])
                lbl.setMinimumSize(160, 0)
                lbl.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
                lbl.setToolTip(field['tooltip'])

                if field['widgettype'] == 'text' or field[
                        'widgettype'] == 'linetext':
                    widget = QLineEdit()
                    widget.setText(field['value'])
                    widget.editingFinished.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'textarea':
                    widget = QTextEdit()
                    widget.setText(field['value'])
                    widget.editingFinished.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'combo':
                    widget = QComboBox()
                    self.populate_combo(widget, field)
                    widget.currentIndexChanged.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'checkbox' or field[
                        'widgettype'] == 'check':
                    widget = QCheckBox()
                    if field['value'] in ('true', 'True', 'TRUE', True):
                        widget.setChecked(True)
                    elif field['value'] in ('false', 'False', 'FALSE', False):
                        widget.setChecked(False)
                    widget.stateChanged.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
                elif field['widgettype'] == 'datetime':
                    widget = QDateEdit()
                    widget.setCalendarPopup(True)
                    if field['value']:
                        field['value'] = field['value'].replace('/', '-')
                    date = QDate.fromString(field['value'], 'yyyy-MM-dd')
                    widget.setDate(date)
                    widget.dateChanged.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'spinbox':
                    widget = QSpinBox()
                    if 'value' in field and field['value'] is not None:
                        value = float(str(field['value']))
                        widget.setValue(value)
                    widget.valueChanged.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                else:
                    pass

                if widget:
                    widget.setObjectName(field['widgetname'])
                else:
                    pass

                # Order Widgets
                if 'layoutname' in field:
                    if field['layoutname'] == 'lyt_topology':
                        self.order_widgets_system(field, self.topology_form,
                                                  lbl, widget)
                    elif field['layoutname'] == 'lyt_builder':
                        self.order_widgets_system(field, self.builder_form,
                                                  lbl, widget)
                    elif field['layoutname'] == 'lyt_review':
                        self.order_widgets_system(field, self.review_form, lbl,
                                                  widget)
                    elif field['layoutname'] == 'lyt_analysis':
                        self.order_widgets_system(field, self.analysis_form,
                                                  lbl, widget)
                    elif field['layoutname'] == 'lyt_system':
                        self.order_widgets_system(field, self.system_form, lbl,
                                                  widget)
Exemplo n.º 32
0
    def construct_form_param_system(self, row, pos):

        widget = None
        for field in row[pos]['fields']:
            if field['label']:
                lbl = QLabel()
                lbl.setObjectName('lbl' + field['widgetname'])
                lbl.setText(field['label'])
                lbl.setMinimumSize(160, 0)
                lbl.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
                lbl.setToolTip(field['tooltip'])

                if field['widgettype'] == 'text' or field[
                        'widgettype'] == 'linetext':
                    widget = QLineEdit()
                    widget.setText(field['value'])
                    widget.editingFinished.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'textarea':
                    widget = QTextEdit()
                    widget.setText(field['value'])
                    widget.editingFinished.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'combo':
                    widget = QComboBox()
                    self.populate_combo(widget, field)
                    widget.currentIndexChanged.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'checkbox' or field[
                        'widgettype'] == 'check':
                    widget = QCheckBox()
                    if field['value'].lower() == 'true':
                        widget.setChecked(True)
                    elif field['value'].lower() == 'FALSE':
                        widget.setChecked(False)
                    widget.stateChanged.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
                elif field['widgettype'] == 'datepickertime':
                    widget = QDateEdit()
                    widget.setCalendarPopup(True)
                    date = QDate.fromString(field['value'], 'yyyy/MM/dd')
                    widget.setDate(date)
                    widget.dateChanged.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'spinbox':
                    widget = QDoubleSpinBox()
                    if 'value' in field and field['value'] is not None:
                        value = float(str(field['value']))
                        widget.setValue(value)
                    widget.valueChanged.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                else:
                    pass

                if widget:
                    widget.setObjectName(field['widgetname'])
                else:
                    pass

                # Order Widgets
                if field['layout_id'] == 1:
                    self.order_widgets_system(field, self.basic_form, lbl,
                                              widget)
                elif field['layout_id'] == 2:
                    self.order_widgets_system(field, self.om_form, lbl, widget)
                elif field['layout_id'] == 3:
                    self.order_widgets_system(field, self.workcat_form, lbl,
                                              widget)
                elif field['layout_id'] == 4:
                    self.order_widgets_system(field, self.mapzones_form, lbl,
                                              widget)
                elif field['layout_id'] == 5:
                    self.order_widgets_system(field, self.cad_form, lbl,
                                              widget)
                elif field['layout_id'] == 6:
                    self.order_widgets_system(field, self.epa_form, lbl,
                                              widget)
                elif field['layout_id'] == 7:
                    self.order_widgets_system(field, self.masterplan_form, lbl,
                                              widget)
                elif field['layout_id'] == 8:
                    self.order_widgets_system(field, self.other_form, lbl,
                                              widget)
                elif field['layout_id'] == 9:
                    self.order_widgets_system(field, self.node_type_form, lbl,
                                              widget)
                elif field['layout_id'] == 10:
                    self.order_widgets_system(field, self.cat_form, lbl,
                                              widget)
                elif field['layout_id'] == 11:
                    self.order_widgets_system(field, self.utils_form, lbl,
                                              widget)
                elif field['layout_id'] == 12:
                    self.order_widgets_system(field, self.connec_form, lbl,
                                              widget)
                elif field['layout_id'] == 13:
                    self.order_widgets_system(field, self.topology_form, lbl,
                                              widget)
                elif field['layout_id'] == 14:
                    self.order_widgets_system(field, self.builder_form, lbl,
                                              widget)
                elif field['layout_id'] == 15:
                    self.order_widgets_system(field, self.review_form, lbl,
                                              widget)
                elif field['layout_id'] == 16:
                    self.order_widgets_system(field, self.analysis_form, lbl,
                                              widget)
                elif field['layout_id'] == 17:
                    self.order_widgets_system(field, self.system_form, lbl,
                                              widget)
Exemplo n.º 33
0
# coding=utf-8
from builtins import object
from qgis.PyQt.QtCore import QDate, QDateTime
from qgis.PyQt.QtWidgets import QAbstractSpinBox

from EditorMetadadosMarswInforbiomares import CONSTANTS as cons

NULLDATE = QDate.fromString('1800-01-01', cons.DATE_FORMAT)
NULLDATETIME = QDateTime.fromString('1800-01-01 00:00:00', cons.DATE_TIME_FORMAT)


class NullQDateEditWrapper(object):
    """

    """

    def __init__(self, qdate_edit):
        self.qdate_edit = qdate_edit
        self.callable_results = []
        self.qdate_edit.setDisplayFormat(cons.DATE_FORMAT)
        self.qdate_edit.setMinimumDate(NULLDATE)
        self.qdate_edit.setSpecialValueText(u"Não Definido")
        self.qdate_edit.setDate(NULLDATE)
        self.qdate_edit.setCalendarPopup(True)
        self.qdate_edit.setButtonSymbols(QAbstractSpinBox.NoButtons)
        self.qdate_edit.editingFinished.connect(self.correct_date)

    def correct_date(self):
        if self.qdate_edit.date() == NULLDATE:
            self.qdate_edit.setDate(QDate.currentDate())
Exemplo n.º 34
0
    def _onPointClicked(self, ps_layer, point):
        # get the id of the point feature under the mouse click
        from .MapTools import FeatureFinder
        fid = FeatureFinder.findAtPoint(ps_layer,
                                        point,
                                        canvas=self.iface.mapCanvas(),
                                        onlyTheClosestOne=True,
                                        onlyIds=True)
        if fid is None:
            return

        # get the attribute map of the selected feature
        feat = QgsFeature()
        feats = ps_layer.getFeatures(QgsFeatureRequest(fid))
        feats.nextFeature(feat)
        attrs = feat.attributes()

        x, y = [], []  # lists containg x,y values
        infoFields = {
        }  # hold the index->name of the fields containing info to be displayed

        ps_source = ps_layer.source()
        ps_fields = ps_layer.dataProvider().fields()

        providerType = ps_layer.providerType()
        uri = ps_source
        subset = ""

        if providerType == 'ogr' and ps_source.lower().endswith(".shp"):
            # Shapefile
            for idx, fld in enumerate(ps_fields):
                if QRegExp("D\\d{8}", Qt.CaseInsensitive).indexIn(
                        fld.name()) < 0:
                    # info fields are all except those containing dates
                    infoFields[idx] = fld
                else:
                    x.append(
                        QDate.fromString(fld.name()[1:],
                                         "yyyyMMdd").toPyDate())
                    y.append(float(attrs[idx]))

        elif providerType == 'ogr' and (
                ps_source.upper().startswith("OCI:")
                or ps_source.lower().endswith(".vrt")):  # Oracle Spatial

            # fields containing values
            dateField = "data_misura"
            valueField = "spost_rel_mm"
            infoFields = dict(enumerate(ps_fields))

            # search for the id_dataset and code_target fields needed to join
            # PS and TS tables
            idDataset = codeTarget = None
            for idx, fld in enumerate(ps_fields):
                if fld.name().lower() == "id_dataset":
                    idDataset = attrs[idx]
                if fld.name().lower() == "code_target":
                    codeTarget = attrs[idx]

            if idDataset is None or codeTarget is None:
                QgsMessageLog.logMessage(
                    "idDataset is %s, codeTarget is %s. Exiting" %
                    (idDataset, codeTarget), "PSTimeSeriesViewer")
                return
            subset = "id_dataset='%s' AND code_target='%s'" % (idDataset,
                                                               codeTarget)

            # create the uri
            if ps_source.upper().startswith("OCI:"):
                default_tbl_name = "RISKNAT.RNAT_TARGET_SSTO"
            elif ps_source.lower().endswith(".vrt"):
                default_tbl_name = "rnat_target_sso.vrt"
            else:
                default_tbl_name = ""
            if not self._askTStablename(ps_layer, default_tbl_name):
                return

            if ps_source.upper().startswith("OCI:"):
                # uri is like OCI:userid/password@database:table
                pos = uri.indexOf(':', 4)
                if pos >= 0:
                    uri = uri[0:pos]
                uri = "%s:%s" % (uri, self.ts_tablename)
            else:
                # it's a VRT file
                uri = "%s/%s" % (QFileInfo(ps_source).path(),
                                 self.ts_tablename)
                uri = QDir.toNativeSeparators(uri)

            # load the layer containing time series
            ts_layer = self._createTSlayer(uri, providerType, subset)
            if ts_layer is None:
                return

            # get time series X and Y values
            try:
                x, y = self._getXYvalues(ts_layer, dateField, valueField)
            finally:
                ts_layer.deleteLater()
                del ts_layer

        elif providerType in ['postgres',
                              'spatialite']:  # either PostGIS or SpatiaLite

            # fields containing values
            dateField = "dataripresa"
            valueField = "valore"
            infoFields = dict(enumerate(ps_fields))

            # search for the id_dataset and code_target fields needed to join
            # PS and TS tables
            code = None
            for idx, fld in enumerate(ps_fields):
                if fld.name().lower() == "code":
                    code = attrs[idx]

            if code is None:
                QgsMessageLog.logMessage("code is None. Exiting" % code,
                                         "PSTimeSeriesViewer")
                return
            subset = "code='%s'" % code

            # create the uri
            dsuri = QgsDataSourceUri(ps_layer.source())
            default_tbl_name = "ts_%s" % dsuri.table()
            if not self._askTStablename(ps_layer, default_tbl_name):
                return
            dsuri.setDataSource(dsuri.schema(), self.ts_tablename,
                                None)  # None or "" ? check during tests
            dsuri.setWkbType(QgsWkbTypes.Unknown)
            dsuri.setSrid(None)
            uri = dsuri.uri()

            # load the layer containing time series
            ts_layer = self._createTSlayer(uri, providerType, subset)
            if ts_layer is None:
                return

            # get time series X and Y values
            try:
                x, y = self._getXYvalues(ts_layer, dateField, valueField)
            finally:
                ts_layer.deleteLater()
                del ts_layer

        if len(x) * len(y) <= 0:
            QMessageBox.warning(
                self.iface.mainWindow(), "PS Time Series Viewer",
                "No time series values found for the selected point.")
            QgsMessageLog.logMessage(
                "provider: %s - uri: %s\nsubset: %s" %
                (providerType, uri, subset), "PSTimeSeriesViewer")
            return

        # display the plot dialog
        from .pstimeseries_dlg import PSTimeSeries_Dlg
        dlg = PSTimeSeries_Dlg(ps_layer, infoFields)
        dlg.setFeatureId(fid)
        dlg.setData(x, y)
        return dlg