コード例 #1
0
void
Monitor::MonitorDataStorage::manageTransportLink(
  TreeNode* node,
  int       transport_id,
  bool&     create
)
{
  // Start by finding the participant node.
  TreeNode* processNode = node->parent();
  if( processNode) {
    // And follow it to the actual process node.
    processNode = processNode->parent();

  } else {
    // Horribly corrupt model, something oughta been done about it!
    ACE_ERROR((LM_ERROR,
      ACE_TEXT("(%P|%t) ERROR: MonitorDataStorage::manageTransportLink() - ")
      ACE_TEXT("unable to locate the ancestor process node!\n")
    ));
    return;
  }

  // Then finds its key in the maps.
  ProcessKey processKey;
  std::pair< bool, ProcessKey> pResult
    = this->findKey( this->processToTreeMap_, processNode);
  if( pResult.first) {
    processKey = pResult.second;

  } else {
    // Horribly corrupt model, something oughta been done about it!
    ACE_ERROR((LM_ERROR,
      ACE_TEXT("(%P|%t) ERROR: MonitorDataStorage::manageTransportLink() - ")
      ACE_TEXT("unable to locate the process node in the maps!\n")
    ));
    return;
  }

  // Now we have enough information to build a TransportKey and find or
  // create a transport node for our Id value.
  TransportKey transportKey(
                 processKey.host,
                 processKey.pid,
                 transport_id
               );
  TreeNode* transportNode = this->getTransportNode( transportKey, create);
  if( !node) {
    return;
  }

  // Transport Id display.
  QString label( QObject::tr( "Transport"));
  int row = node->indexOf( 0, label);
  if( row == -1) {
    // New entry, add a reference to the actual transport node.
    QList<QVariant> list;
    list << label << QString( QObject::tr("<error>"));;
    TreeNode* idNode = new TreeNode( list, node);
    idNode->setColor( 1, QColor("#bfbfff"));
    node->append( idNode);
    transportNode->addValueRef( idNode);
    transportNode->setColor( 1, QColor("#bfffbf"));
    create = true;
  }
}
コード例 #2
0
ファイル: Tree.cpp プロジェクト: rumjack/fhscanhttplibrary
// -----------------------------------------------------------------------------
TreeNode* bTree::TreeInsert(HTTPCSTR str, TreeNode *ParentItem) {
    if (ParentItem == NULL) {
        if (root == NULL) {
            TreeNode *newnode = new TreeNode(str, NULL);
            newnode->SetTreeNodeParentTree(this);
            root = newnode;
            count++;
            return (root);
        }
        else {
            TreeNode *y = NULL;
            TreeNode *x = root;

            while (x != NULL) {
                if (_tcscmp(x->GetTreeNodeName(), str) == 0) {
                    /* already Exists */
                    return (x);
                }
                y = x;
                if (_tcscmp(str, x->GetTreeNodeName()) < 0)
                    x = x->GetTreeNodeLeft();
                else
                    x = x->GetTreeNodeRight();
            }
            /* str doesn't yet exist in tree - add it in */

            TreeNode *newnode = new TreeNode(str, y);
            newnode->SetTreeNodeParentTree(this);
            if (_tcscmp(str, y->GetTreeNodeName()) < 0) {
                y->SetTreeNodeLeft(newnode);
            }
            else {
                y->SetTreeNodeRight(newnode);
            }
            this->count++; /* Add an additional element to the tree counter */
            return (newnode);
        }
    }
    else {
        TreeNode*newnode = ParentItem->GetTreeNodeChildTree()->TreeInsert(str, NULL);
        return (newnode);
    }
}
コード例 #3
0
void TreeDustGridStructure::setupSelfBefore()
{
    GenDustGridStructure::setupSelfBefore();
    Log* log = find<Log>();

    // Validate attribute values

    if (_xmax <= 0.0 || _ymax <= 0.0 || _zmax <= 0.0) throw FATALERROR("The maximum extent should be positive");
    if (_minlevel < 0) throw FATALERROR("The minimum tree level should be at least 0");
    if (_maxlevel < 2) throw FATALERROR("The maximum tree level should be at least 2");
    if (_maxlevel <= _minlevel) throw FATALERROR("Maximum tree level should be larger than minimum tree level");
    if (_Nrandom < 1) throw FATALERROR("Number of random samples must be at least 1");
    if (_maxOpticalDepth < 0.0) throw FATALERROR("The maximum mean optical depth should be positive");
    if (_maxMassFraction < 0.0) throw FATALERROR("The maximum mass fraction should be positive");
    if (_maxDensDispFraction < 0.0) throw FATALERROR("The maximum density dispersion fraction should be positive");

    // If no assigner was set, use an IdenticalAssigner as default (each process builds the entire tree)
    if (!_assigner) setAssigner(new IdenticalAssigner(this));

    // Cache some often used values
    // A Parallel instance is created with a limited amount of threads (4) for performance reasons
    _parallel = find<ParallelFactory>()->parallel(4);
    _dd = find<DustDistribution>();
    _dmib = _dd->interface<DustMassInBoxInterface>();
    _useDmibForSubdivide = _dmib && !_maxDensDispFraction;
    _totalmass = _dd->mass();
    _eps = 1e-12 * extent().widths().norm();

    // Create the root node

    _tree.push_back(createRoot(extent()));

    // Recursively subdivide the root node until all nodes satisfy the
    // necessary criteria. When finished, set the number _Nnodes.

    int currentlevel = -1;
    unsigned int l = 0;
    while (true)
    {
        TreeNode* node = _tree[l];
        int level = node->level();
        if (level>currentlevel)
        {
            log->info("Starting subdivision of level " + QString::number(level) + "...");
            currentlevel = level;
        }
        if (l%50000 == 0)
            log->info("Subdividing node number " + QString::number(l) + "...");
        if (node->ynchildless())
            subdivide(node);
        l++;
        if (l>=_tree.size()) break;
    }
    _Nnodes = _tree.size();

    // Construction of a vector _idv that contains the node IDs of all
    // leaves. This is the actual dust cell vector (only the leaves will
    // eventually become valid dust cells). We also create a vector
    // _cellnumberv with the cell numbers of all the nodes (i.e. the
    // rank m of the node in the vector _idv if the node is a leaf, and
    // -1 if the node is not a leaf).

    int m = 0;
    _cellnumberv.resize(_Nnodes,-1);
    for (int l=0; l<_Nnodes; l++)
    {
        if (_tree[l]->ynchildless())
        {
            _idv.push_back(l);
            _cellnumberv[l] = m;
            m++;
        }
    }
    _Ncells = _idv.size();

    // Log the number of cells

    log->info("Construction of the tree finished.");
    log->info("  Total number of nodes: " + QString::number(_Nnodes));
    log->info("  Total number of leaves: " + QString::number(_Ncells));
    vector<int> countv(_maxlevel+1);
    for (int m=0; m<_Ncells; m++)
    {
        TreeNode* node = _tree[_idv[m]];
        int level = node->level();
        countv[level]++;
    }
    log->info("  Number of leaf cells of each level:");
    for (int level=0; level<=_maxlevel; level++)
        log->info("    Level " + QString::number(level) + ": " + QString::number(countv[level]) + " cells");

    // Determine the number of levels to be included in 3D grid output (if such output is requested)

    if (writeGrid())
    {
        int cumulativeCells = 0;
        for (_highestWriteLevel=0; _highestWriteLevel<=_maxlevel; _highestWriteLevel++)
        {
            cumulativeCells += countv[_highestWriteLevel];
            if (cumulativeCells > 1500) break;          // experimental number
        }
        if (_highestWriteLevel<_maxlevel)
            log->info("Will be outputting 3D grid data up to level " + QString::number(_highestWriteLevel) +
                      ", i.e. " + QString::number(cumulativeCells) + " cells.");
    }

    // Add neighbors to the tree structure (but only if required for the search method)

    if (_search == Neighbor)
    {
        log->info("Adding neighbors to the tree nodes...");
        for (int l=0; l<_Nnodes; l++) _tree[l]->addneighbors();
        for (int l=0; l<_Nnodes; l++) _tree[l]->sortneighbors();
    }
}
コード例 #4
0
void
Monitor::NodeGenerator::generate(TreeNode *t, QGraphicsScene *nodeScene, int w, int h, Node* parent)
{
  static int xpos = 0;
  static int ypos = 0;

  if (t == 0) {
    return;
  }

  Node *node = 0;

  QString text;
  if (isNodeValid(t, text)) {

    xpos = w * 100;
    ypos += 50;

    node = new Node(text, xpos, ypos, t);
    node->setParent(parent);

    // populate tooltips with the children
    TreeNode *c;
    std::ostringstream ttip;
    for (int i = 0; i < t->size(); ++i) {
      c = t->operator[](i);
      std::string k = c->column(0).toString().toLocal8Bit().constData();
      std::string v = c->column(1).toString().toLocal8Bit().constData();

      ttip << k << " : " << v << std::endl;
    }

    node->setToolTip(ttip.str().c_str());

    // this takes ownership of the node so the nodeScene will
    // cleanup all nodes when it's destroyed
    // TODO: This make each nodes parent the nodeScene. change this
    // so parent is the actual parent node using setParent()
    nodeScene->addItem(node);

    // connect us to our parent with a dashed line
    // connect us to the parent
    if (parent  && !nodeOpt_.hideParentChild()) {
      // give edge an actual parent so that z-order works
      Edge *edge = new Edge(parent, node, false,  parent);
      nodeScene->addItem(edge);
      parent->addEdge(edge);
      node->addEdge(edge);
    }
    // store node
    if (parent && !nodeOpt_.hidePubSub()) {
      nMap_[t] = node;
    }
  }

  // draw the child nodes
  ++w;
  for (int i = 0; i < t->size(); ++i) {
    generate(t->operator[](i), nodeScene, w, ++h, node);
  }

}
コード例 #5
0
ファイル: GameMonteCarloTree.cpp プロジェクト: ipidev/RamAi
bool RamAi::GameMonteCarloTree::NodeNeedsExpanding(const TreeNode &node) const
{
	return (node.GetNumberOfChildren() < ConsoleSettings::GetSpecs().GetNumberOfInputCombinations()) && PartialExpansion(node);
}
コード例 #6
0
ファイル: QueryParser.cpp プロジェクト: ptryfon/loxim-stats
	int QueryParser::parseIt(int sessionId, string query, TreeNode *&qTree, string &tcResultString, bool toBeTypeChecked, bool toBeOptimized) {
		QueryParser::setStatEvalRun(0);
		ErrorConsole &ec(ErrorConsole::get_instance(EC_QUERY_PARSER));

		try{
			qTree = parser->parse(query).release();
			debug_print(ec,  "Query not parsed properly...\n");
			debug_print(ec,  (ErrQParser | ENotParsed));
		} catch (LoximException &ex) {
			debug_print(ec, "Query parsed");
			return (ErrQParser | ENotParsed);
		}

		Indexes::QueryOptimizer::optimizeWithIndexes(qTree);

		//Nothing more needs to be done, if this is an internal query. (no screen logging, typechecking, optimization)
		if (!toBeTypeChecked && !toBeOptimized) {
			return 0;
		}

		if (Deb::ugOn()) {
			cout << " Tree before optimization:";
			cout << "\n--------------------------------------\n";
			qTree->putToString();
			cout << "\n--------------------------------------\n";
		}
		if ((shouldTypeCheck || shouldOptimize) && !qTree->skipPreprocessing()) {
			TreeNode *nt = qTree->clone();
			bool metadataCorrect = DataScheme::dScheme(sessionId)->getIsComplete();
			bool metadataUpToDate = DataScheme::dScheme(sessionId)->getIsUpToDate();
			if (!metadataCorrect || !metadataUpToDate) {
				debug_print(ec,  "Data scheme is not complete or not up to date); optimization and typechecking blocked.");
			}

			int typeCheckErrCode = 0;
			if (shouldTypeCheck && toBeTypeChecked && metadataCorrect && metadataUpToDate) {
				if (isTcOffTmp()) { debug_print(ec,  "Typechecking turned off temporarily"); tcResultString = "";}
				else {
					Deb::ug(" \n \n TYPECHECK BEGIN !!! \n \n");
					TypeChecker *tc = new TypeCheck::TypeChecker(nt);
					typeCheckErrCode = tc->doTypeChecking(tcResultString);
					Deb::ug(" \n \n TYPECHECK DONE... \n ");
					if ((typeCheckErrCode != 0) && (typeCheckErrCode != (ErrTypeChecker | ETCNotApplicable))) {
						debug_print(ec,  "TC, Parser: typeCheckErrorCode says general TC error, should return string to user.\n");
						return typeCheckErrCode;
					}
					if (typeCheckErrCode == 0) {
						delete qTree;
						qTree = nt;
					}
				}
			} else {
				if (shouldTypeCheck && toBeTypeChecked && dmlIncompleteAction == DML_AC_RETURN_ERROR) {
					if (!metadataCorrect) return (ErrTypeChecker | EIncompleteMetadata);
					else return (ErrTypeChecker | EMetadataOutdated);
				}
				tcResultString = "";
				Deb::ug("TypeChecking is disabled.");
			}

			if (shouldOptimize && toBeOptimized && metadataCorrect && metadataUpToDate) {
				Deb::ug(" optimisation is set ON !");
				int optres = 0;
				int stat_ev_res;
				nt = qTree->clone();
				if ((stat_ev_res = this->statEvaluate(sessionId, nt)) != 0) {
					Deb::ug("static evaluation did not work out ...");
					optres = -1;
				} else {
					int optres = -2;
					DeathRmver *rmver = new DeathRmver(this);
					rmver->rmvDeath(nt);
					if (this->statEvaluate(sessionId, nt) != 0) optres = -1;
	/* The main optimisation loop - factor out single independent subqueries *
	* as long as ... such exist !                                           */
					while (optres == -2) {
						optres = nt->optimizeTree();
						while (nt->getParent() != NULL) nt = nt->getParent();
						/*one more static eval, to make sure nodes have the right info.. */
						fprintf (stderr, "one more stat eval..\n");
						if (this->statEvaluate(sessionId, nt) != 0) optres = -1;
					}
					AuxRmver *auxRmver = new AuxRmver(this);
					auxRmver->rmvAux(nt);
					JoinRpcer *joinRpcer = new JoinRpcer(this);
					joinRpcer->replaceJoin(nt);
				}
				if (optres != -1) {
					Deb::ug("I'll return optimized tree\n");
					qTree = nt;
					if (Deb::ugOn()) {
						cout << "Tree after optimization:\n--------------------------------------\n";
						qTree->putToString(); cout << "\n--------------------------------------\n";
					}
				} else { Deb::ug("I'll return the tree from before static eval..");}
			} else {
				if (shouldTypeCheck && toBeTypeChecked && dmlIncompleteAction == DML_AC_RETURN_ERROR) {
					if (!metadataCorrect) return (ErrTypeChecker | EIncompleteMetadata);
					else return (ErrTypeChecker | EMetadataOutdated);
				}
				Deb::ug(" optimisation is disabled. \n");
			}
		} else {
			qTree->qpLocalAction(this);
		}
		Deb::ug(" ParseIt() ends successfully!");
		/*			cout << "td1------------------------------------------------------------\n";
					testDeath("EMP.NAME");
					cout << "td2------------------------------------------------------------\n";
					testDeath("(EMP join (WORKS_IN.DEPT)).NAME;");
					cout << "td3------------------------------------------------------------\n";
		*/
		if (Deb::ugOn()) {
			cout << "===================================================================" << endl;
			cout << "P    A    R    S    E    R        R    E    T    U    R    N    S :" << endl;
			qTree->serialize();
			cout << "\n===================================================================" << endl;
		}
		return 0;
	}
