예제 #1
0
파일: dbhandler.py 프로젝트: ZeeD/calendar
 def setData(self, index, value, role=None):
     if not index.isValid() or role not in (Qt.EditRole, Qt.CheckStateRole):
         return False
     expected_datepayd = QDate.fromString(index.data().toString(),
                                          'd MMMM yyyy')
     if role == Qt.EditRole:
         effective_datepayd = value.toDate()
     elif value.toInt()[0] == Qt.Checked:
         effective_datepayd = expected_datepayd
     else:
         print 'Error: Non puoi annullare i pagamenti'
         return False
     query = QSqlQuery(
         'UPDATE payments SET effective_datepayd = '
         ':effective_datepayd WHERE clients_client = :clients_client '
         'AND clients_machine = :clients_machine AND clients_selldate = '
         ':clients_selldate AND expected_datepayd = :expected_datepayd',
         self._db)
     # TODO: trovare client, machine, selldate
     header_data = self.headerData(index.column(), Qt.Horizontal,
                                   Qt.DisplayRole).toString().split('\n')
     client = header_data[0]
     machine = header_data[1]
     selldate = QDate.fromString(header_data[2], 'd MMMM yyyy')
     query.bindValue(':effective_datepayd', QVariant(effective_datepayd))
     query.bindValue(':clients_client', QVariant(client))
     query.bindValue(':clients_machine', QVariant(machine))
     query.bindValue(':clients_selldate', QVariant(selldate))
     query.bindValue(':expected_datepayd', QVariant(expected_datepayd))
     if not query.exec_():
         raise StandardError('SYNTAX ERROR')
     self.emit(SIGNAL("dataChanged()"), index, index)
     return True
예제 #2
0
	def readDates(self, tree):
		"""
		Lese die Daten aus (Geburtsdatum, Verwandlungsdatum, aktuelles Datum im Spiel).
		"""

		dates = tree.find("dates")
		self.__character.dateBirth = QDate.fromString(dates.attrib["birth"], Config.DATE_FORMAT)
		self.__character.dateBecoming = QDate.fromString(dates.attrib["becoming"], Config.DATE_FORMAT)
		self.__character.dateGame = QDate.fromString(dates.attrib["game"], Config.DATE_FORMAT)
예제 #3
0
def date_from_string(s):
    s = s.strip()
    if not s:
        return None
    from PyQt4.QtCore import QDate
    import string
    f = local_date_format()
    dt = QDate.fromString(s, f)
    if not dt.isValid():
        #
        # if there is a mismatch of 1 in length between format and
        # string, prepend a 0, to handle the case of 1/11/2011
        #
        if len(f) == len(s) + 1:
            s = '0' + s
            dt = QDate.fromString(s, f)
    if not dt.isValid():
        #
        # try alternative separators
        #
        separators = u''.join([c for c in f if c not in string.ascii_letters])
        if separators:
            alternative_string = u''.join([
                (c if c in string.digits else separators[0]) for c in s
            ])
            dt = QDate.fromString(alternative_string, f)
    if not dt.isValid():
        # try parsing without separators
        # attention : using non ascii letters will fail on windows
        # string.letters then contains non ascii letters of which we don't know the
        # encoding, so we cannot convert them to unicode to compare them
        only_letters_format = u''.join(
            [c for c in f if c in string.ascii_letters])
        only_letters_string = u''.join(
            [c for c in s if c in (string.ascii_letters + string.digits)])
        dt = QDate.fromString(only_letters_string, only_letters_format)
        if not dt.isValid():
            # try parsing without the year, and take the current year by default
            only_letters_format = u''.join(
                [c for c in only_letters_format if c not in ['y']])
            dt = QDate.fromString(only_letters_string, only_letters_format)
            if not dt.isValid():
                raise ParsingError()


#                # try parsing without year and month, and take the current year and month by default
#                only_letters_format = u''.join([c for c in only_letters_format if c not in ['M']])
#                dt = QDate.fromString(only_letters_string, only_letters_format)
#                if not dt.isValid():
#                    raise ParsingError()
#                else:
#                    today = date.today()
#                    return date(today.year, today.month, dt.day())
            else:
                return date(date.today().year, dt.month(), dt.day())
    return date(dt.year(), dt.month(), dt.day())
예제 #4
0
def date_from_string(s):
    s = s.strip()
    if not s:
        return None
    from PyQt4.QtCore import QDate
    import string
    f = local_date_format()
    dt = QDate.fromString(s, f)
    if not dt.isValid():
        #
        # if there is a mismatch of 1 in length between format and
        # string, prepend a 0, to handle the case of 1/11/2011
        #
        if len(f) == len(s) + 1:
            s = '0' + s
            dt = QDate.fromString(s, f)
    if not dt.isValid():
        #
	# try alternative separators
        #
        separators = u''.join([c for c in f if c not in string.ascii_letters])
        if separators:
            alternative_string = u''.join([(c if c in string.digits else separators[0]) for c in s])
            dt = QDate.fromString(alternative_string, f)
    if not dt.isValid():
        # try parsing without separators
        # attention : using non ascii letters will fail on windows
        # string.letters then contains non ascii letters of which we don't know the
        # encoding, so we cannot convert them to unicode to compare them
        only_letters_format = u''.join([c for c in f if c in string.ascii_letters])
        only_letters_string = u''.join([c for c in s if c in (string.ascii_letters+string.digits)])
        dt = QDate.fromString(only_letters_string, only_letters_format)
        if not dt.isValid():
            # try parsing without the year, and take the current year by default
            only_letters_format = u''.join([c for c in only_letters_format if c not in ['y']])
            dt = QDate.fromString(only_letters_string, only_letters_format)
            if not dt.isValid():
                raise ParsingError()
#                # try parsing without year and month, and take the current year and month by default
#                only_letters_format = u''.join([c for c in only_letters_format if c not in ['M']])
#                dt = QDate.fromString(only_letters_string, only_letters_format)
#                if not dt.isValid():
#                    raise ParsingError()
#                else:
#                    today = date.today()
#                    return date(today.year, today.month, dt.day())
            else:
                return date(date.today().year, dt.month(), dt.day())
    return date(dt.year(), dt.month(), dt.day())
    def _getCalendar(self, display_format, value=None):
        '''
        Get a combobox filled with the given values
        
        :param values: The values as key = value, value = description or text
        :type values: Dict
        
        :returns: A combobox
        :rtype: QWidget
        '''

        widget = QWidget()
        calendar = QDateTimeEdit()
        calendar.setCalendarPopup(True)
        calendar.setDisplayFormat(display_format)
        if value is not None:
            calendar.setDate(QDate.fromString(value, display_format))
        else:
            calendar.setDate(QDate.currentDate())
        layout = QHBoxLayout(widget)
        layout.addWidget(calendar, 1)
        layout.setAlignment(Qt.AlignCenter)
        layout.setContentsMargins(5, 0, 5, 0)
        widget.setLayout(layout)

        return widget
 def _getCalendar(self, display_format, value = None):
     '''
     Get a combobox filled with the given values
     
     :param values: The values as key = value, value = description or text
     :type values: Dict
     
     :returns: A combobox
     :rtype: QWidget
     '''
     
     
     widget = QWidget()
     calendar = QDateTimeEdit()
     calendar.setCalendarPopup(True)
     calendar.setDisplayFormat(display_format)
     if value is not None:
         calendar.setDate(QDate.fromString(value, display_format))
     else:
         calendar.setDate(QDate.currentDate())
     layout = QHBoxLayout(widget)
     layout.addWidget(calendar, 1);
     layout.setAlignment(Qt.AlignCenter);
     layout.setContentsMargins(5,0,5,0);
     widget.setLayout(layout);
             
     return widget
예제 #7
0
def dow(values, feature, parent):
    """
        Returns an integer representing the day of week for a given date. Returned 
        values range from 0-6, where 0 is Sunday.
        
        <p><h4>Syntax</h4>
        dow(<i>date</i>)</p>

        <p><h4>Arguments</h4>
        <i>  date</i> &rarr; a date value. Must be a valid date or datetime field, or a 
        string in the format 'yyyy-mm-dd'.<br></p>
        
        <p><h4>Example</h4>
        <!-- Show example of function.-->
             dow('2013-07-01') &rarr; 1</p>
    """
    input_date = values[0]

    # Return dayOfWeek() % 7 so that values range from 0 (sun) to 6 (sat)
    # to match Postgresql behaviour
    if type(input_date) == QDateTime:
        return input_date.date().dayOfWeek() % 7
    elif type(input_date) == QDate:
        return input_date.dayOfWeek() % 7
    elif type(input_date) in (str, unicode):
        # Convert string to qdate
        input_qdate = QDate.fromString(input_date, "yyyy-MM-dd")
        if input_qdate.isValid():
            return input_qdate.dayOfWeek() % 7
        else:
            return None
예제 #8
0
 def addX(self, a):
     self.Xresult = []
     self.Xindex = a
     if self.isProcess == False:
         self.dlineEdit_X.setText("X : " +
                                  str(self.df.columns[self.Xindex + 6]))
         self.Xresult = np.array(self.df[self.df.columns[self.Xindex + 6]])
         if self.df.columns[self.Xindex + 6] == "Date":
             for tab in range(len(self.Xresult)):
                 tempdate = QDate.fromString(self.Xresult[tab], "yy-MM-dd")
                 tempdate.setYMD(tempdate.year() + 100, tempdate.month(),
                                 tempdate.day())
                 self.Xresult[tab] = tempdate.toPyDate()
         elif self.df.columns[self.Xindex + 6] == "Time":
             for tab in range(len(self.Xresult)):
                 self.Xresult[tab] = QTime.fromString(
                     self.Xresult[tab]).toPyTime()
                 #self.Xresult[tab]=np.datetime_as_string(self.Xresult[tab])
         else:
             pass
     else:
         self.dlineEdit_X.setText("X : " + str(self.ts1.columns[0]))
         tempx = []
         for tab in xrange(len(self.ts1[self.ts1.columns[0]])):
             #print self.ts1[self.ts1.columns[0]][0]
             #print type(self.ts1[self.ts1.columns[0]][0])
             (val1,
              val2) = str(self.ts1[self.ts1.columns[0]][tab]).split(' ', 1)
             tempx.append(QTime.fromString(val2).toPyTime())
         self.Xresult = np.array(tempx)
예제 #9
0
	def addX(self,a):
		self.Xresult = []
		self.Xindex = a
		if self.isProcess==False:
			self.dlineEdit_X.setText("X : " + str(self.df.columns[self.Xindex + 6]))
			self.Xresult = np.array(self.df[self.df.columns[self.Xindex + 6]])
			if self.df.columns[self.Xindex + 6] == "Date":
				for tab in range(len(self.Xresult)):
					tempdate=QDate.fromString(self.Xresult[tab],"yy-MM-dd")
					tempdate.setYMD(tempdate.year()+100,tempdate.month(),tempdate.day())
					self.Xresult[tab] =tempdate.toPyDate()
			elif self.df.columns[self.Xindex + 6] == "Time":
				for tab in range(len(self.Xresult)):
					self.Xresult[tab] = QTime.fromString(self.Xresult[tab]).toPyTime()
					#self.Xresult[tab]=np.datetime_as_string(self.Xresult[tab])
			else:
				pass
		else:
			self.dlineEdit_X.setText("X : " + str(self.ts1.columns[0]))
			tempx=[]
			for tab in xrange(len(self.ts1[self.ts1.columns[0]])):
				#print self.ts1[self.ts1.columns[0]][0]
				#print type(self.ts1[self.ts1.columns[0]][0])
				(val1,val2)=str(self.ts1[self.ts1.columns[0]][tab]).split(' ',1)
				tempx.append( QTime.fromString(val2).toPyTime())
			self.Xresult = np.array(tempx)
    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
예제 #11
0
def dow(values, feature, parent):
    """
        Returns an integer representing the day of week for a given date. Returned 
        values range from 0-6, where 0 is Sunday.
        
        <h4>Syntax</h4>
        <p>dow(<i>date</i>)</p>

        <h4>Arguments</h4>
        <p><i>  date</i> &rarr; a date value. Must be a valid date or datetime field, or a 
        string in the format 'yyyy-mm-dd'.<br></p>
        
        <h4>Example</h4>
        <p><!-- Show example of function.-->
             dow('2013-07-01') &rarr; 1</p>
    """  
    input_date = values[0]
    
    # Return dayOfWeek() % 7 so that values range from 0 (sun) to 6 (sat)
    # to match Postgresql behaviour
    if type(input_date) == QDateTime:
      return input_date.date().dayOfWeek() % 7
    elif type(input_date) == QDate:
      return input_date.dayOfWeek() % 7
    elif type(input_date) in (str, unicode):      
      # Convert string to qdate
      input_qdate = QDate.fromString(input_date, 'yyyy-MM-dd')
      if input_qdate.isValid():
        return input_qdate.dayOfWeek() % 7     
      else:
        return None
