void tst_QSet::intersect_int() { QFETCH(int, lhsSize); QFETCH(int, rhsSize); QFETCH(int, intersectSize); // E.g. when lhsSize = 1000, rhsSize = 1000000 and intersectSize = 500: // lhsSize = { 0, 1, ... 1000 } // rhsSize = { 500, 501, ... 1000500 } QSet<int> lhs; for (int i = 0; i < lhsSize; ++i) lhs.insert(i); QSet<int> rhs; const int start = lhsSize - intersectSize; for (int i = start; i < start + rhsSize; ++i) rhs.insert(i); QBENCHMARK { lhs.intersect(rhs); } QVERIFY(lhs.size() == intersectSize); }
void Generator::cloneScreens(KScreen::OutputList &connectedOutputs) { ASSERT_OUTPUTS(connectedOutputs); if (connectedOutputs.isEmpty()) { return; } QSet<QSize> commonSizes; const QSize maxScreenSize = m_currentConfig->screen()->maxSize(); QList<QSet<QSize>> modes; Q_FOREACH(const KScreen::OutputPtr &output, connectedOutputs) { QSet<QSize> modeSizes; Q_FOREACH(const KScreen::ModePtr &mode, output->modes()) { const QSize size = mode->size(); if (size.width() > maxScreenSize.width() || size.height() > maxScreenSize.height()) { continue; } modeSizes.insert(mode->size()); } //If we have nothing to compare against if (commonSizes.isEmpty()) { commonSizes = modeSizes; continue; } commonSizes.intersect(modeSizes); }
void FixCadGeometry::fixNonManifold2() { cout << "fixing non-manifold edges\n (pass 2) ..." << endl; QVector<bool> copy_face(m_Grid->GetNumberOfCells(), true); for (vtkIdType id_cell = 0; id_cell < m_Grid->GetNumberOfCells(); ++id_cell) { vtkIdType N_pts, *pts; m_Grid->GetCellPoints(id_cell, N_pts, pts); if (N_pts < 3) { copy_face[id_cell] = false; break; } QVector<QSet<vtkIdType> > n2c(N_pts); for (int i = 0; i < N_pts; ++i) { for (int j = 0; j < m_Part.n2cGSize(pts[i]); ++j) { n2c[i].insert(m_Part.n2cGG(pts[i], j)); } } QSet<vtkIdType> faces = n2c[0]; for (int i = 1; i < N_pts; ++i) { faces = faces.intersect(n2c[i]); } if (faces.size() > 1) { vtkIdType id_del = id_cell; foreach (vtkIdType id, faces) { id_del = min(id_del, id); } copy_face[id_del] = false; }
void MeshGenerator::fillNeighborStructures() { QList<QSet<int> > vertexElements; vertexElements.reserve(nodeList.count()); for (int i = 0; i < nodeList.count(); i++) vertexElements.push_back(QSet<int>()); for (int i = 0; i < elementList.count(); i++) if (elementList[i].isUsed) for (int elemNode = 0; elemNode < (elementList[i].isTriangle() ? 3 : 4); elemNode++) vertexElements[elementList[i].node[elemNode]].insert(i); for (int i = 0; i < edgeList.count(); i++) { if (edgeList[i].isUsed && edgeList[i].marker != -1) { QSet<int> neighbours = vertexElements[edgeList[i].node[0]]; neighbours.intersect(vertexElements[edgeList[i].node[1]]); assert((neighbours.size() > 0) && (neighbours.size() <= 2)); edgeList[i].neighElem[0] = neighbours.values()[0]; if (neighbours.size() == 2) edgeList[i].neighElem[1] = neighbours.values()[1]; } } }
void WordMatchSearchImpl::query(const QString &req, QVector<Service::Item *> *res) const { QSet<Service::Item*>* resSet = nullptr; QStringList words = req.split(' ', QString::SkipEmptyParts); // Quit if there are no words in query if (words.empty()) return; for (QString &w : words) { InvertedIndex::const_iterator lb, ub; lb = std::lower_bound (_invertedIndex.cbegin(), _invertedIndex.cend(), w, CaseInsensitiveCompare()); ub = std::upper_bound (_invertedIndex.cbegin(), _invertedIndex.cend(), w, CaseInsensitiveComparePrefix()); QSet<Service::Item*> tmpSet; while (lb!=ub) tmpSet.unite(lb++->second); if (resSet == nullptr) resSet = new QSet<Service::Item*>(tmpSet); else resSet->intersect(tmpSet); } if (resSet != nullptr) { for (Service::Item *s : *resSet) res->append(s); delete resSet; } }
QList<const UserBaseInformations*> FreeUser::Search(QMap<QString,AUser*>::const_iterator begin,QMap<QString,AUser*>::const_iterator end, const UserBaseInformations &inf) const { QSet<const UserBaseInformations*> nameSet; QSet<const UserBaseInformations*> emailSet; QSet<const UserBaseInformations*> resultSet; bool set = false; if(inf.GetName() != "") { for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++) { if((*it)->Profile->GetName() == inf.GetName()) nameSet.insert((*it)->Profile); } if(!set) { set = true; resultSet = nameSet; } } if(inf.GetEmail() != "") { for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++) { if((*it)->Profile->GetEmail() == inf.GetEmail()) emailSet.insert((*it)->Profile); } if(!set) { set = true; resultSet = emailSet; } } if(inf.GetName()!="") resultSet.intersect(nameSet); if(inf.GetEmail()!= "") resultSet.intersect(emailSet); //rimuovo se presente me stesso resultSet.remove(this->Profile); return QList<const UserBaseInformations*>::fromSet(resultSet); }
void QgsServerProjectParser::combineExtentAndCrsOfGroupChildren( QDomElement& groupElem, QDomDocument& doc, bool considerMapExtent ) const { QgsRectangle combinedBBox; QSet<QString> combinedCRSSet; bool firstBBox = true; bool firstCRSSet = true; QDomNodeList layerChildren = groupElem.childNodes(); for ( int j = 0; j < layerChildren.size(); ++j ) { QDomElement childElem = layerChildren.at( j ).toElement(); if ( childElem.tagName() != "Layer" ) continue; QgsRectangle bbox = layerBoundingBoxInProjectCrs( childElem, doc ); if ( !bbox.isEmpty() ) { if ( firstBBox ) { combinedBBox = bbox; firstBBox = false; } else { combinedBBox.combineExtentWith( bbox ); } } //combine crs set QSet<QString> crsSet; if ( crsSetForLayer( childElem, crsSet ) ) { if ( firstCRSSet ) { combinedCRSSet = crsSet; firstCRSSet = false; } else { combinedCRSSet.intersect( crsSet ); } } } QgsConfigParserUtils::appendCrsElementsToLayer( groupElem, doc, combinedCRSSet.toList(), supportedOutputCrsList() ); QgsCoordinateReferenceSystem groupCRS = projectCrs(); if ( considerMapExtent ) { QgsRectangle mapRect = mapRectangle(); if ( !mapRect.isEmpty() ) { combinedBBox = mapRect; } } QgsConfigParserUtils::appendLayerBoundingBoxes( groupElem, doc, combinedBBox, groupCRS, combinedCRSSet.toList(), supportedOutputCrsList() ); }
bool Nfa::runNfa(QString string) { QSet<Node*>* set = new QSet<Node*>(); set->insert(q0); /* Sending -1 to traverse implies sequential execution */ QSet<Node*>* endingStates = traverse(set, &string, -1); endingStates->intersect(*f); bool intersects = endingStates->count() > 0; delete endingStates; // Remove memory allocated for finalStates. return intersects; }
QList<Task*> DefaultConvertFileTask::onSubTaskFinished(Task *subTask) { QList<Task*> result; CHECK(!subTask->hasError() && !subTask->isCanceled(), result); CHECK(!hasError() && !isCanceled(), result); if (saveTask == subTask) { return result; } SAFE_POINT_EXT(loadTask == subTask, setError("Unknown subtask"), result); bool mainThread = false; Document *srcDoc = loadTask->getDocument(mainThread); SAFE_POINT_EXT(NULL != srcDoc, setError("NULL document"), result); DocumentFormatRegistry *dfr = AppContext::getDocumentFormatRegistry(); DocumentFormat *df = dfr->getFormatById(targetFormat); SAFE_POINT_EXT(NULL != df, setError("NULL document format"), result); QSet<GObjectType> selectedFormatObjectsTypes = df->getSupportedObjectTypes(); QSet<GObjectType> inputFormatObjectTypes; QListIterator<GObject*> objectsIterator(srcDoc->getObjects()); while (objectsIterator.hasNext()) { GObject *obj = objectsIterator.next(); inputFormatObjectTypes << obj->getGObjectType(); } inputFormatObjectTypes.intersect(selectedFormatObjectsTypes); if (inputFormatObjectTypes.empty()) { setError(tr("The formats are not compatible: %1 and %2").arg(srcDoc->getDocumentFormatId()).arg(targetFormat)); return result; } QString ext = targetFormat; if (!df->getSupportedDocumentFileExtensions().isEmpty()) { ext = df->getSupportedDocumentFileExtensions().first(); } if (targetUrl.isEmpty()) { QString fileName = srcDoc->getName() + "." + ext; targetUrl = GUrlUtils::rollFileName(workingDir + fileName, QSet<QString>()); } else { if (QFileInfo(targetFormat).suffix() != ext) { targetUrl += "." + ext; } targetUrl = GUrlUtils::rollFileName(targetUrl, QSet<QString>()); } IOAdapterFactory *iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(IOAdapterUtils::url2io(srcDoc->getURL())); Document *dstDoc = srcDoc->getSimpleCopy(df, iof, srcDoc->getURL()); saveTask = new SaveDocumentTask(dstDoc, iof, targetUrl); result << saveTask; return result; }
void QgsProjectParser::combineExtentAndCrsOfGroupChildren( QDomElement& groupElem, QDomDocument& doc ) const { QgsRectangle combinedBBox; QSet<QString> combinedCRSSet; bool firstBBox = true; bool firstCRSSet = true; QDomNodeList layerChildren = groupElem.childNodes(); for ( int j = 0; j < layerChildren.size(); ++j ) { QDomElement childElem = layerChildren.at( j ).toElement(); if ( childElem.tagName() != "Layer" ) continue; QgsRectangle bbox = layerBoundingBoxInProjectCRS( childElem ); if ( !bbox.isEmpty() ) { if ( firstBBox ) { combinedBBox = bbox; firstBBox = false; } else { combinedBBox.combineExtentWith( &bbox ); } } //combine crs set QSet<QString> crsSet; if ( crsSetForLayer( childElem, crsSet ) ) { if ( firstCRSSet ) { combinedCRSSet = crsSet; firstCRSSet = false; } else { combinedCRSSet.intersect( crsSet ); } } } appendCRSElementsToLayer( groupElem, doc, combinedCRSSet.toList() ); const QgsCoordinateReferenceSystem& groupCRS = projectCRS(); appendLayerBoundingBoxes( groupElem, doc, combinedBBox, groupCRS ); }
void tst_QSet::intersect_complexType() { QFETCH(int, lhsSize); QFETCH(int, rhsSize); QFETCH(int, intersectSize); QSet<ComplexType> lhs; for (int i = 0; i < lhsSize; ++i) lhs.insert(ComplexType(i)); QSet<ComplexType> rhs; const int start = lhsSize - intersectSize; for (int i = start; i < start + rhsSize; ++i) rhs.insert(ComplexType(i)); QBENCHMARK { lhs.intersect(rhs); } }
bool KonsoleKalendar::printCalendarList() { Akonadi::CollectionFetchJob *job = new Akonadi::CollectionFetchJob(Akonadi::Collection::root(), Akonadi::CollectionFetchJob::Recursive); QStringList mimeTypes = QStringList() << QStringLiteral("text/calendar") << KCalCore::Event::eventMimeType() << KCalCore::Todo::todoMimeType() << KCalCore::Journal::journalMimeType(); job->fetchScope().setContentMimeTypes(mimeTypes); QEventLoop loop; QObject::connect(job, &Akonadi::CollectionFetchJob::result, &loop, &QEventLoop::quit); job->start(); loop.exec(); if (job->error() != 0) { return false; } Akonadi::Collection::List collections = job->collections(); if (collections.isEmpty()) { cout << i18n("There are no calendars available.").toLocal8Bit().data() << endl; } else { cout << "--------------------------" << endl; QSet<QString> mimeTypeSet = mimeTypes.toSet(); foreach (const Akonadi::Collection &collection, collections) { if (!mimeTypeSet.intersect(collection.contentMimeTypes().toSet()).isEmpty()) { QString colId = QString::number(collection.id()).leftJustified(6, QLatin1Char(' ')); colId += QLatin1String("- "); bool readOnly = !(collection.rights() & Akonadi::Collection::CanCreateItem || collection.rights() & Akonadi::Collection::CanChangeItem || collection.rights() & Akonadi::Collection::CanDeleteItem); QString readOnlyString = readOnly ? i18n("(Read only)") + QLatin1Char(' ') : QString(); cout << colId.toLocal8Bit().data() << readOnlyString.toLocal8Bit().constData() << collection.displayName().toLocal8Bit().data() << endl; } } } return true; }
bool CollectionFilterModel::filterAcceptsRow(int row, const QModelIndex &parent) const { bool accepted = true; const QModelIndex index = sourceModel()->index(row, 0, parent); const Akonadi::Collection collection = index.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>(); if (!collection.isValid()) { return false; } if (!mContentMimeTypes.isEmpty()) { QSet<QString> contentMimeTypes = collection.contentMimeTypes().toSet(); accepted = accepted && !(contentMimeTypes.intersect(mContentMimeTypes).isEmpty()); } if (mRights != Akonadi::Collection::ReadOnly) { accepted = accepted && (collection.rights() & mRights); } return accepted; }
void TestProject::runTestsForFiles(const FileNameList &files, CustomRunConfiguration *configuration) const { Q_ASSERT (configuration != NULL); Q_ASSERT (!gtestIncludeFiles_.isEmpty ()); QSet<FileName> testFiles = getDependentFiles (gtestIncludeFiles_).toSet (); QSet<FileName> dependentFiles = getDependentFiles (files).toSet (); testFiles.intersect (dependentFiles); if (testFiles.isEmpty ()) { return; } QStringList testCases = getTestCases (testFiles); if (testCases.isEmpty ()) { return; } QString arguments = gtestFilter.arg(testCases.join (gtestFilterSeparator)); configuration->setArguments (arguments); runTests (configuration); }
bool Drive::recalculate(QList<Tag *> tags) { if(this->results_.size() > 0) { beginRemoveRows(QModelIndex(), 0, this->results_.size()-1); this->results_ = QFileInfoList(); endRemoveRows(); } QFileInfoList newResults; if(tags.size() == 0) { this->parent_->setExpressionLabel(tr("All Files")); newResults = this->directory_->entryInfoList(QDir::Files); } else { QString expressionLabel = ""; QSet<QString> fileNames = tags[0]->allFiles(); for (int i = 0; i < tags.size(); i += TAG_TREE_COLUMNS) { expressionLabel.append(tags[i]->data(0).toString()); fileNames = fileNames.intersect(tags[i]->allFiles()); if (i < tags.size() - TAG_TREE_COLUMNS) expressionLabel.append(tr(" ∩ ")); } this->parent_->setExpressionLabel(expressionLabel); for(auto i = fileNames.begin(); i != fileNames.end(); ++i) { newResults.append(QFileInfo(*i)); } } if(newResults.size() > 0) { beginInsertRows(QModelIndex(), 0, newResults.size()-1); this->results_ = newResults; endInsertRows(); } this->sort(this->sortColumn_,this->sortOrder_); emit(doneCalculating()); return true; }
bool GamesProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &/*sourceParent*/) const { GamesModel *model = qobject_cast<GamesModel *>(sourceModel()); if (!model) return false; const ServerInfo_Game &game = model->getGame(sourceRow); if (!unavailableGamesVisible) { if (game.player_count() == game.max_players()) return false; if (game.started()) return false; if (!(ownUser->user_level() & ServerInfo_User::IsRegistered)) if (game.only_registered()) return false; } if (!passwordProtectedGamesVisible && game.with_password()) return false; if (!gameNameFilter.isEmpty()) if (!QString::fromStdString(game.description()).contains(gameNameFilter, Qt::CaseInsensitive)) return false; if (!creatorNameFilter.isEmpty()) if (!QString::fromStdString(game.creator_info().name()).contains(creatorNameFilter, Qt::CaseInsensitive)) return false; QSet<int> gameTypes; for (int i = 0; i < game.game_types_size(); ++i) gameTypes.insert(game.game_types(i)); if (!gameTypeFilter.isEmpty() && gameTypes.intersect(gameTypeFilter).isEmpty()) return false; if ((maxPlayersFilterMin != -1) && (game.max_players() < maxPlayersFilterMin)) return false; if ((maxPlayersFilterMax != -1) && (game.max_players() > maxPlayersFilterMax)) return false; return true; }
/// Returns the default action for a given list of \a uris representing /// Tracker resources. If the URIs represent objects of different types /// (e.g. one is an image, other is an audio file), a default action cannot be /// constructed in this manner. In that case the \c nie:mimeType properties /// of all \a uris are checked and we attempt to construct a default action /// based on them (passing \c nie:url as argument) (\see /// Action::defaultAction(const QString& uri) also). If both ways fail, it /// falls back to the first action returned by actions(). If there are none, /// an invalid Action is returned. Action Action::defaultAction(const QStringList& uris) { if (uris.isEmpty()) return Action(); // FIXME: this function doesn't include the hack for nfo:Bookmark & // nfo:WebHistory. QList<QStringList> mimeTypes = mimeTypesForUris(uris); LCA_DEBUG << "pseudo mimes per uri" << mimeTypes; QSet<QString> defApps; for (int i = 0; i < mimeTypes.size(); ++i) { QSet<QString> defs; Q_FOREACH (const QString& mimeType, mimeTypes[i]) { QString def = defaultAppForContentType(mimeType); if (!def.isEmpty()) defs << def; } if (i == 0) defApps = defs; else defApps.intersect(defs); }
//##################################################################### // Function mergeBlocks //##################################################################### void StructureConstructor::mergeBlocks() { qStableSort(mSeparatorList.begin(), mSeparatorList.end(), Separator::lessThanWeight); int separatorIndex = 0; while(separatorIndex < mSeparatorList.size()) { int minWeight = mSeparatorList[separatorIndex].mWeight; QVector<QSet<BentoBlock*> > mergeBlockList; QSet<BentoBlock*> tempBlockPool = mSeparatorList[separatorIndex].blocks(); mergeBlockList.append(tempBlockPool); separatorIndex++; while(separatorIndex < mSeparatorList.size()) { if(mSeparatorList[separatorIndex].mWeight > minWeight) break; tempBlockPool = mSeparatorList[separatorIndex].blocks(); // has two QVector<int> mergeIndexArray; for (int i=mergeBlockList.size()-1; i>=0; i--) { QSet<BentoBlock*> intersectBlockPool = mergeBlockList[i]; // has only one if (!intersectBlockPool.intersect(tempBlockPool).isEmpty()) mergeIndexArray.append(i); } foreach (int index, mergeIndexArray) tempBlockPool = tempBlockPool.unite(mergeBlockList[index]); mergeBlockList.append(tempBlockPool); foreach (int index, mergeIndexArray) mergeBlockList.remove(index); separatorIndex++; } if (separatorIndex < mSeparatorList.size()) foreach(QSet<BentoBlock*> blockPool, mergeBlockList) attachToParent(blockPool, false, separatorIndex); else attachToParent(mergeBlockList[0]); } }
bool Nfa::runNfaP(QString string) { /* Create the partition of states */ QList<QSet<Node*>*>* part = partition(); /* Allocate threads depending on size partitioning */ pthread_t* threads = (pthread_t*)malloc(part->size()*sizeof(pthread_t)); /* Allocate params for each thread */ NfaParams* params = (NfaParams*)malloc(part->size()*sizeof(NfaParams)); /* Initial state set will be stored here later in the code */ QSet<Node*>* initialStateSet = NULL; /* Loop counter */ int i; /* * IMPORTANT: An assumption is being made here that the very last set * in the list contains ONLY the inital state * */ for(i = 0; i < part->size(); i++) { params[i].nfa = this; params[i].str = &string; /* If the set is the initial state, mark it as such */ if (i == part->size() - 1) { initialStateSet = part->at(i); params[i].isInitial = true; } else { params[i].isInitial = false; } /* Assign the params being sent to the thread the list it will be working on */ params[i].nodes = part->at(i); /* Send off the thread! */ pthread_create(&threads[i], NULL, &traverseP, ¶ms[i]); } /* Reap the threads */ for (i = 0; i < part->size(); i++) { int* ptr; pthread_join(threads[i], (void**)&ptr); } bool intersects = false; /* Again, we're assuming the last list is the inital state so we aren't checking it */ /* If there's any intersection between the initial set and the final sets then it was a valid string */ for(i = 0; i < part->size() - 1; i++) { if(initialStateSet->intersect(*part->at(i)).size() > 0) intersects = true; } free(threads); free(params); return intersects; }
QList<const UserBaseInformations*> ExecutiveUser::Search(QMap<QString,AUser*>::const_iterator begin,QMap<QString,AUser*>::const_iterator end, const UserBaseInformations &inf) const { //prima parte di codice QSet<const UserBaseInformations*> nameSet; QSet<const UserBaseInformations*> emailSet; QSet<const UserBaseInformations*> surnameSet; QSet<const UserBaseInformations*> ageSet; QSet<const UserBaseInformations*> genderSet; QSet<const UserBaseInformations*> countrySet; QSet<const UserBaseInformations*> citySet; QSet<const UserBaseInformations*> streetSet; bool set = false; QSet<const UserBaseInformations*> resultSet; if(inf.GetName() != "") { for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++) { if((*it)->Profile->GetName() == inf.GetName()) nameSet.insert((*it)->Profile); } if(!set) { set = true; resultSet = nameSet; } } if(inf.GetEmail() != "") { for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++) { if((*it)->Profile->GetEmail() == inf.GetEmail()) emailSet.insert((*it)->Profile); } if(!set) { set = true; resultSet = emailSet; } } if(inf.GetSurname() != "") { for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++) { if((*it)->Profile->GetSurname() == inf.GetSurname()) surnameSet.insert((*it)->Profile); } if(!set) { set = true; resultSet = surnameSet; } } if(inf.GetAge() != 0) { for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++) { if((*it)->Profile->GetAge() == inf.GetAge()) ageSet.insert((*it)->Profile); } if(!set) { set = true; resultSet = ageSet; } } if(inf.GetGender() != 0) { for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++) { if((*it)->Profile->GetGender() == inf.GetGender()) genderSet.insert((*it)->Profile); } if(!set) { set = true; resultSet = genderSet; } } if(inf.GetCountry() != 0) { for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++) { if((*it)->Profile->GetCountry() == inf.GetCountry()) countrySet.insert((*it)->Profile); } if(!set) { set = true; resultSet = countrySet; } } if(inf.GetCity() != 0) { for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++) { if((*it)->Profile->GetCity() == inf.GetCity()) citySet.insert((*it)->Profile); } if(!set) { set = true; resultSet = citySet; } } if(inf.GetStreet() != 0) { for(QMap<QString,AUser*>::const_iterator it = begin;it != end ;it++) { if((*it)->Profile->GetStreet() == inf.GetStreet()) streetSet.insert((*it)->Profile); } if(!set) { set = true; resultSet = streetSet; } } if(inf.GetName()!="") resultSet.intersect(nameSet); if(inf.GetEmail()!= "") resultSet.intersect(emailSet); if(inf.GetSurname()!="") resultSet.intersect(surnameSet); if(inf.GetAge()!= 0) resultSet.intersect(ageSet); if(inf.GetGender() != 0) resultSet.intersect(genderSet); if(inf.GetCountry()!="") resultSet.intersect(countrySet); if(inf.GetCity()!= 0) resultSet.intersect(citySet); if(inf.GetStreet() != 0) resultSet.intersect(streetSet); //rimuovo se presente me stesso resultSet.remove(this->Profile); return QList<const UserBaseInformations*>::fromSet(resultSet); }
// No QSet::intersects until Qt 5.6 template <class T> bool setIntersects(const QSet<T> &this_, const QSet<T> &other) { QSet<T> s = this_; return !s.intersect(other).isEmpty(); }
void FillIn::updateMetrics() { QSharedPointer<Food> selectedFood = getSelectedFood(); if (!selectedFood) { ui.btnFillIn->setEnabled(false); ui.txtAmount->setText(""); ui.txtAverageError->setText(""); ui.txtLargestError->setText(""); ui.txtLargestErrorField->setText(""); ui.txtLargestErrorSelectedVal->setText(""); ui.txtLargestErrorYourVal->setText(""); ui.txtNumFields->setText(""); ui.txtStdDev->setText(""); fillinNutrients.clear(); } else { ui.btnFillIn->setEnabled(true); // TODO: Break this up into multiple methods // Step 1. Compute the amount of the selected food needed to give the same // number of calories as the original food QSharedPointer<const Nutrient> calories = Nutrient::getNutrientByName(Nutrient::CALORIES_NAME); FoodAmount selectedBaseAmount = selectedFood->getBaseAmount(); double caloriesInOriginal = originalNutrients[calories->getId()].getAmount(); double caloriesInSelectedBaseAmount = selectedBaseAmount.getScaledNutrients()[calories->getId()].getAmount(); qDebug() << "Calories in original: " << caloriesInOriginal; qDebug() << "Calories in selected base amount: " << selectedBaseAmount.getScaledNutrients()[calories->getId()].getAmount(); FoodAmount selectedAmount = selectedBaseAmount * (caloriesInOriginal / caloriesInSelectedBaseAmount); ui.txtAmount->setText(QString::number(selectedAmount.getAmount(), 'f', 2) + " " + selectedAmount.getUnit()->getAbbreviation()); // Step 2. Determine which nutrients are in common, and which can be filled in QMap<QString, NutrientAmount> selectedNutrients = selectedAmount.getScaledNutrients(); QSet<QString> originalNutrientIds = originalNutrients.keys().toSet(); QSet<QString> selectedNutrientIds = selectedNutrients.keys().toSet(); QSet<QString> commonNutrientIds = originalNutrientIds; commonNutrientIds.intersect(selectedNutrientIds); QSet<QString> fillinNutrientIds = selectedNutrientIds; fillinNutrientIds.subtract(originalNutrientIds); qDebug() << "Original nutrients: " << originalNutrientIds.size(); qDebug() << "Selected nutrients: " << selectedNutrientIds.size(); qDebug() << "Common nutrients: " << commonNutrientIds.size(); qDebug() << "Fill-in nutrients: " << fillinNutrientIds.size(); ui.txtNumFields->setText(QString::number(fillinNutrientIds.size())); // Step 3. Compute the percent error for each common nutrient, and compute // the average, also making note of the largest. QMap<QString, double> pctError; double sumOfErrors = 0; QString largestErrorId; double largestError = 0; for (QSet<QString>::const_iterator i = commonNutrientIds.begin(); i != commonNutrientIds.end(); ++i) { double originalValue = originalNutrients[*i].getAmount(); if (originalValue > 0) { double selectedValue = selectedNutrients[*i].getAmount(); double error = std::fabs(originalValue - selectedValue) / originalValue; pctError[*i] = error; sumOfErrors += error; if (error > largestError) { largestErrorId = *i; largestError = error; } qDebug() << "Error for common nutrient " << *i << " (" << originalNutrients[*i].getNutrient()->getName() << ") is " << error; } } double avgError = sumOfErrors / pctError.size(); ui.txtAverageError->setText(QString::number(avgError * 100, 'f', 2) + " %"); ui.txtLargestError->setText(QString::number(largestError * 100, 'f', 2) + " %"); ui.txtLargestErrorField->setText(originalNutrients[largestErrorId].getNutrient()->getName()); ui.txtLargestErrorYourVal->setText (QString::number(originalNutrients[largestErrorId].getAmount(), 'f', 2) + " " + originalNutrients[largestErrorId].getUnit()->getAbbreviation()); ui.txtLargestErrorSelectedVal->setText (QString::number(selectedNutrients[largestErrorId].getAmount(), 'f', 2) + " " + selectedNutrients[largestErrorId].getUnit()->getAbbreviation()); // Step 4. Compute the standard deviation of the error percentages double sumOfDistancesSquared = 0; for (QMap<QString, double>::const_iterator i = pctError.begin(); i != pctError.end(); ++i) { double distance = i.value() - avgError; sumOfDistancesSquared += (distance * distance); } double stdDev = std::sqrt(sumOfDistancesSquared / pctError.size()); ui.txtStdDev->setText(QString::number(stdDev, 'f', 2)); // Step 5. Save a copy of all of the fill-in nutrient amounts fillinNutrients.clear(); for (QSet<QString>::const_iterator i = fillinNutrientIds.begin(); i != fillinNutrientIds.end(); ++i) { fillinNutrients[*i] = selectedNutrients[*i]; } } }
bool MeshGenerator::writeToHermes() { // edges XMLSubdomains::edges_type edges; for (int i = 0; i < edgeList.count(); i++) if (edgeList[i].isUsed && edgeList[i].marker != -1) edges.ed().push_back(XMLSubdomains::ed(edgeList[i].node[0], edgeList[i].node[1], QString::number(edgeList[i].marker).toStdString(), i)); // curved edges XMLMesh::curves_type curves; for (int i = 0; i<edgeList.count(); i++) { if (edgeList[i].marker != -1) { // curve if (Agros2D::scene()->edges->at(edgeList[i].marker)->angle() > 0.0 && Agros2D::scene()->edges->at(edgeList[i].marker)->isCurvilinear()) { int segments = Agros2D::scene()->edges->at(edgeList[i].marker)->segments(); // subdivision angle and chord double theta = deg2rad(Agros2D::scene()->edges->at(edgeList[i].marker)->angle()) / double(segments); double chord = 2 * Agros2D::scene()->edges->at(edgeList[i].marker)->radius() * sin(theta / 2.0); // length of short chord double chordShort = (nodeList[edgeList[i].node[1]] - nodeList[edgeList[i].node[0]]).magnitude(); // direction Point center = Agros2D::scene()->edges->at(edgeList[i].marker)->center(); int direction = (((nodeList[edgeList[i].node[0]].x-center.x)*(nodeList[edgeList[i].node[1]].y-center.y) - (nodeList[edgeList[i].node[0]].y-center.y)*(nodeList[edgeList[i].node[1]].x-center.x)) > 0) ? 1 : -1; double angle = direction * theta * chordShort / chord; curves.arc().push_back(XMLMesh::arc(edgeList[i].node[0], edgeList[i].node[1], rad2deg(angle))); } } } // move nodes (arcs) for (int i = 0; i<edgeList.count(); i++) { // assert(edgeList[i].marker >= 0); // markers changed to marker - 1, check... if (edgeList[i].marker != -1) { // curve if (Agros2D::scene()->edges->at(edgeList[i].marker)->angle() > 0.0 && Agros2D::scene()->edges->at(edgeList[i].marker)->isCurvilinear()) { // angle Point center = Agros2D::scene()->edges->at(edgeList[i].marker)->center(); double pointAngle1 = atan2(center.y - nodeList[edgeList[i].node[0]].y, center.x - nodeList[edgeList[i].node[0]].x) - M_PI; double pointAngle2 = atan2(center.y - nodeList[edgeList[i].node[1]].y, center.x - nodeList[edgeList[i].node[1]].x) - M_PI; nodeList[edgeList[i].node[0]].x = center.x + Agros2D::scene()->edges->at(edgeList[i].marker)->radius() * cos(pointAngle1); nodeList[edgeList[i].node[0]].y = center.y + Agros2D::scene()->edges->at(edgeList[i].marker)->radius() * sin(pointAngle1); nodeList[edgeList[i].node[1]].x = center.x + Agros2D::scene()->edges->at(edgeList[i].marker)->radius() * cos(pointAngle2); nodeList[edgeList[i].node[1]].y = center.y + Agros2D::scene()->edges->at(edgeList[i].marker)->radius() * sin(pointAngle2); } } } // vertices XMLMesh::vertices_type vertices; for (int i = 0; i<nodeList.count(); i++) vertices.v().push_back(std::auto_ptr<XMLMesh::v>(new XMLMesh::v(QString::number(nodeList[i].x).toStdString(), QString::number(nodeList[i].y).toStdString(), i))); // elements XMLSubdomains::elements_type elements; for (int i = 0; i<elementList.count(); i++) if (elementList[i].isUsed) if (elementList[i].isTriangle()) elements.el().push_back(XMLSubdomains::t_t(elementList[i].node[0], elementList[i].node[1], elementList[i].node[2], QString::number(elementList[i].marker).toStdString(), i)); else elements.el().push_back(XMLSubdomains::q_t(elementList[i].node[0], elementList[i].node[1], elementList[i].node[2], QString::number(elementList[i].marker).toStdString(), i, elementList[i].node[3])); // find edge neighbours // for each vertex list elements that it belogns to QList<QSet<int> > vertexElements; vertexElements.reserve(nodeList.count()); for (int i = 0; i < nodeList.count(); i++) vertexElements.push_back(QSet<int>()); for (int i = 0; i < elementList.count(); i++) if (elementList[i].isUsed) for(int elemNode = 0; elemNode < (elementList[i].isTriangle() ? 3 : 4); elemNode++) vertexElements[elementList[i].node[elemNode]].insert(i); for (int i = 0; i < edgeList.count(); i++) { if (edgeList[i].isUsed && edgeList[i].marker != -1) { QSet<int> neighbours = vertexElements[edgeList[i].node[0]]; neighbours.intersect(vertexElements[edgeList[i].node[1]]); assert((neighbours.size() > 0) && (neighbours.size() <= 2)); edgeList[i].neighElem[0] = neighbours.values()[0]; if(neighbours.size() == 2) edgeList[i].neighElem[1] = neighbours.values()[1]; } } // subdomains XMLSubdomains::subdomains subdomains; if (Agros2D::problem()->fieldInfos().isEmpty()) { // one domain XMLSubdomains::subdomain subdomain(Agros2D::problem()->fieldInfos().begin().value()->fieldId().toStdString()); subdomains.subdomain().push_back(subdomain); } else { // more subdomains foreach (FieldInfo* fieldInfo, Agros2D::problem()->fieldInfos()) { XMLSubdomains::subdomain subdomain(fieldInfo->fieldId().toStdString()); subdomain.elements().set(XMLSubdomains::subdomain::elements_type()); subdomain.boundary_edges().set(XMLSubdomains::subdomain::boundary_edges_type()); subdomain.inner_edges().set(XMLSubdomains::subdomain::inner_edges_type()); for (int i = 0; i<elementList.count(); i++) if (elementList[i].isUsed && (Agros2D::scene()->labels->at(elementList[i].marker)->marker(fieldInfo) != SceneMaterialContainer::getNone(fieldInfo))) subdomain.elements()->i().push_back(i); QList<int> unassignedEdges; for (int i = 0; i < edgeList.count(); i++) { if (edgeList[i].isUsed && edgeList[i].marker != -1) { int numNeighWithField = 0; for (int neigh_i = 0; neigh_i < 2; neigh_i++) { int neigh = edgeList[i].neighElem[neigh_i]; if (neigh != -1) { if (Agros2D::scene()->labels->at(elementList[neigh].marker)->marker(fieldInfo) != SceneMaterialContainer::getNone(fieldInfo)) numNeighWithField++; } } // edge has boundary condition prescribed for this field bool hasFieldBoundaryCondition = (Agros2D::scene()->edges->at(edgeList[i].marker)->hasMarker(fieldInfo) && (Agros2D::scene()->edges->at(edgeList[i].marker)->marker(fieldInfo) != SceneBoundaryContainer::getNone(fieldInfo))); if (numNeighWithField == 1) { // edge is on "boundary" of the field, should have boundary condition prescribed if (!hasFieldBoundaryCondition) if (!unassignedEdges.contains(edgeList[i].marker)) unassignedEdges.append(edgeList[i].marker); subdomain.boundary_edges()->i().push_back(i); } else if (numNeighWithField == 2) { // todo: we could enforce not to have boundary conditions prescribed inside: // assert(!hasFieldBoundaryCondition); subdomain.inner_edges()->i().push_back(i); } } } // not assigned boundary if (unassignedEdges.count() > 0) { QString list; foreach (int index, unassignedEdges) list += QString::number(index) + ", "; Agros2D::log()->printError(tr("Mesh generator"), tr("Boundary condition for %1 is not assigned on following edges: %2").arg(fieldInfo->name()).arg(list.left(list.count() - 2))); return false; } subdomains.subdomain().push_back(subdomain); }
void ExchangeApproveDialog::appendRequestItems(const QList<IRosterExchangeItem> &AItems) { for (QList<IRosterExchangeItem>::const_iterator it=AItems.constBegin(); it!=AItems.constEnd(); ++it) { QString actionText; IRosterItem ritem = FRoster->findItem(it->itemJid); if (it->action == ROSTEREXCHANGE_ACTION_ADD) { if (ritem.isNull()) { if (it->groups.isEmpty()) actionText = tr("Add new contact '%1 <%2>'").arg(it->name,it->itemJid.uBare()); else actionText = tr("Add new contact '%1 <%2>' to the group: %3").arg(it->name,it->itemJid.uBare(),groupSetToString(it->groups)); ui.chbSubscribe->setVisible(true); } else if (!it->groups.isEmpty()) { actionText = tr("Copy contact '%1' to the group: %2").arg(contactName(it->itemJid),groupSetToString(it->groups-ritem.groups)); } } else if (!ritem.isNull() && it->action == ROSTEREXCHANGE_ACTION_DELETE) { QSet<QString> oldGroups = it->groups; oldGroups.intersect(ritem.groups); if (it->groups.isEmpty()) actionText = tr("Remove contact '%1' from contact list").arg(contactName(it->itemJid)); else actionText = tr("Remove contact '%1' from the group: %2").arg(contactName(it->itemJid),groupSetToString(oldGroups)); } else if (!ritem.isNull() && it->action == ROSTEREXCHANGE_ACTION_MODIFY) { QSet<QString> newGroups = it->groups - ritem.groups; QSet<QString> oldGroups = ritem.groups - it->groups; if (it->name != ritem.name) { actionText = tr("Rename contact '%1' to '%2'").arg(contactName(it->itemJid),it->name); } if (!newGroups.isEmpty()) { if (!actionText.isEmpty()) actionText += "; "; actionText += tr("Copy contact '%1' to the group: %2").arg(contactName(it->itemJid),groupSetToString(newGroups)); } if (!oldGroups.isEmpty()) { if (!actionText.isEmpty()) actionText += "; "; actionText += tr("Remove contact '%1' from the group: %2").arg(contactName(it->itemJid),groupSetToString(oldGroups)); } } if (!actionText.isEmpty()) { QTableWidgetItem *actionItem = new QTableWidgetItem; actionItem->setFlags(Qt::ItemIsEnabled|Qt::ItemIsUserCheckable); actionItem->setCheckState(Qt::Checked); actionItem->setText(actionText); ui.tbwItems->setRowCount(ui.tbwItems->rowCount()+1); ui.tbwItems->setItem(ui.tbwItems->rowCount()-1,COL_ACTION,actionItem); ui.tbwItems->verticalHeader()->SETRESIZEMODE(actionItem->row(),QHeaderView::ResizeToContents); FItems.insert(actionItem,*it); } } }