Example #1
0
void MusicDataModel::deactivateDuplicates(const DupResolutionCriteria &criteria) {
    int i = 0;
    QList<QStringList> dList;
    QList< QPair<QString, QPair<int, int> > > dbPairMirrorList; /* index and crit comparison val in second pair */
    QHash<QString, QPair<int,int> > bestForDestination; /* map destination to index and crit comparison value*/

    /* initialize a pair list that mirrors the destinations/indices inside our database */
    for (QList<MusicFileData>::const_iterator it = this->db.begin(); it != this->db.end(); ++it, ++i) {
        if (it->isGood) {
            switch(criteria) {
            case BITRATE:
                dbPairMirrorList.append(QPair<QString,QPair<int,int> >(it->destination, QPair<int,int>(i, it->bitrate)));
                break;

            case DURATION:
                dbPairMirrorList.append(QPair<QString,QPair<int,int> >(it->destination, QPair<int,int>(i, it->duration)));
                break;

            case SAMPLERATE:
                dbPairMirrorList.append(QPair<QString,QPair<int,int> >(it->destination, QPair<int,int>(i, it->samplerate)));
                break;
            }
        }
    }

    /* now, traverse the pairlist to find the duplicates */
    for (QList< QPair<QString,QPair<int,int> > >::const_iterator it = dbPairMirrorList.begin(), cit;
         it != dbPairMirrorList.end(); ++it) {

        /* traverse from current index until the end */
        for (cit = it; cit != dbPairMirrorList.end(); ++cit) {
            /* act on destination match */
            QString f = it->first;

            if (f == cit->first) {
                if (bestForDestination.value(f, QPair<int,int>(-1,-1)).second < cit->second.second) {
                    if (bestForDestination.contains(f)) {
                        this->db[bestForDestination[f].first].isGood = false;
                        bestForDestination[f].first  = cit->second.first;
                        bestForDestination[f].second = cit->second.second;
                        dbPairMirrorList.removeOne(*cit);
                        cit = it;
                    } else {
                        bestForDestination[f].first  = cit->second.first;
                        bestForDestination[f].second = cit->second.second;
                    }
                } else {
                    this->db[cit->second.first].isGood = false;
                    dbPairMirrorList.removeOne(*cit);
                    cit = it;
                }
            }
        }
    }
}
Example #2
0
void QmlProfilerTool::populateFileFinder(QString projectDirectory, QString activeSysroot)
{
    // Initialize filefinder with some sensible default
    QStringList sourceFiles;
    QList<Project *> projects = SessionManager::projects();
    if (Project *startupProject = SessionManager::startupProject()) {
        // startup project first
        projects.removeOne(startupProject);
        projects.insert(0, startupProject);
    }
    foreach (Project *project, projects)
        sourceFiles << project->files(Project::SourceFiles);

    if (!projects.isEmpty()) {
        if (projectDirectory.isEmpty())
            projectDirectory = projects.first()->projectDirectory().toString();

        if (activeSysroot.isEmpty()) {
            if (Target *target = projects.first()->activeTarget())
                if (RunConfiguration *rc = target->activeRunConfiguration())
                    activeSysroot = sysroot(rc);
        }
    }

    d->m_projectFinder.setProjectDirectory(projectDirectory);
    d->m_projectFinder.setProjectFiles(sourceFiles);
    d->m_projectFinder.setSysroot(activeSysroot);
}
	void EventsSettingsManager::RebuildAddableEvents ()
	{
		QList<QString> remainingEvents
		{
			AN::TypeIMMUCMsg,
			AN::TypeIMIncMsg,
			AN::TypeIMMUCHighlight,
			AN::TypeIMStatusChange,
			AN::TypeIMEventTuneChange,
			AN::TypeIMEventMoodChange,
			AN::TypeIMEventActivityChange,
			AN::TypeIMEventLocationChange
		};

		for (int i = 0, rc = Model_->rowCount (); i < rc; ++i)
			remainingEvents.removeOne (Model_->item (i)->data (Role::EventId).toString ());

		const auto& map = Util::Map (remainingEvents,
				[] (const QString& eventId) -> QVariant
				{
					return QVariantMap
					{
						{ "Name", Util::AN::GetTypeName (eventId) },
						{ "ID", eventId }
					};
				});
		Model_->setHeaderData (0, Qt::Horizontal,
				map,
				DataSources::DataSourceRole::FieldValues);
	}
Example #4
0
void NetworkManager::removeLocalCertificate(const QSslCertificate &cert)
{
    m_localCerts.removeOne(cert);
    QList<QSslCertificate> certs = QSslSocket::defaultCaCertificates();
    certs.removeOne(cert);
    QSslSocket::setDefaultCaCertificates(certs);

    //Delete cert file from profile
    bool deleted = false;
    QString certFileName = fileNameForCert(cert);
    int startIndex = 0;
    QDirIterator it(mApp->getActiveProfilPath() + "certificates", QDir::Files, QDirIterator::FollowSymlinks | QDirIterator::Subdirectories);
    while (it.hasNext()) {
        QString filePath = startIndex == 0 ? it.next() : it.next().mid(startIndex);
        if (!filePath.contains(certFileName)) {
            continue;
        }

        QFile file(filePath);
        if (!file.remove()) {
            qWarning() << "NetworkManager::removeLocalCertificate cannot remove file" << filePath;
        }
        deleted = true;
        break;
    }

    if (!deleted) {
        qWarning() << "NetworkManager::removeLocalCertificate cannot find file" << certFileName;
    }
}
void QDeclarativeViewInspectorPrivate::_q_removeFromSelection(QObject *obj)
{
    QList<QGraphicsItem*> items = selectedItems();
    if (QGraphicsItem *item = qobject_cast<QGraphicsObject*>(obj))
        items.removeOne(item);
    setSelectedItems(items);
}
Example #6
0
    ZVariant removeOne(const QList<ZVariant> &args)
    {
        if (args.count() > 1) {
            QList<ZVariant> list = args.first().toList();

            list.removeOne(args.at(1));
            args.first().depthCopyAssign(list);
        }

        return args.first();
    }
void QgsGeometryOverlapCheck::collectErrors( QList<QgsGeometryCheckError *> &errors, QStringList &messages, QAtomicInt *progressCounter, const QMap<QString, QgsFeatureIds> &ids ) const
{
  double overlapThreshold = mThresholdMapUnits;
  QMap<QString, QgsFeatureIds> featureIds = ids.isEmpty() ? allLayerFeatureIds() : ids;
  QgsGeometryCheckerUtils::LayerFeatures layerFeaturesA( mContext->featurePools, featureIds, mCompatibleGeometryTypes, progressCounter, true );
  QList<QString> layerIds = featureIds.keys();
  for ( const QgsGeometryCheckerUtils::LayerFeature &layerFeatureA : layerFeaturesA )
  {
    // Ensure each pair of layers only gets compared once: remove the current layer from the layerIds, but add it to the layerList for layerFeaturesB
    layerIds.removeOne( layerFeatureA.layer().id() );

    QgsRectangle bboxA = layerFeatureA.geometry()->boundingBox();
    QSharedPointer<QgsGeometryEngine> geomEngineA = QgsGeometryCheckerUtils::createGeomEngine( layerFeatureA.geometry(), mContext->tolerance );
    if ( !geomEngineA->isValid() )
    {
      messages.append( tr( "Overlap check failed for (%1): the geometry is invalid" ).arg( layerFeatureA.id() ) );
      continue;
    }

    QgsGeometryCheckerUtils::LayerFeatures layerFeaturesB( mContext->featurePools, QList<QString>() << layerFeatureA.layer().id() << layerIds, bboxA, mCompatibleGeometryTypes );
    for ( const QgsGeometryCheckerUtils::LayerFeature &layerFeatureB : layerFeaturesB )
    {
      // > : only report overlaps within same layer once
      if ( layerFeatureA.layer().id() == layerFeatureB.layer().id() && layerFeatureB.feature().id() >= layerFeatureA.feature().id() )
      {
        continue;
      }
      QString errMsg;
      if ( geomEngineA->overlaps( layerFeatureB.geometry(), &errMsg ) )
      {
        QgsAbstractGeometry *interGeom = geomEngineA->intersection( layerFeatureB.geometry() );
        if ( interGeom && !interGeom->isEmpty() )
        {
          QgsGeometryCheckerUtils::filter1DTypes( interGeom );
          for ( int iPart = 0, nParts = interGeom->partCount(); iPart < nParts; ++iPart )
          {
            QgsAbstractGeometry *interPart = QgsGeometryCheckerUtils::getGeomPart( interGeom, iPart );
            double area = interPart->area();
            if ( area > mContext->reducedTolerance && area < overlapThreshold )
            {
              errors.append( new QgsGeometryOverlapCheckError( this, layerFeatureA, interPart->clone(), interPart->centroid(), area, layerFeatureB ) );
            }
          }
        }
        else if ( !errMsg.isEmpty() )
        {
          messages.append( tr( "Overlap check between features %1 and %2 %3" ).arg( layerFeatureA.id() ).arg( layerFeatureB.id() ).arg( errMsg ) );
        }
        delete interGeom;
      }
    }
  }
}
Example #8
0
/* TODO Old system. Random generation of matches.
 *
 * Should generate next matches on the fly !
 * Even over few next phases
 */