예제 #12
0
 def changeDateFormat(self):
    action = self.sender()
    oldFormat = self.currentDateFormat
    newFormat = self.currentDateFormat = action.text()
    for row in range(self.table.rowCount()):
       item = self.table.item(row, 1)
       date = QDate.fromString(item.text(), oldFormat)
       item.setText(date.toString(newFormat))
예제 #13
0
    def date(self):
        date_string = self._line_edit.text()
        if len(str(date_string).strip()) > 0:
            date = QDate.fromString(date_string, "yyyy-MM-dd")
            if date.isValid():
                return datetime.date(date.year(), date.month(), date.day())

        return None
예제 #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
예제 #15
0
    def date(self):
        date_string = self._line_edit.text()
        if len(str(date_string).strip()) > 0:
            date = QDate.fromString(date_string, "yyyy-MM-dd")
            if date.isValid():
                return datetime.date(date.year(), date.month(), date.day())

        return None
예제 #16
0
    def __init__(self):
        box = gui.widgetBox(self.controlArea, 'Yahoo Finance Stock Data',
                            orientation='horizontal')
        lbox = gui.widgetBox(box, orientation='vertical')
        hbox = gui.widgetBox(lbox, orientation='horizontal')
        gui.label(hbox, self, 'Ticker:')
        self.combo = combo = QComboBox(editable=True,
                                       insertPolicy=QComboBox.InsertAtTop)
        combo.addItems(self.symbols)
        hbox.layout().addWidget(combo)
        # combo = gui.comboBox(
        #     lbox, self, 'symbol',#, items=self.symbols,
        #     label='Ticker:', orientation='horizontal',
        #     editable=True, maximumContentsLength=-1)
        gui.rubber(combo.parentWidget())
        minDate = QDate.fromString(self.MIN_DATE.strftime(self.PY_DATE_FORMAT),
                                   self.QT_DATE_FORMAT)
        date_from = QDateEdit(
            QDate.fromString(self.date_from, self.QT_DATE_FORMAT),
            displayFormat=self.QT_DATE_FORMAT,
            minimumDate=minDate,
            calendarPopup=True)
        date_to = QDateEdit(
            QDate.fromString(self.date_to, self.QT_DATE_FORMAT),
            displayFormat=self.QT_DATE_FORMAT,
            minimumDate=minDate,
            calendarPopup=True)
        date_from.dateChanged.connect(
            lambda date: setattr(self, 'date_from',
                                 date.toString(self.QT_DATE_FORMAT)))
        date_to.dateChanged.connect(
            lambda date: setattr(self, 'date_to',
                                 date.toString(self.QT_DATE_FORMAT)))
        hbox = gui.hBox(lbox)
        gui.label(hbox, self, "From:")
        hbox.layout().addWidget(date_from)
        hbox = gui.hBox(lbox)
        gui.label(hbox, self, "To:")
        hbox.layout().addWidget(date_to)

        gui.radioButtons(box, self, 'data_granularity',
                         btnLabels=[i.name.capitalize().replace('_', ' ')
                                    for i in DataGranularity],
                         box='Resolution')
        self.button = gui.button(self.controlArea, self, 'Download',
                                 callback=self.download)
예제 #17
0
        def hasDate(feature, nameField):
            value = feature.attribute(nameField)
            if value is None or type(value) == QPyNullVariant:
                return False

            date = value if type(value) is QDate else QDate.fromString(
                value, 'yyyy-MM-dd')

            return True if date.isValid() else False
예제 #18
0
    def __init__(self, parent=None, testing=False, participantId=None):
        # Initialize object using ui_addParticipant
        super(EditParticipantDialog, self).__init__(parent)
        self.ui = Ui_AddParticipantDialog()
        self.ui.setupUi(self)

        # Initialize class variables
        self.testing = testing
        if participantId is None:
            QMessageBox.critical(self, 'Invalid Participant', "An invalid participant was chosen.", QMessageBox.Ok)
            self.reject()
        # if participantId[0] == 's':
        #     self.participantId = participantId[1:]
        # else:
        #     self.participantId = participantId
        self.participantId = participantId
        self.participant = dbInteractionInstance.getParticipantFromId(participantId)

        # Set up the contact
        self.contactId = self.participant.contact
        if self.contactId:
            c = dbInteractionInstance.getTeacherFromId(self.contactId)
            if c is not None:
                self.ui.contactPersonLineEdit.setText("{0} {1}".format(c.first, c.last))

        # Initialize ui with variables
        self.ui.addParticipantBtn.setText("&Update Participant")
        self.setWindowTitle("Edit Participant")
        self.ui.firstNameLineEdit.setText(self.participant.first)
        self.ui.lastNameLineEdit.setText(self.participant.last)
        self.ui.addressLineEdit.setText(self.participant.address)
        self.ui.cityLineEdit.setText(self.participant.city)
        self.ui.postalCodeLineEdit.setText(humanPostalCodeFormat(self.participant.postal))
        self.ui.homePhoneLineEdit.setText(humanPhoneNumberFormat(self.participant.home))
        self.ui.cellPhoneLineEdit.setText(humanPhoneNumberFormat(self.participant.cell))
        self.ui.emailLineEdit.setText(self.participant.email)
        self.ui.dateOfBirthDateEdit.setDate(QDate.fromString(self.participant.dob, "yyyy-MM-dd"))
        self.ui.ageLabel.setText("Age as of Jan. 1 {0}".format(QDate.currentDate().year()))
        self.ui.schoolAttendingLineEdit.setText(self.participant.schoolAttending)
        self.ui.parentLineEdit.setText(self.participant.parent)
        self.ui.schoolGradeLineEdit.setText(self.participant.schoolGrade)
        self.ui.groupNameLineEdit.setText(self.participant.groupName)
        self.ui.numberParticipantsLineEdit.setText(self.participant.numberParticipants)
        self.ui.schoolGradeLineEdit.setText(self.participant.schoolGrade)
        self.ui.averageAgeLineEdit.setText(self.participant.averageAge)
        if self.participant.earliestPerformanceTime != "":
            self.ui.timeConstraintsGroupBox.setChecked(True)
            self.ui.earliestPerformanceTimeTimeEdit.setTime(QTime.fromString(self.participant.earliestPerformanceTime, "h:mm A"))
            self.ui.latestPerformanceTimeTimeEdit.setTime(QTime.fromString(self.participant.latestPerformanceTime, "h:mm A"))
        self.ui.participantsTextEdit.setText(self.participant.participants)

        # Set the age display
        self.dob_changed()

        # Make the buttons do things
        self.connectSlots()
예제 #19
0
파일: main.py 프로젝트: jeremiando/des
    def setText(self):
        print self.data
        id, nama, tgl_lahir, kelamin, alamat = self.data
        tgl_lahir = QDate.fromString(tgl_lahir, "yyyy-MM-dd")
        kelamin = 1 if kelamin == "Male" else 0

        self.namaInput.setText(nama)
        self.alamatInput.setText(alamat)
        self.tglLhrInput.setDate(tgl_lahir)
        self.kelaminInput.setCurrentIndex(kelamin)
예제 #20
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
예제 #21
0
def date_from_string(s):
    if not s:
        return None
    from PyQt4.QtCore import QDate
    import string
    s = s.strip()
    f = local_date_format()
    if not s:
        return None
    dt = QDate.fromString(s, f)
    if not dt.isValid():
        # try parsing without separators
        # attention : using non ascii letters will fail on windows
        # string.letters then contains non ascii letters of which we don't know the
        # encoding, so we cannot convert them to unicode to compare them
        only_letters_format = u''.join(
            [c for c in f if c in string.ascii_letters])
        only_letters_string = u''.join(
            [c for c in s if c in (string.ascii_letters + string.digits)])
        dt = QDate.fromString(only_letters_string, only_letters_format)
        if not dt.isValid():
            # try parsing without the year, and take the current year by default
            only_letters_format = u''.join(
                [c for c in only_letters_format if c not in ['y']])
            dt = QDate.fromString(only_letters_string, only_letters_format)
            if not dt.isValid():
                raise ParsingError()


#                # try parsing without year and month, and take the current year and month by default
#                only_letters_format = u''.join([c for c in only_letters_format if c not in ['M']])
#                dt = QDate.fromString(only_letters_string, only_letters_format)
#                if not dt.isValid():
#                    raise ParsingError()
#                else:
#                    today = date.today()
#                    return date(today.year, today.month, dt.day())
            else:
                return date(date.today().year, dt.month(), dt.day())
    return date(dt.year(), dt.month(), dt.day())
예제 #22
0
    def parse_daily_xml(self, xml_data, full_image=False, day_index=0):
        root = ElementTree.fromstring(xml_data)

        if full_image:
            base_url = 'http://www.bing.com' + root[0].find('urlBase').text
            start_date = QDate.fromString(root[0].find('startdate').text, 'yyyyMMdd')
            copyright_info = root[0].find('copyright').text

            image_url = '{}_{}.jpg'.format(base_url, self.resolution)
            if image_url == self.last_image_url:
                print 'Image is the same as last downloaded image.'
                self.download_finished.emit(QImage(), QDate(), '')
                return
            self.status_text.emit('Downloading image...')
            self.last_image_url = image_url
            self._get_url(image_url, 1, (start_date, copyright_info))
        else:
            for image_number in xrange(len(root) - 1):
                image_day_index = image_number + day_index
                url = 'http://www.bing.com' + root[image_number].find('url').text
                image_date = QDate.fromString(root[image_number].find('startdate').text, 'yyyyMMdd')
                copyright_info = root[image_number].find('copyright').text
                self._get_url(url, 4, (image_date, copyright_info, image_day_index))
예제 #23
0
    def updateDetailFilter( self, index ):
        record = self.navmodel.record( index )
        self.dtPicker.setDate( 
                      QDate.fromString( 
                               record.value( "Fecha" ).toString(),
                               "dd/MM/yyyy" ) )
        valor = Decimal( record.value( "totalc" ).toString() )
        self.sbtotalc.setMaximum( valor )
        self.sbtotalc.setValue( valor )

        valor = Decimal( record.value( "totald" ).toString() )
        self.sbtotald.setMaximum( valor )
        self.sbtotald.setValue( valor )

        self.tablenavigation.selectRow( self.mapper.currentIndex() )
예제 #24
0
    def averageDates(self):
        """Calculates and displays the average age"""
        ages = []
        asOfDate = self.ui.asOfDateEdit.date()
        averageAge = 0

        for row in range(self.ui.birthdateListWidget.count()):
            text = str(self.ui.birthdateListWidget.item(row).text())
            date = QDate.fromString(text, "d/M/yyyy")
            age = int(date.daysTo(asOfDate) / 365)
            ages.append(age)

        if len(ages) > 0:
            averageAge = sum(ages)/float(len(ages))

        self.ui.averageAgeLineEdit.setText(str(averageAge))
예제 #25
0
파일: dbhandler.py 프로젝트: ZeeD/calendar
 def data(self, index, role=None):
     """return a QVariant saying if exists a payment at index.(row|column)"""
     if not index.isValid() or role not in (Qt.DisplayRole,
                                            Qt.CheckStateRole):
         return QVariant()
     #self.update_db_content()
     # find the month from the row number
     month_year = QDate().fromString(
         self.headerData(index.row(), Qt.Vertical, role).toString(),
         'MMMM yyyy')
     month = month_year.month()
     year = month_year.year()
     # find the client from the column number
     header_infos = self.headerData(index.column(), Qt.Horizontal,
                                    role).toString().split('\n')
     client = header_infos[0]
     machine = header_infos[1]
     selldate = QDate.fromString(header_infos[2], 'd MMMM yyyy')
     deltamonth = int(header_infos[3][5:-5])  # [len('Ogni '):-len(' mesi')]
     anticiped = header_infos[4][10:-6] == 'anti'  # 'Pagamento ':-'cipato'
     query = QSqlQuery(
         'SELECT expected_datepayd, effective_datepayd FROM '
         'payments WHERE clients_client = :client AND clients_machine = '
         ':machine AND clients_selldate = :selldate AND '
         'expected_datepayd BETWEEN :datebefore AND :dateafter', self._db)
     query.bindValue(':client', QVariant(client))
     query.bindValue(':machine', QVariant(machine))
     query.bindValue(':selldate', QVariant(selldate))
     # primo giorno del mese
     d = QDate(year, month, 1)
     query.bindValue(':datebefore', QVariant(d))
     # ultimo giorno del mese
     query.bindValue(':dateafter', QVariant(d.addMonths(1).addDays(-1)))
     if not query.exec_():
         raise StandardError('SYNTAX ERROR')
     if not query.first():
         return QVariant()
     expected_datepayd = query.value(0).toDate()
     payed = not query.isNull(1)
     effective_datepayd = query.value(1).toDate()
     if role == Qt.CheckStateRole:
         return QVariant(Qt.Checked if payed else Qt.Unchecked)
     else:  # DisplayRole
         date = effective_datepayd if payed else expected_datepayd
         return QVariant(date.toString('d MMMM yyyy'))
