Пример #1
0
void QWebFramePrivate::renderPrivate(QPainter *painter, const QRegion &clip, bool contents)
{
    if (!frame->view() || !frame->contentRenderer())
        return;

    QVector<QRect> vector = clip.rects();
    if (vector.isEmpty())
        return;

    WebCore::FrameView* view = frame->view();
    view->layoutIfNeededRecursive();

    GraphicsContext context(painter);

    if (!contents)
        view->paint(&context, vector.first());
    else
        view->paintContents(&context, vector.first());

    for (int i = 1; i < vector.size(); ++i) {
        const QRect& clipRect = vector.at(i);
        painter->save();
        painter->setClipRect(clipRect, Qt::IntersectClip);
        if (!contents)
            view->paint(&context, clipRect);
        else
            view->paintContents(&context, clipRect);
        painter->restore();
    }
}
Пример #2
0
ScriptEngine *loadEngine(const QString &language, Types::ComponentType type, QObject *parent,
    const QVariantList &args = QVariantList())
{
    Q_UNUSED(parent);

    ScriptEngine *engine = 0;

    auto filter = [&language](const KPluginMetaData &md) -> bool
    {
        return md.value(QStringLiteral("X-Plasma-API")) == language;
    };
    QVector<KPluginMetaData> plugins = KPluginLoader::findPlugins(QStringLiteral("plasma/scriptengines"), filter);

    if (!plugins.isEmpty()) {
        const QStringList componentTypes = KPluginMetaData::readStringList(plugins.first().rawData(), QStringLiteral("X-Plasma-ComponentTypes"));
        if (((type & Types::AppletComponent)     && !componentTypes.contains(QStringLiteral("Applet")))
         || ((type & Types::DataEngineComponent) && !componentTypes.contains(QStringLiteral("DataEngine")))) {

            qCWarning(LOG_PLASMA) << "ScriptEngine" << plugins.first().name() << "does not provide Applet or DataEngine components, returning empty.";
            return 0;
        }
        KPluginLoader loader(plugins.first().fileName());
        KPluginFactory *factory = loader.factory();
        if (factory) {
            engine = factory->create<Plasma::ScriptEngine>(0, args);
        } else {
            qCWarning(LOG_PLASMA) << "Unable to load" << plugins.first().name() << "ScriptEngine";
        }
    }

    return engine;
}
Пример #3
0
void PlotterWindow::plotSpectr(HyperCube *ptrCube, uint dataX, uint dataY)
{

    quint16 Chnls = ptrCube->GetCountofChannels();
    qint16* pSpectrValues = new qint16[Chnls];
    try{    //если можем получить точку гиперкуба
        ptrCube->GetSpectrumPoint(dataX, dataY,pSpectrValues); // записали в pSpectrValues из гиперкуба
        QVector<double> xArr(Chnls), yArr(Chnls);
        for (quint16 i = 0; i < Chnls; ++i )
        {
           xArr[i] = i;
           yArr[i] = pSpectrValues[i];
        }

        QVector<double> sortedYArr;
        sortedYArr = yArr;
        qSort(sortedYArr);
        if (sortedYArr.first() < minY )
            minY = sortedYArr.first();
        if (sortedYArr.last() > maxY )
            maxY = sortedYArr.last();
        QString grafName;
        grafName.append("X:");
        grafName.append(QString::number(dataX));
        grafName.append(" Y:");
        grafName.append(QString::number(dataY));
        m_customPlot->setInteraction(QCP::iRangeDrag , true);
        m_customPlot->setInteraction(QCP::iRangeZoom  , true);

        m_customPlot->legend->setVisible(true);
        if (!m_hold)
            m_customPlot->clearGraphs();

        m_customPlot->addGraph();
        if (m_customPlot->graphCount() == 1) // первый график всегда черного цвета, остальные - рандомные
            m_customPlot->graph()->setPen(QPen(Qt::black));
        else
        {
           QColor color;
           int limit = 256;
           int randR = qrand() % limit;
           int randG = qrand() % limit;
           int randB = qrand() % limit;
           color.setRgb(randR,randG,randB);
           m_customPlot->graph()->setPen(QPen(color));
        }
        m_customPlot->graph()->setName(grafName);
        m_customPlot->graph()->setData(xArr,yArr);
        m_customPlot->xAxis->setRange(xArr.first(),xArr.last());
        m_customPlot->yAxis->setRange(minY,maxY);
        m_customPlot->replot();
    }catch(...){
        m_customPlot->replot();
    }
    delete pSpectrValues;



}
Пример #4
0
LayerTileSet LayerTileSet::fromLayer(const Layer &layer)
{
	const QVector<Tile> tiles = layer.tiles();
	const int cols = Tile::roundTiles(layer.width());

	Q_ASSERT(!tiles.isEmpty());

	QVector<TileRun> runs;

	// First, Run Length Encode the tile vector
	runs << TileRun { tiles.first(), 0, 0, 1, tiles.first().solidColor() };

	for(int i=1;i<tiles.size();++i) {
		if(runs.last().len < 0xffff && runs.last().tile.equals(tiles.at(i))) {
			runs.last().len++;
		} else {
			runs << TileRun { tiles.at(i), i%cols, i/cols, 1, tiles.at(i).solidColor() };
		}
	}

	// Count the number of solid color tiles.
	QHash<quint32, int> colors;
	for(const TileRun &tr : runs) {
		if(tr.color.isValid())
			colors[tr.color.rgba()] += tr.len;
	}

	// If half of the tiles are of the same
	// solid color, use that as the background color.
	// Otherwise, transparency is a safe default choice.
	QColor background = Qt::transparent;
	const int treshold = tiles.length() / 2;
	for(QHash<quint32, int>::const_iterator i = colors.constBegin();i!=colors.constEnd();++i) {
		if(i.value() >= treshold) {
			background = QColor::fromRgba(i.key());
			break;
		}
	}

	// Remove solid color tiles that match the background
	QMutableVectorIterator<TileRun> tri(runs);
	while(tri.hasNext()) {
		if(tri.next().color == background)
			tri.remove();
	}

	// All done!
	return LayerTileSet {
		runs,
		background
	};
}
void BlobWindow::on_loadBtn_clicked()
{
    QString name = ui->loadNameEdt->text();
    QSqlQuery query;
    QString qry_string = "SELECT floatsVec FROM Blobs WHERE Name='%1'";
    query.exec(qry_string.arg(name));
    query.first();
    QByteArray data = query.value("floatsVec").toByteArray();
    qDebug() << data.toHex() << __func__;
    QVector<myType> *vec = unBlobifyCustom(data);

    qDebug() << vec->first().flt << vec->first().bl << __func__;
}
Пример #6
0
void ParserTests::testMemcheckSample3()
{
    MSKIP_SINGLE("testfile does not exist");

    initTest(QLatin1String("memcheck-output-sample3.xml"));

    Valgrind::XmlProtocol::Parser parser;
    Recorder rec(&parser);

    parser.parse(m_socket);

    m_process->waitForFinished();
    QCOMPARE(m_process->exitStatus(), QProcess::NormalExit);
    QCOMPARE(m_process->state(), QProcess::NotRunning);
    QVERIFY2(parser.errorString().isEmpty(), qPrintable(parser.errorString()));

    const QList<Error> errors = rec.errors;
    QCOMPARE(errors.size(), 6);

    {
        const Error error = errors.at(0);
        const QVector<Stack> stacks = error.stacks();

        QCOMPARE(error.unique(), 0x1ll);
        QCOMPARE(error.what(), QLatin1String("Conditional jump or move depends on uninitialised value(s)"));
        QCOMPARE(error.kind(), UninitCondition);
        QCOMPARE(stacks.size(), 1);
        QCOMPARE(stacks.first().frames().size(), 12);
        QVERIFY(!error.suppression().isNull());
        QCOMPARE(error.suppression().frames().count(), stacks.first().frames().size());
        QCOMPARE(error.suppression().kind(), QLatin1String("Memcheck:Cond"));
        QVERIFY(!error.suppression().rawText().trimmed().isEmpty());

        // rawtext contains <...> while <name></name> does not
        QCOMPARE(error.suppression().name(), QLatin1String("insert_a_suppression_name_here"));
        Suppression sup = error.suppression();
        sup.setName(QLatin1String("<insert_a_suppression_name_here>"));
        QCOMPARE(sup.toString().trimmed(), sup.rawText().trimmed());

        QCOMPARE(error.suppression().frames().first().object(),
                 QLatin1String("/usr/lib/kde4/plugins/styles/qtcurve.so"));
        QVERIFY(error.suppression().frames().first().function().isEmpty());
        QCOMPARE(error.suppression().frames().last().function(), QLatin1String("main"));
        QVERIFY(error.suppression().frames().last().object().isEmpty());
    }

    QCOMPARE(rec.suppcounts.count(), 3);
    QCOMPARE(rec.suppcounts.at(0).second, qint64(1));
    QCOMPARE(rec.suppcounts.at(1).second, qint64(2));
    QCOMPARE(rec.suppcounts.at(2).second, qint64(3));
}
Пример #7
0
void Entity::initialize()
{
    QByteArray vsrc =
        "attribute highp vec4 vertexAttr;\n"
        "attribute highp vec2 texAttr;\n"
        "uniform mediump mat4 matrix;\n"
        "varying highp vec2 texCoord;\n"
        "void main(void)\n"
        "{\n"
        "    texCoord = texAttr;\n"
        "    gl_Position = matrix * vertexAttr;\n"
        "}\n";

    QByteArray fsrc =
        "uniform sampler2D texture;\n"
        "varying highp vec2 texCoord;\n"
        "void main(void)\n"
        "{\n"
        "    gl_FragColor = texture2D(texture, texCoord);\n"
        "}\n";

    m_program = generateShaderProgram(this, vsrc, fsrc);

    m_vertexAttr = m_program->attributeLocation("vertexAttr");
    m_texAttr = m_program->attributeLocation("texAttr");
    m_matrixUniform = m_program->uniformLocation("matrix");

    QVector<QImage> images = loadSoldierImages();
    int w = images.first().width() + 2;
    int h = images.first().height() + 2;

    m_tileMod = (images.size() + 3) / 4;

    QImage image(m_tileMod * w, 4 * h, QImage::Format_ARGB32_Premultiplied);
    image.fill(Qt::transparent);

    QPainter p(&image);
    p.setCompositionMode(QPainter::CompositionMode_Source);
    for (int i = 0; i < images.size(); ++i)
        p.drawImage(w * (i % m_tileMod) + 1, h * (i / m_tileMod) + 1, images.at(i));
    p.end();

    qDebug() << "Initialized soldier image" << image.size();

    m_tileWidth = w;
    m_tileHeight = h;

    m_texture = generateTexture(image, false, false);
    m_textureSize = image.size();
}
Пример #8
0
QPointF RoundCornersCommand::tangentAtStart(const KoPathSegment &s)
{
    QVector<QPointF> cp = s.controlPoints();
    QPointF tn = cp[1] - cp.first();
    qreal length = sqrt(tn.x() * tn.x() + tn.y() * tn.y());
    return tn / length;
}
Пример #9
0
static bool
isVariantEditable(const QVariant &var)
{
    if (var.canConvert<ApiArray>()) {
        ApiArray array = var.value<ApiArray>();
        QVector<QVariant> vals = array.values();
        if (vals.isEmpty())
            return false;
        else
            return isVariantEditable(vals.first());
    }
    switch (var.userType()) {
    case QVariant::Bool:
    case QVariant::Int:
    case QVariant::UInt:
    case QVariant::LongLong:
    case QVariant::ULongLong:
    case QMetaType::Float:
    case QVariant::Double:
    case QVariant::String:
        return true;
    default:
        return false;
    }
}
Пример #10
0
AMRange AMUtility::rangeFinder(const QVector<double> &data, double valueToIgnore)
{
	AMRange range = AMRange();

	if (!data.isEmpty()){

		double minimum = data.first();
		double maximum = minimum;

		for (int i = 1, size = data.size(); i < size; i++){

			double value = data.at(i);

			if (value < minimum && value != valueToIgnore)
				minimum = value;

			if (value > maximum && value != valueToIgnore)
				maximum = value;
		}

		range.setRange(minimum, maximum);
	}

	return range;
}
Пример #11
0
// static
double BeatUtils::calculateFixedTempoFirstBeat(
    bool enableOffsetCorrection,
    const QVector<double> rawbeats, const int sampleRate,
    const int totalSamples, const double globalBpm) {
    if (rawbeats.size() == 0) {
        return 0;
    }

    if (!enableOffsetCorrection) {
        return rawbeats.first();
    }

    QVector <double> corrbeats;
    // Length of a beat at globalBpm in mono samples.
    const double beat_length = 60.0 * sampleRate / globalBpm;


    double firstCorrectBeat = findFirstCorrectBeat(
        rawbeats, sampleRate, globalBpm);

    // We start building a fixed beat grid at globalBpm and the first beat from
    // rawbeats that matches globalBpm.
    double i = firstCorrectBeat;
    while (i <= totalSamples) {
        corrbeats << i;
        i += beat_length;
    }

    if (rawbeats.size() == 1 || corrbeats.size()==1) {
        return firstCorrectBeat;
    }

    /*
     * calculateOffset compares the beats from the analyzer and the
     * beats from the beat grid constructed above in corrbeats.
     */
    // qDebug() << "Calculating best offset";
    // double offset = calculateOffset(rawbeats, globalBpm, corrbeats, sampleRate);
    // // Adjust firstCorrectBeat by offset
    // firstCorrectBeat += offset;


    // Find the smallest positive beat that is linked to firstCorrectBeat by
    // beat_length steps.
    double FirstFrame = firstCorrectBeat;
    while (FirstFrame < 0) {
        FirstFrame += beat_length;
    }
    while (FirstFrame > beat_length) {
        FirstFrame -= beat_length;
    }

    // Round to nearest integer.
    double firstBeat = floor(FirstFrame + 0.5);
    if (sDebug) {
        qDebug() << "calculateFixedTempoFirstBeat chose a first beat at frame" << firstBeat
                 << "while the first raw beat was at" << rawbeats.at(0);
    }
    return firstBeat;
}
Пример #12
0
double BeatUtils::findFirstCorrectBeat(const QVector<double> rawbeats,
                                       const int SampleRate, const double global_bpm) {
    for (int i = N; i < rawbeats.size(); i++) {
        // get start and end sample of the beats
        double start_sample = rawbeats.at(i-N);
        double end_sample = rawbeats.at(i);

        // The time in seconds represented by this sample range.
        double time = (end_sample - start_sample)/SampleRate;

        // Average BPM within this sample range.
        double avg_bpm = 60.0 * N / time;

        //qDebug() << "Local BPM between beat " << (i-N) << " and " << i << " is " << avg_bpm;

        // If the local BPM is within kCorrectBeatLocalBpmEpsilon of the global
        // BPM then use this window as the first beat.
        if (fabs(global_bpm - avg_bpm) <= kCorrectBeatLocalBpmEpsilon) {
            //qDebug() << "Using beat " << (i-N) << " as first beat";
            return start_sample;
        }
    }

    // If we didn't find any beat that matched the window, return the first
    // beat.
    return !rawbeats.empty() ? rawbeats.first() : 0.0;
}
Пример #13
0
void SaveBurstsDual(const QVector<BurstDual> &burstVectorDual, const QString filename)
{
    QFile file;
    if(filename.isEmpty()) qFatal("SaveBursts: enter a valid filename");
    else file.setFileName(filename);
    if(burstVectorDual.size()==0) AlexEvalLog::warning("No dual bursts to save!");
    if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) AlexEvalLog::warning(file.errorString());
    QTextStream out(&file);
    out.setRealNumberPrecision(11);
    out <<"# ALEX dual bursts\n# "<<burstVectorDual.size()<<" bursts were analyzed.\n";

    out<<burstVectorDual.first().toStringHeader().c_str();
    for(int i=0;i<burstVectorDual.size();++i) {
        out<<burstVectorDual.at(i).toString("",", ").c_str()<<"\n";
    }
    AlexEvalLog::text(burstVectorDual.size()+"bursts written to file "+file.fileName());
    file.close();

    //    out <<"# start time in s\tburst duration in ms\tproximity ratio\tstoichiometry ratio\tnumber of photons\tn_Dem_Dex\tn_Aem_Dex\tn_Dem_Aex\tn_Aem_Aex\tduration Dem in ms\tduration Aem in ms\tPR_RAW\tS_RAW\ttype\n";

    //    for(int i=0;i<burstVectorDual.size();++i) {
    //        out <<burstVectorDual.at(i).startTime<<"\t"<<burstVectorDual.at(i).duration*1e3<<"\t"
    //           <<burstVectorDual.at(i).proximityRatio<<"\t"<<burstVectorDual.at(i).stoichiometryRatio<<"\t"<<burstVectorDual.at(i).numberOfPhotons<<"\t"
    //           <<burstVectorDual.at(i).n_Dem_Dex<<"\t"<<burstVectorDual.at(i).n_Aem_Dex<<"\t"<<burstVectorDual.at(i).n_Dem_Aex<<"\t"<<burstVectorDual.at(i).n_Aem_Aex<<"\t"<<burstVectorDual.at(i).durationDonor*1e3<<"\t"<<burstVectorDual.at(i).durationAcceptor*1e3<<"\t"<<burstVectorDual.at(i).proximityRatioRaw<<"\t"<<burstVectorDual.at(i).stoichiometryRatioRaw<<"\t"<<(int)burstVectorDual.at(i).type<<"\n";
    //    }

}
Пример #14
0
GameVersionChoiceDialog::GameVersionChoiceDialog(const QList <BTech::GameVersion> &allowedVersions)
	: QDialog()
{
	setFixedSize(200, 300);

	QVBoxLayout *checkBoxLayout = new QVBoxLayout;
	checkBoxLayout->setAlignment(Qt::AlignTop);

	QVector <QCheckBox *> checkBox;
	group = new QButtonGroup;
	group->setExclusive(true);
	for (BTech::GameVersion version : allowedVersions) {
		checkBox << new QCheckBox(BTech::gameVersionStringChange[version]);
		group->addButton(checkBox.last());
		checkBoxLayout->addWidget(checkBox.last());
	}
	checkBox.first()->setChecked(true);

	QVBoxLayout *layout = new QVBoxLayout;

	layout->addItem(checkBoxLayout);

	confirmButton = new QPushButton(BTech::Strings::ButtonConfirm);
	connect(confirmButton, &QPushButton::pressed, this, &GameVersionChoiceDialog::accept);
	layout->addWidget(confirmButton);

	setLayout(layout);
}
Пример #15
0
void ParserTests::testMemcheckSample2()
{
    MSKIP_SINGLE("testfile does not exist");

    initTest(QLatin1String("memcheck-output-sample2.xml"));

    Valgrind::XmlProtocol::Parser parser;
    Recorder rec(&parser);

    parser.parse(m_socket);

    m_process->waitForFinished();
    QCOMPARE(m_process->exitStatus(), QProcess::NormalExit);
    QCOMPARE(m_process->state(), QProcess::NotRunning);
    QVERIFY2(parser.errorString().isEmpty(), qPrintable(parser.errorString()));

    //tests: multiple stacks with auxwhat == stack count - 1.
    //the first auxwhat should be assigned to the _second_ stack.
    const QList<Error> errors = rec.errors;
    QCOMPARE(errors.size(), 1);
    const QVector<Stack> stacks = errors.first().stacks();
    QCOMPARE(stacks.size(), 2);
    QCOMPARE(stacks.first().auxWhat(), QString());
    QCOMPARE(stacks.last().auxWhat(), QLatin1String("Address 0x11b66c50 is 0 bytes inside a block of size 16 free'd"));
}
Пример #16
0
ScriptEngine *loadEngine(const QString &language, Types::ComponentType type, QObject *parent,
    const QVariantList &args = QVariantList())
{
    ScriptEngine *engine = 0;

    auto filter = [&language](const KPluginMetaData &md) -> bool
    {
        return md.value(QStringLiteral("X-Plasma-API")) == language;
    };
    QVector<KPluginMetaData> plugins = KPluginLoader::findPlugins(QStringLiteral("plasma/scriptengines"), filter);

    if (plugins.count()) {
        const QString componentTypes = plugins.first().value(QStringLiteral("X-Plasma-ComponentTypes"));
        if (((type & Types::AppletComponent)     && componentTypes != QLatin1String("Applet"))
         || ((type & Types::DataEngineComponent) && componentTypes != QLatin1String("DataEngine"))) {
            return 0;
        }
        KPluginInfo::List lst = KPluginInfo::fromMetaData(plugins);
        KPluginLoader loader(lst.first().libraryPath());
        KPluginFactory *factory = loader.factory();
        if (factory) {
            engine = factory->create<Plasma::ScriptEngine>(0, args);
        }
    }

    return engine;
}
Пример #17
0
void GeneticAlgorithm::run()
{
    initGenerator();

    for (int i = 0; i < GA_MAXITER; i++) {

        QList<double> *points = new QList<double>();
        for( int j = 0; j < GA_POWER; j++){
            points->append(m_genotype.at(j).x);
        }
        emit updatePoints(points);
        reproductionOperator();
        mutationOperator();
        reductionOperator();


        QVector<gene> tmp = m_genotype;
        tmp.removeAll(tmp.first());
        if (tmp.isEmpty()) {
            qDebug() << "EARLY END";
            qDebug() << "Total iterations: " << i;
            break;
        }
    }

    qDebug() << "Result:" << m_genotype.last().fitness;

}
QVector<double> ActorHighLevel::lowPass(QVector<double> in, double alpha)
{
    int l = in.length();
    if (l == 0)
        return QVector< double >();

    // Gewichtung berechnen, falls auf default (0)
    if(alpha == 0){
        double rate     = 1.0 / config::actorPeriodMotionControl;
        double slowRate = 1.0 / (config::actorPeriodMotionControl+1);
        alpha = rate / (rate + slowRate);
    }

    // Vorwärts filtern
    QVector< double > forward(l);
    forward.first() = in.first();
    for(int i=1; i < l; ++i){
        forward[i]  = alpha * in[i]  + (1-alpha) * in[i-1];
    }

    // Rückwärts filtern
    QVector< double > backward(l);
    backward.last() = in.last();
    for(int i=l-2; i >= 0; --i){
        backward[i]  = alpha * in[i]  + (1-alpha) * in[i+1];
    }

    // Überlagern
    QVector< double > out(l);
    for(int i=0; i < l; ++i){
        out[i]  = (forward[i]  + backward[i] ) / 2;
    }

    return out;
}
Пример #19
0
void TimeSeriesMotion::ifft(const QVector<std::complex<double> >& in, QVector<double>& out ) const
{
/*
#ifdef USE_IFFTW
    // Copy the input QVector into a double array
    fftw_complex* inArray = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * in.size());

    for( int i = 0; i < in.size(); i++ ) {
        inArray[i][0] = in.at(i).real();
        inArray[i][1] = in.at(i).imag();
    }    

    // Allocate the space for the output
    int n = 2 * (in.size() - 1);
    double* outArray = (double*)fftw_malloc(sizeof(double) * n);

    // Create the plan and execute the FFT
    fftw_plan p = fftw_plan_dft_c2r_1d(n, inArray, outArray, FFTW_ESTIMATE);
    fftw_execute(p);

    // Copy the data to the output QVector and normalize by QVector length
    out.resize(n);
    for (int i = 0; i < out.size(); i++) {
        out[i] = outArray[i] / out.size();
    }

    // Free the memory
    fftw_destroy_plan(p);
    fftw_free(inArray);
    fftw_free(outArray);
*/
    const int n = 2 * (in.size() - 1);
    double *d = new double[n];

    d[0] = in.first().real();
    for (int i = 1; i < in.size(); ++i) {
        d[i] = in.at(i).real();
        d[n - i] = in.at(i).imag();
    }
    d[n / 2] = in.last().real();

#if USE_FFTW
    fftw_plan p = fftw_plan_r2r_1d(n, d, d, FFTW_HC2R, FFTW_ESTIMATE);
    fftw_execute(p);

    for (int i = 0; i < n; ++i) {
        // Scale by n
        d[i] /= n;
    }
#else
    gsl_fft_halfcomplex_radix2_inverse(d, 1, n);
#endif

    // Copy results to output
    out.resize(n);
    memcpy(out.data(), d, n * sizeof(double));

    delete [] d;
}
Пример #20
0
void KTracks::on_acSelect_triggered()
{
   QModelIndexList selection = ui->tvTracks->selectionModel()->selectedRows();
   QAbstractItemModel *model = ui->tvTracks->model();

   if (!selection.isEmpty()) {
       QList<QGeoPositionInfo> trackList;
       trackList.clear();
       trackList = sql.selTrack(model->data(model->index(selection.at(0).row(),0)).toInt());

       ui->cpPlot->clearGraphs();
       ui->cpPlot->addGraph();

       QGeoPositionInfo tp;
       QVector<double> x;
       QVector<double> y;
       int cnt = trackList.count();
       x.resize(cnt);
       y.resize(cnt);

       //options
       int pType;
       if (ui->miAltitude->isChecked()) {
           ui->cpPlot->yAxis->setLabel("Altitude [m]");
           pType = 1; }
       if (ui->miDistance->isChecked()) {
           ui->cpPlot->yAxis->setLabel("Distance [m]");
           pType = 2; }
       if (ui->miSpeed->isChecked()) {
           ui->cpPlot->yAxis->setLabel("Speed [m/s]");
           pType = 3; }
       ui->cpPlot->xAxis->setLabel("time [hh:mm:ss]");

       for (int i=0; i<cnt; i++) {
           tp = trackList.value(i);
           x[i] = tp.timestamp().toTime_t();
           switch (pType) {
             case 1: {
               y[i] = tp.coordinate().altitude();
               break; }
             case 2: {
               y[i] = tp.coordinate().distanceTo(trackList.value(0).coordinate());
               break; }
             case 3: {
               y[i] = tp.attribute(QGeoPositionInfo::GroundSpeed);
               break; }
           } //switch
       } //for to

       ui->cpPlot->graph(0)->setData(x,y);
       // set axes ranges, so we see all data:
       ui->cpPlot->xAxis->setRange(x[0],x[cnt-1]);
       qSort(y.begin(), y.end());
       ui->cpPlot->yAxis->setRange(y.first(),y.last());
       //repaint
       ui->cpPlot->replot();

   } //selection.isempty
}
Пример #21
0
BookmarksModel::Bookmark* BookmarksManager::getBookmark(const QUrl &url)
{
	ensureInitialized();

	const QVector<BookmarksModel::Bookmark*> bookmarks(m_model->getBookmarks(url));

	return (bookmarks.isEmpty() ? nullptr : bookmarks.first());
}
Пример #22
0
void TourCaptureDialog::loadDestinationFile()
{
    const QVector<MovieFormat> formats = m_recorder->availableFormats();
    if( formats.isEmpty() ) {
        QMessageBox::warning( this, tr( "Codecs are unavailable" ), tr( "Supported codecs are not found." ) );
        return;
    }
    QString filter = formats.first().name() + QLatin1String(" (*.") + formats.first().extension() + QLatin1Char(')');
    for( int i = 1; i < formats.size(); i++ )
    {
        filter += QLatin1String(";;") + formats.at(i).name() + QLatin1String(" (*.") + formats.at(i).extension() + QLatin1Char(')');
    }
    const QString defaultFileName =
            ui->destinationEdit->text().isEmpty() ? m_defaultFileName : ui->destinationEdit->text();

    const QString destination =
            QFileDialog::getSaveFileName(this, tr("Save video file"), defaultFileName,
                                         filter );

    if (destination.isEmpty()) {
        return;
    }

    bool supported = false;
    foreach(const MovieFormat &format, formats) {
        if (destination.endsWith(QLatin1Char('.') + format.extension())) {
            supported = true;
            break;
        }
    }

    if (!supported) {
        QString formatsExtensions = QLatin1Char('.') + formats.at(0).extension();
        for( int i = 1; i < formats.size(); ++i )
        {
            formatsExtensions += QLatin1String(", .") + formats.at(i).extension();
        }
        QMessageBox::warning(this, tr("Filename is not valid"),
                             tr("This file format is not supported. "
                                "Please, use %1 instead").arg( formatsExtensions ) );
        return;
    }

    ui->destinationEdit->setText(destination);
    m_recorder->setFilename(destination);
}
Пример #23
0
void SearchWidget::streetSelected(QListWidgetItem *item)
{
    QVector<int> segmentLength;
    QVector<UnsignedCoordinate> coordinates;
    if (m_addrLookup->GetStreetData(item->text(), &segmentLength, &coordinates)) {
        GPSCoordinate coord = coordinates.first().ToGPSCoordinate();
        emit centerOn(coord.longitude, coord.latitude);
    }
}
Пример #24
0
HelpViewer *HelpPlugin::createHelpViewer(qreal zoom)
{
    // check for backends
    typedef std::function<HelpViewer *()> ViewerFactory;
    typedef QPair<QByteArray, ViewerFactory>  ViewerFactoryItem; // id -> factory
    QVector<ViewerFactoryItem> factories;
#ifndef QT_NO_WEBKIT
    factories.append(qMakePair(QByteArray("qtwebkit"), []() { return new QtWebKitHelpViewer(); }));
#endif
#ifdef QTC_WEBENGINE_HELPVIEWER
    factories.append(qMakePair(QByteArray("qtwebengine"), []() { return new WebEngineHelpViewer(); }));
#endif
    factories.append(qMakePair(QByteArray("textbrowser"), []() { return new TextBrowserHelpViewer(); }));

#ifdef QTC_MAC_NATIVE_HELPVIEWER
    // default setting
#ifdef QTC_MAC_NATIVE_HELPVIEWER_DEFAULT
     factories.prepend(qMakePair(QByteArray("native"), []() { return new MacWebKitHelpViewer(); }));
#else
     factories.append(qMakePair(QByteArray("native"), []() { return new MacWebKitHelpViewer(); }));
#endif
#endif

    HelpViewer *viewer = nullptr;

    // check requested backend
    const QByteArray backend = qgetenv("QTC_HELPVIEWER_BACKEND");
    if (!backend.isEmpty()) {
        const int pos = Utils::indexOf(factories, [backend](const ViewerFactoryItem &item) {
            return backend == item.first;
        });
        if (pos == -1) {
            qWarning("Help viewer backend \"%s\" not found, using default.", backend.constData());
        } else {
            viewer  = factories.at(pos).second();
        }
    }

    if (!viewer)
        viewer = factories.first().second();
    QTC_ASSERT(viewer, return nullptr);

    // initialize font
    viewer->setViewerFont(LocalHelpManager::fallbackFont());
    connect(LocalHelpManager::instance(), &LocalHelpManager::fallbackFontChanged,
            viewer, &HelpViewer::setViewerFont);

    // initialize zoom
    viewer->setScale(zoom);

    // add find support
    Aggregation::Aggregate *agg = new Aggregation::Aggregate();
    agg->add(viewer);
    agg->add(new HelpViewerFindSupport(viewer));

    return viewer;
}
Пример #25
0
void MonavMap::parseBoundingBox( const QFileInfo &file )
{
    GeoDataLineString points;
    bool tooLarge = false;
    QFile input( file.absoluteFilePath() );
    if ( input.open( QFile::ReadOnly ) ) {
        GeoDataParser parser( GeoData_KML );
        if ( !parser.read( &input ) ) {
            mDebug() << "Could not parse file: " << parser.errorString();
            return;
        }

        GeoDocument *doc = parser.releaseDocument();
        input.close();
        GeoDataDocument *document = dynamic_cast<GeoDataDocument*>( doc );
        QVector<GeoDataPlacemark*> placemarks = document->placemarkList();
        if ( placemarks.size() == 1 ) {
            GeoDataPlacemark* placemark = placemarks.first();
            m_name = placemark->name();
            m_version = placemark->extendedData().value( "version" ).value().toString();
            m_date = placemark->extendedData().value( "date" ).value().toString();
            m_transport = placemark->extendedData().value( "transport" ).value().toString();
            m_payload = placemark->extendedData().value( "payload" ).value().toString();
            GeoDataMultiGeometry* geometry = dynamic_cast<GeoDataMultiGeometry*>( placemark->geometry() );
            if ( geometry->size() > 1500 ) {
                tooLarge = true;
            }
            for ( int i = 0; geometry && i < geometry->size(); ++i ) {
                GeoDataLinearRing* poly = dynamic_cast<GeoDataLinearRing*>( geometry->child( i ) );
                if ( poly ) {
                    for ( int j = 0; j < poly->size(); ++j ) {
                        points << poly->at( j );
                    }
                    m_tiles.push_back( *poly );
                }

                if ( poly->size() > 1500 ) {
                    tooLarge = true;
                }
            }
        } else {
            mDebug() << "File " << file.absoluteFilePath() << " does not contain one placemark, but " << placemarks.size();
        }

        delete doc;
    }
    m_boundingBox = points.latLonAltBox();

    if ( tooLarge ) {
        // The bounding box polygon is rather complicated, therefore not allowing a quick check
        // and also occupying memory. Discard the polygon and only store the rectangular bounding
        // box. Only happens for non-simplified bounding box polygons.
        mDebug() << "Discarding too large bounding box poylgon for " << file.absoluteFilePath() << ". Please check for a map update.";
        m_tiles.clear();
    }
}
Пример #26
0
void PaintingItemPainter::drawPathLine(const QVector<QPoint> &points, const QPoint translate) {
    painter()->beginPath();
    QPoint firstPoint = points.first() + translate;
    painter()->moveTo(firstPoint.x(), firstPoint.y()-1);
    painter()->lineTo(firstPoint);
    for (int i=1; i<points.size(); ++i) {
        painter()->lineTo(points.at(i) + translate);
    }
    painter()->stroke();
}
Пример #27
0
void ExtractAnnotatedRegionTask::run() {
    QVector<U2Region> safeLocation = inputAnn->getRegions();
    U2Region::bound(0, inputSeq.length(), safeLocation);
    QList<QByteArray> resParts = U1SequenceUtils::extractRegions(inputSeq.seq, safeLocation, complT, NULL, inputSeq.circular);
    if (aminoT == NULL) { // extension does not work for translated annotations
        if (cfg.extLeft > 0) {
            int annStart = safeLocation.first().startPos;
            int preStart = qMax(0,  annStart - cfg.extLeft);
            int preLen = annStart - preStart;
            QByteArray preSeq = inputSeq.seq.mid(preStart, preLen);
            resParts.prepend(preSeq);

            for (int i = 0; i < safeLocation.size(); ++i) {
                safeLocation[i].startPos -= preLen;
                safeLocation[i].length += preLen;
            }
        }
        if (cfg.extRight) {
            U2Region annRegion = U2Region::containingRegion(safeLocation);
            int annEnd = annRegion.endPos();
            int postEnd = qMin(inputSeq.length(), annEnd + cfg.extRight);
            int postLen = postEnd - annEnd;
            QByteArray postSeq = inputSeq.seq.mid(annEnd, postLen);
            resParts.append(postSeq);

            for (int i = 0; i < safeLocation.size(); ++i) {
                safeLocation[i].length += postLen;
            }
        }
    } else {
        resParts = U1SequenceUtils::translateRegions(resParts, aminoT, inputAnn->isJoin());
    }
    foreach (const QByteArray &seq, resParts) {
        bool onlyOneIteration = false;
        DNASequence s;
        s.info[DNAInfo::ID] = inputSeq.getName();
        if (!cfg.splitJoined || resParts.size() == 1){
            s.seq = resParts.size() == 1 ? resParts.first() : U1SequenceUtils::joinRegions(resParts, cfg.gapLength);
            onlyOneIteration = true;
        }else{
            s.seq = seq;
        }
        s.alphabet = aminoT ? aminoT->getDstAlphabet() : complT ? complT->getDstAlphabet() : inputSeq.alphabet;
        if (aminoT != NULL) {
            s.alphabet = aminoT->getDstAlphabet();
        }else if (complT != NULL) {
            s.alphabet = complT->getDstAlphabet();
        }else {
            s.alphabet = inputSeq.alphabet;
        }
        resultedSeqList.append(s);
        if (onlyOneIteration){
            break;
        }
    }
Пример #28
0
void text_helper::insertDataBreak(double dateTime, QVector<QVector<double> > &seriesData,
                                  QVector<QVector<QString> > &eventData, QList<QVariantMap> &metaData)
{
    //Add the date and time
    seriesData.first().append(dateTime);

    //Iterate through meta data and append data as needed
    for (auto &mData : metaData) {
        if (mData.contains("Data Type")) {
            if (mData.value("Data Type") == "Series") {
                seriesData[mData.value("Data Value Storage Index").toInt()].append(
                    std::numeric_limits<double>::quiet_NaN());
            }
        }
    }
    if ( !eventData.isEmpty() ) {
        QVector<QString> spacerVector(eventData.first().size());
        eventData.append(spacerVector);
    }
}
Пример #29
0
static QPixmap combinedPlainPixmaps(const QVector<IconMaskAndColor> &images)
{
    QPixmap result(StyleHelper::dpiSpecificImageFile(images.first().first));
    auto pixmap = images.constBegin();
    pixmap++;
    for (;pixmap != images.constEnd(); ++pixmap) {
        const QPixmap overlay(StyleHelper::dpiSpecificImageFile((*pixmap).first));
        result.paintEngine()->painter()->drawPixmap(0, 0, overlay);
    }
    return result;
}
Пример #30
0
void McaEditorReferenceArea::sl_onSelectionChanged(LRegionsSelection * /*selection*/, const QVector<U2Region> &addedRegions, const QVector<U2Region> &removedRegions) {
    if (addedRegions.size() == 1) {
        const U2Region addedRegion = addedRegions.first();
        qint64 baseToScrollTo = -1;
        if (removedRegions.size() == 1) {
            const U2Region removedRegion = removedRegions.first();
            if (addedRegion.startPos < removedRegion.startPos && addedRegion.endPos() == removedRegion.endPos()) {
                baseToScrollTo = addedRegion.startPos;
            } else if (addedRegion.startPos == removedRegion.startPos && addedRegion.endPos() > removedRegion.endPos()) {
                baseToScrollTo = addedRegion.endPos() - 1;
            } else {
                baseToScrollTo = addedRegion.startPos;
            }
        } else {
            baseToScrollTo = addedRegion.startPos;
        }
        ui->getScrollController()->scrollToBase(static_cast<int>(baseToScrollTo), width());
    }
    emit si_selectionChanged();
}