Example #1
0
int Tano::Xmltv::timeZoneDiff()
{
    QDateTime local = QDateTime::currentDateTime();
    local.setTime(QTime(0, 0));
    QDateTime utc = local.toUTC();
    local.setTimeSpec(Qt::LocalTime);
    QDateTime offset = local.toUTC();
    QTime properTimeOffset = QTime(offset.time().hour(), offset.time().minute());
    offset.setTimeSpec(Qt::LocalTime);
    utc.setTimeSpec(Qt::UTC);

    bool isNegative;
    if (offset.secsTo(utc) < 0) {
        isNegative = true;
    } else {
        isNegative = false;
        properTimeOffset.setHMS(24 - properTimeOffset.hour() - (properTimeOffset.minute()/60.0) - (properTimeOffset.second()/3600.0), properTimeOffset.minute() - (properTimeOffset.second()/60.0), properTimeOffset.second());
        if (!properTimeOffset.isValid()) { //Midnight case
            properTimeOffset.setHMS(0,0,0);
        }
    }

    if (isNegative)
        return properTimeOffset.secsTo(QTime(0, 0));
    else
        return - properTimeOffset.secsTo(QTime(0, 0));
}
Example #2
0
// --------stay()函数待补充 ---------
void Passenger::UpdateWaitTime(VTime* t) // 不断更新当前乘客的等待时间,如果等待时间超出最大忍耐时限会发出leave()信号
{
    QTime current = t->GetCurVTime();
    int waitTime = - current.secsTo(requestTime);
    if(waitTime >= tolerationTime)
        emit leave(this);  // 向楼层发出“离开”信号  -> 楼层接到该信号后应将该乘客从等待链表中删去。
}
void
MetaQueryWidget::numValue2Changed( const QTime& value )
{
    m_filter.numValue2 = qAbs( value.secsTo( QTime(0,0,0) ) );

    emit changed(m_filter);
}
Example #4
0
QTipDlg::QTipDlg(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::QTipDlg)
{
    ui->setupUi(this);
    QDesktopWidget *dwsktopwidget = QApplication::desktop();
    QRect screenrect = dwsktopwidget->screenGeometry();
//    qCritical("screenrect.w==%s\n",qPrintable(QString::number(screenrect.width())));
//    qCritical("screenrect.h==%s\n",qPrintable(QString::number(screenrect.height())));

    QString imgStyle = "border-image: url(:/pic/pic/background";
    QString imgStr = ".jpg);";
    int picNo = qrand()%10+1;
    this->ui->graphicsView->setStyleSheet(imgStyle+QString::number(picNo)+imgStr);


    this->setGeometry(screenrect.width()-500+160,screenrect.height()-240-60,300,240);
    this->setWindowFlags(Qt::FramelessWindowHint);

    QTime nowTime = QTime::currentTime();
    int nowHour = nowTime.hour();
    QTime targetTime = QTime(nowHour,59,59);//到下一个 整点时钟

    int seconds = nowTime.secsTo(targetTime)+1;

    ui->labelTime->setText("现在是北京时间"+nowTime.toString("hh点mm分"));
    QString secs = QString::number(seconds,10);

    ui->labelTip->setText("请休息一下吧  ");
}
Example #5
0
QTime modCalcDayLength::lengthOfDay(QTime setQTime, QTime riseQTime){
	QTime dL(0,0,0);
	int dds = riseQTime.secsTo(setQTime);
	QTime dLength = dL.addSecs( dds );

	return dLength;
}
void TestSingleSignon::multipleClientsAtOnceTest()
{
    QList<SsoClientThread *> clientThreads;

    QTime startTime = QTime::currentTime();
    for(int i = 0; i < m_numberOfTestClients; i++)
    {
        qDebug() << "\n\nCreating SSO test client thread...\n\n";
        SsoClientThread *thread = new SsoClientThread(SsoTestClient::AllTests);
        thread->start();
        clientThreads.append(thread);
    }

    SsoClientThread *thread = NULL;
    bool done = false;

    //this assumes all client threads will be finished at a certain point
    while(!done)
    {
        int finishedThreadsCount = 0;
        foreach(thread, clientThreads)
            if(thread->isFinished()) ++finishedThreadsCount;

        done = ((finishedThreadsCount == m_numberOfTestClients) ? true : false);
        sleep(1);
    }

    while(!clientThreads.empty())
        if(SsoClientThread *thread = clientThreads.takeFirst()) delete thread;

    QTime endTime = QTime::currentTime();
    int elapsed = startTime.secsTo(endTime);
    qDebug() << QString("TestSingleSignon::multipleClientsAtOnceTest() ---- TIME --> Total elapsed time: %1 seconds.\n\n").arg(elapsed);
}
Example #7
0
void PendingFileQueue::processPendingFiles()
{
    QTime currentTime = QTime::currentTime();
    int nextUpdate = m_maxTimeout;

    QMutableHashIterator<QString, QTime> it(m_pendingFiles);
    while (it.hasNext()) {
        it.next();

        int secondsLeft = currentTime.secsTo(it.value());
        if (secondsLeft <= 0) {
            Q_EMIT indexModifiedFile(it.key());
            m_recentlyEmitted.insert(it.key(), currentTime);

            it.remove();
        }
        else {
            nextUpdate = qMin(secondsLeft, nextUpdate);
        }
    }

    if (!m_pendingFiles.isEmpty()) {
        m_pendingFilesTimer.setInterval(nextUpdate * 1000);
        m_pendingFilesTimer.start();
    }

    if (!m_recentlyEmitted.isEmpty() && !m_clearRecentlyEmittedTimer.isActive()) {
        m_clearRecentlyEmittedTimer.setInterval(m_trackingTime * 1000);
        m_clearRecentlyEmittedTimer.start();
    }
}
Example #8
0
void
ScriptEngine::resolve( const Tomahawk::query_ptr& query )
{
    qDebug() << Q_FUNC_INFO << query->toString();
    QString eval = QString( "resolve( '%1', '%2', '%3', '%4' );" )
                      .arg( query->id().replace( "'", "\\'" ) )
                      .arg( query->artist().replace( "'", "\\'" ) )
                      .arg( query->album().replace( "'", "\\'" ) )
                      .arg( query->track().replace( "'", "\\'" ) );

    QList< Tomahawk::result_ptr > results;

    QVariantMap m = mainFrame()->evaluateJavaScript( eval ).toMap();
    qDebug() << "JavaScript Result:" << m;

    const QString qid = query->id();
    const QVariantList reslist = m.value( "results" ).toList();

    foreach( const QVariant& rv, reslist )
    {
        QVariantMap m = rv.toMap();
        qDebug() << "RES" << m;

        Tomahawk::result_ptr rp( new Tomahawk::Result() );
        Tomahawk::artist_ptr ap = Tomahawk::Artist::get( 0, m.value( "artist" ).toString() );
        rp->setArtist( ap );
        rp->setAlbum( Tomahawk::Album::get( 0, m.value( "album" ).toString(), ap ) );
        rp->setTrack( m.value( "track" ).toString() );
        rp->setBitrate( m.value( "bitrate" ).toUInt() );
        rp->setUrl( m.value( "url" ).toString() );
        rp->setSize( m.value( "size" ).toUInt() );
        rp->setScore( m.value( "score" ).toFloat() * ( (float)m_parent->weight() / 100.0 ) );
        rp->setRID( uuid() );
        rp->setFriendlySource( m_parent->name() );

        if ( m.contains( "year" ) )
        {
            QVariantMap attr;
            attr[ "releaseyear" ] = m.value( "year" );
            rp->setAttributes( attr );
        }

        rp->setDuration( m.value( "duration", 0 ).toUInt() );
        if ( rp->duration() <= 0 && m.contains( "durationString" ) )
        {
            QTime time = QTime::fromString( m.value( "durationString" ).toString(), "hh:mm:ss" );
            rp->setDuration( time.secsTo( QTime( 0, 0 ) ) * -1 );
        }

        rp->setMimetype( m.value( "mimetype" ).toString() );
        if ( rp->mimetype().isEmpty() )
        {
            rp->setMimetype( TomahawkUtils::extensionToMimetype( m.value( "extension" ).toString() ) );
            Q_ASSERT( !rp->mimetype().isEmpty() );
        }

        results << rp;
    }
Example #9
0
int LoggingWindow::timetableSlotFromTime(QTime time) {
    int returnInt;
    if (time.secsTo(*this->p1) > 0) {
        returnInt = 0;
    }
    else if (time.secsTo(*this->p2) > 0) {
        returnInt = 1;
    }
    else if (time.secsTo(*this->form) > 0) {
        returnInt = 2;
    }
    else if (time.secsTo(*this->p3) > 0) {
        returnInt = 3;
    }
    else if (time.secsTo(*this->p4) > 0) {
        returnInt = 4;
    }
    else if (time.secsTo(*this->lunch) > 0) {
        returnInt = 5;
    }
    else if (time.secsTo(*this->p5) > 0) {
        returnInt = 6;
    }
    else {
        returnInt = 7;
    }
    return returnInt;

}
Example #10
0
QTime Funcoes::DiferencaEntreHoras(QTime hora1, QTime hora2)
{
    QTime diferenca(0, 0, 0);

    if( hora1 < hora2 )
        diferenca = diferenca.addSecs( hora1.secsTo( hora2 ) );

    return diferenca;
}
Example #11
0
/**
 * Parse a time value from the provided string.
 *
 * @param value The text to be parsed
 * @param ok Pointer to a boolean value which will represent the success or
 *           failure of the parsing attempt
 * @return The number of seconds after midnight in the parsed time, shown as
 *         a string
 */
QString Formatting::parseTimeString(const QString &value, bool *ok)
{
    // check for imported blank
    if (value.isEmpty()) {
        *ok = true;
        return "-1";
    }
    int length = value.length();
    int firstColon = value.indexOf(':');
    if (firstColon == -1) {
        // assume it's a number of seconds, as used internally
        int totalSeconds = value.toInt(ok);
        if (!(*ok) || totalSeconds < -1 || totalSeconds > 86399) {
            *ok = false;
        }
        return value;
    }
    // from here on is used only when importing
    if (firstColon < 1 || length < firstColon + 3) {
        *ok = false;
        return value;
    }
    int hours = value.left(firstColon).toInt(ok);
    if (!(*ok)) {
        return value;
    }
    int minutes = value.mid(firstColon + 1, 2).toInt(ok);
    if (!(*ok)) {
        return value;
    }
    int seconds = 0;
    int secondColon = value.indexOf(':', firstColon + 1);
    if (secondColon != -1 && length > secondColon + 2) {
        seconds = value.mid(secondColon + 1, 2).toInt(ok);
        if (!(*ok)) {
            return value;
        }
    }
    if (value.indexOf("pm", 0, Qt::CaseInsensitive) != -1) {
        if (hours < 12) {
            hours += 12;
        }
    }
    else if (value.indexOf("am", 0, Qt::CaseInsensitive) != -1 && hours == 12) {
        hours = 0;
    }
    QTime time;
    if (!time.setHMS(hours, minutes, seconds)) {
        *ok = false;
        return value;
    }
    QTime midnight;
    int totalSeconds = midnight.secsTo(time);
    *ok = true;
    return QString::number(totalSeconds);
}
Example #12
0
//保存当前列表
void MusicList::slot_SaveList()
{
	QString fileName = QFileDialog::getSaveFileName(this, tr("保存播放列表"), tr("播放列表"), tr("*.m3u *.pls"));
	if (!fileName.isEmpty())
	{
		ofstream file(fileName.toStdString());

		QString strSuffixName = fileName.right(3);//得到后缀名
		if (strSuffixName == "m3u" || strSuffixName == "M3U")
		{
			file << "#EXTM3U" << endl;			//表示一个M3U文件
		}
		else if (strSuffixName == "pls" || strSuffixName == "PLS")
		{
			file << "[playlist]" << endl;		//表示一个pls文件
		}

		vector<MusicListSaveFormatEntity> vec;
		if (DBModule::readMusicListSaveFormatEntity(vec))
		{
			int i = 0;
			foreach (MusicListSaveFormatEntity entity, vec)
			{
				++i;
				QTime qTime;
				int nTime = qTime.secsTo(QTime::fromString(QString::fromStdString(entity.getTime()), "mm:ss"));

				if (strSuffixName == "m3u" || strSuffixName == "M3U")
				{
					QString sFileName = QString::fromStdString(entity.getFileName());
					QString strMusicName = "";
					if (sFileName.contains(" - "))
					{
						strMusicName = sFileName.split(" - ").at(1);
					}
					file << "#EXTINF:" << nTime << "," << strMusicName.toStdString() << "\n" << entity.getFilePath() << endl;
				}
				else if (strSuffixName == "pls" || strSuffixName == "PLS")
				{
					QString sFileName = QString::fromStdString(entity.getFileName());
					QString strMusicName = "";
					if (sFileName.contains(" - "))
					{
						strMusicName = sFileName.split(" - ").at(1);
					}
					file << "File" << i << "=" << entity.getFilePath() << "\n"
						 << "Title" << i << "=" << strMusicName.toStdString() << "\n"
						 << "Length" << i << "=" << nTime << endl;
				}
			}
			if (strSuffixName == "pls" || strSuffixName == "PLS")
			{
				file << "NumberOfEntries=" << i <<  endl;
			}
		}
Example #13
0
void TreeButton::refreshConnectedSince()
{
    this->timer.stop();

    if (Preferences::instance()->isVisible()) {
        QDate cDate (this->getParentItemCast()->getOpenVPN()->getConnectedSinceDate());
        QTime cTime (this->getParentItemCast()->getOpenVPN()->getConnectedSinceTime());

        // Nun die Zet ermitteln
        int diffDays (cDate.daysTo(QDate::currentDate()));
        int diffSeconds (cTime.secsTo(QTime::currentTime()));

        int hours (0);
        int minutes (0);
        int seconds (0);
        if (diffSeconds < 0) {
            // Bei einem negativen Ergebniss liegt die Zeit in der Zukunft,
            // es muss aber in der Vergangeheit liegen, es kann ein neuer Tag sein
            // Sekunden zurücksetzen
            diffSeconds = 0;
            this->getParentItemCast()->getOpenVPN()->setConnectedSinceTime(QTime::currentTime());
        }

        if (diffSeconds >= 3600) {
            // Stunden sind da
            // Stunden ermitteln
            hours = (int) diffSeconds / 3600;
            // Neuen Rest
            diffSeconds = diffSeconds - (3600 * hours);
            if (diffDays > 0) {
                // Tage auf Stunden rechnen
                hours = hours + diffDays * 24;
            }
        }
        // Minuten da?
        if (diffSeconds >= 60) {
            minutes = (int) diffSeconds / 60;
            // Neuen Rest ermitteln
            diffSeconds = diffSeconds - (minutes * 60);
        }

        // Sind noch Sekunden übrig?
        if (diffSeconds > 0) {
            seconds = diffSeconds;
        }

        // Alles ermittelt nun setzen
        this->getParentItem()->setText(1, this->getParentItemCast()->getOpenVPN()->getConfigName()
                                          + QLatin1String ("\n") + (hours < 10 ? "0" : "") + QString::number(hours)
                                          + QLatin1String (":") + (minutes < 10 ? "0" : "") + QString::number(minutes)
                                          + QLatin1String (":") + (seconds < 10 ? "0" : "") + QString::number(seconds));
    }

    this->timer.start();
}
void TestSingleSignon::singleTestClient()
{
    QTime startTime = QTime::currentTime();

    SsoTestClient client;
    client.runAllTests();

    QTime endTime = QTime::currentTime();
    int elapsed = startTime.secsTo(endTime);
    qDebug() << QString("TestSingleSignon::singleTestClient() ---- TIME --> Total elapsed time: %1 seconds.\n\n").arg(elapsed);
}
Example #15
0
void PendingFileQueue::processCache()
{
    QTime currentTime = QTime::currentTime();

    for (const PendingFile& file : qAsConst(m_cache)) {
        if (file.shouldRemoveIndex()) {
            Q_EMIT removeFileIndex(file.path());

            m_recentlyEmitted.remove(file.path());
            m_pendingFiles.remove(file.path());
        }
        else if (file.shouldIndexXAttrOnly()) {
            Q_EMIT indexXAttr(file.path());
        }
        else if (file.shouldIndexContents()) {
            if (m_pendingFiles.contains(file.path())) {
                QTime time = m_pendingFiles[file.path()];

                int secondsLeft = currentTime.secsTo(time);
                secondsLeft = qBound(m_minTimeout, secondsLeft * 2, m_maxTimeout);

                time = currentTime.addSecs(secondsLeft);
                m_pendingFiles[file.path()] = time;
            }
            else if (m_recentlyEmitted.contains(file.path())) {
                QTime time = currentTime.addSecs(m_minTimeout);
                m_pendingFiles[file.path()] = time;
            }
            else {
                if (file.isNewFile()) {
                    Q_EMIT indexNewFile(file.path());
                } else {
                    Q_EMIT indexModifiedFile(file.path());
                }
                m_recentlyEmitted.insert(file.path(), currentTime);
            }
        } else {
            Q_ASSERT_X(false, "FileWatch", "The PendingFile should always have some flags set");
        }
    }

    m_cache.clear();

    if (!m_pendingFiles.isEmpty() && !m_pendingFilesTimer.isActive()) {
        m_pendingFilesTimer.setInterval(m_minTimeout * 1000);
        m_pendingFilesTimer.start();
    }

    if (!m_recentlyEmitted.isEmpty() && !m_clearRecentlyEmittedTimer.isActive()) {
        m_clearRecentlyEmittedTimer.setInterval(m_trackingTime * 1000);
        m_clearRecentlyEmittedTimer.start();
    }
}
Example #16
0
void SplitVideo::toTimeChanged( const QTime & )
{
    QTime t;
    m_endTime = t.secsTo( ui->teTo->time() );

    qDebug( "SplitVideo::toTimeChanged:    m_endTime = %d", m_endTime );

    // correct time
    if ( m_startTime > m_endTime )
        m_startTime = m_endTime;

    updateTime();
}
Example #17
0
void QTipDlg::on_pushbutton_ok_clicked()
{
    this->hide();

    QTime nowTime = QTime::currentTime();
    int nowHour = nowTime.hour();
    QTime targetTime = QTime(nowHour,59,59);//到下一个 整点时钟
    int seconds = nowTime.secsTo(targetTime)+1;
    qDebug()<<seconds;

    QTimer::singleShot(seconds*10, this, SLOT(showTip()));

}
void CannonField::newTarget()
{
	static bool firstTime = true;

	if (firstTime)
	{
		firstTime = false;
		QTime midnight (0, 0, 0);
		qsrand (midnight.secsTo (QTime::currentTime()));
	}

	target = QPoint (200 + qrand() % 190, 10 + qrand() % 255);
	update();
}
QRect NextAvailabiliyManager::simplifiedDateToRect(const int weekDay, const QTime &start, const QTime &end)
{
    // TOP : day of week
    //   1px = 1minute
    //   linear Monday to Sunday
    //   1 day = 1440 minutes
    // X = month + day
    // WIDTH = year
    // HEIGHT = durationInMinutes
    int day = (weekDay-1) * 1440;
    int top = start.hour() * 60 + start.minute() + day;
    int durationInMinutes = start.secsTo(end) / 60;
    return QRect(0, top, 11, durationInMinutes);
}
Example #20
0
time_t KTimeZone::toTime_t(const QDateTime &utcDateTime)
{
    static const QDate epochDate(1970,1,1);
    static const QTime epochTime(0,0,0);
    if (utcDateTime.timeSpec() != Qt::UTC)
        return InvalidTime_t;
    const qint64 days = epochDate.daysTo(utcDateTime.date());
    const qint64 secs = epochTime.secsTo(utcDateTime.time());
    const qint64 t64 = days * 86400 + secs;
    const time_t t = static_cast<time_t>(t64);
    if (static_cast<qint64>(t) != t64)
        return InvalidTime_t;
    return t;
}
Example #21
0
void Save::done()
{
	QTime tRender = QTime::currentTime();
	lwProgess->addItem(tr("Rendering finished at %1.").arg(tRender.toString("hh:mm:ss")));
	lwProgess->addItem(tr("Time elapsed: %1.%2s.").arg(tStart.secsTo(tRender)).arg(tStart.msecsTo(tRender) % 1000));
	lwProgess->scrollToBottom();
	QImage outImg = this->img->scaled(OUTSZ, OUTSZ, Qt::KeepAspectRatio);
	lOutput->setPixmap(QPixmap::fromImage(outImg));
	lOutput->resize(outImg.size());
#if 0
	QTime tEnd = QTime::currentTime();
	lwProgess->addItem(tr("Image scalling finished at %1.").arg(tEnd.toString("hh:mm:ss")));
	lwProgess->addItem(tr("Time elapsed: %1.%2s.").arg(tRender.secsTo(tEnd)).arg(tRender.msecsTo(tEnd) % 1000));
#endif
}
Example #22
0
QList< Tomahawk::result_ptr >
QtScriptResolver::parseResultVariantList( const QVariantList& reslist )
{
    QList< Tomahawk::result_ptr > results;

    foreach( const QVariant& rv, reslist )
    {
        QVariantMap m = rv.toMap();

        Tomahawk::result_ptr rp( new Tomahawk::Result() );
        Tomahawk::artist_ptr ap = Tomahawk::Artist::get( m.value( "artist" ).toString(), true );
        rp->setArtist( ap );
        rp->setAlbum( Tomahawk::Album::get( ap, m.value( "album" ).toString(), true ) );
        rp->setTrack( m.value( "track" ).toString() );
        rp->setBitrate( m.value( "bitrate" ).toUInt() );
        rp->setUrl( m.value( "url" ).toString() );
        rp->setSize( m.value( "size" ).toUInt() );
        rp->setScore( m.value( "score" ).toFloat() * ( (float)weight() / 100.0 ) );
        rp->setRID( uuid() );
        rp->setFriendlySource( name() );

        if ( m.contains( "year" ) )
        {
            QVariantMap attr;
            attr[ "releaseyear" ] = m.value( "year" );
            rp->setAttributes( attr );
        }

        rp->setDuration( m.value( "duration", 0 ).toUInt() );
        if ( rp->duration() <= 0 && m.contains( "durationString" ) )
        {
            QTime time = QTime::fromString( m.value( "durationString" ).toString(), "hh:mm:ss" );
            rp->setDuration( time.secsTo( QTime( 0, 0 ) ) * -1 );
        }

        rp->setMimetype( m.value( "mimetype" ).toString() );
        if ( rp->mimetype().isEmpty() )
        {
            rp->setMimetype( TomahawkUtils::extensionToMimetype( m.value( "extension" ).toString() ) );
            Q_ASSERT( !rp->mimetype().isEmpty() );
        }

        results << rp;
    }
 bool TriggerTimeRange::isActive(QTime startTime, QTime duration, QDateTime now,
         ExecutionState* state)
 {
     int difference = startTime.secsTo(now.time());
     if (difference < 0) {
         // start time is ahead of us today, let's check if previous date hasn't spilled over to cover current time
         if (isValueTrue(
                 getParameter(now.date().addDays(-1).toString("dddd").toStdString(), state))
                 && (difference + 24 * 60 * 60 <= getTotalSeconds(duration))) {
             return true;
         }
     } else {
         // We already passed start time, let's check if duration is long enough to cover current time
         if (isValueTrue(getParameter(now.date().toString("dddd").toStdString(), state))
                 && (difference <= getTotalSeconds(duration))) {
             return true;
         }
     }
     return false;
 }
Example #24
0
void Save::save()
{
	if (img == 0 || img->isNull())
		return;
	QString file = QFileDialog::getSaveFileName(this, "Save image to...", QString(),
						    "PNG image (*.png);;BMP image (*.bmp)");
	if (file.isEmpty())
		return;
	QTime tStart = QTime::currentTime();
	if (!img->save(file)) {
		lwProgess->addItem(tr("Save to image failed!"));
		return;
	}
	QTime tEnd = QTime::currentTime();
	lwProgess->addItem(tr("Image saving finished at %1.").arg(tEnd.toString("hh:mm:ss")));
	lwProgess->addItem(tr("Time elapsed: %1.%2s.").arg(tStart.secsTo(tEnd)).arg(tStart.msecsTo(tEnd) % 1000));
	delete img;
	img = 0;
	lwProgess->addItem(tr("Image memory freed."));
	lwProgess->scrollToBottom();
}
Example #25
0
void ImportProgressDialog::updateImportStatus(const QTime& startTime,
                                             int numReadGames, qint64 numReadBytes)
{
	int elapsed = startTime.secsTo(QTime::currentTime());
	if (elapsed == 0)
		return;

	// Update the status once a second
	if (elapsed <= m_lastUpdateSecs)
		return;

	m_lastUpdateSecs = elapsed;

	ui->m_importProgressBar->setMinimum(0);
	ui->m_importProgressBar->setMaximum(100);
	ui->m_importProgressBar->setValue(int((double(numReadBytes) / m_totalFileSize) * 100));

	int remainingSecs = (m_totalFileSize - numReadBytes) / (numReadBytes / elapsed);

	ui->m_statusLabel->setText(QString(tr("%1 games/sec - %2")).arg((int)numReadGames / elapsed)
	    .arg(humaniseTime(remainingSecs)));
}
Example #26
0
void Window::process()
{
    if(m_pTable->rowCount() < 2)
    {
        QMessageBox::warning(this, tr("Erreur"), tr("Vous devez spécifier au "
            "moins deux points."));
        return ;
    }

    // Construit la liste de points
    {
        points.clear();
        int row = 0;
        int t1, t2;
        QTime zero;
        QTimeEdit *te;
        for(; row < m_pTable->rowCount(); row++)
        {
            te = qobject_cast<QTimeEdit*>(
                m_pTable->cellWidget(row, 0));
            t1 = zero.secsTo(te->time());
            te = qobject_cast<QTimeEdit*>(
                m_pTable->cellWidget(row, 1));
            t2 = zero.secsTo(te->time());
            points.push_back(std::pair<int, int>(t1, t2));
        }
        std::sort(points.begin(), points.end(), comp);
    }

    // Vérifie que les noms de fichier ont été donnés
    if( (m_pSourceFile->path() == "")
     || (m_pTargetFile->path() == "") )
    {
        QMessageBox::warning(this, tr("Erreur"), tr("Vous devez spécifier les "
            "fichiers de départ et d'arrivée..."));
        return;
    }

    // Ouvre les fichiers
    QFile in(m_pSourceFile->path());
    if(!in.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QMessageBox::critical(this, tr("Erreur"), tr("Impossible d'ouvrir le "
            "fichier de départ (%1) !").arg(m_pSourceFile->path()));
        return ;
    }
    QFile out(m_pTargetFile->path());
    if(!out.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QMessageBox::critical(this, tr("Erreur"), tr("Impossible d'ouvrir le "
            "fichier cible (%1) !").arg(m_pTargetFile->path()));
        in.close();
        return ;
    }

    static char buffer[1024];

    // Indique le numéro de la ligne qui sera lue le coup d'après
    // 1 : première ligne, le numéro du sous-titre
    // 2 : deuxième ligne, le temps. Exemple : 00:00:35,463 --> 00:00:38,245
    // 3 et plus : lignes suivantes, à recopier sans changement
    int state = 1;
    int line = 1;
    double u; // unused
    while(in.readLine(buffer, 1024) > 0)
    {
        QString str = buffer;
        str.resize(str.size() - 1); // supprime le \n
        if(str == "")
            state = 1;
        else if(state == 1)
            state = 2;
        else if(state == 2)
        {
            QRegExp rx("^([0-9]{2}):([0-9]{2}):([0-9]{2}),([0-9]{2,3})"
                " --> "
                "([0-9]{2}):([0-9]{2}):([0-9]{2}),([0-9]{2,3})");
            if(!rx.exactMatch(str))
            {
                QMessageBox::critical(this, tr("Erreur de syntaxe"),
                    tr("Erreur de syntaxe à la ligne %1").arg(line));
                return ;
            }
            double t1 = rx.cap(1).toInt()*3600.0 + rx.cap(2).toInt()*60.0
                + rx.cap(3).toInt() + rx.cap(4).toInt()*0.001;
            double t2 = rx.cap(5).toInt()*3600.0 + rx.cap(6).toInt()*60.0
                + rx.cap(7).toInt() + rx.cap(8).toInt()*0.001;
            t1 = shift(t1); t2 = shift(t2);
            int ti1 = (int)t1, ti2 = (int)t2;
            std::ostringstream oss;
            oss << std::setfill('0') << std::setw(2) << ti1/3600 << ":"
                << std::setw(2) << (ti1%3600)/60 << ":" << std::setw(2)
                << ti1%60 << "," << std::setw(3) << (int)(modf(t1, &u)*1000.0)
                << " --> " << std::setw(2) << ti2/3600 << ":"
                << std::setw(2) << (ti2%3600)/60 << ":" << std::setw(2)
                << ti2%60 << "," << std::setw(3) << (int)(modf(t2, &u)*1000.0);
            str = QString::fromStdString(oss.str());
            state = 3;
        }
        out.write(str.toAscii());
        out.write("\n");
        line++;
    }

    out.close();
    in.close();
}
Example #27
0
void Veturi::paivitaJkvTiedot()
{
    jkvTiedot_.clear();
    if( !aktiivinenAkseli() || !aktiivinenAkseli()->kiskolla())
        return;

    qreal matka = 0;
    QPointF liitosSijainti;

    RataKisko* kiskolla = aktiivinenAkseli()->kiskolla();

    if( aktiivinenAkseli()->suuntaKiskolla() == RaiteenPaa::Etelaan )
    {
        matka = aktiivinenAkseli()->sijaintiKiskolla();
        liitosSijainti = kiskolla->etelainen();
    }
    else
    {
        matka = kiskolla->pituus() - aktiivinenAkseli()->sijaintiKiskolla();
        liitosSijainti = kiskolla->pohjoinen();
    }

    RataKisko* seuraavaKisko = 0;
    while(1)
    {
        // Selvitetään naapuri, jotta tiedetään sen sn.
        seuraavaKisko = kiskolla->haeAktiivinenNaapuri(liitosSijainti);

        RaiteenPaa::Opaste opaste=RaiteenPaa::Tyhja;
        int nopeusRajoitus = 0;

        if( seuraavaKisko)
        {
            nopeusRajoitus = seuraavaKisko->sn();

            // Varatun raiteen kulkutien viimeisellä raiteella sn 20
            if( seuraavaKisko->raide()->kulkutieTyyppi() == RataRaide::Varattukulkutie&&
                    seuraavaKisko->raide()->kulkutienRaide()->kulkutie()->maaliRaide() ==
                    seuraavaKisko->raide() )
            {
                opaste = RaiteenPaa::VarattuRaide;
                if( nopeusRajoitus > 20 )
                    nopeusRajoitus = 20;
            }
        }
        else
            opaste = RaiteenPaa::SeisLevy;

        if( kiskolla->opastinSijainnissa(liitosSijainti))
            opaste = kiskolla->opastinSijainnissa(liitosSijainti)->opaste();

        if( opaste == RaiteenPaa::AjaVarovasti && nopeusRajoitus > 35)
            nopeusRajoitus = 35;    // Vaihtotyöalueella max. nopeusrajoitus 35 km/h


        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //  Ehdot junan pysähtymiselle aikataulun mukaisesti

        int pysahdylaiturille = 0;      // Kuinka monta sekuntia pysähdystä on jäljellä?
                                        // -1 tarkoittaa, että ollaan saavuttu määräasemalle

        QString raidetunnus = kiskolla->raide()->raidetunnusLiikennepaikalla();

        if( reitti_.contains( raidetunnus ))  // Tämä raide on mainittu aikataulussa
        {
            int pysahdysAjasta = 0;
            int pysahdysLahtoajasta = 0;
            QDateTime lahtoaikaPysahdyksesta;

            if( reitti_.value( raidetunnus ).tapahtumaTyyppi() == ReittiTieto::Saapuu &&
                    ( opaste != RaiteenPaa::Tyhja || kiskolla->laituri() != Kisko::LaituriEi )     )
            {
                // Saavuttu määräasemalle (joko laituriin tai opastimen eteen
                pysahdylaiturille = -1;
            }
            else
            {
                // Selvitetään, pysähdysajan mukainen pysähdys. Se tehdään VAIN laiturille, eli tavarajunat kulkevat
                // vain aikataulunsa mukaisesti
                if( kiskolla->laituri() != Kisko::LaituriEi && reitti_.value(raidetunnus).pysahtyy())
                {
                    if( kiskolla == aktiivinenAkseli()->kiskolla()   // Ollaan tällä kiskolla
                            && pysahtyi_.isValid()                   // Ollaan pysähdyksissä
                            && pysahtyiKiskolle_ != kiskolla)       // Ei vielä olla pysähdytty tälle kiskolle
                    {
                        // Pysähdys on jo menossa
                        // Määritellään pysähdyksen loppuaika, ja lasketaan erotus nykyhetkestä
                        lahtoaikaPysahdyksesta = pysahtyi_.addSecs( reitti_.value(raidetunnus).pysahtyy() );
                        pysahdysAjasta = RatapihaIkkuna::getInstance()->skene()->simulaatioAika().secsTo( lahtoaikaPysahdyksesta );


                        if( pysahdysAjasta < 0 || pysahdysAjasta > 1800 )
                            pysahdysAjasta = 0;
                    }
                    else if( pysahtyiKiskolle_ != kiskolla )
                    {
                        // Pysähdys on vielä edessäpäin, eli tässä ilmoitetaan koko odotettavissa oleva pysähdysaika
                        pysahdysAjasta = reitti_.value( raidetunnus).pysahtyy();
                    }
                }

                // Pysähdys aikataulun mukaan tehdään laiturille (ja opastimen eteen)
                if( (opaste != RaiteenPaa::Tyhja || kiskolla->laituri() != Kisko::LaituriEi)
                        && reitti_.value(raidetunnus).tapahtumaTyyppi() != ReittiTieto::Ohittaa )
                {
                    // Lasketaan pysähdys aikataulun mukaan
                    QTime aikataulunlahtoaika = reitti_.value( raidetunnus).lahtoAika();
                    if( aikataulunlahtoaika.isValid() )
                    {
                        // Aikataulussa on lähtöaika
                        pysahdysLahtoajasta = RatapihaIkkuna::getInstance()->skene()->simulaatioAika().time().secsTo( aikataulunlahtoaika );

                        if( pysahdysLahtoajasta < 0)
                        {
                            if( pysahdysLahtoajasta < -84600)   // Keskiyön ylitys: varaudutaan puolen tunnin
                                pysahdysLahtoajasta += 86400;
                            else if( pysahdysAjasta > 1800 )  // Samoin tähän suuntaan...
                                pysahdysLahtoajasta = 0;
                            else
                                pysahdysLahtoajasta = 0;
                        }


                        // Myöhästyminen asemalla ollessa voidaan laskea siitä, kuinka paljon
                        // pysähdysajasta laskettu lähtöaika on aikataulun mukaista
                        // lähtöaikaa suurempi
                        if( lahtoaikaPysahdyksesta.isValid() )
                        {
                            int myohassa = aikataulunlahtoaika.secsTo(lahtoaikaPysahdyksesta.time());
                            if( myohassa < 1)
                                myohassa_ = 0;
                            else
                                myohassa_ = myohassa;
                        }

                        // Jos kello on jo ohittanut aikataulun mukaisen lähtöajan, saattaa myöhässä oleminen
                        // olla vielä tätäkin suurempi ...
                        int myohastysTassa = aikataulunlahtoaika.secsTo( RatapihaIkkuna::getInstance()->simulaatioAika().time() );
                        if( myohastysTassa > 10 && myohastysTassa < 60 * 60 * 12 && myohastysTassa > myohassa_)
                        {
                            myohassa_ = myohastysTassa;
                        }
                    }


                }

                // Nyt on laskettu kaksi pysähdysaikaa, joista pidempi on voimassa
                pysahdylaiturille = qMax( pysahdysAjasta, pysahdysLahtoajasta);

                // Ei kuitenkaan toisteta pysähdystä sekä laiturille että opastimelle
                if( !jkvTiedot_.empty() && jkvTiedot_.last().kisko() == kiskolla
                        && jkvTiedot_.last().pysahdyLaiturille() == pysahdylaiturille )
                    pysahdylaiturille = 0;

                // Aikataulun mukaiselle lähtöraiteelle annetaan erillinen lähtöopaste
                if( reitti_.value(raidetunnus).tapahtumaTyyppi() == ReittiTieto::Lahtee)
                {
                    if( pysahdylaiturille > 0)
                    {
                        // Muodostetaan oma Odota lähtölupaa - opasteensa
                        jkvTiedot_.append( JkvOpaste(kiskolla, RaiteenPaa::OdotaLahtolupaa, 0.0,
                                                     0, pysahdylaiturille, false, hidastuvuus()) );
                        pysahdylaiturille = 0;
                    }
                    else
                    {
                        // Näytetään Lähtölupa-opaste
                        jkvTiedot_.append( JkvOpaste(kiskolla, RaiteenPaa::Lahtolupa, 0.0,
                                                     enimmaisNopeus(), 0, false, hidastuvuus()));
                    }
                }
            }

        }
        // Aikataulun mukainen pysähdys selvitetty, ja muuttujassa pysahdylaiturille
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////7

        // Matkaa vähennetään, jotta suuri simulaationopeus ei aiheuta läpiajoa
        matka -= nopeusMs() * RatapihaIkkuna::getInstance()->skene()->nopeutusKerroin() / 5;

        JkvOpaste jkvopaste(kiskolla, opaste, matka, nopeusRajoitus, pysahdylaiturille,
                            jkvTila() != JunaJkv, hidastuvuus()) ;

        jkvTiedot_.append( jkvopaste );

        // Jos nopeus menee nollille, ollaan valmiita
        // Kuitenkin laiturilta näytetään eteenpäin
        // siksi tarkistetaan, olisiko joku ajon salliva opaste
        if( !jkvopaste.sn() && jkvopaste.opaste()!=RaiteenPaa::Aja
                && jkvopaste.opaste() != RaiteenPaa::AjaSn && jkvopaste.opaste() != RaiteenPaa::Tyhja
                && jkvopaste.opaste() != RaiteenPaa::NopeusRajoitus )
            break;

        if( !seuraavaKisko)
            break;

        // Sitten siirrytään seuraavaan päähän
        matka += seuraavaKisko->pituus();

        if( liitosSijainti == seuraavaKisko->etelainen())
            liitosSijainti = seuraavaKisko->pohjoinen();
        else
            liitosSijainti = seuraavaKisko->etelainen();
        kiskolla = seuraavaKisko;
    }

    // Listan yksinkertaistaminen siten, että yksinkertaistetaan eteenpäin...
    for( int i = jkvTiedot_.count() - 1;  i > 0 ; i--)
    {
        qreal etaisyys = jkvTiedot_.at(i).matka() - jkvTiedot_.at(i-1).matka();
        int tamaSn = jkvTiedot_.at(i).sn() ;
        int edellinenSn = jkvTiedot_.at(i-1).sn();

        // Jos etäisyyttä on enintään 300m, yksinkertaistetaan nopeusrajoitus edelliseen

        if( jkvTiedot_.at(i).opaste() == RaiteenPaa::Tyhja && !jkvTiedot_.at(i).pysahdyLaiturille() )
        {
            if( tamaSn != edellinenSn )
            {
                // On nopeusrajoitus, jota pitää käsitellä etäisyysehdolla
                if( tamaSn < edellinenSn && etaisyys < 300)
                {
                    // YHDISTETÄÄN!!!
                    jkvTiedot_[i-1].asetaYhdistettySn( tamaSn );
                }
                else
                {
                    // On itsenäinen nopeusrajoitus
                    // Ei kuitenkaan näytetä, jos kohta (300m) tulossa alhaisempi,
                    // tai (500m) nolla
                    if( !( (tamaSn > edellinenSn) &&
                            (etaisyys < 300 || ( edellinenSn == 0 && etaisyys < 500)   )))
                        jkvTiedot_[i].asetaNopeusrajoitukseksi();
                }
            }
        }
    }
    // Nyt lista "yksinkertaistettu"

    // Nyt on jkv-tiedot listassa. Sitten pitäisi valita pienin nopeus jkv-nopeudeksi
    int jkvnopeus = enimmaisNopeus();


    foreach( JkvOpaste opaste, jkvTiedot_)
        if( opaste.jkvNopeus() < jkvnopeus)
            jkvnopeus = opaste.jkvNopeus();

    // Vaihtotyön sn rajoitetaan 50 km/h
    if( jkvTila()==VaihtoJkv && jkvnopeus > 50 )
        jkvnopeus = 50;
    // Jos ollaan vaihtokulkutiellä, niin max nopeus 35 km/h
    if( jkvTila()==VaihtoJkv &&  aktiivinenAkseli()->kiskolla()->raide()->kulkutieTyyppi() == RataRaide::Vaihtokulkutie && jkvnopeus > 20)
        jkvnopeus = 35;
    // Varatun raiteen kulkutien viimeisellä raiteella sn 20
    if(  aktiivinenAkseli()->kiskolla()->raide()->kulkutieTyyppi() == RataRaide::Varattukulkutie &&
            aktiivinenAkseli()->kiskolla()->raide()->kulkutienRaide()->kulkutie()->maaliRaide() ==
            aktiivinenAkseli()->kiskolla()->raide()
         && jkvnopeus > 20)
        jkvnopeus = 20;


    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Tarkistetaan vielä raiteen voimassaoleva nopeusrajoitus, josta voi myös
    // tulla jkv-nopeus

    int nopeusrajoitus = aktiivinenAkseli()->kiskolla()->sn();
     QList<QPair<qreal,int> >::iterator i = nopeusRajoitukset_.begin();
     while( i != nopeusRajoitukset_.end())
     {

         // Onko nopeusrajoitus jo umpeutunut
         // Lisätään junan pituudella ja 10 metrin varalla

         if( (*i).first + junaPituus() + 10 < matkaMittari() )
         {
             // on umpeutunut
             // Tyhjennetään listaa loppuun
             nopeusRajoitukset_.erase(i--, nopeusRajoitukset_.end()); // ++i --> i--
             break;
         }
         // Pienin nopeusrajoitus käyttöön!!
         if( (*i).second < nopeusrajoitus )
             nopeusrajoitus = (*i).second;

         ++i;
     }
    nopeusRajoitus_ = nopeusrajoitus;

    // Ellei jkv käytössä, jkvnopeus aina 50
    if( jkvTila() == EiJkv )
    {
        jkvNopeus_ = 50;
        return;
    }

    // Muun kuin matkustajajunan (Pikajuna, Henkilöjuna, S=Pendolino)
    // enimmäisnopeus on 100 km/h. ( M - nopea siirto, Muu )
    if( !junaNumero().startsWith('P') && !junaNumero().startsWith('H')
            && !junaNumero().startsWith('S') && !junaNumero().startsWith('M')  && jkvnopeus > 100)
        jkvnopeus = 100;

    // Rajoittava nopeus:
    if( nopeusrajoitus < jkvnopeus )
        jkvNopeus_ = nopeusrajoitus;
    else
        jkvNopeus_ = jkvnopeus;


}
void WorkThread::onSendSysBroadcast()
{
    QTime t;
    double dist  = 0;
    ResultSet& _lineInfoSet = GlobalInfo::getInstance()->lineInfoSet;
    //GlobalInfo::getInstance()->debugStack.appendStack(QThread::currentThreadId(),"ready entry onSendSysBroadcast");
//    qDebug("entry file:%s line:%d func:%s thread:%ld",__FILE__,__LINE__,__FUNCTION__,QThread::currentThreadId());
    ResultSet lineInfos = GlobalInfo::getInstance()->lineInfoSet;
    ZTPprotocol ztp;
    ztp.addPara("T","G_INFO");    //消息类型
    ztp.addPara("TrainNum",QString::number(GlobalInfo::getInstance()->train_id));    //发送者身份标识
    ztp.addPara("DateTime",rmc.dateTime.toString("yy-MM-dd hh:mm:ss"));
    if(rmc.speed < 2.5)
            ztp.addPara("Speed",QString::number(0));
    else
        ztp.addPara("Speed",QString::number(rmc.speed));

    int curIndex = GlobalInfo::getInstance()->curStationIndex;
    if(GlobalInfo::getInstance()->lineInfoSet.count() == 0)
    {
        QString startStationEN = "START";
        QString startStationThai = QString::fromUtf8("เริ่มต้นที่สถานี");
        QString endStationEN = "END";
        QString endStationThai = QString::fromUtf8("สุดท้ายยืน");

        ztp.addPara("CurrentStationEn","--");
        ztp.addPara("CurrentStationTh","--");
        ztp.addPara("StartStation",startStationEN);//始发站
        ztp.addPara("StartStation_th",startStationThai);
        ztp.addPara("EndStation",endStationEN);//终点站
        ztp.addPara("EndStation_th",endStationThai);
        ztp.addPara("NextStation","--");
        ztp.addPara("NextStation_th","--");
        ztp.addPara("NextStationTime","--");
        ztp.addPara("PreStation","--");
        ztp.addPara("PreStation_th","--");
        goto label;
    }

    if(curIndex < 0)
        return;
    //仅当当前位置在当前站点500米范围内时才显示当前站。
    dist = BhcTool::geogToDistance(rmc.longitude_nh,rmc.latitude_nh,_lineInfoSet[curIndex].getParaDouble("lng"),_lineInfoSet[curIndex].getParaDouble("lat"));
    if( dist < 0.5 )
    {
        t = QTime::fromString(_lineInfoSet[curIndex].getPara("start_time"),"hh:mm");
        if(t.isValid())
        {
            int secs_off = t.secsTo(QTime::currentTime());
            if(secs_off/60/60 < 16)//如果当前时间比起时刻表提前超过16小时,则认为是时间回滚,需要时刻表时间+1天
            {
                secs_off += 60*60*24;
            }
            if(secs_off/60 > 1) //迟出发1分钟以上
                GlobalInfo::getInstance()->secs_off = secs_off;
        }
        else
        {
            t = QTime::fromString(_lineInfoSet[curIndex].getPara("arrive_time"),"hh:mm");
            if(t.isValid())
            {

                int secs_off = t.secsTo(QTime::currentTime());
                if(secs_off/60/60 < 16)//如果当前时间比起时刻表提前超过16小时,则认为是时间回滚,需要时刻表时间+1天
                {
                    secs_off += 60*60*24;
                }
                if(secs_off/60 > 10) //呆在本站1分钟以上
                    GlobalInfo::getInstance()->secs_off = secs_off;
            }
        }
        ztp.addPara("SECS_OFF",QString::number(GlobalInfo::getInstance()->secs_off));
        ztp.addPara("CurrentStationEn",lineInfos[curIndex].getPara("station_name_en"));
        ztp.addPara("CurrentStationTh",lineInfos[curIndex].getPara("station_name_th"));
    }
    else
    {
//        curStationEmpty = true;
//        qDebug()<<"xxxxxxxxxxxxxxxxxxxx  "<<rmc.longitude_nh<<"  "<<rmc.latitude_nh<<"  "<<dist;
        ztp.addPara("CurrentStationEn","--");
        ztp.addPara("CurrentStationTh","--");
    }
    ztp.addPara("ArriveTime",lineInfos[GlobalInfo::getInstance()->lineInfoSet.count()-1].getPara("arrive_time"));//终点站到站时间
    t =QTime::fromString(lineInfos[GlobalInfo::getInstance()->lineInfoSet.count()-1].getPara("arrive_time"),"hh:mm");
    if(t.isValid())//如果满足时间条件 则覆盖ArriveTime
    {
        t = t.addSecs(GlobalInfo::getInstance()->secs_off);
        ztp.addPara("ArriveTime",t.toString("hh:mm"));
    }
    //
    ztp.addPara("StartStation",lineInfos[0].getPara("station_name_en"));//始发站
    ztp.addPara("StartStation_th",QString::fromUtf8(lineInfos[0].getPara("station_name_th").toUtf8()));
    ztp.addPara("EndStation",lineInfos[GlobalInfo::getInstance()->lineInfoSet.count()-1].getPara("station_name_en"));//终点站
    ztp.addPara("EndStation_th",QString::fromUtf8(lineInfos[GlobalInfo::getInstance()->lineInfoSet.count()-1].getPara("station_name_th").toUtf8()));


//    QString str =  ztp.getPara("StartStation_th");
//    str = str.toUtf8();
//    //QString str =  "นึ่รู้รู้รู้";
//    QByteArray bytes = ZTools::str2unicode(str);
//    //qDebug()<<str;
//    for(int i = 0; i< bytes.length();i++)
//    {
//        qDebug("%d : %x",i,bytes.data()[i]);
//    }


    if(curIndex == 0)
    {
        ztp.addPara("PreStation","--");
        ztp.addPara("PreStation_th","--");
        if(lineInfos.count() > 1)
        {
            ztp.addPara("NextStation",lineInfos[curIndex+1].getPara("station_name_en"));
            ztp.addPara("NextStation_th",lineInfos[curIndex+1].getPara("station_name_th"));
            ztp.addPara("NextStationTime",lineInfos[curIndex+1].getPara("arrive_time"));
            QTime t =QTime::fromString(lineInfos[curIndex+1].getPara("arrive_time"),"hh:mm");
            if(t.isValid())
            {
                t = t.addSecs(GlobalInfo::getInstance()->secs_off);
                ztp.addPara("NextStationTime",t.toString("hh:mm"));
            }

        }
        else
        {
            ztp.addPara("NextStation","--");
            ztp.addPara("NextStation_th","--");
            ztp.addPara("NextStationTime","--");
        }
    }
    else if(curIndex < GlobalInfo::getInstance()->lineInfoSet.count() - 1)
    {
        ztp.addPara("PreStation",lineInfos[curIndex-1].getPara("station_name_en"));
        ztp.addPara("PreStation_th",lineInfos[curIndex-1].getPara("station_name_th"));
        if(lineInfos.count() > 1)
        {
            ztp.addPara("NextStation",lineInfos[curIndex+1].getPara("station_name_en"));
            ztp.addPara("NextStation_th",lineInfos[curIndex+1].getPara("station_name_th"));
            ztp.addPara("NextStationTime",lineInfos[curIndex+1].getPara("arrive_time"));
            QTime t =QTime::fromString(lineInfos[curIndex+1].getPara("arrive_time"),"hh:mm");
            if(t.isValid())
            {
                t = t.addSecs(GlobalInfo::getInstance()->secs_off);
                ztp.addPara("NextStationTime",t.toString("hh:mm"));
            }
        }
        else
        {
            ztp.addPara("NextStation","--");
            ztp.addPara("NextStation_th","--");
            ztp.addPara("NextStationTime","--");
        }

    }
    else
    {
        ztp.addPara("PreStation",lineInfos[curIndex-1].getPara("station_name_en"));
        ztp.addPara("PreStation_th",lineInfos[curIndex-1].getPara("station_name_th"));
        ztp.addPara("NextStation","--");
        ztp.addPara("NextStation_th","--");
        ztp.addPara("NextStationTime","--");
    }
label:
    ztpm->SendOneZtp(ztp,QHostAddress(BROADCAST_IP),8311);
    //GlobalInfo::getInstance()->debugStack.appendStack(QThread::currentThreadId(),"leave onSendSysBroadcast");

}
Example #29
0
void ServerThread::maybeSendBacktrace()
{
    QFile coreFile("core");

    if (!coreFile.exists()) {
        qDebug() << "No core dump found";
        return;
    }

    char *receiver = getenv("CRASH_REPORT_RECEIVER");
    if (!receiver) {
        qDebug() << "CRASH_REPORT_RECEIVER environment variable not set";
        return;
    }

    QProcess gdb;
    gdb.start(QString("gdb %1 core -q -x print-backtrace.gdb")
            .arg(mExecutable));

    if (!gdb.waitForStarted()) {
        qDebug() << "Failed to launch gdb";
        coreFile.remove();
        return;
    }

    if (!gdb.waitForFinished()) {
        qDebug() << "gdb process is not finishing, killing";
        gdb.kill();
        coreFile.remove();
        return;
    }

    coreFile.remove();

    const QByteArray gdbOutput = gdb.readAllStandardOutput();
    qDebug() << "gdb output:\n" << gdbOutput.constData();

    QTime current = QTime::currentTime();
    if (!mLastCrash.isNull() && mLastCrash.secsTo(current) < 60 * 10) {
        qDebug() << "Sent a crash report less than 10 minutes ago, "
            "dropping this one";
        return;
    }

    mLastCrash = current;

    QProcess mail;
    mail.start(QString("mail -s \"Crash report for %1\" %2")
            .arg(mExecutable, QString::fromLocal8Bit(receiver)));

    if (!mail.waitForStarted()) {
        qDebug() << "Failed to launch mail";
        return;
    }

    mail.write(gdbOutput);
    mail.closeWriteChannel();

    if (mail.waitForFinished()) {
        qDebug() << "Crash report sent to" << receiver;
    } else {
        qDebug() << "mail process is not finishing, killing";
        mail.kill();
    }
}
Example #30
0
int Helper::GetDuration(QTime from, QTime to)
{
    int secs = from.secsTo(to);
    return secs;
}