void FourMatchesContest::generateNextMatchList()
{
  QList<Team> teamsList = TeamModel::getInstance()->getRawData();

  Util<Team>::shuffle( &teamsList );
  //qDebug() << "Is teamsList.size() even ? " << (teamsList.size() % 2 == 0);

  if( teamsList.size() % 2 != 0 && mState != NOT_STARTED_YET) {
      QList<Team> mustPlay = getTeamsAlreadyBeenExempt();
//      qDebug() << "Must play :";
//      Q_FOREACH(Team team, mustPlay) {
//          qDebug() << team.getName();
//      }
//      qDebug() << "";

      while( !mustPlay.isEmpty() ) {
        QList<Team> teamsAvailable = teamsAvailableToPlayAgainst( mustPlay.first(), teamsList );
        //qDebug() << "New match " << teamsList.first().getName() << " vs " << teamsAvailable.first().getName();
        addMatchToCurrentPhase( mustPlay.first(), teamsAvailable.first() );
        teamsList.removeOne( mustPlay.first() );
        teamsList.removeOne( teamsAvailable.first() );
        mustPlay.removeFirst();
      }
  }

  while( !teamsList.isEmpty() ) {
    //qDebug() << " >> teamsList.size() == " << teamsList.size();
    if( teamsList.size() > 1 ) {
      QList<Team> teamsAvailable = teamsAvailableToPlayAgainst( teamsList.first(), teamsList );
      //qDebug() << "New match " << teamsList.first().getName() << " vs " << teamsAvailable.first().getName();
      addMatchToCurrentPhase( teamsList.first(), teamsAvailable.first() );
      teamsList.removeFirst();
      teamsList.removeOne( teamsAvailable.first() );
    } else if( teamsList.size() == 1 ) {
        //qDebug() << "Generate last match with " << teamsList.first().getName();
        addMatchToCurrentPhase( teamsList.first(), Team() );
        teamsList.removeFirst();
    }
  }
}
Example #9
0
bool CookieJar::setCookiesFromUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url)
{
    QList<QNetworkCookie> newList = cookieList;

    foreach(const QNetworkCookie & cookie, newList) {
        if (rejectCookie(url.host(), cookie)) {
            newList.removeOne(cookie);
            continue;
        }
    }

    return QNetworkCookieJar::setCookiesFromUrl(newList, url);
}
Example #10
0
QList<core::GraphicObject *> core::Connector::removeIgnoredObjects(const QList<GraphicObject *> &list) const
{
	GraphicObject *obj;
	QList<GraphicObject*> returnedList = list;

	for(auto i = 0; i < returnedList.size(); i++){
		obj = returnedList[i];

		if(obj->type() == gotConnector || obj == beginObject){
			returnedList.removeOne(obj);
			i--;
		}
	}

	return returnedList;
}
Example #11
0
short TankBuilder::getHighestAndRemove(QList<short> &aNumberList)
{
    short highestValue = -1;

    if (!aNumberList.isEmpty())
    {
        foreach(short number, aNumberList)
        {
            if (number > highestValue)
            {
                highestValue = number;
            }
        }

        aNumberList.removeOne(highestValue);
    }
void RewriteActionCompressor::compressImports(QList<RewriteAction *> &actions) const
{
    QList<RewriteAction *> actionsToRemove;
    QHash<Import, RewriteAction *> addedImports;
    QHash<Import, RewriteAction *> removedImports;

    QMutableListIterator<RewriteAction *> iter(actions);
    iter.toBack();
    while (iter.hasPrevious()) {
        RewriteAction *action = iter.previous();

        if (RemoveImportRewriteAction *removeImportAction = action->asRemoveImportRewriteAction()) {
            const Import import = removeImportAction->import();
            if (removedImports.contains(import)) {
                actionsToRemove.append(action);
            } else if (RewriteAction *addImportAction = addedImports.value(import, 0)) {
                actionsToRemove.append(action);
                actionsToRemove.append(addImportAction);
                addedImports.remove(import);
                delete addImportAction;
            } else {
                removedImports.insert(import, action);
            }
        } else if (AddImportRewriteAction *addImportAction = action->asAddImportRewriteAction()) {
            const Import import = addImportAction->import();
            if (RewriteAction *duplicateAction = addedImports.value(import, 0)) {
                actionsToRemove.append(duplicateAction);
                addedImports.remove(import);
                delete duplicateAction;
                addedImports.insert(import, action);
            } else if (RewriteAction *removeAction = removedImports.value(import, 0)) {
                actionsToRemove.append(action);
                actionsToRemove.append(removeAction);
                removedImports.remove(import);
                delete removeAction;
            } else {
                addedImports.insert(import, action);
            }
        }
    }

    foreach (RewriteAction *action, actionsToRemove) {
        actions.removeOne(action);
        delete action;
    }
Example #13
0
    virtual bool trigger(TriggerEvent event, ServerPlayer *player, QVariant &data) const{
        Room *room = player->getRoom();
        QList<const Card *> clubs;

        if(event == CardUsed){
            CardUseStruct use = data.value<CardUseStruct>();
            const SkillCard *skill_card = qobject_cast<const SkillCard *>(use.card);
            if(skill_card && skill_card->subcardsLength() > 0 && skill_card->willThrow()){
                clubs = getClubs(skill_card);
            }
        }else if(event == CardDiscarded){
            const Card *card = data.value<CardStar>();
            if(card->subcardsLength() == 0)
                return false;

            clubs = getClubs(card);
        }else if(event == FinishJudge){
            JudgeStar judge = data.value<JudgeStar>();
            if(room->getCardPlace(judge->card->getEffectiveId()) == Player::DiscardedPile
               && judge->card->getSuit() == Card::Club)
               clubs << judge->card;
        }

        ServerPlayer *caozhi = room->findPlayerBySkillName(objectName());
        foreach(const Card* card, clubs)
            if(card->objectName() == "shit")
                if(caozhi && room->askForChoice(caozhi, objectName(), "yes+no") == "no")
                    clubs.removeOne(card);

        if(clubs.isEmpty())
            return false;

        if(caozhi && caozhi->askForSkillInvoke(objectName(), data)){
            if(player->getGeneralName() == "zhenji")
                room->playSkillEffect("luoying", 2);
            else
                room->playSkillEffect("luoying", 1);

            foreach(const Card *club, clubs)
                caozhi->obtainCard(club);
        }

        return false;
    }
Example #14
0
void CookieManager::removeCookie()
{
    QTreeWidgetItem* current = ui->cookieTree->currentItem();
    if (!current) {
        return;
    }

    QList<QNetworkCookie> allCookies = mApp->cookieJar()->getAllCookies();

    if (current->text(1).isEmpty()) {     //Remove whole cookie group
        QString domain = current->whatsThis(0);
        foreach(const QNetworkCookie & cookie, allCookies) {
            if (cookie.domain() == domain || cookie.domain()  ==  domain.mid(1)) {
                allCookies.removeOne(cookie);
            }
        }

        ui->cookieTree->deleteItem(current);
    }
Example #15
0
QList<QByteArray> SkyNet::filter_existing_chans(QList<QByteArray> peer_ids)
{
    QList<QByteArray> ret = peer_ids;

    if (!nodelink)
      return ret;

    struct PICA_chaninfo *iptr = nodelink->chan_list_head;

    while(iptr)
        {
        if (peer_ids.contains(QByteArray((const char*)iptr->peer_id, PICA_ID_SIZE)))
            ret.removeOne((const char*)iptr->peer_id);

        iptr = iptr->next;
        }

    return ret;
}
Example #16
0
int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);

	QList<int> list;

	for (unsigned int i = 0; i < 10; i++)
	{
		list.append(i);
	}

	list.removeOne(5);

	foreach (int mNumber, list)
	{
		qDebug() << mNumber;
	}

	return a.exec();
}
Example #17
0
void ServerConnector::loadAndPruneChunks()
{
	ChunkPosition currentPosition = world().chunkPosition(me()->v_position.x, me()->v_position.z);
	QList<ChunkPosition> wantedChunks; // The chunks we still want to be active

	// Create a list of the wanted chunks
	for(int x = - i_viewDistance; x < i_viewDistance+1; ++x)
	{
		for(int z = - i_viewDistance; z < i_viewDistance+1; ++z)
		{
			ChunkPosition position = ChunkPosition(currentPosition.first + x, currentPosition.second + z);
			wantedChunks.push_back(position);
		}
	}

	// Let's see if we have to prune unwanted ones...
	for (int i = 0; i < m_loadedChunks.size(); ++i) {
		ChunkPosition processingChunk = m_loadedChunks.at(i);

		// If the chunk is wanted
		if(wantedChunks.contains(processingChunk)) {
			// delete it from the wanted ones
			wantedChunks.removeOne(processingChunk);
		}
		else {
			// The chunk is unwanted, get rid of it
			ChunkConnectEvent* event = new ChunkConnectEvent(processingChunk, ChunkConnectEvent::ChunkConnection_Disconnect);
			emit postEvent(event);
			// Delete it from the loaded chunks list
			m_loadedChunks.removeAt(i); i--;
		}
	}

	// Now we load the chunks that were not in the loaded chunks
	for (int i = 0; i < wantedChunks.size(); ++i) {
		ChunkPosition processingChunk = wantedChunks.at(i);
		ChunkConnectEvent* event = new ChunkConnectEvent(processingChunk, ChunkConnectEvent::ChunkConnection_Connect);
		emit postEvent(event);
		m_loadedChunks.push_back(processingChunk);
	}
}
Example #18
0
QList<QGraphicsItem*> FaceGroup::Private::hotItems(const QPointF& scenePos)
{
    if (!q->hasVisibleItems())
    {
        return QList<QGraphicsItem*>();
    }

    const int distance               = 15;
    QRectF hotSceneRect              = QRectF(scenePos, QSize(0, 0)).adjusted(-distance, -distance, distance, distance);
    QList<QGraphicsItem*> closeItems = view->scene()->items(hotSceneRect, Qt::IntersectsItemBoundingRect);

    closeItems.removeOne(view->previewItem());

    return closeItems;

    /*
        qreal distance;
        d->faceGroup->closestItem(mapToScene(e->pos()), &distance);
        if (distance < 15)
            return false;
    */
}
DeployConfigurationFactory::~DeployConfigurationFactory()
{
    g_deployConfigurationFactories.removeOne(this);
}
Example #20
0
void ProcessModel::dynUpdateTopolSort(QList<ListDigraph::Node> &topolOrdering, const ListDigraph::Node &i, const ListDigraph::Node &k) {
	QTextStream out(stdout);

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

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

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

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

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

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

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

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

	//getchar();
	 */

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

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

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

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

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

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

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

	// Update the affected region

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

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

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

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

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

	deltaF.reserve(ar.size());

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

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

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

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

			tmpidx = ar.indexOf(tmpnode);

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

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

			}

		}
	}

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

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

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

	deltaB.reserve(ar.size());

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

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

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

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

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

			tmpidx = ar.indexOf(tmpnode);

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

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

		}
	}
	 */

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

	// Check the correctness of the topological sorting

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


	//getchar();

	//##########################################################################   
}
Example #21
0
IAnalyzerEngine *QmlProfilerTool::createEngine(const AnalyzerStartParameters &sp,
    RunConfiguration *runConfiguration)
{
    QmlProfilerEngine *engine = new QmlProfilerEngine(this, sp, runConfiguration);

    engine->registerProfilerStateManager(d->m_profilerState);

    bool isTcpConnection = true;

    if (runConfiguration) {
        // Check minimum Qt Version. We cannot really be sure what the Qt version
        // at runtime is, but guess that the active build configuraiton has been used.
        QtSupport::QtVersionNumber minimumVersion(4, 7, 4);
        if (Qt4ProjectManager::Qt4BuildConfiguration *qt4Config
                = qobject_cast<Qt4ProjectManager::Qt4BuildConfiguration*>(
                    runConfiguration->target()->activeBuildConfiguration())) {
            if (qt4Config->qtVersion()->isValid() && qt4Config->qtVersion()->qtVersion() < minimumVersion) {
                int result = QMessageBox::warning(QApplication::activeWindow(), tr("QML Profiler"),
                     tr("The QML profiler requires Qt 4.7.4 or newer.\n"
                     "The Qt version configured in your active build configuration is too old.\n"
                     "Do you want to continue?"), QMessageBox::Yes, QMessageBox::No);
                if (result == QMessageBox::No)
                    return 0;
            }
        }

        // Check whether we should use OST instead of TCP
        if (Qt4ProjectManager::S60DeployConfiguration *deployConfig
                = qobject_cast<Qt4ProjectManager::S60DeployConfiguration*>(
                    runConfiguration->target()->activeDeployConfiguration())) {
            if (deployConfig->communicationChannel()
                    == Qt4ProjectManager::S60DeployConfiguration::CommunicationCodaSerialConnection) {
                d->m_profilerConnections->setOstConnection(deployConfig->serialPortName());
                isTcpConnection = false;
            }
        }
    }

    // FIXME: Check that there's something sensible in sp.connParams
    if (isTcpConnection) {
        d->m_profilerConnections->setTcpConnection(sp.connParams.host, sp.connParams.port);
    }

    d->m_runConfiguration = runConfiguration;

    //
    // Initialize m_projectFinder
    //

    QString projectDirectory;
    if (d->m_runConfiguration) {
        Project *project = d->m_runConfiguration->target()->project();
        projectDirectory = project->projectDirectory();
    }

    // get files from all the projects in the session
    QStringList sourceFiles;
    SessionManager *sessionManager = ProjectExplorerPlugin::instance()->session();
    QList<Project *> projects = sessionManager->projects();
    if (Project *startupProject = ProjectExplorerPlugin::instance()->startupProject()) {
        // startup project first
        projects.removeOne(ProjectExplorerPlugin::instance()->startupProject());
        projects.insert(0, startupProject);
    }
    foreach (Project *project, projects)
        sourceFiles << project->files(Project::ExcludeGeneratedFiles);

    d->m_projectFinder.setProjectDirectory(projectDirectory);
    d->m_projectFinder.setProjectFiles(sourceFiles);
    d->m_projectFinder.setSysroot(sp.sysroot);

    connect(engine, SIGNAL(processRunning(quint16)), d->m_profilerConnections, SLOT(connectClient(quint16)));
    connect(engine, SIGNAL(finished()), d->m_profilerConnections, SLOT(disconnectClient()));
    connect(d->m_profilerConnections, SIGNAL(connectionFailed()), engine, SLOT(cancelProcess()));

    return engine;
}
sta::StateVector
ScenarioReEntryTrajectory::propagate(PropagationFeedback& propFeedback,
                                     const sta::StateVector& initialState,
                                     QList<double>& sampleTimes,
                                     QList<sta::StateVector>& samples)
{
    ScenarioSpaceVehicle* spacevehicle = dynamic_cast<ScenarioSpaceVehicle*>(this->parent()->parent());
    ScenarioProperties* vehicleproperties= spacevehicle->properties();
    EntrySettings inputSettings = createEntrySettings(this, vehicleproperties);
    EntryTrajectory trajectory(inputSettings);

    //Removing atmosphericDrag from the list of perturbations, as it is considered as a major force.
    QList<Perturbations*> perturbationsList = environment()->createListPerturbations(vehicleproperties);
    foreach (Perturbations* perturbation, perturbationsList)
    {
        if (dynamic_cast<AtmosphericDragPerturbations*>(perturbation))
            perturbationsList.removeOne(perturbation);
    }

    if (simulationMode()->isActive())
    {
        const double startTime = simulationMode()->simulationParameters()->timeline()->startTime();
        double time_jd = sta::MjdToJd(startTime);
        double dt = trajectoryPropagation()->timeStep();

        double time_s = sta::daysToSecs(startTime);
        EntryParameters parameters = createEntryParametersSimulation(this, vehicleproperties);

        //Message errors on input parameters :
        if (dt == 0.0)
        {
            propFeedback.raiseError(QObject::tr("Time step is zero!"));
            return initialState;
        }
        if (parameters.m == 0.0)
        {
            propFeedback.raiseError(QObject::tr("Vehicle mass is zero!"));
            return initialState;
        }
        if (parameters.R == 0.0)
        {
            propFeedback.raiseError(QObject::tr("Vehicle base radius is zero!"));
            return initialState;
        }
        if (inputSettings.maxheatrate == 0)
        {
            propFeedback.raiseError(QObject::tr("The maximum heat rate is zero!"));
            return initialState;
        }
        if (inputSettings.maxloadfactor == 0)
        {
            propFeedback.raiseError(QObject::tr("The maximum load factor is zero!"));
            return initialState;
        }
        if (trajectory.capsule.flag == 1)
        {
            propFeedback.raiseError(QObject::tr("Cd coefficient file name is not valid!"));
            return initialState;
        }
        if (trajectory.capsule.flag == 2)
        {
            propFeedback.raiseError(QObject::tr("Cd parachute coefficient file name is not valid!"));
            return initialState;
        }
        sta::StateVector stateVector;
        stateVector = trajectory.initialise(parameters, initialState, time_jd);
        _status status = OK;

        while (status == OK)
        {
            stateVector = trajectory.integrate(stateVector, perturbationsList);
            status = trajectory.status;

            time_jd += sta::secsToDays(dt);
            double theta = getGreenwichHourAngle(time_jd);
            time_s += dt;
            JulianDate jd = sta::secsToDays(time_s);
            sampleTimes << jd;

            double posx, posy, posz, velx, vely, velz;
            int celestialbody;
            if (inputSettings.bodyname == "Earth")
                celestialbody = 0;
            else if (inputSettings.bodyname == "Mars")
                celestialbody = 3;
            fixedTOinertial(celestialbody, theta , stateVector.position.x(), stateVector.position.y(), stateVector.position.z(), stateVector.velocity.x(), stateVector.velocity.y(), stateVector.velocity.z(),
                posx, posy, posz, velx, vely, velz);

            Eigen::Vector3d pos = Vector3d(posx/1000, posy/1000, posz/1000);
            Eigen::Vector3d vel = Vector3d(velx/1000, vely/1000, velz/1000);
            sta::StateVector statevector = sta::StateVector(pos, vel);
            samples << statevector;
        }
        //trajectory.printReport();
        return stateVector;
    }

//    else if (windowMode()->isActive())
//    {
//        qDebug() << "I'm propagating the window mode";
//        EntryParameterIntervals parameterIntervals = reentryValues.createEntryParameterIntervals(this);
//        EntryParameters parameters = reentryValues.createEntryParametersWindow(this, parameterIntervals);
//        const ScenarioTimeline* timeline = windowMode()->simulationParameters()->timeline();
//        double startTime = sta::daysToSecs(timeline->startTime());
//        trajectory.initialise(parameters, startTime);
//
//        int InputNsimulations, Npoints, Nsimulations;
//        double cd = 1.5;
//        bool failed_target = false;
//
//        InputNsimulations = windowMode()->numSimulations();//800
//        Npoints = int ( round (pow(InputNsimulations,0.5)) );
//        Nsimulations = Npoints * Npoints;
//        angle TargetLatitude = reentryValues.createTargetAngleLatitudeWindow(this);
//        angle TargetLongitude = reentryValues.createTargetAngleLongitudeWindow(this);
//
//        Endstate endresult = trajectory.getEndstate();
//
//        qDebug() << endresult.status;
//
//        if (endresult.status == landed) {
//        double difflong, difflat;
//                do {
//                    //Initialise the entry trajectory
//                    trajectory.initialise(parameters, startTime);
//
//
//                    //Get the landing location
//                    Endstate endresult = trajectory.getEndstate();
//                    if (endresult.status != landed) {
//                        cout << "Target not reached with middle point trajectory, entering at (0, 0)" << endl;
//                        parameters.inputstate[1] = 0.0;
//                        parameters.inputstate[2] = 0.0;
//                        failed_target = true;
//                        qDebug() << failed_target;
//                        break;
//                    }
//                    //Update the entry location
//                    difflong = endresult.longitude - windowMode()->simulationParameters()->finalState()->targetLon();
//                    difflat = endresult.latitude - windowMode()->simulationParameters()->finalState()->targetLat();;
//                    parameters.inputstate[1] -= difflong;
//                    parameters.inputstate[2] -= difflat;
//
//                } while (abs(difflong) > 0.0001 || abs(difflat) > 0.0001);
//                if (!failed_target) {
//                    qDebug() << "Target reached with middle point trajectory, entering at (" << parameters.inputstate[1] << "," << parameters.inputstate[2] << ")";
//                }
//    }
//    else {
//        qDebug() << "Target not reached with middle point trajectory, entering at (0, 0)";
//        parameters.inputstate[1] = 0.0;
//        parameters.inputstate[2] = 0.0;
//    }
//        //Open the output file
//    //--------------------
//    ofstream window_output ("C:/Users/Tizy/Desktop/Code/trunk/sta-src/Entry/REMWindowOutput.stap");
//    //--------------------
//    qDebug() << "window1";
//    //Create the matrices to store the results
//    //----------------------------------------
//    double * xArray = new double [Npoints];
//    double * yArray = new double [Npoints];
//    TNT::Array2D< double > MaxCqdotMatrix(Npoints, Npoints);
//    TNT::Array2D< double > MaxCqdotAltMatrix(Npoints, Npoints);
//    TNT::Array2D< double > MaxCqdotTimeMatrix(Npoints, Npoints);
//    TNT::Array2D< double > MaxRqdotMatrix(Npoints, Npoints);
//    TNT::Array2D< double > MaxRqdotAltMatrix(Npoints, Npoints);
//    TNT::Array2D< double > MaxRqdotTimeMatrix(Npoints, Npoints);
//    TNT::Array2D< double > MaxTqdotMatrix(Npoints, Npoints);
//    TNT::Array2D< double > MaxTqdotAltMatrix(Npoints, Npoints);
//    TNT::Array2D< double > MaxTqdotTimeMatrix(Npoints, Npoints);
//    TNT::Array2D< double > MaxGMatrix(Npoints, Npoints) ;
//    TNT::Array2D< double > MaxGAltMatrix(Npoints, Npoints);
//    TNT::Array2D< double > MaxGTimeMatrix(Npoints, Npoints);
//    TNT::Array2D< double > Mach1AltMatrix(Npoints, Npoints);
//    TNT::Array2D< double > Mach1TimeMatrix(Npoints, Npoints);
//    TNT::Array2D< double > DeployAltMatrix(Npoints, Npoints);
//    TNT::Array2D< double > DeployTimeMatrix(Npoints, Npoints);
//    TNT::Array2D< double > TotalQMatrix(Npoints, Npoints);
//    TNT::Array2D< double > TPSMassMatrix(Npoints, Npoints);
//    TNT::Array2D< double > TofMatrix(Npoints, Npoints);
//    TNT::Array2D< double > ImpactVMatrix(Npoints, Npoints);
//    TNT::Array2D< double > StatusMatrix(Npoints, Npoints);
//    //----------------------------------------
//
//    //Create the parameter arrays and fill them
//    //-----------------------------------------
//    double * KArray = new double[Nsimulations];
//    double * RnArray = new double[Nsimulations];
//    double * VArray = new double[Nsimulations];
//    double * gammaArray = new double[Nsimulations];
//    double * chiArray = new double[Nsimulations];
//    int xparameter = 2;//windowMode()->window()->xAxisVariable()->returnType();
//    int yparameter = 4;//windowMode()->window()->yAxisVariable()->returnType();
//    //------
//    switch (xparameter) {
//        case 1: for (int i = 0; i < Npoints; i++) { xArray[i] = parameterIntervals.K.low + ( i * (parameterIntervals.K.high-parameterIntervals.K.low) / (Npoints-1) );} break;
//        case 2: for (int i = 0; i < Npoints; i++) { xArray[i] = parameterIntervals.Rn.low + ( i * (parameterIntervals.Rn.high-parameterIntervals.Rn.low) / (Npoints-1) );}; break;
//        case 3: for (int i = 0; i < Npoints; i++) { xArray[i] = parameterIntervals.velocity.low + ( i * (parameterIntervals.velocity.high-parameterIntervals.velocity.low) / (Npoints-1) );}; break;
//        case 4: for (int i = 0; i < Npoints; i++) { xArray[i] = parameterIntervals.gamma.low + ( i * (parameterIntervals.gamma.high-parameterIntervals.gamma.low) / (Npoints-1) );}; break;
//        case 5: for (int i = 0; i < Npoints; i++) { xArray[i] = parameterIntervals.chi.low + ( i * (parameterIntervals.chi.high-parameterIntervals.chi.low) / (Npoints-1) );}; break;
//    }
//    switch (yparameter) {
//        case 1: for (int i = 0; i < Npoints; i++) { yArray[i] = parameterIntervals.K.high - ( i * (parameterIntervals.K.high-parameterIntervals.K.low) / (Npoints-1) );}; break;
//        case 2: for (int i = 0; i < Npoints; i++) { yArray[i] = parameterIntervals.Rn.high - ( i * (parameterIntervals.Rn.high-parameterIntervals.Rn.low) / (Npoints-1) );}; break;
//        case 3: for (int i = 0; i < Npoints; i++) { yArray[i] = parameterIntervals.velocity.high - ( i * (parameterIntervals.velocity.high-parameterIntervals.velocity.low) / (Npoints-1) );}; break;
//        case 4: for (int i = 0; i < Npoints; i++) { yArray[i] = parameterIntervals.gamma.high - ( i * (parameterIntervals.gamma.high-parameterIntervals.gamma.low) / (Npoints-1) );}; break;
//        case 5: for (int i = 0; i < Npoints; i++) { yArray[i] = parameterIntervals.chi.high - ( i * (parameterIntervals.chi.high-parameterIntervals.chi.low) / (Npoints-1) );}; break;
//    }
//    qDebug() << "window2";
//    //------
//    if (xparameter == 1) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) KArray[i*Npoints + j] = xArray[i];}}
//    else if (yparameter == 1) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) KArray[i*Npoints + j] = yArray[j];}}
//    else for (int i = 0; i < Nsimulations; i++) KArray[i] = parameterIntervals.K.low;
//    //------
//    if (xparameter == 2) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) RnArray[i*Npoints + j] = xArray[i];}}
//    else if (yparameter == 2) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) RnArray[i*Npoints + j] = yArray[j];}}
//    else for (int i = 0; i < Nsimulations; i++) RnArray[i] = parameterIntervals.Rn.low;
//    //------
//    if (xparameter == 3) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) VArray[i*Npoints + j] = xArray[i];}}
//    else if (yparameter == 3) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) VArray[i*Npoints + j] = yArray[j];}}
//    else for (int i = 0; i < Nsimulations; i++) VArray[i] = parameterIntervals.velocity.low;
//    //------
//    if (xparameter == 4) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) gammaArray[i*Npoints + j] = xArray[i];}}
//    else if (yparameter == 4) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) gammaArray[i*Npoints + j] = yArray[j];}}
//    else for (int i = 0; i < Nsimulations; i++) gammaArray[i] = parameterIntervals.gamma.low;
//    //------
//    if (xparameter == 5) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) chiArray[i*Npoints + j] = xArray[i];}}
//    else if (yparameter == 5) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) chiArray[i*Npoints + j] = yArray[j];}}
//    else for (int i = 0; i < Nsimulations; i++) chiArray[i] = parameterIntervals.chi.low;
//    //-------------------------------------------------------------------------
//qDebug() << "window3";
//
//        //Main loop
//        //=====================
//        qDebug() << "Number of steps: " << Npoints;
//        for (int xstep = 0; xstep < Npoints; xstep++) {
//
//            for (int ystep = 0; ystep < Npoints; ystep++) {
//
//                //Make the parameter structure
//                //----------------------------
//                parameters.m = 100.0;
//                double localK = KArray[xstep * Npoints + ystep];
//                parameters.R = sqrt( parameters.m/ (localK * acos(-1) * cd) );
//                parameters.Rn = RnArray [xstep * Npoints + ystep];
//                parameters.inputstate[3] = VArray [xstep * Npoints + ystep];
//                parameters.inputstate[4] = gammaArray [xstep * Npoints + ystep];
//                parameters.inputstate[5] = chiArray [xstep * Npoints + ystep];
//                //----------------------------
//
//                //Initialise the entry trajectory
//                //-----------------------------------------
//                trajectory.initialise(parameters, startTime);
//                //-----------------------------------------
//
//                //Get the endstate of the trajectory
//                //----------------------------------
//                Endstate endresult = trajectory.getEndstate();
//                //----------------------------------
//
//                //Fill the output matrices
//                //------------------------
//                MaxCqdotMatrix[xstep][ystep] = endresult.maxconvheatrate.value * (1 - endresult.status);
//                MaxCqdotAltMatrix[xstep][ystep] = endresult.maxconvheatrate.altitude * (1 - endresult.status);
//                MaxCqdotTimeMatrix[xstep][ystep] = endresult.maxconvheatrate.time * (1 - endresult.status);
//                MaxRqdotMatrix[xstep][ystep] = endresult.maxradheatrate.value * (1 - endresult.status);
//                MaxRqdotAltMatrix[xstep][ystep] = endresult.maxradheatrate.altitude * (1 - endresult.status);
//                MaxRqdotTimeMatrix[xstep][ystep] = endresult.maxradheatrate.time * (1 - endresult.status);
//                MaxTqdotMatrix[xstep][ystep] = endresult.maxtotalheatrate.value * (1 - endresult.status);
//                MaxTqdotAltMatrix[xstep][ystep] = endresult.maxtotalheatrate.altitude * (1 - endresult.status);
//                MaxTqdotTimeMatrix[xstep][ystep] = endresult.maxtotalheatrate.time * (1 - endresult.status);
//                MaxGMatrix[xstep][ystep] = endresult.maxloadfactor.value * (1 - endresult.status);
//                MaxGAltMatrix[xstep][ystep] = endresult.maxloadfactor.value * (1 - endresult.status);
//                MaxGTimeMatrix[xstep][ystep] = endresult.maxloadfactor.value * (1 - endresult.status);
//                Mach1AltMatrix[xstep][ystep] = endresult.Machone_transition_altitude * (1 - endresult.status);
//                Mach1TimeMatrix[xstep][ystep] = endresult.Machone_transition_time * (1 - endresult.status);
//                DeployAltMatrix[xstep][ystep] = endresult.parachutedeploy_altitude * (1 - endresult.status);
//                DeployTimeMatrix[xstep][ystep] = endresult.parachutedeploy_time * (1 - endresult.status);
//                TotalQMatrix[xstep][ystep] = endresult.totalheatload * (1 - endresult.status);
//                TPSMassMatrix[xstep][ystep] = endresult.tpsmass * (1 - endresult.status);
//                TofMatrix[xstep][ystep] = endresult.timeofflight * (1 - endresult.status);
//                ImpactVMatrix[xstep][ystep] = endresult.impactvelocity * (1 - endresult.status);
//                StatusMatrix[xstep][ystep] = endresult.status;
//                //-----------------
//            }
//qDebug() << "window4";
//            //Give feedback about progress
//            //----------------------------
//            qDebug() << xstep+1;
//            //----------------------------
//        }
//        //=====================
//
//
//        //Write the output file
//        //---------------------
//        for (int i=0; i<Npoints; i++) {
//            window_output << xArray[i] << "     ";
//        }
//        window_output << "\n";
//        //------
//        for (int i=0; i<Npoints; i++) {
//            window_output << yArray[i] << "     ";
//        }
//        window_output << "\n";
//        //-----------------------------------------------------
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxCqdotMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxCqdotAltMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxCqdotTimeMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxRqdotMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxRqdotAltMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxRqdotTimeMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxTqdotMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxTqdotAltMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxTqdotTimeMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxGMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxGAltMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxGTimeMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << Mach1AltMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << Mach1TimeMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << DeployAltMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << DeployTimeMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << TotalQMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << TPSMassMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << TofMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << ImpactVMatrix[i][j] << "     ";} window_output << "\n";}
//        for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << StatusMatrix[i][j] << "     ";} window_output << "\n";}
//        qDebug() << "window5";//-----------------------------------------------------
//        window_output.close();
//        //----------------------
//    }
//    //    //Dispersion analysis mode ++++++++++++++++++++++++++++
//    if (simulationMode()->dispersionAnalysis()->isActive())
//    {
//        //Set the seed of the random number generator
//        srand ( time(NULL) );
//
//        Uncertainties_struct inputuncertainties = reentryValues.createUncertainties_struct(this);
//        EntryParameters parameters;
//        //ifstream dispersion_input ("REMDispersionInput.stap");
//        int Nsimulations;
//        double inputstate_temp[6];
//        double mass_temp;
//        Nsimulations = simulationMode()->dispersionAnalysis()->numSimulations();
//        parameters.R = vehicle()->mainBodyCharacteristics()->radiusBase();
//        mass_temp = vehicle()->mainBodyCharacteristics()->mass();
//        parameters.Rn = vehicle()->mainBodyCharacteristics()->radiusNose();
//
//        const ScenarioTimeline* timeline = simulationMode()->simulationParameters()->timeline();
//        double startTime = sta::daysToSecs(timeline->startTime());
//
//        QString coordinatesystem = simulationMode()->simulationParameters()->initialStatePosition()->initialState()->elementName();
//
//        if (coordinatesystem=="SphericalCoordinates")
//        {
//            parameters.coordselector = 1;
//            ScenarioSphericalCoordinates* sphericalCoord = dynamic_cast<ScenarioSphericalCoordinates*>(simulationMode()->simulationParameters()->initialStatePosition()->initialState());
//            inputstate_temp[1] = sphericalCoord->altitude();
//            inputstate_temp[2] = sphericalCoord->longitude();
//            inputstate_temp[3] = sphericalCoord->latitude();
//            inputstate_temp[4] = sphericalCoord->inertialVelocity();
//            inputstate_temp[5] = sphericalCoord->inertialFlightPathAngle();
//            inputstate_temp[6] = sphericalCoord->inertialHeading();
//
//        }
//        else if (coordinatesystem=="KeplerianElements")
//        {
//            parameters.coordselector = 2;
//            ScenarioKeplerianElements* elements = dynamic_cast<ScenarioKeplerianElements*>(simulationMode()->simulationParameters()->initialStatePosition()->initialState());
//            inputstate_temp[1] = elements->semimajorAxis();
//            inputstate_temp[2] = elements->eccentricity();
//            inputstate_temp[3] = elements->inclination();
//            inputstate_temp[4] = elements->raan();
//            inputstate_temp[5] = elements->argumentOfPeriapsis();
//            inputstate_temp[6] = elements->trueAnomaly();
//        }
//        else  qFatal("Error in the initial state position coordinate systems");
//
//    angle TargetLongitude, TargetLatitude;
//    AngleConversion angleconversion;
//    double latitudeDecimal = simulationMode()->dispersionAnalysis()->deviations()->entryLat();
//    double longitudeDecimal = simulationMode()->dispersionAnalysis()->deviations()->entryLong();
//    angleconversion.decimalToDegMinSec(latitudeDecimal, TargetLatitude.degrees, TargetLatitude.minutes, TargetLatitude.seconds);
//    angleconversion.decimalToDegMinSec(longitudeDecimal, TargetLongitude.degrees, TargetLongitude.minutes, TargetLongitude.seconds);
//
//
//    //-------------------------------------------
//
//    //Open the output file
//    //--------------------
//    ofstream dispersion_output ("REMDispersionOutput.stap");
//    dispersion_output << longitudeDecimal << "\t" << latitudeDecimal << "\t" << 0 << "\t" << 0 << endl;
//    //--------------------
//
//    //Creat the dynamic arrays
//    //------------------------
//    double * dispersion_longitudes = new double [Nsimulations];
//    double * dispersion_latitudes = new double [Nsimulations];
//    double * dispersion_crosstracks = new double [Nsimulations];
//    double * dispersion_alongtracks = new double [Nsimulations];
//    double maxalongtrack = 0.0, maxcrosstrack = 0.0;
//    //------------------------
//
//    //Main loop
//    //========================
//    for (int i=0; i<Nsimulations; i++) {
//
//        //Create the uncertainties based on the variances
//        //-------------------------------------------
//        parameters.uncertainties.mass = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.mass) - inputuncertainties.mass;
//        parameters.uncertainties.altitude = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.altitude) - inputuncertainties.altitude;
//        parameters.uncertainties.tau = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.tau) - inputuncertainties.tau;
//        parameters.uncertainties.delta = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.delta) - inputuncertainties.delta;
//        parameters.uncertainties.velocity = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.velocity) - inputuncertainties.velocity;
//        parameters.uncertainties.gamma = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.gamma) - inputuncertainties.gamma;
//        parameters.uncertainties.chi = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.chi) - inputuncertainties.chi;
//        parameters.uncertainties.density = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.density) - inputuncertainties.density;
//        parameters.uncertainties.temperature = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.temperature) - inputuncertainties.temperature;
//        parameters.uncertainties.pressure = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.pressure) - inputuncertainties.pressure;
//        parameters.uncertainties.speedofsound = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.speedofsound) - inputuncertainties.speedofsound;
//        parameters.uncertainties.cdcapsule = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.cdcapsule) - inputuncertainties.cdcapsule;
//        parameters.uncertainties.cdparachute = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.cdparachute) - inputuncertainties.cdparachute;
//        //-------------------------------------------
//
//        //Construct the parameter structure
//        //-------------------------------------------
//        parameters.m = mass_temp + parameters.uncertainties.mass;
//        parameters.inputstate[0] = inputstate_temp[0] + parameters.uncertainties.altitude;
//        parameters.inputstate[1] = inputstate_temp[1] + parameters.uncertainties.tau;
//        parameters.inputstate[2] = inputstate_temp[2] + parameters.uncertainties.delta;
//        parameters.inputstate[3] = inputstate_temp[3] + parameters.uncertainties.velocity;
//        parameters.inputstate[4] = inputstate_temp[4] + parameters.uncertainties.gamma;
//        parameters.inputstate[5] = inputstate_temp[5] + parameters.uncertainties.chi;
//        //-------------------------------------------
//
//        //Initialise the entry trajectory
//        //-----------------------------------------
//        trajectory.initialise(parameters, startTime);
//        //-----------------------------------------
//
//        //Get the endstate of the trajectory
//        //----------------------------------
//        Endstate endresult = trajectory.getEndstate();
//        //----------------------------------
//
//        //Write the output file
//        //----------------------------------
//        dispersion_longitudes[i] = endresult.longitude;
//        dispersion_latitudes[i] = endresult.latitude;
//        AngleConversion angleconversion;
//        dispersion_alongtracks[i] = (dispersion_longitudes[i]-angleconversion.DegMinSecToDecimal(TargetLongitude.degrees, TargetLongitude.minutes, TargetLongitude.seconds))*cos((inputstate_temp[5]-90.0)) - (dispersion_latitudes[i]-angleconversion.DegMinSecToDecimal(TargetLatitude.degrees, TargetLatitude.minutes, TargetLatitude.seconds))*sin((inputstate_temp[5]-90.0)) ;//- angle2double(TargetLongitude);
//        dispersion_crosstracks[i] = (dispersion_longitudes[i]-angleconversion.DegMinSecToDecimal(TargetLongitude.degrees, TargetLongitude.minutes, TargetLongitude.seconds))*sin((inputstate_temp[5]-90.0)) + (dispersion_latitudes[i]-angleconversion.DegMinSecToDecimal(TargetLatitude.degrees, TargetLatitude.minutes, TargetLatitude.seconds))*cos((inputstate_temp[5]-90.0)) ;//- angle2double(TargetLatitude);
//        dispersion_output << dispersion_longitudes[i] << "\t" << dispersion_latitudes[i] << "\t" << dispersion_alongtracks[i] << "\t" << dispersion_crosstracks[i] << endl;
//        if (dispersion_alongtracks[i] > maxalongtrack) maxalongtrack = dispersion_alongtracks[i];
//        if (dispersion_crosstracks[i] > maxcrosstrack) maxcrosstrack = dispersion_crosstracks[i];
//        //----------------------------------
//
//        //Give feedback about progress
//        //----------------------------
//        cout << i << endl;
//        //----------------------------
//        }
//        //========================
//    dispersion_output.close();
//
//    //Write out a report
//    //------------------
//    ofstream dispersion_report ("REMDispersionReport.stap");
//    dispersion_report << "Dispersion analysis: report" << endl;
//    dispersion_report << "===========================" << endl << " " << endl;
//    dispersion_report << "Nominal mission parameters" << endl;
//    dispersion_report << "--------------------------" << endl;
//    dispersion_report << "Capsule radius:\t\t   " << parameters.R << " m" << endl;
//    dispersion_report << "Capsule mass:\t\t   " << mass_temp << " kg" << endl;
//    dispersion_report << "Capsule nose radius:\t   " << parameters.Rn << " m" << endl;
//    dispersion_report << "Entry altitude:\t\t   " << inputstate_temp[0] << " m" << endl;
//    dispersion_report << "Entry longitude:\t   " << inputstate_temp[1] << " °" << endl;
//    dispersion_report << "Entry latitude:\t\t   " << inputstate_temp[2] << " °" << endl;
//    dispersion_report << "Entry velocity:\t\t   " << inputstate_temp[3] << " m/s" << endl;
//    dispersion_report << "Entry flight path angle:   " << inputstate_temp[4] << " °" << endl;
//    dispersion_report << "Entry heading:\t\t   " << inputstate_temp[5] << " °" << endl;
//    dispersion_report << "--------------------------" << endl << " " << endl;
//    dispersion_report << "Variances of uncertainties" << endl;
//    dispersion_report << "--------------------------" << endl;
//    dispersion_report << "Capsule mass:\t "  << "+-" << inputuncertainties.mass << " kg" << endl;
//    dispersion_report << "Capsule Cd profile:\t " << "+-" << inputuncertainties.cdcapsule*100 << "%" << endl;
//    dispersion_report << "Parachute Cd profile:\t " << "+-" << inputuncertainties.cdparachute*100 << "%" << endl;
//    dispersion_report << "Entry altitude:\t " << "+-" << inputuncertainties.altitude << " m" << endl;
//    dispersion_report << "Entry longitude:\t " << "+-" << inputuncertainties.tau << " deg" << endl;
//    dispersion_report << "Entry latitude:\t " << "+-" << inputuncertainties.delta << " deg" << endl;
//    dispersion_report << "Entry velocity:\t\t " << "+-" << inputuncertainties.velocity << " m/s" << endl;
//    dispersion_report << "Entry flight path angle:\t " << "+-" << inputuncertainties.gamma << " deg" << endl;
//    dispersion_report << "Entry heading:\t " << "+-" << inputuncertainties.chi << " deg" << endl;
//    dispersion_report << "--------------------------" << endl << " " << endl;
//    dispersion_report << "Dispersion results" << endl;
//    dispersion_report << "--------------------------" << endl;
//    dispersion_report << "Maximum along track dispersion: " << maxalongtrack*111111.11 << "m" << endl;
//    dispersion_report << "Maximum cross track dispersion: " << maxcrosstrack*111111.11 << "m" << endl;
//    dispersion_report << "--------------------------" << endl;
//    //------------------
//    }
//    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //return 0;

}
Example #23
0
 void objectDestroyed(QObject *) {
     // we assume priv will always be destroyed after objectDestroyed calls
     list->removeOne(*this);
 }