コード例 #7
0
int main () {
	//create a binary tree first

	TreeNode * a = new TreeNode ("A");
	TreeNode * b = new TreeNode ("B");
	TreeNode * c = new TreeNode ("C");
	TreeNode * d = new TreeNode ("D");
	TreeNode * e = new TreeNode ("E");
	TreeNode * f = new TreeNode ("F");
	TreeNode * g = new TreeNode ("G");
	TreeNode * h = new TreeNode ("H");
	TreeNode * i = new TreeNode ("I");


	a->setRight(c);
	a->setLeft(b);

	b->setRight(d);

	c->setRight(f);
	c->setLeft(e);

	e->setLeft(g);

	f->setLeft(h);
	f->setRight(i);

	vector <string> result = preorderTraversal(a);

	for(int i = 0; i < result.size(); i++ ) {
		cout << result[i] << endl;
	}

	return 0;
}
コード例 #8
0
int model::DbContainerModel::rowCount(const QModelIndex& parent /*= QModelIndex()*/) const
{
	TreeNode* node = Index2Node(parent);
	// Check for root
	return (node == nullptr) ? m_rootNodes.size() : node->GetChildrenCount();
}
コード例 #9
0
void ParticleTreeDustGridStructure::setupSelfBefore()
{
    GenDustGridStructure::setupSelfBefore();

    // Verify property values
    if (_xmax <= 0.0 || _ymax <= 0.0 || _zmax <= 0.0) throw FATALERROR("The maximum extent should be positive");

    // Cache some often used values
    Log* log = find<Log>();
    _eps = 1e-12 * extent().widths().norm();
    DustDistribution* dd = find<DustDistribution>();
    _dmib = dd->interface<DustMassInBoxInterface>();
    DustParticleInterface* dpi = dd->interface<DustParticleInterface>();
    if (!dpi) throw FATALERROR("Can't retrieve particle locations from this dust distribution");
    int numParticles = dpi->numParticles();
    log->info("Constructing tree for " + QString::number(numParticles) + " particles...");

    // Create a list, used only during construction, that contains the index of the particle
    // contained in each leaf node so far created, or -1 if the node is empty
    // (the value is undefined for nonleaf nodes)
    vector<int> particlev;

    // Create the root node (which at this point is an empty leaf) using the requested type
    switch (_treeType)
    {
    default:
    case OctTree:
        _tree.push_back(new OctTreeNode(0,0,extent()));
        break;
    case BinTree:
        _tree.push_back(new BinTreeNode(0,0,extent()));
        break;
    }
    particlev.push_back(-1);
    int maxlevel = 0;

    // Add particles one by one, subdividing if the leaf node containing the new particle
    // already contains another particle
    for (int i=0; i<numParticles; i++)
    {
        if (i%50000 == 0) log->info("Adding particle number " + QString::number(i) +
                                    " (" + QString::number(i*100/numParticles) + "%)...");
        int level = addParticleToNode(i, root(), dpi, particlev, _tree);
        maxlevel = max(maxlevel, level);
    }

    // Perform additional subdivisions as requested
    if (_extraLevels>0)
    {
        log->info("Performing additional subdivisions...");
        maxlevel += _extraLevels;
        for (int e=0; e<_extraLevels; e++)
        {
            int Nnodes = _tree.size();
            for (int l=0; l<Nnodes; l++)
            {
                TreeNode* node = _tree[l];
                if (node->ynchildless())
                {
                    node->createchildren(_tree.size());
                    _tree.insert(_tree.end(), node->children().begin(), node->children().end());
                }
            }
        }
    }

    // Construction of a vector _idv that contains the node IDs of all
    // leaves. This is the actual dust cell vector (only the leaves will
    // eventually become valid dust cells). We also create a vector
    // _cellnumberv with the cell numbers of all the nodes (i.e. the
    // rank m of the node in the vector _idv if the node is a leaf, and
    // -1 if the node is not a leaf).
    int Nnodes = _tree.size();
    int m = 0;
    _cellnumberv.resize(Nnodes,-1);
    for (int l=0; l<Nnodes; l++)
    {
        if (_tree[l]->ynchildless())
        {
            _idv.push_back(l);
            _cellnumberv[l] = m;
            m++;
        }
    }
    _Ncells = _idv.size();

    // Log the number of cells
    log->info("Construction of the tree finished.");
    log->info("  Total number of nodes: " + QString::number(Nnodes));
    log->info("  Total number of leaves: " + QString::number(_Ncells));
    vector<int> countv(maxlevel+1);
    for (int m=0; m<_Ncells; m++)
    {
        TreeNode* node = _tree[_idv[m]];
        int level = node->level();
        countv[level]++;
    }
    log->info("  Number of leaf cells of each level:");
    for (int level=0; level<=maxlevel; level++)
        log->info("    Level " + QString::number(level) + ": " + QString::number(countv[level]) + " cells");

    // Determine the number of levels to be included in 3D grid output (if such output is requested)
    if (writeGrid())
    {
        int cumulativeCells = 0;
        for (_highestWriteLevel=0; _highestWriteLevel<=maxlevel; _highestWriteLevel++)
        {
            cumulativeCells += countv[_highestWriteLevel];
            if (cumulativeCells > 1500) break;          // experimental number
        }
        if (_highestWriteLevel<maxlevel)
            log->info("Will be outputting 3D grid data up to level " + QString::number(_highestWriteLevel) +
                      ", i.e. " + QString::number(cumulativeCells) + " cells.");
    }
}
コード例 #10
0
 iterator begin(){
     if (root) return iterator(root->leftMost());
     else return iterator(NULL);
 }
