Example #1
0
    def IfGet(self):
        def plot1():
            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "捕获时间分析-结束")
            CatchT = model.run1DB.get('CatchTime')
            if CatchT == 0:
                QMessageBox.information(self, "注意!", "星载雷达没有截获导弹",
                                        QMessageBox.Ok)
            else:
                self.lineEdit_24.setText('%d' % CatchT)

        def plot2():
            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "捕获概率分析-结束")
            detectionP = model.run1DB.get('DetectionProbality')
            self.lineEdit_23.setText('%.7f' % detectionP)

        self.parent().textBrowser.append(
            QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "捕获时间分析-开始")
        with self.lock:
            self.newthread = PlotThread(Process.CatchTime, plot1)
            self.newthread.start()

        self.parent().textBrowser.append(
            QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "捕获概率分析-开始")
        with self.lock:
            self.newthread = PlotThread(Process.DetectionProbality, plot2)
            self.newthread.start()
Example #2
0
    def SaveAnalyseResult(self):
        r = QMessageBox.warning(self, "注意!", "是否全部运行完?",
                                QMessageBox.Yes | QMessageBox.No)
        if r == QMessageBox.Yes:
            data_dist = {
                'EmitSignal': model.run1DB.get('EmitSignal'),
                'ClutterSignal': model.run1DB.get('ClutterSignal'),
                'ClutterSignalFFT': model.run1DB.get('ClutterSignalFFT'),
                'MTIout': model.run1DB.get('MTIout'),
                'MTDout': model.run1DB.get('MTDout'),
                'DetectionProbality': model.run1DB.get('DetectionProbality'),
                'CatchTime': model.run1DB.get('CatchTime'),
            }
            data_dist2 = {
                'N': model.run2DB.get('N'),
                'number': model.run2DB.get('number'),

                'SampleRate': model.run1DB.get('SampleRate'),
            }
            try:
                model.lastDB.append(data_dist)
                model.lastDB.append(data_dist2)
                model.lastDB.dump()
                self.parent().textBrowser.append(
                    QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "保存本次仿真结果---成功")
            except TypeError:
                QMessageBox.warning(self, "注意!", "数据类型错误或不存在")
                self.parent().textBrowser.append(
                    QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "保存本次仿真结果---失败(数据类型错误或不存在)")
        else:
            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "保存本次仿真结果---失败(未运行所有结果)")
 def setTimeslice(self, ts):
     if not ts == self.chart.timeslice:
         maxdt = QDateTime()
         maxdt.setTime_t(self.chart.sensorgroup.stop-ts)
         self.StartInput.setMaximumDate(maxdt.date())
         self.chart.setTimeslice(ts)
         self.updateChart()
Example #4
0
    def MissileMatTriggered(self):
        # 读取MAT
        self.parent().textBrowser.append(
            QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "读取导弹参数设定文件")
        self.LoadMissileMat = QFileDialog.getOpenFileName(self, "Load a missile Mat File!", ".", "MAT Files (*.mat)")
        self.lineEdit_7.setText(self.LoadMissileMat)
        self.textBrowser_5.clear()
        # 检查filename是否存在,内容是否合理!!
        if self.LoadMissileMat:
            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString(
                    "yyyy.MM.dd hh:mm:ss:zzz ") + "尝试显示文件" + self.LoadMissileMat + "中具体参数内容")
            mat_content = sio.loadmat(self.LoadMissileMat)
            try:
                self.Missile_Data_dic = {
                    'mp_L': mat_content['mp_L'][0, 0], 'mp_B': mat_content['mp_B'][0, 0],
                    'mp_H': mat_content['mp_H'][0, 0],
                    'mv_x': mat_content['mv_x'][0, 0], 'mv_y': mat_content['mv_y'][0, 0],
                    'mv_z': mat_content['mv_z'][0, 0],
                    'ma_x': mat_content['ma_x'][0, 0], 'ma_y': mat_content['ma_y'][0, 0],
                    'ma_z': mat_content['ma_z'][0, 0],
                }
                content_string = ''.join('{}: {}\n'.format(key, var) for key, var in sorted(self.Missile_Data_dic.items()))
                self.textBrowser_5.setText(content_string)
                self.parent().textBrowser.append(
                    QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "显示"+ self.LoadMissileMat + "成功")
            except KeyError:
                self.LoadMissileMat=""
                self.textBrowser_5.setText('对不起,该参数文件已损坏,请尝试其他参数文件,或自行设定具体参数内容')
                self.parent().textBrowser.append(
                    QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "显示过程中发现参数设定文件已损坏")

        else:
            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "导弹参数设定文件路径未设定")
Example #5
0
    def save_recent_projects(self, folder):
        recent_project_list = QSettings().value('recentProjects', {}).toMap()
        #if already exist on the list update the date time
        projectProperties = json_manager.read_ninja_project(folder)
        name = projectProperties.get('name', '')
        description = projectProperties.get('description', '')

        if name == '':
            name = file_manager.get_basename(folder)

        if description == '':
            description = self.tr('no description available')

        if QString(folder) in recent_project_list:
            properties = recent_project_list[QString(folder)].toMap()
            properties[QString("lastopen")] = QDateTime.currentDateTime()
            properties[QString("name")] = name
            properties[QString("description")] = description
            recent_project_list[QString(folder)] = properties
        else:
            recent_project_list[QString(folder)] = {
                "name": name,
                "description": description,
                "isFavorite": False, "lastopen": QDateTime.currentDateTime()}
            #if the length of the project list it's high that 10 then delete
            #the most old
            #TODO: add the length of available projects to setting
            if len(recent_project_list) > 10:
                del recent_project_list[self.find_most_old_open()]
        QSettings().setValue('recentProjects', recent_project_list)
 def __init__(self):
     ProviderConfig.__init__(self)
     self.url = 'http://localhost:8080/geoserver/wps'
     #self.url = 'http://172.19.115.90:8080/geoserver/wps'
     self.wps_id = 'gs:JRodosGeopkgWPS'  # gs:JRodosWPS = one zipped shapefile, gs:JRodosGeopkgWPS = one GeoPackage
     self.user = '******'
     self.password = '******'
     # taskArg parameter:
     self.jrodos_project = "'wps-test-3'"
     # dataitem parameter:
     self.jrodos_path = "'Model data=;=Output=;=Prognostic Results=;=Potential doses=;=Total potential dose=;=effective'"
     # jrodos_path=  "'Model data=;=Output=;=Prognostic Results=;=Cloud arrival time=;=Cloud arrival time'"  # 1
     # jrodos_path = "'Model data=;=Output=;=Prognostic Results=;=Activity concentrations=;=Air concentration, time integrated near ground surface=;=I -135'" # 24
     # jrodos_path = "'Model data=;=Output=;=Prognostic Results=;=Activity concentrations=;=Air concentration, time integrated near ground surface=;=Cs-137'" # 24
     # jrodos_path = "'Model data=;=Output=;=Prognostic Results=;=Activity concentrations=;=Ground contamination dry+wet=;=I -135'" # 24
     # jrodos_path = "'Model data=;=Output=;=Prognostic Results=;=Activity concentrations=;=Ground contamination dry+wet=;=Cs-137'" # 24
     # jrodos_path = "'Model data=;=Output=;=Prognostic Results=;=Potential doses=;=Total potential dose=;=effective'"
     # this 3 props define the column parameter
     self.jrodos_datetime_start = QDateTime(QDate(2016, 05, 17), QTime(6, 0))
     self.jrodos_model_time = -1  # IN MINUTES !
     self.jrodos_model_step = 3600  # IN SECONDS !
     self.jrodos_columns = 0  # starting at 0, but can also be a range: '0,' '0-23', '0-'
     # vertical parameter:
     self.jrodos_verticals = 0  # z / layers
     # actual output format for WPS
     self.jrodos_format = "application/zip"  # format = "application/zip" "text/xml; subtype=wfs-collection/1.0"
     self.jrodos_datetime_start = QDateTime(QDate(2016, 05, 17), QTime(6, 0))
     self.jrodos_datetime_format = "yyyy-MM-ddTHH:mm:ss.000 00:00"  # '2016-04-25T08:00:00.000+00:00'
     self.timestamp = datetime.now().strftime("%Y%m%d%H%M%f")
     self.units = ''
