FlowField_sV* FlowSourceOpenCV_sV::buildFlow(uint leftFrame, uint rightFrame, FrameSize frameSize) throw(FlowBuildingError)
{
#if CV_MAJOR_VERSION == 2
#ifdef HAVE_OPENCV_OCL
    if (ocl_device_index >= 0) {
        setupOclDevice();
    }
#endif
#endif
    QString flowFileName(flowPath(leftFrame, rightFrame, frameSize));

    /// \todo Check if size is equal
    if (!QFile(flowFileName).exists()) {
        QTime time;
        time.start();
        QString prevpath = project()->frameSource()->framePath(leftFrame, frameSize);
        QString path = project()->frameSource()->framePath(rightFrame, frameSize);

        qDebug() << "Building flow for left frame " << leftFrame << " to right frame " << rightFrame << "; Size: " << frameSize;

        // check if file have been generated !
        //TODO: maybe better error handling ?
        if (!QFile(prevpath).exists())
            throw FlowBuildingError(QString("Could not read image " + prevpath));

        if (!QFile(path).exists())
            throw FlowBuildingError(QString("Could not read image " + path));

        cv::Mat prevgray, gray;
        prevgray = cv::imread(prevpath.toStdString(), CV_LOAD_IMAGE_ANYDEPTH);
        gray = cv::imread(path.toStdString(), CV_LOAD_IMAGE_ANYDEPTH);
#if CV_MAJOR_VERSION == 3
        cv::UMat uprevgray, ugray;
        prevgray.copyTo(uprevgray);
        gray.copyTo(ugray);
#endif

        {
            if (!prevgray.empty()) {
#if CV_MAJOR_VERSION == 3
                buildFlowOpenCV_3(uprevgray, ugray, flowFileName.toStdString());
#else
#ifdef HAVE_OPENCV_OCL
                if (ocl_device_index >= 0) {
                    buildFlowOpenCV_OCL(prevgray, gray, flowFileName.toStdString());
                } else {
                    buildFlowOpenCV_CPU(prevgray, gray, flowFileName.toStdString());
                }
#else
                buildFlowOpenCV_CPU(prevgray, gray, flowFileName.toStdString());
#endif
#endif
            } else {
                qDebug() << "imread: Could not read image " << prevpath;
                throw FlowBuildingError(QString("imread: Could not read image " + prevpath));
            }
        }
        qDebug() << "Optical flow built for " << flowFileName << " in " << time.elapsed() << " ms.";
    } else {
        qDebug().nospace() << "Re-using existing flow image for left frame " << leftFrame << " to right frame " << rightFrame << ": " << flowFileName;
    }

    try {
        return FlowRW_sV::load(flowFileName.toStdString());
    } catch (FlowRW_sV::FlowRWError &err) {
        throw FlowBuildingError(err.message.c_str());
    }
}
Example #2
0
void XSPFParser::load() {
	QTime timeElapsed;
	timeElapsed.start();

	_stop = false;

	QList<MediaInfo> files;

	qDebug() << __FUNCTION__ << "Playlist:" << _filename;

	QFile file(_filename);
	if (file.open(QIODevice::ReadOnly)) {
		MediaInfo mediaInfo;

		QXmlStreamReader xml(&file);
		while (!xml.atEnd() && !_stop) {
			xml.readNext();

			switch (xml.tokenType()) {

			case QXmlStreamReader::StartElement: {
				QString element(xml.name().toString());

				if (element == XSPF_TRACK) {
					readTrack(xml, mediaInfo);

					if (!mediaInfo.fileName().isEmpty()) {
						//Add file to the list of files
						files << mediaInfo;

						//Clear the MediaInfo
						mediaInfo.clear();

						if (files.size() > FILES_FOUND_LIMIT) {
							//Emits the signal every FILES_FOUND_LIMIT files found
							emit filesFound(files);
							files.clear();
						}
					}
				}

				//Otherwise won't read the track end element
				break;
			}

			}
		}

		if (xml.hasError()) {
			qCritical() << __FUNCTION__ << "Error:" << xml.errorString()
				<< "line:" << xml.lineNumber()
				<< "column:" << xml.columnNumber();
		}
	}

	file.close();

	if (!files.isEmpty()) {
		//Emits the signal for the remaining files found (< FILES_FOUND_LIMIT)
		emit filesFound(files);
	}

	//Emits the last signal
	emit finished(timeElapsed.elapsed());
}
Example #3
0
void QgsPalLabeling::drawLabeling( QgsRenderContext& context )
{
  Q_ASSERT( mMapRenderer != NULL );
  QPainter* painter = context.painter();
  QgsRectangle extent = context.extent();

  if ( mLabelSearchTree )
  {
    mLabelSearchTree->clear();
  }

  QTime t;
  t.start();

  // do the labeling itself
  double scale = mMapRenderer->scale(); // scale denominator
  QgsRectangle r = extent;
  double bbox[] = { r.xMinimum(), r.yMinimum(), r.xMaximum(), r.yMaximum() };

  std::list<LabelPosition*>* labels;
  pal::Problem* problem;
  try
  {
    problem = mPal->extractProblem( scale, bbox );
  }
  catch ( std::exception& e )
  {
    Q_UNUSED( e );
    QgsDebugMsg( "PAL EXCEPTION :-( " + QString::fromLatin1( e.what() ) );
    //mActiveLayers.clear(); // clean up
    return;
  }

  const QgsMapToPixel* xform = mMapRenderer->coordinateTransform();

  // draw rectangles with all candidates
  // this is done before actual solution of the problem
  // before number of candidates gets reduced
  mCandidates.clear();
  if ( mShowingCandidates && problem )
  {
    painter->setPen( QColor( 0, 0, 0, 64 ) );
    painter->setBrush( Qt::NoBrush );
    for ( int i = 0; i < problem->getNumFeatures(); i++ )
    {
      for ( int j = 0; j < problem->getFeatureCandidateCount( i ); j++ )
      {
        pal::LabelPosition* lp = problem->getFeatureCandidate( i, j );

        drawLabelCandidateRect( lp, painter, xform );
      }
    }
  }

  // find the solution
  labels = mPal->solveProblem( problem, mShowingAllLabels );

  QgsDebugMsg( QString( "LABELING work:  %1 ms ... labels# %2" ).arg( t.elapsed() ).arg( labels->size() ) );
  t.restart();

  painter->setRenderHint( QPainter::Antialiasing );

  // draw the labels
  std::list<LabelPosition*>::iterator it = labels->begin();
  for ( ; it != labels->end(); ++it )
  {
    QgsPalGeometry* palGeometry = dynamic_cast< QgsPalGeometry* >(( *it )->getFeaturePart()->getUserGeometry() );
    if ( !palGeometry )
    {
      continue;
    }

    //layer names
    QString layerNameUtf8 = QString::fromUtf8(( *it )->getLayerName() );
    if ( palGeometry->isDiagram() )
    {
      //render diagram
      QHash<QgsVectorLayer*, QgsDiagramLayerSettings>::iterator dit = mActiveDiagramLayers.begin();
      for ( dit = mActiveDiagramLayers.begin(); dit != mActiveDiagramLayers.end(); ++dit )
      {
        if ( dit.key() && dit.key()->id().append( "d" ) == layerNameUtf8 )
        {
          QgsPoint outPt = xform->transform(( *it )->getX(), ( *it )->getY() );
          dit.value().renderer->renderDiagram( palGeometry->diagramAttributes(), context, QPointF( outPt.x(), outPt.y() ) );
        }
      }

      //insert into label search tree to manipulate position interactively
      if ( mLabelSearchTree )
      {
        //for diagrams, remove the additional 'd' at the end of the layer id
        QString layerId = layerNameUtf8;
        layerId.chop( 1 );
        mLabelSearchTree->insertLabel( *it,  QString( palGeometry->strId() ).toInt(), layerId, true );
      }
      continue;
    }

    const QgsPalLayerSettings& lyr = layer( layerNameUtf8 );
    QFont fontForLabel = lyr.textFont;
    QColor fontColor = lyr.textColor;
    double bufferSize = lyr.bufferSize;
    QColor bufferColor = lyr.bufferColor;

    //apply data defined settings for the label
    //font size
    QVariant dataDefinedSize = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::Size );
    if ( dataDefinedSize.isValid() )
    {
      fontForLabel.setPixelSize( lyr.sizeToPixel( dataDefinedSize.toDouble(), context ) );
    }
    //font color
    QVariant dataDefinedColor = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::Color );
    if ( dataDefinedColor.isValid() )
    {
      fontColor.setNamedColor( dataDefinedColor.toString() );
      if ( !fontColor.isValid() )
      {
        fontColor = lyr.textColor;
      }
    }
    //font bold
    QVariant dataDefinedBold = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::Bold );
    if ( dataDefinedBold.isValid() )
    {
      fontForLabel.setBold(( bool )dataDefinedBold.toInt() );
    }
    //font italic
    QVariant dataDefinedItalic = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::Italic );
    if ( dataDefinedItalic.isValid() )
    {
      fontForLabel.setItalic(( bool ) dataDefinedItalic.toInt() );
    }
    //font underline
    QVariant dataDefinedUnderline = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::Underline );
    if ( dataDefinedUnderline.isValid() )
    {
      fontForLabel.setUnderline(( bool ) dataDefinedUnderline.toInt() );
    }
    //font strikeout
    QVariant dataDefinedStrikeout = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::Strikeout );
    if ( dataDefinedStrikeout.isValid() )
    {
      fontForLabel.setStrikeOut(( bool ) dataDefinedStrikeout.toInt() );
    }
    //font family
    QVariant dataDefinedFontFamily = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::Family );
    if ( dataDefinedFontFamily.isValid() )
    {
      fontForLabel.setFamily( dataDefinedFontFamily.toString() );
    }
    //buffer size
    QVariant dataDefinedBufferSize = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::BufferSize );
    if ( dataDefinedBufferSize.isValid() )
    {
      bufferSize = dataDefinedBufferSize.toDouble();
    }

    //buffer color
    QVariant dataDefinedBufferColor = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::BufferColor );
    if ( dataDefinedBufferColor.isValid() )
    {
      bufferColor.setNamedColor( dataDefinedBufferColor.toString() );
      if ( !bufferColor.isValid() )
      {
        bufferColor = lyr.bufferColor;
      }
    }

    if ( lyr.bufferSize != 0 )
      drawLabel( *it, painter, fontForLabel, fontColor, xform, bufferSize, bufferColor, true );

    drawLabel( *it, painter, fontForLabel, fontColor, xform );

    if ( mLabelSearchTree )
    {
      mLabelSearchTree->insertLabel( *it,  QString( palGeometry->strId() ).toInt(), ( *it )->getLayerName() );
    }
  }

  QgsDebugMsg( QString( "LABELING draw:  %1 ms" ).arg( t.elapsed() ) );

  delete problem;
  delete labels;

  // delete all allocated geometries for features
  QHash<QgsVectorLayer*, QgsPalLayerSettings>::iterator lit;
  for ( lit = mActiveLayers.begin(); lit != mActiveLayers.end(); ++lit )
  {
    QgsPalLayerSettings& lyr = lit.value();
    for ( QList<QgsPalGeometry*>::iterator git = lyr.geometries.begin(); git != lyr.geometries.end(); ++git )
      delete *git;
    lyr.geometries.clear();
  }

  //delete all allocated geometries for diagrams
  QHash<QgsVectorLayer*, QgsDiagramLayerSettings>::iterator dIt = mActiveDiagramLayers.begin();
  for ( ; dIt != mActiveDiagramLayers.end(); ++dIt )
  {
    QgsDiagramLayerSettings& dls = dIt.value();
    for ( QList<QgsPalGeometry*>::iterator git = dls.geometries.begin(); git != dls.geometries.end(); ++git )
    {
      delete *git;
    }
    dls.geometries.clear();
  }
}
Example #4
0
QList<struct BansheeDbConnection::PlaylistEntry> BansheeDbConnection::getPlaylistEntries(int playlistId) {

    QTime time;
    time.start();

    QList<struct BansheeDbConnection::PlaylistEntry> list;
    struct BansheeDbConnection::PlaylistEntry entry;

    QSqlQuery query(m_database);
    query.setForwardOnly(true); // Saves about 50% time

    QString queryString;

    if (playlistId == 0) {
        // Create Master Playlist
        queryString = QString(
            "SELECT "
            "CoreTracks.TrackID, "        // 0
            "CoreTracks.TrackID, "        // 1
            "CoreTracks.Title, "          // 2
            "CoreTracks.Uri, "            // 3
            "CoreTracks.Duration, "       // 4
            "CoreTracks.ArtistID, "       // 5
            "CoreArtists.Name, "          // 6
            "CoreTracks.Year, "           // 7
            "CoreTracks.AlbumID, "        // 8
            "CoreAlbums.Title, "          // 9
            "CoreTracks.Rating, "         // 10
            "CoreTracks.Genre, "          // 11
            "CoreTracks.TrackNumber, "    // 12
            "CoreTracks.DateAddedStamp, " // 13
            "CoreTracks.BPM, "            // 14
            "CoreTracks.BitRate, "        // 15
            "CoreTracks.Comment, "        // 16
            "CoreTracks.PlayCount, "      // 17
            "CoreTracks.Composer, "       // 18
            "CoreTracks.Grouping, "       // 19
            "CoreAlbums.ArtistID, "       // 20
            "AlbumArtists.Name "          // 21
            "FROM CoreTracks "
            "INNER JOIN CoreArtists ON CoreArtists.ArtistID = CoreTracks.ArtistID "
            "INNER JOIN CoreArtists AlbumArtists ON AlbumArtists.ArtistID = CoreAlbums.ArtistID "
            "INNER JOIN CoreAlbums ON CoreAlbums.AlbumID = CoreTracks.AlbumID ");
     } else {
        // SELECT playlist from CorePlaylistEntries
        queryString = QString(
            "SELECT "
            "CorePlaylistEntries.TrackID, "   // 0
            "CorePlaylistEntries.ViewOrder, " // 1
            "CoreTracks.Title, "              // 2
            "CoreTracks.Uri, "                // 3
            "CoreTracks.Duration, "           // 4
            "CoreTracks.ArtistID, "           // 5
            "CoreArtists.Name, "              // 6
            "CoreTracks.Year, "               // 7
            "CoreTracks.AlbumID, "            // 8
            "CoreAlbums.Title, "              // 9
            "CoreTracks.Rating, "             // 10
            "CoreTracks.Genre, "              // 11
            "CoreTracks.TrackNumber, "        // 12
            "CoreTracks.DateAddedStamp, "     // 13
            "CoreTracks.BPM, "                // 14
            "CoreTracks.BitRate, "            // 15
            "CoreTracks.Comment, "            // 16
            "CoreTracks.PlayCount, "          // 17
            "CoreTracks.Composer, "           // 18
            "CoreTracks.Grouping, "           // 19
            "CoreAlbums.ArtistID, "           // 20
            "AlbumArtists.Name "              // 21
            "FROM CorePlaylistEntries "
            "INNER JOIN CoreTracks ON CoreTracks.TrackID = CorePlaylistEntries.TrackID "
            "INNER JOIN CoreArtists ON CoreArtists.ArtistID = CoreTracks.ArtistID "
            "INNER JOIN CoreArtists AlbumArtists ON AlbumArtists.ArtistID = CoreAlbums.ArtistID "
            "INNER JOIN CoreAlbums ON CoreAlbums.AlbumID = CoreTracks.AlbumID "
            "WHERE CorePlaylistEntries.PlaylistID = %1")
                .arg(playlistId);
    }

    query.prepare(queryString);

    if (query.exec()) {
        while (query.next()) {
            entry.trackId = query.value(0).toInt();
            entry.viewOrder = query.value(1).toInt();
            m_trackMap[entry.trackId].title = query.value(2).toString();
            m_trackMap[entry.trackId].uri = QUrl::fromEncoded(query.value(3).toByteArray(), QUrl::StrictMode);
            m_trackMap[entry.trackId].duration = query.value(4).toInt();

            int artistId = query.value(5).toInt();
            m_artistMap[artistId].name = query.value(6).toString();
            m_trackMap[entry.trackId].year = query.value(7).toInt();
            int albumId = query.value(8).toInt();
            m_albumMap[albumId].title = query.value(9).toString();
            int albumArtistId = query.value(20).toInt();
            m_artistMap[albumArtistId].name = query.value(21).toString();
            m_trackMap[entry.trackId].rating = query.value(10).toInt();
            m_trackMap[entry.trackId].genre = query.value(11).toString();
            m_trackMap[entry.trackId].grouping = query.value(19).toString();
            m_trackMap[entry.trackId].tracknumber = query.value(12).toInt();
            m_trackMap[entry.trackId].dateadded = query.value(13).toInt();
            m_trackMap[entry.trackId].bpm = query.value(14).toInt();
            m_trackMap[entry.trackId].bitrate = query.value(15).toInt();
            m_trackMap[entry.trackId].comment = query.value(16).toString();
            m_trackMap[entry.trackId].playcount = query.value(17).toInt();
            m_trackMap[entry.trackId].composer = query.value(18).toString();

            entry.pTrack = &m_trackMap[entry.trackId];
            entry.pArtist = &m_artistMap[artistId];
            entry.pAlbum = &m_albumMap[albumId];
            entry.pAlbumArtist = &m_artistMap[albumArtistId];
            list.append(entry);
        }
    } else {
        LOG_FAILED_QUERY(query);
    }

    qDebug() << "BansheeDbConnection::getPlaylistEntries(), took " << time.elapsed() << "ms";

    return list;
}
Example #5
0
            void run()
            {
                testsTurn.release();

                // TEST 1: thread can't acquire lock
                threadsTurn.acquire();
                QVERIFY(!normalMutex.tryLock());
                testsTurn.release();

                // TEST 2: thread can acquire lock
                threadsTurn.acquire();
                QVERIFY(normalMutex.tryLock());
                QVERIFY(lockCount.testAndSetRelaxed(0, 1));
                QVERIFY(!normalMutex.tryLock());
                QVERIFY(lockCount.testAndSetRelaxed(1, 0));
                normalMutex.unlock();
                testsTurn.release();

                // TEST 3: thread can't acquire lock, timeout = waitTime
                threadsTurn.acquire();
                QTime timer;
                timer.start();
                QVERIFY(!normalMutex.tryLock(waitTime));
                QVERIFY(timer.elapsed() >= waitTime);
                testsTurn.release();

                // TEST 4: thread can acquire lock, timeout = waitTime
                threadsTurn.acquire();
                timer.start();
                QVERIFY(normalMutex.tryLock(waitTime));
                QVERIFY(timer.elapsed() <= waitTime);
                QVERIFY(lockCount.testAndSetRelaxed(0, 1));
                timer.start();
                // it's non-recursive, so the following lock needs to fail
                QVERIFY(!normalMutex.tryLock(waitTime));
                QVERIFY(timer.elapsed() >= waitTime);
                QVERIFY(lockCount.testAndSetRelaxed(1, 0));
                normalMutex.unlock();
                testsTurn.release();

                // TEST 5: thread can't acquire lock, timeout = 0
                threadsTurn.acquire();
                QVERIFY(!normalMutex.tryLock(0));
                testsTurn.release();

                // TEST 6: thread can acquire lock, timeout = 0
                threadsTurn.acquire();
                timer.start();
                QVERIFY(normalMutex.tryLock(0));
                QVERIFY(timer.elapsed() < waitTime);
                QVERIFY(lockCount.testAndSetRelaxed(0, 1));
                QVERIFY(!normalMutex.tryLock(0));
                QVERIFY(lockCount.testAndSetRelaxed(1, 0));
                normalMutex.unlock();
                testsTurn.release();

                // TEST 7 overflow: thread can acquire lock, timeout = 3000 (QTBUG-24795)
                threadsTurn.acquire();
                timer.start();
                QVERIFY(normalMutex.tryLock(3000));
                QVERIFY(timer.elapsed() < 3000);
                normalMutex.unlock();
                testsTurn.release();

                threadsTurn.acquire();
            }