コード例 #11
0
void algorithm2(int n, int m, int k, AdjacencyList &Graph, int** &Groups) {

    Tree* T = new Tree;
    Tree* C = NULL;
    Tree* R_i = NULL;
    Tree* current_path = NULL;
    TreeNode* ptr = NULL;
    int current_weight, i, j, current_t_i, t_i, real_weight;
    long int d_i = 1000000000;
    int group = 1000;

    // Add vertex in Groups[0] to T
    // and mark as reached
    T->insert(Groups[0][2], 0);
    Groups[0][0] = 1;
    cout << "0\n";
    
    while(1) {
        // check if there is at least one group that is unreached
        for(i = 0; i < k; i++) {
            if (!Groups[i][0]) // if there is a group unreached
                break;
        }
        if (i == k) // if i == k, then all groups are reached and we are done
            break;

        d_i = 1000000000;
        t_i = 1;
        group = 1000;

        for(i = 0; i < k; i++) {
            if (Groups[i][0] == 1)
                continue;

            // find a shortest path from vertex in g_i to vertex in T
            for (j = 2; j < Groups[i][1] + 2; j++) {
                // find a shortest path from vertex j in g_i to vertex in T
                current_path = Dijkstra(n, Groups[i][j], T, Graph);
                current_weight = current_path->get_last()->get_vertex_weight();
                current_path->set_total_weight(current_weight);// path_into_tree sums them at the end!
                current_t_i = num_groups_in_path(current_path, Groups, k);
                // the number of "not reached" groups that current_path visits


                // now comapre based off of d_i/t_i
                if ((double)current_weight/current_t_i < (double)d_i/t_i) {
                    R_i = current_path;
                    d_i = current_weight;
                    t_i = current_t_i;
                    group = i;
                } else if ((double)current_weight/current_t_i == (double)d_i/t_i) {
                    if (i < group) {
                        R_i = current_path;
                        d_i = current_weight;
                        t_i = current_t_i;
                        group = i;
                    } else if (i == group) { // if the distances AND groups are equal, lexicographic
                        if (!lexicographic(current_path, R_i)) {
                            R_i = current_path;
                            d_i = current_weight;
                            group = i;
                        }
                    }
                }
            }
        }

        // add R_i to T and mark group as reached
        T->insert(R_i);
        // create C - a collection of all the groups visited by path R_i that are not currently reached
        C = groups_in_path(R_i, Groups, k);
        // mark all the groups in C as marked
        for (ptr = C->get_first(); ptr != NULL; ptr = ptr->get_next()) {
            Groups[ptr->get_vertex_id()][0] = 1;
        }

        // create array from nodes in C, then sort the array
        int* C_array = new int[C->get_tree_size()];
        int* temp = new int[C->get_tree_size()];
        int step = 0;
        TreeNode* array_c;
        for(array_c = C->get_first(); array_c != NULL; array_c = array_c->get_next()) {
            C_array[step] = array_c->get_vertex_id();
            step++;
        }
        merge_sort(C_array, temp, 0, C->get_tree_size()-1);
        for (step = 0; step < C->get_tree_size(); step++) {
            cout << C_array[step] << "\n";
        }
        delete[] C_array;
        delete[] temp;
    }

    // print all vertices in T from smallest values to largest per line
    // create array from nodes in T, then sort the array
    // print sum of the weight of all the endges in T in one line
    int* final_array = new int[T->get_tree_size()];
    int* temp = new int[T->get_tree_size()];
    int step = 0;
    TreeNode* final_p;
    for(final_p = T->get_first(); final_p != NULL; final_p = final_p->get_next()) {
        final_array[step] = final_p->get_vertex_id();
        step++;
    }
    merge_sort(final_array, temp, 0, T->get_tree_size()-1);
    for (step = 0; step < T->get_tree_size(); step++)
        cout << final_array[step] << "\n";
    cout << T->get_total_weight() << "\n";

}
コード例 #12
0
ファイル: mdsobjex.cpp プロジェクト: Sangil-Lee/RefCode
int main(int argc, char *argv)
{
	int i, j;
	float data[10];
	float currData[2];

#if 0
	int socket;

	/* Connect to MDSplus */
	socket = MdsConnect (SERVER_ADDR);
	if ( socket == -1 ) {
		fprintf(stderr,"Error connecting to Atlas.\n");
		return EXIT_FAILURE;
	}
	printf ("after MdsConnect\n");
#endif

	try {
#if 0
		Connection *conn = new Connection (SERVER_ADDR);
		if (!conn) {
			printf ("Connection failed \n");
		}

		printf ("after Connection\n");
#endif

		/* Open pulse file, shot # */
		Tree *t = new Tree(TREE_NAME, SHOT_NUM);
		printf ("after Tree\n");

		/* Get node */
		TreeNode *node = t->getNode(TAG_NAME);
		printf ("after getNode\n");

		/* Make sure no data is contained */
		// Segmentation fault => 3.0 library & header is ok
		node->deleteData();

		//float stime = -5;
		float stime = -5;

		Data *start = new Float64(10.);
		Data *end = new Float64(11.);
		Data *rate = new Float64(0.1);
		Data *dimension = new Range(start, end, rate);

		memset (data, 0x00, sizeof(data));
		Array *dataArray = new Float32Array(data, 2);

		for (i = 0; i < 5; i++) {
			start = new Float64(stime + i);
			end = new Float64(stime + 0.1 + i);
			rate = new Float64(0.1);
			dimension = new Range(start, end, rate);

			node->beginSegment (start, end, dimension, dataArray);

			for(j = 0; j < 2; j++) {
				currData[j] = i+1;
			}

			printf ("[%02d] putSegment ... \n", i);

			Array *subArr = new Float32Array(currData, 2);

			node->putSegment (subArr, -1);

			Event::setEvent (EVENT_NAME);

			cout << "Data (" << node->getNumSegments() << ") : " << node->getData() << endl;

			/* Free stuff */
			//deleteData(start);
			//deleteData(end);
			//deleteData(rate);
			deleteData(dimension);
			delete(subArr);

			sleep (2);
		}
		delete(t);
	}
	catch(MdsException *exc) {
		cout << "Error appending segments: " << exc->what();
	}
}
コード例 #13
0
void
Monitor::MonitorDataStorage::displayNvp(
  TreeNode*                    parent,
  const OpenDDS::DCPS::NVPSeq& data,
  bool                         layoutChanged,
  bool                         dataChanged
)
{
  // NAME / VALUE DATA
  int size = data.length();
  for( int index = 0; index < size; ++index) {
    QString name( data[ index].name);
    int row = parent->indexOf( 0, name);
    if( row == -1) {
      // This is new data, insert it.
      QList<QVariant> list;
      list << name;
      switch( data[ index].value._d()) {
        case OpenDDS::DCPS::INTEGER_TYPE:
          list << QString::number( data[ index].value.integer_value());
          break;

        case OpenDDS::DCPS::DOUBLE_TYPE:
          list << QString::number( data[ index].value.double_value());
          break;

        case OpenDDS::DCPS::STRING_TYPE:
          list << QString( data[ index].value.string_value());
          break;

        case OpenDDS::DCPS::STATISTICS_TYPE:
        case OpenDDS::DCPS::STRING_LIST_TYPE:
          list << QString( QObject::tr("<display unimplemented>"));
          break;
      }
      TreeNode* node = new TreeNode( list, parent);
      parent->append( node);
      layoutChanged = true;

    } else {
      // This is existing data, update the value.
      TreeNode* node = (*parent)[ row];
      switch( data[ index].value._d()) {
        case OpenDDS::DCPS::INTEGER_TYPE:
          node->setData( 1, QString::number( data[ index].value.integer_value()));
          break;

        case OpenDDS::DCPS::DOUBLE_TYPE:
          node->setData( 1, QString::number( data[ index].value.double_value()));
          break;

        case OpenDDS::DCPS::STRING_TYPE:
          node->setData( 1, QString( data[ index].value.string_value()));
          break;

        case OpenDDS::DCPS::STATISTICS_TYPE:
        case OpenDDS::DCPS::STRING_LIST_TYPE:
          break;
      }
      dataChanged = true;
    }
  }

  // Notify the GUI if we have changed the underlying model.
  if( layoutChanged) {
    /// @TODO: Check that we really do not need to do updated here.
    this->model_->changed();

  } else if( dataChanged) {
    this->model_->updated( parent, 1, (*parent)[ parent->size()-1], 1);
  }
}
コード例 #14
0
void
Monitor::MonitorDataStorage::manageTopicLink(
  TreeNode*                    node,
  const OpenDDS::DCPS::GUID_t& dp_id,
  const OpenDDS::DCPS::GUID_t& topic_id,
  bool&                        create
)
{
  // This gets a bit tedious.  Here are the cases:
  // 1) We currently have no reference, and found a Topic node to
  //    reference:
  //    - attach a reference to the topic node;
  // 2) We currently have no reference, and found a Name node to
  //    reference:
  //    - attach a reference to the name node;
  // 3) We currently have a Topic node referenced, and found the same
  //    topic node to reference:
  //    - nothing to do;
  // 4) We currently have a Topic node referenced, and found a different
  //    Topic node to reference:
  //    - detach previous reference and reattach to new topic node;
  // 5) We currently have a Topic node referenced, but were able to find
  //    a name node to reference:
  //    - detach previous reference and reattach to new name node;
  // 6) We currently have a Name node referenced, and found the same name
  //    node to reference:
  //    - nothing to do;
  // 7) We currently have a Name node referenced, and found a different
  //    name node to reference:
  //    - detach previous reference and reattach to new name node;
  // 8) We currently have a Name node referenced, and found a different
  //    Topic node to reference:
  //    - detach previous reference and reattach to new topic node.
  //
  // Note that cases (4), (7), and (8) indicate inconsistent data reports
  // and are error conditions.  We chose to not handle these cases.
  // Cases (3) and (6) require no action, so the only code paths we need
  // to consider are for cases (1), (2), and (5).

  // Find the actual topic.
  TreeNode* topicNode = this->getNode(
                          std::string( "Topic"),
                          dp_id,
                          topic_id,
                          create
                        );
  if( !topicNode) {
    return;
  }

  // Find the topic name to reference instead of the GUID value.
  TreeNode* nameNode = 0;
  QString nameLabel( QObject::tr( "Topic Name"));
  int row = topicNode->indexOf( 0, nameLabel);
  if( row != -1) {
    nameNode = (*topicNode)[ row];
  }

  // Check for an existing Topic entry.
  QString topicLabel( QObject::tr( "Topic"));
  int topicRow = node->indexOf( 0, topicLabel);
  if( nameNode && topicRow != -1) {
    // Case 5: We have a topic reference and found a name reference,
    //         remove the existing topic reference
    TreeNode* topicRef = (*node)[ topicRow];
    if( topicRef && topicRef->valueSource()) {
      topicRef->valueSource()->removeValueRef( topicRef);
    }
//  node->removeChildren( topicRow, 1); // DEVELOPMENT: don't delete to show stale data.
  }

  // The node to install.
  TreeNode* refNode = nameNode;
  if( !refNode) {
    refNode = topicNode;
  }

  // Check to see if we need to create a name entry.
  int nameRow  = node->indexOf( 0, nameLabel);
  if( nameRow == -1) {
    // New entry, add a reference to the topic or its name.
    QList<QVariant> list;
    list << topicLabel << QString( QObject::tr("<error>"));
    TreeNode* idNode = new TreeNode( list, node);
    idNode->setColor( 1, QColor("#bfbfff"));
    node->append( idNode);
    refNode->addValueRef( idNode);
    refNode->setColor( 1, QColor("#bfffbf"));
    create = true;
  }
}
コード例 #15
0
	void print() {
		root->print();
	}