Example #7
0
	def set(self, tpl):
		self.idLabel.setText(str(tpl[0]))
		self.beginEdit.setDateTime(QDateTime.fromTime_t(tpl[1]))
		self.endEdit.setDateTime(QDateTime.fromTime_t(tpl[2]))
		self.timeDiff.setText( self.mkDiff( tpl[1], tpl[2] ) )
		self.descriptionEdit.setText(str(tpl[3]))
		self.noteEdit.setText(str(tpl[4]))
Example #8
0
    def save_recent_projects(self, folder):
        recent_project_list = QSettings(
            resources.SETTINGS_PATH, QSettings.IniFormat).value(
                'recentProjects', {})

        project = nproject.NProject(folder)
        #if already exist on the list update the date time
        if folder in recent_project_list:
            properties = recent_project_list[folder]
            properties["lastopen"] = QDateTime.currentDateTime()
            properties["name"] = project.name
            properties["description"] = project.description
            recent_project_list[folder] = properties
        else:
            recent_project_list[folder] = {
                "name": project.name,
                "description": project.description,
                "isFavorite": False, "lastopen": QDateTime.currentDateTime()}
            #if the length of the project list it's high that 10 then delete
            #the most old
            #TODO: add the length of available projects to setting
            if len(recent_project_list) > 10:
                del recent_project_list[self.find_most_old_open()]
        QSettings(resources.SETTINGS_PATH, QSettings.IniFormat).setValue(
            'recentProjects', recent_project_list)
Example #9
0
 def minimum( self ):
     """
     Returns the minimum value for this ruler.  If the cached value is None,
     then a default value will be specified based on the ruler type.
     
     :return     <variant>
     """
     if ( self._minimum is not None ):
         return self._minimum
     
     rtype = self.rulerType()
     
     if ( rtype == XChartRuler.Type.Number ):
         self._minimum = 0
         
     elif ( rtype == XChartRuler.Type.Date ):
         self._minimum = QDate.currentDate()
     
     elif ( rtype == XChartRuler.Type.Datetime ):
         self._minimum = QDateTime.currentDateTime()
     
     elif ( rtype == XChartRuler.Type.Time ):
         self._minimum = QDateTime.currentDateTime().time()
     
     else:
         notches = self.notches()
         if ( notches ):
             self._minimum = notches[0]
     
     return self._minimum
Example #10
0
    def add_talk(self):
        date = self.addTalkWidget.dateEdit.date()
        time = self.addTalkWidget.timeEdit.time()
        datetime = QDateTime(date, time)
        presentation = Presentation(unicode(self.addTalkWidget.titleLineEdit.text()),
                                    unicode(self.addTalkWidget.presenterLineEdit.text()),
                                    "",  # description
                                    "",  # level
                                    unicode(self.addTalkWidget.eventLineEdit.text()),
                                    unicode(self.addTalkWidget.roomLineEdit.text()),
                                    unicode(datetime.toString(Qt.ISODate)))

        # Do not add talks if they are empty strings
        if (len(presentation.title) == 0):
            return

        self.db.insert_presentation(presentation)

        # cleanup
        self.addTalkWidget.titleLineEdit.clear()
        self.addTalkWidget.presenterLineEdit.clear()

        self.presentationModel.select()

        self.hide_add_talk_widget()

        # If this is launched from the recording app
        # refresh the talk list
        if self.recordapp:
            self.recordapp.load_event_list()
Example #11
0
 def __init__(self, date):
     if date:
         d = QDateTime(QDate(0, 0, 0))
         d.setTime_t(int(date))
         EdwCell.__init__(self, d.toString("yyyy-MM-dd hh:mm"))
     else:
         EdwCell.__init__(self, tr("Never"))
Example #12
0
    def save_recent_projects(self, folder):
        settings = IDE.data_settings()
        recent_project_list = settings.value('recentProjects', {})
        #if already exist on the list update the date time
        projectProperties = json_manager.read_ninja_project(folder)
        name = projectProperties.get('name', '')
        description = projectProperties.get('description', '')

        if name == '':
            name = file_manager.get_basename(folder)

        if description == '':
            description = translations.TR_NO_DESCRIPTION

        if folder in recent_project_list:
            properties = recent_project_list[folder]
            properties["lastopen"] = QDateTime.currentDateTime()
            properties["name"] = name
            properties["description"] = description
            recent_project_list[folder] = properties
        else:
            recent_project_list[folder] = {
                "name": name,
                "description": description,
                "isFavorite": False, "lastopen": QDateTime.currentDateTime()}
            #if the length of the project list it's high that 10 then delete
            #the most old
            #TODO: add the length of available projects to setting
            if len(recent_project_list) > 10:
                del recent_project_list[self.find_most_old_open(
                    recent_project_list)]
        settings.setValue('recentProjects', recent_project_list)
Example #13
0
    def add_talk(self):
        date = self.addTalkWidget.dateEdit.date()
        time = self.addTalkWidget.timeEdit.time()
        datetime = QDateTime(date, time)
        presentation = Presentation(unicode(self.addTalkWidget.titleLineEdit.text()),
                                    unicode(self.addTalkWidget.presenterLineEdit.text()),
                                    "",  # description
                                    "",  # level
                                    unicode(self.addTalkWidget.eventLineEdit.text()),
                                    unicode(self.addTalkWidget.roomLineEdit.text()),
                                    unicode(datetime.toString()))

        # Do not add talks if they are empty strings
        if (len(presentation.title) == 0):
            return

        self.db.insert_presentation(presentation)

        # cleanup
        self.addTalkWidget.titleLineEdit.clear()
        self.addTalkWidget.presenterLineEdit.clear()

        self.failureModel.select()

        self.hide_add_talk_widget()
Example #14
0
    def run(self):
        while 1:
            if not self.exec_():
                return False

            try:
                if self.ui.starttime.dateTime() >= self.ui.endtime.dateTime():
                        QMessageBox.critical(self, self.tr('Range error'),
                                            self.tr('Start time is superior to end time'),
                                            QMessageBox.Ok)
                if self.parent != None:
                    start = QDateTime.fromTime_t( \
                                        self.ui.starttime.dateTime().toTime_t() - self.parent.interval.delta() \
                                                )
                    end = QDateTime.fromTime_t( \
                                        self.ui.endtime.dateTime().toTime_t() - self.parent.interval.delta() \
                                                )
                    self.parent.interval = Interval('custom', start, end)

                    self.parent.interval.setLastStartTime(self.ui.starttime.dateTime().toTime_t())
                    self.parent.interval.setLastEndClient(self.ui.endtime.dateTime().toTime_t())
                return True

            except CheckError, e:
                QMessageBox.critical(self, self.tr("Invalid argument"),
                                           unicode(e), QMessageBox.Ok)
Example #15
0
def interval_previous_week():
    date = QDate.currentDate()
    end = QDateTime(date.addDays(-(date.dayOfWeek() - 1)))
    begin = QDateTime(date.addDays(-(date.dayOfWeek() - 1) - 7))
    return {'start_time': begin.toTime_t(),
            'end_time':   end.toTime_t()
           }