예제 #26
0
파일: BettyGUI.py 프로젝트: Whatang/QBetty
 def populateInfo(self):
     self.nameEdit.setText(self.model.racename)
     setCombo(self.courseCombo, self.model.course)
     setCombo(self.classCombo, self.model.raceclass)
     self.prizeSpinner.setValue(self.model.prize)
     if self.model.date is None:
         self.dateEdit.setDate(QDate.currentDate())
     else:
         self.dateEdit.setDate(QDate.fromString(self.model.date, QString("dd/MM/yyyy")))
     if self.model.time is None:
         self.timeEdit.setTime(QTime(12, 0))
     else:
         self.timeEdit.setTime(QTime.fromString(self.model.time, QString("hh:mm")))
     miles = self.model.distance / 8
     furlongs = self.model.distance % 8
     self.milesSpinner.setValue(miles)
     self.furlongCombo.setCurrentIndex(furlongs)
     self.__setNumRunners()
예제 #27
0
    def __init__(self, context, eventId, dateBegin, dateEnd):
        CInfoProxyList.__init__(self, context)
        self._eventId = eventId
        self._dates = []

        db = QtGui.qApp.db
        stmt = "CALL getEventDrugDestinationsDates('%s', '%s', '%s')" % (
            eventId, dateBegin.toString('yyyy-MM-dd'),
            dateEnd.toString('yyyy-MM-dd'))
        query = db.query(stmt)
        while query.next():
            dateStrings = forceString(query.record().value('takeDate'))
            dateStrings = dateStrings.split(',')
            for dateStr in dateStrings:
                date = QDate.fromString(dateStr, 'yyyy-MM-dd')
                if not self._dates.__contains__(date):
                    self._dates.append(date)
        self._items = [None] * len(self._dates)
예제 #28
0
    def go2epa_options_get_data(self, tablename, dialog):
        """ Get data from selected table """
        
        sql = "SELECT * FROM " + self.schema_name + "." + 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
예제 #29
0
 def populateInfo(self):
     self.nameEdit.setText(self.model.racename)
     setCombo(self.courseCombo, self.model.course)
     setCombo(self.classCombo, self.model.raceclass)
     self.prizeSpinner.setValue(self.model.prize)
     if self.model.date is None:
         self.dateEdit.setDate(QDate.currentDate())
     else:
         self.dateEdit.setDate(
             QDate.fromString(self.model.date, QString("dd/MM/yyyy")))
     if self.model.time is None:
         self.timeEdit.setTime(QTime(12, 0))
     else:
         self.timeEdit.setTime(
             QTime.fromString(self.model.time, QString("hh:mm")))
     miles = self.model.distance / 8
     furlongs = self.model.distance % 8
     self.milesSpinner.setValue(miles)
     self.furlongCombo.setCurrentIndex(furlongs)
     self.__setNumRunners()
예제 #30
0
    def __init__(self, parent=None, testing=False, participantId=None):
        # Initialize object using ui_addSoloParticipant
        super(EditSoloParticipantDialog, self).__init__(parent)
        self.ui = Ui_AddSoloParticipantDialog()
        self.ui.setupUi(self)
       
        # Initialize class variables
        self.testing = testing
        if participantId is None:
            QMessageBox.critical(self, 'Invalid Participant', "An invalid participant was chosen.", QMessageBox.Ok)
            self.reject()
        if participantId[0] == 's':
            self.participantId = participantId[1:]
        else:
            self.participantId = participantId
        self.participant = dbInteractionInstance.getParticipantFromId(participantId)

        # Initialize ui with variables
        self.ui.addParticipantBtn.setText("&Update Participant")
        self.setWindowTitle("Edit Participant")
        self.ui.firstNameLineEdit.setText(self.participant.first)
        self.ui.lastNameLineEdit.setText(self.participant.last)
        self.ui.addressLineEdit.setText(self.participant.address)
        self.ui.cityLineEdit.setText(self.participant.town)
        self.ui.postalCodeLineEdit.setText(humanPostalCodeFormat(self.participant.postal))
        self.ui.homePhoneLineEdit.setText(humanPhoneNumberFormat(self.participant.home))
        self.ui.cellPhoneLineEdit.setText(humanPhoneNumberFormat(self.participant.cell))
        self.ui.emailLineEdit.setText(self.participant.email)
        self.ui.dateOfBirthDateEdit.setDate(QDate.fromString(self.participant.dob, "yyyy-MM-dd"))
        self.ui.ageLabel.setText("Age as of Jan. 1 {0}".format(QDate.currentDate().year()))
        self.ui.schoolAttendingLineEdit.setText(self.participant.schoolAttending)
        self.ui.parentLineEdit.setText(self.participant.parent)
        self.ui.schoolGradeLineEdit.setText(self.participant.schoolGrade)

        # Set the age display
        self.dob_changed()

        # Make the buttons do things
        self.connectSlots()
예제 #31
0
파일: form.py 프로젝트: IGNF/saisie_carhab
 def set_field_value(self, widget, value):
     if isinstance(widget, QComboBox):
         idx = widget.findText(unicode(value))
         if not idx == -1:
             widget.setCurrentIndex(idx)
         else:
             widget.setEditText(unicode(value)) if value\
                 else widget.setEditText(None)
     elif isinstance(widget, QLineEdit) or isinstance(widget, QTextEdit):
         widget.setText(unicode(value)) if value else widget.setText(None)
     elif isinstance(widget, QCheckBox):
         widget.setChecked(int(value)) if value \
             else widget.setChecked(False)
     elif isinstance(widget, QDateEdit):
         widget.setDate(QDate.fromString(value, 'yyyy-MM-dd')) if value\
             else widget.setDate(QDate.currentDate())
     elif isinstance(widget, QSpinBox):
         widget.setValue(value) if value\
             else widget.setValue(0)
     elif isinstance(widget, QDoubleSpinBox):
         widget.setValue(value) if value\
             else widget.setValue(0.0)
