Пример #1
0
int main ()
{
    QLinkedList<QString> list;
    list << "A" << "B" << "C" << "D" << "E" << "F";
    assert(list.takeFirst() == "A");
    assert(list.size() == 5);
  return 0;
}
Пример #2
0
int main ()
{
    QLinkedList<QString> list;
    list << "sun" << "cloud" << "sun" << "rain";
    list.removeAll("sun");
    assert(list.size() == 2);
    // list: ["cloud", "rain"]
  return 0;
}
Пример #3
0
	void BatteryHistoryDialog::UpdateHistory (const QLinkedList<BatteryHistory>& hist)
	{
		QVector<double> xdata (hist.size ());
		QVector<double> percents (hist.size ());
		QVector<double> energy (hist.size ());

		int i = 0;
		std::for_each (hist.begin (), hist.end (),
				[&xdata, &percents, &energy, &i] (const BatteryHistory& bh)
				{
					percents [i] = bh.Percentage_;
					energy [i] = bh.EnergyRate_;
					xdata [i] = i;
					++i;
				});
		Percent_->setSamples (xdata, percents);
		Energy_->setSamples (xdata, energy);

		Ui_.PercentPlot_->replot ();
	}
Пример #4
0
int main ()
{
  unsigned int i;
  QLinkedList<unsigned int> myQLinkedList;
  QLinkedList<unsigned int>::iterator it1,it2;

  // set some values:
  for (i=1; i<10; i++) myQLinkedList.push_back(i*10);

                              // 10 20 30 40 50 60 70 80 90
  it1 = it2 = myQLinkedList.begin(); // ^^
  advance (it2,6);            // ^                 ^
  assert(*it2 != 70);
  ++it1;                      //    ^              ^

  it1 = myQLinkedList.erase (it1);   // 10 30 40 50 60 70 80 90
  assert(*it1 != 30);
  assert(myQLinkedList.size() == 8);
                              //    ^           ^

  it2 = myQLinkedList.erase (it2);   // 10 30 40 50 60 80 90
                              //    ^           ^
  assert(*it2 != 80);
  assert(myQLinkedList.size() == 7);

  ++it1;                      //       ^        ^
  --it2;                      //       ^     ^

  myQLinkedList.erase (it1,it2);     // 10 30 60 80 90
                              //        ^
  assert(myQLinkedList.size() == 5);

  assert(*it2 != 60);

  cout << "myQLinkedList contains:";
  for (it1=myQLinkedList.begin(); it1!=myQLinkedList.end(); ++it1)
    cout << " " << *it1;
  cout << endl;

  return 0;
}
Пример #5
0
int main() {
	cout << "Methods of finding function roots.\nPodkopaev Anton, SPbSU, 2011\n";
	cout << "f(x) = x^2 - sin(5x)\n\n";

	double A = -10;
	double B = 10;
	double eps = 0.000001;

	cout << "Enter interval\n";
	cout << "Left border: ";
	cin >> A;
	cout << "Right border: ";
	cin >> B;
	cout << "Enter accurancy: ";
	cin >> eps;

	double step = eps * 1000;
	cout << "Enter first step: ";
	cin >> step;

	QLinkedList<Interval> intervals = rootDividing<CurFunc>(A, B, step);
	int oldRootNumber = intervals.size();
	do {
		step /= 2;
		intervals = rootDividing<CurFunc>(A, B, step);
	} while((step > 2 * eps) && (oldRootNumber != intervals.size()));

	cout << "Result tabulation step: " << step << "\n";
	cout << "Interval number: " << intervals.size() << "\n\n";

	cin.get();
	foreach (Interval curInterval, intervals) {
		cout << "\n\t\t\tInterval: " << curInterval.toString().toStdString();
		bisectionMethod<CurFunc>(curInterval, eps);
		newtonMethod<CurFunc>(curInterval, eps);
		secantMethod<CurFunc>(curInterval, eps);
		cin.get();
	}
/**
 * Set the items of the Patient list, removes the old ones
 * Rows containing Patient Name and Health Card Number and optionally Bed Type
 *
 * @param patientItems map of patient's health card number to a Patient pointer
 * @param includeBeds True if beds should be included, False otherwise
 */
void MovePatientForm::setPatientItems(const QLinkedList<Patient*> &patientItems, bool includeBeds)
{
    _patientList->clear();
    if (patientItems.size() > 0)
    {
        QList<QTreeWidgetItem*> items;
	foreach (Patient* patient, patientItems)
	{
            // Store the name first, then the hcn
	    QStringList info = QStringList() << patient->getName() << patient->getHealthCardNumber();
            // Optionally store the bed type
	    if (includeBeds) { info << Convenience::careTypeToQString(patient->getOccupiedCare()); }
            items.append(new QTreeWidgetItem((QTreeWidget*)0, info));
        }
Пример #7
0
int main ()
{
  QLinkedList<int> myints;
  cout << "0. size: " << (int) myints.size() << endl;
  assert(myints.size() == 0);
  for (int i=0; i<10; i++) myints.push_back(i);
  cout << "1. size: " << (int) myints.size() << endl;
  assert(myints.size() == 10);
  myints.insert (myints.begin(),10);
  cout << "2. size: " << (int) myints.size() << endl;
  assert(myints.size() == 11);
  myints.pop_back();
  cout << "3. size: " << (int) myints.size() << endl;
  assert(myints.size() == 10);
  return 0;
}
Пример #8
0
void tst_ExceptionSafety::exceptionLinkedList() {

    {
        QLinkedList<FlexibleThrowerSmall> list;
        QLinkedList<FlexibleThrowerSmall> list2;
        QLinkedList<FlexibleThrowerSmall> list3;

        for( int i = 0; i<10; i++ )
            list.append( FlexibleThrowerSmall(i) );

        try {
            throwType = ThrowAtCopy;
            list.append( FlexibleThrowerSmall(10));
        } catch (...) {
        }
        QCOMPARE( list.size(), 10 );

        try {
            throwType = ThrowAtCopy;
            list.prepend( FlexibleThrowerSmall(10));
        } catch (...) {
        }
        QCOMPARE( list.first().value(), 0 );
        QCOMPARE( list.size(), 10 );

        try {
            throwType = ThrowAtCopy;
            list3 = list;
            list3.append( FlexibleThrowerSmall(11) );
        } catch (...) {
        }
        QCOMPARE( list.first().value(), 0 );
        QCOMPARE( list.size(), 10 );
        QCOMPARE( list3.size(), 10 );
    }
    QCOMPARE(objCounter, 0 ); // check that every object has been freed
}
Пример #9
0
int main ()
{
  QLinkedList<int> myQLinkedList;
  int sum (0);

  for (int i=1;i<=10;i++) myQLinkedList.push_back(i);

  assert(!myQLinkedList.empty());
  while (!myQLinkedList.empty())
  {
     sum += myQLinkedList.front();
     myQLinkedList.pop_front();
  }
  assert(myQLinkedList.empty()&&(myQLinkedList.size() == 0));
  cout << "total: " << sum << endl;
  
  return 0;
}
Пример #10
0
  QLinkedList<const GEOSGeometry *> *unmulti( const GEOSGeometry *the_geom )
  {
    QLinkedList<const GEOSGeometry*> *queue = new QLinkedList<const GEOSGeometry*>;
    QLinkedList<const GEOSGeometry*> *final_queue = new QLinkedList<const GEOSGeometry*>;

    const GEOSGeometry *geom;

    queue->append( the_geom );
    int nGeom;
    int i;

    while ( queue->size() > 0 )
    {
      geom = queue->takeFirst();
      GEOSContextHandle_t geosctxt = geosContext();
      switch ( GEOSGeomTypeId_r( geosctxt, geom ) )
      {
        case GEOS_MULTIPOINT:
        case GEOS_MULTILINESTRING:
        case GEOS_MULTIPOLYGON:
          nGeom = GEOSGetNumGeometries_r( geosctxt, geom );
          for ( i = 0; i < nGeom; i++ )
          {
            queue->append( GEOSGetGeometryN_r( geosctxt, geom, i ) );
          }
          break;
        case GEOS_POINT:
        case GEOS_LINESTRING:
        case GEOS_POLYGON:
          final_queue->append( geom );
          break;
        default:
          delete final_queue;
          delete queue;
          return NULL;
      }
    }
    delete queue;

    return final_queue;
  }
Пример #11
0
	void RDFGraphBasic::removeResources(RDFVariable const &variable)
	{
		QLinkedList<RDFVariable> removes;
		removes << variable;
		RDFTransactionPtr tx = createTransaction();
		while(1)
		{
			RDFStatementList removed_statements;
			executeQuery
					(RDFUpdate(service_context_data_->update())
					.addDeletion(*recurseRemoveResources
							(&removed_statements, removes.front(), &removes)));
			removes.pop_front();
			tx->commit();
			if(!removes.size())
				return;
			if(!(tx = createTransaction(RDFTransaction::Exclusive)))
			{
				warning() << "using recursive sharing removes requires that "
						"no transaction is active on the service";
				return;
			}
		}
	}
Пример #12
0
TEST_F(CoverArtUtilTest, searchImage) {
    // creating a temp track directory
    QString trackdir(QDir::tempPath() % "/TrackDir");
    ASSERT_FALSE(QDir().exists(trackdir)); // it must start empty
    ASSERT_TRUE(QDir().mkpath(trackdir));

    TrackPointer pTrack(Track::newTemporary(kTrackLocationTest));
    SoundSourceProxy(pTrack).loadTrackMetadata();
    QLinkedList<QFileInfo> covers;
    CoverArt res;
    // looking for cover in an empty directory
    res = CoverArtUtils::selectCoverArtForTrack(pTrack.data(), covers);
    CoverArt expected;
    expected.info.source = CoverInfo::GUESSED;
    EXPECT_EQ(expected, res);

    // Looking for a track with embedded cover.
    pTrack = TrackPointer(Track::newTemporary(kTrackLocationTest));
    SoundSourceProxy(pTrack).loadTrackMetadataAndCoverArt();
    expected = CoverArt();
    expected.image = pTrack->getCoverArt().image;
    expected.info.type = CoverInfo::METADATA;
    expected.info.source = CoverInfo::GUESSED;
    expected.info.coverLocation = QString();
    expected.info.hash = CoverArtUtils::calculateHash(expected.image);
    EXPECT_EQ(expected, pTrack->getCoverArt());

    const char* format("jpg");
    const QString qFormat(format);

    // Since we already parsed this image from the matadata in
    // kTrackLocationTest, hang on to it since we use it as a template for
    // stuff below.
    const QImage img = expected.image;


    QString trackBaseName = "cover-test";
    QString trackAlbum = "album_name";

    // Search Strategy
    // 0. If we have just one file, we will get it.
    // 1. %track-file-base%.jpg in the track directory for %track-file-base%.mp3
    // 2. %album%.jpg
    // 3. cover.jpg
    // 4. front.jpg
    // 5. album.jpg
    // 6. folder.jpg
    // 7. if just one file exists take that otherwise none.

    // All the following expect the same image/hash to be selected.
    expected.image = img;
    expected.info.hash = CoverArtUtils::calculateHash(expected.image);

    // All the following expect FILE and GUESSED.
    expected.info.type = CoverInfo::FILE;
    expected.info.source = CoverInfo::GUESSED;

    // 0. saving just one cover in our temp track dir
    QString cLoc_foo = QString(trackdir % "/" % "foo." % qFormat);
    EXPECT_TRUE(img.save(cLoc_foo, format));

    // looking for cover in an directory with one image will select that one.
    expected.image = QImage(cLoc_foo);
    expected.info.coverLocation = "foo.jpg";
    expected.info.hash = CoverArtUtils::calculateHash(expected.image);
    covers << QFileInfo(cLoc_foo);
    res = CoverArtUtils::selectCoverArtForTrack(trackBaseName, trackAlbum,
                                                covers);
    EXPECT_EQ(expected, res);
    QFile::remove(cLoc_foo);

    QStringList extraCovers;
    // adding some extra images (bigger) just to populate the track dir.
    QString cLoc_big1 = QString(trackdir % "/" % "big1." % qFormat);
    EXPECT_TRUE(img.scaled(1000,1000).save(cLoc_big1, format));
    extraCovers << cLoc_big1;
    QString cLoc_big2 = QString(trackdir % "/" % "big2." % qFormat);
    EXPECT_TRUE(img.scaled(900,900).save(cLoc_big2, format));
    extraCovers << cLoc_big2;
    QString cLoc_big3 = QString(trackdir % "/" % "big3." % qFormat);
    EXPECT_TRUE(img.scaled(800,800).save(cLoc_big3, format));
    extraCovers << cLoc_big3;

    // saving more covers using the preferred names in the right order
    QLinkedList<QFileInfo> prefCovers;
    // 1. track_filename.jpg
    QString cLoc_filename = QString(trackdir % "/cover-test." % qFormat);
    EXPECT_TRUE(img.scaled(500,500).save(cLoc_filename, format));
    prefCovers << QFileInfo(cLoc_filename);
    // 2. album_name.jpg
    QString cLoc_albumName = QString(trackdir % "/album_name." % qFormat);
    EXPECT_TRUE(img.scaled(500,500).save(cLoc_albumName, format));
    prefCovers << QFileInfo(cLoc_albumName);
    // 3. cover.jpg
    QString cLoc_cover = QString(trackdir % "/" % "cover." % qFormat);
    EXPECT_TRUE(img.scaled(400,400).save(cLoc_cover, format));
    prefCovers << QFileInfo(cLoc_cover);
    // 4. front.jpg
    QString cLoc_front = QString(trackdir % "/" % "front." % qFormat);
    EXPECT_TRUE(img.scaled(300,300).save(cLoc_front, format));
    prefCovers << QFileInfo(cLoc_front);
    // 5. album.jpg
    QString cLoc_album = QString(trackdir % "/" % "album." % qFormat);
    EXPECT_TRUE(img.scaled(100,100).save(cLoc_album, format));
    prefCovers << QFileInfo(cLoc_album);
    // 6. folder.jpg
    QString cLoc_folder = QString(trackdir % "/" % "folder." % qFormat);
    EXPECT_TRUE(img.scaled(100,100).save(cLoc_folder, format));
    prefCovers << QFileInfo(cLoc_folder);
    // 8. other1.jpg
    QString cLoc_other1 = QString(trackdir % "/" % "other1." % qFormat);
    EXPECT_TRUE(img.scaled(10,10).save(cLoc_other1, format));
    prefCovers << QFileInfo(cLoc_other1);
    // 7. other2.jpg
    QString cLoc_other2 = QString(trackdir % "/" % "other2." % qFormat);
    EXPECT_TRUE(img.scaled(10,10).save(cLoc_other2, format));
    prefCovers << QFileInfo(cLoc_other2);

    // we must find covers in the right order
    EXPECT_EQ(8, prefCovers.size());

    // Remove the covers one by one from the front, checking that each one is
    // selected as we remove the previously-most-preferable cover.
    while (!prefCovers.isEmpty()) {
        QFileInfo cover = prefCovers.first();

        // We expect no cover selected for other1 since there are 2 covers,
        // neither of which match our preferred cover names. other2 will be
        // selected once we get to it since it is the only cover available.
        if (cover.baseName() == "other1") {
            expected.image = QImage();
            expected.info.type = CoverInfo::NONE;
            expected.info.coverLocation = QString();
            expected.info.hash = 0;
        } else {
            expected.image = QImage(cover.filePath());
            expected.info.type = CoverInfo::FILE;
            expected.info.coverLocation = cover.fileName();
            expected.info.hash = CoverArtUtils::calculateHash(expected.image);
        }
        res = CoverArtUtils::selectCoverArtForTrack(trackBaseName, trackAlbum,
                                                    prefCovers);
        EXPECT_QSTRING_EQ(expected.info.coverLocation, res.info.coverLocation);
        EXPECT_QSTRING_EQ(expected.info.hash, res.info.hash);
        EXPECT_EQ(expected, res);

        QFile::remove(cover.filePath());
        prefCovers.pop_front();
    }

    //
    // Additional tests
    //

    // what is chosen when cover.jpg and cover.JPG exists?
    // (it must always prefer the lighter cover)
    QString cLoc_coverJPG = trackdir % "/" % "cover." % "JPG";
    EXPECT_TRUE(img.scaled(200,200).save(cLoc_coverJPG, "JPG"));
    prefCovers.append(QFileInfo(cLoc_coverJPG));
    QString cLoc_coverjpg = trackdir % "/" % "cover." % "jpg";
    EXPECT_TRUE(img.scaled(400,400).save(cLoc_coverjpg, "jpg"));
    prefCovers.append(QFileInfo(cLoc_coverjpg));
    extraCovers << cLoc_coverJPG << cLoc_coverjpg;

    res = CoverArtUtils::selectCoverArtForTrack(trackBaseName, trackAlbum,
                                                prefCovers);
    expected.image = QImage(cLoc_coverJPG);
    expected.info.hash = CoverArtUtils::calculateHash(expected.image);
    expected.info.coverLocation = "cover.JPG";
    EXPECT_EQ(expected, res);

    // As we are looking for %album%.jpg and %base_track.jpg%,
    // we need to check if everything works with UTF8 chars.
    trackBaseName = QString::fromUtf8("track_ðÑöæäî");
    trackAlbum = QString::fromUtf8("öæäîðÑ_album");

    prefCovers.clear();

    // 2. album_name.jpg
    cLoc_albumName = QString(trackdir % "/" % trackAlbum % "." % qFormat);
    EXPECT_TRUE(img.save(cLoc_albumName, format));
    prefCovers.append(QFileInfo(cLoc_albumName));
    res = CoverArtUtils::selectCoverArtForTrack(trackBaseName, trackAlbum,
                                                prefCovers);
    expected.image = QImage(cLoc_albumName);
    expected.info.hash = CoverArtUtils::calculateHash(expected.image);
    expected.info.coverLocation = trackAlbum % ".jpg";
    EXPECT_EQ(expected, res);

    // 1. track_filename.jpg
    cLoc_filename = QString(trackdir % "/" % trackBaseName % "." % qFormat);
    EXPECT_TRUE(img.save(cLoc_filename, format));
    prefCovers.append(QFileInfo(cLoc_filename));
    res = CoverArtUtils::selectCoverArtForTrack(trackBaseName, trackAlbum,
                                                prefCovers);
    expected.image = QImage(cLoc_filename);
    expected.info.hash = CoverArtUtils::calculateHash(expected.image);
    expected.info.coverLocation = trackBaseName % ".jpg";
    EXPECT_EQ(expected, res);

    QFile::remove(cLoc_filename);
    QFile::remove(cLoc_albumName);

    // cleaning temp dir
    foreach (QString loc, extraCovers) {
        QFile::remove(loc);
    }
Пример #13
0
void ClangSymbolSearcher::search(const QLinkedList<Symbol> &allSymbols)
{
    QString findString = (m_parameters.flags & Find::FindRegularExpression
                          ? m_parameters.text : QRegExp::escape(m_parameters.text));
    if (m_parameters.flags & Find::FindWholeWords)
        findString = QString::fromLatin1("\\b%1\\b").arg(findString);
    QRegExp matcher(findString, (m_parameters.flags & Find::FindCaseSensitively
                                 ? Qt::CaseSensitive : Qt::CaseInsensitive));

    const int chunkSize = 10;
    QVector<Core::SearchResultItem> resultItems;
    resultItems.reserve(100);

    m_future->setProgressRange(0, allSymbols.size() % chunkSize);
    m_future->setProgressValue(0);

    int symbolNr = 0;
    foreach (const Symbol &s, allSymbols) {
        if (symbolNr % chunkSize == 0) {
            m_future->setProgressValue(symbolNr / chunkSize);
            m_future->reportResults(resultItems);
            resultItems.clear();

            if (m_future->isPaused())
                m_future->waitForResume();
            if (m_future->isCanceled())
                return;
        }
        ++symbolNr;

        CppTools::ModelItemInfo info;

        switch (s.m_kind) {
        case Symbol::Enum:
            if (m_parameters.types & SymbolSearcher::Enums) {
                info.type = CppTools::ModelItemInfo::Enum;
                info.symbolType = QLatin1String("enum");
                break;
            } else {
                continue;
            }
        case Symbol::Class:
            if (m_parameters.types & SymbolSearcher::Classes) {
                info.type = CppTools::ModelItemInfo::Class;
                info.symbolType = QLatin1String("class");
                break;
            } else {
                continue;
            }
        case Symbol::Method:
        case Symbol::Function:
        case Symbol::Constructor:
        case Symbol::Destructor:
            if (m_parameters.types & SymbolSearcher::Functions) {
                info.type = CppTools::ModelItemInfo::Function;
                break;
            } else {
                continue;
            }
        case Symbol::Declaration:
            if (m_parameters.types & SymbolSearcher::Declarations) {
                info.type = CppTools::ModelItemInfo::Declaration;
                break;
            } else {
                continue;
            }

        default: continue;
        }

        if (matcher.indexIn(s.m_name) == -1)
            continue;

        info.symbolName = s.m_name;
        info.fullyQualifiedName = s.m_qualification.split(QLatin1String("::")) << s.m_name;
        info.fileName = s.m_location.fileName();
        info.icon = s.iconForSymbol();
        info.line = s.m_location.line();
        info.column = s.m_location.column() - 1;

        Core::SearchResultItem item;
        item.path << s.m_qualification;
        item.text = s.m_name;
        item.icon = info.icon;
        item.textMarkPos = -1;
        item.textMarkLength = 0;
        item.lineNumber = -1;
        item.userData = qVariantFromValue(info);

        resultItems << item;
    }

    if (!resultItems.isEmpty())
        m_future->reportResults(resultItems);
}
Пример #14
0
void ConditionalDialog::init()
{
    QLinkedList<KCConditional> conditionList;
    QLinkedList<KCConditional> otherList;
    bool found;
    int numCondition;

    QLinkedList<KCConditional>::iterator it1;
    QLinkedList<KCConditional>::iterator it2;

    KCSheet* sheet = m_selection->activeSheet();

    conditionList = KCCell(sheet, m_selection->marker()).conditions().conditionList();
    /* this is the list, but only display the conditions common to all selected
       cells*/

    for (int x = m_selection->lastRange().left(); x <= m_selection->lastRange().right(); x++) {
        for (int y = m_selection->lastRange().top(); y <= m_selection->lastRange().bottom(); y++) {
            otherList = KCCell(sheet, x, y).conditions().conditionList();

            it1 = conditionList.begin();
            while (it1 != conditionList.end()) {
                kDebug() << "Here";
                found = false;
                for (it2 = otherList.begin(); !found && it2 != otherList.end(); ++it2) {
                    kDebug() << "Found:" << found;
                    found = ((*it1).value1 == (*it2).value1 &&
                             (*it1).value2 == (*it2).value2 &&
                             (*it1).cond == (*it2).cond);

                    if (!found)
                        continue;

                    if ((*it1).styleName != (*it2).styleName)
                        found = false;
                }

                if (!found) {  /* if it's not here, don't display this condition */
                    it1 = conditionList.erase(it1);
                } else {
                    ++it1;
                }
            }
        }
    }

    kDebug() << "KCConditions:" << conditionList.size();

    m_dlg->m_condition_2->setEnabled(false);
    m_dlg->m_condition_3->setEnabled(false);

    m_dlg->m_style_1->setEnabled(false);
    m_dlg->m_style_2->setEnabled(false);
    m_dlg->m_style_3->setEnabled(false);

    numCondition = 0;
    for (it1 = conditionList.begin(); numCondition < 3 && it1 != conditionList.end(); ++it1) {
        init(*it1, numCondition);

        ++numCondition;
    }
}
Пример #15
0
bool PlotIO::write(const QString& path, const ros::Time& start, const ros::Time& end)
{
	FileFormat* io = 0;

	if(path.endsWith(".bag"))
		io = new BagFormat;
	else if(path.endsWith(".csv"))
		io = new CSVFormat;

	if(!io)
	{
		fprintf(stderr, "Could not find output format\n");
		return false;
	}

	if(!io->init(path, start))
		return false;

	QLinkedList<Plot::LinkedBufferIterator> its = m_rootPlot->iterators(io->defaultFlags());

	io->writeHeader(its);

	QVector<Plot::LinkedBufferIterator*> to_write(its.size(), 0);

	while(1)
	{
		ros::Time stamp = ros::Time(0);
		qFill(to_write, (Plot::LinkedBufferIterator*)0);

		// Get a list of iterators with the next timestamp
		int i = 0;
		for(QLinkedList<Plot::LinkedBufferIterator>::iterator it = its.begin(); it != its.end(); ++it, ++i)
		{
			Plot::LinkedBufferIterator& buf_it = *it;
			if(!buf_it.isValid())
				continue;

			const Plot::DataPoint& point = *buf_it;

			if(point.time < stamp || stamp == ros::Time(0))
			{
				qFill(to_write, (Plot::LinkedBufferIterator*)0);
				to_write[i] = &buf_it;
				stamp = point.time;
			}
			else if(point.time == stamp)
				to_write[i] = &buf_it;
		}

		if(stamp == ros::Time(0))
			break;

		if(end != ros::Time(0) && stamp > end)
			break;

		if(stamp >= start)
			io->writeData(stamp, to_write);

		// Advance all used iterators
		Q_FOREACH(Plot::LinkedBufferIterator* it, to_write)
		{
			if(!it)
				continue;

			++(*it);
		}
	}

	delete io;
	return true;
}
Пример #16
0
bool Layer::registerFeature( const QString& geom_id, PalGeometry *userGeom, double label_x, double label_y, const QString &labelText,
                             double labelPosX, double labelPosY, bool fixedPos, double angle, bool fixedAngle,
                             int xQuadOffset, int yQuadOffset, double xOffset, double yOffset, bool alwaysShow, double repeatDistance )
{
    if ( geom_id.isEmpty() || label_x < 0 || label_y < 0 )
        return false;

    mMutex.lock();

    if ( hashtable->contains( geom_id ) )
    {
        mMutex.unlock();
        //A feature with this id already exists. Don't throw an exception as sometimes,
        //the same feature is added twice (dateline split with otf-reprojection)
        return false;
    }

    // Split MULTI GEOM and Collection in simple geometries
    const GEOSGeometry *the_geom = userGeom->getGeosGeometry();

    Feature* f = new Feature( this, geom_id, userGeom, label_x, label_y );
    if ( fixedPos )
    {
        f->setFixedPosition( labelPosX, labelPosY );
    }
    if ( xQuadOffset != 0 || yQuadOffset != 0 )
    {
        f->setQuadOffset( xQuadOffset, yQuadOffset );
    }
    if ( xOffset != 0.0 || yOffset != 0.0 )
    {
        f->setPosOffset( xOffset, yOffset );
    }
    if ( fixedAngle )
    {
        f->setFixedAngle( angle );
    }
    // use layer-level defined rotation, but not if position fixed
    if ( !fixedPos && angle != 0.0 )
    {
        f->setFixedAngle( angle );
    }
    f->setRepeatDistance( repeatDistance );

    f->setAlwaysShow( alwaysShow );

    bool first_feat = true;

    double geom_size = -1, biggest_size = -1;
    FeaturePart* biggest_part = NULL;

    // break the (possibly multi-part) geometry into simple geometries
    QLinkedList<const GEOSGeometry*>* simpleGeometries = unmulti( the_geom );
    if ( simpleGeometries == NULL ) // unmulti() failed?
    {
        mMutex.unlock();
        throw InternalException::UnknownGeometry();
    }

    GEOSContextHandle_t geosctxt = geosContext();

    while ( simpleGeometries->size() > 0 )
    {
        const GEOSGeometry* geom = simpleGeometries->takeFirst();

        // ignore invalid geometries (e.g. polygons with self-intersecting rings)
        if ( GEOSisValid_r( geosctxt, geom ) != 1 ) // 0=invalid, 1=valid, 2=exception
        {
//        std::cerr << "ignoring invalid feature " << geom_id << std::endl;
            continue;
        }

        int type = GEOSGeomTypeId_r( geosctxt, geom );

        if ( type != GEOS_POINT && type != GEOS_LINESTRING && type != GEOS_POLYGON )
        {
            mMutex.unlock();
            throw InternalException::UnknownGeometry();
        }

        FeaturePart* fpart = new FeaturePart( f, geom );

        // ignore invalid geometries
        if (( type == GEOS_LINESTRING && fpart->nbPoints < 2 ) ||
                ( type == GEOS_POLYGON && fpart->nbPoints < 3 ) )
        {
            delete fpart;
            continue;
        }

        // polygons: reorder coordinates
        if ( type == GEOS_POLYGON && reorderPolygon( fpart->nbPoints, fpart->x, fpart->y ) != 0 )
        {
            delete fpart;
            continue;
        }

        if ( mMode == LabelPerFeature && ( type == GEOS_POLYGON || type == GEOS_LINESTRING ) )
        {
            if ( type == GEOS_LINESTRING )
                GEOSLength_r( geosctxt, geom, &geom_size );
            else if ( type == GEOS_POLYGON )
                GEOSArea_r( geosctxt, geom, &geom_size );

            if ( geom_size > biggest_size )
            {
                biggest_size = geom_size;
                delete biggest_part; // safe with NULL part
                biggest_part = fpart;
            }
            continue; // don't add the feature part now, do it later
            // TODO: we should probably add also other parts to act just as obstacles
        }

        // feature part is ready!
        addFeaturePart( fpart, labelText );

        first_feat = false;
    }
    delete simpleGeometries;

    userGeom->releaseGeosGeometry( the_geom );

    mMutex.unlock();

    // if using only biggest parts...
    if (( mMode == LabelPerFeature || f->fixedPosition() ) && biggest_part != NULL )
    {
        addFeaturePart( biggest_part, labelText );
        first_feat = false;
    }

    // add feature to layer if we have added something
    if ( !first_feat )
    {
        features->append( f );
        hashtable->insert( geom_id, f );
    }
    else
    {
        delete f;
    }

    return !first_feat; // true if we've added something
}
Пример #17
0
/*!
 * @desc collects groups of concurrent items in the offset range
 */
QList< QLinkedList<QxtScheduleInternalItem *> > QxtScheduleViewPrivate::findConcurrentItems(const int from, const int to) const
{
    QList< QLinkedList<QxtScheduleInternalItem *> > allConcurrentItems;

    QList<QxtScheduleInternalItem *> allItemsSorted = m_Items;
    
    if(m_Items.size() == 0)
        return allConcurrentItems;
    
    qSort(allItemsSorted.begin(), allItemsSorted.end(), qxtScheduleItemLessThan);

    int startItem = 0;
    int endItem = allItemsSorted.size() - 1;

    //find the startitem that interferes with our range
    for (int i = 0; i < allItemsSorted.size(); i++)
    {
        if (i > 0)
        {
            if (!(allItemsSorted.at(i - 1)->visualEndTableOffset() >=  allItemsSorted.at(i)->visualStartTableOffset()
                    && allItemsSorted.at(i - 1)->visualStartTableOffset() <=  allItemsSorted.at(i)->visualEndTableOffset()))
                startItem = i;
        }

        if (allItemsSorted.at(i)->visualEndTableOffset() >= from && allItemsSorted.at(i)->visualStartTableOffset() <= to)
            break;
    }

    //find the last item that interferes with our range
    for (int i = allItemsSorted.size() - 1; i >= 0 ; i--)
    {
        if (i < allItemsSorted.size() - 1)
        {
            if (!(allItemsSorted.at(i + 1)->visualEndTableOffset() >=  allItemsSorted.at(i)->visualStartTableOffset()
                    && allItemsSorted.at(i + 1)->visualStartTableOffset() <=  allItemsSorted.at(i)->visualEndTableOffset()))
                endItem = i;
        }

        if (allItemsSorted.at(i)->visualEndTableOffset() >= from && allItemsSorted.at(i)->visualStartTableOffset() <= to)
            break;
    }

    int startOffset = allItemsSorted.at(startItem)->visualStartTableOffset();
    int endOffset = allItemsSorted.at(endItem)->visualEndTableOffset();

    /*now we have to populate a list with all items that interfere with our range */
    QLinkedList<QxtScheduleInternalItem *> concurrentItems;
    for (int iAllItemLoop = startItem; iAllItemLoop <= endItem; iAllItemLoop++)
    {
        int tempStartOffset = allItemsSorted.at(iAllItemLoop)->visualStartTableOffset();
        int tempEndOffset = allItemsSorted.at(iAllItemLoop)->visualEndTableOffset();

        if (tempEndOffset >= startOffset && tempStartOffset <= endOffset)
        {

            if (concurrentItems.size() >= 1)
            {
                bool bAppend = false;
                /*check all items in the list if the current items interfers although the items are ordered by startIndex
                *we can loose some of them if the endTime of the last Item is before the endTime of the pre last item
                */

                for (QLinkedList<QxtScheduleInternalItem *>::iterator it = concurrentItems.begin(); it != concurrentItems.end(); ++it)
                {
                    int lastStartOffset = (*it)->visualStartTableOffset();
                    int lastEndOffset   = (*it)->visualEndTableOffset();

                    if (tempEndOffset >= lastStartOffset && tempStartOffset <= lastEndOffset)
                    {
                        bAppend = true;
                        break;
                    }
                }

                if (bAppend)
                {
                    concurrentItems.append(allItemsSorted.at(iAllItemLoop));
                }
                else
                {
                    allConcurrentItems.append(concurrentItems);
                    concurrentItems.clear();
                    concurrentItems.append(allItemsSorted.at(iAllItemLoop));
                }
            }
            else
                concurrentItems.append(allItemsSorted.at(iAllItemLoop));

            if (tempStartOffset < startOffset)
                startOffset = tempStartOffset;

            if (tempEndOffset > endOffset)
                endOffset = tempEndOffset;
        }
    }
    if (concurrentItems.size() > 0)
        allConcurrentItems.append(concurrentItems);

    return allConcurrentItems;
}
Пример #18
0
std::unique_ptr<Problem> Pal::extract( const QgsRectangle &extent, const QgsGeometry &mapBoundary )
{
  // to store obstacles
  RTree<FeaturePart *, double, 2, double> *obstacles = new RTree<FeaturePart *, double, 2, double>();

  std::unique_ptr< Problem > prob = qgis::make_unique< Problem >();

  int i, j;

  double bbx[4];
  double bby[4];

  double amin[2];
  double amax[2];

  int max_p = 0;

  LabelPosition *lp = nullptr;

  bbx[0] = bbx[3] = amin[0] = prob->bbox[0] = extent.xMinimum();
  bby[0] = bby[1] = amin[1] = prob->bbox[1] = extent.yMinimum();
  bbx[1] = bbx[2] = amax[0] = prob->bbox[2] = extent.xMaximum();
  bby[2] = bby[3] = amax[1] = prob->bbox[3] = extent.yMaximum();

  prob->pal = this;

  QLinkedList<Feats *> *fFeats = new QLinkedList<Feats *>;

  FeatCallBackCtx context;

  // prepare map boundary
  geos::unique_ptr mapBoundaryGeos( QgsGeos::asGeos( mapBoundary ) );
  geos::prepared_unique_ptr mapBoundaryPrepared( GEOSPrepare_r( QgsGeos::getGEOSHandler(), mapBoundaryGeos.get() ) );

  context.fFeats = fFeats;
  context.obstacles = obstacles;
  context.candidates = prob->candidates;
  context.mapBoundary = mapBoundaryPrepared.get();

  ObstacleCallBackCtx obstacleContext;
  obstacleContext.obstacles = obstacles;
  obstacleContext.obstacleCount = 0;

  // first step : extract features from layers

  int previousFeatureCount = 0;
  int previousObstacleCount = 0;

  QStringList layersWithFeaturesInBBox;

  mMutex.lock();
  const auto constMLayers = mLayers;
  for ( Layer *layer : constMLayers )
  {
    if ( !layer )
    {
      // invalid layer name
      continue;
    }

    // only select those who are active
    if ( !layer->active() )
      continue;

    // check for connected features with the same label text and join them
    if ( layer->mergeConnectedLines() )
      layer->joinConnectedFeatures();

    layer->chopFeaturesAtRepeatDistance();

    layer->mMutex.lock();

    // find features within bounding box and generate candidates list
    context.layer = layer;
    layer->mFeatureIndex->Search( amin, amax, extractFeatCallback, static_cast< void * >( &context ) );
    // find obstacles within bounding box
    layer->mObstacleIndex->Search( amin, amax, extractObstaclesCallback, static_cast< void * >( &obstacleContext ) );

    layer->mMutex.unlock();

    if ( context.fFeats->size() - previousFeatureCount > 0 || obstacleContext.obstacleCount > previousObstacleCount )
    {
      layersWithFeaturesInBBox << layer->name();
    }
    previousFeatureCount = context.fFeats->size();
    previousObstacleCount = obstacleContext.obstacleCount;
  }
  mMutex.unlock();

  prob->nbLabelledLayers = layersWithFeaturesInBBox.size();
  prob->labelledLayersName = layersWithFeaturesInBBox;

  if ( fFeats->isEmpty() )
  {
    delete fFeats;
    delete obstacles;
    return nullptr;
  }

  prob->nbft = fFeats->size();
  prob->nblp = 0;
  prob->featNbLp = new int [prob->nbft];
  prob->featStartId = new int [prob->nbft];
  prob->inactiveCost = new double[prob->nbft];

  Feats *feat = nullptr;

  // Filtering label positions against obstacles
  amin[0] = amin[1] = std::numeric_limits<double>::lowest();
  amax[0] = amax[1] = std::numeric_limits<double>::max();
  FilterContext filterCtx;
  filterCtx.cdtsIndex = prob->candidates;
  filterCtx.pal = this;
  obstacles->Search( amin, amax, filteringCallback, static_cast< void * >( &filterCtx ) );

  if ( isCanceled() )
  {
    const auto constFFeats = *fFeats;
    for ( Feats *feat : constFFeats )
    {
      qDeleteAll( feat->lPos );
      feat->lPos.clear();
    }

    qDeleteAll( *fFeats );
    delete fFeats;
    delete obstacles;
    return nullptr;
  }

  int idlp = 0;
  for ( i = 0; i < prob->nbft; i++ ) /* foreach feature into prob */
  {
    feat = fFeats->takeFirst();

    prob->featStartId[i] = idlp;
    prob->inactiveCost[i] = std::pow( 2, 10 - 10 * feat->priority );

    switch ( feat->feature->getGeosType() )
    {
      case GEOS_POINT:
        max_p = point_p;
        break;
      case GEOS_LINESTRING:
        max_p = line_p;
        break;
      case GEOS_POLYGON:
        max_p = poly_p;
        break;
    }

    // sort candidates by cost, skip less interesting ones, calculate polygon costs (if using polygons)
    max_p = CostCalculator::finalizeCandidatesCosts( feat, max_p, obstacles, bbx, bby );

    // only keep the 'max_p' best candidates
    while ( feat->lPos.count() > max_p )
    {
      // TODO remove from index
      feat->lPos.last()->removeFromIndex( prob->candidates );
      delete feat->lPos.takeLast();
    }

    // update problem's # candidate
    prob->featNbLp[i] = feat->lPos.count();
    prob->nblp += feat->lPos.count();

    // add all candidates into a rtree (to speed up conflicts searching)
    for ( j = 0; j < feat->lPos.count(); j++, idlp++ )
    {
      lp = feat->lPos.at( j );
      //lp->insertIntoIndex(prob->candidates);
      lp->setProblemIds( i, idlp ); // bugfix #1 (maxence 10/23/2008)
    }
    fFeats->append( feat );
  }

  int nbOverlaps = 0;

  while ( !fFeats->isEmpty() ) // foreach feature
  {
    if ( isCanceled() )
    {
      const auto constFFeats = *fFeats;
      for ( Feats *feat : constFFeats )
      {
        qDeleteAll( feat->lPos );
        feat->lPos.clear();
      }

      qDeleteAll( *fFeats );
      delete fFeats;
      delete obstacles;
      return nullptr;
    }

    feat = fFeats->takeFirst();
    while ( !feat->lPos.isEmpty() ) // foreach label candidate
    {
      lp = feat->lPos.takeFirst();
      lp->resetNumOverlaps();

      // make sure that candidate's cost is less than 1
      lp->validateCost();

      prob->addCandidatePosition( lp );
      //prob->feat[idlp] = j;

      lp->getBoundingBox( amin, amax );

      // lookup for overlapping candidate
      prob->candidates->Search( amin, amax, LabelPosition::countOverlapCallback, static_cast< void * >( lp ) );

      nbOverlaps += lp->getNumOverlaps();
    }
    delete feat;
  }
  delete fFeats;

  //delete candidates;
  delete obstacles;

  nbOverlaps /= 2;
  prob->all_nblp = prob->nblp;
  prob->nbOverlap = nbOverlaps;

  return prob;
}
Пример #19
0
//static
CoverArt CoverArtUtils::selectCoverArtForTrack(
        const QString& trackBaseName,
        const QString& albumName,
        const QLinkedList<QFileInfo>& covers) {
    CoverArt art;
    art.info.source = CoverInfo::GUESSED;
    if (covers.isEmpty()) {
        return art;
    }

    PreferredCoverType bestType = NONE;
    const QFileInfo* bestInfo = NULL;

    // If there is a single image then we use it unconditionally. Otherwise
    // we use the priority order described in PreferredCoverType. Notably,
    // if there are multiple image files in the folder we require they match
    // one of the name patterns -- otherwise we run the risk of picking an
    // arbitrary image that happens to be in the same folder as some of the
    // user's music files.
    if (covers.size() == 1) {
        bestInfo = &covers.first();
    } else {
        // TODO(XXX) Sort instead so that we can fall-back if one fails to
        // open?
        foreach (const QFileInfo& file, covers) {
            const QString coverBaseName = file.baseName();
            if (bestType > TRACK_BASENAME &&
                coverBaseName.compare(trackBaseName,
                                      Qt::CaseInsensitive) == 0) {
                bestType = TRACK_BASENAME;
                bestInfo = &file;
                // This is the best type so we know we're done.
                break;
            } else if (bestType > ALBUM_NAME &&
                       coverBaseName.compare(albumName,
                                             Qt::CaseInsensitive) == 0) {
                bestType = ALBUM_NAME;
                bestInfo = &file;
            } else if (bestType > COVER &&
                       coverBaseName.compare(QLatin1String("cover"),
                                             Qt::CaseInsensitive) == 0) {
                bestType = COVER;
                bestInfo = &file;
            } else if (bestType > FRONT &&
                       coverBaseName.compare(QLatin1String("front"),
                                             Qt::CaseInsensitive) == 0) {
                bestType = FRONT;
                bestInfo = &file;
            } else if (bestType > ALBUM &&
                       coverBaseName.compare(QLatin1String("album"),
                                             Qt::CaseInsensitive) == 0) {
                bestType = ALBUM;
                bestInfo = &file;
            } else if (bestType > FOLDER &&
                       coverBaseName.compare(QLatin1String("folder"),
                                             Qt::CaseInsensitive) == 0) {
                bestType = FOLDER;
                bestInfo = &file;
            }
        }
    }

    if (bestInfo != NULL) {
        art.image = QImage(bestInfo->filePath());
        if (!art.image.isNull()) {
            art.info.source = CoverInfo::GUESSED;
            art.info.type = CoverInfo::FILE;
            // TODO() here we may introduce a duplicate hash code
            art.info.hash = CoverArtUtils::calculateHash(art.image);
            art.info.coverLocation = bestInfo->fileName();
            return art;
        }
    }

    return art;
}