Example #16
0
    def save_recent_projects(self, folder):
        recent_project_list = QSettings().value("recentProjects", {})
        # if already exist on the list update the date time
        projectProperties = json_manager.read_ninja_project(folder)
        name = projectProperties.get("name", "")
        description = projectProperties.get("description", "")

        if name == "":
            name = file_manager.get_basename(folder)

        if description == "":
            description = self.tr("no description available")

        if folder in recent_project_list:
            properties = recent_project_list[folder]
            properties["lastopen"] = QDateTime.currentDateTime()
            properties["name"] = name
            properties["description"] = description
            recent_project_list[folder] = properties
        else:
            recent_project_list[folder] = {
                "name": name,
                "description": description,
                "isFavorite": False,
                "lastopen": QDateTime.currentDateTime(),
            }
            # if the length of the project list it's high that 10 then delete
            # the most old
            # TODO: add the length of available projects to setting
            if len(recent_project_list) > 10:
                del recent_project_list[self.find_most_old_open()]
        QSettings().setValue("recentProjects", recent_project_list)
Example #17
0
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget
        @type QWidget
        """
        QMainWindow.__init__(self, parent)
        self.setupUi(self)

        # init event
        # self.btn_Query.clicked.connect(self.on_btn_Query_clicked)

        # 获得系统默认编码格式
        self.sysCharType = sys.getfilesystemencoding()

        self.data_list_youka = None

        now_time = str(datetime.date.today()) + ' 00:00:00'
        from_time_default = get_default_time(-1)
        self.date_from.setDateTime(QDateTime.fromString(from_time_default, 'yyyy-MM-dd hh:mm:ss'))
        self.date_end.setDateTime(QDateTime.fromString(now_time, 'yyyy-MM-dd hh:mm:ss'))
        # init table_results
        self.table_results.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.table_results.setColumnCount(3)
        self.table_results.setRowCount(0)
        self.table_results.setHorizontalHeaderLabels([u'学校代码', u'学校名称', u'增长数量'])
Example #18
0
    def showpickdialog(self):
        """
        Open the date time picker dialog

        control - The control that will recive the user set date time.
        """

        if type(self.datewidget) is QDateEdit:
            mode = "Date"
        else:
            mode = "DateTime"

        dlg = DateTimePickerDialog(mode)
        dlg.setWindowTitle("Select a date")
        if self.datewidget.dateTime() == DateWidget.DEFAULTDATE:
            dlg.setAsNow()
        else:
            dlg.setDateTime(self.datewidget.dateTime())

        dlg.setMinValue(self.datewidget.minimumDate())
        if dlg.exec_():
            datetime = QDateTime()
            datetime.setDate(dlg.getSelectedDate())
            datetime.setTime(dlg.getSelectedTime())
            self.setvalue(datetime)
Example #19
0
	def __convertXData(self, data):
		loc = QLocale()
		out = []
		for polozka in data:
			time = QDateTime()
			time.setTime_t(polozka)
			out.append(time.toString(loc.dateFormat(QLocale.ShortFormat)))
		return out
 def go(self, p, rel=True):
     if rel:
         t = self.StartInput.dateTime().toTime_t()
     else:
         t = 0
     dt = QDateTime()
     dt.setTime_t(t + p)
     self.StartInput.setDateTime(dt)
Example #21
0
    def filter_score(self, index):
        """
            Returns the number of filters matching the given index.

            :param index:
                The index of the item that will be checked against the filters.
        """
        column = index.column()
        field_name = self.git_model.get_columns()[column]
        filters = self._filters

        if field_name in TIME_FIELDS:
            filters = self._filters
            timestamp, tz = self.git_model.data(index)
            _q_datetime = QDateTime()
            _q_datetime.setTime_t(timestamp)

            item_date = _q_datetime.date()
            item_weekday = item_date.dayOfWeek()
            item_time = _q_datetime.time()

            date_time_filters = ("afterWeekday", "beforeWeekday",
                                 "beforeDate", "afterDate",
                                 "beforeHour", "afterHour")
            has_date_time_filter = False
            for model_filter in filters:
                if model_filter in date_time_filters:
                    has_date_time_filter = True

            if not has_date_time_filter:
                return 0
            else:
                return self.date_match(item_date) + \
                       self.weekday_match(item_weekday) + \
                       self.time_match(item_time)

        elif field_name in ACTOR_FIELDS:
            if "nameEmail" in filters:
                regexp = filters["nameEmail"]
                value = self.git_model.data(index)
                if regexp.isValid() and regexp.indexIn(value) != -1:
                    return 1

        elif field_name in TEXT_FIELDS:
            if "message" in filters:
                regexp = filters["message"]
                commit_message = self.git_model.data(index)
                if regexp.isValid() and regexp.indexIn(commit_message) != -1:
                    return 1

        elif field_name == "hexsha":
            if "localOnly" in filters:
                commits = self.git_model.get_commits()
                commit = commits[index.row()]
                if not self.git_model.is_commit_pushed(commit):
                    return 1

        return 0
 def init_date(self):
     date_from_last = str(tool.get_lastweek_someday(calendar.MONDAY) + datetime.timedelta(days=-9)) + ' 00:00:00'
     self.date_from_last.setDateTime(QDateTime.fromString(date_from_last, 'yyyy-MM-dd hh:mm:ss'))
     date_end_last = str(tool.get_lastweek_someday(calendar.MONDAY) + datetime.timedelta(days=-2)) + ' 00:00:00'
     self.date_end_last.setDateTime(QDateTime.fromString(date_end_last, 'yyyy-MM-dd hh:mm:ss'))
     date_from = str(tool.get_lastweek_someday(calendar.MONDAY) + datetime.timedelta(days=-2)) + ' 00:00:00'
     self.date_from.setDateTime(QDateTime.fromString(date_from, 'yyyy-MM-dd hh:mm:ss'))
     date_end = str(tool.get_current_week_someday(5)) + ' 00:00:00'
     self.date_end.setDateTime(QDateTime.fromString(date_end, 'yyyy-MM-dd hh:mm:ss'))
 def setTimeSpan(self, time_values):
     self._time_from = self._time_to = None
     if time_values is not None and len(time_values):
         self._time_to = time_to = QDateTime.fromMSecsSinceEpoch(1000 * time_values[-1]).toUTC()
         if len(time_values) > 1:
             time_from = QDateTime.fromMSecsSinceEpoch(1000 * time_values[0]).toUTC()
             if time_from.secsTo(time_to) < 23 * 3600:  # timespan < 23 hours
                 self._time_from = time_from
     self.update()
Example #24
0
 def emit_now(self):
     formatted_date = self.meet.daysTo(QDateTime.currentDateTime())
     one_day_seconds = (self.meet.secsTo(QDateTime.currentDateTime())
               - formatted_date *24 * 60 * 60)
     hours = one_day_seconds / 3600
     minutes = one_day_seconds / 60 - hours * 60 
     seconds = one_day_seconds % 60
     msgString = u'亲爱的,从我们相遇至今已经有 %s天 %s小时 %s分钟 %s秒了 \n\n\n你是我的天使,每一分钟,每一秒钟我都很宝贝.\n\n你呢 每天都要快快乐乐的知道么\n\n睡个好觉 做个好梦\n\n么么 wanan' \
                 % (unicode(formatted_date),unicode(hours),unicode(minutes),unicode(seconds),)
     self.now.emit(msgString)
def convert_timestamp_to_qdatetime(timestamp):
    from PyQt4.QtCore import QDateTime
    from math import modf
    timestamp_frac, timestamp_whole = modf(timestamp)
    # Qt time
    qdatetime = QDateTime()
    qdatetime.setTime_t(int(timestamp_whole))
    qdatetime = qdatetime.addMSecs(int(timestamp_frac*1000))
    #
    return qdatetime
Example #26
0
class DateLabel(QLabel):
    def __init__(self, text, parent, date_format):
        self.date_format = date_format
        self.t = QDateTime()
        super(DateLabel, self).__init__(text=text, parent=parent)

    def setValue(self, unixtimestampe):
        """Set the text with a value from a unix timestamp"""
        self.t.setTime_t(unixtimestampe)
        super(DateLabel, self).setText(self.t.toString(self.date_format))
Example #27
0
def tickStringsDate(self, values, scale, spacing):
    """Return HH:mm:ss strings from unixtime values"""
    # FIXME Change date format depending of min max value
    # FIXME Make better date locator
    out = []
    for value in values:
        t = QDateTime()
        t.setTime_t(value)
        out.append(t.toString('HH:mm:ss'))
    return out
Example #28
0
 def _load_settings(self):
     s = QSettings()
     self.ui.nldasEdit.setText(s.value("pihm_helper/nldas/cache", "./cache").toString())
     o = s.value("pihm_helper/nldas/output", ".").toString()
     self.ui.coverageBox.setEditText(s.value("pihm_helper/nldas/input", ".").toString())
     self.ui.beginEdit.setDateTime(QDateTime.fromString(s.value("pihm_helper/nldas/begin", "1999-12-31T19:00:00").toString(), Qt.ISODate))
     self.ui.endEdit.setDateTime(QDateTime.fromString(s.value("pihm_helper/nldas/end", "2000-01-01T02:00:00").toString(), Qt.ISODate))
     if _iface:
         p = QgsProject.instance()
         o = p.readPath(p.readEntry("pihm_helper", "nldas/output", o)[0])
     self.ui.outputEdit.setText(o)
Example #29
0
    def setEditorData(self, editor, index):
        columns = index.model().get_git_model().get_columns()
        field_name = columns[index.column()]

        if field_name in TEXT_FIELDS or field_name in ACTOR_FIELDS:
            text = index.model().data(index, Qt.EditRole).toString()
            editor.setText(text)
        elif field_name in TIME_FIELDS:
            timestamp, tz = index.model().data(index, Qt.EditRole)
            _q_datetime = QDateTime()
            _q_datetime.setTime_t(timestamp)
            editor.setDateTime(_q_datetime)
Example #30
0
    def __init__(self, client, arg, value, compatibility=None):
        ArgFilterBase.__init__(self, client, arg, value, compatibility=compatibility)
        QDateTimeEdit.__init__(self)

        datevalue = QDateTime()
        try:
            datevalue.setTime_t(int(value))
            self.setDateTime(datevalue)
        except (TypeError, ValueError):
            self.setDateTime(QDateTime.currentDateTime())

        self.setCalendarPopup(True)
Example #31
0
 def __add_layer_definition_file(self, file_name, root_group):
     """
     shamelessly copied from
     https://github.com/qgis/QGIS/blob/master/src/core/qgslayerdefinition.cpp
     """
     qfile = QFile(file_name)
     if not qfile.open(QIODevice.ReadOnly):
         return None
     doc = QDomDocument()
     if not doc.setContent(qfile):
         return None
     file_info = QFileInfo(qfile)
     QDir.setCurrent(file_info.absoluteDir().path())
     root = QgsLayerTreeGroup()
     ids = doc.elementsByTagName('id')
     for i in xrange(0, ids.size()):
         id_node = ids.at(i)
         id_elem = id_node.toElement()
         old_id = id_elem.text()
         layer_name = old_id[:-17]
         date_time = QDateTime.currentDateTime()
         new_id = layer_name + date_time.toString('yyyyMMddhhmmsszzz')
         id_elem.firstChild().setNodeValue(new_id)
         tree_layer_nodes = doc.elementsByTagName('layer-tree-layer')
         for j in xrange(0, tree_layer_nodes.count()):
             layer_node = tree_layer_nodes.at(j)
             layer_elem = layer_node.toElement()
             if old_id == layer_elem.attribute('id'):
                 layer_node.toElement().setAttribute('id', new_id)
     layer_tree_elem = doc.documentElement().firstChildElement(
         'layer-tree-group')
     load_in_legend = True
     if not layer_tree_elem.isNull():
         root.readChildrenFromXML(layer_tree_elem)
         load_in_legend = False
     layers = QgsMapLayer.fromLayerDefinition(doc)
     QgsMapLayerRegistry.instance().addMapLayers(layers, load_in_legend)
     nodes = root.children()
     for node in nodes:
         root.takeChild(node)
     del root
     root_group.insertChildNodes(-1, nodes)
     return None
Example #32
0
def startRec():
    global camState
    global saveFilePath
    if camState == 'recording':
        print('Alredy Recording')
    else:
        file_nameH = str(
            ('Lepton HD5F Vid ' + QDateTime.currentDateTime().toString()))
        try:
            filePathAndName = str(saveFilePath + '/' + file_nameH)
            #saveFilePathSlash = str(saveFilePath + '/')
            startRec.hdf5_file = h5py.File(filePathAndName, mode='w')
            #startRec.hdf5_file = h5py.File(os.path.join(saveFilePathSlash, file_nameH))
            camState = 'recording'
            print('Started Recording')
        except:
            print('Incorrect File Path')
            camState = 'not_recording'
            print('Did Not Begin Recording')
Example #33
0
    def _load(self):
        self.cookie = QNetworkCookie('Settings',
                                     'Player~others|Bandwidth~ALL|Codec~ALL')
        self.cookie.setDomain('.shoutcast.com')
        self.cookie.setExpirationDate(QDateTime())
        self.cookie.setPath('/')

        self.webView = QWebView(self)
        self.webPage = self.webView.page()
        self.cookiejar = QNetworkCookieJar()
        self.cookiejar.setAllCookies([self.cookie])
        self.webPage.networkAccessManager().setCookieJar(self.cookiejar)

        self.layout = QVBoxLayout(self)
        self.layout.addWidget(self.webView)
        self.webView.load(QUrl(HOMEURL))
        self.webPage.setLinkDelegationPolicy(QWebPage.DelegateExternalLinks)
        self.connect(self.webPage, SIGNAL('linkClicked(const QUrl&)'),
                     self._processLink)
Example #34
0
File: data.py Project: cb-flts/stdm
 def to_pyqt(obj, type_=None):
     """
     Converts data from python object type to PyQt equivalent
     :param obj: Python object
     :type obj: Multiple types
     :param type_: Cast type
     :type type_: Object
     :return: Converted value
     :rtype: Multiple types
     """
     if isinstance(obj, int):
         return obj
     if isinstance(obj, (Decimal, float)):
         obj = Decimal(obj).normalize()
     elif type(obj) is datetime.date:
         return QDate(obj)
     elif type(obj) is datetime.datetime:
         return QDateTime(obj).toLocalTime()
     return unicode(obj) if obj is not None else obj
Example #35
0
    def handleStarted(self):
        reply = self.sender()
        if not reply:
            return
        if reply in self.m_started:
            return

        self.m_started.append(reply)

        headers = []
        for header in reply.rawHeaderList():
            header = {
                'name': str(header),
                'value': str(reply.rawHeader(header))
            }
            headers.append(header)

        data = {
            'stage':
            'start',
            'id':
            self.m_ids[reply],
            'url':
            reply.url().toString(),
            'status':
            reply.attribute(QNetworkRequest.HttpStatusCodeAttribute),
            'statusText':
            reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute),
            'contentType':
            reply.header(QNetworkRequest.ContentTypeHeader),
            'bodySize':
            reply.size(),
            'redirectURL':
            reply.header(QNetworkRequest.LocationHeader),
            'headers':
            headers,
            'time':
            QDateTime.currentDateTime()
        }

        do_action('NetworkAccessManagerHandleStarted')

        self.resourceReceived.emit(data)
    def evaluation_test( self, mComposition, mLabel ):
        # $CURRENT_DATE evaluation
        mLabel.setText( "__$CURRENT_DATE__" )
        assert mLabel.displayText() == ( "__" + QDate.currentDate().toString() + "__" )

        # $CURRENT_DATE() evaluation
        mLabel.setText( "__$CURRENT_DATE(dd)(ok)__" )
        expected = "__" + QDateTime.currentDateTime().toString( "dd" ) + "(ok)__"
        assert mLabel.displayText() == expected

        # $CURRENT_DATE() evaluation (inside an expression)
        mLabel.setText( "__[%$CURRENT_DATE(dd) + 1%](ok)__" )
        dd = QDate.currentDate().day()
        expected = "__%d(ok)__" % (dd+1)
        assert mLabel.displayText() == expected

        # expression evaluation (without associated feature)
        mLabel.setText( "__[%\"NAME_1\"%][%21*2%]__" )
        assert mLabel.displayText() == "__[NAME_1]42__"
Example #37
0
 def startRec2(self):
     global thread
     global camState
     global saveFilePath
     global fileNamingFull
     if thread == 'active':
         if camState == 'recording':
             print('Already Recording')
         else:
             if fileNamingFull != "":
                 dateAndTime = str(QDateTime.currentDateTime().toString())
                 dateAndTime = dateAndTime.replace(" ", "_")
                 dateAndTime = dateAndTime.replace(":", "-")
                 filePathAndName = str(fileNamingFull + '_' + dateAndTime)
                 print(filePathAndName)
                 self.filePathDisp.setText(filePathAndName)
                 try:
                     startRec.hdf5_file = h5py.File(filePathAndName,
                                                    mode='w')
                     camState = 'recording'
                     print('Started Recording')
                     if saveFilePath == "":
                         self.history.insertPlainText(
                             'Saved ' + str(filePathAndName) + ' to ' +
                             os.path.dirname(os.path.abspath(__file__)) +
                             '\n')
                         self.history.moveCursor(QTextCursor.End)
                     else:
                         self.history.insertPlainText('Saved to ' +
                                                      str(filePathAndName) +
                                                      '\n')
                         self.history.moveCursor(QTextCursor.End)
                 except:
                     print('Incorrect File Path')
                     camState = 'not_recording'
                     print('Did Not Begin Recording')
             else:
                 print('No FileName Specified')
     else:
         print('Remember to Start Stream')
         self.history.insertPlainText('Remember to Start Stream\n')
         self.history.moveCursor(QTextCursor.End)
Example #38
0
    def __init__(self, parent=None):
        RecordListModel.__init__(self, parent)
        self.ServiceFilter = '^AB_'
        self.setColumns(['Service', 'Enabled', 'Pulse'])
        self.ServiceStateIcons = {}
        self.ServiceStateIcons[ServiceStateOnline] = self.createOnlineIcon(
            Qt.green)
        self.ServiceStateIcons[ServiceStateOffline] = self.createOnlineIcon(
            Qt.black)
        self.ServiceStateIcons[ServiceStateError] = self.createOnlineIcon(
            Qt.red)
        self.ServiceStateIcons[ServiceStateConflict] = self.createOnlineIcon(
            QColor(200, 100, 100))
        self.RefreshTime = QDateTime.currentDateTime()
        self.setRootList(self.getServiceList())

        self.HostServiceTable = Database.current().tableByName('HostService')
        self.HostServiceIndex = self.HostServiceTable.indexFromSchema(
            self.HostServiceTable.schema().field('fkeyService').index())
        self.HostServiceIndex.setCacheEnabled(True)
Example #39
0
    def set_widgets(self):
        """Set widgets on the Source tab."""
        # Just set values based on existing keywords
        source = self.parent.get_existing_keyword('source')
        if source or source == 0:
            self.leSource.setText(get_unicode(source))
        else:
            self.leSource.clear()

        source_scale = self.parent.get_existing_keyword('scale')
        if source_scale or source_scale == 0:
            self.leSource_scale.setText(get_unicode(source_scale))
        else:
            self.leSource_scale.clear()

        source_date = self.parent.get_existing_keyword('date')
        if source_date:
            self.ckbSource_date.setChecked(True)
            self.dtSource_date.setDateTime(
                QDateTime.fromString(get_unicode(source_date),
                                     'yyyy-MM-dd HH:mm:ss'))
        else:
            self.ckbSource_date.setChecked(False)
            self.dtSource_date.clear()

        source_url = self.parent.get_existing_keyword('url')
        try:
            source_url = source_url.toString()
        except AttributeError:
            pass

        if source_url or source_url == 0:
            self.leSource_url.setText(get_unicode(source_url))
        else:
            self.leSource_url.clear()

        source_license = self.parent.get_existing_keyword('license')
        if source_license or source_license == 0:
            self.leSource_license.setText(get_unicode(source_license))
        else:
            self.leSource_license.clear()
Example #40
0
    def setDefaultRestrictionDetails(self, currRestriction,
                                     currRestrictionLayer):
        QgsMessageLog.logMessage("In setDefaultRestrictionDetails: ",
                                 tag="TOMs panel")

        self.userName = (QgsExpressionContextUtils.globalScope().variable(
            "user_account_name"))
        QgsMessageLog.logMessage(
            "In setDefaultRestrictionDetails: curr user name: " +
            self.userName,
            tag="TOMs panel")

        try:
            #currRestrictionLayer.changeAttributeValue(currRestriction.id(), currRestriction.fieldNameIndex("Signs_DateTime"), QDateTime.currentDateTime())
            currRestriction.setAttribute("Signs_DateTime",
                                         QDateTime.currentDateTime())
            currRestriction.setAttribute("Surveyor", self.userName)
        except:
            reply = QMessageBox.information(
                None, "Information", "Problems with default values ...",
                QMessageBox.Ok)
Example #41
0
    def testDateTimeFormats(self):
        # check that date and time formats are correctly interpreted
        basetestfile = os.path.join(TEST_DATA_DIR, 'tab_file.tab')
        vl = QgsVectorLayer(u'{}|layerid=0'.format(basetestfile), u'test', u'ogr')

        fields = vl.dataProvider().fields()
        self.assertEqual(fields.at(fields.indexFromName('date')).type(), QVariant.Date)
        self.assertEqual(fields.at(fields.indexFromName('time')).type(), QVariant.Time)
        self.assertEqual(fields.at(fields.indexFromName('date_time')).type(), QVariant.DateTime)

        f = vl.getFeatures(QgsFeatureRequest()).next()

        date_idx = vl.fieldNameIndex('date')
        assert isinstance(f.attributes()[date_idx], QDate)
        self.assertEqual(f.attributes()[date_idx], QDate(2004, 5, 3))
        time_idx = vl.fieldNameIndex('time')
        assert isinstance(f.attributes()[time_idx], QTime)
        self.assertEqual(f.attributes()[time_idx], QTime(13, 41, 00))
        datetime_idx = vl.fieldNameIndex('date_time')
        assert isinstance(f.attributes()[datetime_idx], QDateTime)
        self.assertEqual(f.attributes()[datetime_idx], QDateTime(QDate(2004, 5, 3), QTime(13, 41, 00)))
Example #42
0
    def har_cookie2qt(cls, cookie):
        qcookie = QNetworkCookie()
        qcookie.setName(cookie["name"])
        qcookie.setValue(cookie["value"])

        if 'domain' in cookie:
            qcookie.setDomain(cookie["domain"])

        if 'httpOnly' in cookie:
            qcookie.setHttpOnly(cookie["httpOnly"])

        if 'secure' in cookie:
            qcookie.setSecure(cookie["secure"])

        if 'path' in cookie:
            qcookie.setPath(cookie["path"])

        if cookie.get('expires'):
            expires = QDateTime.fromString(cookie["expires"], Qt.ISODate)
            qcookie.setExpirationDate(expires)

        return qcookie
Example #43
0
    def __init__(self):

        buxpaper.Window.__init__(self)

        start_time = QDateTime.currentDateTime().time()
        self.displayTime = (start_time.hour(), start_time.minute())

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.updateTime)
        self.timer.setInterval(5000)
        self.timer.start()

        self.foreground = QPen(self.palette().foreground().color())
        self.background = self.palette().background()

        font = QFont(QApplication.font())
        desktop = QApplication.desktop()
        geometry = desktop.screenGeometry()
        font.setPixelSize(min(geometry.width() / 8, geometry.height() / 4))
        self.setFont(font)

        self.maxHeight = QFontMetrics(font).height()
Example #44
0
    def handle_cookiesSave_clicked(self):
        cookieJar = self.framework.get_global_cookie_jar()
        cookieList = cookieJar.allCookies()
        domain = str(self.mainWindow.cookiesCookieJarDomainEdit.text())
        name = str(self.mainWindow.cookiesCookieJarNameEdit.text())
        value = str(self.mainWindow.cookiesCookieJarValueEdit.text())
        if not (domain and name and value):
            return
        cookie = self.find_cookie_by_domain_and_name(cookieList, domain, name)
        if cookie is None:
            # new
            cookie = QNetworkCookie(name, value)
            index = -1
        else:
            index = cookieList.index(cookie)

        cookie.setName(name)
        cookie.setDomain(domain)
        cookie.setValue(value)
        cookie.setPath(str(self.mainWindow.cookiesCookieJarPathEdit.text()))
        if self.mainWindow.cookiesCookieJarSessionCookieCheckbox.isChecked():
            cookie.setExpirationDate(QDateTime())
        else:
            cookie.setExpirationDate(
                self.mainWindow.cookiesCookieJarExpiryEdit.dateTime())
        cookie.setSecure(
            self.mainWindow.cookiesCookieJarSecureCheckbox.isChecked())
        cookie.setHttpOnly(
            self.mainWindow.cookiesCookieJarHttpOnlyCheckbox.isChecked())

        if -1 == index:
            cookieList.append(cookie)
        else:
            cookieList[index] = cookie

        cookieJar.setAllCookies(cookieList)
        self.populate_cookie_jar_tree()
    def handleFinished(self, reply):
        headers = []
        for header in reply.rawHeaderList():
            header = {
                'name': str(header),
                'value': str(reply.rawHeader(header))
            }
            headers.append(header)

        data = {
            'stage':
            'end',
            'id':
            self.m_ids[reply],
            'url':
            reply.url().toString(),
            'status':
            reply.attribute(QNetworkRequest.HttpStatusCodeAttribute),
            'statusText':
            reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute),
            'contentType':
            reply.header(QNetworkRequest.ContentTypeHeader),
            'redirectURL':
            reply.header(QNetworkRequest.LocationHeader),
            'headers':
            headers,
            'time':
            QDateTime.currentDateTime()
        }

        del self.m_ids[reply]
        if reply in self.m_started:
            del self.m_started[self.m_started.index(reply)]

        do_action('NetworkAccessManagerHandleFinished', Bunch(locals()))

        self.resourceReceived.emit(data)
Example #46
0
    def __init__(self):
        super(XCalendarItem, self).__init__()

        curr_dtime = QDateTime.currentDateTime()
        curr_date = curr_dtime.date()
        curr_time = curr_dtime.time()

        self.setFlags(self.flags() | self.ItemIsSelectable)
        self.setAcceptHoverEvents(True)

        # round to the nearest 15 minute segment
        curr_time = QTime(curr_time.hour(),
                          curr_time.minute() - curr_time.minute() % 30, 0)

        self._rebuildBlocked = False
        self._textData = []

        self._customData = {}
        self._textColor = QColor('white')
        self._fillColor = QColor('blue')
        self._borderColor = QColor('blue')
        self._highlightColor = QColor('blue')

        self._title = 'No Title'
        self._description = ''
        self._dateStart = curr_date
        self._dateEnd = curr_date
        self._timeStart = curr_time
        self._timeEnd = curr_time.addSecs(60 * 60)
        self._allDay = True
        self._rebuildRequired = False

        if (QTime(23, 0, 0) <= self._timeStart):
            self._timeEnd = QTime(23, 59, 0)

        self.setColor('blue')
Example #47
0
    def setvalue(self, value):
        strvalue = value
        if value is None:
            value = DateWidget.DEFAULTDATE
        elif isinstance(value, basestring):
            value = QDateTime.fromString(strvalue, Qt.ISODate)
            if not value or (value and value.date().year() < 0):
                value = QDateTime.fromString(strvalue,
                                             Qt.SystemLocaleShortDate)

        if isinstance(value, QDate):
            value = QDateTime(value)

        if hasattr(self.datewidget, 'setDate'):
            self.datewidget.setDate(value.date())

        if hasattr(self.datewidget, 'setTime'):
            self.datewidget.setTime(value.time())

        self.set_date(value)
Example #48
0
class DateWidget(EditorWidget):
    widgettype = 'Date'
    DEFAULTDATE = QDateTime(2000, 1, 1, 00, 00, 00, 0)

    def __init__(self, *args, **kwargs):
        super(DateWidget, self).__init__(*args)

    def createWidget(self, parent):
        return DateUiWidget(parent)

    def initWidget(self, widget):
        pickbutton = widget.findChild(QPushButton)

        if not pickbutton is None:
            pickbutton.setIcon(QIcon(":/icons/calender"))
            pickbutton.setText("Select")
            pickbutton.setIconSize(QSize(24, 24))
            pickbutton.pressed.connect(self.showpickdialog)
            self.datewidget.hide()

        if type(self.datewidget) is QDateEdit:
            self.datawidget.dateChanged.connect(self.emitvaluechanged)
        else:
            self.datewidget.dateTimeChanged.connect(self.emitvaluechanged)
        self.datewidget.installEventFilter(self)

    def eventFilter(self, object, event):
        # Hack I really don't like this but there doesn't seem to be a better way at the
        # moment
        if event.type() in [QEvent.FocusIn, QEvent.MouseButtonPress]:
            RoamEvents.openkeyboard.emit()
        return False

    @property
    def datewidget(self):
        if type(self.widget) is QDateTimeEdit:
            return self.widget
        else:
            return self.widget.findChild(QDateTimeEdit)

    def validate(self, *args):
        if self.value() is None:
            return False
        else:
            return True

    def showpickdialog(self):
        """
        Open the date time picker dialog

        control - The control that will recive the user set date time.
        """

        if type(self.datewidget) is QDateEdit:
            mode = "Date"
        else:
            mode = "DateTime"

        config = dict(mode=mode, mindate=self.datewidget.minimumDate())

        self.largewidgetrequest.emit(BigDateWidget, self.value(),
                                     self.setvalue, config)

    def set_date(self, value):
        string = value.toString(Qt.SystemLocaleShortDate)
        pickbutton = self.widget.findChild(QPushButton)
        if pickbutton:
            if not string:
                string = "Select"
            pickbutton.setText(string)

    def setvalue(self, value):
        if value is None:
            value = DateWidget.DEFAULTDATE
        elif isinstance(value, basestring):
            value = QDateTime.fromString(value, Qt.ISODate)

        if isinstance(value, QDate):
            value = QDateTime(value)

        if hasattr(self.datewidget, 'setDate'):
            self.datewidget.setDate(value.date())

        if hasattr(self.datewidget, 'setTime'):
            self.datewidget.setTime(value.time())

        self.set_date(value)

    def value(self):
        datetime = self.datewidget.dateTime()
        if datetime == DateWidget.DEFAULTDATE:
            return None
        else:
            return datetime.toString(Qt.ISODate)
Example #49
0
 def __init__(self, parent=None):
     super(XDateTimeEdit, self).__init__(parent)
     
     # define custom properties
     self.setCalendarPopup(True)
     self.setDateTime(QDateTime.currentDateTime())
Example #50
0
 def setHoraPc(self):
     self.dateTimeEdit.setDateTime(QDateTime.currentDateTime())
Example #51
0
 def clear(self):
     self.control.setDateTime(QDateTime.currentDateTime())
Example #52
0
    def test_existing_complex_keywords(self):
        """Test for existing complex keywords in wizard in locale mode."""
        from safe.gui.tools.wizard_dialog import WizardDialog
        from safe.test.utilities import (
            clone_shp_layer, remove_vector_temp_file)
        layer = clone_shp_layer(
            name='tsunami_polygon', include_keywords=True, source_directory='')

        from safe.test.utilities import get_qgis_app
        # Get QGis app handle
        # noinspection PyPep8Naming
        _, _, IFACE, PARENT = get_qgis_app()
        # noinspection PyTypeChecker
        dialog = WizardDialog(PARENT, IFACE)
        dialog.set_keywords_creation_mode(layer)

        # select hazard
        self.select_from_list_widget('ancaman', dialog.lstCategories)
        dialog.pbnNext.click()

        # select volcano
        self.select_from_list_widget('gunung berapi', dialog.lstSubcategories)
        dialog.pbnNext.click()

        # select volcano categorical unit
        self.select_from_list_widget('Kategori gunung berapi', dialog.lstUnits)
        dialog.pbnNext.click()

        # select GRIDCODE
        self.select_from_list_widget('GRIDCODE', dialog.lstFields)
        dialog.pbnNext.click()

        unit = dialog.selected_unit()
        default_classes = unit['classes']
        unassigned_values = []  # no need to check actually, not save in file
        assigned_values = {
            'low': ['5.0'],
            'medium': ['3.0', '4.0'],
            'high': ['2.0']
        }
        dialog.populate_classified_values(
            unassigned_values, assigned_values, default_classes)
        dialog.pbnNext.click()

        source = 'Source'
        source_scale = 'Source Scale'
        source_url = 'Source Url'
        source_date = QDateTime.fromString(
            '06-12-2015 12:30',
            'dd-MM-yyyy HH:mm')

        dialog.leSource.setText(source)
        dialog.leSource_scale.setText(source_scale)
        dialog.leSource_url.setText(source_url)
        dialog.leSource_date.seDateTime(source_date)
        dialog.pbnNext.click()  # next
        dialog.pbnNext.click()  # finish

        # noinspection PyTypeChecker
        dialog = WizardDialog(PARENT, IFACE)
        dialog.set_keywords_creation_mode(layer)

        # step 1 of 7 - select category
        self.check_current_text('ancaman', dialog.lstCategories)

        # Click Next
        dialog.pbnNext.click()

        # step 2 of 7 - select subcategory
        # noinspection PyTypeChecker
        self.check_current_text('gunung berapi', dialog.lstSubcategories)

        # Click Next
        dialog.pbnNext.click()

        # step 3 of 7 - select volcano units
        self.check_current_text('Kategori gunung berapi', dialog.lstUnits)

        # Click Next
        dialog.pbnNext.click()

        # step 4 of 7 - select field
        self.check_current_text('GRIDCODE', dialog.lstFields)

        # Click Next
        dialog.pbnNext.click()

        for index in range(dialog.lstUniqueValues.count()):
            message = ('%s Should be in unassigned values' %
                       dialog.lstUniqueValues.item(index).text())
            self.assertIn(
                dialog.lstUniqueValues.item(index).text(),
                unassigned_values,
                message)
        real_assigned_values = dialog.selected_mapping()
        self.assertDictEqual(real_assigned_values, assigned_values)

        # Click Next
        dialog.pbnNext.click()

        # step 6 of 7 - enter source
        message = ('Invalid Next button state in step 6! Disabled while '
                   'source is optional')
        self.assertTrue(dialog.pbnNext.isEnabled(), message)

        message = 'Source should be %s' % source
        self.assertEqual(dialog.leSource.text(), source, message)
        message = 'Source Url should be %s' % source_url
        self.assertEqual(dialog.leSource_url.text(), source_url, message)
        message = 'Source Date should be %s' % source_date.toString(
            'dd-MM-yyyy HH:mm')
        self.assertEqual(dialog.leSource_date.dateTime(), source_date, message)
        message = 'Source Scale should be %s' % source_scale
        self.assertEqual(dialog.leSource_scale.text(), source_scale, message)
        dialog.pbnNext.click()

        dialog.pbnCancel.click()

        remove_vector_temp_file(layer.source())
Example #53
0
 def openGraficos(self):
     if self.graficos is None:
         intervalo = int(self.intervaloSpin.text())
         self.graficos = Graficos(self.analogSetUp, self.digitalSetUp,
                                  intervalo, self.unidadTiempo,
                                  QDateTime.currentDateTime())
    def __init__(self, parent=None, aptinkerQSettings=None):
        """Constructor"""

        QDialog.__init__(self, parent=parent)

        self.setupUi(self)

        self.setWindowFlags(Qt.Window)  # To add Maximize & Minimize buttons
        self.setWindowTitle('Select Snapshot from Database')

        # Load Startup Preferences for Snapshot Table
        self.default_ss_pref = dict(
            vis_col_key_list=config.DEF_VIS_COL_KEYS['snapshot_DB'][:])
        if osp.exists(PREF_SS_JSON_FILEPATH):
            with open(PREF_SS_JSON_FILEPATH, 'r') as f:
                self.ss_pref = json.load(f)
        else:
            self.ss_pref = self.default_ss_pref

        # Load Startup Preferences for Snapshot Meta Table
        self.default_ss_meta_pref = dict(vis_col_key_list=[
            'ss_id', 'config_id', 'ss_ctime', 'ss_name', 'ss_username'
        ])
        if osp.exists(PREF_SS_META_JSON_FILEPATH):
            with open(PREF_SS_META_JSON_FILEPATH, 'r') as f:
                self.ss_meta_pref = json.load(f)
        else:
            self.ss_meta_pref = self.default_ss_meta_pref

        self.ssDBViewWidget = SnapshotDBViewWidget(self.groupBox_selected_ss,
                                                   DB_selector=True)
        self.tableView_ss = self.ssDBViewWidget.tableView

        self.ssMetaDBViewWidget = SnapshotMetaDBViewWidget(
            self.groupBox_search_result)
        self.tableView_ss_meta = self.ssMetaDBViewWidget.tableView
        self.textEdit_description = \
            self.ssMetaDBViewWidget.textEdit_description

        self.settings = QSettings('APHLA', 'TinkerSSDBSelector')
        self.loadViewSettings()

        self._aptinkerQSettings = aptinkerQSettings

        self.pushButton_search.setIcon(QIcon(':/search.png'))

        all_ctime_operators = [
            self.comboBox_time_created_1.itemText(i)
            for i in range(self.comboBox_time_created_1.count())
        ]
        self.comboBox_time_created_1.setCurrentIndex(
            all_ctime_operators.index(''))
        self.dateTimeEdit_time_created_1.setDateTime(
            QDateTime.currentDateTime())
        self.dateTimeEdit_time_created_2.setDateTime(
            QDateTime.currentDateTime())

        self.search_params = dict(ss_id_1='',
                                  ss_id_2='',
                                  config_id_1='',
                                  config_id_2='',
                                  ss_ref_step_size_1='',
                                  ss_ref_step_size_2='',
                                  ss_name='',
                                  ss_desc='',
                                  ss_username='',
                                  ss_ctime_1='',
                                  ss_ctime_2='',
                                  ss_synced_gruop_weight='',
                                  ss_masar_id_1='',
                                  ss_masar_id_2='')

        db_id_validator = QIntValidator()
        db_id_validator.setBottom(1)
        self.lineEdit_ss_id_1.setValidator(db_id_validator)
        self.lineEdit_ss_id_2.setValidator(db_id_validator)
        self.lineEdit_config_id_1.setValidator(db_id_validator)
        self.lineEdit_config_id_2.setValidator(db_id_validator)
        self.lineEdit_masar_id_1.setValidator(db_id_validator)
        self.lineEdit_masar_id_2.setValidator(db_id_validator)

        self.prev_valid_ref_step_sizes = dict(lineEdit_ref_step_size_1=np.nan,
                                              lineEdit_ref_step_size_2=np.nan)

        # Set up Snapshot Table
        self.ss_model = SnapshotModel(self.ss_pref['vis_col_key_list'])
        self.tableModel_ss = self.ss_model.table
        proxyModel = QSortFilterProxyModel()
        proxyModel.setSourceModel(self.tableModel_ss)
        proxyModel.setDynamicSortFilter(False)
        tbV = self.tableView_ss
        tbV.setModel(proxyModel)
        tbV.setItemDelegate(
            SnapshotDBTableViewItemDelegate(tbV, self.tableModel_ss,
                                            tbV.parent()))

        #self.db = TinkerMainDatabase()
        self.db = self.ss_model.db
        if '[ss_meta_table text view]' not in self.db.getViewNames(
                square_brackets=True):
            self.db.create_temp_ss_meta_table_text_view()

        # Set up Snapshot Meta Table
        self.ss_meta_all_col_keys = self.ssMetaDBViewWidget.all_col_keys
        self.search_result = {k: [] for k in self.ss_meta_all_col_keys}

        self.tableModel_ss_meta = MetaTableModel(self.search_result,
                                                 self.ssMetaDBViewWidget)
        proxyModel = QSortFilterProxyModel()
        proxyModel.setSourceModel(self.tableModel_ss_meta)
        proxyModel.setDynamicSortFilter(False)
        tbV = self.tableView_ss_meta
        tbV.setModel(proxyModel)
        self.selectionModel = QItemSelectionModel(proxyModel)
        tbV.setSelectionModel(self.selectionModel)

        # Apply Visible Column Preference to Snapshot Meta Table
        ss_meta_vis_col_name_list = [
            self.ssMetaDBViewWidget.col_names_wo_desc[
                self.ssMetaDBViewWidget.col_keys_wo_desc.index(k)]
            for k in self.ss_meta_pref['vis_col_key_list']
        ]
        self.ssMetaDBViewWidget.on_column_selection_change(
            ss_meta_vis_col_name_list, force_visibility_update=True)

        # Make connection

        self.connect(self.lineEdit_ref_step_size_1,
                     SIGNAL('editingFinished()'), self.validate_ref_step_size)
        self.connect(self.lineEdit_ref_step_size_2,
                     SIGNAL('editingFinished()'), self.validate_ref_step_size)

        self.connect(self.pushButton_search, SIGNAL('clicked()'),
                     self.update_search)

        self.connect(
            self.selectionModel,
            SIGNAL(
                'currentRowChanged(const QModelIndex &, const QModelIndex &)'),
            self.on_selection_change)
Example #55
0
 def get_filename(self):
     name = QDateTime.currentDateTime().toString(
         "yyyy-MM-dd-hh-mm-ss-zzz.JPG")
     return name
Example #56
0
def convert_QDateTime(t):
    return QDateTime.fromTime_t(int(t))
Example #57
0
 def emit_now(self):
     formatted_date = QDateTime.currentDateTime().toString()
     self.now.emit(formatted_date)
class LogResultRow():
    def __init__(self, logFeature, featureLayer, pkeyName, geomColumn):
        self.featureLayer = featureLayer
        self.fields = featureLayer.dataProvider().fields()
        self.logFeature = QgsFeature(logFeature)
        self.geomColumn = geomColumn
        self.date = QDateTime().fromString(logFeature["action_tstamp_clk"],
                                           Qt.ISODate)
        print logFeature[
            "action_tstamp_clk"], self.date, self.date.toMSecsSinceEpoch()
        self.dateMs = self.date.toMSecsSinceEpoch()
        self.logData = self.logFeature["row_data"]
        self.layerFeatureId = int(self.getFieldValue(self.logData, pkeyName))

    def getFieldValue(self, data, fieldName):
        if data is None:
            return None
        p = fieldRe(fieldName).search(data)
        if p:
            value = ""
            data = data[p.end():]
            p = dataReWithQuote.match(data)
            if p:
                value = data[p.start() + 1:p.end() - 1]
            else:
                p = dataReWithoutQuote.match(data)
                if p:
                    value = data[p.start():p.end() - 1]
                else:
                    p = dataReWithoutQuoteEndOfString.match(data)
                    if p:
                        value = data[p.start():p.end()]
            return value
        return None

    def dateStr(self):
        return self.date.toString("ddd dd MMM yyyy hh:mm")

    def user(self):
        return self.logFeature["session_user_name"]

    def action(self):
        action = self.logFeature["action"]
        if action == "I":
            #return u"\u002B" # plus sign
            return "insert"
        if action == "U":
            #return u"\u2713" # check sign
            return "update"
        if action == "D":
            #return u"\u2A2F" # cross sign
            return "delete"
        raise NameError("Invalid action %s" % action)

    def application(self):
        return self.logFeature["application_name"]

    def clientIP(self):
        return self.logFeature["client_addr"]

    def clientPort(self):
        return self.logFeature["client_port"]

    def changedFields(self):
        data = self.logFeature["changed_fields"]
        columns = ""
        for field in self.fields:
            if self.getFieldValue(data, field.name()) is not None:
                columns += field.name() + ", "
        return columns[:-2]

    def changedGeometry(self):
        data = self.logFeature["changed_fields"]
        geometry = self.getFieldValue(data, self.geomColumn)
        return geometry is not None

    def changedGeometryStr(self):
        if self.changedGeometry():
            return u"\u2713"  # i.e. check sign
        else:
            return ""

    def geometry(self):
        if self.geomColumn is None:
            return QgsGeometry()
        ewkb = "%s" % self.getFieldValue(self.logData, self.geomColumn)
        return geometryTools.ewkb2gqgis(ewkb)

    def data(self):
        out = dict()
        for field in self.fields:
            out[field.name()] = self.getFieldValue(self.logData, field.name())
        return out

    def getLayerFeature(self):
        layerFeature = QgsFeature()
        featReq = QgsFeatureRequest().setFilterFid(self.layerFeatureId)
        if not self.featureLayer.hasGeometryType():
            featReq.setFlags(QgsFeatureRequest.NoGeometry)
        if self.featureLayer.getFeatures(featReq).nextFeature(layerFeature):
            return layerFeature
        else:
            return None

    def restoreFeature(self):
        if not self.featureLayer.isEditable():
            return False

        currentFeature = self.getLayerFeature()
        editBuffer = self.featureLayer.editBuffer()
        if currentFeature is not None:
            fid = currentFeature.id()
            for idx, field in enumerate(self.fields):
                value = self.getFieldValue(self.logData, field.name())
                editBuffer.changeAttributeValue(fid, idx, value)
            if self.featureLayer.hasGeometryType():
                editBuffer.changeGeometry(fid, self.geometry())
        else:
            newFeature = QgsFeature()
            newFeature.setFields(self.fields)
            newFeature.initAttributes(self.fields.size())
            for field in self.fields:
                value = self.getFieldValue(self.logData, field.name())
                newFeature[field.name()] = QVariant(value)
            if self.featureLayer.hasGeometryType():
                newFeature.setGeometry(self.geometry())
            editBuffer.addFeature(newFeature)
Example #59
0
 def value(self):
     datetime = QDateTime()
     datetime.setDate(self.getSelectedDate())
     datetime.setTime(self.getSelectedTime())
     return datetime
Example #60
0
 def setAsNow(self):
     """
     Set the current date and time on the picker as now.
     """
     now = QDateTime.currentDateTime()
     self.setDateTime(now)