Пример #1
0
/**
* @brief Determines whether to show or hide the reminder date time edit
*/
void TodoDialog::on_reminderCheckBox_clicked() {
    if (ui->reminderCheckBox->isChecked()) {
        QDateTime alarmDate = currentCalendarItem.getAlarmDate();

        // if no alarm date was set use the current date plus 1h
        if (!alarmDate.isValid()) {
            alarmDate = QDateTime::currentDateTime().addSecs(3600);
        }

        ui->reminderDateTimeEdit->setDateTime(alarmDate);
        ui->reminderDateTimeEdit->show();
    } else {
        ui->reminderDateTimeEdit->hide();
    }
}
Пример #2
0
void Easter::getResponse(const QtSoapMessage &message)
{
    if (message.isFault()) {
	qDebug("Error: %s", qPrintable(message.faultString().toString()));
    }
    else {
        QString res = message.returnValue().toString();
        QDateTime dt = QDateTime::fromString(res, Qt::ISODate);
        if (dt.isValid())
            res = QLocale::c().toString(dt.date());

        qDebug("Easter is: %s", res.toLatin1().constData());
    }
    QCoreApplication::quit();
}
Пример #3
0
void QgsDateTimeEdit::setDateTime( const QDateTime &dateTime )
{
  mIsEmpty = false;

  // set an undefined date
  if ( !dateTime.isValid() || dateTime.isNull() )
  {
    clear();
  }
  else
  {
    QDateTimeEdit::setDateTime( dateTime );
    changed( dateTime );
  }
}
Пример #4
0
bool Dvr::RemoveRecorded( int              nChanId,
                          const QDateTime &dStartTime  )
{
    if (nChanId <= 0 || !dStartTime.isValid())
        throw( QString("Channel ID or StartTime appears invalid."));

    bool bResult = false;

    ProgramInfo *pInfo = new ProgramInfo(nChanId, dStartTime);

    if (pInfo->HasPathname())
        bResult = RemoteDeleteRecording(nChanId, dStartTime, true, false);

    return bResult;
}
Пример #5
0
QDateTime RFC822TimeToQDateTime(const QString& t)
{
    QMap<QString, int> TimezoneOffsets;

    if (t.size() < 20)
        return QDateTime();

    QString time = t.simplified();
    short int hoursShift = 0, minutesShift = 0;

    QStringList tmp = time.split(' ');
    if (tmp.isEmpty())
        return QDateTime();
    if (tmp. at(0).contains(QRegExp("\\D")))
        tmp.removeFirst();
    if (tmp.size() != 5)
        return QDateTime();
    QString timezone = tmp.takeAt(tmp.size() -1);
    if (timezone.size() == 5)
    {
        bool ok;
        int tz = timezone.toInt(&ok);
        if(ok)
        {
            hoursShift = tz / 100;
            minutesShift = tz % 100;
        }
    }
    else
        hoursShift = TimezoneOffsets.value(timezone, 0);

    if (tmp.at(0).size() == 1)
        tmp[0].prepend("0");
    tmp [1].truncate(3);

    time = tmp.join(" ");

    QDateTime result;
    if (tmp.at(2).size() == 4)
        result = QLocale::c().toDateTime(time, "dd MMM yyyy hh:mm:ss");
    else
        result = QLocale::c().toDateTime(time, "dd MMM yy hh:mm:ss");
    if (result.isNull() || !result.isValid())
        return QDateTime();
    result = result.addSecs(hoursShift * 3600 * (-1) + minutesShift *60 * (-1));
    result.setTimeSpec(Qt::UTC);
    return result;
}
Пример #6
0
QString TimeSource::parseName(const QString &name)
{
    m_userDateTime = false;
    if (!name.contains('|')) {
        // the simple case where it's just a timezone request
        return name;
    }

    // the various keys we recognize
    static const QString latitude = I18N_NOOP("Latitude");
    static const QString longitude = I18N_NOOP("Longitude");
    static const QString solar = I18N_NOOP("Solar");
    static const QString moon = I18N_NOOP("Moon");
    static const QString datetime = I18N_NOOP("DateTime");

    // now parse out what we got handed in
    const QStringList list = name.split('|', QString::SkipEmptyParts);

    const int listSize = list.size();
    for (int i = 1; i < listSize; ++i) {
        const QString arg = list[i];
        const int n = arg.indexOf('=');

        if (n != -1) {
            const QString key = arg.mid(0, n);
            const QString value = arg.mid(n + 1);

            if (key == latitude) {
                m_latitude = value.toDouble();
            } else if (key == longitude) {
                m_longitude = value.toDouble();
            } else if (key == datetime) {
                QDateTime dt = QDateTime::fromString(value, Qt::ISODate);
                if (dt.isValid()) {
                    setData(I18N_NOOP("DateTime"), dt);
                    m_userDateTime = true;
                }
            }
        } else if (arg == solar) {
            m_solarPosition = true;
        } else if (arg == moon) {
            m_moonPosition = true;
        }
    }

    // timezone is first item ...
    return list.at(0);
}
Пример #7
0
void Client::sendAgentStatus(QString username, QString fullname, Client::Phone phone, int handle, int abandoned, QString group, QDateTime login, QString address, QString extension)
{
    bool groupEmpty = group.isEmpty();

    socketOut.writeStartElement("agent");

    socketOut.writeTextElement("username", username);
    socketOut.writeTextElement("fullname", fullname);

    if (!groupEmpty)
        socketOut.writeTextElement("group", group);

    socketOut.writeTextElement("handle", QString::number(handle));
    socketOut.writeTextElement("abandoned", QString::number(abandoned));

    if (login.isValid())
        socketOut.writeTextElement("login", login.toString("yyyy-MM-dd HH:mm:ss"));

    socketOut.writeTextElement("time", phone.time.toString("yyyy-MM-dd HH:mm:ss"));

    if (!address.isEmpty())
        socketOut.writeTextElement("address", address);

    if (!extension.isEmpty())
        socketOut.writeTextElement("extension", extension);

    socketOut.writeStartElement("phone");
    socketOut.writeAttribute("status", phone.status);
    socketOut.writeAttribute("outbound", phone.outbound ? "true" : "false");

    if (!groupEmpty)
        socketOut.writeAttribute("group", group);

    if (!phone.channel.isEmpty()) {
        socketOut.writeAttribute(phone.active ? "activechannel" : "passivechannel", phone.channel);
    }

    if (!phone.dnis.isEmpty()) {
        socketOut.writeEmptyElement(phone.active ? "callee" : "caller");
        socketOut.writeAttribute("dnis", phone.dnis);
    }

    socketOut.writeEndElement(); // phone

    socketOut.writeEndElement(); // agent

    socket->write("\n");
}
Пример #8
0
void TestDir::createFile(const QString& path, const QByteArray& data, const QDateTime& time)
{
    QString absolutePath = path;
    makePathAbsoluteAndCreateParents(absolutePath);

    QFile f(absolutePath);
    f.open(QIODevice::WriteOnly);
    f.write(data);
    f.close();

    if (time.isValid()) {
        setTimeStamp(absolutePath, time);
    }

    Q_ASSERT(QFile::exists(absolutePath));
}
Пример #9
0
void Column::Private::setDateTimeAt(int row, const QDateTime& new_value)
{
    if (d_data_type != SciDAVis::TypeQDateTime) return;

    emit d_owner->dataAboutToChange(d_owner);
    if (row >= rowCount())
    {
        if (row+1-rowCount() > 1) // we are adding more than one row in resizeTo()
            d_validity.setValue(Interval<int>(rowCount(), row-1), true);
        resizeTo(row+1);
    }

    static_cast< QList<QDateTime>* >(d_data)->replace(row, new_value);
    d_validity.setValue(Interval<int>(row, row), !new_value.isValid());
    emit d_owner->dataChanged(d_owner);
}
Пример #10
0
QFileInfo Content::GetRecording( int              nChanId,
                                 const QDateTime &recstarttsRaw )
{
    if (!recstarttsRaw.isValid())
        throw( "StartTime is invalid" );

    // ------------------------------------------------------------------
    // Read Recording From Database
    // ------------------------------------------------------------------

    QDateTime recstartts = recstarttsRaw.toUTC();

    ProgramInfo pginfo((uint)nChanId, recstartts);

    if (!pginfo.GetChanID())
    {
        LOG(VB_UPNP, LOG_ERR, QString("GetRecording - for '%1' failed")
            .arg(ProgramInfo::MakeUniqueKey(nChanId, recstartts)));

        return QFileInfo();
    }

    if (pginfo.GetHostname().toLower() != gCoreContext->GetHostName().toLower())
    {
        // We only handle requests for local resources

        QString sMsg =
            QString("GetRecording: Wrong Host '%1' request from '%2'.")
                          .arg( gCoreContext->GetHostName())
                          .arg( pginfo.GetHostname() );

        LOG(VB_UPNP, LOG_ERR, sMsg);

        throw HttpRedirectException( pginfo.GetHostname() );
    }

    QString sFileName( GetPlaybackURL(&pginfo) );

    // ----------------------------------------------------------------------
    // check to see if the file exists
    // ----------------------------------------------------------------------

    if (QFile::exists( sFileName ))
        return QFileInfo( sFileName );

    return QFileInfo();
}
Пример #11
0
Track
ITunesLibrary::Track::lastfmTrack() const
{
    // TODO: why are we doing this? It will return true for manual tracks as it checks the path.
    if ( isNull() )
        return Track();

    COM::ITunesTrack i = d->i;

    // These will throw if something goes wrong
    IPodScrobble t;
    t.setArtist( QString::fromStdWString( i.artist() ) );
    t.setTitle( QString::fromStdWString( i.track() ) );
    t.setDuration( i.duration() );
    t.setAlbum( QString::fromStdWString( i.album() ) );
    t.setPlayCount( i.playCount() );

    QDateTime stamp = QDateTime::fromString( QString::fromStdWString( i.lastPlayed() ), "yyyy-MM-dd hh:mm:ss" );
    if ( stamp.isValid() )
    {
        uint unixTime = stamp.toTime_t();

        // This is to prevent the spurious scrobble bug that can happen if iTunes is
        // shut during twiddling. The timestamp returned in that case was FFFFFFFF
        // so let's check for that.
        if ( unixTime == 0xFFFFFFFF )
        {
			qWarning() << "Caught a 0xFFFFFFFF timestamp, assume it's the scrobble of spury:" << QString::fromStdWString( i.toString() );
            return Track();
        } 
        
        t.setTimestamp( stamp );
    }
    else
    {
        // If we don't have a valid timestamp, set to current time. Should work. We hope.
        qWarning() << "Invalid timestamp, set to current:" << QString::fromStdWString( i.toString() );
        t.setTimestamp( QDateTime::currentDateTime() );
    }

    const QString path = QString::fromStdWString( i.path() );

	t.setUrl( QUrl::fromLocalFile( QFileInfo( path ).absoluteFilePath() ) );
    t.setSource( Track::MediaDevice );

    return t;
}
Пример #12
0
QString utils::toSqlValue(QVariant value)
{
    QString toret;
    bool ok;
    value.toDouble(&ok);
    if(ok){
        toret = QString::number(value.toDouble());
    }else{
        QDateTime d = value.toDateTime();
        if(d.isValid()){
            toret = "'" + value.toDateTime().toString("yyyy-MM-dd hh:mm:ss") + "'";
        }else{
            toret = "'" + value.toString() + "'";
        };
    };
    return toret;
}
Пример #13
0
SchemaTime::Ptr SchemaTime::fromDateTime(const QDateTime &dt)
{
    Q_ASSERT(dt.isValid());
    /* Singleton value, allocated once instead of each time it's needed. */
    // STATIC DATA
    static const QDate time_defaultDate(AbstractDateTime::DefaultYear,
                                        AbstractDateTime::DefaultMonth,
                                        AbstractDateTime::DefaultDay);

    QDateTime result;
    copyTimeSpec(dt, result);

    result.setDate(time_defaultDate);
    result.setTime(dt.time());

    return SchemaTime::Ptr(new SchemaTime(result));
}
Пример #14
0
/*!
 * \brief Check if file has been modified since given date/time
 *
 * \param filename File to examine
 * \param date_modified Date to use in comparison
 *
 * \returns True if file has been modified, otherwise false
 */