コード例 #16
0
ファイル: TreeNode.cpp プロジェクト: Aatch/bullet3
void TreeNode::iterate(int action, int* curIndex, int* targetIndex)
{

	Gwen::String name = Gwen::Utility::UnicodeToString(m_Title->GetText());
	
//	int actualIndex = curIndex? *curIndex : -1;
	//printf("iterated over item %d with name = %s\n", actualIndex, name.c_str());

	if (action==ITERATE_ACTION_SELECT)
	{
		if (curIndex && targetIndex)
		{
			if ((*curIndex)==(*targetIndex))
			{
				SetSelected(true);
				
				*targetIndex=-1;
			}
		}
	}

	if (IsSelected())
	{
		//printf("current selected: name = %s\n", name.c_str());
		switch (action)
		{
		case ITERATE_ACTION_DESELECT_INDEX:
			{
				if (targetIndex && curIndex)
				{
					if (*targetIndex == *curIndex)
						SetSelected(false);
				}
				break;
			}
		case ITERATE_ACTION_FIND_SELECTED_INDEX:
			{
				if (targetIndex && curIndex)
				{
					*targetIndex = *curIndex;
				}
				break;
			}
		case ITERATE_ACTION_OPEN:
			{
				Open();
				
				
				break;
			}
		case ITERATE_ACTION_CLOSE:
		{
			//either close or select parent
			if (this->GetChildren().size())
			{
				if (m_ToggleButton && m_ToggleButton->GetToggleState())
				{
					Close();
				} else
				{
					
					TreeNode* pChild = (GetParent())->DynamicCastTreeNode();
					TreeControl* pChild2 = (GetParent())->DynamicCastTreeControl();
					if (pChild && !pChild2)
					{
						SetSelected(false);
						pChild->SetSelected(true);
					}
				}
			}
			else
			{
				
				TreeNode* pChild = (GetParent())->DynamicCastTreeNode();
				TreeControl* pChild2 = (GetParent())->DynamicCastTreeControl();
				if (pChild && !pChild2)
				{
					SetSelected(false);
					pChild->SetSelected(true);
				}
			}
			
			break;
		}
		default:
			{
			}
		};
	}

	if (curIndex)
		(*curIndex)++;

	bool needsRecursion = true;

	if (action == ITERATE_ACTION_FIND_SELECTED_INDEX || action==ITERATE_ACTION_SELECT || action==ITERATE_ACTION_DESELECT_INDEX)
	{
		if (m_ToggleButton && !m_ToggleButton->GetToggleState())
		{
			needsRecursion=false;
		}
	}

	if (needsRecursion)
	{
		Base::List& children = m_InnerPanel->GetChildren();
		for ( Base::List::iterator iter = children.begin(); iter != children.end(); ++iter )
		{
			TreeNode* pChild = (*iter)->DynamicCastTreeNode();
			if ( !pChild ) 
				continue;

			pChild->iterate(action , curIndex, targetIndex);
		}
	}

	
	
}
コード例 #17
0
ファイル: Tree.hpp プロジェクト: Raychee/SoftLabelForest
Tree<_DATA>& Tree<_DATA>::
read_this(const char* dir) {
    char path[SIZEOF_PATH], * filename, line_str[SIZEOF_PATH], * filename_str;
    std::strcpy(path, dir);
    std::size_t dir_len = std::strlen(path);
    std::size_t file_len;
    if (dir_len > 0 && (path[dir_len - 1] != '/' && path[dir_len - 1] != '\\'))
        path[dir_len++] = '/';
    filename = path + dir_len;
    file_len = SIZEOF_PATH - dir_len;
    std::strcpy(filename, "Tree");
    std::ifstream file(path);
    if (!file.is_open()) {
        std::cerr << "\nFailed opening file: " << path << std::endl;
        return *this;
    }
    while(file.getline(line_str, SIZEOF_LINE) && !line_str[0]);
    if (!line_str[0]) {
        std::cerr << "\nFailed finding file for root." << std::endl;
        return *this;
    }
    file.close();
    filename_str = strtostr(line_str);
    std::strcpy(filename, filename_str);
    file.open(path);
    if (!file.is_open()) {
        std::cerr << "\nFailed opening file: " << path << std::endl;
        return *this;
    }
    unsigned long node_num;
    _DATA* data;
    std::queue<unsigned long> node_name;
    std::queue<TreeNode*>     node_parent_pointer;
    file.getline(line_str, SIZEOF_LINE);
    file.getline(line_str, SIZEOF_LINE);
    file.getline(line_str, SIZEOF_LINE);
    unsigned int n_child = strto<unsigned int>(line_str, 10);
    root_ = new TreeNode(NULL, NULL, n_child);
    for (unsigned int i = 0; i < n_child; ++i) {
        file.getline(line_str, SIZEOF_LINE);
        node_num = strto<unsigned long>(line_str, 10);
        node_name.push(node_num);
        node_parent_pointer.push(root_);
    }
    data = new _DATA();
    file >> *data;
    file.close();
    root_->pcontent(data);
    while (!node_name.empty()) {
        unsigned long name   = node_name.front();
        TreeNode*     parent = node_parent_pointer.front();
        std::snprintf(filename, file_len, "%016lu.node", name);
        file.open(path);
        if (!file.is_open()) {
            std::cerr << "\nFailed opening file: " << path << std::endl;
            node_name.pop();
            node_parent_pointer.pop();
            continue;
        }
        file.getline(line_str, SIZEOF_LINE);
        file.getline(line_str, SIZEOF_LINE);
        file.getline(line_str, SIZEOF_LINE);
        unsigned int n_child = strto<unsigned int>(line_str, 10);
        TreeNode* node = new TreeNode(NULL, parent, n_child);
        parent->attach_child(node);
        for (unsigned int i = 0; i < n_child; ++i) {
            file.getline(line_str, SIZEOF_LINE);
            node_num = strto<unsigned long>(line_str, 10);
            node_name.push(node_num);
            node_parent_pointer.push(node);
        }
        data = new _DATA();
        file >> *data;
        file.close();
        node->pcontent(data);
        node_name.pop();
        node_parent_pointer.pop();
    }
    return *this;
}
コード例 #18
0
TreeNode* Parser::Factor()
{
	TreeNode* node;
	Token rememberedToken = currentToken;
	switch (currentToken.type)
	{
		case tokBraceOpen:
			matchToken(tokBraceOpen);
			node = Expression();
			matchToken(tokBraceClose);
			break;

		case tokUnknown:
			node = getId();
			if (learnedFunctionList.contains(rememberedToken.look) > 0) // is function call
			{
				delete node;
				node = FunctionCall(rememberedToken);
				node->setType(funcReturnNode); // expect returned value on stack
			}
			break;

		case tokString:
			node = new TreeNode(currentToken, constantNode);
			{ // extra scope to localize the QString 'str'
				QString str = currentToken.look;
				if ( currentToken.look.endsWith("\"") )
				{
					// cut off the quotes and store the value
					str.remove(0, 1).truncate( currentToken.look.length() - 2 );
				}
				else // problems but we need to keep it moving
				{
					str.remove(0, 1); // cut off the first quote only
					Error(currentToken, i18n("String text not properly delimited with a ' \" ' (double quote)"), 1060);
				}
				node->setValue(str);
			}
			matchToken(tokString);
			break;

		case tokNumber:
			node = new TreeNode(currentToken, constantNode);
			node->setValue(currentToken.value);
			matchToken(tokNumber);
			break;

		case tokRun:
			node = ExternalRun();
			break;

		case tokInputWindow:
			node = InputWindow();
			break;

		case tokRandom:
			node = Random();
			break;

		case tokEOL:
			node = new TreeNode(currentToken, Unknown);
			break;

		default:
			QString s = currentToken.look;
			if ( s.isEmpty() || currentToken.type == tokEOF )
			{
				Error(currentToken, i18n("INTERNAL ERROR NR %1: please sent this Logo script to KTurtle developers").arg(1), 1020);
				// if this error occurs the see the Parser::Repeat for the good solution using 'preservedToken'
			}
			else
			{
				Error(currentToken, i18n("Cannot understand '%1', expected an expression after the '%2' command").arg(s).arg(preservedToken.look), 1020);
			}
			node = new TreeNode(currentToken, Unknown);
			getToken();
			break;
	}
	return node;
}
コード例 #19
0
void AVLTree::Delete(TreeNode * &node, int x, QAnimationGroup *group)
{
    if (node == NULL)
        return;
    if (group&& node->parent)
        group->addAnimation(node->parent->getTurnRedAnim());
    TreePath *path;
    if (group && node->parent)
    {
        path = new TreePath(node->parent, node, view);
        group->addAnimation(path->getToSonAnim());
    }
    TreeNode* parent = node->parent;
    if (x < node->data)
    {
        //如果x小于节点的值,就继续在节点的左子树中删除x
        Delete(node->Lson, x, group);
        if (group && node->parent)
            group->addAnimation(path->getToParentAnim());
        if (2 == height(node->Rson) - height(node->Lson))
        {
            if (node->Rson->Lson != NULL &&
                (height(node->Rson->Lson)>height(node->Rson->Rson)))
                RL(node, group);
            else
                RR(node, group);
        }

    }
    else if (x > node->data)
    {
        Delete(node->Rson, x, group);//如果x大于节点的值,就继续在节点的右子树中删除x
        if (group && node->parent)
            group->addAnimation(path->getToParentAnim());
        if (2 == height(node->Lson) - height(node->Rson))
        {
            if (node->Lson->Rson != NULL &&
                (height(node->Lson->Rson)>height(node->Lson->Lson)))
                LR(node, group);
            else
                LL(node, group);
        }

    }
    else//如果相等,此节点就是要删除的节点
    {
        if (group)
            group->addAnimation(node->getPopAnim());
        else
            node->getPopAnim()->start(QAbstractAnimation::DeleteWhenStopped);
        if (node->Lson && node->Rson)//此节点有两个儿子
        {
            TreeNode* temp = node->Rson;//temp指向节点的右儿子
            while (temp->Lson != NULL) temp = temp->Lson;//找到右子树中值最小的节点
            //把右子树中最小节点的值赋值给本节点
            if (group)
                group->addAnimation(node->getValueAnim(temp->data));
            else
                node->data = temp->data;
            //node->freq = temp->freq;
            Delete(node->Rson, temp->data, group);//删除右子树中最小值的节点
            if (group && node->parent)
                group->addAnimation(path->getToParentAnim());
            if (2 == height(node->Lson) - height(node->Rson))
            {
                if (node->Lson->Rson != NULL &&
                    (height(node->Lson->Rson)>height(node->Lson->Lson)))
                    LR(node, group);
                else
                    LL(node, group);
            }
        }
        else//此节点有1个或0个儿子
        {
            TreeNode* temp = node;
            TreeNode* parent = node->parent;
            if (group && node->parent)
                group->addAnimation(path->getToParentAnim());
            if (node->Lson == NULL)//有右儿子或者没有儿子
                node = node->Rson;
            else if (node->Rson == NULL)//有左儿子
                node = node->Lson;
            if (group)
            {
                QParallelAnimationGroup *anim = new QParallelAnimationGroup;
                anim->addAnimation(temp->getFadeOutAnim());
                if (node)
                    anim->addAnimation(node->setParent(parent));
                group->addAnimation(anim);
            }
            else
            {
                temp->getFadeOutAnim()->start(QAbstractAnimation::DeleteWhenStopped);
                if (node)
                    node->setParent(parent)->start(QAbstractAnimation::DeleteWhenStopped);
            }
            if (group)
                group->addAnimation(getPosAnim());
        }
    }
    if (group && parent)
        group->addAnimation(parent->getTurnBlackAnim());
    if (node == NULL)
        return;
    node->h = max(height(node->Lson), height(node->Rson)) + 1;
    return;
}
コード例 #20
0
/* Parse and Translate an Expression */
TreeNode* Parser::Expression()
{
	TreeNode* retExp = Term(); // preset the base-TreeNode as it eventually will be returned
	TreeNode* pos = retExp;
	TreeNode* left = NULL;
	TreeNode* right = NULL;

	while ( isAddOp(currentToken) )
	{
		left = pos;
		pos = new TreeNode(currentToken, Unknown);
		pos->appendChild(left);
		switch (currentToken.type)
		{
			case tokPlus:
				matchToken(tokPlus);
				right = Term();
				pos->setType(addNode);
				break;

			case tokMinus:
				matchToken(tokMinus);
				right = Term();
				pos->setType(subNode);
				break;

			case tokGt:
				matchToken(tokGt);
				right = Term();
				pos->setType(nodeGT);
				break;

			case tokLt:
				matchToken(tokLt);
				right = Term();
				pos->setType(nodeLT);
				break;

			case tokGe:
				matchToken(tokGe);
				right = Term();
				pos->setType(nodeGE);
				break;

			case tokLe:
				matchToken(tokLe);
				right = Term();
				pos->setType(nodeLE);
				break;

			case tokEq:
				matchToken(tokEq);
				right = Term();
				pos->setType(nodeEQ);
				break;

			case tokNe:
				matchToken(tokNe);
				right = Term();
				pos->setType(nodeNE);
				break;

			case tokOr:
				matchToken(tokOr);
				right = Term();
				pos->setType(orNode);
				break;

			default:
				Error(currentToken, i18n("Expected '*' or '/'"), 1040);
				getToken();
				return pos;
				break;
		}
		if (right != NULL) pos->appendChild(right);
		retExp = pos;
	}
	return retExp;
}
コード例 #21
0
void Qtilities::Testing::TestSubjectIterator::testIterationComplex() {
    TreeNode node;
    TreeNode* nodeA = node.addNode("A");
    TreeNode* nodeB = node.addNode("B");
    nodeA->addItem("1");
    TreeItem* shared_item = nodeA->addItem("2");
    nodeA->addItem("3");
    nodeB->addItem("4");
    nodeB->addItem("5");
    nodeB->attachSubject(shared_item);
    nodeB->addItem("6");

    // If we want to iterate through the subjects in nodeA:
    SubjectIterator<QObject> itrA(nodeA,SubjectIterator<QObject>::IterateChildren);
    QVERIFY(itrA.current() != 0);

    // In this case item1 will be skipped:
    QStringList testListA;
    testListA << itrA.current()->objectName();
    while (itrA.hasNext()) {
        testListA << itrA.next()->objectName();
    }

    QCOMPARE(testListA.count(), 3);
    QCOMPARE(testListA.at(0), QString("1"));
    QCOMPARE(testListA.at(1), QString("2"));
    QCOMPARE(testListA.at(2), QString("3"));

    // If we want to iterate through the subjects in nodeB:
    SubjectIterator<QObject> itrB(nodeB,SubjectIterator<QObject>::IterateChildren);

    // In this case item1 will be skipped:
    QStringList testListB;
    testListB << itrB.current()->objectName();
    while (itrB.hasNext()) {
        testListB << itrB.next()->objectName();
    }

    QCOMPARE(testListB.count(), 4);
    QCOMPARE(testListB.at(0), QString("4"));
    QCOMPARE(testListB.at(1), QString("5"));
    QCOMPARE(testListB.at(2), QString("2"));
    QCOMPARE(testListB.at(3), QString("6"));

    // If we want to iterate through the subjects in nodeB:
    SubjectIterator<QObject> itrC(shared_item,nodeB);

    // In this case item1 will be skipped:
    QStringList testListC;
    testListC << itrC.current()->objectName();
    while (itrC.hasNext()) {
        testListC << itrC.next()->objectName();
    }

    QCOMPARE(testListC.count(), 2);
    QCOMPARE(testListC.at(0), QString("2"));
    QCOMPARE(testListC.at(1), QString("6"));

    // If we want to iterate through the subjects in nodeB:
    SubjectIterator<QObject> itrD(shared_item,nodeA);

    // In this case item1 will be skipped:
    QStringList testListD;
    testListD << itrD.current()->objectName();
    while (itrD.hasNext()) {
        testListD << itrD.next()->objectName();
    }

    QCOMPARE(testListD.count(), 2);
    QCOMPARE(testListD.at(0), QString("2"));
    QCOMPARE(testListD.at(1), QString("3"));
}
コード例 #22
0
ファイル: main.cpp プロジェクト: KGE-INC/VirtualDub
void output_standard_tag(Context& ctx, std::string *out, const TreeNode& tag) {
	if (!tag.mbIsText && tag.mName == "pre")
		++ctx.pre_count;

	if (out && (tag.mbIsControl || !tag.mbIsText)) {
		if (ctx.holding_space && ctx.cdata_count) {
			if (!ctx.eat_next_space) {
				*out += ' ';
			}
			ctx.eat_next_space = false;
			ctx.holding_space = false;
		}
	}

	if (!ctx.construction_stack.empty()) {
		TreeNode *new_tag = ctx.mpDocument->AllocNode();

		new_tag->mpLocation		= tag.mpLocation;
		new_tag->mLineno		= tag.mLineno;
		new_tag->mName			= tag.mName;
		new_tag->mAttribs		= tag.mAttribs;
		new_tag->mbIsText		= tag.mbIsText;
		new_tag->mbIsControl	= tag.mbIsControl;

		ctx.construction_stack.back()->mChildren.push_back(new_tag);
		ctx.construction_stack.push_back(new_tag);

		output_tag_contents(ctx, out, tag);

		ctx.construction_stack.pop_back();
	} else if (tag.mbIsText) {
		if (out) {
			if (tag.mbIsControl) {
				*out += tag.mName;
			} else if (ctx.cdata_count) {
				if (ctx.pre_count) {
					*out += tag.mName;
				} else {
					std::string::const_iterator it(tag.mName.begin()), itEnd(tag.mName.end());

					for(; it!=itEnd; ++it) {
						const char c = *it;

						if (isspace(c)) {
							ctx.holding_space = true;
						} else {
							if (ctx.eat_next_space)
								ctx.eat_next_space = false;
							else if (ctx.holding_space)
								*out += ' ';

							ctx.holding_space = false;
							*out += c;
						}
					}
				}
			} else {
				std::string::const_iterator it(tag.mName.begin()), itEnd(tag.mName.end());

				for(; it!=itEnd; ++it) {
					const char c = *it;

					if (!isspace(c))
						error(ctx, "inline text not allowed");
				}
			}
		}
	} else {
		bool cdata = tag.SupportsCDATA();

		if (cdata) {
			if (!ctx.cdata_count) {
				ctx.holding_space = false;
				ctx.eat_next_space = true;
			}
			++ctx.cdata_count;
		}

		if (!out) {
			output_tag_contents(ctx, out, tag);
		} else if (tag.mChildren.empty()) {
			*out += '<';
			*out += tag.mName;
			output_tag_attributes(*out, tag);
			*out += '>';
		} else {
			*out += '<';
			*out += tag.mName;
			output_tag_attributes(*out, tag);
			*out += '>';

			output_tag_contents(ctx, out, tag);

			*out += "</";
			*out += tag.mName;
			*out += '>';
		}

		if (cdata)
			--ctx.cdata_count;
	}
	if (!tag.mbIsText && tag.mName == "pre")
		--ctx.pre_count;
}
コード例 #23
0
bool
Monitor::NodeGenerator::isNodeValid(TreeNode *t, QString &text)
{
  bool ret = false;

  // draw this node ?
  if (t != root_ && t->width() >= 2) {
    if (!honorDisplayFlag_ || (honorDisplayFlag_ && t->display())) {
      std::string key = t->column(0).toString().toLocal8Bit().constData();
      std::string val = t->column(1).toString().toLocal8Bit().constData();

      // host and process nodes
      // TODO: this is terribly ugly
      if (
        (key == "Host" && !nodeOpt_.ignoreHosts()) ||
        (key == "Process" && !nodeOpt_.ignoreProcs()) ||
        (key == "DomainParticipant") ||
        (key == "Publisher" && !nodeOpt_.ignorePubs()) ||
        (key == "Subscriber" && !nodeOpt_.ignoreSubs()) ||
        (key == "Topic" && !nodeOpt_.hideTopics()) ||
        (key == "Transport" && !nodeOpt_.ignoreTransports()) ||
        (key == "Reader" || key == "Writer") ||
        (key == "Qos" && !nodeOpt_.ignoreQos())
        ) {

          ret = true;

          // check for ignoreBuiltInTopics
          if (key == "Topic" && !nodeOpt_.hideTopics() &&
              nodeOpt_.ignoreBuiltinTopics()) {

            ret = false;
            std::string tmp;
            TreeNode* c;

            for (int i = 0; i < t->size(); ++i) {
              c = t->operator[](i);
              tmp = c->column(0).toString().toLocal8Bit().constData();

              if (tmp == "Topic Name") {
                tmp = c->column(1).toString().toLocal8Bit().constData();
                if(tmp.substr(0, 4) != "DCPS") {
                  ret = true;
                }
              }
            }
          }

          if (ret) {
            // yes, draw this node!
            if (nodeOpt_.abbrGUIDs()) {
              val = abbr(val);
            }

            text = key.c_str();
            text += "\n";
            text += val.c_str();
          }
        }
    }
  }

  return ret;
}
コード例 #24
0
ファイル: main.cpp プロジェクト: KGE-INC/VirtualDub
void output_special_tag(Context& ctx, std::string *out, const TreeNode& tag) {
	if (tag.mName == "lina:fireball") {
		const TreeAttribute *a1 = tag.Attrib("src");
		const TreeAttribute *a2 = tag.Attrib("dst");

		if (!a1 || !a2)
			error(ctx, "<lina:fireball> requires SRC and DST attributes");

		g_fileCopies[a2->mValue] = a1->mValue;
	} else if (tag.mName == "lina:write") {
		const TreeAttribute *a = tag.Attrib("file");

		if (!a)
			error(ctx, "<lina:write> must specify FILE");

		std::string s;

		std::list<TreeNode *> tempStack;
		ctx.construction_stack.swap(tempStack);
		int cdataCount = ctx.cdata_count;
		int preCount = ctx.pre_count;
		ctx.cdata_count = 0;
		ctx.pre_count = 0;
		bool bHoldingSpace = ctx.holding_space;
		bool bEatNextSpace = ctx.eat_next_space;
		ctx.holding_space = false;
		ctx.eat_next_space = true;
		output_tag_contents(ctx, &s, tag);
		ctx.holding_space = bHoldingSpace;
		ctx.eat_next_space = bEatNextSpace;
		ctx.pre_count = cdataCount;
		ctx.cdata_count = preCount;
		ctx.construction_stack.swap(tempStack);

		std::string filename(create_output_filename(a->mValue));

		FILE *f = fopen(filename.c_str(), "wb");
		if (!f)
			error(ctx, "couldn't create \"%s\"", a->mValue.c_str());
		fwrite(s.data(), s.length(), 1, f);
		fclose(f);

		printf("created file: %s\n", a->mValue.c_str());
	} else if (tag.mName == "lina:body") {

//		printf("outputting:\n");
//		dump_parse_tree(*ctx.invocation_stack.back(), 4);

		output_tag_contents(ctx, out, *ctx.invocation_stack.back());
	} else if (tag.mName == "lina:tag") {
		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:tag> must have NAME attribute");

		ctx.construction_stack.push_back(ctx.mpDocument->AllocNode());
		TreeNode *new_tag = ctx.construction_stack.back();

		new_tag->mpLocation = tag.mpLocation;
		new_tag->mLineno = tag.mLineno;
		new_tag->mName = a->mValue;
		new_tag->mbIsText = false;
		new_tag->mbIsControl = false;

		// compatibility
		if (!new_tag->mName.compare(0, 2, "w:"))
			new_tag->mName.replace(0, 2, "lina:");

		output_tag_contents(ctx, NULL, tag);

		ctx.construction_stack.pop_back();
		output_tag(ctx, out, *new_tag);
	} else if (tag.mName == "lina:arg") {
		if (!out && ctx.construction_stack.empty())
			error(ctx, "<lina:arg> can only be used in an output context");
		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:arg> must have NAME attribute");

		if (ctx.invocation_stack.empty())
			error(ctx, "<lina:arg> can only be used during macro expansion");

		std::list<const TreeNode *>::const_iterator it(ctx.invocation_stack.end());
		--it;

		int levels = 1;
		const char *name = a->mValue.c_str();
		while(*name == '^') {
			++levels;
			++name;

			if (it == ctx.invocation_stack.begin())
				error(ctx, "Number of up-scope markers in name exceeds macro nesting level");

			--it;
		}

		const TreeNode& macrotag = **it;
		const TreeAttribute *a2 = macrotag.Attrib(name);
		if (!a2)
			error(ctx, "macro invocation <%s> does not have an attribute \"%s\"", macrotag.mName.c_str(), name);

		if (out) {
			*out += a2->mValue;

			ctx.eat_next_space = false;
			ctx.holding_space = false;
		} else {
			TreeNode *t = ctx.mpDocument->AllocNode();

			t->mpLocation = tag.mpLocation;
			t->mLineno = tag.mLineno;
			t->mbIsControl = false;
			t->mbIsText = true;
			t->mName = a2->mValue;

			ctx.construction_stack.back()->mChildren.push_back(t);
		}
	} else if (tag.mName == "lina:if-arg") {
		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:if-arg> must have NAME attribute");

		if (ctx.invocation_stack.empty())
			error(ctx, "<lina:if-arg> can only be used during macro expansion");

		const TreeNode& macrotag = *ctx.invocation_stack.back();
		const TreeAttribute *a2 = macrotag.Attrib(a->mValue);
		if (a2)
			output_tag_contents(ctx, out, tag);
	} else if (tag.mName == "lina:if-not-arg") {
		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:if-not-arg> must have NAME attribute");

		if (ctx.invocation_stack.empty())
			error(ctx, "<lina:if-not-arg> can only be used during macro expansion");

		const TreeNode& macrotag = *ctx.invocation_stack.back();
		const TreeAttribute *a2 = macrotag.Attrib(a->mValue);
		if (!a2)
			output_tag_contents(ctx, out, tag);
	} else if (tag.mName == "lina:attrib") {
		if (ctx.construction_stack.empty())
			error(ctx, "<lina:attrib> can only be used in a <lina:tag> element");

		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:attrib> must have NAME attribute");

		std::string s;
		std::list<TreeNode *> tempStack;
		ctx.construction_stack.swap(tempStack);
		++ctx.cdata_count;
		++ctx.pre_count;
		bool bHoldingSpace = ctx.holding_space;
		bool bEatNextSpace = ctx.eat_next_space;
		ctx.holding_space = false;
		ctx.eat_next_space = true;
		output_tag_contents(ctx, &s, tag);
		ctx.holding_space = bHoldingSpace;
		ctx.eat_next_space = bEatNextSpace;
		--ctx.pre_count;
		--ctx.cdata_count;
		ctx.construction_stack.swap(tempStack);

		TreeNode *t = ctx.construction_stack.back();
		TreeAttribute new_att;
		if (tag.Attrib("novalue")) {
			new_att.mbNoValue = true;
		} else {
			new_att.mbNoValue = false;
			new_att.mValue = s;
		}
		new_att.mName = a->mValue;
		t->mAttribs.push_back(new_att);
	} else if (tag.mName == "lina:pull") {
		if (ctx.invocation_stack.empty())
			error(ctx, "<lina:pull> can only be used during macro expansion");

		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:pull> must have NAME attribute");

		const TreeNode *t = ctx.find_tag(a->mValue);
		
		if (!t)
			error(ctx, "cannot find tag <%s> referenced in <lina:pull>", a->mValue.c_str());

		output_tag_contents(ctx, out, *t);		
	} else if (tag.mName == "lina:for-each") {
		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:for-each> must have NAME attribute");
		
		std::string node_name;
		const TreeNode *parent;
		if (ctx.invocation_stack.empty()) {
			if (!a->mValue.empty() && a->mValue[0] == '/')
				parent = ctx.mpDocument->mpRoot->ResolvePath(a->mValue.substr(1), node_name);
			else
				error(ctx, "path must be absolute if not in macro context");
		} else {
			std::list<const TreeNode *>::reverse_iterator it(ctx.invocation_stack.rbegin()), itEnd(ctx.invocation_stack.rend());
			
			for(; it!=itEnd; ++it) {
				parent = (*it)->ResolvePath(a->mValue, node_name);
				if(parent)
					break;
				if (!a->mValue.empty() && a->mValue[0] == '/')
					break;
			}
		}

		if (!parent)
			error(ctx, "cannot resolve path \"%s\"", a->mValue.c_str());

		std::list<TreeNode *>::const_iterator it2(parent->mChildren.begin()), it2End(parent->mChildren.end());

		ctx.invocation_stack.push_back(NULL);
		for(; it2!=it2End; ++it2) {
			if ((*it2)->mName == node_name) {
				ctx.invocation_stack.back() = *it2;
				output_tag_contents(ctx, out, tag);
			}
		}
		ctx.invocation_stack.pop_back();
	} else if (tag.mName == "lina:apply") {
		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:apply> must have NAME attribute");

		std::map<std::string, TreeNode *>::const_iterator it(ctx.mpDocument->mMacros.find(a->mValue));

		if (it == ctx.mpDocument->mMacros.end())
			error(ctx, "macro \"%s\" undeclared", a->mValue.c_str());
		
		std::list<TreeNode *>::const_iterator it2(tag.mChildren.begin()), it2End(tag.mChildren.end());

		ctx.invocation_stack.push_back(NULL);
		for(; it2!=it2End; ++it2) {
			if (!(*it2)->mbIsText) {
				ctx.invocation_stack.back() = *it2;
				output_tag_contents(ctx, out, *(*it).second);
			}
		}
		ctx.invocation_stack.pop_back();
	} else if (tag.mName == "lina:if-present") {
		if (ctx.invocation_stack.empty())
			error(ctx, "<lina:if-present> can only be used during macro expansion");
		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:if-present> must have NAME attribute");

		const TreeNode *t = ctx.find_tag(a->mValue);
		if (t)
			output_tag_contents(ctx, out, tag);
	} else if (tag.mName == "lina:if-not-present") {
		if (ctx.invocation_stack.empty())
			error(ctx, "<lina:if-not-present> can only be used during macro expansion");
		const TreeAttribute *a = tag.Attrib("name");
		if (!a)
			error(ctx, "<lina:if-not-present> must have NAME attribute");

		const TreeNode *t = ctx.find_tag(a->mValue);
		if (!t)
			output_tag_contents(ctx, out, tag);
	} else if (tag.mName == "lina:pre") {
		++ctx.pre_count;
		++ctx.cdata_count;
		if (!out)
			output_standard_tag(ctx, out, tag);
		else {
			output_tag_contents(ctx, out, tag);
		}
		--ctx.cdata_count;
		--ctx.pre_count;
	} else if (tag.mName == "lina:cdata") {
		++ctx.cdata_count;
		if (!out)
			output_standard_tag(ctx, out, tag);
		else
			output_tag_contents(ctx, out, tag);
		--ctx.cdata_count;
	} else if (tag.mName == "lina:delay") {
		std::list<TreeNode *>::const_iterator it(tag.mChildren.begin()), itEnd(tag.mChildren.end());
		for(; it!=itEnd; ++it) {
			output_standard_tag(ctx, out, **it);
		}
	} else if (tag.mName == "lina:dump-stack") {
		dump_stack(ctx);
	} else if (tag.mName == "lina:replace") {
		const TreeAttribute *a = tag.Attrib("from");
		if (!a || a->mbNoValue)
			error(ctx, "<lina:replace> must have FROM attribute");
		const TreeAttribute *a2 = tag.Attrib("to");
		if (!a2 || a2->mbNoValue)
			error(ctx, "<lina:replace> must have TO attribute");

		const std::string& x = a->mValue;
		const std::string& y = a2->mValue;

		std::string s, t;
		std::string::size_type i = 0;

		output_tag_contents(ctx, &s, tag);

		for(;;) {
			std::string::size_type j = s.find(x, i);
			if (j != i)
				t.append(s, i, j-i);
			if (j == std::string::npos)
				break;
			t.append(y);
			i = j + x.size();
		}

		TreeNode *new_tag = ctx.mpDocument->AllocNode();

		new_tag->mpLocation = tag.mpLocation;
		new_tag->mLineno = tag.mLineno;
		new_tag->mbIsText = true;
		new_tag->mbIsControl = false;
		new_tag->mName = t;

		output_tag(ctx, out, *new_tag);
	} else if (tag.mName == "lina:set-option") {
		const TreeAttribute *a_name = tag.Attrib("name");
		if (!a_name)
			error(ctx, "<lina:set-option> must have NAME attribute");

		if (a_name->mValue == "link-truncate") {
			const TreeAttribute *a_val = tag.Attrib("baseurl");
			if (!a_val || a_val->mbNoValue)
				error(ctx, "option \"link-truncate\" requires BASEURL attribute");

			bool bTruncate = !tag.Attrib("notruncate");

			g_truncateURLs.push_back(std::make_pair(a_val->mValue, bTruncate));
		} else if (a_name->mValue == "output-dir") {
			const TreeAttribute *a_val = tag.Attrib("target");
			if (!a_val || a_val->mbNoValue)
				error(ctx, "option \"output-dir\" requires TARGET attribute");

			g_outputDir = a_val->mValue;
		} else if (a_name->mValue == "tag-info") {
			const TreeAttribute *a_tagname = tag.Attrib("tag");
			if (!a_tagname || a_tagname->mbNoValue)
				error(ctx, "option \"tag-info\" requires TAG attribute");

			const TreeAttribute *a_cdata = tag.Attrib("cdata");

			if (!a_cdata || a_cdata->mbNoValue)
				error(ctx, "option \"tag-info\" requires CDATA attribute");

			TreeNode::SetSupportsCDATA(a_tagname->mValue, is_true(a_cdata->mValue));
		} else
			error(ctx, "option \"%s\" unknown\n", a_name->mValue.c_str());

	} else if (tag.mName == "lina:data") {
		// do nothing
	} else if (tag.mName == "lina:source") {
		if (out) {
			std::list<TreeNode *>::const_iterator itBegin(tag.mChildren.begin()), it(itBegin), itEnd(tag.mChildren.end());
			for(; it!=itEnd; ++it) {
				output_source_tags(ctx, out, **it);
			}
		}
	} else if (tag.mName == "lina:htmlhelp-toc") {
		const TreeAttribute *a_val = tag.Attrib("file");
		if (!a_val || a_val->mbNoValue)
			error(ctx, "<lina:htmlhelp-toc> requires FILE attribute");

		const std::string filename(create_output_filename(a_val->mValue));

		// build new tag with TOC contents
		ctx.construction_stack.push_back(ctx.mpDocument->AllocNode());
		TreeNode *new_tag = ctx.construction_stack.back();

		new_tag->mpLocation = tag.mpLocation;
		new_tag->mLineno = tag.mLineno;
		new_tag->mName = a_val->mValue;
		new_tag->mbIsText = false;
		new_tag->mbIsControl = false;

		output_tag_contents(ctx, NULL, tag);

		ctx.construction_stack.pop_back();
		output_tag(ctx, out, *new_tag);

		FILE *f = fopen(filename.c_str(), "wb");
		if (!f)
			error(ctx, "couldn't create htmlhelp toc \"%s\"", a_val->mValue.c_str());
		output_toc(f, *new_tag);
		fclose(f);

	} else if (tag.mName == "lina:htmlhelp-project") {
		const TreeAttribute *file_val = tag.Attrib("file");
		if (!file_val || file_val->mbNoValue)
			error(ctx, "<lina:htmlhelp-project> requires FILE attribute");

		const TreeAttribute *output_val = tag.Attrib("output");
		if (!output_val || output_val->mbNoValue)
			error(ctx, "<lina:htmlhelp-project> requires OUTPUT attribute");

		const TreeAttribute *toc_val = tag.Attrib("toc");
		if (!toc_val || toc_val->mbNoValue)
			error(ctx, "<lina:htmlhelp-project> requires TOC attribute");

		const TreeAttribute *title_val = tag.Attrib("title");
		if (!title_val || title_val->mbNoValue)
			error(ctx, "<lina:htmlhelp-project> requires TITLE attribute");

		const std::string filename(create_output_filename(file_val->mValue));

		FILE *f = fopen(filename.c_str(), "wb");
		if (!f)
			error(ctx, "couldn't create htmlhelp project \"%s\"", file_val->mValue.c_str());
		fprintf(f,
			"[OPTIONS]\n"
			"Auto Index=Yes\n"
			"Compatibility=1.1 or later\n"
			"Compiled file=%s\n"
			"Contents file=%s\n"
			"Default topic=index.html\n"
			"Display compile progress=no\n"
			"Full-text search=Yes\n"
			, output_val->mValue.c_str()
			, toc_val->mValue.c_str()
			);


		const TreeAttribute *fullstop_val = tag.Attrib("fullstop");
		if (fullstop_val && !fullstop_val->mbNoValue)
			fprintf(f, "Full text search stop list file=%s\n", fullstop_val->mValue.c_str());

		fprintf(f,
			"Language=0x0409 English (United States)\n"
			"Title=%s\n"
			"\n"
			"[FILES]\n"
			, title_val->mValue.c_str()
			);

		std::list<std::string>::const_iterator it(g_htmlHelpFiles.begin()), itEnd(g_htmlHelpFiles.end());
		for(; it!=itEnd; ++it) {
			fprintf(f, "%s\n", (*it).c_str());
		}

		fclose(f);		
	} else if (tag.mName == "lina:htmlhelp-addfile") {
		const TreeAttribute *file_val = tag.Attrib("file");
		if (!file_val || file_val->mbNoValue)
			error(ctx, "<lina:htmlhelp-addfile> requires FILE attribute");

		g_htmlHelpFiles.push_back(file_val->mValue);
	} else {
		std::string macroName(tag.mName, 5, std::string::npos);
		std::map<std::string, TreeNode *>::const_iterator it = ctx.mpDocument->mMacros.find(macroName);

		if (it == ctx.mpDocument->mMacros.end())
			error(ctx, "macro <lina:%s> not found", macroName.c_str());

//		dump_stack(ctx);
//		printf("executing macro: %s (%s:%d)\n", tag.mName.c_str(), tag.mLocation->name.c_str(), tag.mLineno);

		ctx.invocation_stack.push_back(&tag);
		output_tag_contents(ctx, out, *(*it).second);
		ctx.invocation_stack.pop_back();

//		printf("exiting macro: %s (%s:%d)\n", tag.mName.c_str(), tag.mLocation->name.c_str(), tag.mLineno);
	}
}
コード例 #25
0
static TreeNode* createRandomTree( const GlobalContext* ctx, const strus::utils::Document& doc, std::size_t& docitr, unsigned int depth=0)
{
	TreeNode* rt = 0;
	if (RANDINT( 1,5-depth) == 1)
	{
		if (docitr >= doc.itemar.size()) return 0;
		rt = new TreeNode( termId( strus::utils::Token, doc.itemar[ docitr].termid));
	}
	else
	{
		unsigned int argc = ctx->randomArgc();
		unsigned int range = argc + ctx->randomRange();
		unsigned int cardinality = 0; //... it seems currently too difficult to handle other than the default cardinality in this test
		TreeNode::JoinOperation op = ctx->randomOp();
		std::vector<TreeNode*> args;
		unsigned int rangesum = 0;
		unsigned int ai;
		for (ai=0; docitr < doc.itemar.size() && ai<argc; ++ai,++docitr)
		{
			TreeNode* arg = createRandomTree( ctx, doc, docitr, depth+1);
			if (arg == 0)
			{
				TreeNode::deleteTreeAr( args);
				return 0;
			}
			args.push_back( arg);
			rangesum += arg->range();
		}
		if (argc == 1
			&& (op == strus::PatternMatcherInstanceInterface::OpSequenceStruct
				|| op == strus::PatternMatcherInstanceInterface::OpWithinStruct)
			&& args[0]->term() == termId( strus::utils::SentenceDelim, 0))
		{
			// ... add another node for a sequence of size 1, if we have a sequence of length 1 with a delimiter element only (prevent anomaly)
			TreeNode* arg = createRandomTree( ctx, doc, docitr, depth+1);
			if (arg == 0)
			{
				TreeNode::deleteTreeAr( args);
				return 0;
			}
			args.push_back( arg);
			rangesum += arg->range();
		}
		range += rangesum;
		if (ai < argc)
		{
			TreeNode::deleteTreeAr( args);
			return 0;
		}
		switch (op)
		{
			case strus::PatternMatcherInstanceInterface::OpSequence:
			case strus::PatternMatcherInstanceInterface::OpSequenceImm:
			{
				break;
			}
			case strus::PatternMatcherInstanceInterface::OpSequenceStruct:
			{
				TreeNode* delim = new TreeNode( termId( strus::utils::SentenceDelim, 0));
				args.insert( args.begin(), delim);
				++argc;
				break;
			}
			case strus::PatternMatcherInstanceInterface::OpWithin:
			{
				for (int ii=0; ii<3; ii++)
				{
					unsigned int r1 = RANDINT(0,argc);
					unsigned int r2 = RANDINT(0,argc);
					if (r1 != r2) std::swap( args[r1], args[r2]);
				}
				break;
			}
			case strus::PatternMatcherInstanceInterface::OpWithinStruct:
			{
				for (int ii=0; ii<3; ii++)
				{
					unsigned int r1 = RANDINT(0,argc);
					unsigned int r2 = RANDINT(0,argc);
					if (r1 != r2) std::swap( args[r1], args[r2]);
				}
				TreeNode* delim = new TreeNode( termId( strus::utils::SentenceDelim, 0));
				args.insert( args.begin(), delim);
				++argc;
				break;
			}
			case strus::PatternMatcherInstanceInterface::OpAny:
				cardinality = 0;
				break;
			case strus::PatternMatcherInstanceInterface::OpAnd:
				throw std::runtime_error( "operator 'And' not implemented yet");
		}
		rt = new TreeNode( op, args, range, cardinality);
	}
	if (RANDINT(1,10) == 1)
	{
		rt->attachVariable( RANDINT(1,10));
	}
	return rt;
}
コード例 #26
0
	bool insertBody(Body body) {
		//cout << "IN INSERT" << endl;
		int quad = getQuadrantOfBody(body);
		if (getState() == INTERNAL) {
			if (quad == 1) {
		//		cout << "going to quad 1" << endl;
				return _NW->insertBody(body);
			} else if (quad == 2) {
		//		cout << "going to quad 2" << endl;
				return _NE->insertBody(body);
			} else if (quad == 3) {
		//		cout << "going to quad 3" << endl;
				return _SW->insertBody(body);
			} else if (quad == 4) {
		//		cout << "going to quad 4" << endl;
				return _SE->insertBody(body);
			} else {
		//		cout << "Invalid quadrant!" << endl;
				return false;
			}
		} else {
			if (_body == NULL){
				_body = new Body(body);
			} else {
				quad = _parent->getQuadrantOfBody(body);
				if (quad == 1) {
		//			cout << "inserting in quad 1" << endl;
					TreeNode* toDelete = _parent->_NW;
					_parent->_NW = new TreeNode(_box, INTERNAL);
					_parent->_NW->setParent(_parent);
					_parent->_NW->insertBody(*_body);
					_parent->_NW->insertBody(body);
					delete toDelete;
					return true;
				} else if (quad == 2) {
		//			cout << "inserting in quad 2" << endl;
					TreeNode* toDelete = _parent->_NE;
					_parent->_NE = new TreeNode(_box, INTERNAL);
					_parent->_NE->setParent(_parent);
					_parent->_NE->insertBody(*_body);
					_parent->_NE->insertBody(body);
					delete toDelete;
					return true;
				} else if (quad == 3) {
		//			cout << "inserting in quad 3" << endl;
					TreeNode* toDelete = _parent->_SW;
					_parent->_SW = new TreeNode(_box, INTERNAL);
					_parent->_SW->setParent(_parent);
					_parent->_SW->insertBody(*_body);
					_parent->_SW->insertBody(body);
					delete toDelete;
					return true;
				} else if (quad == 4) {
		//			cout << "inserting in quad 4" << endl;
					TreeNode* toDelete = _parent->_SE;
					_parent->_SE = new TreeNode(_box, INTERNAL);
					_parent->_SE->setParent(_parent);
					_parent->_SE->insertBody(*_body);
					_parent->_SE->insertBody(body);
					delete toDelete;
					return true;
				} else {
		//			cout << "Invalid quadrant!" << endl;
					return false;
				}
			}
		}

//			updateCenterOfMass(body);
	//	cout << "LEAVING INSERT" << endl;
	}