예제 #32
0
    def eContFill(self, a):

        sid = 23
        data = self.pullStudents(a)
        self.resize(430, 530)

        #self.tabz = QTabWidget(self)
        self.tabz.clear()

        self.tab1 = QWidget(self)
        self.tab2 = QWidget(self)
        self.tab3 = QWidget(self)

        self.schno = QLabel("School Number")
        self.schnoData = QLineEdit()
        self.schnoData.setObjectName("schno")
        if (data['schno'] and len(data['schno']) > 1):
            self.schnoData.setText(data['schno'])
        else:
            self.schnoData.setPlaceholderText("00000000")

        self.surname = QLabel("Surname")
        self.surnameData = QLineEdit()
        self.surnameData.setObjectName("surname")
        if (data['surname'] and len(data['surname']) > 1):
            tx = data['surname']
            self.surnameData.setText(tx.title())
        else:
            self.surnameData.setPlaceholderText("Surname")

        self.firstname = QLabel("Firstname")
        self.firstnameData = QLineEdit()
        self.firstnameData.setObjectName("firstname")
        if (data['firstname'] and len(data['firstname'])):
            tx = data['firstname']
            self.firstnameData.setText(tx.title())
        else:
            self.firstnameData.setPlaceholderText("Firstname")

        self.middlename = QLabel("Middlename")
        self.middlenameData = QLineEdit()
        self.middlenameData.setObjectName("middlename")
        if (data['othername'] and len(data['othername']) > 1):
            tx = data['othername']
            self.middlenameData.setText(tx.title())
        else:
            self.middlenameData.setPlaceholderText("othername")

        self.soo = QLabel("State/Region of Origin")
        self.sooData = QLineEdit()
        self.sooData.setObjectName("soo")
        if (data['soo'] and len(data['soo']) > 1):
            tx = data['soo']
            self.sooData.setText(tx.title())
        else:
            self.sooData.setPlaceholderText("Lagos")

        self.lga = QLabel("LGA/District")
        self.lgaData = QLineEdit()
        self.lgaData.setObjectName("lga")
        if (data['lga'] and len(data['lga'])):
            tx = data['lga']
            self.lgaData.setText(tx.title())
        else:
            self.lgaData.setPlaceholderText("Ikeja")

        self.addr = QLabel("House Address")
        self.addrData = QTextEdit()
        self.addrData.setObjectName("addr")
        if (data['addr'] and len(data['addr'])):
            tx = data['addr']
            self.addrData.setText(tx)
        else:
            pass

        self.dob = QLabel("Date of Birth")
        self.dobData = QDateEdit()
        self.dobData.setObjectName("dob")
        tx = QDate.fromString(data['dob'], 'yyyy-MM-dd')
        self.dobData.setDate(QDate(tx.year(), tx.month(), tx.day()))

        self.admit = QLabel("Date Admitted")
        self.admitData = QDateEdit()
        self.admitData.setObjectName("admit")
        tx = QDate.fromString(data['admit'], 'yyyy-MM-dd')
        self.admitData.setDate(QDate(tx.year(), tx.month(), tx.day()))

        self.pb4 = QPushButton()
        self.pb4.setObjectName("Submit")
        self.pb4.setText("Submit")

        self.pb5 = QPushButton()
        self.pb5.setObjectName("Cancel")
        self.pb5.setText("Cancel")

        hbo = QHBoxLayout()
        self.gender = QLabel('Gender')
        self.r1 = QRadioButton('Male')
        self.r2 = QRadioButton('Female')
        if (data['gender'] == 'Male'):
            self.r1.setChecked(True)
        elif (data['gender'] == 'Female'):
            self.r2.setChecked(True)

        hbo.addWidget(self.r1)
        hbo.addWidget(self.r2)

        Formlayout = QFormLayout()
        Formlayout.addRow(self.schno, self.schnoData)
        Formlayout.addRow(self.surname, self.surnameData)
        Formlayout.addRow(self.firstname, self.firstnameData)
        Formlayout.addRow(self.middlename, self.middlenameData)
        Formlayout.addRow(self.gender, hbo)
        Formlayout.addRow(self.dob, self.dobData)
        Formlayout.addRow(self.admit, self.admitData)
        Formlayout.addRow(self.soo, self.sooData)
        Formlayout.addRow(self.lga, self.lgaData)
        Formlayout.addRow(self.addr, self.addrData)

        grid = QGridLayout()
        grid.addWidget(self.pb1, 0, 1)
        grid.addWidget(self.pb, 0, 0)

        groupBox = QGroupBox('BIODATA')
        groupBox.setLayout(Formlayout)

        vbox = QVBoxLayout()
        vbox.addWidget(groupBox)
        vbox.addStretch()
        vbox.addLayout(grid)

        #self.setLayout(vbox)
        self.connect(self.pb4, SIGNAL("clicked()"),
                     lambda: self.button1_click(sid))
        self.connect(self.pb5, SIGNAL("clicked()"), self.close)
        self.tab1.setLayout(vbox)

        relations = [
            'Father', 'Mother', 'Aunt', 'Uncle', 'Grand Parent', 'Guardian',
            'Others'
        ]

        #first guardian details
        self.g1name = QLabel("First Guardian")
        self.g1Data = QLineEdit()
        self.g1Data.setObjectName("g1name")
        if (data['g1'] and len(data['g1']) > 1):
            tx = data['g1']
            self.g1Data.setText(tx.title())
        else:
            self.g1Data.setPlaceholderText("Mr. Surname Lastname")

        self.g1rel = QLabel('Relationship')
        self.g1relData = QComboBox()
        self.g1relData.addItems(relations)
        if data['g1rel'] and len(data['g1rel']) > 0:
            index1 = self.g1relData.findText(data['g1rel'],
                                             Qt.QtMatchFixedString)
            if index1 >= 0:
                self.g1relData.setCurrentIndex(index1)

        self.g1p1 = QLabel("Phone Number")
        self.g1p1Data = QLineEdit()
        self.g1p1Data.setObjectName("g1p1")
        if (data['g1p1'] and len(data['g1p1']) > 1):
            tx = data['g1p1']
            self.g1p1Data.setText(tx.title())
        else:
            self.g1p1Data.setPlaceholderText("08000000000")

        self.g1p2 = QLabel("Alt. Phone Number")
        self.g1p2Data = QLineEdit()
        self.g1p2Data.setObjectName("g1p2")
        if (data['g1p2'] and len(data['g1p2']) > 1):
            tx = data['g1p2']
            self.g1p2Data.setText(tx.title())
        else:
            self.g1p2Data.setPlaceholderText("08000000000")

        self.g1email = QLabel("Email")
        self.g1emailData = QLineEdit()
        self.g1emailData.setObjectName("g1email")
        if (data['g1email'] and len(data['g1email']) > 1):
            tx = data['g1email']
            self.g1Data.setText(tx.title())
        else:
            self.g1Data.setPlaceholderText("*****@*****.**")

        self.g1addr = QLabel("Address")
        self.g1addrData = QTextEdit()
        self.g1addrData.setObjectName("g1add")
        if (data['g1addr'] and len(data['g1addr']) > 1):
            tx = data['g1addr']
            self.g1Data.setText(tx.title())
        else:
            pass

        #second guardian details
        self.g2name = QLabel("Second Guardian")
        self.g2Data = QLineEdit()
        self.g2Data.setObjectName("g2name")
        if (data['g2'] and len(data['g2']) > 1):
            tx = data['g2']
            self.g2Data.setText(tx.title())
        else:
            self.g2Data.setPlaceholderText("Title. Surname Lastname")

        self.g2rel = QLabel('Relationship')
        self.g2relData = QComboBox()
        self.g2relData.addItems(relations)
        if data['g2rel'] and len(data['g2rel']) > 0:
            index2 = self.g2relData.findText(data['g2rel'],
                                             Qt.QtMatchFixedString)
            if index2 >= 0:
                self.g2relData.setCurrentIndex(index2)

        self.g2p1 = QLabel("Phone Number")
        self.g2p1Data = QLineEdit()
        self.g2p1Data.setObjectName("g2p1")
        if (data['g2p1'] and len(data['g2p1']) > 1):
            tx = data['g2p1']
            self.g2p1Data.setText(tx.title())
        else:
            self.g2p1Data.setPlaceholderText("08000000000")

        self.g2p2 = QLabel("Alt. Phone Number")
        self.g2p2Data = QLineEdit()
        self.g2p2Data.setObjectName("g2p2")
        if (data['g2p2'] and len(data['g2p2']) > 1):
            tx = data['g2p2']
            self.g2p2Data.setText(tx.title())
        else:
            self.g2p2Data.setPlaceholderText("0800000000")

        self.g2email = QLabel("Email")
        self.g2emailData = QLineEdit()
        self.g2emailData.setObjectName("g2email")
        if (data['g2email'] and len(data['g2email']) > 1):
            tx = data['g2email']
            self.g2emailData.setText(tx.title())
        else:
            self.g2emailData.setPlaceholderText("*****@*****.**")

        self.g2addr = QLabel("Address")
        self.g2addrData = QTextEdit()
        self.g2addrData.setObjectName("g2add")
        if (data['g2addr'] and len(data['g2addr']) > 1):
            tx = data['g2addr']
            self.g2Data.setText(tx.title())
        else:
            pass

        self.pb = QPushButton()
        self.pb.setObjectName("Submit")
        self.pb.setText("Submit")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Cancel")
        self.pb1.setText("Cancel")

        hbo = QHBoxLayout()

        self.gender = QLabel('Gender')
        self.r1 = QRadioButton('Male')
        self.r2 = QRadioButton('Female')
        hbo.addWidget(self.r1)
        hbo.addWidget(self.r2)

        Formlayout1 = QFormLayout()
        Formlayout1.addRow(self.g1name, self.g1Data)
        Formlayout1.addRow(self.g1rel, self.g1relData)
        Formlayout1.addRow(self.g1p1, self.g1p1Data)
        Formlayout1.addRow(self.g1p2, self.g1p2Data)
        Formlayout1.addRow(self.g1email, self.g1emailData)
        Formlayout1.addRow(self.g1addr, self.g1addrData)

        Formlayout2 = QFormLayout()
        Formlayout2.addRow(self.g2name, self.g2Data)
        Formlayout2.addRow(self.g2rel, self.g2relData)
        Formlayout2.addRow(self.g2p1, self.g2p1Data)
        Formlayout2.addRow(self.g2p2, self.g2p2Data)
        Formlayout2.addRow(self.g2email, self.g2emailData)
        Formlayout2.addRow(self.g2addr, self.g2addrData)

        grid1 = QGridLayout()
        grid1.addWidget(self.pb, 0, 0)
        grid1.addWidget(self.pb1, 0, 1)

        hbox1 = QHBoxLayout()
        hbox1.addLayout(Formlayout1)
        hbox1.addStretch()
        hbox1.addLayout(Formlayout2)

        groupBox2 = QGroupBox('GUARDIAN')
        groupBox2.setLayout(hbox1)

        vbox1 = QVBoxLayout()
        vbox1.addWidget(groupBox2)
        vbox1.addStretch()
        vbox1.addLayout(grid1)

        self.tab2.setLayout(vbox1)

        #photo
        picstyle = QSize(120, 180)
        picstyle1 = Qt.KeepAspectRatio

        self.pic1Lbl = QLabel('YEAR 1 & 2')
        self.pic2Lbl = QLabel('YEAR 3 & 4')
        self.pic3Lbl = QLabel('YEAR 5 & 6')

        self.pic1 = QLabel()
        pixmap1 = QPixmap('img/studentz.png').scaled(picstyle, picstyle1)
        self.pic1.setPixmap(pixmap1)

        self.pic2 = QLabel()
        pixmap2 = QPixmap('img/studentz.png').scaled(picstyle, picstyle1)
        self.pic2.setPixmap(pixmap2)

        self.pic3 = QLabel()
        pixmap3 = QPixmap('img/studentz.png').scaled(picstyle, picstyle1)
        self.pic3.setPixmap(pixmap3)

        self.picBtn1 = QPushButton('Select Image')
        self.picBtn1.clicked.connect(self.getFilez)

        self.picBtn2 = QPushButton('Select Image')
        self.picBtn2.clicked.connect(self.getFilez)

        self.picBtn3 = QPushButton('Select Image')
        self.picBtn3.clicked.connect(self.getFilez)

        self.pic1Lbl.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.pic2Lbl.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.pic3Lbl.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)

        self.picBtn1.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.picBtn2.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.picBtn3.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)

        h1pic = QVBoxLayout()
        h2pic = QVBoxLayout()
        h3pic = QVBoxLayout()
        vpic = QHBoxLayout()

        h1pic.addWidget(self.pic1Lbl)
        h1pic.addStretch(0)
        h1pic.addWidget(self.pic1)
        h1pic.addStretch(0)
        h1pic.addWidget(self.picBtn1)
        h1pic.setContentsMargins(0, 0, 0, 0)
        h1pic.setSpacing(0)
        h1pic.setMargin(0)

        h2pic.addWidget(self.pic2Lbl)
        h2pic.addStretch(0)
        h2pic.addWidget(self.pic2)
        h2pic.addStretch(0)
        h2pic.addWidget(self.picBtn2)
        h2pic.setContentsMargins(0, 0, 0, 0)
        h2pic.setSpacing(0)
        h2pic.setMargin(0)

        h3pic.addWidget(self.pic3Lbl)
        h3pic.addStretch(0)
        h3pic.addWidget(self.pic3)
        h3pic.addStretch(0)
        h3pic.addWidget(self.picBtn3)
        h3pic.setContentsMargins(0, 0, 0, 0)
        h3pic.setSpacing(0)
        h3pic.setMargin(0)

        vpic.addLayout(h1pic)
        vpic.addStretch(0)
        vpic.addLayout(h2pic)
        vpic.addStretch(0)
        vpic.addLayout(h3pic)
        vpic.setSpacing(0)
        vpic.setMargin(0)
        vpic.setContentsMargins(0, 0, 0, 0)

        self.tab3.setLayout(vpic)
        self.tab3.resize(100, 100)
        self.tab3.setStyleSheet(
            "background-color: red; margin:5px; border:1px solid red;")

        self.tabz.addTab(self.tab1, 'Bio-Data')
        self.tabz.addTab(self.tab2, 'Contact Details')
        self.tabz.addTab(self.tab3, 'Passports')

        self.setWindowTitle("Add Student Data")
        self.show()
예제 #33
0
 def toCorrectEndDate(self, datetime):
     res = self.toDateTuple(datetime)
     if res[0] < 0:  #-4713
         res = self.toDateTuple(
             datetime, QDate.fromString('2199-12-31', 'yyyy-MM-dd'))
     return res