bool MusicFileScanner::HasFileChanged(
    const QString &filename, const QString &date_modified)
{
    QFileInfo fi(filename);
    QDateTime dt = fi.lastModified();
    if (dt.isValid())
    {
        QDateTime old_dt = MythDate::fromString(date_modified);
        return !old_dt.isValid() || (dt > old_dt);
    }
    else
    {
        LOG(VB_GENERAL, LOG_ERR, QString("Failed to stat file: %1")
            .arg(filename));
        return false;
    }
}
Пример #15
0
void UiCodeModelSupport::init() const
{
    m_initialized = true;
    QDateTime sourceTime = QFileInfo(m_sourceName).lastModified();
    QFileInfo uiHeaderFileInfo(m_fileName);
    QDateTime uiHeaderTime = uiHeaderFileInfo.exists() ? uiHeaderFileInfo.lastModified() : QDateTime();
    if (uiHeaderTime.isValid() && (uiHeaderTime > sourceTime)) {
        QFile file(m_fileName);
        if (file.open(QFile::ReadOnly | QFile::Text)) {
            if (debug)
                qDebug()<<"ui*h file is more recent then source file, using information from ui*h file"<<m_fileName;
            QTextStream stream(&file);
            m_contents = stream.readAll().toUtf8();
            m_cacheTime = uiHeaderTime;
            return;
        }
    }

    if (debug)
        qDebug()<<"ui*h file not found, or not recent enough, trying to create it on the fly";
    QFile file(m_sourceName);
    if (file.open(QFile::ReadOnly | QFile::Text)) {
        QTextStream stream(&file);
        const QString contents = stream.readAll();
        if (runUic(contents)) {
            if (debug)
                qDebug()<<"created on the fly";
            return;
        } else {
            // uic run was unsuccesfull
            if (debug)
                qDebug()<<"uic run wasn't succesfull";
            m_cacheTime = QDateTime ();
            m_contents = QByteArray();
            // and if the header file wasn't there, next time we need to update
            // all of the files that include this header
            if (!uiHeaderFileInfo.exists())
                m_updateIncludingFiles = true;
            return;
        }
    } else {
        if (debug)
            qDebug()<<"Could open "<<m_sourceName<<"needed for the cpp model";
        m_contents = QByteArray();
    }
}
StatSyncing::ScrobblingService::ScrobbleError
ScrobblerAdapter::scrobble( const Meta::TrackPtr &track, double playedFraction,
                            const QDateTime &time )
{
    Q_ASSERT( track );
    if( isToBeSkipped( track ) )
    {
        debug() << "scrobble(): refusing track" << track->prettyUrl()
                << "- contains label:" << m_config->filteredLabel() << "which is marked to be skipped";
        return SkippedByUser;
    }
    if( track->length() * qMin( 1.0, playedFraction ) < 30 * 1000 )
    {
        debug() << "scrobble(): refusing track" << track->prettyUrl() << "- played time ("
                << track->length() / 1000 << "*" << playedFraction << "s) shorter than 30 s";
        return TooShort;
    }
    int playcount = qRound( playedFraction );
    if( playcount <= 0 )
    {
        debug() << "scrobble(): refusing track" << track->prettyUrl() << "- played "
                << "fraction (" << playedFraction * 100 << "%) less than 50 %";
        return TooShort;
    }

    lastfm::MutableTrack lfmTrack;
    copyTrackMetadata( lfmTrack, track );
    // since liblastfm >= 1.0.3 it interprets following extra property:
    lfmTrack.setExtra( "playCount", QString::number( playcount ) );
    lfmTrack.setTimeStamp( time.isValid() ? time : QDateTime::currentDateTime() );
    debug() << "scrobble: " << lfmTrack.artist() << "-" << lfmTrack.album() << "-"
            << lfmTrack.title() << "source:" << lfmTrack.source() << "duration:"
            << lfmTrack.duration();
    m_scrobbler.cache( lfmTrack );
    m_scrobbler.submit(); // since liblastfm 1.0.7, submit() is not called automatically upon cache()
    switch( lfmTrack.scrobbleStatus() )
    {
        case lastfm::Track::Cached:
        case lastfm::Track::Submitted:
            return NoError;
        case lastfm::Track::Null:
        case lastfm::Track::Error:
            break;
    }
    return BadMetadata;
}
Пример #17
0
void CQMiriamWidget::slotCreatedDTChanged(QDateTime newDT)
{
  //Now update.
  // Created at
  std::string DT = "";

  if (newDT.isValid())
    {
      DT = TO_UTF8(newDT.toString(Qt::ISODate));
      DT += "Z";

      if (DT != mpMIRIAMInfo->getCreatedDT())
        {
          mpMIRIAMInfo->setCreatedDT(DT);
        }
    }
}
Пример #18
0
DateTime DateTime::fromString( const QString &dts, const QTimeZone &timeZone )
{
    if (dts.isEmpty()) {
        return DateTime();
    }
    QDateTime dt = QDateTime::fromString(dts, Qt::ISODate);
    if ( ! dt.isValid() ) {
        // try to parse in qt default format (used in early version)
        dt = QDateTime::fromString(dts, Qt::TextDate);
        if (timeZone.isValid()) {
            dt.setTimeZone(timeZone);
        }
        return DateTime(dt);
    }

    return DateTime(dt);
}
Пример #19
0
QDateTime KTimeZone::toZoneTime(const QDateTime &utcDateTime, bool *secondOccurrence) const
{
    if (secondOccurrence)
        *secondOccurrence = false;
    if (!utcDateTime.isValid()  ||  utcDateTime.timeSpec() != Qt::UTC)    // check for invalid time
        return QDateTime();

    // Convert UTC to local time
    if (hasTransitions())
    {
        if (!data(true))
        {
            // No data - default to UTC
            QDateTime dt = utcDateTime;
            dt.setTimeSpec(Qt::LocalTime);
            return dt;
        }

        const KTimeZoneData *data = d->d->data;
        const int index = data->transitionIndex(utcDateTime);
        const int secs = (index >= 0) ? data->transitions().at(index).phase().utcOffset() : data->previousUtcOffset();
        QDateTime dt = utcDateTime.addSecs(secs);
        if (secondOccurrence)
        {
            // Check whether the local time occurs twice around a daylight savings time
            // shift, and if so, whether it's the first or second occurrence.
            *secondOccurrence = data->d->isSecondOccurrence(dt, index);
        }
        dt.setTimeSpec(Qt::LocalTime);
        return dt;
    }
    else
    {
        const int secs = offsetAtUtc(utcDateTime);
        QDateTime dt = utcDateTime.addSecs(secs);
        dt.setTimeSpec(Qt::LocalTime);
        if (secondOccurrence)
        {
            // Check whether the local time occurs twice around a daylight savings time
            // shift, and if so, whether it's the first or second occurrence.
            *secondOccurrence = (secs != offsetAtZoneTime(dt));
        }
        return dt;
    }
}
Пример #20
0
void MidpFileSystemMonitor::timerEvent(QTimerEvent*)
{
    static QDateTime lm;

    QFileInfo fi("/etc/mtab");
    QDateTime dt = fi.lastModified();

    // determine whether 'lm' is not initialized (a first call of the method)
    if (!lm.isValid()) {
        lm = dt;
    }

    // determine whether the file is changed
    if (dt != lm) {
        lm = dt;
        MidpMountedRoots::update();
    }
}
Пример #21
0
qint64 Logger::finishTiming(const QString &AVariable, const QString &AContext)
{
	qint64 timing = -1;

	QMutexLocker locker(&FMutex);
	LoggerData *q = instance()->d;

	QMap<QString, QDateTime> &varMap = q->timings[AVariable];
		
	QDateTime startTime = varMap.take(AContext);
	if (startTime.isValid())
		timing = startTime.msecsTo(QDateTime::currentDateTime());

	if (varMap.isEmpty())
		q->timings.remove(AVariable);

	return timing;
}
void KCalResourceSlox::requestTodos()
{
  KUrl url = mPrefs->url();
  url.setPath( "/servlet/webdav.tasks/" );
  url.setUser( mPrefs->user() );
  url.setPass( mPrefs->password() );

  kDebug() << url;

  QString lastsync = "0";
  if ( mPrefs->useLastSync() ) {
    QDateTime dt = mPrefs->lastTodoSync();
    if ( dt.isValid() ) {
      lastsync = WebdavHandler::qDateTimeToSlox( dt.addDays( -1 ) );
    }
  }

  QDomDocument doc;
  QDomElement root = WebdavHandler::addDavElement( doc, doc, "propfind" );
  QDomElement prop = WebdavHandler::addDavElement( doc, root, "prop" );
  WebdavHandler::addSloxElement( this, doc, prop, fieldName( LastSync ), lastsync );
  WebdavHandler::addSloxElement( this, doc, prop, fieldName( FolderId ), mPrefs->taskFolderId() );
  if ( type() == "ox" ) {
    WebdavHandler::addSloxElement( this, doc, prop, fieldName( ObjectType ), "NEW_AND_MODIFIED" );
    WebdavHandler::addSloxElement( this, doc, prop, fieldName( ObjectType ), "DELETED" );
  } else
    WebdavHandler::addSloxElement( this, doc, prop, fieldName( ObjectType ), "all" );

  kDebug() << "REQUEST TASKS:" << doc.toString( 2 );

  mLoadTodosJob = KIO::davPropFind( url, doc, "0", KIO::HideProgressInfo );
  connect( mLoadTodosJob, SIGNAL( result( KJob * ) ),
           SLOT( slotLoadTodosResult( KJob * ) ) );
  connect( mLoadTodosJob, SIGNAL( percent( KJob *, unsigned long ) ),
           SLOT( slotTodosProgress( KJob *, unsigned long ) ) );

  mLoadTodosProgress = KPIM::ProgressManager::instance()->createProgressItem(
      KPIM::ProgressManager::getUniqueID(), i18n("Downloading to-dos") );
  connect( mLoadTodosProgress,
           SIGNAL( progressItemCanceled( KPIM::ProgressItem * ) ),
           SLOT( cancelLoadTodos() ) );

  mPrefs->setLastTodoSync( QDateTime::currentDateTime() );
}
Пример #23
0
void insertLog(QString table, QString operation, QVariant id, QString userId, QDateTime time)
{
    if (operation != "insert" && operation != "update" && operation != "delete")
        qDebug() << "log operation error: " << operation;

    QString data;

    QSqlQuery qry;
    qry.exec(QString("select * from %1 where id = %2").arg(table).arg(id.toString()));
    if (qry.next())
        data = getRecordJSON(qry);

    // check data change
    if (operation == "update" && table != "files") {
        qry.exec(QString("select row_data from logs where table_name = '%1' and row_id = %2 order by created_at desc").arg(table).arg(id.toString()));
        if (!qry.next() || data == qry.value(0).toString())
            return;
    }

    // check entity id
    if (entityTables.contains(table) && !id.toString().startsWith(App::instance()->libraryId)) {
        qDebug() << "Denied entity edit:" << id.toString();
        return;
    }

    if (! time.isValid())
        time = QDateTime::currentDateTime();

    if (userId.isEmpty() && !App::instance()->userId.isEmpty())
        userId = App::instance()->userId;
    else if (userId.toInt() == 0)
        userId.clear();

    qry.prepare("insert into logs values (?, ?, ?, ?, ?, ?)");
    qry.addBindValue(table);
    qry.addBindValue(operation);
    qry.addBindValue(id);
    qry.addBindValue(data);
    qry.addBindValue(userId);
    qry.addBindValue(formatDateTime(time));
    if (! qry.exec())
        qDebug() << "log " << qry.lastError();
}
Пример #24
0
    bool
  parseDateRFC1123(const QStringList & l, QDateTime & dt)
  {
    if ("GMT" != l[5])
      return false;

    uint day(l[1].toUInt());

    bool haveMonth = false;
    uint month = 0;

    QStringList::ConstIterator it;

    for (it = monthList.begin(); it != monthList.end(); ++it)
    {
      if (*it == l[2])
      {
        haveMonth = true;
        break;
      }

      ++month;
    }

    if (!haveMonth)
      return false;

    uint year(l[3].toUInt());

    QStringList timeTokenList(QStringList::split(':', l[4]));

    if (3 != timeTokenList.count())
      return false;

    uint hours    (timeTokenList[0].toUInt());
    uint minutes  (timeTokenList[1].toUInt());
    uint seconds  (timeTokenList[2].toUInt());

    dt.setDate(QDate(year, month + 1, day));
    dt.setTime(QTime(hours, minutes, seconds));

    return dt.isValid();
  }
