コード例 #1
0
ファイル: Telnet.cpp プロジェクト: descent/Qelly
void Telnet::processBytes(QByteArray bytes)
{
    QQueue<uchar> buffer;
    foreach (uchar c, bytes)
    {
        switch (_state)
        {
        case TOP_LEVEL:
            handleStateTopLevel(c, &buffer);
            break;
        case SEENCR:
            handleStateSeenCr(c, &buffer);
            break;
        case SEENIAC:
            handleStateSeenIac(c);
            break;
        case SEENWILL:
            handleStateSeenWill(c);
            break;
        case SEENWONT:
            sendCommand(DONT, c);
            _state = TOP_LEVEL;
            break;
        case SEENDO:
            handleStateSeenDo(c);
            break;
        case SEENDONT:
            sendCommand(WONT, c);
            _state = TOP_LEVEL;
            break;
        case SEENSB:
            _sbOption = c;
            _sbBuffer->clear();
            _state = SUBNEGOT;
            break;
        case SUBNEGOT:
            if (c == IAC)
                _state = SUBNEG_IAC;
            else
                _sbBuffer->append(c);
            break;
        case SUBNEG_IAC:
            handleStateSubNegIac(c);
            break;
        default:
            break;
        }
    }

    int chunk_sz = 256;
    while (!buffer.isEmpty())
    {
        QByteArray data;
        int length = buffer.size() < chunk_sz ? buffer.size() : chunk_sz;
        for (int i = 0; i < length; i++)
            data.append(buffer.dequeue());
        emit processedBytes(data);
    }
}
コード例 #2
0
KisPaintInformation
KisToolFreehandHelper::Private::getStabilizedPaintInfo(const QQueue<KisPaintInformation> &queue,
        const KisPaintInformation &lastPaintInfo)
{
    KisPaintInformation result(lastPaintInfo);

    if (queue.size() > 1) {
        QQueue<KisPaintInformation>::const_iterator it = queue.constBegin();
        QQueue<KisPaintInformation>::const_iterator end = queue.constEnd();

        /**
         * The first point is going to be overridden by lastPaintInfo, skip it.
         */
        it++;
        int i = 2;

        if (smoothingOptions->stabilizeSensors()) {
            while (it != end) {
                qreal k = qreal(i - 1) / i; // coeff for uniform averaging
                result = KisPaintInformation::mix(k, *it, result);
                it++;
                i++;
            }
        } else {
            while (it != end) {
                qreal k = qreal(i - 1) / i; // coeff for uniform averaging
                result = KisPaintInformation::mixOnlyPosition(k, *it, result);
                it++;
                i++;
            }
        }
    }

    return result;
}
コード例 #3
0
ファイル: main.cpp プロジェクト: Czhian/QtAV
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    FrameReader r;
    r.setMedia(a.arguments().last());
    QQueue<qint64> t;
    int count = 0;
    qint64 t0 = QDateTime::currentMSecsSinceEpoch();
    while (r.readMore()) {
        while (r.hasEnoughVideoFrames()) {
            const VideoFrame f = r.getVideoFrame(); //TODO: if eof
            if (!f)
                continue;
            count++;
            //r.readMore();
            const qint64 now = QDateTime::currentMSecsSinceEpoch();
            const qint64 dt = now - t0;
            t.enqueue(now);
            printf("decode @%.3f count: %d, elapsed: %lld, fps: %.1f/%.1f\r", f.timestamp(), count, dt, count*1000.0/dt, t.size()*1000.0/(now - t.first()));fflush(0);
            if (t.size() > 10)
                t.dequeue();
        }
    }
    while (r.hasVideoFrame()) {
        const VideoFrame f = r.getVideoFrame();
        qDebug("pts: %.3f", f.timestamp());
    }
    qDebug("read done");
    return 0;
}
コード例 #4
0
int BleRtmpSendThread::service(BleRtmpMuxer & muxer)
{
    int ret = BLE_SUCESS;

    if ((ret = sendVideoSh(muxer)) != BLE_SUCESS) {
        return ret;
    }

    if ((ret = sendAudioSh(muxer)) != BLE_SUCESS) {
        return ret;
    }

    while (!m_stop) {
        QQueue<BleAVPacket *> pkts = BleAVQueue::instance()->dequeue();
        if (pkts.isEmpty()) {
            msleep(50);
            continue;
        }

        BleAutoLocker(m_mutex);

        while (!pkts.empty()) {
            BleAVPacket *pkt = pkts.dequeue();
            BleAutoFree(BleAVPacket, pkt);

            MStream &data = pkt->data;

            if (pkt->pktType == Packet_Type_Video) {
                if (muxer.addH264(data, pkt->dts) != TRUE ) {
                    ret = BLE_RTMPSEND_ERROR;
                    break;
                }

                m_videoKbps += (data.size() + 11);
                m_fps += 1;
            } else if (pkt->pktType == Packet_Type_Audio) {
                if (muxer.addAAC(data, pkt->dts) != TRUE ) {
                    ret = BLE_RTMPSEND_ERROR;
                    break;
                }

                m_audioKbps += (data.size() + 11);
            }

            m_sendDataCount += (data.size() + 11);
        }

        // if send failed, then pkts may has some pkt
        // we should delete it.
        for (int i = 0; i < pkts.size(); ++i) {
            BleAVPacket *pkt = pkts.at(i);
            BleFree(pkt);
        }
    }

    return ret;
}
コード例 #5
0
ファイル: grafo.cpp プロジェクト: pcamarillor/Exploratory3D
int Grafo::indexElementoMenor(QQueue<vertice*> cola)
{
    int indexMin = 0;
    for(int i = 0; i < cola.size(); i++)
    {
        if(cola.at(i)->costoHastaAhora < cola.at(indexMin)->costoHastaAhora)
            indexMin = i;
    }
    return indexMin;
}
コード例 #6
0
void OpenstreetmapMapProvider::startDownload(QQueue<Tile>& queue)
{
    mIsRunning = true;

    while (queue.size() > 0)
    {
        Tile info = queue.dequeue();
        fetchTile(info);
    }
}
コード例 #7
0
ファイル: main.cpp プロジェクト: AramKS/Mif39
/*
Send-Import:
    Count 1658 bytes
    Dict Size 76272 bytes
    Data Size 91315785 bytes
    Total Size 91392057 bytes
Recv-Export:
    Count 1616 bytes
    Dict Size 74340 bytes
    Data Size 91309561 bytes
    Total Size 91383901 bytes
*/
int main ( int argc, char** argv ) {
    /*
    __attach();
    __attachInterfaces();
    __attachGenerics();
    __attachAssets();*/
    __attachQImage();
    __attachWavefront();

    recvCB [ UUIDManager::createUUID("AssetImplementation::World") ] = OnReceiveWorld;
    recvCB [ UUIDManager::createUUID("AssetImplementation::WorldCell") ] = OnReceiveWorldCell;
    recvCB [ UUIDManager::createUUID("AssetImplementation::GameObject") ] = OnReceiveGameObject;
    recvCB [ UUIDManager::createUUID("AssetImplementation::GameEntity") ] = OnReceiveGameEntity;
    recvCB [ UUIDManager::createUUID("AssetImplementation::Light") ] = OnReceiveLight;
    recvCB [ UUIDManager::createUUID("AssetImplementation::Image") ] = OnReceiveImage;
    recvCB [ UUIDManager::createUUID("AssetImplementation::WavefrontMaterial") ] = OnReceiveWavefrontMaterial;
    recvCB [ UUIDManager::createUUID("AssetImplementation::Mesh") ] = OnReceiveMesh;

    SimpleTcpEndPoint::Options options;
    options.serverIP = "127.0.0.1";
    options.connectionPort = 3000;
    SimpleTcpEndPoint client ( options );
    if ( client.open() == false ) exit ( -1 );
    // reception de l'UUID du monde
    QUuid worldID = receiveUUID(client);
    fetchResource(worldID);
    while ( true ) {
        if ( resourceToFetch.size() > 0 ) {
            QUuid uuid = resourceToFetch.dequeue();
            if ( recvResources.find(uuid)==recvResources.end () ) {
                sendUUID(client, uuid);
                receiveResource(client);
            }
        }
        else break;
    }
    std::cout << "Received " << received << " bytes" << std::endl;
    /*
    sendUUID(client,worldID);
    Assets::WorldPtr world = receiveResource(client).dynamicCast<Assets::World>();
    std::cout << world->mTypeID.toString().toStdString() << std::endl;
    std::cout << UUIDManager::createUUID("AssetImplementation::World").toString().toStdString() << std::endl;
    for ( int i = 0 ; i < world->getSize < QUuid > ( "Cells" ) ; i ++ ) {
        sendUUID(client,world->get < QUuid > ( "Cells", i ));
        Assets::WorldCellPtr cell = receiveResource(client).dynamicCast<Assets::WorldCell>();
    }
    */
    client.close ();
    ResourceHolder::Export( "world.binary" );
    return 0;
}
コード例 #8
0
void QuickAndroidTests::loading()
{
    QStringList res;
    QQueue<QString> queue;
    queue.enqueue(":/QuickAndroid");

    QQmlEngine engine;
    engine.addImportPath("qrc:///");

    while (queue.size()) {
        QString path = queue.dequeue();
        QDir dir(path);
        QFileInfoList infos = dir.entryInfoList(QStringList());
        for (int i = 0 ; i < infos.size();i++) {
            QFileInfo info = infos.at(i);
            if (info.fileName() == "." || info.fileName() == "..")
                continue;
            if (info.isDir()) {
                queue.enqueue(info.absoluteFilePath());
                continue;
            }
            QUrl url = info.absoluteFilePath().remove(0,1);
            url.setScheme("qrc");

            if (info.suffix() != "qml") {
                continue;
            }

            QFile file(":" + url.path());
            QVERIFY(file.open(QIODevice::ReadOnly));
            QString content = file.readAll();
            content = content.toLower();

            // Skip singleton module as it can not be loaded directly
            if (content.indexOf("pragma singleton") != -1) {
                qDebug() << QString("%1 : Skipped (singleton)").arg(url.toString());
                continue;
            }

            QQmlComponent comp(&engine);
            comp.loadUrl(url);
            if (comp.isError()) {
                qDebug() << QString("%1 : Load Failed. Reason :  %2").arg(info.absoluteFilePath()).arg(comp.errorString());
            }
            QVERIFY(!comp.isError());

            qDebug() << QString("%1 : Passed").arg(info.absoluteFilePath());
        }
    }
}
コード例 #9
0
ファイル: trafficgraphwidget.cpp プロジェクト: OFCoin/OFCCoin
void TrafficGraphWidget::paintPath(QPainterPath &path, QQueue<float> &samples)
{
    int h = height() - YMARGIN * 2, w = width() - XMARGIN * 2;
    int sampleCount = samples.size(), x = XMARGIN + w, y;
    if(sampleCount > 0) {
        path.moveTo(x, YMARGIN + h);
        for(int i = 0; i < sampleCount; ++i) {
            x = XMARGIN + w - w * i / DESIRED_SAMPLES;
            y = YMARGIN + h - (int)(h * samples.at(i) / fMax);
            path.lineTo(x, y);
        }
        path.lineTo(x, YMARGIN + h);
    }
}
コード例 #10
0
void MainWindow::on_horizontalScrollBar_sliderMoved(int position) {
    QString q = QString::number(widget.PlotView0->xAxis->range().size(), 0, 0);
    //    qDebug(q.toStdString().c_str());

    int n = (qLL.size()) / 100000;

    if (qAbs(widget.PlotView0->xAxis->range().center() - position) > 0.01) // if user is dragging plot, we don't want to replot twice
    {
        widget.PlotView0->xAxis->setRange((n + 1) * position, widget.PlotView0->xAxis->range().size(), Qt::AlignLeft);
        widget.PlotView0->replot();
    }
    if (qAbs(widget.PlotView1->xAxis->range().center() - position) > 0.01) // if user is dragging plot, we don't want to replot twice
    {
        widget.PlotView1->xAxis->setRange((n + 1) * position, widget.PlotView1->xAxis->range().size(), Qt::AlignLeft);
        widget.PlotView1->replot();
    }

}
コード例 #11
0
void MainWindow::ffmpegGraphPlot(QQueue<int> LL, QQueue<int> RR) {
    qLL = LL;
    qRR = RR;

    widget.PlotView0->addGraph();
    widget.PlotView0->graph()->setPen(QPen(Qt::blue));
    widget.PlotView0->graph()->setBrush(QBrush(QColor(0, 0, 255, 20)));
    widget.PlotView0->graph()->setPen(QPen(Qt::red));

    widget.PlotView1->addGraph();
    widget.PlotView1->graph()->setPen(QPen(Qt::blue));
    widget.PlotView1->graph()->setBrush(QBrush(QColor(0, 0, 255, 20)));
    widget.PlotView1->graph()->setPen(QPen(Qt::red));

    //int size = qLL.size();
    int size = LL.size() / 5;
    QVector<double> x0(size), y0(size); // initialize with entries 0..100
    QVector<double> x1(size), y1(size); // initialize with entries 0..100

    for (int i = 0; i < size; i += 1) {
        x0[i] = i; // x goes from -1 to 1
        y0[i] = LL.at(i); // let's plot a quadratic function
        //        y1[i] = LL.at(i+1); // let's plot a quadratic function
        //        y0[i] = rand()*1000;
        //        cout<<LL.at(i)<<endl;
        //        y1[i] = Samples[100000 + i + 1] / 20; // let's plot a quadratic function
    }

    widget.PlotView0->addGraph();
    widget.PlotView0->graph(0)->setData(x0, y0);

    widget.PlotView0->xAxis->setRange(0, 1000);
    widget.PlotView0->yAxis->setRange(-255, 255);
    widget.PlotView0->replot();

    widget.PlotView1->addGraph();
    widget.PlotView1->graph(0)->setData(x0, y0);

    widget.PlotView1->xAxis->setRange(0, 1000);
    widget.PlotView1->yAxis->setRange(-255, 255);
    widget.PlotView1->replot();

    cout << size << endl;
}
コード例 #12
0
void BleEncoderThread::run()
{
    BleImageProcessThread * imageProcessThread = dynamic_cast<BleImageProcessThread *> (m_imageProcessThread);
    BleAssert(imageProcessThread);

    while (!m_stop) {
        QQueue<BleImage*> images = BleAVContext::instance()->captureThread->getQueue();

        // if can't get image, then sleep 50 ms.
        if (images.isEmpty()) {
            msleep(5);
            continue;
        }

        while (!images.empty()) {
            BleImage * image = images.dequeue();
            BleAutoFree(BleImage, image);

            if (image->dataSize <= 0) continue;

            IplImage* imgYUV = cvCreateImage(cvSize(image->width, image->height * 3 / 2), IPL_DEPTH_8U, 1);
            IplImage *cvImage = cvCreateImageHeader(cvSize(image->width, image->height), IPL_DEPTH_8U, 3);
            cvImage->imageData = image->data;
            cvImage->imageDataOrigin = image->data;

            cvCvtColor(cvImage, imgYUV, CV_BGR2YUV_I420);

            m_x264Encoder->encode((uchar*)imgYUV->imageData, image->pts, image->opaque);

            cvReleaseImageHeader(&cvImage);
            cvReleaseImage(&imgYUV);

            if (m_stop) break;
        }

        // do clean
        for (int i = 0; i > images.size(); ++i) {
            BleImage *img = images.at(i);
            BleFree(img);
        }
    }

    log_trace("BleEncoderThread exit normally.");
}
コード例 #13
0
ファイル: data.cpp プロジェクト: AndyQsmart/QtMusic-1.0
QQueue<QString> Data::getListList()
{
    tryConnectListList();
    QQueue <QString> q;
    QSqlQuery query;
    query.exec("select * from listlist order by id;");
    while (query.next())
    {
        q.push_back(query.value(0).toString());
        qDebug() << "Get list" << query.value(1).toInt() << ":" << query.value(0).toString()<< endl;
    }
    if (q.size() == 0)
    {
        query.exec("insert into listlist"
                   "(name, id, count) values('默认列表', 0, 0);");
        Data::changeListCount(1);
        q.push_back(QString("默认列表"));
        qDebug() << "Create list:默认列表" << endl;
    }
    return q;
}
コード例 #14
0
ファイル: data.cpp プロジェクト: AndyQsmart/QtMusic-1.0
QQueue<MusicInfo> Data::getMusicList(QString listName)
{
    tryConnectMusicList();
    listName = listName.replace("'", "''");
    QQueue <MusicInfo> q;
    MusicInfo musicInfo;
    QSqlQuery query;
    query.exec("select * from musiclist where listname = '"+listName+"' order by id;");
    while (query.next())
    {
        musicInfo.setDir(query.value(2).toString());
        musicInfo.setName(query.value(3).toString());
        musicInfo.setArtist(query.value(4).toString());
        q.push_back(musicInfo);
        qDebug() << "Get music:" << query.value(3).toString() << endl;
    }
    int all = q.size();
    query.exec("select * from listlist;");
    QString str =
            QString("update listlist set count = %1 "
                    "where name = '%2';").arg(all).arg(listName);
    query.exec(str);
    return q;
}
コード例 #15
0
//protected
void MapGraphicsView::doTileLayout()
{
    //Calculate the center point and polygon of the viewport in QGraphicsScene coordinates
    const QPointF centerPointQGS = _childView->mapToScene(_childView->width()/2.0,
                                                          _childView->height()/2.0);
    QPolygon viewportPolygonQGV;
    viewportPolygonQGV << QPoint(0,0) << QPoint(0,_childView->height()) << QPoint(_childView->width(),_childView->height()) << QPoint(_childView->width(),0);

    const QPolygonF viewportPolygonQGS = _childView->mapToScene(viewportPolygonQGV);
    const QRectF boundingRect = viewportPolygonQGS.boundingRect();

    //We exaggerate the bounding rect for some purposes!
    QRectF exaggeratedBoundingRect = boundingRect;
    exaggeratedBoundingRect.setSize(boundingRect.size()*2.0);
    exaggeratedBoundingRect.moveCenter(boundingRect.center());

    //We'll mark tiles that aren't being displayed as free so we can use them
    QQueue<MapTileGraphicsObject *> freeTiles;

    QSet<QPointF> placesWhereTilesAre;
    foreach(MapTileGraphicsObject * tileObject, _tileObjects)
    {
        if (!tileObject->isVisible() || !exaggeratedBoundingRect.contains(tileObject->pos()))
        {
            freeTiles.enqueue(tileObject);
            tileObject->setVisible(false);
        }
        else
            placesWhereTilesAre.insert(tileObject->pos());
    }

    const quint16 tileSize = _tileSource->tileSize();
    const quint32 tilesPerRow = sqrt((long double)_tileSource->tilesOnZoomLevel(this->zoomLevel()));
    const quint32 tilesPerCol = tilesPerRow;

    const qint32 perSide = qMax(boundingRect.width()/tileSize,
                       boundingRect.height()/tileSize) + 3;
    const qint32 xc = qMax((qint32)0,
                     (qint32)(centerPointQGS.x() / tileSize) - perSide/2);
    const qint32 yc = qMax((qint32)0,
                     (qint32)(centerPointQGS.y() / tileSize) - perSide/2);
    const qint32 xMax = qMin((qint32)tilesPerRow,
                              xc + perSide);
    const qint32 yMax = qMin(yc + perSide,
                              (qint32)tilesPerCol);

    for (qint32 x = xc; x < xMax; x++)
    {
        for (qint32 y = yc; y < yMax; y++)
        {
            const QPointF scenePos(x*tileSize + tileSize/2,
                                   y*tileSize + tileSize/2);


            bool tileIsThere = false;
            if (placesWhereTilesAre.contains(scenePos))
                tileIsThere = true;

            if (tileIsThere)
                continue;

            //Just in case we're running low on free tiles, add one
            if (freeTiles.isEmpty())
            {
                MapTileGraphicsObject * tileObject = new MapTileGraphicsObject(tileSize);
                tileObject->setTileSource(_tileSource);
                _tileObjects.insert(tileObject);
                _childScene->addItem(tileObject);
                freeTiles.enqueue(tileObject);
            }
            //Get the first free tile and make it do its thing
            MapTileGraphicsObject * tileObject = freeTiles.dequeue();
            if (tileObject->pos() != scenePos)
                tileObject->setPos(scenePos);
            if (tileObject->isVisible() != true)
                tileObject->setVisible(true);
            tileObject->setTile(x,y,this->zoomLevel());
        }
    }

    //If we've got a lot of free tiles left over, delete some of them
    while (freeTiles.size() > 2)
    {
        MapTileGraphicsObject * tileObject = freeTiles.dequeue();
        _tileObjects.remove(tileObject);
        _childScene->removeItem(tileObject);
        delete tileObject;
    }

}
コード例 #16
0
ファイル: ProcessModel.cpp プロジェクト: DrSobik/IPPS
void ProcessModel::dynUpdateTopolSort(QList<ListDigraph::Node> &topolOrdering, const ListDigraph::Node &i, const ListDigraph::Node &k) {
	QTextStream out(stdout);

	/** Algorithm:
	 * 
	 * 1. Find the positions of i and k
	 * 2. IF posi < posk => no changes to the topological sorting needs to be performed. Return.
	 * 3. IF posi > posk => reorder the nodes. The affected region is [posi, posk]. Return.
	 */

	int posi = -1;
	int posk = -1;

	if (k == INVALID) {
		posk = (int) Math::MAX_INTUNI;
	} else {
		posk = topolOrdering.indexOf(k);
	}

	if (i == INVALID) {
		posi = 0;
	} else {
		posi = topolOrdering.indexOf(i);
	}

	if (posi < posk) { // No changes to perform
		return;
	}

	// #####################  DEBUG  ###########################################

	/*
	out << "Before DTO:" << endl;
	out << "posj = " << posj << " ID = " << ((j == INVALID) ? -1 : pm->ops[j]->ID) << endl;
	out << "posi = " << posi << " ID = " << ((i == INVALID) ? -1 : pm->ops[i]->ID) << endl;
	out << "posk = " << posk << " ID = " << ((k == INVALID) ? -1 : pm->ops[k]->ID) << endl;

	for (int l = 0; l < topolOrdering.size(); l++) {
		out << pm->ops[topolOrdering[l]]->ID << " ";
	}
	out << endl;

	//getchar();
	 */

	// #########################################################################

	if (posi == posk) {
		out << "posi = " << posi << " ID = " << ((i == INVALID) ? -1 : this->ops[i]->ID) << endl;
		out << "posk = " << posk << " ID = " << ((k == INVALID) ? -1 : this->ops[k]->ID) << endl;

		for (int l = 0; l < topolOrdering.size(); l++) {
			out << this->ops[topolOrdering[l]]->ID << " ";
		}
		out << endl;

		Debugger::err << "ProcessModel::dynUpdateTopolSort : posi == posk which is impossible!!!" << ENDL;
	}

	// Find the affected region
	int arbegin = -1;
	int arend = -1;
	ListDigraph::Node arstartnode = INVALID;
	ListDigraph::Node arendnode = INVALID;

	if (posi > posk) {
		arbegin = posk;
		arend = posi;
		arstartnode = k;
		arendnode = i;
	}

	// #####################  DEBUG  ###########################################
	/*
	out << "arbegin = " << arbegin << endl;
	out << "arend = " << arend << endl;
	out << "arstartnode = " << pm->ops[arstartnode]->ID << endl;
	out << "arendnode = " << pm->ops[arendnode]->ID << endl;
	 */
	// #########################################################################

	// Update the affected region

	// The nodes of the affected region
	QList<ListDigraph::Node> ar = topolOrdering.mid(arbegin, arend - arbegin + 1);
	QList<bool> visited;
	visited.reserve(ar.size());
	QQueue<ListDigraph::Node> q;
	ListDigraph::Node curnode;
	ListDigraph::Node tmpnode;
	int tmpidx;
	//QList<int> deltaBIdx;

	// #####################  DEBUG  ###########################################

	/*
	out << "ar:" << endl;
	for (int l = 0; l < ar.size(); l++) {
		out << pm->ops[ar[l]]->ID << " ";
	}
	out << endl;
	 */

	// #########################################################################

	// Find nodes which are contained in ar and are reachable from arstartnode
	//out << "Finding deltaF..." << endl;
	QList<ListDigraph::Node> deltaF;

	deltaF.reserve(ar.size());

	for (int l = 0; l < ar.size(); l++) {
		visited.append(false);
	}

	q.clear();
	q.enqueue(arstartnode);

	deltaF.append(arstartnode);
	while (q.size() != 0) {
		curnode = q.dequeue();

		// Check the successors of the current node
		for (ListDigraph::OutArcIt oait(this->graph, curnode); oait != INVALID; ++oait) {
			tmpnode = this->graph.target(oait);

			tmpidx = ar.indexOf(tmpnode);

			if (tmpidx >= 0 && !visited[tmpidx]) { // This successor is within the affected region
				q.enqueue(tmpnode);
				visited[tmpidx] = true;

				// Add the node to the deltaF
				deltaF.append(tmpnode);

			}

		}
	}

	//out << "Found deltaF." << endl;

	//######################  DEBUG  ###########################################
	/*
	out << "deltaF:" << endl;
	for (int l = 0; l < deltaF.size(); l++) {
		out << pm->ops[deltaF[l]]->ID << " ";
	}
	out << endl;
	 */
	//##########################################################################

	// IMPORTANT!!! Actually deltaB is not needed! If we find deltaF and move it to the end of the affected region then the elements
	// of deltaB preserve their initial positions and are placed directly before the elements of deltaF. Thus, the backward arc becomes a forward one
	/*
	// Find the nodes which are in ar and are BACKWARD reachable from arendnode
	QList<ListDigraph::Node> deltaB;

	deltaB.reserve(ar.size());

	for (int l = 0; l < visited.size(); l++) {
		visited[l] = false;
	}

	q.clear();
	q.enqueue(arendnode);

	deltaB.prepend(arendnode);
	deltaBIdx.prepend(ar.size() - 1);

	visited.clear();
	for (int l = 0; l < ar.size(); l++) {
		visited.append(false);
	}
	while (q.size() != 0) {
		curnode = q.dequeue();

		// Check the predecessors of the current node
		for (ListDigraph::InArcIt iait(pm->graph, curnode); iait != INVALID; ++iait) {
			tmpnode = pm->graph.source(iait);

			tmpidx = ar.indexOf(tmpnode);

			if (tmpidx >= 0 && !visited[tmpidx]) { // This successor is within the affected region
				q.enqueue(tmpnode);
				visited[tmpidx] = true;

				// Add the node to the deltaF
				deltaB.prepend(tmpnode); // IMPORTANT!!! PREpend!
				deltaBIdx.prepend(tmpidx);
			}

		}
	}
	 */

	// Move elements of deltaB to the left and the elements of deltaF to the right until the backward ark does not disappear
	//int posB = 0;
	//out << "Shifting deltaF to the right..." << endl;
	int posF = ar.size() - 1;

	// Move elements in deltaF to the right
	while (!deltaF.isEmpty()) {
		// Find the first element in ar starting from posB that is in deltaB
		tmpidx = -1;
		for (int l = posF; l >= 0; l--) {
			if (deltaF.contains(ar[l])) {
				tmpidx = l;
				break;
			}
		}

		if (tmpidx == -1) {
			Debugger::err << "ProcessModel::dynUpdateTopolSort : tmpidx = -1 while shifting deltaF. Probably the graph is NOT DAG! " << ENDL;
		}

		// Erase this element from deltaF
		deltaF.removeOne(ar[tmpidx]);

		// Move this element to the left
		ar.move(tmpidx, posF);
		posF--;
	}
	//out << "Shifted deltaF to the right." << endl;

	// Moving elements of deltaB is not necessary, since they are automatically found before any element of deltaF, since these were moved to the right

	/*
	// Move elements in deltaB to the left so that the last element of deltaB is on the position posF (right before elements of deltaF)
	while (!deltaB.isEmpty()) {
		// Find the first element in ar starting from posB that is in deltaB
		tmpidx = -1;
		for (int l = posB; l < ar.size(); l++) {
			if (deltaB.contains(ar[l])) {
				tmpidx = l;
				break;
			}
		}

		// Erase this element from deltaB
		deltaB.removeOne(ar[tmpidx]);

		// Move this element to the left
		ar.move(tmpidx, posB);
		posB++;
	}
	 */


	// Modify the final topological ordering
	for (int l = 0; l < ar.size(); l++) {
		topolOrdering[arbegin + l] = ar[l];
	}

	//######################  DEBUG  ###########################################

	/*
	out << "After DTO:" << endl;
	out << "posj = " << posj << " ID = " << ((j == INVALID) ? -1 : pm->ops[j]->ID) << endl;
	out << "posi = " << posi << " ID = " << ((i == INVALID) ? -1 : pm->ops[i]->ID) << endl;
	out << "posk = " << posk << " ID = " << ((k == INVALID) ? -1 : pm->ops[k]->ID) << endl;

	out << "ar later:" << endl;
	for (int l = 0; l < ar.size(); l++) {
		out << pm->ops[ar[l]]->ID << " ";
	}
	out << endl;

	//out << "deltaB:" << endl;
	//for (int l = 0; l < deltaB.size(); l++) {
	//out << pm->ops[deltaB[l]]->ID << " ";
	//}
	//out << endl;

	out << "deltaF:" << endl;
	for (int l = 0; l < deltaF.size(); l++) {
		out << pm->ops[deltaF[l]]->ID << " ";
	}
	out << endl;

	for (int l = 0; l < topolOrdering.size(); l++) {
		out << pm->ops[topolOrdering[l]]->ID << " ";
	}
	out << endl;
	 */

	// Check the correctness of the topological sorting

	/*
	QList<ListDigraph::Node> list;
	for (int i = 0; i < topolOrdering.size() - 1; i++) {
		for (int j = i + 1; j < topolOrdering.size(); j++) {
			list.clear();
			list.append(topolOrdering[j]);
			if (reachableFrom(list).contains(topolOrdering[i])) {
				out << *this << endl;
				out << this->ops[topolOrdering[j]]->ID << " -> " << this->ops[topolOrdering[i]]->ID << endl;
				Debugger::err << "Topological sorting is not correct after DTO!!!" << ENDL;
			}
		}
	}
	 */


	//getchar();

	//##########################################################################   
}
コード例 #17
0
ファイル: timelistener.cpp プロジェクト: athairus/MicroTimer
void TimeListener::printStatistics() {
    // Print this many times per second
    // The more often you print, the less reliable the results due to overhead
    // 1 or less recommended
    static qreal perSecond = 2;

    // Use the average of the last __ print statements' data to determine the rolling average
    static qreal rollingAverageSeconds = 10;

    // Don't modify the stuff below (or do... I'm a comment not a cop)
    static qreal rollingAverageTurnover = perSecond * rollingAverageSeconds;
    static int mod = frequency / perSecond;
    static int modCounter = 1;
    static qreal runningTotalHz = 0;
    static QQueue<qreal> numbersQueue;
    static qreal numbersQueueSum = 0;

    if( !timer.isValid() ) {
        timer.start();
    }

    // Print statistics every (mod) calls to this function
    if( modCounter % mod == 0 ) {
        qreal time = ( qreal )timer.nsecsElapsed();
        timer.restart();
        qreal currentFreq = 1.0 / ( time / ( ( qreal )mod * 1000000000.0 ) );
        numbersQueueSum += currentFreq;
        numbersQueue.enqueue( currentFreq );

        // Start removing old entries once past the first __ print statements
        if( numbersQueue.size() > rollingAverageTurnover ) {
            numbersQueueSum -= numbersQueue.dequeue();
        }

        runningTotalHz += currentFreq;
        qreal averageHz = ( qreal )runningTotalHz / modCounter * mod;
        qreal averageMs = 1000.0 / averageHz;

        qreal deltaHz = qAbs( currentFreq - frequency );
        qreal deltaUs = qAbs( ( 1000000.0 / currentFreq ) - ( 1000000.0 / frequency ) );

        qreal rollingAverageHz = numbersQueueSum / numbersQueue.size();
        qreal rollingAverageMs = 1000.0 / rollingAverageHz;
        QString rollingAverageString( "---" );

        qreal rollingDeltaHz = qAbs( rollingAverageHz - frequency );
        qreal rollingDeltaUs = qAbs( ( 1000000.0 / rollingAverageHz ) - ( 1000000.0 / frequency ) );
        QString rollingDeltaString( "---" );

        if( numbersQueue.size() >= rollingAverageTurnover ) {
            rollingAverageString = QString( "%1Hz/%2ms" ).arg( rollingAverageHz ).arg( rollingAverageMs );
            rollingDeltaString = QString( "%1Hz/%2us" ).arg( rollingDeltaHz ).arg( rollingDeltaUs );
        }

        qDebug().nospace().noquote()
                << "last " << ( perSecond != 1 ? QString( "%1 seconds: " ).arg( 1.0 / perSecond ) : QString( "second: " ) )
                << currentFreq << "Hz/" << 1000 / currentFreq << "ms, "
                << "session average: " << averageHz << "Hz/" << averageMs << "ms, "
                << "rolling average (" << rollingAverageTurnover / perSecond << "s): " << rollingAverageString << ", "
                << "delta: " << deltaHz << "Hz/" << deltaUs << "us, "
                << "rolling delta (" << rollingAverageTurnover / perSecond << "s): " << rollingDeltaString << " ";
    }

    modCounter++;
}
コード例 #18
0
void MovingMinMaxAvgTests::runAllTests() {
    {
        // quint64 test

        const int INTERVAL_LENGTH = 100;
        const int WINDOW_INTERVALS = 50;

        MovingMinMaxAvg<quint64> stats(INTERVAL_LENGTH, WINDOW_INTERVALS);

        quint64 min = std::numeric_limits<quint64>::max();
        quint64 max = 0;
        double average = 0.0;
        int totalSamples = 0;

        quint64 windowMin;
        quint64 windowMax;
        double windowAverage;

        QQueue<quint64> windowSamples;
        // fill window samples
        for (int i = 0; i < 100000; i++) {

            quint64 sample = randQuint64();

            windowSamples.enqueue(sample);
            if (windowSamples.size() > INTERVAL_LENGTH * WINDOW_INTERVALS) {
                windowSamples.dequeue();
            }

            stats.update(sample);

            min = std::min(min, sample);
            max = std::max(max, sample);
            average = (average * totalSamples + sample) / (totalSamples + 1);
            totalSamples++;

            assert(stats.getMin() == min);
            assert(stats.getMax() == max);
            assert(fabsf((float)stats.getAverage() / (float)average - 1.0f) < EPSILON ||
                   fabsf((float)stats.getAverage() - (float)average) < EPSILON);

            if ((i + 1) % INTERVAL_LENGTH == 0) {

                assert(stats.getNewStatsAvailableFlag());
                stats.clearNewStatsAvailableFlag();

                windowMin = std::numeric_limits<quint64>::max();
                windowMax = 0;
                windowAverage = 0.0;
                foreach(quint64 s, windowSamples) {
                    windowMin = std::min(windowMin, s);
                    windowMax = std::max(windowMax, s);
                    windowAverage += (double)s;
                }
                windowAverage /= (double)windowSamples.size();

                assert(stats.getWindowMin() == windowMin);
                assert(stats.getWindowMax() == windowMax);
                assert(fabsf((float)stats.getAverage() / (float)average - 1.0f) < EPSILON ||
                       fabsf((float)stats.getAverage() - (float)average) < EPSILON);

            } else {
コード例 #19
0
void MovingMinMaxAvgTests::testInt() {
    // int test

    const int INTERVAL_LENGTH = 1;
    const int WINDOW_INTERVALS = 75;

    MovingMinMaxAvg<int> stats(INTERVAL_LENGTH, WINDOW_INTERVALS);

    int min = std::numeric_limits<int>::max();
    int max = 0;
    double average = 0.0;
    int totalSamples = 0;

    int windowMin;
    int windowMax;
    double windowAverage;

    QQueue<int> windowSamples;
    // fill window samples
    for (int i = 0; i < 100000; i++) {

        int sample = rand();

        windowSamples.enqueue(sample);
        if (windowSamples.size() > INTERVAL_LENGTH * WINDOW_INTERVALS) {
            windowSamples.dequeue();
        }

        stats.update(sample);

        min = std::min(min, sample);
        max = std::max(max, sample);
        average = (average * totalSamples + sample) / (totalSamples + 1);
        totalSamples++;

        QCOMPARE(stats.getMin(), min);
        QCOMPARE(stats.getMax(), max);
        QCOMPARE_WITH_ABS_ERROR((float)stats.getAverage(), (float)average, EPSILON);

        if ((i + 1) % INTERVAL_LENGTH == 0) {

            QVERIFY(stats.getNewStatsAvailableFlag());
            stats.clearNewStatsAvailableFlag();

            windowMin = std::numeric_limits<int>::max();
            windowMax = 0;
            windowAverage = 0.0;
            for (int s : windowSamples) {
                windowMin = std::min(windowMin, s);
                windowMax = std::max(windowMax, s);
                windowAverage += (double)s;
            }
            windowAverage /= (double)windowSamples.size();

            QCOMPARE(stats.getWindowMin(), windowMin);
            QCOMPARE(stats.getWindowMax(), windowMax);
            QCOMPARE_WITH_ABS_ERROR((float)stats.getAverage(), (float)average, EPSILON);
        } else {
            QVERIFY(!stats.getNewStatsAvailableFlag());
        }
    }
}
コード例 #20
0
ファイル: AgentF.cpp プロジェクト: loh-tar/filu
void AgentF::cloneIsReady() // Slot
{
  if(!mRolex)
  {
    mRolex = new QElapsedTimer;
    mRolex->start();
  }

  // Search the clone waiting for a job
  QProcess* clone = 0;
  QString   cloneName;
  for(int i = 0; i < mClones.size(); ++i)
  {
    if(mClones.at(i)->bytesAvailable() == 0) continue;

    clone = mClones.at(i);
    cloneName = mCloneNames.at(i);
    break;
  }

  if(!clone)
  {
    fatal(FUNC, "Curious, no clone found.");
    return; // No more todo
  }

  QString text(clone->readAllStandardOutput());

  if(!text.contains("[READY]")) return;

  QString feedTxt = tr("Feed clone %1: ").arg(cloneName);

  // Feed the clone
  if(mCommands.size() > 0)
  {
    bool tooSlow = false;

    if(mCommands.at(0).at(0) == "this")
    {
      static const int minTimeLag = mRcFile->getIT("MinTimeLag");
      static const int maxTimeLag = mRcFile->getIT("MaxTimeLag");
      static QQueue<int> lagLst;

      lagLst.enqueue(mRolex->elapsed());
      if(lagLst.size() > 5) lagLst.dequeue();

      if(mRolex->elapsed() < minTimeLag)
      {
        verbose(FUNC, tr("Don't ask the provider too rapidly. Will sleep %1ms")
                         .arg(minTimeLag - mRolex->elapsed()), eAmple);
        FTool::sleep(minTimeLag - mRolex->elapsed());
      }
      else
      {
        int avgLag = 0;
        foreach(int lag, lagLst) avgLag += lag;
        avgLag /= lagLst.size();

        verbose(FUNC, tr("AvgTimeLag is %1ms").arg(avgLag), eAmple);
        if(avgLag > maxTimeLag)
        {
          tooSlow = true;
        }
      }

      mRolex->restart();
    }

    QString cmd = mCommands.at(0).join(" ");
    verbose(FUNC, feedTxt + cmd.toUtf8(), eInfo);

    cmd.append("\n");
    clone->write(cmd.toUtf8());

    mCommands.removeAt(0);

    if(tooSlow) startClone();
  }
コード例 #21
0
ファイル: SpeedGraph.cpp プロジェクト: LubosD/fatrat
void SpeedGraph::draw(QQueue<QPair<int,int> > data, QSize size, QPaintDevice* device, QPaintEvent* event)
{
	int top = 0;
	QPainter painter(device);
	int seconds = getSettingsValue("graphminutes").toInt()*60;
	bool bFilled = getSettingsValue("graph_style").toInt() == 0;

	painter.setRenderHint(QPainter::Antialiasing);

	if(event != 0)
	{
		painter.setClipRegion(event->region());
		painter.fillRect(event->rect(), QBrush(Qt::white));
	}
	else
		painter.fillRect(QRect(QPoint(0, 0), size), QBrush(Qt::white));

	if(!data.size())
	{
		drawNoData(size, painter);
		return;
	}

	for(int i=0;i<data.size();i++)
	{
		top = qMax(top, qMax(data[i].first,data[i].second));
	}
	if(!top || data.size()<2)
	{
		drawNoData(size, painter);
		return;
	}

	top = qMax(top/10*11,10*1024);

	const int height = size.height();
	const int width = size.width();
	const int elems = data.size();
	qreal perpt = width / (qreal(qMax(elems,seconds))-1);
	qreal pos = width;
	QVector<QLine> lines(elems);
	QVector<QPoint> filler(elems+2);

	for(int i = 0;i<data.size();i++) // download speed
	{
		float y = height-height/qreal(top)*data[elems-i-1].first;
		filler[i] = QPoint(pos, y);
		if(i > 0)
			lines[i-1] = QLine(filler[i-1], filler[i]);
		pos -= perpt;
	}
	filler[elems] = QPoint(filler[elems-1].x(), height);
	filler[elems+1] = QPoint(filler[0].x(), height);
	
	painter.setPen(Qt::darkBlue);
	
	if(bFilled)
	{
		QColor blueFill(Qt::darkBlue);
		blueFill.setAlpha(64);
		painter.setBrush(blueFill);
		painter.drawPolygon(filler.constData(), filler.size(), Qt::OddEvenFill);
	}
	
	lines[elems-1] = QLine(2,7,12,7);
	painter.drawLines(lines.constData(), lines.size());
	
	pos = width;
	for(int i = 0;i<elems;i++) // upload speed
	{
		float y = height-height/qreal(top)*data[elems-i-1].second;
		filler[i] = QPoint(pos, y);
		if(i > 0)
			lines[i-1] = QLine(filler[i-1], filler[i]);
		pos -= perpt;
	}
	filler[elems] = QPoint(filler[elems-1].x(), height);
	filler[elems+1] = QPoint(filler[0].x(), height);
	
	painter.setPen(Qt::darkRed);
	
	if(bFilled)
	{
		QColor redFill(Qt::darkRed);
		redFill.setAlpha(64);
		painter.setBrush(redFill);
		painter.drawPolygon(filler.constData(), filler.size(), Qt::OddEvenFill);
	}
	
	lines[elems-1] = QLine(2,19,12,19);
	painter.drawLines(lines.constData(), lines.size());
	
	painter.setPen(Qt::black);
	for(int i=0;i<4;i++)
	{
		int x = width-(i+1)*(width/4);
		painter.drawLine(x, height, x, height-15);
		painter.drawText(x+2, height-2, tr("%1 mins ago").arg( (seconds/4) * (i+1) / 60.0 ));
	}
	
	painter.drawText(15,12,tr("Download"));
	painter.drawText(15,24,tr("Upload"));
	
	for(int i=1;i<10;i++)
	{
		int pos = int( float(height)/10.f*i );
		
		painter.setPen(QPen(Qt::gray, 1.0, Qt::DashLine));
		painter.drawLine(0,pos,width,pos);
		
		painter.setPen(Qt::black);
		painter.drawText(0,pos-10,formatSize( qulonglong( top/10.f*(10-i) ), true));
	}
}
コード例 #22
0
ファイル: ControlGraph.cpp プロジェクト: assutech/isis3
 /**
  *  Determines whether or not islands exist and calculates what they are if
  *  present
  */
 void ControlGraph::CalculateIslands()
 {
   // assume subgraphs exist! (check assumption at the very end of the method)
   
   // A search list has a value for every cube, which defaults to false.
   // A breadth-first search is used to test connectivity and works by setting
   // each cubes cooresponding search list value to true as it is visited.
   // At the end of the first round the true entries make up the first
   // subgragh.  As they are added to the first subgraph they are removed from
   // the search list.  The remaining false entries must have the breadth-first
   // search done on them to determine the next subgraph(s).  This process
   // continues until all entries in the search list are true (until all cubes
   // have been visited)
   QMap< int, bool > searchList;
   for (int i = 0; i < graph->size(); i++)
     searchList.insert(i, false);
 
   // For each subgraph keep a list of the cubes in the subgraph.  This is 
   // represented by a 2d vector where the inner vectors are cubes within a
   // subgraph and the outer vector is a list of subgraphs
   islands = new QVector< QVector< int > >();
   
   // keeps track of which itteration of the breadth-first search we are on and
   // thus also which subgraph we are currently populating
   int subgraphIndex = -1;
   
   while (searchList.size())
   {
     // create a new subgraph
     subgraphIndex++;
     islands->push_back(QVector< int >());
     
     // The queue used for breadth-first searching
     QQueue< int > q;
     
     // visit the first cube
     searchList.begin().value() = true;
     q.enqueue(searchList.begin().key());
     
     // visit all cubes possible using the breadth-first approach
     while (q.size())
     {
       int curVertex(q.dequeue());
       QVector< int > adjacentVertices = graph->find(curVertex).value().first
           .GetAdjacentCubes();
  
       for (int i = 0; i < adjacentVertices.size(); i++)
       {
         const int & curNeighbor = adjacentVertices[i];
         
         ASSERT(searchList.find(curNeighbor) != searchList.end());
         
         if (!searchList.find(curNeighbor).value())
         {
           searchList.find(curNeighbor).value() = true;
           q.enqueue(curNeighbor);
         }
       }
     } // end of breadth-first search
     
     // add all true entries to the current subgraph
     QMap< int, bool >::iterator i = searchList.begin();
     while (i != searchList.end())
     {
       if (i.value())
       {
         (*islands)[subgraphIndex].push_back(i.key());
       }
       i++;
     }
     
     // remove all the true entries from the search list
     for (int i = 0; i < (*islands)[subgraphIndex].size(); i++)
     {
       searchList.remove((*islands)[subgraphIndex][i]);
     }
   }
   
   // if there was only ever one subgraph created then the initial assumption
   // was wrong!  There are no islands at all - this is a connected graph!
   if (subgraphIndex == 0)
   {
     islands->clear();
   }
 }