예제 #34
0
    def __init__(self):
        super().__init__()

        self.output_corpus = None
        self.pubmed_api = None
        self.progress = None
        self.email_is_valid = False
        self.record_count = 0
        self.download_running = False

        # To hold all the controls. Makes access easier.
        self.pubmed_controls = []

        h_box = gui.hBox(self.controlArea)
        label = gui.label(h_box, self, 'Email:')
        label.setMaximumSize(label.sizeHint())
        # Drop-down for recent emails.
        self.email_combo = QComboBox(h_box)
        self.email_combo.setMinimumWidth(150)
        self.email_combo.setEditable(True)
        self.email_combo.lineEdit().textChanged.connect(self.sync_email)
        h_box.layout().addWidget(self.email_combo)
        self.email_combo.activated[int].connect(self.select_email)

        # RECORD SEARCH
        self.search_tabs = gui.tabWidget(self.controlArea)
        # --- Regular search ---
        regular_search_box = gui.widgetBox(self.controlArea, addSpace=True)

        # Author
        self.author_input = gui.lineEdit(regular_search_box, self, 'author',
                                         'Author:', orientation=Qt.Horizontal)
        self.pubmed_controls.append(self.author_input)

        h_box = gui.hBox(regular_search_box)
        year_box = gui.widgetBox(h_box, orientation=Qt.Horizontal)
        min_date = QDate.fromString(
                self.MIN_DATE.strftime(self.PY_DATE_FORMAT),
                self.QT_DATE_FORMAT
        )

        if not self.pub_date_from:
            self.pub_date_from = self.MIN_DATE.strftime(self.PY_DATE_FORMAT)
        if not self.pub_date_to:
            self.pub_date_to = date.today().strftime(self.PY_DATE_FORMAT)

        self.date_from = QDateEdit(
                QDate.fromString(self.pub_date_from, self.QT_DATE_FORMAT),
                displayFormat=self.QT_DATE_FORMAT,
                minimumDate=min_date,
                calendarPopup=True
        )
        self.date_to = QDateEdit(
                QDate.fromString(self.pub_date_to, self.QT_DATE_FORMAT),
                displayFormat=self.QT_DATE_FORMAT,
                minimumDate=min_date,
                calendarPopup=True
        )

        self.date_from.dateChanged.connect(
            lambda date: setattr(self, 'pub_date_from',
                                 date.toString(self.QT_DATE_FORMAT)))
        self.date_to.dateChanged.connect(
            lambda date: setattr(self, 'pub_date_to',
                                 date.toString(self.QT_DATE_FORMAT)))
        self.pubmed_controls.append(self.date_from)
        self.pubmed_controls.append(self.date_to)

        gui.label(year_box, self, 'From:')
        year_box.layout().addWidget(self.date_from)
        gui.label(year_box, self, 'to:')
        year_box.layout().addWidget(self.date_to)

        # Keywords.
        h_box = gui.hBox(regular_search_box)
        label = gui.label(h_box, self, 'Query:')
        label.setMaximumSize(label.sizeHint())
        self.keyword_combo = QComboBox(h_box)
        self.keyword_combo.setMinimumWidth(150)
        self.keyword_combo.setEditable(True)
        h_box.layout().addWidget(self.keyword_combo)
        self.keyword_combo.activated[int].connect(self.select_keywords)
        self.pubmed_controls.append(self.keyword_combo)

        tab_height = regular_search_box.sizeHint()
        regular_search_box.setMaximumSize(tab_height)

        # --- Advanced search ---
        advanced_search_box = gui.widgetBox(self.controlArea, addSpace=True)
        # Advanced search query.
        h_box = gui.hBox(advanced_search_box)
        self.advanced_query_input = QTextEdit(h_box)
        h_box.layout().addWidget(self.advanced_query_input)
        self.advanced_query_input.setMaximumSize(tab_height)
        self.pubmed_controls.append(self.advanced_query_input)

        gui.createTabPage(self.search_tabs, 'Regular search',
                          regular_search_box)
        gui.createTabPage(self.search_tabs, 'Advanced search',
                          advanced_search_box)

        # Search info label.
        self.search_info_label = gui.label(
                self.controlArea, self,
                'Number of records found: /')

        # Search for records button.
        self.run_search_button = gui.button(
                self.controlArea,
                self,
                'Find records',
                callback=self.run_search,
                tooltip='Performs a search for articles that fit the '
                        'specified parameters.')
        self.pubmed_controls.append(self.run_search_button)

        h_line = QFrame()
        h_line.setFrameShape(QFrame.HLine)
        h_line.setFrameShadow(QFrame.Sunken)
        self.controlArea.layout().addWidget(h_line)

        # RECORD RETRIEVAL
        # Text includes box.
        text_includes_box = gui.widgetBox(self.controlArea,
                                          'Text includes', addSpace=True)
        self.authors_checkbox = gui.checkBox(text_includes_box, self,
                                          'includes_authors', 'Authors')
        self.title_checkbox = gui.checkBox(text_includes_box, self,
                                        'includes_title', 'Article title')
        self.mesh_checkbox = gui.checkBox(text_includes_box, self,
                                       'includes_mesh', 'Mesh headings')
        self.abstract_checkbox = gui.checkBox(text_includes_box, self,
                                           'includes_abstract', 'Abstract')
        self.url_checkbox = gui.checkBox(text_includes_box, self,
                                         'includes_url', 'URL')
        self.pubmed_controls.append(self.authors_checkbox)
        self.pubmed_controls.append(self.title_checkbox)
        self.pubmed_controls.append(self.mesh_checkbox)
        self.pubmed_controls.append(self.abstract_checkbox)
        self.pubmed_controls.append(self.url_checkbox)

        # Num. records.
        h_box = gui.hBox(self.controlArea)
        label = gui.label(h_box, self, 'Retrieve')
        label.setMaximumSize(label.sizeHint())
        self.num_records_input = gui.spin(h_box, self, 'num_records',
                                          minv=1, maxv=100000)
        self.max_records_label = gui.label(h_box, self, 'records from /.')
        self.max_records_label.setMaximumSize(self.max_records_label
                                              .sizeHint())
        self.pubmed_controls.append(self.num_records_input)

        # Download articles.
        # Search for records button.
        self.retrieve_records_button = gui.button(
                self.controlArea,
                self,
                'Retrieve records',
                callback=self.retrieve_records,
                tooltip='Retrieves the specified documents.')
        self.pubmed_controls.append(self.retrieve_records_button)

        # Num. retrieved records info label.
        self.retrieval_info_label = gui.label(
                self.controlArea,
                self,
                'Number of records retrieved: /')

        # Load the most recent emails.
        self.set_email_list()

        # Load the most recent queries.
        self.set_keyword_list()

        # Check the email and enable controls accordingly.
        if self.recent_emails:
            email = self.recent_emails[0]
            self.email_is_valid = validate_email(email)

        self.enable_controls()
예제 #35
0
 def setEditorValue(self, editor, value):
     editor.setDate(QDate.fromString(value, "yyyy-MM-dd"))
예제 #36
0
 def process_result_value(self, value, dialect):
     return QDate.fromString(value.isoformat(), 'yyyy-MM-dd')
예제 #37
0
파일: gcl.py 프로젝트: wsyshengyun/kmd_2017
def strDateToQdate(sdate):
    return QDate.fromString(sdate, Qt.ISODate)
예제 #38
0
def read_asmm_xml(self, in_file_name):

    f = open(in_file_name, 'r')
    doc = xml.dom.minidom.parse(f)

    ############################
    # Flight Information
    ############################

    self.create_date = get_element_value(doc, "CreationDate")

    flightInformation = get_element(doc, "FlightInformation")

    set_text_value(self.flightNumberLine, flightInformation, "FlightNumber")
    date = get_element_value(flightInformation, "Date")
    self.dateLine.setDate(QDate.fromString(date, Qt.ISODate))
    set_text_value(self.campaignLine, flightInformation, "Campaign")
    set_text_value(self.missionSciLine, flightInformation, "MissionScientist")
    set_text_value(self.flightManagerLine, flightInformation, "FlightManager")
    set_text_value(self.platformLine, flightInformation, "Platform")
    set_text_value(self.operatorLine, flightInformation, "Operator")
    set_text_value(self.countryLine, flightInformation, "Country")

    geographicBoundingBox = get_element(flightInformation,
                                        "GeographicBoundingBox")
    set_text_value(self.westBoundLongitudeLine, geographicBoundingBox,
                   "westBoundLongitude")
    set_text_value(self.eastBoundLongitudeLine, geographicBoundingBox,
                   "eastBoundLongitude")
    set_text_value(self.northBoundLatitudeLine, geographicBoundingBox,
                   "northBoundLatitude")
    set_text_value(self.southBoundLatitudeLine, geographicBoundingBox,
                   "southBoundLatitude")
    set_text_value(self.minAltitudeLine, geographicBoundingBox, "minAltitude")
    set_text_value(self.maxAltitudeLine, geographicBoundingBox, "maxAltitude")

    #############################
    # Metadata Contact Info
    #############################

    contactInfo = get_element(doc, "ContactInfo")

    set_text_value(self.contactNameLine, contactInfo, "ContactName")
    set_text_value(self.contactEmailLine, contactInfo, "ContactEmail")
    combo_text = get_element_value(contactInfo, "ContactRole")
    self.contactRoleBox.setCurrentIndex(
        self.contactRoleBox.findText(combo_text))

    #############################
    # Scientific Aims
    #############################

    scientificAims = get_element(doc, "ScientificAims")

    set_check_values(self.scientific_aims_check_dict, scientificAims,
                     "SA_Code")
    set_text_value(self.SAOtherTextBox, scientificAims, "SA_Other")

    #############################
    # Geographical Region
    #############################

    geographicalRegion = get_element(doc, "GeographicalRegion")

    set_check_values(self.geographical_region_check_dict, geographicalRegion,
                     "GR_Code")
    set_text_value(self.GROtherTextBox, geographicalRegion, "GR_Other")

    #############################
    # Atmospheric Features
    #############################

    atmosphericFeatures = get_element(doc, "AtmosFeatures")

    set_check_values(self.atmospheric_features_check_dict, atmosphericFeatures,
                     "AF_Code")
    set_text_value(self.AFOtherTextBox, atmosphericFeatures, "AF_Other")

    #############################
    # Cloud Types
    #############################

    cloudTypes = get_element(doc, "CloudTypes")

    set_check_values(self.cloud_types_check_dict, cloudTypes, "CT_Code")
    set_text_value(self.CTOtherTextBox, cloudTypes, "CT_Other")

    #############################
    # Particles Sampled
    #############################

    particlesSampled = get_element(doc, "ParticlesSampled")

    set_check_values(self.particles_sampled_check_dict, particlesSampled,
                     "PS_Code")
    set_text_value(self.PSOtherTextBox, particlesSampled, "PS_Other")

    #############################
    # Surfaces Overflown
    #############################

    surfacesOverflown = get_element(doc, "SurfacesOverflown")

    set_check_values(self.surfaces_overflown_check_dict, surfacesOverflown,
                     "SO_Code")
    set_text_value(self.SOOtherTextBox, surfacesOverflown, "SO_Other")

    #############################
    # Altitude Ranges
    #############################

    altitudeRanges = get_element(doc, "AltitudeRanges")

    set_check_values(self.altitude_ranges_check_dict, altitudeRanges,
                     "AR_Code")
    set_text_value(self.AROtherTextBox, altitudeRanges, "AR_Other")

    #############################
    # Flight Types
    #############################

    flightTypes = get_element(doc, "FlightTypes")

    set_check_values(self.flight_types_check_dict, flightTypes, "FT_Code")
    set_text_value(self.FTOtherTextBox, flightTypes, "FT_Other")

    #############################
    # Satellite Coordination
    #############################

    satelliteCoordination = get_element(doc, "SatelliteCoordination")

    set_check_values(self.satellite_coordination_check_dict,
                     satelliteCoordination, "SC_Code")
    set_text_value(self.SCOtherTextBox, satelliteCoordination, "SC_Other")

    #############################
    # Surface Observations
    #############################

    surfaceObservations = get_element(doc, "SurfaceObs")

    self.ground_site_list = get_element_values(surfaceObservations,
                                               "GroundSite")
    self.groundListWidget.addItems(self.ground_site_list)

    self.research_vessel_list = get_element_values(surfaceObservations,
                                                   "ResearchVessel")
    self.vesselListWidget.addItems(self.research_vessel_list)

    self.arm_site_list = get_element_values(surfaceObservations, "ArmSite")
    self.armListWidget.addItems(self.arm_site_list)

    self.arm_mobile_list = get_element_values(surfaceObservations, "ArmMobile")
    self.armMobileListWidget.addItems(self.arm_mobile_list)

    ##############################
    # Other Comments
    ##############################

    set_text_value(self.OtherCommentsTextBox, doc, "OtherComments")
예제 #39
0
        self.validateInputDates()

        if filein.split('.')[-1] == 'nc':
            try:
                Tdata, unit, self.lat, self.lon, self.hw_start, self.hw_end = get_ncdata(
                    file_name, self.hw_start.year, self.hw_end.year, var)
            except KeyError, e:
                raise Exception(
                    'NetCDF file must contain the variable %s in order to continue'
                    % (e, ))
            except Exception, e:
                raise e

            unit = '(' + str(unit) + ')'
            sd = QDate.fromString(self.hw_start.strftime('%Y-%m-%d'),
                                  'yyyy-MM-dd')
            ed = QDate.fromString(self.hw_end.strftime('%Y-%m-%d'),
                                  'yyyy-MM-dd')
            self.dlg.dateEditStart.setDate(sd)
            self.dlg.dateEditEnd.setDate(ed)
            self.dlg.textOutput_lat.setText(str(self.lat))
            self.dlg.textOutput_lon.setText(str(self.lon))

            daily_max = Tdata.resample('24H').max()
            daily_avg = Tdata.resample('24H').mean()
            daily_min = Tdata.resample('24H').min()

        elif filein.split('.')[-1] == 'txt':
            # Ensure user has entered valid lat, lon, start and end times for this data
            self.validateInputCoordinates()
            self.validateInputDates()