コード例 #27
0
int main( int argc, char* argv[] )
{
	using namespace ds;
	Tree tree;

	ds::TextReader textReader("D:\\cpp_practise\\test_cases\\tree_test.txt");
    textReader();

	//populating linkedList
    std::vector<std::string> strVec = textReader.strVec();

	for (std::vector<std::string>::iterator strIt = strVec.begin(); strIt != strVec.end(); ++strIt)
    {
        tree.insert(*strIt);
    }
	//testing iterative search function
	bool found_1 = tree.search("one") != NULL;
	//testing recursive search function
	bool found_2 = tree.search(tree.root(),"these");
	
	//in-order traversal
	LinkedList inOrderList;
	tree.inOrderTraversal(tree.root(), inOrderList);

	std::cout << "\n in-order traversal: \n";
	Node* curNode = inOrderList.head();
	while(curNode)
	{
		std::cout << curNode->item() << " ";
		curNode = curNode->next();
	}
	std::cout << std::endl;
	//END of in-order traversal

	TreeNode* successorNode = tree.successor(tree.search("is"));
	std::cout << "successor node: ";
	if (successorNode)
	{
		std::cout << successorNode->item() << std::endl;
	}

	tree.remove(tree.search("was")); //test case: deleting an element which doesn't exist in the tree
	
	//test case: node to be deleted has only left child
	//e.g. node to be deleted: "used", node to be tested: "that"

	//test case: node to be deleted has both child. node's successor is its right child.
	//e.g. node to be deleted: "one", node to be tested: "that"

	//test case: node to be deleted has both child. node's successor is its right child's descendant.
	//e.g. node to be deleted: "introduces", node to be tested: "further" "is"
	tree.remove(tree.search("introduces"));
	TreeNode* testNode0 = tree.search("is");
	std::cout << "parent: ";
	if (testNode0->parent())
	{
		std::cout << (testNode0->parent())->item();
	}
	std::cout << std::endl;
	std::cout << "left child: ";
	if (testNode0->left())
	{
		std::cout << (testNode0->left())->item();
		std::cout << " :: left child's parent: ";
		if ((testNode0->left())->parent())
		{
			std::cout << ((testNode0->left())->parent())->item();
		}
	}
	std::cout << std::endl;

	if (testNode0->right())
	{
		std::cout << "right child: " << (testNode0->right())->item();
		std::cout << " :: right child's parent: ";
		if ((testNode0->right())->parent())
		{
			std::cout << ((testNode0->right())->parent())->item();
		}
	}
	std::cout << std::endl;

	//testing char to int conversion
	//int gh = '\r';

	return 0;
}
コード例 #28
0
	void insertBody(Body body) {
		root->insertBody(body);
		double dummy;
		Vec2D dummy2;
		root->updateCenterOfMass(dummy, dummy2);
	}