Example #24
0
void freeKickDirect::setPositions()
{
    Position leftDefPos,rightDefPos,goaliePos;
    int leftID = -1, rightID = -1 , midID = -1;
    bool rightNav , leftNav;

    if( wm->ourRobot[tDefenderLeft->getID()].Role == AgentRole::DefenderLeft )
        leftID = tDefenderLeft->getID();

    if( wm->ourRobot[tDefenderRight->getID()].Role == AgentRole::DefenderRight )
        rightID = tDefenderRight->getID();

    if( leftChecker > 100 || leftID == -1 )
        midID = rightID;

    if( rightChecker > 100  || rightID == -1)
        midID = leftID;

    zonePositions(leftID,rightID,midID,goaliePos,leftDefPos,leftNav,rightDefPos,rightNav);

    tGolie->setIdlePosition(goaliePos);
    tDefenderLeft->setIdlePosition(leftDefPos);
    tDefenderLeft->setUseNav(leftNav);
    tDefenderRight->setIdlePosition(rightDefPos);
    tDefenderRight->setUseNav(rightNav);

    if( leftID != -1)
    {
        if( (wm->ourRobot[leftID].pos.loc - leftDefPos.loc).length() > 250 )
            leftChecker++;
        else
            leftChecker = 0;
    }

    if( rightID != -1)
    {
        if( (wm->ourRobot[rightID].pos.loc - rightDefPos.loc).length() > 250 )
            rightChecker++;
        else
            rightChecker = 0;
    }

    Position pos;

    QList<int> ourAttackers = wm->kn->findAttackers();
    ourAttackers.removeOne(tAttackerMid->getID());

    Positioning voronoi;
    voronoi.setWorldModel(wm);
    bool isMatched;

    QList<Positioning_Struct> positions = voronoi.find_positions(ourAttackers,isMatched);

    for(int i=0; i<positions.size(); i++)
    {
        Positioning_Struct tmp = positions.at(i);

        switch (wm->ourRobot[tmp.ourI].Role) {
        case AgentRole::AttackerLeft:
            pos.loc = tmp.loc;
            pos.dir = (Field::oppGoalCenter - pos.loc).dir().radian();
            tAttackerLeft->setIdlePosition(pos);
            break;
        case AgentRole::AttackerRight:
            pos.loc = tmp.loc;
            pos.dir = (Field::oppGoalCenter - pos.loc).dir().radian();
            tAttackerRight->setIdlePosition(pos);
            break;
        default:
            break;
        }
    }
}
Route *GeneticAlgorithm::crossbreedRoutes(Route *firstRoute, Route *secondRoute)
{
    Route * result = new Route(firstRoute->getSize(),firstRoute->getAdjacencyMatrix());
    //QMap<unsigned int,unsigned int> nodeMap;
    QList<unsigned int> unusedNodes;

    unsigned int firstPosition = 0;
    unsigned int secondPosition = 0;

    do
    {
        firstPosition = qrand() % firstRoute->getSize();
        secondPosition = qrand() % firstRoute->getSize();
    }
    while(!((firstPosition != 0) && (secondPosition != 0)));

    for(unsigned int m = 0; m < firstRoute->getSize(); m++)
    {
        unusedNodes.append(m);
    }

    if(firstPosition > secondPosition)
    {
        unsigned int tempValue = firstPosition;
        firstPosition = secondPosition;
        secondPosition = tempValue;
    }
    if(firstPosition == secondPosition)
    {
        if(firstPosition > 1)
        {
            firstPosition = firstPosition - 1;
        }
        if(secondPosition < (result->getSize() - 1))
        {
            secondPosition = secondPosition + 1;
        }

    }
    result->insertNode(0,firstRoute->at(0));
    unusedNodes.removeOne(firstRoute->at(0));

    for(unsigned int i = firstPosition; i<=secondPosition; i++)
    {
        result->insertNode(i,firstRoute->at(i));
        unusedNodes.removeOne(firstRoute->at(i));
    }
    for(unsigned int j = 1; j < firstPosition; j++)
    {
        if(!result->containsNode(secondRoute->at(j)))
        {
            result->insertNode(j,secondRoute->at(j));
            unusedNodes.removeOne(secondRoute->at(j));
        }
    }
    for(unsigned int k = secondPosition + 1; k < firstRoute->getSize(); k++)
    {
        if(!result->containsNode(secondRoute->at(k)))
        {
            result->insertNode(k,secondRoute->at(k));
            unusedNodes.removeOne(secondRoute->at(k));
        }
    }
    for(unsigned int n = 1; n < firstRoute->getSize(); n++)
    {
        if(result->at(n) == -1)
        {
            if(unusedNodes.size() != 0)
            {
                unsigned int randomNodePosition = qrand() % unusedNodes.size();
                result->insertNode(n,unusedNodes.at(randomNodePosition));
                unusedNodes.removeAt(randomNodePosition);
            }
            else
            {
                qDebug() << "Watch here";
            }
        }


    }
    //qDebug() << "First position:" << firstPosition << "Second position" << secondPosition;
    return result;

}
Example #26
0
void UmlSequenceMessage::write_fragment(FileOut & out, UmlItem * diagram, QList< UmlSequenceMessage* > & msgs)
{
    msgs.removeOne(this);

#define MSG  "MSG", itsrank
#define SEND "MSGOCCSPECSEND", itsrank
#define REF_SEND  "MSGOCCSPECSEND", reverse->itsrank
#define REC  "MSGOCCSPECREC", itsrank
#define BEH  "BEHEXECSPEC", itsrank
#define REF_BEH  "BEHEXECSPEC", reverse->itsrank
#define EXEC "EXECOCCSPEC", itsrank
#define REF_EXEC "EXECOCCSPEC", reverse->itsrank
#define DEL "DELOCCSPEC", itsrank

    UmlPackage * prj = UmlPackage::getProject();

    switch (kind()) {
    case aSynchronousCall:
    case anAsynchronousCall:
        used = TRUE;

        if (from() != 0) {
            out.indent();
            out << "<fragment xmi:type=\"uml:MessageOccurrenceSpecification\"";
            out.id_prefix(diagram, SEND);
            out.ref(diagram, "covered", from()->lifeline());
            out.ref(prj, "event",
                    (operation() != 0) ? operation()->event(FALSE)
                    : UmlOperation::event("SEND", form()));
            out.ref(diagram, "message", MSG);
            out << "/>\n";
        }

        if (to() != 0) {
            out.indent();
            out << "<fragment xmi:type=\"uml:MessageOccurrenceSpecification\"";
            out.id_prefix(diagram, REC);
            out.ref(diagram, "covered", to()->lifeline());
            out.ref(prj, "event",
                    (operation() != 0) ? operation()->event(TRUE)
                    : UmlOperation::event("REC", form()));
            out.ref(diagram, "message", MSG);
            out << "/>\n";

            out.indent();
            out << "<fragment xmi:type=\"uml:BehaviorExecutionSpecification\"";
            out.id_prefix(diagram, BEH);
            out.ref(diagram, "covered", to()->lifeline());
            out.ref(diagram, "start", REC);

            if (reverse != 0) {
                if (reverse->kind() == anExplicitReturn)
                    out.ref(diagram, "finish", REF_SEND);
                else
                    out.ref(diagram, "finish", REF_EXEC);
            }

            out << "/>\n";
        }

        break;

    case anExplicitReturn:
        used = TRUE;

        out.indent();
        out << "<fragment xmi:type=\"uml:MessageOccurrenceSpecification\"";
        out.id_prefix(diagram, SEND);
        out.ref(diagram, "covered", from()->lifeline());
        out.ref(prj, "event", UmlOperation::event("SEND", form()));
        out.ref(diagram, "message", MSG);
        out << "/>\n";

        out.indent();
        out << "<fragment xmi:type=\"uml:MessageOccurrenceSpecification\"";
        out.id_prefix(diagram, REC);
        out.ref(diagram, "covered", to()->lifeline());
        out.ref(prj, "event", UmlOperation::event("REC", form()));
        out.ref(diagram, "message", MSG);
        out << "/>\n";
        break;

    case aDestruction:
        out.indent();
        out << "<fragment xmi:type=\"uml:OccurrenceSpecification\"";
        out.id_prefix(diagram, DEL);
        out.ref(diagram, "covered", from()->lifeline());
        out.ref(prj, "event", UmlOperation::event("DEL", ""));
        out << "/>\n";
        break;

    case anInteractionUse:
        break;

    default:
        if (reverse != 0) {
            out.indent();
            out << "<fragment xmi:type=\"uml:ExecutionOccurrenceSpecification\"";
            out.id_prefix(diagram, EXEC);
            out.ref(diagram, "covered", from()->lifeline());
            out.ref(prj, "event", UmlOperation::event("EXEC", form()));
            out.ref(diagram, "execution", REF_BEH);
            out << "/>\n";
        }

        break;
    }

#undef MSG
#undef SEND
#undef REF_SEND
#undef REC
#undef BEH
#undef REF_BEH
#undef EXEC
#undef REF_EXEC
#undef DEL
}
Example #27
0
void QgsAuthImportCertDialog::validateCertificates()
{
  mCerts.clear();
  teValidation->clear();
  teValidation->setStyleSheet( QString() );

  bool valid = false;
  QList<QSslCertificate> certs;
  QList<QSslCertificate> nixcerts;
  int validcerts = 0;
  bool allowinvalid = chkAllowInvalid->isChecked();
  bool filterCAs = ( mFilter == CaFilter );
  int cas = 0;

  if ( radioImportFile->isChecked() && !leImportFile->text().isEmpty() )
  {
    certs = QgsAuthCertUtils::certsFromFile( leImportFile->text() );
  }
  else if ( radioImportText->isChecked() && !teCertText->toPlainText().trimmed().isEmpty() )
  {
    certs = QgsAuthCertUtils::certsFromString( teCertText->toPlainText().trimmed() );
  }

  int certssize = certs.size();

  const auto constCerts = certs;
  for ( const QSslCertificate &cert : constCerts )
  {
    if ( QgsAuthCertUtils::certIsViable( cert ) )
      ++validcerts;

    if ( filterCAs )
    {
      if ( QgsAuthCertUtils::certificateIsAuthorityOrIssuer( cert ) )
      {
        ++cas;
      }
      else
      {
        nixcerts << cert;
      }
    }
  }

  valid = ( certssize > 0
            && ( allowinvalid || certssize == validcerts )
            && ( !filterCAs || nixcerts.size() < certssize ) );

  if ( !nixcerts.isEmpty() )
  {
    const auto constNixcerts = nixcerts;
    for ( const QSslCertificate &nixcert : constNixcerts )
    {
      certs.removeOne( nixcert );
    }
  }

  if ( valid )
    mCerts = certs;

  if ( certssize > 0 )
  {
    teValidation->setStyleSheet(
      valid ? QgsAuthGuiUtils::greenTextStyleSheet( QStringLiteral( "QTextEdit" ) )
      : QgsAuthGuiUtils::redTextStyleSheet( QStringLiteral( "QTextEdit" ) ) );
  }

  QString msg = tr( "Certificates found: %1\n"
                    "Certificates valid: %2" ).arg( certssize ).arg( validcerts );

  if ( filterCAs )
  {
    msg += tr( "\nAuthorities/Issuers: %1%2" ).arg( cas )
           .arg( !nixcerts.isEmpty() && nixcerts.size() < certssize ? " (others not imported)" : "" );
  }

  teValidation->setText( msg );

  okButton()->setEnabled( valid );
}