예제 #40
0
    def rebuild( self ):
        """
        Rebuilds the scene based on the current settings.
        
        :param      start | <QDate>
                    end   | <QDate>
        """
        gantt           = self.ganttWidget()
        start           = gantt.dateStart()
        end             = gantt.dateEnd()
        cell_width      = gantt.cellWidth()
        cell_height     = gantt.cellHeight()
        rect            = self.sceneRect()
        view            = gantt.viewWidget()
        height          = rect.height()
        header          = gantt.treeWidget().header()
        header_height   = header.height()
        
        if ( not header.isVisible() ):
            header_height   = 0
        
        self._labels            = []
        self._hlines            = []
        self._vlines            = []
        self._weekendRects      = []
	self._bookedRects       = []
	self._unavailableRects = []
	self._overbookedRects      = []
	self._underbookedRects      = []
	self._unassignedRects  = []
	self._holidayRects      = []
	self._currentDayRects   = []
        self._alternateRects    = []
        self._topLabels         = []
        
        # generate formatting info
        top_format      = 'MMM'
	Week            = 'd'
        label_format    = 'd'
        increment       = 1     # days
        
        # generate vertical lines
        x           = 0
        i           = 0
        half        = header_height / 2.0
        curr        = start
        top_label   = start.toString(top_format)
        top_rect    = QRect(0, 0, 0, half)
        alt_rect    = None
        
        while ( curr < end ):
            # update the month rect
            new_top_label = curr.toString(top_format)
            if ( new_top_label != top_label ):
                top_rect.setRight(x)
                self._topLabels.append((top_rect, top_label))
                top_rect  = QRect(x, 0, 0, half)
                top_label = new_top_label
                
                if ( alt_rect is not None ):
                    alt_rect.setRight(x)
                    self._alternateRects.append(alt_rect)
                    alt_rect = None
                else:
                    alt_rect = QRect(x, 0, 0, height)
            
            # create the line
            self._hlines.append(QLine(x, 0, x, height))
            
            # create the header label/rect
            label = str(curr.toString(label_format))
            rect  = QRect(x, half, cell_width, half)
            self._labels.append((rect, label))
            
	    # store weekend rectangles
            if ( curr.dayOfWeek() in (6, 7) ):
                rect = QRect(x, 0, cell_width, height)
                self._weekendRects.append(rect)
	    
	    # store current day rectangle
	    elif ( curr.toString("ddMMyyyy") == QDate.currentDate().toString("ddMMyyyy") ):
                rect = QRect(x, 0, cell_width, height)
                self._currentDayRects.append(rect)
		
            
            
	    # store holiday rectangles
	    
	    
	    
            # increment the dates
            curr = curr.addDays(increment)
            x += cell_width
            i += 1

        if gantt._availabilityEnabled:
	    #iterate through rows
	    for itemcount in range(0,gantt.topLevelItemCount()):
		#check top item, then check child items
		item = gantt.topLevelItem(itemcount)
		if item._dbEntry is not None:
		    if item._dbEntry._type == "phase":
			phase = item._dbEntry
			for key in phase._availability.keys():			    
			    if QDate.fromString(key,"yyyy-MM-dd") >= start:
				diff = start.daysTo(QDate.fromString(key,"yyyy-MM-dd"))
				rect = QRect((diff)*cell_width, header_height+cell_height*(itemcount), cell_width, cell_height)
				if phase._availability[key] == 1:
				    self._underbookedRects.append(rect)
				elif phase._availability[key] == 2:
				    self._bookedRects.append(rect)
				elif phase._availability[key] == 3:
				    self._overbookedRects.append(rect)
			'''
			for pa in item._dbEntry._phaseAssignments.values():
			    for key in pa._availability.keys():						    
				if pa._availability[key] > 8:
				    if QDate.fromString(key,"yyyy-MM-dd") >= start:
					diff = start.daysTo(QDate.fromString(key,"yyyy-MM-dd"))
					rect = QRect((diff)*cell_width, header_height+cell_height*(itemcount), cell_width, cell_height)
					self._overbookedRects.append(rect)
			'''
	
	
	# update the month rect
        top_rect.setRight(x)
        top_label = end.toString(top_format)
        self._topLabels.append((top_rect, top_label))
        
        if ( alt_rect is not None ):
            alt_rect.setRight(x)
            self._alternateRects.append(alt_rect)
        
        # resize the width to match the last date range
        new_width = x
        self.setSceneRect(0, 0, new_width, height)
        
        # generate horizontal lines
        y       = 0
        h       = height
        width   = new_width
        
        while ( y < h ):
            self._vlines.append(QLine(0, y, width, y))
            y += cell_height
        
        # clear the dirty flag
        self._dirty = False
예제 #41
0
    def newDocument( self ):
        """
        Iniciar un nuevo documento
        """
        query = QSqlQuery()
        try:
            if not QSqlDatabase.database().isOpen() and not QSqlDatabase.database().open():
                raise UserWarning( u"No se pudo establecer una conexión "
                                   "con la base de datos" )

            dlgCuenta = dlgSelectCuenta( self )

            fila = -1
    #REPETIR MIENTRAS NO SELECCIONE UNA FILA
            while fila == -1:
                if dlgCuenta.exec_() == QDialog.Accepted:
                    fila = dlgCuenta.tblCuenta.selectionModel().currentIndex().row()
                    if fila == -1:
                        QMessageBox.information( self, qApp.organizationName(),
                                              "Por favor seleccione una cuenta" )
                else:
    #SALIR
                    return




    # SI SELECCIONO UNA FILA SIGUE
            self.editmodel = ConciliacionModel( 
                dlgCuenta.data['saldo_inicial_libro'],
                dlgCuenta.data['fecha'],
                dlgCuenta.data['banco'],
                dlgCuenta.data['cuenta_bancaria'],
                dlgCuenta.data['id_cuenta_contable'],
                dlgCuenta.data['codigo_cuenta_contable'],
                dlgCuenta.data['moneda']
            )

            self.txtbanco.setText( self.editmodel.banco )
            self.txtcuentabanco.setText( self.editmodel.cuenta_bancaria )
            self.txtmoneda.setText( self.editmodel.moneda )
            self.txtcuenta.setText( self.editmodel.codigo_cuenta_contable )
            self.lblfecha.setText( self.editmodel.datetime.toString( "MMMM yyyy" ).upper() )



            if not query.exec_( "CALL spMovimientoCuenta( %d, %s )" % ( 
                    self.editmodel.id_cuenta_contable,
                    self.editmodel.fecha_conciliacion.toString( "yyyyMMdd" )
                )
            ):
                raise Exception( query.lastError().text() )

            row = 0
            while query.next():
                linea = LineaConciliacion( 
                    query.value( 5 ).toBool(), #del_banco
                    Decimal( query.value( 3 ).toString() ), #saldo_inicial
                    Decimal( query.value( DEBE ).toString() ), #monto
                    QDate.fromString( query.value( FECHA ).toString(), 'dd/M/yy' ), #fecha
                    query.value( 6 ).toInt()[0], # tipo_doc
                    query.value( 8 ).toInt()[0], # id_documento
                    query.value( CONCEPTO ).toString() #descripcion
                )
                
                linea.monto = Decimal( query.value( 2 ).toString() )
                self.editmodel.insertRows( row )
                self.editmodel.lines[row] = linea
                row += 1

            #self.editmodel.saldoInicialLibro = self.editmodel.lines[row - 1].saldo
            self.txtsaldolibro.setText( moneyfmt( self.editmodel.saldo_inicial_libro, 4, self.editmodel.moneda ) )
            self.updateLabels()

            self.proxymodel.setSourceModel( self.editmodel )

            self.setControls( False )
            self.tabnavigation.setEnabled( False )
            self.tabWidget.setCurrentIndex( 0 )
            self.tabledetails.setModel( self.editmodel )

            self.tabledetails.resizeColumnsToContents()

            self._ocultar_columnas()

            self.editmodel.dataChanged[QModelIndex, QModelIndex].connect( self.updateLabels )

        except UserWarning as inst:
            logging.error( unicode( inst ) )
            QMessageBox.critical( self, qApp.organizationName(),
                                   unicode( inst ) )
        except Exception as inst:
            logging.critical( unicode( inst ) )
            QMessageBox.critical( self, qApp.organizationName(),
                                   u"Hubo un error al intentar iniciar una"
                                   + u" nueva conciliación" )
        finally:
            if self.database.isOpen():
                self.database.close()
def text_to_date(text):
    text = '{} {}'.format(str(text), str(QDate.currentDate().year()))
    return QDate.fromString(text, 'dddd dd MMMM yyyy')