コード例 #29
0
double TreeDustGridStructure::density(int h, int m) const
{
    TreeNode* node = getnode(m);
    return _dmib->massInBox(h, node->extent()) / node->volume();
}
コード例 #30
0
Monitor::TreeNode*
Monitor::MonitorDataStorage::getNode(
  const std::string&           label,
  const OpenDDS::DCPS::GUID_t& parentId,
  const OpenDDS::DCPS::GUID_t& id,
  bool&                        create
)
{
  TreeNode* node   = 0;
  GuidToTreeMap::iterator location = this->guidToTreeMap_.find( id);
  if( location == this->guidToTreeMap_.end()) {
    // We are done if not creating a new node.
    if( !create) return 0;

    // We need to add a new DomainParticipant.

    // Find the parent node, if any.  It is ok to not have a parent node
    // for cases of out-of-order udpates.  We handle that as the updates
    // are actually processed.
    TreeNode* parent = 0;
    GuidToTreeMap::iterator parentLocation
      = this->guidToTreeMap_.find( parentId);
    if( parentLocation != this->guidToTreeMap_.end()) {
      parent = parentLocation->second.second;
    }

    // Node data.
    OpenDDS::DCPS::GuidConverter converter( id);
    QList<QVariant> list;
    list << QString( QObject::tr( label.c_str()))
         << QString( QObject::tr( std::string( converter).c_str()));
    node = new TreeNode( list, parent);
    if( parent) {
      parent->append( node);
    }

    // Install the new node.
    this->guidToTreeMap_[ id] = std::make_pair( node->row(), node);

  } else {
    node = location->second.second;
    create = false;
  }

  // If there have been some out-of-order reports, we may have been
  // created without a parent node.  We can now fill in that information
  // if we can.  If we created the node, we already know it has a
  // parent so this will be bypassed.
  if( !node->parent()) {
    // Need to search for the parent.
    TreeNode* parent = 0;
    GuidToTreeMap::iterator parentLocation
      = this->guidToTreeMap_.find( parentId);
    if( parentLocation != this->guidToTreeMap_.end()) {
      parent = parentLocation->second.second;
    }

    // And install anything that is found.
    node->parent() = parent;
  }

  return node;
}