void
NodeMobilityMgr::populateNodePosTable(QString filter1,
                                      QString filter2,
                                      QString filter3,
                                      QString filter4,
                                      QTableWidget *tbl,
                                      bool showTraj,
                                      QProgressBar * progressBar)
{
    QStringList headerList;
    headerList << "Time"
               << "Node Id"
               << "X coord"
               << "Y coord";

    tbl->clearContents();
    tbl->setRowCount(0);
    tbl->setColumnCount(headerList.count());
    tbl->setHorizontalHeaderLabels(headerList);

    int64_t filter1NodeId = -1;
    int64_t filter2NodeId = -1;
    int64_t filter3NodeId = -1;
    int64_t filter4NodeId = -1;

    if(filter1 != "All")
    {
        filter1NodeId = filter1.toUInt();
    }
    if(filter2 != "None")
    {
        filter2NodeId = filter2.toUInt();
    }
    if(filter3 != "None")
    {
        filter3NodeId = filter3.toUInt();
    }
    if(filter4 != "None")
    {
        filter4NodeId = filter4.toUInt();
    }
    QTime t;
    t.start();
    hideAllTrajectoryPaths();

    uint32_t progressBarValue = 0;

    for(NodeIdTimeLocationMap_t::const_iterator i = m_tsAnimNodes.begin();
        i != m_tsAnimNodes.end();
        ++i)
    {
        uint32_t nodeId = i->first;

        if(filter1 != "All")
        {
            if(filter1NodeId == nodeId)
                goto resume;
            if(filter2NodeId == nodeId)
                goto resume;
            if(filter3NodeId == nodeId)
                goto resume;
            if(filter4NodeId == nodeId)
                goto resume;
            continue;
        }
    resume:
        TimeLocationVector_t tlv = i->second;
        if(showTraj)
            showTrajectory(nodeId, tlv);
        for (TimeLocationVector_t::const_iterator j = tlv.begin();
             j != tlv.end();
             ++j)
        {
            TimeLocation tl = *j;
            if(!tbl)
            {
                return;
            }
            int row = tbl->rowCount();
            tbl->insertRow(row);
            QTableWidgetItem * wiTime   = new QTableWidgetItem(QString::number(tl.timeStamp));
            QTableWidgetItem * wiNodeId = new QTableWidgetItem(QString::number(nodeId));
            QTableWidgetItem * wiXCoord = new QTableWidgetItem(QString::number(tl.location.x()));
            QTableWidgetItem * wiYCoord = new QTableWidgetItem(QString::number(tl.location.y()));

            tbl->setItem(row, 0, wiTime);
            tbl->setItem(row, 1, wiNodeId);
            tbl->setItem(row, 2, wiXCoord);
            tbl->setItem(row, 3, wiYCoord);

        }
        progressBar->setValue(++progressBarValue);

        if(t.elapsed() > 1000)
        {
            QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
            t.restart();
        }

    }

    tbl->setVisible(true);



}
Example #7
0
void UARTWidget::run()
{
    qDebug() << "[UARTWidget] Thread created.";
    m_serialPort = new QSerialPort(m_serialInfo);

    m_serialPort->setBaudRate(250000);
    m_serialPort->setDataBits(QSerialPort::Data8);
    m_serialPort->setStopBits(QSerialPort::TwoStop);
    m_serialPort->setParity(QSerialPort::NoParity);
    m_serialPort->setFlowControl(QSerialPort::NoFlowControl);

    if (!m_serialPort->open(QIODevice::ReadWrite))
    {
        qWarning() << QString("[UARTWidget] Failed to open port %1, error: %2")
                      .arg(m_serialInfo.portName()).arg(m_serialPort->errorString());
        return;
    }

// If the "new" custom baud rate method is available, then use it to
// make sure the baud rate is properly set to 250Kbps

#if defined(TCGETS2)
    int fd = m_serialPort->handle();
    static const int rate = 250000;

    struct termios2 tio;  // linux-specific terminal stuff

    if (ioctl(fd, TCGETS2, &tio) < 0)
    {
        qDebug() << "[UARTWidget] Error in getting termios2 data";
        return;
    }

    tio.c_cflag &= ~CBAUD;
    tio.c_cflag |= BOTHER;
    tio.c_ispeed = rate;
    tio.c_ospeed = rate;  // set custom speed directly
    if (ioctl(fd, TCSETS2, &tio) < 0)
    {
        qDebug() << "[UARTWidget] Error in setting termios2 data";
        return;
    }
#endif

    m_serialPort->clear();
    m_serialPort->setRequestToSend(false);

    // One "official" DMX frame can take (1s/44Hz) = 23ms
    int frameTime = (int) floor(((double)1000 / 30) + (double)0.5);
    m_granularity = Bad;

    QTime time;
    time.start();
    usleep(1000);
    if (time.elapsed() <= 3)
        m_granularity = Good;

    m_running = true;
    while (m_running == true)
    {
        time.restart();

        if (m_mode & Output)
        {
            m_serialPort->setBreakEnabled(true);
            if(m_granularity == Good)
                usleep(DMX_BREAK);
            m_serialPort->setBreakEnabled(false);
            if(m_granularity == Good)
                usleep(DMX_MAB);

            if (m_serialPort->write(m_outputBuffer) == 0)
                qDebug() << "[UARTWidget] Error in writing output buffer";
            m_serialPort->waitForBytesWritten(10);

            // Sleep for the rest of the DMX frame time
            if (m_granularity == Good)
                while (time.elapsed() < frameTime) { usleep(1000); }
            else
                while (time.elapsed() < frameTime) { /* Busy sleep */ }
        }
    }
}
Example #8
0
// instance is created by Core::CorePlugin()
CoreImpl::CoreImpl(QObject *parent) :
        ICore(parent),
        m_MainWindow(0),
        m_ActionManager(0),
        m_ContextManager(0),
        m_PadTools(0)
{
    m_instance = this;

    m_Settings = new SettingsPrivate(this);
    m_Settings->setPath(ISettings::UpdateUrl, Utils::Constants::FREETOOLBOX_UPDATE_URL);

    m_Theme = new ThemePrivate(this);
    m_Theme->setThemeRootPath(m_Settings->path(ISettings::ThemeRootPath));

//    m_CommandLine = new CommandLine();
//    m_CommandLine->feedPatientDatas(m_Patient);

    QTime chrono;
    chrono.start();
    bool logChrono = false; // m_CommandLine->value(CommandLine::CL_Chrono).toBool();
    if (logChrono)
        Utils::Log::logTimeElapsed(chrono, "Core", "command line parsing");

    m_Theme->createSplashScreen(Constants::FREETOOLBOX_SPLASHSCREEN);

    // add translators
    m_Theme->messageSplashScreen(tkTr(Trans::Constants::INITIALIZING_TRANSLATIONS));
    m_Translators = new Translators(this);
    m_Translators->setPathToTranslations(m_Settings->path(ISettings::TranslationsPath));
    // Qt
    m_Translators->addNewTranslator("qt");
    // Core Needed Libs
    m_Translators->addNewTranslator(Trans::Constants::CONSTANTS_TRANSLATOR_NAME);
    m_Translators->addNewTranslator("lib_utils");
    m_Translators->addNewTranslator("plugin_ftbcore");

    if (logChrono)
        Utils::Log::logTimeElapsed(chrono, "Core", "translators");

    m_Theme->messageSplashScreen(tkTr(Trans::Constants::STARTING_APPLICATION_AT_1).arg(QDateTime::currentDateTime().toString()));

    m_FileManager = new FileManager(this);
    m_UpdateChecker = new Utils::UpdateChecker(this);

    LOG_FOR("Core", tkTr(Trans::Constants::STARTING_APPLICATION_AT_1).arg( QDateTime::currentDateTime().toString()));

    // initialize the settings
    m_Theme->messageSplashScreen(tkTr(Trans::Constants::LOADING_SETTINGS));

    // WINE compatibility (only for testing under ubuntu when crosscompiling)
#ifdef Q_OS_WIN
    // For WINE testings
//    if (m_CommandLine->value(Core::CommandLine::CL_RunningUnderWine).toBool()) {
//        LOG_FOR( "Core", "Running under Wine environnement." );
//        QFont::insertSubstitution("MS Shell Dlg", "Tahoma" );
//        QFont::insertSubstitution("MS Shell Dlg 2", "Tahoma" );
//    }
#endif

    foreach(const QString &l, QCoreApplication::libraryPaths()) {
        LOG_FOR("Core" , tkTr(Trans::Constants::USING_LIBRARY_1).arg(l));
    }
Example #9
0
void Spider::start(){

    XpathUtil *util = new XpathUtil(page);
    int count = 0;
    global::unVisitedUrl->pop();
    global::unVisitedUrl->pop();
    while (!global::unVisitedUrl->empty())
    {
        Node node = global::unVisitedUrl->top();
        this->node = node;
        //判断url是否本地采集过
        if(global::bf->contains(node.url.toStdString())){
            qDebug()<< node.url<<" already crawled before !";
            global::unVisitedUrl->pop();
            continue;
        }
        count++;
        qDebug()<<count;
        //判断数据采集节点是否服务器已经采集过
        if(node.depth == global::maxDepth){
            instance->flag = false;
            instance->getService = true;
            if(this->get(instance,node.url)){
                qDebug()<<"elasticesearch indexed :" +node.url;
                logInfo(QString::number(count)+" elasticesearch indexed :"+node.url);
                global::bf->insert(node.url.toStdString());
                global::unVisitedUrl->pop();
                continue;
            }
        }
        logInfo(QString::number(count)+" load url :"+node.url);
        qDebug()<<"load url :"+node.url;
        page->flag = true;
        page->mainFrame()->load(QUrl(node.url));
        QEventLoop eventLoop;
        QObject::connect(page, SIGNAL(loadFinished(bool)), &eventLoop, SLOT(quit()));
        QTimer timer;
        timer.setSingleShot(true);
        QObject::connect(&timer,SIGNAL(timeout()),&eventLoop,SLOT(quit()));
        //5s
        timer.start(5000);
        eventLoop.exec();       //block until finish
        if(timer.isActive()){
            timer.stop();
        }
        //采集数据节点
        int emptyCount = 0;
        if(node.depth == global::maxDepth){

            page->flag = true;
            QMap<int,QStringList> result;
            QMap<QString, QVariant> map;
            emptyCount=0;
            for(int j=0;j<node.collectData.size()-3;j++){
                QStringList tmpResult;
                QString nameFiled = node.collectData.at(j)["name"];
                QString resultFiled = util->parserXpath(page,node.collectData.at(j)["xpath"],node.collectData.at(j)["type"].toInt());
                //logInfo("[collect data ] nameFiled : "+nameFiled +" resultFiled :"+resultFiled);
                //logInfo("debug : "+node.collectData.at(j)["xpath"]+ " debug :"+node.collectData.at(j)["type"]);
                tmpResult.append(nameFiled);
                tmpResult.append(resultFiled);
                result.insert(j+1,tmpResult);
                map.insert(nameFiled,resultFiled);
                if(resultFiled.trimmed()==""){
                    emptyCount++;
                }
            }
            QStringList tmpResult;
            tmpResult.append("url");
            tmpResult.append(node.url);
            result.insert(node.collectData.size()-2,tmpResult);
            map.insert("url",node.url);
            QStringList tmpResult2;
            tmpResult2.append("来源");
            tmpResult2.append(global::taskID);
            result.insert(node.collectData.size()-1,tmpResult2);
            map.insert("来源",global::taskID);
            QDateTime current_date_time = QDateTime::currentDateTime();
            QString current_date = current_date_time.toString("yyyy-MM-dd hh:mm:ss");
            QStringList tmpResult3;
            tmpResult3.append("采集时间");
            tmpResult3.append(current_date);
            map.insert("采集时间",current_date);
            result.insert(node.collectData.size(),tmpResult3);
            if(emptyCount<7){
                global::sqlite->insertXpathResult(global::taskID,result);
                this->post(map,instance);

            }

        }else{
            //非采集节点
            page->flag = false;

            //qDebug()<<page->mainFrame()->toHtml();

            for(int j=0;j<node.regionXpath.size();j++){
                qDebug()<<"region xpath";
                this->node = (*(global::nodeMap))[node.depth];
                this->isRegionNode = true;
                this->currentSubNode = node.regionXpath.at(j);

                qDebug()<<"--------------------------";
                qDebug()<<"REGION :GET URL FROM XPATH";

                //QStringList regionUrlResult = util->getUrlFromXpath(page,node.regionXpath.at(j).value);
                QString html = util->parserXpath(page,node.regionXpath.at(j).value,2);
                qDebug()<<"------------------html";
                int time=1;
                while(html==""){
                    QTime t;
                    t.start();
                    while(t.elapsed()<time*1000){
                        QCoreApplication::processEvents();
                    }
                    time++;
                    html = util->parserXpath(page,node.regionXpath.at(j).value,2);
                    if(time>=5){
                        break;
                    }
                }
                qDebug()<<"time***********";
                qDebug()<<time;
                QStringList regionUrlResult = util->getUrl(html);

//                for(int i=0;i<regionUrlResult.length();i++){
//                    qDebug()<< "GET URL FROM XPATH";
//                    qDebug()<< regionUrlResult.at(i);
//                    addUrlToQueue(regionUrlResult.at(i));
//                }
                int count = util->getANodeNumFromXpath(page,node.regionXpath.at(j).value);
                qDebug()<<"**********************";
                qDebug()<<count;
                qDebug()<<"**********************";
                if(count==0){
                    count = util->getANodeNumFromXpath(page,node.regionXpath.at(j).value);
                }
                for(int m=0;m<count;m++){
                    util->clickNodeAtCount(page,node.regionXpath.at(j).value,m);
                }
            }

            for(int j=0;j<node.loopXpath.size();j++){
                qDebug()<<"loop xpath";
                this->node = (*(global::nodeMap))[node.depth];
                this->isRegionNode = false;
                qDebug()<<"--------------------------";
                qDebug()<<"LOOP :GET URL FROM XPATH";
                QStringList loopUrlResult = util->getUrlFromXpath(page,node.loopXpath.at(j).value);
                for(int i=0;i<loopUrlResult.length();i++){
                    qDebug()<< "GET URL FROM XPATH";
                    qDebug()<< loopUrlResult.at(i);
                    addUrlToQueue(loopUrlResult.at(i));
                }

                int count = util->getANodeNumFromXpath(page,node.loopXpath.at(j).value);

                for(int m=0;m<count;m++){
                    util->clickNodeAtCount(page,node.loopXpath.at(j).value,m);
                }
            }
        }
        global::bf->insert(node.url.toStdString());
        global::unVisitedUrl->pop();
    }
    logInfo("spider finished");
    emit finish();
    qDebug()<<"spider finished";
}
// This requires all the Grids be of the same size and all the orbitals to be
// of the same spin.  Returns true only if something was calculated.
bool MolecularOrbitals::computeOrbitalGrids(Data::GridDataList& grids)
{
   if (grids.isEmpty()) return false;;

   // Check that the grids are all of the same size and Spin
   Data::GridData* g0(grids[0]);
   QList<int> orbitals;
   Data::GridDataList::iterator iter;

   for (iter = grids.begin(); iter != grids.end(); ++iter) {
qDebug() << "Computing grid" << (*iter)->surfaceType().toString() ;
(*iter)->size().dump();
       if ( ((*iter)->size() != g0->size()) ) {
          QLOG_ERROR() << "Different sized grids found in molecular orbitals calculator";
          return false;
       }
       if ( ((*iter)->surfaceType().kind() != Data::SurfaceType::AlphaOrbital) &&
            ((*iter)->surfaceType().kind() != Data::SurfaceType::BetaOrbital) ) {
          QLOG_ERROR() << "Incorrect grid type found in molecular orbitals calculator";
          QLOG_ERROR() << (*iter)->surfaceType().toString(); 
          return false;
       }
       orbitals.append((*iter)->surfaceType().index()-1);
   }

   QTime time;
   time.start();

   Matrix const* coefficients;
   if (g0->surfaceType().kind() == Data::SurfaceType::AlphaOrbital) {
      QLOG_TRACE() << "Setting MO coefficient data to Alpha";
      coefficients = &(m_molecularOrbitals.alphaCoefficients());
   }else {
      QLOG_TRACE() << "Setting MO coefficient data to Beta";
      coefficients = &(m_molecularOrbitals.betaCoefficients());
   }
   
   unsigned nOrb(orbitals.size());
   unsigned nx, ny, nz;
   g0->getNumberOfPoints(nx, ny, nz);
   Vec delta(g0->delta());
   Vec origin(g0->origin());

   QProgressDialog progressDialog("Calculating orbital grid data", "Cancel", 0, 
       nx, QApplication::activeWindow());
   int progress(0);

   progressDialog.setValue(progress);
   progressDialog.setWindowModality(Qt::WindowModal);
   progressDialog.show();

   double  x, y, z;
   double* values;
   double* tmp = new double[nOrb];
   unsigned i, j, k;

   Data::ShellList const& shells(m_molecularOrbitals.shellList());
   Data::ShellList::const_iterator shell;

   for (i = 0, x = origin.x;  i < nx;  ++i, x += delta.x) {
       for (j = 0, y = origin.y;  j < ny;  ++j, y += delta.y) {
           for (k = 0, z = origin.z;  k < nz;  ++k, z += delta.z) {
   
               Vec gridPoint(x,y,z);

               for (unsigned orb = 0; orb < nOrb; ++orb) tmp[orb] = 0.0;
               unsigned count(0);

               //-----------------------------------------------------
               for (shell = shells.begin(); shell != shells.end(); ++shell) {
                   if ( (values = (*shell)->evaluate(gridPoint)) ) {
                      for (unsigned s = 0; s < (*shell)->nBasis(); ++s) {
                          for (unsigned orb = 0; orb < nOrb; ++orb) {
                              tmp[orb] += (*coefficients)(orbitals[orb], count) * values[s];
                          }
                          ++count;
                      }
                   }else {
                      count += (*shell)->nBasis();
                   }
               }

               for (unsigned orb = 0; orb < nOrb; ++orb) {
                   (*grids.at(orb))(i, j, k) = tmp[orb];
               }
               //-----------------------------------------------------
           }
       }

       ++progress;
       progressDialog.setValue(progress);
       if (progressDialog.wasCanceled()) return false;
   }

   delete [] tmp;

   double t = time.elapsed() / 1000.0;
   QLOG_INFO() << "Time to compute orbital grid data:" << t << "seconds";

   return true;
}
bool MolecularOrbitals::computeDensityGrids(Data::GridData*& alpha, Data::GridData*& beta)
{
   QTime time;
   time.start();

   unsigned nx, ny, nz;
   alpha->getNumberOfPoints(nx, ny, nz);
   Vec delta(alpha->delta());
   Vec origin(alpha->origin());

   // We take a two pass approach, the first computes data on a grid with half
   // the number of points for each dimension (so a factor of 8 fewer points
   // than the target grid).  We then used these values in a subsequent pass to
   // refine only those parts with significant density.

   unsigned totalProgress(8*nx);  // first and second passes
   unsigned progress(0);
   unsigned i, j, k;
   double x, y, z;

   QProgressDialog progressDialog("Calculating density grid data", "Cancel", 0, 
       totalProgress, QApplication::activeWindow());
   progressDialog.setValue(progress);
   progressDialog.setWindowModality(Qt::WindowModal);
   progressDialog.show();

   for (i = 0, x = origin.x; i < nx; i += 2, x += 2*delta.x) {
       for (j = 0, y = origin.y; j < ny; j += 2, y += 2*delta.y) {
           for (k = 0, z = origin.z; k < nz; k += 2, z += 2*delta.z) {
               Vec gridPoint(x, y, z);
               computeShellPairs(gridPoint);
               (*alpha)(i, j, k) = inner_prod(m_alphaDensity, m_shellPairValues);
               (*beta )(i, j, k) = inner_prod(m_betaDensity,  m_shellPairValues);
           }
       }

       ++progress;
       progressDialog.setValue(progress);
       if (progressDialog.wasCanceled()) return false;
   }

   double a000, a001, a010, a011, a100, a101, a110, a111, aTot;
   double b000, b001, b010, b011, b100, b101, b110, b111, bTot;
   double thresh(0.125*Data::Shell::thresh());

   origin += delta;

   for (i = 1, x = origin.x;  i < nx-1;  i += 2, x += 2*delta.x) {
       for (j = 1, y = origin.y;  j < ny-1;  j += 2, y += 2*delta.y) {
           for (k = 1, z = origin.z;  k < nz-1;  k += 2, z += 2*delta.z) {

               a000 = (*alpha)(i-1, j-1, k-1);
               a001 = (*alpha)(i-1, j-1, k+1);
               a010 = (*alpha)(i-1, j+1, k-1);
               a011 = (*alpha)(i-1, j+1, k+1);
               a100 = (*alpha)(i+1, j-1, k-1);
               a101 = (*alpha)(i+1, j-1, k+1);
               a110 = (*alpha)(i+1, j+1, k-1);
               a111 = (*alpha)(i+1, j+1, k+1);
               aTot = a000+a001+a010+a011+a100+a101+a110+a111;

               b000 = (*beta)(i-1, j-1, k-1);
               b001 = (*beta)(i-1, j-1, k+1);
               b010 = (*beta)(i-1, j+1, k-1);
               b011 = (*beta)(i-1, j+1, k+1);
               b100 = (*beta)(i+1, j-1, k-1);
               b101 = (*beta)(i+1, j-1, k+1);
               b110 = (*beta)(i+1, j+1, k-1);
               b111 = (*beta)(i+1, j+1, k+1);
               bTot = b000+b001+b010+b011+b100+b101+b110+b111;

               if (std::abs(aTot) > thresh || std::abs(bTot) > thresh) {


                  computeShellPairs(Vec(x, y, z));
                  (*alpha)(i,  j,  k  ) = inner_prod(m_alphaDensity, m_shellPairValues);
                  (*beta )(i,  j,  k  ) = inner_prod(m_betaDensity,  m_shellPairValues);

                  computeShellPairs(Vec(x, y, z-delta.z));
                  (*alpha)(i,  j,  k-1) = inner_prod(m_alphaDensity, m_shellPairValues);
                  (*beta )(i,  j,  k-1) = inner_prod(m_betaDensity,  m_shellPairValues);

                  computeShellPairs(Vec(x, y-delta.y, z));
                  (*alpha)(i,  j-1,k  ) = inner_prod(m_alphaDensity, m_shellPairValues);
                  (*beta )(i,  j-1,k  ) = inner_prod(m_betaDensity,  m_shellPairValues);

                  computeShellPairs(Vec(x, y-delta.y, z-delta.z));
                  (*alpha)(i,  j-1,k-1) = inner_prod(m_alphaDensity, m_shellPairValues);
                  (*beta )(i,  j-1,k-1) = inner_prod(m_betaDensity,  m_shellPairValues);

                  computeShellPairs(Vec(x-delta.x, y, z));
                  (*alpha)(i-1,j,  k  ) = inner_prod(m_alphaDensity, m_shellPairValues);
                  (*beta )(i-1,j,  k  ) = inner_prod(m_betaDensity,  m_shellPairValues);

                  computeShellPairs(Vec(x-delta.x, y, z-delta.z));
                  (*alpha)(i-1,j,  k-1) = inner_prod(m_alphaDensity, m_shellPairValues);
                  (*beta )(i-1,j,  k-1) = inner_prod(m_betaDensity,  m_shellPairValues);

                  computeShellPairs(Vec(x-delta.x, y-delta.y, z));
                  (*alpha)(i-1,j-1,k  ) = inner_prod(m_alphaDensity, m_shellPairValues);
                  (*beta )(i-1,j-1,k  ) = inner_prod(m_betaDensity,  m_shellPairValues);
                  
               }else {

                  (*alpha)(i,  j,  k  ) = 0.125*aTot;
                  (*beta )(i,  j,  k  ) = 0.125*bTot;

                  (*alpha)(i,  j,  k-1) = 0.25*(a000+a010+a100+a110);
                  (*beta )(i,  j,  k-1) = 0.25*(b000+b010+b100+b110);

                  (*alpha)(i,  j-1,k  ) = 0.25*(a000+a001+a100+a101);
                  (*beta )(i,  j-1,k  ) = 0.25*(b000+b001+b100+b101);

                  (*alpha)(i,  j-1,k-1) = 0.50*(a000+a100);
                  (*beta )(i,  j-1,k-1) = 0.50*(b000+b100);

                  (*alpha)(i-1,j,  k  ) = 0.25*(a000+a001+a010+a011);
                  (*beta )(i-1,j,  k  ) = 0.25*(b000+b001+b010+b011);

                  (*alpha)(i-1,j,  k-1) = 0.50*(a000+a010);
                  (*beta )(i-1,j,  k-1) = 0.50*(b000+b010);

                  (*alpha)(i-1,j-1,k  ) = 0.50*(a000+a001);
                  (*beta )(i-1,j-1,k  ) = 0.50*(b000+b001);

               }
            }
       }

       progress += 7;
       progressDialog.setValue(progress);
       if (progressDialog.wasCanceled()) return false;
   }

   // qDebug() << "End of calculation" << nPoints << count << progress;

   double t = time.elapsed() / 1000.0;
   QLOG_INFO() << "Time to compute density grid data:" << t << "seconds";

   return true;
}
Example #12
0
void Interpreter::run()
{
    int res;
    QTime time;

    // init
    try
    {
        ChirpProc versionProc;
        uint16_t *version;
        uint32_t verLen, responseInt;

        if (m_link.open()<0)
            throw std::runtime_error("Unable to open USB device.");
        m_chirp = new ChirpMon(this, &m_link);        

        // get version and compare
        versionProc = m_chirp->getProc("version");
        if (versionProc<0)
            throw std::runtime_error("Can't get firmware version.");
        res = m_chirp->callSync(versionProc, END_OUT_ARGS, &responseInt, &verLen, &version, END_IN_ARGS);
        if (res<0)
            throw std::runtime_error("Can't get firmware version.");
        memcpy(m_version, version, 3*sizeof(uint16_t));
        if (m_version[0]!=VER_MAJOR || m_version[1]>VER_MINOR)
        {
            char buf[0x100];
            sprintf(buf, "This Pixy's firmware version (%d.%d.%d) is not compatible with this PixyMon version (%d.%d.%d).",
                    m_version[0], m_version[1], m_version[2], VER_MAJOR, VER_MINOR, VER_BUILD);
            throw std::runtime_error(buf);
        }

        m_exec_run = m_chirp->getProc("run");
        m_exec_running = m_chirp->getProc("running");
        m_exec_stop = m_chirp->getProc("stop");
        m_exec_get_action = m_chirp->getProc("getAction");
        m_get_param = m_chirp->getProc("prm_get");
        m_getAll_param = m_chirp->getProc("prm_getAll");
        m_set_param = m_chirp->getProc("prm_set");

        if (m_exec_run<0 || m_exec_running<0 || m_exec_stop<0 || m_exec_get_action<0 ||
                m_get_param<0 || m_getAll_param<0 || m_set_param<0)
            throw std::runtime_error("Communication error with Pixy.");
    }
    catch (std::runtime_error &exception)
    {
        emit error(QString(exception.what()));
        return;
    }
    qDebug() << "*** init done";

    time.start();
    getRunning();

    handleLoadParams(); // load params upon initialization

    while(m_run)
    {
        if (!m_programming &&
                ((m_fastPoll && time.elapsed()>RUN_POLL_PERIOD_FAST) ||
                (!m_fastPoll && time.elapsed()>RUN_POLL_PERIOD_SLOW)))
        {
            getRunning();
            time.start();
        }
        else
        {
            m_chirp->service(false);
            msleep(1); // give config thread time to run
        }
        handlePendingCommand();
        if (!m_running)
        {
            if (m_localProgramRunning)
                execute();
            else
            {
                Sleeper::msleep(10);
                if (m_mutexProg.tryLock())
                {
                    if (m_argv.size())
                    {
                        if (m_externalCommand!="") // print command to make things explicit and all pretty
                            emit textOut(PROMPT " " + m_externalCommand);
                        if (m_argv[0]=="help")
                            handleHelp();
                        else
                        {
                            res = call(m_argv, true);
                            if (res<0)
                            {
                                if (m_programming)
                                {
                                    endLocalProgram();
                                    clearLocalProgram();
                                }
                                m_commandList.clear(); // abort our little scriptlet
                            }
                        }
                        m_argv.clear();
                        if (m_externalCommand=="")
                            prompt(); // print prompt only if we expect an actual human to be typing into the command window
                        else
                            m_externalCommand = "";
                        // check quickly to see if we're running after this command
                        if (!m_programming)
                            getRunning();
                        // is there another command in our little scriptlet?
                        if (m_commandList.size())
                        {
                            execute(m_commandList[0]);
                            m_commandList.removeFirst();
                        }
                    }
                    m_mutexProg.unlock();
                }
            }
        }
    }
    sendStop();
    msleep(200); // let things settle a bit
    qDebug("worker thead exiting");
}
Example #13
0
// This is called from the AnalyserQueue thread
bool AnalyserQueue::doAnalysis(TrackPointer tio, SoundSourceProxy* pSoundSource) {
    int totalSamples = pSoundSource->length();
    //qDebug() << tio->getFilename() << " has " << totalSamples << " samples.";
    int processedSamples = 0;

    QTime progressUpdateInhibitTimer;
    progressUpdateInhibitTimer.start(); // Inhibit Updates for 60 milliseconds

    int read = 0;
    bool dieflag = false;
    bool cancelled = false;
    int progress; // progress in 0 ... 100

    do {
        ScopedTimer t("AnalyserQueue::doAnalysis block");
        read = pSoundSource->read(kAnalysisBlockSize, m_pSamplesPCM);

        // To compare apples to apples, let's only look at blocks that are the
        // full block size.
        if (read != kAnalysisBlockSize) {
            t.cancel();
        }

        // Safety net in case something later barfs on 0 sample input
        if (read == 0) {
            t.cancel();
            break;
        }

        // If we get more samples than length, ask the analysers to process
        // up to the number we promised, then stop reading - AD
        if (read + processedSamples > totalSamples) {
            qDebug() << "While processing track of length " << totalSamples << " actually got "
                     << read + processedSamples << " samples, truncating analysis at expected length";
            read = totalSamples - processedSamples;
            dieflag = true;
        }

        // Normalize the samples from [SHRT_MIN, SHRT_MAX] to [-1.0, 1.0].
        // TODO(rryan): Change the SoundSource API to do this for us.
        for (int i = 0; i < read; ++i) {
            m_pSamples[i] = static_cast<CSAMPLE>(m_pSamplesPCM[i]) / SHRT_MAX;
        }

        QListIterator<Analyser*> it(m_aq);

        while (it.hasNext()) {
            Analyser* an =  it.next();
            //qDebug() << typeid(*an).name() << ".process()";
            an->process(m_pSamples, read);
            //qDebug() << "Done " << typeid(*an).name() << ".process()";
        }

        // emit progress updates
        // During the doAnalysis function it goes only to 100% - FINALIZE_PERCENT
        // because the finalise functions will take also some time
        processedSamples += read;
        //fp div here prevents insane signed overflow
        progress = (int)(((float)processedSamples)/totalSamples *
                         (1000 - FINALIZE_PERCENT));

        if (m_progressInfo.track_progress != progress) {
            if (progressUpdateInhibitTimer.elapsed() > 60) {
                // Inhibit Updates for 60 milliseconds
                emitUpdateProgress(tio, progress);
                progressUpdateInhibitTimer.start();
            }
        }

        // Since this is a background analysis queue, we should co-operatively
        // yield every now and then to try and reduce CPU contention. The
        // analyser queue is CPU intensive so we want to get out of the way of
        // the audio callback thread.
        //QThread::yieldCurrentThread();
        //QThread::usleep(10);

        //has something new entered the queue?
        if (deref(m_aiCheckPriorities)) {
            m_aiCheckPriorities = false;
            if (isLoadedTrackWaiting(tio)) {
                qDebug() << "Interrupting analysis to give preference to a loaded track.";
                dieflag = true;
                cancelled = true;
            }
        }

        if (m_exit) {
            dieflag = true;
            cancelled = true;
        }

        // Ignore blocks in which we decided to bail for stats purposes.
        if (dieflag || cancelled) {
            t.cancel();
        }
    } while(read == kAnalysisBlockSize && !dieflag);

    return !cancelled; //don't return !dieflag or we might reanalyze over and over
}
Example #14
0
bool GribV2::loadFile(QString fileName) {

    FILE * fptr=NULL;
    int msg=0;

    this->fileName=fileName;

    QTime tLoad;
    int m_sec_readCgrib=0;
    int m_sec_ginfo=0;
    int m_sec_g2_getfld=0;
    int m_sec_grecConst=0;
    int m_sec_endLoop=0;

    qWarning() << "GV2 loading " << fileName;

    g2int lskip=0,lgrib=0,iseek=0;
    unsigned char *cgrib; // msg buffer
    g2int ierr,listsec0[3],listsec1[13],numfields,numlocal;


    std::string fname = qPrintable(fileName);
    if(fileName == "") return false;

    gribfield  *gfld=NULL;

    ok=false;

    fptr=fopen(fname.c_str(),"rb");
    if(!fptr) {
        qWarning() << "Can't open Grib2 file (in loadFile): " << fileName;
        return false;
    }

    fseek(fptr,0,SEEK_END);
    fileSize=ftell(fptr);
    rewind(fptr);

    /* clean data structure + iso lines */
    clean_all_vectors();
    Util::cleanListPointers(listIsobars);
    Util::cleanListPointers(listIsotherms0);

    for(;;) {

        msg++;

        seekgb(fptr,iseek,32000,&lskip,&lgrib);
        if (lgrib == 0) break;    // end loop at EOF or problem

        cgrib=(unsigned char *)malloc(lgrib);

        fseek(fptr,lskip,SEEK_SET);
        tLoad.start();
        fread(cgrib,sizeof(unsigned char),lgrib,fptr);
        m_sec_readCgrib+=tLoad.elapsed();
        //qWarning() << "Size of cgrib: " << lgrib << ", skip=" << lskip;
        //qWarning() << "Bytes read from file: " << bRead;
        //qWarning() << "EOF=" << feof(fptr) << ", ferror=" << ferror(fptr);
        //qWarning() << "File pos=" << ftell(fptr);
        //qWarning() << "End of grib=" << cgrib[lgrib-4] << cgrib[lgrib-3] << cgrib[lgrib-2] << cgrib[lgrib-1];

        iseek=lskip+lgrib;

        tLoad.start();
        ierr=g2_info(cgrib,listsec0,listsec1,&numfields,&numlocal);
        m_sec_ginfo+=tLoad.elapsed();
        if(ierr) {
            qWarning() << "msg " << msg << ": g2_info error num=" << ierr;
            fclose(fptr);
            return false;
        }



        // accepting only GRIB2 with discipline=0 => Meteorological product (table 0.0)
        if(listsec0[1]!=2 || (listsec0[0]!=0 && listsec0[0]!=10)) {
            qWarning() << "msg " << msg << ": wrong version " << listsec0[1] << ", or discipline: " << listsec0[0];
            continue;
        }

        if(listsec1[4]!=1) {
            qWarning() << "msg " << msg << ": wrong reference time type: " << listsec1[4];
            continue;
        }

        /* loop on th fields => 1 field = 1 GribRecord */
        //qWarning() << "nb fields=" << numfields << ", nb locals=" << numlocal;

        for(int i=0;i<numfields;++i) {
            tLoad.start();
            ierr=g2_getfld(cgrib,i+1,GRB2_UNPACK,GRB2_EXPAND,&gfld);
            m_sec_g2_getfld+=tLoad.elapsed();
            if(ierr) {
                qWarning() << "msg=" << msg << "- field=" << i << ": g2_getfld error num=" << ierr;
                continue;
            }
            tLoad.start();
            GribV2Record * record = new GribV2Record(gfld,msg,i);
            m_sec_grecConst+=tLoad.elapsed();
            tLoad.start();
            if(record && record->isOk() && record->isDataKnown())
                addRecord(record);
            else
                if(record) delete record;
            g2_free(gfld);
            m_sec_endLoop+=tLoad.elapsed();
        }
        free(cgrib);
    }

    if(fptr) fclose(fptr);

    qWarning() << "GRIBV2 load finished";
    qWarning() << "NB key: " << mapGribRecords.size();
    qWarning() << "List:";
    std::map <long int, QMap<time_t,GribRecord *>* >::iterator it;
    int i=0;
    for(it=mapGribRecords.begin();it!=mapGribRecords.end();++it) {
        qWarning() << "key " << i << ": key= " << it->first << ", nb elem" << it->second->size();
        ++i;
    }

    qWarning() << "Time stat:";
    qWarning() << "\t read Cgrib: " << m_sec_readCgrib;
    qWarning() << "\t call gInfo: " << m_sec_ginfo;
    qWarning() << "\t call getFld: " << m_sec_g2_getfld;
    qWarning() << "\t const GribRecordV2: " << m_sec_grecConst;
    qWarning() << "\t End loop: " << m_sec_endLoop;

    createDewPointData();

    ok=true;
    return true;
}
void ConversationModelPerfTest::getEvents()
{
    QFETCH(int, messages);
    QFETCH(int, contacts);
    QFETCH(int, limit);

    qRegisterMetaType<QModelIndex>("QModelIndex");

    QDateTime startTime = QDateTime::currentDateTime();

    addTestGroups( group1, group2 );

    int commitBatchSize = 75;
    #ifdef PERF_BATCH_SIZE
    commitBatchSize = PERF_BATCH_SIZE;
    #endif

    EventModel addModel;
    QDateTime when = QDateTime::currentDateTime();
    QList<QString> remoteUids;

    qDebug() << __FUNCTION__ << "- Creating" << contacts << "new contacts";

    int ci = 0;
    while(ci < contacts) {
        ci++;
        QString phoneNumber = QString().setNum(qrand() % 10000000);
        remoteUids << phoneNumber;
        addTestContact(QString("Test Contact %1").arg(ci), phoneNumber);

        if(ci % commitBatchSize == 0 && ci < contacts) {
            qDebug() << __FUNCTION__ << "- adding" << commitBatchSize
                << "contacts (" << ci << "/" << contacts << ")";
            waitForIdle(5000);
        }
    }
    qDebug() << __FUNCTION__ << "- adding rest of the contacts ("
        << ci << "/" << contacts << ")";
    waitForIdle(5000);
    QTest::qWait(TIMEOUT);

    qDebug() << __FUNCTION__ << "- Creating" << messages << "new messages";

    QList<Event> eventList;

    int ei = 0;
    while(ei < messages) {
        ei++;

        Event::EventDirection direction;
        direction = qrand() % 2 > 0 ? Event::Inbound : Event::Outbound;

        Event e;
        e.setType(Event::SMSEvent);
        e.setDirection(direction);
        e.setGroupId(group1.id());
        e.setStartTime(when.addSecs(ei));
        e.setEndTime(when.addSecs(ei));
        e.setLocalUid(ACCOUNT1);
        e.setRemoteUid(remoteUids.at(0));
        e.setFreeText(randomMessage(qrand() % 49 + 1)); // Max 50 words / message
        e.setIsDraft(false);
        e.setIsMissedCall(false);

        eventList << e;

        if(ei % commitBatchSize == 0 && ei != messages) {
            qDebug() << __FUNCTION__ << "- adding" << commitBatchSize
                << "messages (" << ei << "/" << messages << ")";
            QVERIFY(addModel.addEvents(eventList, false));
            eventList.clear();
            waitForIdle();
        }
    }

    QVERIFY(addModel.addEvents(eventList, false));
    qDebug() << __FUNCTION__ << "- adding rest of the messages ("
        << ei << "/" << messages << ")";
    eventList.clear();
    waitForIdle();

    int iterations = 10;
    int sum = 0;
    QList<int> times;

    #ifdef PERF_ITERATIONS
    iterations = PERF_ITERATIONS;
    #endif

    char *iterVar = getenv("PERF_ITERATIONS");
    if (iterVar) {
        int iters = QString::fromAscii(iterVar).toInt();
        if (iters > 0) {
            iterations = iters;
        }
    }

    QTest::qWait(TIMEOUT);

    qDebug() << __FUNCTION__ << "- Fetching messages." << iterations << "iterations";
    for(int i = 0; i < iterations; i++) {

        ConversationModel fetchModel;
        bool result = false;

        QSignalSpy rowsInserted(&fetchModel, SIGNAL(rowsInserted(const QModelIndex &, int, int)));

        if (limit < 0) {
            fetchModel.setQueryMode(EventModel::SyncQuery);
        } else {
            fetchModel.setQueryMode(EventModel::StreamedAsyncQuery);
            fetchModel.setFirstChunkSize(limit);
            fetchModel.setChunkSize(limit);
        }

        QTime time;
        time.start();
        result = fetchModel.getEvents(group1.id());

        if(limit >= 0) {
            while (time.elapsed() < 10000 && rowsInserted.isEmpty())
            QCoreApplication::processEvents();
        }

        int elapsed = time.elapsed();
        times << elapsed;
        sum += elapsed;
        qDebug("Time elapsed: %d ms", elapsed);

        QVERIFY(result);
        QVERIFY(fetchModel.rowCount() > 0);

        // With 1000 messages deleting model right away results in segfault
        waitForIdle();
    }

    if(logFile) {
        QTextStream out(logFile);

        out << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") << ": "
            << metaObject()->className() << "::" << QTest::currentTestFunction() << "("
            << QTest::currentDataTag() << ", " << iterations << " iterations)"
            << "\n";

        for (int i = 0; i < times.size(); i++) {
            out << times.at(i) << " ";
        }
        out << "\n";
    }

    qSort(times);
    float median = 0.0;
    if(iterations % 2 > 0) {
        median = times[(int)(iterations / 2)];
    } else {
        median = (times[iterations / 2] + times[iterations / 2 - 1]) / 2.0f;
    }

    float mean = sum / (float)iterations;
    int testSecs = startTime.secsTo(QDateTime::currentDateTime());

    qDebug("##### Mean: %.1f; Median: %.1f; Test time: %dsec", mean, median, testSecs);

    if(logFile) {
        QTextStream out(logFile);
        out << "Median average: " << (int)median << " ms. Test time: ";
        if (testSecs > 3600) { out << (testSecs / 3600) << "h "; }
        if (testSecs > 60) { out << ((testSecs % 3600) / 60) << "m "; }
        out << ((testSecs % 3600) % 60) << "s\n";
    }
}
Example #16
0
File: bsp.cpp Project: dgu123/qpcpp
//............................................................................
bool QP::QS::onStartup(void const *) {
    static uint8_t qsBuf[4*1024]; // 4K buffer for Quantum Spy
    initBuf(qsBuf, sizeof(qsBuf));

    QSPY_config(QP_VERSION,         // version
                QS_OBJ_PTR_SIZE,    // objPtrSize
                QS_FUN_PTR_SIZE,    // funPtrSize
                QS_TIME_SIZE,       // tstampSize
                Q_SIGNAL_SIZE,      // sigSize,
                QF_EVENT_SIZ_SIZE,  // evtSize
                QF_EQUEUE_CTR_SIZE, // queueCtrSize
                QF_MPOOL_CTR_SIZE,  // poolCtrSize
                QF_MPOOL_SIZ_SIZE,  // poolBlkSize
                QF_TIMEEVT_CTR_SIZE,// tevtCtrSize
                (void *)0,          // matFile,
                (void *)0,
                &custParserFun);    // customized parser function

    l_time.start();                 // start the time stamp

    // set up the QS filters...
//    QS_FILTER_ON(QS_QEP_STATE_ENTRY);
//    QS_FILTER_ON(QS_QEP_STATE_EXIT);
//    QS_FILTER_ON(QS_QEP_STATE_INIT);
//    QS_FILTER_ON(QS_QEP_INIT_TRAN);
//    QS_FILTER_ON(QS_QEP_INTERN_TRAN);
//    QS_FILTER_ON(QS_QEP_TRAN);
//    QS_FILTER_ON(QS_QEP_IGNORED);
//    QS_FILTER_ON(QS_QEP_DISPATCH);
//    QS_FILTER_ON(QS_QEP_UNHANDLED);

//    QS_FILTER_ON(QS_QF_ACTIVE_ADD);
//    QS_FILTER_ON(QS_QF_ACTIVE_REMOVE);
//    QS_FILTER_ON(QS_QF_ACTIVE_SUBSCRIBE);
//    QS_FILTER_ON(QS_QF_ACTIVE_UNSUBSCRIBE);
//    QS_FILTER_ON(QS_QF_ACTIVE_POST_FIFO);
//    QS_FILTER_ON(QS_QF_ACTIVE_POST_LIFO);
//    QS_FILTER_ON(QS_QF_ACTIVE_GET);
//    QS_FILTER_ON(QS_QF_ACTIVE_GET_LAST);
//    QS_FILTER_ON(QS_QF_EQUEUE_INIT);
//    QS_FILTER_ON(QS_QF_EQUEUE_POST_FIFO);
//    QS_FILTER_ON(QS_QF_EQUEUE_POST_LIFO);
//    QS_FILTER_ON(QS_QF_EQUEUE_GET);
//    QS_FILTER_ON(QS_QF_EQUEUE_GET_LAST);
//    QS_FILTER_ON(QS_QF_MPOOL_INIT);
    QS_FILTER_ON(QS_QF_MPOOL_GET);
//    QS_FILTER_ON(QS_QF_MPOOL_PUT);
//    QS_FILTER_ON(QS_QF_PUBLISH);
//    QS_FILTER_ON(QS_QF_RESERVED8);
//    QS_FILTER_ON(QS_QF_NEW);
//    QS_FILTER_ON(QS_QF_GC_ATTEMPT);
//    QS_FILTER_ON(QS_QF_GC);
//    QS_FILTER_ON(QS_QF_TICK);
//    QS_FILTER_ON(QS_QF_TIMEEVT_ARM);
//    QS_FILTER_ON(QS_QF_TIMEEVT_AUTO_DISARM);
//    QS_FILTER_ON(QS_QF_TIMEEVT_DISARM_ATTEMPT);
//    QS_FILTER_ON(QS_QF_TIMEEVT_DISARM);
//    QS_FILTER_ON(QS_QF_TIMEEVT_REARM);
//    QS_FILTER_ON(QS_QF_TIMEEVT_POST);
//    QS_FILTER_ON(QS_QF_TIMEEVT_CTR);
//    QS_FILTER_ON(QS_QF_CRIT_ENTRY);
//    QS_FILTER_ON(QS_QF_CRIT_EXIT);
//    QS_FILTER_ON(QS_QF_ISR_ENTRY);
//    QS_FILTER_ON(QS_QF_ISR_EXIT);
//    QS_FILTER_ON(QS_QF_INT_DISABLE);
//    QS_FILTER_ON(QS_QF_INT_ENABLE);
//    QS_FILTER_ON(QS_QF_ACTIVE_POST_ATTEMPT);
//    QS_FILTER_ON(QS_QF_EQUEUE_POST_ATTEMPT);
//    QS_FILTER_ON(QS_QF_MPOOL_GET_ATTEMPT);
//    QS_FILTER_ON(QS_QF_RESERVED1);
//    QS_FILTER_ON(QS_QF_RESERVED0);

//    QS_FILTER_ON(QS_QK_MUTEX_LOCK);
//    QS_FILTER_ON(QS_QK_MUTEX_UNLOCK);
//    QS_FILTER_ON(QS_QK_SCHEDULE);
//    QS_FILTER_ON(QS_QK_RESERVED1);
//    QS_FILTER_ON(QS_QK_RESERVED0);

//    QS_FILTER_ON(QS_QEP_TRAN_HIST);
//    QS_FILTER_ON(QS_QEP_TRAN_EP);
//    QS_FILTER_ON(QS_QEP_TRAN_XP);
//    QS_FILTER_ON(QS_QEP_RESERVED1);
//    QS_FILTER_ON(QS_QEP_RESERVED0);

    QS_FILTER_ON(QS_SIG_DICT);
    QS_FILTER_ON(QS_OBJ_DICT);
    QS_FILTER_ON(QS_FUN_DICT);
    QS_FILTER_ON(QS_USR_DICT);
    QS_FILTER_ON(QS_EMPTY);
    QS_FILTER_ON(QS_RESERVED3);
    QS_FILTER_ON(QS_RESERVED2);
    QS_FILTER_ON(QS_TEST_RUN);
    QS_FILTER_ON(QS_TEST_FAIL);
    QS_FILTER_ON(QS_ASSERT_FAIL);

    return true; // success
}
void PerspetiveRectificationWithQt::startAllPictures()
{
	std::string picturePath = "picture";
	std::string pathEnd = ".jpg";
	readApexs();
	QTime time;
	time.start();
	for(int pictureCounter=0;pictureCounter<NUMBER_OF_PICTURES;pictureCounter++) {
		ostringstream ss;
		ss << pictureCounter;
		std::string number = ss.str();
		std::string fullPath = picturePath+number+pathEnd;
		IplImage* image = cvLoadImage(fullPath.c_str());
		if(image!=NULL) {
			InputQuadrangle* quadrangle = new InputQuadrangle();
			quadrangle->setFirstPointToRectification(apexsMatrix[pictureCounter*(POINTS*2)+0],apexsMatrix[pictureCounter*(POINTS*2)+1]);
			quadrangle->setSecondPointToRectification(apexsMatrix[pictureCounter*(POINTS*2)+2],apexsMatrix[pictureCounter*(POINTS*2)+3]);
			quadrangle->setThirdPointToRectification(apexsMatrix[pictureCounter*(POINTS*2)+4],apexsMatrix[pictureCounter*(POINTS*2)+5]);
			quadrangle->setFourthPointToRectification(apexsMatrix[pictureCounter*(POINTS*2)+6],apexsMatrix[pictureCounter*(POINTS*2)+7]);

			/*std::string fullPathSource = "origin"+number+".jpg";
			cvLine(image,cvPoint(apexsMatrix[pictureCounter*(POINTS*2)+0],apexsMatrix[pictureCounter*(POINTS*2)+1]),cvPoint(apexsMatrix[pictureCounter*(POINTS*2)+2],apexsMatrix[pictureCounter*(POINTS*2)+3]),cvScalar(0, 255, 0, 0),2);
			cvLine(image,cvPoint(apexsMatrix[pictureCounter*(POINTS*2)+2],apexsMatrix[pictureCounter*(POINTS*2)+3]),cvPoint(apexsMatrix[pictureCounter*(POINTS*2)+4],apexsMatrix[pictureCounter*(POINTS*2)+5]),cvScalar(0, 255, 0, 0),2);
			cvLine(image,cvPoint(apexsMatrix[pictureCounter*(POINTS*2)+4],apexsMatrix[pictureCounter*(POINTS*2)+5]),cvPoint(apexsMatrix[pictureCounter*(POINTS*2)+6],apexsMatrix[pictureCounter*(POINTS*2)+7]),cvScalar(0, 255, 0, 0),2);
			cvLine(image,cvPoint(apexsMatrix[pictureCounter*(POINTS*2)+6],apexsMatrix[pictureCounter*(POINTS*2)+7]),cvPoint(apexsMatrix[pictureCounter*(POINTS*2)+0],apexsMatrix[pictureCounter*(POINTS*2)+1]),cvScalar(0, 255, 0, 0),2);
			cvSaveImage(fullPathSource.c_str(),image);*/

			QTime time1;
			time1.start();
			DimensionCalculationThread* dimThread = new DimensionCalculationThread();
			dimThread->setAllData(image,quadrangle);
			dimThread->start();
			while(dimThread->isRunning()) {
			}
			int milis = time1.elapsed();
			ui.label_7->setNum(milis);
			IplImage* output = cvCreateImage(cvSize(dimThread->mWidth, dimThread->mHeight),IPL_DEPTH_8U,3);
			QTime time2;
			time2.start();
			HomographyCalculationThread *thread = new HomographyCalculationThread();
			thread->setAllData(image,output,dimThread->mWidth,dimThread->mHeight,dimThread->mOldFirstApexX,dimThread->mOldFirstApexY
				,dimThread->newPictureXApex,dimThread->newPictureYApex,dimThread->mPictureApexXPosition,dimThread->mPictureApexYPosition);
			thread->start();
			while(thread->isRunning()) {
			}
			int milis2 = time2.elapsed();
			ui.label_8->setNum(milis2);
			QTime time3;
			time3.start();
			RectificationThread* rectificationThread = new RectificationThread();
			rectificationThread->setAllData(image,output,dimThread->mOldFirstApexX,dimThread->mOldFirstApexY,dimThread->mWidth,dimThread->mHeight,thread->getHMatrix());
			rectificationThread->start();
			while(rectificationThread->isRunning()) {
			}
			int milis3 = time3.elapsed();
			ui.label_9->setNum(milis3);
			delete quadrangle;
			delete thread;
			delete dimThread; 
		}
	}
	int milis = time.elapsed();
	ui.label_2->setNum(milis);
}
Example #18
0
int main(int argc, char *argv[]){
    QTime t;
    t.start();
    //START APP
    QApplication app(argc,argv);
    app.setWindowIcon(QIcon(":/data/img/11412394_407750046078820_6932822019341529347_n.jpg"));
    QApplication::setApplicationName("Huffman");
    QApplication::setApplicationVersion("ÚNICO");
    QQmlApplicationEngine engine;
    QQmlContext *interpreter = engine.rootContext();
    Huffman huff;
    DHuffman deHuff;
    QCommandLineParser parser;
    //Parser
    parser.addHelpOption();
    parser.addVersionOption();
    parser.setApplicationDescription("Huffman Parsers");
    parser.addPositionalArgument("in-file.x", QCoreApplication::translate("main", "File being compressed."));
    parser.addPositionalArgument("out-name.huff", QCoreApplication::translate("main", "Name to save archive."));
    //parser.addPositionalArgument("dir", QCoreApplication::translate("main", "Dir being compressed"));
    parser.addPositionalArgument("local", QCoreApplication::translate("main", "Local to save archive."));
    QCommandLineOption compress("c",QApplication::translate("main","Compress <in-file.x>."),
                                QApplication::translate("main","in-file.x"));
    parser.addOption(compress);
    QCommandLineOption outName("o",QApplication::translate("main","Save as <out-name.huff>."),
                               QApplication::translate("main","out-file.huff"));
    parser.addOption(outName);
    QCommandLineOption local("d",QApplication::translate("main","Decompress in <local>."),
                             QApplication::translate("main","local"));
    parser.addOption(local);
    QCommandLineOption startGui({"g", "gui"},QApplication::translate("main","Start gui."));
    parser.addOption(startGui);
    parser.process(app);

    //ARGUMENTS
    if(parser.isSet(startGui)){
        interpreter->setContextProperty("_huff",&huff);
        interpreter->setContextProperty("_dehuff",&deHuff);
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    }
    else if(parser.isSet(compress) && parser.isSet(outName))
    {
        cout << "case 1" << endl;
        huff.Huff(parser.value(compress),parser.value(outName));
    }
    else if(parser.isSet(compress))
    {
        cout << "case 2" << endl;
        huff.Huff(parser.value(compress),parser.value(compress));
    }
    else{
        if(app.arguments().size() == 1)
            qDebug() << qPrintable(parser.helpText());
        else if(parser.isSet(local))
            deHuff.DHuff(app.arguments().at(1),parser.value(local));
        else
            deHuff.DHuff(app.arguments().at(1),app.arguments().at(1));
    }
    //END APP
    qDebug("%s <> Tempo de execução: %d ms",Q_FUNC_INFO,t.elapsed());
    return app.exec();
}
Example #19
0
bool WinDebugInterface::runLoop()
{
    m_waitHandles[TerminateEventHandle] = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (GetLastError() == ERROR_ALREADY_EXISTS)
        return false;
    m_waitHandles[DataReadyEventHandle] = CreateEvent(NULL, FALSE, FALSE, L"DBWIN_DATA_READY");
    if (!m_waitHandles[TerminateEventHandle] || !m_waitHandles[DataReadyEventHandle]
            || GetLastError() == ERROR_ALREADY_EXISTS)
        return false;
    m_bufferReadyEvent = CreateEvent(NULL, FALSE, FALSE, L"DBWIN_BUFFER_READY");
    if (!m_bufferReadyEvent
            || GetLastError() == ERROR_ALREADY_EXISTS)
        return false;
    m_sharedFile = CreateFileMapping((HANDLE)-1, NULL, PAGE_READWRITE, 0, 4096, L"DBWIN_BUFFER");
    if (!m_sharedFile || GetLastError() == ERROR_ALREADY_EXISTS)
        return false;
    m_sharedMem = MapViewOfFile(m_sharedFile, FILE_MAP_READ, 0, 0,  512);
    if (!m_sharedMem)
        return false;

    LPSTR  message = reinterpret_cast<LPSTR>(m_sharedMem) + sizeof(DWORD);
    LPDWORD processId = reinterpret_cast<LPDWORD>(m_sharedMem);

    SetEvent(m_bufferReadyEvent);

    QTime timer; // time since last signal sent
    timer.start();

    QMap<qint64, QString> delayedMessages;

    auto flushMessages = [this, &delayedMessages, &timer](){
        auto it = delayedMessages.constBegin();
        auto end = delayedMessages.constEnd();
        for (; it != end; ++it)
            emit debugOutput(it.key(), it.value());
        delayedMessages.clear();
        timer.start();
    };

    while (true) {
        DWORD timeout = INFINITE;
        if (!delayedMessages.isEmpty()) // if we have delayed message, don't wait forever
            timeout = qMax(60 - timer.elapsed(), 1);
        const DWORD ret = WaitForMultipleObjects(HandleCount, m_waitHandles, FALSE, timeout);

        if (ret == WAIT_FAILED || ret - WAIT_OBJECT_0 == TerminateEventHandle) {
            flushMessages();
            break;
        }
        if (ret == WAIT_TIMEOUT) {
            flushMessages();
            SetEvent(m_bufferReadyEvent);
        } else if (ret - WAIT_OBJECT_0 == DataReadyEventHandle) {
            if (*processId != m_creatorPid) {
                if (timer.elapsed() < 60) {
                    delayedMessages[*processId].append(QString::fromLocal8Bit(message));
                } else {
                    delayedMessages[*processId] += QString::fromLocal8Bit(message);
                    flushMessages();
                }
            }
            SetEvent(m_bufferReadyEvent);
        }
    }
    return true;
}
Example #20
0
void QVX_Sim::SimLoop(QString* pSimMessage)
{
	std::string tmp; //need to link this up to get info back...
	if (!Import(NULL, NULL, &tmp)) return;

	int Count = 0; //Possibly redundant with internal sim count.
	int LastCount = 0;
	bool IsStillDrawing;
	Vec3D<> CurSelPos;
	QString PosLabel;
	bool InternalEnding = false;
	QString Message, DispMessage;
	std::string RetMsg;
	QTime tLastPlot; //plot point add every...
	QTime tLastStatus; //status text box updated...
//	QTime tLastStatCalc; //simulation max/mins calculated every...
	tLastPlot.start();
	tLastStatus.start();
//	tLastStatCalc.start();

	emit ReqUiUpdate(); //for slider ranges that depend on dt or other sim params
	emit StartExternalGLUpdate(DEFAULT_DISPLAY_UPDATE_MS);
	StopSim = false;
	Running = true;
	Paused = false;

	//initialize the COM at the start of the simulation	
	IniCM=GetCM();
	Vec3D<> LastCM = IniCM;

	int StatusNumber = 1, PlotPointNumber = 1;
	double UpStatEv = 500; //Updates status pane every X ms
	int UpPlotEv = 30; //updates plot every X ms when not plotting every point.
	char PlotDataTypes;
	bool PlotVis, StatusVis;

	while (true){ //do this step...
		if (StopConditionMet()){InternalEnding = true; StatToCalc=CALCSTAT_ALL; UpdateStats(); RetMsg+="Simulation stop condition reached.\n";break;}//if stop condition met...
		
		//figure out what stats we need to calculate
		StatToCalc=CALCSTAT_NONE;

		emit IsPlotVisible(&PlotVis);
		bool PlottingPoint = (LogEvery?true:tLastPlot.elapsed() > PlotPointNumber*UpPlotEv) && PlotVis;
		if (PlottingPoint){ //ensure we calculate the info we want to plot
			emit GetPlotRqdStats(&PlotDataTypes);
			StatToCalc |= PlotDataTypes;
		}
		emit IsStatusTextVisible(&StatusVis);
		bool UpdatingStatus = (tLastStatus.elapsed() > StatusNumber*UpStatEv) && StatusVis;
		if (UpdatingStatus){StatToCalc |= CALCSTAT_COM;} //calc any data we need in the text status box

		bool DrawingGLLocal = (GLUpdateEveryNFrame != -1 && Count%GLUpdateEveryNFrame==0);
		if (DrawingGLLocal || NeedStatsUpdate){ //calc any data we need to draw the opengl view...
			StatToCalc |= StatRqdToDraw();
			NeedStatsUpdate = false;
			if (LockCoMToCenter) StatToCalc |= CALCSTAT_COM;
		}


//		if (tLastStatCalc.elapsed() > StatCalcNumber*30){CalcStat=true; StatCalcNumber++; /*tLastStatCalc.restart();*/}

		if (!TimeStep(&RetMsg)){InternalEnding = true; break;}//if something happened in this timestep

		if (DrawingGLLocal){
			IsStillDrawing = true;
			ReqGLDrawingStatus(&IsStillDrawing);
			while (IsStillDrawing){ //wait to finish drawing the previous timestep before continuing
				LOCALSLEEP(1);
				ReqGLDrawingStatus(&IsStillDrawing); //are 
			}
			emit ReqGLUpdate(); 
		} 

		if (StopSim) break;
		while(Paused){
			ActuallyPaused = true;
			if (StopSim) break; //kick out of the loop if we've stopped...
			LOCALSLEEP(100);
		}

		if(UpdatingStatus){
//			emit IsStatusTextVisible...
			if (CurXSel != -1){PosLabel = "Vox "+QString::number(XtoSIndexMap[CurXSel]) + "(sim)"; CurSelPos = VoxArray[XtoSIndexMap[CurXSel]].GetCurPos()*1000; }//position in mm
			else {PosLabel = "CoM "; CurSelPos = SS.CurCM*1000;} //center of mass in mm if nothing else selected
			Message = "Time " + QString::number(CurTime, 'g', 3) + " Sec" + 
					"\nStep Num " + QString::number(CurStepCount) + 
					"\nTime Step = " + QString::number(dt, 'g', 3)+ " Sec" + 
					"\nDisplay Rate  = "+ QString::number((Count-LastCount)/(UpStatEv/1000.0), 'g', 3)+" Steps/sec" +
					"\n" + PosLabel + " X:"+ QString::number(CurSelPos.x, 'g', 3)+"  Y:"+ QString::number(CurSelPos.y, 'g', 3)+"  Z:"+ QString::number(CurSelPos.z, 'g', 3)+ " mm" +
					"\nCoM Displacement = "+ QString::number((SS.CurCM-IniCM).Length()*1000, 'g', 3)+" mm" +
					"\nCoM Velocity = "+ QString::number((SS.CurCM-LastCM).Length()*1000/(dt*(Count-LastCount)), 'g', 3)+" mm/s\n";
					
			if (pEnv->IsFloorEnabled()) Message += "Voxel touching ground: " + QString::number(GetNumTouchingFloor()) + "\n";

					Message += "\n";
					LastCM = SS.CurCM;
			
			if (LogEvery) ApproxMSperLog = (double)tLastStatus.elapsed()/(Count-LastCount); //only update ms per step if its not fixed by the timer
			LastCount = Count;

			emit UpdateText(Message);
			StatusNumber++;
		}

		if (PlottingPoint){
			if (LogEvery) emit ReqAddPlotPoint(GetCurTime());
			else {
				ApproxMSperLog = UpPlotEv;
				emit ReqAddPlotPoint(GetCurTime());
				PlotPointNumber++;
			}
		}

//		if (StatCalcNumber == INT_MAX){StatCalcNumber=1; tLastStatCalc.restart();} //avoid int rollover for our counters
		if (StatusNumber == INT_MAX){StatusNumber=1; tLastStatus.restart();}
		if (PlotPointNumber == INT_MAX){PlotPointNumber=1; tLastPlot.restart();}


		Count++;
	}

	emit StopExternalGLUpdate();

//	emit SetExternalGLUpdate(false);
	Running = false;
	Paused = false;

	Message = "Time " + QString::number(CurTime, 'g', 3) + " Sec" + 
		"\nStep Num " + QString::number(CurStepCount) + 
		"\nTime Step = " + QString::number(dt, 'g', 3)+ " Sec" + 
		"\n" + PosLabel + " X:"+ QString::number(CurSelPos.x, 'g', 3)+"  Y:"+ QString::number(CurSelPos.y, 'g', 3)+"  Z:"+ QString::number(CurSelPos.z, 'g', 3)+ " mm" +
		"\nCOM_Dist = "+ QString::number((SS.CurCM-IniCM).Length()*1000, 'g', 3)+" mm\n\n";

	RetMsg += "Simulation stopped.\n";
	Message += RetMsg.c_str();
	DispMessage = Message + "\nFinal Conditions:\nStep = " + QString::number(CurStepCount) + "\nTime Step = " + QString::number(dt)+"\nKinetic Energy = " + QString::number(SS.TotalObjKineticE)+"\n" ;
	emit UpdateText(DispMessage);

	if (InternalEnding)	emit SimEndedInternally(RetMsg.c_str());

//	Running = false;



}
Example #21
0
int main(int argc, char *argv[]) {
    QSet<QString> valuedOptions, flagedOptions;
    valuedOptions << "o" << "fps" << "dir" << "assets";
    flagedOptions << "pot" << "M";

    QHash<QString, QString> options;
    QSet<QString> flags;
    QString key;
    QString inputPath;
    bool isOption = false;
    for(int i = 1; i < argc; i++) {
        QString arg(argv[i]);
        if(isOption) {
            options[key] = arg;
            isOption = false;
        } else {
            if(arg[0] == '-') {
                key = arg.mid(1);
                if(valuedOptions.contains(key)) {
                    isOption = true;
                } else if(flagedOptions.contains(key)) {
                    flags << key;
                } else {
                    qDebug() << "Warning: Ignored unrecognized flag or option " << arg;
                }
            } else {
                if(inputPath.isEmpty())
                    inputPath = arg;
                else {
                    qDebug() << "Warning: Only one input file is allowed, will ignore " << arg;
                }
            }
        }
    }
    if(inputPath.isEmpty()) {
        qDebug() << "Error: Must specify input tml file";
        printHelp();
    }

#define OPT(KEY, DEFAULT) (options.contains(#KEY) ? options[#KEY] : DEFAULT)
#define ABS_PATH(X) QDir().absoluteFilePath(X).toUtf8().data()

    inputPath = ABS_PATH(inputPath);
    CCPlus::setAssetsPath(ABS_PATH(OPT(assets, dirname(argv[0]) + "assets")));
    CCPlus::RenderTarget t;
    t.inputPath = inputPath.toUtf8().data();
    t.outputPath = ABS_PATH(OPT(o, inputPath + ".mp4"));
    t.footageDir = ABS_PATH(OPT(dir, dirname(inputPath)));
    t.fps = OPT(fps, "18").toInt();
    if(t.fps < 4)
        t.fps = 4;
    CCPlus::renderFlag = 0;
    if(flags.contains("pot")) {
        CCPlus::renderFlag |= CCPlus::FORCE_POT;
    }
    if(flags.contains("M")) {
        CCPlus::collectorTimeInterval     = 1;
        CCPlus::collectorWindowSize       = 10;
        CCPlus::collectorThreadsNumber    = 8;
        CCPlus::renderFlag |= CCPlus::LARGE_MEM;
    }
    QApplication app(argc, argv);
    QTime timer;
    timer.start();
    CCPlus::go(t);
    t.waitFinish();
    app.exit(0);
    qDebug() << "Elapsed: " << timer.elapsed() * 0.001 << "s";
    qDebug() << "END";
    return 0;
}
Example #22
0
bool ESerialPort::open(OpenMode mode)
{
    if (!(mode & ReadWrite)) return false;
    DWORD options = 0;
    if (mode & ReadOnly) options |= GENERIC_READ;
    if (mode & ReadWrite) options |= GENERIC_WRITE;
    if (fd != ESP_INVALID_HANDLE) {
        ::CloseHandle(fd);
        fd = ESP_INVALID_HANDLE;
        QIODevice::close();
    }
    fd = CreateFileA(deviceName.toAscii().data(),
                    options,
                    0,
                    0,
                    OPEN_EXISTING,
                    FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
                    0);
    if (fd == ESP_INVALID_HANDLE) {
        return false;
    }
    FlushFileBuffers(fd);
    PurgeComm(fd, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);

    DCB dcbSerialParams = {0};
    dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
    if (!GetCommState(fd, &dcbSerialParams)) {
        ::CloseHandle(fd);
        fd = ESP_INVALID_HANDLE;
        return false;
    }
    DWORD baud = (DWORD)nativeBaudRate(baudRate);
    dcbSerialParams.BaudRate = baud;
    dcbSerialParams.ByteSize=8;
    dcbSerialParams.StopBits=ONESTOPBIT;
    dcbSerialParams.Parity=NOPARITY;
    if(!SetCommState(fd, &dcbSerialParams)){
        ::CloseHandle(fd);
        fd = ESP_INVALID_HANDLE;
        return false;
    }


    COMMTIMEOUTS timeouts={0};
    timeouts.ReadIntervalTimeout=1;
    timeouts.ReadTotalTimeoutConstant = 1;
    timeouts.ReadTotalTimeoutMultiplier=1;
    timeouts.WriteTotalTimeoutConstant=50;
    timeouts.WriteTotalTimeoutMultiplier=10;
    if(!SetCommTimeouts(fd, &timeouts)){
        ::CloseHandle(fd);
        fd = ESP_INVALID_HANDLE;
        return false;
    }

    if (!EscapeCommFunction(fd, CLRDTR)) {
        ::CloseHandle(fd);
        fd = ESP_INVALID_HANDLE;
        return false;
    }
    {
        QTime t;
        t.start();
        while (t.elapsed() < 60) {};
    }
    QIODevice::open(mode);
    setDtr(false);
    return true;
}
Example #23
0
 void start()
 {
     t.start();
     QThread::start();
 }
Example #24
0
void Lockin2::interpretInput()
{
    QTime time;
    time.start();

    _timeValue += _outputPeriod;

    // récupère les nouvelles valeurs
    /*
     * le nombre de nouvelle valeurs = outputPeriod * sampleRate / 1000
     * outputPeriod (~0.1 s) étant beaucoup plus grand que la periode du chopper (~1/500 s)
     * meme dans le cas d'un chopper lent et d'un temps de sortie rapide le nombre de periodes
     * du chopper reste elevé. (~50)
     * On peut donc garder uniquement les periodes entières
     * On a donc une perte de présision de l'ordre de 2/50 = 4%
     * Plus outputPeriod et grand et plus le chopper est rapide plus la perte diminue.
     * 0.5s 500Hz -> 0.8%
     * 1.0s 500Hz -> 0.4%
     */


    QList<qreal> leftSignal;
    QList<int> chopperSignal;

    // les des données et les adapte
    // left [-1;+1]
    // right -1 ou +1
    readSoudCard(leftSignal, chopperSignal);

    if (leftSignal.size() == 0 || chopperSignal.size() == 0)
        return;

    QList<QPair<qreal, qreal> > chopperSinCos = parseChopperSignal(chopperSignal, _phase);

    // multiplie le leftSignal ([-1;1]) par chopperSinCos ([-1;1])
    for (int i = 0; i < leftSignal.size(); ++i) {
        qreal x, y;
        if (chopperSinCos[i].first != 3.0) { // 3.0 est la valeur qui indique ignoreValue dans parseChopperSignal(...)
            x = chopperSinCos[i].first * leftSignal[i]; // sin
            y = chopperSinCos[i].second * leftSignal[i]; // cos
        } else {
            x = y = 3.0; // ignore value
        }
        _dataXY << QPair<qreal, qreal>(x, y);
    }

    // renouvelle le view data (prend la fin des listes, qui correspond aux parties les plus récentes)
    if (_vumeterMutex.tryLock()) {
        _vumeterData.clear();
        for (int i = leftSignal.size() - 1; i >= 0; --i) {
            if (_vumeterData.size() >= _sampleVumeter)
                break;

            if (chopperSinCos[i].first != 3.0) {
                _vumeterData.prepend(QPair<qreal, qreal>(leftSignal[i], chopperSinCos[i].first));
            }
        }
        _vumeterMutex.unlock();
    } else {
        qDebug() << __FUNCTION__ << ": the view Mutex is locked";
    }



    // le nombre d'échantillons correslondant au temps d'integration

    if (_dataXY.size() < _sampleIntegration) {
        // pas encore assez d'elements pour faire la moyenne
        emit info("wait more input data...");
        return;
    }

    // supprime les valeurs en trop
    while (_dataXY.size() > _sampleIntegration)
        _dataXY.removeFirst();

    qreal dataCount = 0.0;
    qreal x = 0.0;
    qreal y = 0.0;

    for (int i = 0; i < _dataXY.size(); ++i) {
        // deux fois 3.0 indique ignoreValue
        if (_dataXY[i].first != 3.0) {
            x += _dataXY[i].first;
            y += _dataXY[i].second;
            dataCount += 1.0;
        }
    }

    if (dataCount == 0.0) {
        qDebug() << __FUNCTION__ << ": no data usable";
        emit info("signal too low");
        return;
    }

    x /= dataCount;
    y /= dataCount;

    //    _values << QPair<qreal, QPair<qreal, qreal> >(_timeValue, QPair<qreal, qreal>(x, y));
    _xValue = x;
    _yValue = y;

    emit newValues(_timeValue, x, y);

    qDebug() << __FUNCTION__ << ": execution time " << time.elapsed() << "ms";
}
void mathGraph::dijkstra()
{
    QTime t;
    t.start();

    QVector<QVector<int> > sum;
    sum.resize(matrixOfSize.size()-1);
    for (int i = 0; i < sum.size(); ++i)
        sum[i].resize(matrixOfSize.size()-1);



    for (int i = 0; i < sum.size(); i++) {
        for (int j = 0; j < sum.size(); j++) {
            sum[i][j] = matrixOfSize[i][j];
        }
    }

    // alg

    QVector<bool> visited;
    QVector<int> distance;
    visited.resize(sum.size());
    distance.resize(sum.size());


    int index, u;
    int max = 0;
    for(int vert = 0; vert < sum.size(); vert++) { // vert - начальная точка
        for (int i=0; i<sum.size(); i++)
        {
            distance[i]=INT_MAX;
            visited[i]=false;
        }


        distance[vert]=0;
        for (int count=0; count<sum.size()-1; count++)
        {
            int min=INT_MAX;
            for (int i=0; i<sum.size(); i++)
                if (!visited[i] && distance[i]<=min) {
                    min=distance[i];
                    index=i;
                }
            u=index;
            visited[u]=true;
            for (int i=0; i<sum.size(); i++)
                if (!visited[i] && sum[u][i] && distance[u]!=INT_MAX && distance[u]+sum[u][i]<distance[i])
                    distance[i]=distance[u]+sum[u][i];
        }
        for(int i = 0; i  < sum.size(); ++i) {
            if (distance[i]!=INT_MAX)
                if(max < distance[i]) {
                    max = distance[i];
                }
        }
    }
    qDebug() << "max dex" << max;
    dijkstraResults << max;
    dijkstraTime << t.elapsed();

    //end alg
    for (int i = 0; i < sum.size(); i++){
        for (int j = 0; j < sum.size(); j++){
            if (sum[i][j] == INT_MAX)
                sum[i][j] = 0;
        }
    }
    qDebug() << "dijk end";
}
Example #26
0
int AirspaceHelper::loadAirspaces( QList<Airspace>& list )
{
  // Set a global lock during execution to avoid calls in parallel.
  QMutexLocker locker( &m_mutex );
  QTime t; t.start();
  uint loadCounter = 0; // number of successfully loaded files

  m_airspaceDictionary.clear();

  QString mapDir = MapContents::instance()->getMapRootDirectory() + "/airspaces";
  QStringList preselect;

  // Setup a filter for the desired file extensions.
  QString filter = "*.txt *.TXT *.aip";

  MapContents::addDir( preselect, mapDir, filter );

  if( preselect.count() == 0 )
    {
      qWarning( "ASH: No Airspace files found in the map directory!" );
      return loadCounter;
    }

  // Check, which files shall be loaded.
  QStringList files = _settings.value( "/Airspace/FileList", QStringList(QString("All"))).toStringList();

  if( files.isEmpty() )
    {
      // No files shall be loaded
      qWarning() << "ASH: No Airspace files defined for loading!";
      return loadCounter;
    }

  if( files.first() != "All" )
    {
      // Check for desired files to be loaded. All other items are removed from
      // the files list.
      for( int i = preselect.size() - 1; i >= 0; i-- )
        {
          QString file = QFileInfo(preselect.at(i)).fileName();

          if( files.contains( file ) == false )
            {
              preselect.removeAt(i);
            }
        }
    }

  OpenAirParser oap;
  OpenAip oaip;
  QString errorInfo;

  while( ! preselect.isEmpty() )
    {
      QString srcName;

      if( preselect.first().endsWith(QString(".TXT")) ||
	  preselect.first().endsWith(QString(".txt")) )
        {
          srcName = preselect.first();

          if( oap.parse(srcName, list) )
            {
              loadCounter++;
            }

          preselect.removeAt(0);
          continue;
        }

      if( preselect.first().endsWith(QString(".aip")) )
        {
          // there can't be the same name aic after this aip
          // parse found aip file
          srcName = preselect.first();

          if( oaip.readAirspaces(srcName, list, errorInfo ) )
            {
              loadCounter++;
            }

          preselect.removeAt(0);
          continue;
        }

    } // End of While

  qDebug("ASH: %d Airspace file(s) loaded in %dms", loadCounter, t.elapsed());

//    for(int i=0; i < list.size(); i++ )
//      {
//        list.at(i)->debug();
//      }

  return loadCounter;
}
Example #27
0
void M3UParser::load() {
	QTime timeElapsed;
	timeElapsed.start();

	_stop = false;

	QList<MediaInfo> files;

	qDebug() << __FUNCTION__ << "Playlist:" << _filename;

	//See http://regexlib.com/DisplayPatterns.aspx

	//#EXTM3U
	static QRegExp rx_extm3u("^#EXTM3U$|^#M3U$");
	//#EXTINF:123,Sample title
	static QRegExp rx_extinf("^#EXTINF:([-+]?\\d+),(.*)$");
	//#EXTINF:Sample title
	static QRegExp rx_extinf_title("^#EXTINF:(.*)$");
	//#Just a comment
	static QRegExp rx_comment("^#.*$");

	QFile file(_filename);
	if (file.open(QIODevice::ReadOnly)) {
		QString path(QFileInfo(_filename).path());

		QTextStream stream(&file);

		if (isUtf8()) {
			stream.setCodec("UTF-8");
		} else {
			stream.setCodec(QTextCodec::codecForLocale());
		}

		MediaInfo mediaInfo;

		while (!stream.atEnd() && !_stop) {
			//Line of text excluding '\n'
			QString line(stream.readLine().trimmed());

			if (line.isEmpty()) {
				//Do nothing
			}

			else if (rx_extm3u.indexIn(line) != -1) {
				//#EXTM3U line, ignored
			}

			else if (rx_extinf.indexIn(line) != -1) {
				//#EXTINF line
				QString length(rx_extinf.cap(1));
				if (!length.isEmpty()) {
					mediaInfo.setLength(length.toInt());
				}
				QString title(rx_extinf.cap(2));
				if (!title.isEmpty()) {
					mediaInfo.insertMetadata(MediaInfo::Title, title);
				}
			}

			else if (rx_extinf_title.indexIn(line) != -1) {
				QString title(rx_extinf_title.cap(1));
				if (!title.isEmpty()) {
					mediaInfo.insertMetadata(MediaInfo::Title, title);
				}
			}

			else if (rx_comment.indexIn(line) != -1) {
				//# line, comment, ignored
			}

			else {
				bool isUrl = MediaInfo::isUrl(line);
				mediaInfo.setUrl(isUrl);
				if (isUrl) {
					mediaInfo.setFileName(line);
				} else {
					mediaInfo.setFileName(Util::canonicalFilePath(path, line));
				}

				//Add file to the list of files
				files << mediaInfo;

				//Clear the MediaInfo for the next 2 lines from the m3u playlist
				mediaInfo.clear();

				if (files.size() > FILES_FOUND_LIMIT) {
					//Emits the signal every FILES_FOUND_LIMIT files found
					emit filesFound(files);
					files.clear();
				}
			}
		}
	}

	file.close();

	if (!files.isEmpty()) {
		//Emits the signal for the remaining files found (< FILES_FOUND_LIMIT)
		emit filesFound(files);
	}

	//Emits the last signal
	emit finished(timeElapsed.elapsed());
}
Example #28
0
void AndroidRetracer::run()
{
    m_androidUtils.reloadAdb();
    QString errorStr;
    bool setupRet;
    QMetaObject::invokeMethod(this, "setup", Qt::BlockingQueuedConnection,
                              Q_RETURN_ARG(bool, setupRet),
                              Q_ARG(QString *, &errorStr));

    if (!setupRet) {
        emit finished(errorStr);
        return;
    }

    if (!m_androidUtils.runAdb(QStringList() << _("shell") << _("am") << _("start") << _("-n") << packageName + activityName)) {
        emit finished(tr("Can't start apitrace application"));
        return;
    }
    QByteArray which;
    if (!m_androidUtils.runAdb(QStringList() << _("shell") << _("readlink") << _("$(which ps)") , &which)) {
        emit finished(tr("Can't start adb"));
        return;
    }

    bool isBusyBox = which.startsWith("busybox");
    QStringList psArgs;
    psArgs << _("shell") << _("ps");
    if (isBusyBox)
        psArgs << _("-w");

    qint64 processPID;
    bool wasStarted = false;
    QTime startTime;
    startTime.start();

    QTcpSocket stdoutSocket;
    QTcpSocket stderrSocket;

    ImageHash thumbnails;

    QVariantMap parsedJson;
    trace::Profile* profile = isProfiling() ? new trace::Profile() : NULL;

    QList<ApiTraceError> errors;
    QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$");

    QString msg = QLatin1String("Replay finished!");
    QByteArray ubjsonBuffer;
    QByteArray outputBuffer;
    bool keepGoing = true;
    while(keepGoing) {
        if (!wasStarted || startTime.elapsed() > 1000) {
            QByteArray psOut;
            m_androidUtils.runAdb(psArgs, &psOut);
            processPID = extractPid(psOut);
            if (wasStarted)
                startTime.restart();
        }

        if (processPID == -1) {
            if (wasStarted) {
                break;
            } else {
                if (startTime.elapsed() > 3000) { // wait 3 seconds to start
                    emit finished(tr("Unable to start retrace on device."));
                    return;
                }
            }
            msleep(100);
            continue;
        }

        // we have a valid pid, it means the application started
        if (!wasStarted) {
            // connect the sockets
            int tries = 0;
            do {
                stdoutSocket.connectToHost(QHostAddress::LocalHost, m_stdoutPort);
            } while (!stdoutSocket.waitForConnected(100) && ++tries < 10);
            if (stdoutSocket.state() != QAbstractSocket::ConnectedState) {
                emit finished(tr("Can't connect to stdout socket."));
                return;
            }

            // Android doesn't suport GPU and PPD profiling (at leats not on my devices)
            //setProfiling(false, isProfilingCpu(), false);

            QString args = (retraceArguments() << m_androdiFileName).join(" ") + _("\n");
            stdoutSocket.write(args.toUtf8());
            if (!stdoutSocket.waitForBytesWritten()) {
                emit finished(tr("Can't send params."));
                return;
            }


            stderrSocket.connectToHost(QHostAddress::LocalHost, m_stderrPort);
            stderrSocket.waitForConnected(100);
            if (stderrSocket.state() != QAbstractSocket::ConnectedState) {
                emit finished(tr("Can't connect to stderr socket."));
                return;
            }
            wasStarted = true;
        }

        // We are going to read both channels at the same time

        // read stdout channel
        if (stdoutSocket.waitForReadyRead(100)) {
            if (captureState())
                ubjsonBuffer.append(stdoutSocket.readAll());
            else if (captureThumbnails()) {
                // read one image
                image::PNMInfo info;
                QByteArray header;
                int headerLines = 3; // assume no optional comment line
                for (int headerLine = 0; headerLine < headerLines; ++headerLine) {
                    QByteArray line = readLine(stdoutSocket);
                    if (line.isEmpty()) {
                        keepGoing = false;
                        break;
                    }
                    header += line;
                    // if header actually contains optional comment line, ...
                    if (headerLine == 1 && line[0] == '#') {
                        ++headerLines;
                    }
                }

                const char *headerEnd = image::readPNMHeader(header.constData(), header.size(), info);

                // if invalid PNM header was encountered, ...
                if (headerEnd == NULL ||
                    info.channelType != image::TYPE_UNORM8) {
                    qDebug() << "error: invalid snapshot stream encountered";
                    keepGoing = false;
                    break;
                }

                unsigned channels = info.channels;
                unsigned width = info.width;
                unsigned height = info.height;

                // qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height";

                QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888);

                int rowBytes = channels * width;
                for (int y = 0; y < height; ++y) {
                    unsigned char *scanLine = snapshot.scanLine(y);
                    if (!read(stdoutSocket, (char *) scanLine, rowBytes)) {
                        keepGoing = false;
                        break;
                    }
                }

                QImage thumb = thumbnail(snapshot);
                thumbnails.insert(info.commentNumber, thumb);
            } else if (isProfiling()) {
                QByteArray line = readLine(stdoutSocket);
                if (line.isEmpty()) {
                    keepGoing = false;
                    break;
                }
                line.append('\0');
                trace::Profiler::parseLine(line.constData(), profile);
            } else {
                outputBuffer.append(stdoutSocket.readAll());
            }
        }

        // read stderr channel
        if (stderrSocket.waitForReadyRead(5) && stderrSocket.canReadLine()) {
            QString line = stderrSocket.readLine();
            if (regexp.indexIn(line) != -1) {
                ApiTraceError error;
                error.callIndex = regexp.cap(1).toInt();
                error.type = regexp.cap(2);
                error.message = regexp.cap(3);
                errors.append(error);
            } else if (!errors.isEmpty()) {
                // Probably a multiligne message
                ApiTraceError &previous = errors.last();
                if (line.endsWith("\n")) {
                    line.chop(1);
                }
                previous.message.append('\n');
                previous.message.append(line);
            }
        }
    }

    if (outputBuffer.size() < 80)
        msg = outputBuffer;

    if (captureState()) {
        QBuffer io(&ubjsonBuffer);
        io.open(QIODevice::ReadOnly);

        parsedJson = decodeUBJSONObject(&io).toMap();
        ApiTraceState *state = new ApiTraceState(parsedJson);
        emit foundState(state);
    }

    if (captureThumbnails() && !thumbnails.isEmpty()) {
        emit foundThumbnails(thumbnails);
    }

    if (isProfiling() && profile) {
        emit foundProfile(profile);
    }

    if (!errors.isEmpty()) {
        emit retraceErrors(errors);
    }

    emit finished(msg);
}
// Refresh not up to date metrics and metrics after date
void MetricAggregator::refreshMetrics(QDateTime forceAfterThisDate)
{
    // only if we have established a connection to the database
    if (dbaccess == NULL || main->isclean==true) return;

    // first check db structure is still up to date
    // this is because metadata.xml may add new fields
    dbaccess->checkDBVersion();

    // Get a list of the ride files
    QRegExp rx = RideFileFactory::instance().rideFileRegExp();
    QStringList filenames = RideFileFactory::instance().listRideFiles(home);
    QStringListIterator i(filenames);

    // get a Hash map of statistic records and timestamps
    QSqlQuery query(dbaccess->connection());
    QHash <QString, status> dbStatus;
    bool rc = query.exec("SELECT filename, timestamp, fingerprint FROM metrics ORDER BY ride_date;");
    while (rc && query.next()) {
        status add;
        QString filename = query.value(0).toString();
        add.timestamp = query.value(1).toInt();
        add.fingerprint = query.value(2).toInt();
        dbStatus.insert(filename, add);
    }

    // begin LUW -- byproduct of turning off sync (nosync)
    dbaccess->connection().transaction();

    // Delete statistics for non-existant ride files
    QHash<QString, status>::iterator d;
    for (d = dbStatus.begin(); d != dbStatus.end(); ++d) {
        if (QFile(home.absolutePath() + "/" + d.key()).exists() == false) {
            dbaccess->deleteRide(d.key());
#ifdef GC_HAVE_LUCENE
            main->lucene->deleteRide(d.key());
#endif
        }
    }

    unsigned long zoneFingerPrint = static_cast<unsigned long>(zones->getFingerprint())
                                  + static_cast<unsigned long>(hrzones->getFingerprint()); // checksum of *all* zone data (HR and Power)

    // update statistics for ride files which are out of date
    // showing a progress bar as we go
    QTime elapsed;
    elapsed.start();
    QString title = tr("Refreshing Ride Statistics...\nStarted");
    QProgressDialog bar(title, tr("Abort"), 0, filenames.count(), main);
    bar.setWindowModality(Qt::WindowModal);
    bar.setMinimumDuration(0);
    bar.show();

    int processed=0;
    QApplication::processEvents(); // get that dialog up!

    // log of progress
    QFile log(home.absolutePath() + "/" + "metric.log");
    log.open(QIODevice::WriteOnly);
    log.resize(0);
    QTextStream out(&log);
    out << "METRIC REFRESH STARTS: " << QDateTime::currentDateTime().toString() + "\r\n";

    while (i.hasNext()) {
        QString name = i.next();
        QFile file(home.absolutePath() + "/" + name);

        // if it s missing or out of date then update it!
        status current = dbStatus.value(name);
        unsigned long dbTimeStamp = current.timestamp;
        unsigned long fingerprint = current.fingerprint;

        RideFile *ride = NULL;

        // update progress bar
        long elapsedtime = elapsed.elapsed();
        QString elapsedString = QString("%1:%2:%3").arg(elapsedtime/3600000,2)
                                                .arg((elapsedtime%3600000)/60000,2,10,QLatin1Char('0'))
                                                .arg((elapsedtime%60000)/1000,2,10,QLatin1Char('0'));
        QString title = tr("Refreshing Ride Statistics...\nElapsed: %1\n%2").arg(elapsedString).arg(name);
        bar.setLabelText(title);
        bar.setValue(++processed);
        QApplication::processEvents();

        if (dbTimeStamp < QFileInfo(file).lastModified().toTime_t() ||
            zoneFingerPrint != fingerprint ||
            (!forceAfterThisDate.isNull() && name >= forceAfterThisDate.toString("yyyy_MM_dd_hh_mm_ss"))) {
            QStringList errors;

            // log
            out << "Opening ride: " << name << "\r\n";

            // read file and process it if we didn't already...
            if (ride == NULL) ride = RideFileFactory::instance().openRideFile(main, file, errors);

            out << "File open completed: " << name << "\r\n";

            if (ride != NULL) {

                out << "Getting weight: " << name << "\r\n";
                ride->getWeight();
                out << "Updating statistics: " << name << "\r\n";
                importRide(home, ride, name, zoneFingerPrint, (dbTimeStamp > 0));

            }
        }

        // update cache (will check timestamps itself)
        // if ride wasn't opened it will do it itself
        // we only want to check so passing check=true
        // because we don't actually want the results now
        RideFileCache updater(main, home.absolutePath() + "/" + name, ride, true);

        // free memory - if needed
        if (ride) delete ride;

        if (bar.wasCanceled()) {
            out << "METRIC REFRESH CANCELLED\r\n";
            break;
        }
    }

    // end LUW -- now syncs DB
    out << "COMMIT: " << QDateTime::currentDateTime().toString() + "\r\n";
    dbaccess->connection().commit();

#ifdef GC_HAVE_LUCENE
#ifndef WIN32 // windows crashes here....
    out << "OPTIMISE: " << QDateTime::currentDateTime().toString() + "\r\n";
    main->lucene->optimise();
#endif
#endif
    main->isclean = true;

    // stop logging
    out << "SIGNAL DATA CHANGED: " << QDateTime::currentDateTime().toString() + "\r\n";
    dataChanged(); // notify models/views

    out << "METRIC REFRESH ENDS: " << QDateTime::currentDateTime().toString() + "\r\n";
    log.close();
}
Example #30
0
void Solution::run() {
    //     for ( count = 0; count < _myInstance->numPoints(); ++count ) {
    //         _pointsType[count] = CCP::Consumer;//Everyone is consumer at begin...
    //     }
    //    if (!_lock.tryLock()){
    //        return;
    //    }
    //    QProgressDialog dialog ("Progress of algorithm", "cancel", 0,100);
    //
    //    dialog.setWindowModality(Qt::WindowModal);
    if (_centers != 0){
        delete [] _centers;
    }
    QTime count;
    count.start();
    switch (_type){
    case Farthest: {
            FarthestCluster far(_myInstance);
            //            connect (&far, SIGNAL(complete(int)), &dialog, SLOT(setValue(int)));
            _centers = far.buildClusters();
            _myAlgorithmName = "Farthest";
            _myIterations = far.iterations();
            _history = far.history();
        }
        break;
    case Density: {
            DensityCluster density(_myInstance);
            //            connect (&density, SIGNAL(complete(int)), &dialog, SLOT(setValue(int)));
            _centers = density.buildClusters();
            _myAlgorithmName = "Density";
            _myIterations = density.iterations();
            _history = density.history();
        }
        break;
    case HMeans: {
            HMeansCluster hmean(_myInstance);
            //          connect (&hmean, SIGNAL(complete(int)), &dialog, SLOT(setValue(int)));
            _centers = hmean.buildClusters();
            _myAlgorithmName = "HMeans";
            _myIterations = hmean.iterations();
            _history = hmean.history();
        }break;
    case JMeans: {
            JMeansCluster jmean(_myInstance);
            //              connect (&jmean, SIGNAL(complete(int)), &dialog, SLOT(setValue(int)));
            _centers = jmean.buildClusters();
            _myAlgorithmName = "JMeans";
            _myIterations = jmean.iterations();
            _history = jmean.history();
        }break;
    case RandonDensity: {
              RandomDensityCluster randomD(_myInstance);
              _centers = randomD.buildClusters();
              _myAlgorithmName = "Randon Density";
              _history = randomD.history();
          }break;
    case DensityHMeans: {
          HMeansWithDensity hd(_myInstance);
          _centers = hd.buildClusters();
          _myAlgorithmName = "HMeans With Density";
          _history = hd.history();
    }break;
    case DensityJMeans: {
          JMeansWithDensity jd(_myInstance);
          _centers = jd.buildClusters();
          _myAlgorithmName = "JMeans With Density";
          _history = jd.history();
    }break;

    }

    _myTime = count.elapsed()/1000.0;

    //    dialog.setValue(100);
    //    _lock.unlock();

    //    emit finished();
}