예제 #43
0
    def processAlgorithm(self, progress):
        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)

        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 = inLayer.dataProvider().fieldNameIndex(attribute)
            selectType = inLayer.dataProvider().fields()[selectindex].type()
            selectionError = False

            if selectType == 2:
                try:
                    y = int(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to integer' %
                                  unicode(comparisonvalue))
            elif selectType == 6:
                try:
                    y = float(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to float' %
                                  unicode(comparisonvalue))
            elif selectType == 10:
                # 10: string, boolean
                try:
                    y = unicode(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to unicode' %
                                  unicode(comparisonvalue))
            elif selectType == 14:
                # date
                dateAndFormat = comparisonvalue.split(' ')

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

                    if y.isNull():
                        msg = self.tr(
                            'Cannot convert "%s" to date with system date format %s'
                            % (unicode(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"'
                            % (unicode(dateAndFormat[0]), dateAndFormat[1]))
                else:
                    y = QDate()
                    msg = ''

                if y.isNull():
                    # Conversion was unsuccessfull
                    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 != 10:
                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 inLayer.getFeatures():
                    aValue = feature.attributes()[selectindex]

                    if aValue is None:
                        continue

                    if selectType == 2:
                        x = int(aValue)
                    elif selectType == 6:
                        x = float(aValue)
                    elif selectType == 10:
                        # 10: string, boolean
                        x = unicode(aValue)
                    elif selectType == 14:
                        # 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())

            inLayer.setSelectedFeatures(selected)

        if inLayer.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 inLayer.selectedFeatures():
            featToEliminate.append(aFeat)

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

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

        progress.setPercentage(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 = inLayer.getFeatures(
                    QgsFeatureRequest().setFilterRect(bbox))
                mergeWithFid = None
                mergeWithGeom = None
                max = 0
                min = -1
                selFeat = QgsFeature()

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

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

                        if iGeom is None:
                            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 inLayer.changeGeometry(mergeWithFid, newGeom):
                        madeProgress = True
                    else:
                        raise GeoAlgorithmExecutionException(
                            self.
                            tr('Could not replace geometry of feature with id %s'
                               % mergeWithFid))

                    start = start + add
                    progress.setPercentage(start)
                else:
                    featNotEliminated.append(feat)

            # End for featToEliminate

            featToEliminate = featNotEliminated

        # End while

        # Create output
        provider = inLayer.dataProvider()
        output = self.getOutputFromName(self.OUTPUT)
        writer = output.getVectorWriter(provider.fields(),
                                        provider.geometryType(), inLayer.crs())

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

        # Leave inLayer untouched
        inLayer.rollBack()

        for feature in featNotEliminated:
            writer.addFeature(feature)
예제 #44
0
    def __init__(self):
        super().__init__()

        self.output_corpus = None
        self.all_hits = 0
        self.num_retrieved = 0
        self.nyt_api = None
        self.api_key = ""
        self.api_key_is_valid = False
        self.query_running = False

        # To hold all the controls. Makes access easier.
        self.nyt_controls = []

        # Root box.
        parameter_box = gui.widgetBox(self.controlArea, addSpace=True)

        # API key box.
        api_key_box = gui.widgetBox(parameter_box, orientation=0)
        # Valid API key feedback.
        self.api_key_valid_label = gui.label(api_key_box, self, "")
        self.update_validity_icon()
        self.api_key_valid_label.setMaximumSize(self.api_key_valid_label.sizeHint())
        # Set API key button.
        self.open_set_api_key_dialog_button = gui.button(api_key_box, self, 'Article API key',
                                                         callback=self.open_set_api_key_dialog,
                                                         tooltip="Set the API key for this widget.")
        self.open_set_api_key_dialog_button.setFocusPolicy(QtCore.Qt.NoFocus)

        # Query box.
        query_box = gui.widgetBox(parameter_box, orientation=0)
        q_label = gui.label(query_box, self, "Query:")
        q_label.setMaximumSize(q_label.sizeHint())
        # Drop-down for recent queries.
        self.query_combo = QComboBox(query_box)
        self.query_combo.setMinimumWidth(150)
        self.query_combo.setEditable(True)
        query_box.layout().addWidget(self.query_combo)
        self.query_combo.activated[int].connect(self.select_query)
        self.query_combo.lineEdit().returnPressed.connect(self.run_initial_query)
        self.nyt_controls.append(self.query_combo)

        # Year box.
        year_box = gui.widgetBox(parameter_box, orientation=0)

        minDate = QDate.fromString(self.MIN_DATE.strftime(self.PY_DATE_FORMAT),
                                   self.QT_DATE_FORMAT)
        date_from = QDateEdit(QDate.fromString(self.date_from, self.QT_DATE_FORMAT),
                              displayFormat=self.QT_DATE_FORMAT,
                              minimumDate=minDate,
                              calendarPopup=True)
        date_to = QDateEdit(QDate.fromString(self.date_to, self.QT_DATE_FORMAT),
                            displayFormat=self.QT_DATE_FORMAT,
                            minimumDate=minDate,
                            calendarPopup=True)
        date_from.dateChanged.connect(
            lambda date: setattr(self, 'date_from', date.toString(self.QT_DATE_FORMAT)))
        date_to.dateChanged.connect(
            lambda date: setattr(self, 'date_to', date.toString(self.QT_DATE_FORMAT)))

        gui.label(year_box, self, "From:")
        year_box.layout().addWidget(date_from)
        gui.label(year_box, self, "to:")
        year_box.layout().addWidget(date_to)

        self.nyt_controls.append(date_from)
        self.nyt_controls.append(date_to)

        # Text includes box.
        self.text_includes_box = gui.widgetBox(self.controlArea,
                                               "Text includes", addSpace=True)
        self.headline_chbox = gui.checkBox(self.text_includes_box, self,
                                           "includes_headline", "Headline")
        self.lead_paragraph_chbox = gui.checkBox(self.text_includes_box, self,
                                                 "includes_lead_paragraph",
                                                 "Lead paragraph")
        self.snippet_chbox = gui.checkBox(self.text_includes_box, self,
                                          "includes_snippet", "Snippet")
        self.abstract_chbox = gui.checkBox(self.text_includes_box, self,
                                           "includes_abstract", "Abstract")
        self.keywords_chbox = gui.checkBox(self.text_includes_box, self,
                                           "includes_keywords", "Keywords")
        self.type_of_material_chbox = gui.checkBox(self.text_includes_box, self,
                                                   "includes_type_of_material",
                                                   "Article type")
        self.web_url_chbox = gui.checkBox(self.text_includes_box, self,
                                          "includes_web_url", "URL")
        self.word_count_chbox = gui.checkBox(self.text_includes_box, self,
                                             "includes_word_count",
                                             "Word count")
        self.nyt_controls.append(self.headline_chbox)
        self.nyt_controls.append(self.lead_paragraph_chbox)
        self.nyt_controls.append(self.snippet_chbox)
        self.nyt_controls.append(self.abstract_chbox)
        self.nyt_controls.append(self.keywords_chbox)
        self.nyt_controls.append(self.type_of_material_chbox)
        self.nyt_controls.append(self.web_url_chbox)
        self.nyt_controls.append(self.word_count_chbox)

        # Run query button.
        self.run_query_button = gui.button(self.controlArea, self, 'Run query',
                                           callback=self.run_initial_query,
                                           tooltip="Run the chosen NYT article query.")
        self.run_query_button.setFocusPolicy(QtCore.Qt.NoFocus)
        self.nyt_controls.append(self.run_query_button)
        h_line = QFrame()
        h_line.setFrameShape(QFrame.HLine)
        h_line.setFrameShadow(QFrame.Sunken)
        self.controlArea.layout().addWidget(h_line)

        # Query info.
        query_info_box = gui.widgetBox(self.controlArea, addSpace=True)
        self.query_info_label = gui.label(query_info_box, self, "Records: /\nRetrieved: /")

        # Retrieve other records.
        self.retrieve_other_button = gui.button(self.controlArea, self, 'Retrieve remaining records',
                                                callback=self.retrieve_remaining_records,
                                                tooltip="Retrieve the remaining records obtained in the query.")
        self.retrieve_other_button.setFocusPolicy(QtCore.Qt.NoFocus)
        self.retrieve_other_button.setEnabled(False)

        # Load the most recent queries.
        self.set_query_list()

        # Check the API key and enable controls accordingly.
        if self.recent_api_keys:
            self.api_key = self.recent_api_keys[0]
            self.check_api_key(self.api_key)

        self.enable_controls()
예제 #45
0
    def restoreValue(self, fail=None):

        valtype = self.attribute('type')
        value = None

        # Restore a list item
        if (valtype == 'list'):
            value = []
            for child in self.children():
                value.append(child.restoreValue())

        # Restore a dictionary item
        elif (valtype == 'dict'):
            value = {}
            for child in self.children():
                value[child.attribute('key')] = child.restoreValue()

        # Record a qdatetime
        elif (valtype == 'QDateTime'):
            value = QDateTime.fromString(self.attribute('value'),
                                         'yyyy-MM-dd hh:mm:ss')

        # Record a qdate
        elif (valtype == 'QDate'):
            value = QDate.fromString(self.attribute('value'), 'yyyy-MM-dd')

        # Restore a QRect
        elif (valtype == 'QRect'):
            value = self.findRect('rect')

        # Restore a QRectF
        elif (valtype == 'QRectF'):
            value = self.findRectF('rect')

        # Restore a QSize
        elif (valtype == 'QSize'):
            value = self.findSize('size')

        # Restore a QSizeF
        elif (valtype == 'QSizeF'):
            value = self.findSizeF('size')

        # Restore a QPoint
        elif (valtype == 'QPoint'):
            value = self.findPoint('point')

        # Restore a QPointF
        elif (valtype == 'QPointF'):
            value = self.findPointF('point')

        # Restore a QColor
        elif (valtype == 'QColor'):
            value = self.findColor('color')

        # restore a QFont
        elif (valtype == 'QFont'):
            value = QFont()
            value.fromString(self.attribute('value'))

        # Restore a string
        elif (valtype in ('str', 'unicode', 'QString')):
            value = unicode(self.attribute('value'))

        elif (valtype == 'ViewMode'):
            # If treated as a basic value would return fail
            value = int(self.attribute('value'))

        # Restore a QByteArray (Experimental)
        elif (valtype == 'QByteArray'):
            value = QByteArray.fromPercentEncoding(self.attribute('value', ''))

        # Restore a Qt.CheckState
        elif valtype == 'CheckState':
            value = Qt.CheckState(self.attribute('value', 0))

        # Restore a basic value
        else:
            try:
                value = eval('%s(%s)' % (valtype, self.attribute('value')))
            except:
                value = fail

        return value
예제 #46
0
    def rebuild(self):
        """
        Rebuilds the scene based on the current settings.
        
        :param      start | <QDate>
                    end   | <QDate>
        """
        gantt = self.ganttWidget()
        start = gantt.dateStart()
        end = gantt.dateEnd()
        cell_width = gantt.cellWidth()
        cell_height = gantt.cellHeight()
        rect = self.sceneRect()
        view = gantt.viewWidget()
        height = rect.height()
        header = gantt.treeWidget().header()
        header_height = header.height()

        if (not header.isVisible()):
            header_height = 0

        self._labels = []
        self._hlines = []
        self._vlines = []
        self._weekendRects = []
        self._bookedRects = []
        self._unavailableRects = []
        self._overbookedRects = []
        self._underbookedRects = []
        self._unassignedRects = []
        self._holidayRects = []
        self._currentDayRects = []
        self._alternateRects = []
        self._topLabels = []

        # generate formatting info
        top_format = 'MMM'
        Week = 'd'
        label_format = 'd'
        increment = 1  # days

        # generate vertical lines
        x = 0
        i = 0
        half = header_height / 2.0
        curr = start
        top_label = start.toString(top_format)
        top_rect = QRect(0, 0, 0, half)
        alt_rect = None

        while (curr < end):
            # update the month rect
            new_top_label = curr.toString(top_format)
            if (new_top_label != top_label):
                top_rect.setRight(x)
                self._topLabels.append((top_rect, top_label))
                top_rect = QRect(x, 0, 0, half)
                top_label = new_top_label

                if (alt_rect is not None):
                    alt_rect.setRight(x)
                    self._alternateRects.append(alt_rect)
                    alt_rect = None
                else:
                    alt_rect = QRect(x, 0, 0, height)

            # create the line
            self._hlines.append(QLine(x, 0, x, height))

            # create the header label/rect
            label = str(curr.toString(label_format))
            rect = QRect(x, half, cell_width, half)
            self._labels.append((rect, label))

            # store weekend rectangles
            if (curr.dayOfWeek() in (6, 7)):
                rect = QRect(x, 0, cell_width, height)
                self._weekendRects.append(rect)

# store current day rectangle
            elif (curr.toString("ddMMyyyy") == QDate.currentDate().toString(
                    "ddMMyyyy")):
                rect = QRect(x, 0, cell_width, height)
                self._currentDayRects.append(rect)

# store holiday rectangles

# increment the dates
            curr = curr.addDays(increment)
            x += cell_width
            i += 1

        self._maxOverbooked = 0

        if gantt._availabilityEnabled:
            #iterate through rows
            for itemcount in range(0, gantt.topLevelItemCount()):
                #check top item, then check child items
                item = gantt.topLevelItem(itemcount)
                if item._dbEntry is not None:
                    if item._dbEntry._type == "phase":
                        phase = item._dbEntry
                        for key in phase._availability.keys():
                            if QDate.fromString(key, "yyyy-MM-dd") >= start:
                                diff = start.daysTo(
                                    QDate.fromString(key, "yyyy-MM-dd"))
                                rect = QRect(
                                    (diff) * cell_width,
                                    header_height + cell_height * (itemcount),
                                    cell_width, cell_height)
                                if phase._availability[key] == 1:
                                    self._underbookedRects.append(rect)
                                elif phase._availability[key] == 2:
                                    self._bookedRects.append(rect)
                                elif phase._availability[key] > 2:
                                    if self._maxOverbooked < int(
                                            phase._availability[key]):
                                        self._maxOverbooked = int(
                                            phase._availability[key])
                                    self._overbookedRects.append(
                                        [rect,
                                         int(phase._availability[key])])
                        '''
			for pa in item._dbEntry._phaseAssignments.values():
			    for key in pa._availability.keys():						    
				if pa._availability[key] > 8:
				    if QDate.fromString(key,"yyyy-MM-dd") >= start:
					diff = start.daysTo(QDate.fromString(key,"yyyy-MM-dd"))
					rect = QRect((diff)*cell_width, header_height+cell_height*(itemcount), cell_width, cell_height)
					self._overbookedRects.append(rect)
			'''

# update the month rect
        top_rect.setRight(x)
        top_label = end.toString(top_format)
        self._topLabels.append((top_rect, top_label))

        if (alt_rect is not None):
            alt_rect.setRight(x)
            self._alternateRects.append(alt_rect)

        # resize the width to match the last date range
        new_width = x
        self.setSceneRect(0, 0, new_width, height)

        # generate horizontal lines
        y = 0
        h = height
        width = new_width

        while (y < h):
            self._vlines.append(QLine(0, y, width, y))
            y += cell_height

        # clear the dirty flag
        self._dirty = False
예제 #47
0
파일: dbhandler.py 프로젝트: ZeeD/calendar
 def setEditorData(self, editor, index):
     """Set the "default" editor data (from the index)"""
     editor.setDate(QDate.fromString(index.data().toString(), self.format))
예제 #48
0
    def __init__(self, filepath):
        tree = ET.parse(filepath)
        root = tree.getroot()
        self.data = {}

        for child in root:

            # project
            if child.tag == 'P_T':
                self.data[child.find('P_ID').text] = dict(
                    RootPath=os.path.dirname(filepath),
                    Name=self.getValue(child, 'P_Name'),
                    Date=QDateTime.fromString(self.getValue(child, 'P_Date'), 'dd.MM.yyyy hh:mm:ss'),
                    Channel='',
                    Sections={})

                #print child.find('P_Name').text

            # section
            if child.tag == 'S_T':
                self.data[child.find('S_Project_ID').text]['Sections'][child.find('S_ID').text] = dict(
                    QgepChannelId1=None,
                    QgepChannelId2=None,
                    QgepChannelId3=None,
                    UsePreviousSection=False,
                    Counter=self.getValue(child, 'S_Counter'),
                    StartNode=self.getValue(child, 'S_StartNode'),
                    EndNode=self.getValue(child, 'S_EndNode'),
                    Sectionlength=float(self.getValue(child, 'S_Sectionlength')),
                    SectionUse=self.getValue(child, 'S_SectionUse'),
                    PipeMaterial=self.getValue(child, 'S_PipeMaterial'),
                    Profile=self.getValue(child, 'S_Profile'),
                    PipeDia=float(self.getValue(child, 'S_PipeDia')),
                    PipeWidth=float(self.getValue(child, 'S_PipeWidth')),
                    #Medianumber=self.getValue(child, 'S_Medianumber'),  # do not exist in XML
                    Inspections={},
                    Import=True)


            # inspection
            if child.tag == 'SI_T':
                found = False
                for p_id, project in self.data.items():
                    for s_id in project['Sections']:
                        if s_id == child.find('SI_Section_ID').text:
                            self.data[p_id]['Sections'][s_id]['Inspections'][child.find('SI_ID').text] = dict(
                                InspMethod=self.getValue(child, 'SI_InspMethod'),
                                InspectionDir=self.getValue(child, 'SI_InspectionDir'),
                                CodeInspectionDir=self.getValue(child, 'CodeSI_InspectionDir'),
                                InspectedLength=float(self.getValue(child, 'SI_InspectedLength') or 0),
                                Operator=self.getValue(child, 'SI_Operator'),
                                Weather=self.getValue(child, 'SI_Weather'),
                                InclinationFileName=self.getValue(child, 'SI_InclinationFileName'),
                                Cleaned=self.getValue(child, 'SI_Cleaned'),
                                InspDate=QDate.fromString(self.getValue(child, 'SI_InspDate'), 'dd.MM.yyyy'),
                                VideoName=self.getValue(child, 'SI_Virtual_x007E_ClipFilename'),
                                Observations={},
                                Import=True)
                            found = True
                            break
                    if found: break
                if not found:
                    raise ValueError('insepction has no section')

            # observation
            if child.tag == 'SO_T':
                found = False
                for p_id, project in self.data.items():
                    for s_id, section in project['Sections'].items():
                        for i_id in section['Inspections']:
                            if i_id == child.find('SO_Inspecs_ID').text:
                                code = self.getValue(child, 'SO_OpCode')
                                PhotoFilenames = []
                                i = 1
                                while True:
                                    pf = self.getValue(child, 'SO_PhotoFilename{}'.format(i))
                                    i += 1
                                    if pf is None:
                                        break
                                    PhotoFilenames.append(pf)
                                self.data[p_id]['Sections'][s_id]['Inspections'][i_id]['Observations'][child.find('SO_ID').text] = dict(
                                    Counter=self.getValue(child, 'SO_Counter'),
                                    Position=float(self.getValue(child, 'SO_Position')),
                                    ToGoMeter=self.getValue(child, 'SO_ToGoMeter'),
                                    Text=self.getValue(child, 'SO_Text'),
                                    MPEGPosition=self.getValue(child, 'SO_MPEGPosition'),
                                    PhotoFilename=PhotoFilenames,
                                    Rate=int(round(float(self.getValue(child, 'SO_Rate') or 4))),
                                    OpCode=code,
                                    ClipFileName1=self.getValue(child, 'SO_ClipFileName1'),
                                    Quant1=self.getValue(child, 'SO_Quant1'),
                                    Quant2=self.getValue(child, 'SO_Quant2'),
                                    Quant1Unit=self.getValue(child, 'SO_Quant1Unit'),
                                    Quant2Unit=self.getValue(child, 'SO_Quant2Unit'),
                                    ObservCode=self.getValue(child, 'SO_ObservCode'),
                                    BendAngleDeg=self.getValue(child, 'SO_BendAngleDeg'),
                                    BendClockH=self.getValue(child, 'SO_BendClockH'),
                                    Import=True if code is not None and code not in SkipCode else False,
                                    ForceImport=False)  # force import if observation is out of channel (channel too short)
                                found = True
                                break
                    if found: break
                if not found:
                        raise ValueError('observation has no insepction')


        # order elements by counter
        for p_id in self.data.keys():
            self.data[p_id]['Sections'] = OrderedDict(sorted(self.data[p_id]['Sections'].items(), key=lambda t: int(t[1]['Counter'])))

            for s_id in self.data[p_id]['Sections'].keys():
                for i_id in self.data[p_id]['Sections'][s_id]['Inspections'].keys():
                    self.data[p_id]['Sections'][s_id]['Inspections'][i_id]['Observations'] = OrderedDict( sorted(self.data[p_id]['Sections'][s_id]['Inspections'][i_id]['Observations'].items(), key=lambda t: t[1]['Position']) )
예제 #49
0
    def processAlgorithm(self, progress):
        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)

        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 = inLayer.dataProvider().fieldNameIndex(attribute)
            selectType = inLayer.dataProvider().fields()[selectindex].type()
            selectionError = False

            if selectType == 2:
                try:
                    y = int(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to integer' % unicode(comparisonvalue))
            elif selectType == 6:
                try:
                    y = float(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to float' % unicode(comparisonvalue))
            elif selectType == 10:
               # 10: string, boolean
                try:
                    y = unicode(comparisonvalue)
                except ValueError:
                    selectionError = True
                    msg = self.tr('Cannot convert "%s" to unicode' % unicode(comparisonvalue))
            elif selectType == 14:
                # date
                dateAndFormat = comparisonvalue.split(' ')

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

                    if y.isNull():
                        msg = self.tr('Cannot convert "%s" to date with system date format %s' % (unicode(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"' % (unicode(dateAndFormat[0]), dateAndFormat[1]))
                else:
                    y = QDate()
                    msg = ''

                if y.isNull():
                    # Conversion was unsuccessfull
                    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 != 10:
                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 inLayer.getFeatures():
                    aValue = feature.attributes()[selectindex]

                    if aValue is None:
                        continue

                    if selectType == 2:
                        x = int(aValue)
                    elif selectType == 6:
                        x = float(aValue)
                    elif selectType == 10:
                        # 10: string, boolean
                        x = unicode(aValue)
                    elif selectType == 14:
                        # 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())

            inLayer.setSelectedFeatures(selected)

        if inLayer.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 inLayer.selectedFeatures():
            featToEliminate.append(aFeat)

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

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

        progress.setPercentage(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 = inLayer.getFeatures(
                    QgsFeatureRequest().setFilterRect(bbox))
                mergeWithFid = None
                mergeWithGeom = None
                max = 0
                min = -1
                selFeat = QgsFeature()

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

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

                        if iGeom == None:
                            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 inLayer.changeGeometry(mergeWithFid, newGeom):
                        madeProgress = True
                    else:
                        raise GeoAlgorithmExecutionException(
                            self.tr('Could not replace geometry of feature with id %s' % mergeWithFid))

                    start = start + add
                    progress.setPercentage(start)
                else:
                    featNotEliminated.append(feat)

            # End for featToEliminate

            featToEliminate = featNotEliminated

        # End while

        # Create output
        provider = inLayer.dataProvider()
        output = self.getOutputFromName(self.OUTPUT)
        writer = output.getVectorWriter(provider.fields(),
                provider.geometryType(), inLayer.crs())

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

        # Leave inLayer untouched
        inLayer.rollBack()

        for feature in featNotEliminated:
            writer.addFeature(feature)
예제 #50
0
    def __init__(self):
        super().__init__()

        self.output_corpus = None
        self.all_hits = 0
        self.num_retrieved = 0
        self.nyt_api = None
        self.api_key = ""
        self.api_key_is_valid = False
        self.query_running = False

        # To hold all the controls. Makes access easier.
        self.nyt_controls = []

        # Root box.
        parameter_box = gui.widgetBox(self.controlArea, addSpace=True)

        # API key box.
        api_key_box = gui.widgetBox(parameter_box, orientation=0)
        # Valid API key feedback.
        self.api_key_valid_label = gui.label(api_key_box, self, "")
        self.update_validity_icon()
        self.api_key_valid_label.setMaximumSize(
            self.api_key_valid_label.sizeHint())
        # Set API key button.
        self.open_set_api_key_dialog_button = gui.button(
            api_key_box,
            self,
            'Article API key',
            callback=self.open_set_api_key_dialog,
            tooltip="Set the API key for this widget.")
        self.open_set_api_key_dialog_button.setFocusPolicy(QtCore.Qt.NoFocus)

        # Query box.
        query_box = gui.widgetBox(parameter_box, orientation=0)
        q_label = gui.label(query_box, self, "Query:")
        q_label.setMaximumSize(q_label.sizeHint())
        # Drop-down for recent queries.
        self.query_combo = QComboBox(query_box)
        self.query_combo.setMinimumWidth(150)
        self.query_combo.setEditable(True)
        query_box.layout().addWidget(self.query_combo)
        self.query_combo.activated[int].connect(self.select_query)
        self.query_combo.lineEdit().returnPressed.connect(
            self.run_initial_query)
        self.nyt_controls.append(self.query_combo)

        # Year box.
        year_box = gui.widgetBox(parameter_box, orientation=0)

        minDate = QDate.fromString(self.MIN_DATE.strftime(self.PY_DATE_FORMAT),
                                   self.QT_DATE_FORMAT)
        date_from = QDateEdit(QDate.fromString(self.date_from,
                                               self.QT_DATE_FORMAT),
                              displayFormat=self.QT_DATE_FORMAT,
                              minimumDate=minDate,
                              calendarPopup=True)
        date_to = QDateEdit(QDate.fromString(self.date_to,
                                             self.QT_DATE_FORMAT),
                            displayFormat=self.QT_DATE_FORMAT,
                            minimumDate=minDate,
                            calendarPopup=True)
        date_from.dateChanged.connect(lambda date: setattr(
            self, 'date_from', date.toString(self.QT_DATE_FORMAT)))
        date_to.dateChanged.connect(lambda date: setattr(
            self, 'date_to', date.toString(self.QT_DATE_FORMAT)))

        gui.label(year_box, self, "From:")
        year_box.layout().addWidget(date_from)
        gui.label(year_box, self, "to:")
        year_box.layout().addWidget(date_to)

        self.nyt_controls.append(date_from)
        self.nyt_controls.append(date_to)

        # Text includes box.
        self.text_includes_box = gui.widgetBox(self.controlArea,
                                               "Text includes",
                                               addSpace=True)
        self.headline_chbox = gui.checkBox(self.text_includes_box, self,
                                           "includes_headline", "Headline")
        self.lead_paragraph_chbox = gui.checkBox(self.text_includes_box, self,
                                                 "includes_lead_paragraph",
                                                 "Lead paragraph")
        self.snippet_chbox = gui.checkBox(self.text_includes_box, self,
                                          "includes_snippet", "Snippet")
        self.abstract_chbox = gui.checkBox(self.text_includes_box, self,
                                           "includes_abstract", "Abstract")
        self.keywords_chbox = gui.checkBox(self.text_includes_box, self,
                                           "includes_keywords", "Keywords")
        self.type_of_material_chbox = gui.checkBox(
            self.text_includes_box, self, "includes_type_of_material",
            "Article type")
        self.web_url_chbox = gui.checkBox(self.text_includes_box, self,
                                          "includes_web_url", "URL")
        self.word_count_chbox = gui.checkBox(self.text_includes_box, self,
                                             "includes_word_count",
                                             "Word count")
        self.nyt_controls.append(self.headline_chbox)
        self.nyt_controls.append(self.lead_paragraph_chbox)
        self.nyt_controls.append(self.snippet_chbox)
        self.nyt_controls.append(self.abstract_chbox)
        self.nyt_controls.append(self.keywords_chbox)
        self.nyt_controls.append(self.type_of_material_chbox)
        self.nyt_controls.append(self.web_url_chbox)
        self.nyt_controls.append(self.word_count_chbox)

        # Run query button.
        self.run_query_button = gui.button(
            self.controlArea,
            self,
            'Run query',
            callback=self.run_initial_query,
            tooltip="Run the chosen NYT article query.")
        self.run_query_button.setFocusPolicy(QtCore.Qt.NoFocus)
        self.nyt_controls.append(self.run_query_button)
        h_line = QFrame()
        h_line.setFrameShape(QFrame.HLine)
        h_line.setFrameShadow(QFrame.Sunken)
        self.controlArea.layout().addWidget(h_line)

        # Query info.
        query_info_box = gui.widgetBox(self.controlArea, addSpace=True)
        self.query_info_label = gui.label(query_info_box, self,
                                          "Records: /\nRetrieved: /")

        # Retrieve other records.
        self.retrieve_other_button = gui.button(
            self.controlArea,
            self,
            'Retrieve remaining records',
            callback=self.retrieve_remaining_records,
            tooltip="Retrieve the remaining records obtained in the query.")
        self.retrieve_other_button.setFocusPolicy(QtCore.Qt.NoFocus)
        self.retrieve_other_button.setEnabled(False)

        # Load the most recent queries.
        self.set_query_list()

        # Check the API key and enable controls accordingly.
        if self.recent_api_keys:
            self.api_key = self.recent_api_keys[0]
            self.check_api_key(self.api_key)

        self.enable_controls()
예제 #51
0
 def setEditorData(self, editor, index):
    if isinstance(editor, QLineEdit):
       editor.setText(index.model().data(index, Qt.EditRole).toString())
    elif isinstance(editor, QDateTimeEdit):
       editor.setDate(QDate.fromString(
            index.model().data(index, Qt.EditRole), self.parent().currentDateFormat))
예제 #52
0
파일: gcl.py 프로젝트: wsyshengyun/kmd_2017
def strDateTimeToQdate(stida):
    tsr = stida.split()[0]
    return QDate.fromString(tsr, Qt.ISODate)