Пример #25
0
/*!
  Translate a double value into a QDateTime object.

  For QDateTime result is bounded by QwtDate::minDate() and QwtDate::maxDate()

  \return QDateTime object initialized with timeSpec() and utcOffset().
  \sa timeSpec(), utcOffset(), QwtDate::toDateTime()
 */
QDateTime QwtDateScaleEngine::toDateTime( double value ) const
{
    QDateTime dt = QwtDate::toDateTime( value, d_data->timeSpec );
    if ( !dt.isValid() )
    {
        const QDate date = ( value <= 0.0 ) 
            ? QwtDate::minDate() : QwtDate::maxDate();

        dt = QDateTime( date, QTime( 0, 0 ), d_data->timeSpec );
    }

    if ( d_data->timeSpec == Qt::OffsetFromUTC )
    {
        dt = dt.addSecs( d_data->utcOffset );
        dt.setUtcOffset( d_data->utcOffset );
    }

    return dt;
}
Пример #26
0
QVariantList EventQuery::createDisplayData(const QStringList & item) const
{
    QVariantList displayList;
    displayList.reserve(Max_columns-1);

    for(int i = 0; i < Max_columns; i++) {
        QVariant newEntry;
        switch(i) {

        case Column_Date: {

            QDateTime date = QDateTime::fromString( item.at(Column_Date), Qt::ISODate);
            if(date.isValid()) {
                newEntry = date.toString("dd.MM.yyyy");
            }

            break;
        }
        case Column_Publication:
        {
            QString publicationsContent = QLatin1String("<font size=\"85%\">");
            publicationsContent.append( item.at(i) );

            publicationsContent.chop(5); //last </br>
            publicationsContent.append(QLatin1String("</font>"));

            newEntry = publicationsContent;
            break;
        }
        case Column_StarRate:
        case Column_Title:
            newEntry = item.at(i);
            break;
        default:
            newEntry = QVariant();
        }

        displayList.append(newEntry);
    }

    return displayList;
}
Пример #27
0
DTC::RecRule* Dvr::GetRecordSchedule( uint      nRecordId,
                                      QString   sTemplate,
                                      int       nChanId,
                                      QDateTime dStartTimeRaw,
                                      bool      bMakeOverride )
{
    RecordingRule rule;
    QDateTime dStartTime = dStartTimeRaw.toUTC();

    if (nRecordId > 0)
    {
        rule.m_recordID = nRecordId;
        if (!rule.Load())
            throw QString("Record ID does not exist.");
    }
    else if (!sTemplate.isEmpty())
    {
        if (!rule.LoadTemplate(sTemplate))
            throw QString("Template does not exist.");
    }
    else if (nChanId > 0 && dStartTime.isValid())
    {
        RecordingInfo::LoadStatus status;
        RecordingInfo info(nChanId, dStartTime, false, 0, &status);
        if (status != RecordingInfo::kFoundProgram)
            throw QString("Program does not exist.");
        RecordingRule *pRule = info.GetRecordingRule();
        if (bMakeOverride && rule.m_type != kSingleRecord &&
            rule.m_type != kOverrideRecord && rule.m_type != kDontRecord)
            pRule->MakeOverride();
        rule = *pRule;
    }
    else
    {
        throw QString("Invalid request.");
    }

    DTC::RecRule *pRecRule = new DTC::RecRule();
    FillRecRuleInfo( pRecRule, &rule );

    return pRecRule;
}
Пример #28
0
void
ReportEdit::refresh( const QDateTime & key )
{
	m_model->setQuery( QString("SELECT "
			"%1, "			// datetime is a unique attribute
			"c.who, "
			"l.num_text, "
			"l.num, "
			"CASE WHEN l.zakaz = 0 THEN '' ELSE 'заказное' END, "
			"%2 "
		"FROM "
			"%3 l "
		"INNER JOIN "
			"%4 c ON l.contact_id = c.id "
		"WHERE "
			"%5 "
		"ORDER BY "
			"6 "	// by time
			)
		.arg( _dbPg ? "date_trunc( 'second', l.drec )" : "l.timestamp" )
		.arg( _dbPg ? "\"time\"( l.drec )" : "substr( l.timestamp, 12 )" )
		.arg( _tableName( "log" ) )
		.arg( _tableName( "contact" ) )
		.arg( _dbPg ? QString("date( l.drec ) = '%1'").arg( m_date.toString("yyyy-MM-dd") ) :
				QString("substr( l.timestamp, 1, 10 ) = '%1'").arg( m_date.toString("yyyy-MM-dd") ) ) );

	hideColumn( 0 );	// datetime
	hideColumn( 5 );	// time

	resizeColumnsToContents();

	if ( key.isValid() ) {
		for ( int i = 0; i < m_model->rowCount(); ++i ) {
			if ( m_model->index( i, 0 ).data().toDateTime() == key ) {
				const QModelIndex index = m_model->index( i, 1 );
				setCurrentIndex( index );
				scrollTo( index );
				break;
			}
		}
	}
}
Пример #29
0
void KdbxXmlWriter::writeDateTime(const QString& qualifiedName, const QDateTime& dateTime)
{
    Q_ASSERT(dateTime.isValid());
    Q_ASSERT(dateTime.timeSpec() == Qt::UTC);

    QString dateTimeStr;
    if (m_kdbxVersion < KeePass2::FILE_VERSION_4) {
        dateTimeStr = dateTime.toString(Qt::ISODate);

        // Qt < 4.8 doesn't append a 'Z' at the end
        if (!dateTimeStr.isEmpty() && dateTimeStr[dateTimeStr.size() - 1] != 'Z') {
            dateTimeStr.append('Z');
        }
    } else {
        qint64 secs = QDateTime(QDate(1, 1, 1), QTime(0, 0, 0, 0), Qt::UTC).secsTo(dateTime);
        QByteArray secsBytes = Endian::sizedIntToBytes(secs, KeePass2::BYTEORDER);
        dateTimeStr = QString::fromLatin1(secsBytes.toBase64());
    }
    writeString(qualifiedName, dateTimeStr);
}
Пример #30
0
bool Dvr::UpdateRecordedWatchedStatus ( int RecordedId,
                                        int   chanid,
                                        const QDateTime &recstarttsRaw,
                                        bool  watched)
{
    if ((RecordedId <= 0) &&
        (chanid <= 0 || !recstarttsRaw.isValid()))
        throw QString("Recorded ID or Channel ID and StartTime appears invalid.");

    // TODO Should use RecordingInfo
    ProgramInfo pi;
    if (RecordedId > 0)
        pi = ProgramInfo(RecordedId);
    else
        pi = ProgramInfo(chanid, recstarttsRaw.toUTC());

    pi.SaveWatched(watched);

    return true;
}