bool ComplexXMLWithMixedElementsAndNodesWithoutAttributes() { // Children lists for a and b elements nodeList la = nodeList(); nodeList lc = nodeList(); Node* b = new TextNode(string("Blorg1")); Node* d = new TextNode(string("Blorg2")); Node* e = new TextNode(string("Blorg3")); la.push_back(b); lc.push_back(d); ElementName ena = ElementName(string("xml"), string("xml")); ElementName enc = ElementName(string("yoyo"), string("yoyo")); Node* c = Element::createElement(&enc, NULL, &lc); la.push_back(c); la.push_back(e); Node* a = Element::createElement(&ena, NULL, &la); string expected = "<xml>\nBlorg1\n<yoyo>\nBlorg2\n</yoyo>\nBlorg3\n</xml>"; string result = a->toXML(); if (result != expected) { fail("ComplexXMLWithMixedElementsAndNodesWithoutAttributes (to_xml)", "toXML did not answer expected result." << std::endl << "Expected : " << std::endl << expected << std::endl << "Got: " << std::endl << result << std::endl) } delete a; delete b; delete c; delete d; return true; }
void DisplayNodeVisitor::visitor(Root* root) { stringstream ss; int depth = 1; string blank(depth * 2, ' '); //計算深度的空白數量 int indexDepth = 0; ss << "+-" << root->getDescription() << "(" << root->getType() << "," << "ID:" << root->getId() << ")" << endl; //印出節點內容 list<Component*> nodeList(root->getNodeList()); for (list<Component *>::iterator it = nodeList.begin(); it != nodeList.end(); ++it) { for (indexDepth = 0; indexDepth < depth; indexDepth++) //print 前置空白 { Component* parent = (*it); for (int i = 0; i < depth - indexDepth; i++) { parent = parent->getParent(); } if (indexDepth >= 1 && parent->haveSibling()) // not root && have sibling ss << "| "; else ss << " "; //two sapce } ss << (**it).getMap(depth + 1).str(); } cout << ss.str(); }
void MSTableColumnGroup::print(ostream &os_,unsigned level_) const { unsigned i; for (i=0; i<level_; i++) os_<<'\t'; os_<<"(GROUP) "; if (heading().length()==0) os_<<endl; else os_<<heading(); for (unsigned j=0; j<nodeList().length(); j++) { const Node &node=nodeList()[j]; if (node.type()==Node::Group) node.group()->print(os_,level_+1); else if (node.type()==Node::Column) { for (i=0; i<=level_; i++) os_<<'\t'; os_<<node.column()->heading(); } } }
/*** To find a cluster we repeatedly insert nodes into the bfNetwork and try to distribute the weight * of incident edges. If not all weight can be distributed, then a cluster is found. In this case, * create a new cluster, and add all nodes that are labeled in the bfNetwork. */ WCConstraintCluster* WCConstraintPlanner::FindCluster(const WPUInt &dConst) { //Copy the node list std::list<WCConstraintNode*> nodeList(this->_nodeList); WCConstraintCluster* newCluster = NULL; std::list<WCConstraintNode*>::iterator iter; WCConstraintNode* node; int retVal; //Convert the D geometric constant into the K constant int kConst = -1 * (dConst + 1); //Reset and sort the node list this->ResetMarks(nodeList); //Get a reference to the first node to be added into gPrime node = nodeList.front(); nodeList.pop_front(); //Mark all of this node's neighbors node->MarkNeighbors(); nodeList.sort(WCConstraintNode::MarkSort); //Create a new bipartite flow network if (this->_network != NULL) delete this->_network; this->_network = new WCBipartiteFlowNetwork(); //Add in the first node CLOGGER_INFO(WCLogManager::RootLogger(), "WCConstraintPlanner::FindCluster - Adding Node:" << node); this->_network->AddVertexNode(node, node->Weight()); //Go through the rest of the nodes until a node has an edge that can't be distributed while (nodeList.size() > 0) { //Get a reference to the next node to be added into gPrime node = nodeList.front(); CLOGGER_INFO(WCLogManager::RootLogger(), "WCConstraintPlanner::FindCluster - Adding Node:" << node); //Try to distribute the edges, if not we are done retVal = node->DistributeEdges(this->_network, kConst); if (retVal > 0) { CLOGGER_DEBUG(WCLogManager::RootLogger(), "Dense subgraph found...creating cluster...") //Create the new cluster from the labeled vertices in the bipartite flow network newCluster = new WCConstraintCluster( this->_network->LabeledVertices(), dConst); //Check to make sure that the new cluster is valid if (!newCluster->IsValidCluster()) { CLOGGER_ERROR(WCLogManager::RootLogger(), "CConstraintPlanner::FindCluster - Invalid cluster found."); //Make sure to delete invalid clusters delete newCluster; return NULL; } return newCluster; } nodeList.pop_front(); //Mark all of this node's neighbors node->MarkNeighbors(); //Sort and reverse the list nodeList.sort(WCConstraintNode::MarkSort); } //No cluster found...graph must be under constrained... CLOGGER_INFO(WCLogManager::RootLogger(), "CConstraintPlanner::FindCluster - No cluster found. Graph underconstrained"); return NULL; }
MSBoolean MSTableColumnGroup::depthFirstNodeIteration(ConstIterator &iterator_, ColumnGroupList &groupList_) const { groupList_<<this; unsigned len=nodeList().length(); for (unsigned i=0; i<len; i++) { const Node &node=nodeList()[i]; if (node.type()==Node::Column) { if (iterator_.applyTo(node.column(),groupList_)==MSFalse) return MSFalse; } else if (node.type()==Node::Group) { if (node.group()->depthFirstNodeIteration(iterator_,groupList_)==MSFalse) return MSFalse; } } MSBoolean ret=iterator_.applyTo(*this,groupList_); groupList_.removeAt(groupList_.length()-1); return ret; }
bool ComplexXMLWithMixedElementsAndNodesWithAttributes() { // Children lists for a and b elements nodeList la = nodeList(); nodeList lc = nodeList(); Node* b = new TextNode(string("Blorg1")); Node* d = new TextNode(string("Blorg2")); Node* e = new TextNode(string("Blorg3")); la.push_back(b); lc.push_back(d); attributesMap attrMapa, attrMapc; //* Recall: The attributes will be output in alphabetical order, not in the order of addition to the attributesMap attrMapa["blorg1"] = "blurp"; attrMapa["huhu"] = "haha"; attrMapc["numeric"] = "42"; attrMapc["vulgar"] = "Hey, you touch my tralala."; attrMapc["type"] = "xml"; ElementName ena = ElementName(string("blorg"), string("xml")); ElementName enc = ElementName(string("blorg"), string("yoyo")); Node* c = Element::createElement(&enc, &attrMapc, &lc); la.push_back(c); la.push_back(e); Node* a = Element::createElement(&ena, &attrMapa, &la); string expected = "<xml blorg1=\"blurp\" huhu=\"haha\">\nBlorg1\n<yoyo numeric=\"42\" type=\"xml\" vulgar=\"Hey, you touch my tralala.\">\nBlorg2\n</yoyo>\nBlorg3\n</xml>"; string result = a->toXML(); if (result != expected) { fail("ComplexXMLWithMixedElementsAndNodesWithoutAttributes (to_xml)", "toXML did not answer expected result." << std::endl << "\n------------------------\nExpected : " << std::endl << expected << std::endl << "------------------------\nGot: " << std::endl << result << std::endl) } delete a; delete b; delete c; delete d; return true; }
MSBoolean MSTableColumnGroup::isOkToAdd(MSTableColumn *column_) { if (column_!=0) { if (column_->table()==table()) { unsigned len=nodeList().length(); for (unsigned i=0; i<len; i++) { Node &node=nodeList()[i]; if (node.type()==Node::Column) { if (column_==node.column()) { MSMessageLog::warningMessage("Warning: MSTableColumnGroup - Column already exists, append fails"); return MSFalse; } } else if (node.type()==Node::Group) { if (node.group()->isOkToAdd(column_)==MSFalse) return MSFalse; } } return MSTrue; } else { MSMessageLog::warningMessage("Warning: MSTableColumnGroup - Try to append column from a different table, append fails"); return MSFalse; } } else { MSMessageLog::warningMessage("Warning: MSTableColumnGroup - Null column pointer, append fails"); return MSFalse; } }
bool simpleToXMLWithoutAttributes() { nodeList l = nodeList(); Node* b = new TextNode(string("Blorg")); l.push_back(b); ElementName en = ElementName(string("xml"), string("xml")); Node* a = Element::createElement(&en, NULL, &l); string expected = "<xml>\nBlorg\n</xml>"; string result = a->toXML(); if (result != expected) { fail("simpleToXMLWithoutAttributes (to_xml)", "toXML did not answer expected result." << std::endl << "Expected : " << std::endl << expected << std::endl << "Got: " << std::endl << result << std::endl) } delete b; delete a; return true; }
bool simpleToXMLWithAttributes() { nodeList l = nodeList(); Node* b = new TextNode(string("Blorg")); l.push_back(b); ElementName en = ElementName(string("xml"), string("xml")); attributesMap attrMap; attrMap["blorg1"] = "blurp"; attrMap["huhu"] = "haha"; attrMap["numeric"] = "42"; Node* a = Element::createElement(&en, &attrMap, &l); string expected = "<xml blorg1=\"blurp\" huhu=\"haha\" numeric=\"42\">\nBlorg\n</xml>"; string result = a->toXML(); if (result != expected) { fail("simpleToXMLWithAttributes (to_xml)", "toXML did not answer expected result." << std::endl << "Expected : " << std::endl << expected << std::endl << "Got: " << std::endl << result << std::endl) } delete b; delete a; return true; }
QgsRasterCalculator::Result QgsRasterCalculator::processCalculationGPU( std::unique_ptr< QgsRasterCalcNode > calcNode, QgsFeedback *feedback ) { QString cExpression( calcNode->toString( true ) ); QList<const QgsRasterCalcNode *> nodeList( calcNode->findNodes( QgsRasterCalcNode::Type::tRasterRef ) ); QSet<QString> capturedTexts; for ( const auto &r : qgis::as_const( nodeList ) ) { QString s( r->toString().remove( 0, 1 ) ); s.chop( 1 ); capturedTexts.insert( s ); } // Extract all references struct LayerRef { QString name; int band; QgsRasterLayer *layer = nullptr; QString varName; QString typeName; size_t index; size_t bufferSize; size_t dataSize; }; // Collects all layers, band, name, varName and size information std::vector<LayerRef> inputRefs; size_t refCounter = 0; for ( const auto &r : capturedTexts ) { if ( r.startsWith( '"' ) ) continue; QStringList parts( r.split( '@' ) ); if ( parts.count() != 2 ) continue; bool ok = false; LayerRef entry; entry.name = r; entry.band = parts[1].toInt( &ok ); for ( const auto &ref : mRasterEntries ) { if ( ref.ref == entry.name ) entry.layer = ref.raster; } if ( !( entry.layer && entry.layer->dataProvider() && ok ) ) continue; entry.dataSize = entry.layer->dataProvider()->dataTypeSize( entry.band ); switch ( entry.layer->dataProvider()->dataType( entry.band ) ) { case Qgis::DataType::Byte: entry.typeName = QStringLiteral( "unsigned char" ); break; case Qgis::DataType::UInt16: entry.typeName = QStringLiteral( "unsigned int" ); break; case Qgis::DataType::Int16: entry.typeName = QStringLiteral( "short" ); break; case Qgis::DataType::UInt32: entry.typeName = QStringLiteral( "unsigned int" ); break; case Qgis::DataType::Int32: entry.typeName = QStringLiteral( "int" ); break; case Qgis::DataType::Float32: entry.typeName = QStringLiteral( "float" ); break; // FIXME: not sure all OpenCL implementations support double // maybe safer to fall back to the CPU implementation // after a compatibility check case Qgis::DataType::Float64: entry.typeName = QStringLiteral( "double" ); break; default: return BandError; } entry.bufferSize = entry.dataSize * mNumOutputColumns; entry.index = refCounter; entry.varName = QStringLiteral( "input_raster_%1_band_%2" ) .arg( refCounter++ ) .arg( entry.band ); inputRefs.push_back( entry ); } // Prepare context and queue cl::Context ctx( QgsOpenClUtils::context() ); cl::CommandQueue queue( QgsOpenClUtils::commandQueue() ); // Create the C expression std::vector<cl::Buffer> inputBuffers; inputBuffers.reserve( inputRefs.size() ); QStringList inputArgs; for ( const auto &ref : inputRefs ) { cExpression.replace( QStringLiteral( "\"%1\"" ).arg( ref.name ), QStringLiteral( "%1[i]" ).arg( ref.varName ) ); inputArgs.append( QStringLiteral( "__global %1 *%2" ) .arg( ref.typeName ) .arg( ref.varName ) ); inputBuffers.push_back( cl::Buffer( ctx, CL_MEM_READ_ONLY, ref.bufferSize, nullptr, nullptr ) ); } //qDebug() << cExpression; // Create the program QString programTemplate( R"CL( // Inputs: ##INPUT_DESC## // Expression: ##EXPRESSION_ORIGINAL## __kernel void rasterCalculator( ##INPUT## __global float *resultLine ) { // Get the index of the current element const int i = get_global_id(0); // Expression resultLine[i] = ##EXPRESSION##; } )CL" ); QStringList inputDesc; for ( const auto &ref : inputRefs ) { inputDesc.append( QStringLiteral( " // %1 = %2" ).arg( ref.varName ).arg( ref.name ) ); } programTemplate = programTemplate.replace( QStringLiteral( "##INPUT_DESC##" ), inputDesc.join( '\n' ) ); programTemplate = programTemplate.replace( QStringLiteral( "##INPUT##" ), inputArgs.length() ? ( inputArgs.join( ',' ).append( ',' ) ) : QChar( ' ' ) ); programTemplate = programTemplate.replace( QStringLiteral( "##EXPRESSION##" ), cExpression ); programTemplate = programTemplate.replace( QStringLiteral( "##EXPRESSION_ORIGINAL##" ), calcNode->toString( ) ); // qDebug() << programTemplate; // Create a program from the kernel source cl::Program program( QgsOpenClUtils::buildProgram( programTemplate, QgsOpenClUtils::ExceptionBehavior::Throw ) ); // Create the buffers, output is float32 (4 bytes) // We assume size of float = 4 because that's the size used by OpenCL and IEEE 754 Q_ASSERT( sizeof( float ) == 4 ); std::size_t resultBufferSize( 4 * static_cast<size_t>( mNumOutputColumns ) ); cl::Buffer resultLineBuffer( ctx, CL_MEM_WRITE_ONLY, resultBufferSize, nullptr, nullptr ); auto kernel = cl::Kernel( program, "rasterCalculator" ); for ( unsigned int i = 0; i < inputBuffers.size() ; i++ ) { kernel.setArg( i, inputBuffers.at( i ) ); } kernel.setArg( static_cast<unsigned int>( inputBuffers.size() ), resultLineBuffer ); QgsOpenClUtils::CPLAllocator<float> resultLine( static_cast<size_t>( mNumOutputColumns ) ); //open output dataset for writing GDALDriverH outputDriver = openOutputDriver(); if ( !outputDriver ) { mLastError = QObject::tr( "Could not obtain driver for %1" ).arg( mOutputFormat ); return CreateOutputError; } gdal::dataset_unique_ptr outputDataset( openOutputFile( outputDriver ) ); if ( !outputDataset ) { mLastError = QObject::tr( "Could not create output %1" ).arg( mOutputFile ); return CreateOutputError; } GDALSetProjection( outputDataset.get(), mOutputCrs.toWkt().toLocal8Bit().data() ); GDALRasterBandH outputRasterBand = GDALGetRasterBand( outputDataset.get(), 1 ); if ( !outputRasterBand ) return BandError; // Input block (buffer) std::unique_ptr<QgsRasterBlock> block; // Run kernel on all scanlines auto rowHeight = mOutputRectangle.height() / mNumOutputRows; for ( int line = 0; line < mNumOutputRows; line++ ) { if ( feedback && feedback->isCanceled() ) { break; } if ( feedback ) { feedback->setProgress( 100.0 * static_cast< double >( line ) / mNumOutputRows ); } // Read lines from rasters into the buffers for ( const auto &ref : inputRefs ) { // Read one row QgsRectangle rect( mOutputRectangle ); rect.setYMaximum( rect.yMaximum() - rowHeight * line ); rect.setYMinimum( rect.yMaximum() - rowHeight ); // TODO: check if this is too slow // if crs transform needed if ( ref.layer->crs() != mOutputCrs ) { QgsRasterProjector proj; proj.setCrs( ref.layer->crs(), mOutputCrs ); proj.setInput( ref.layer->dataProvider() ); proj.setPrecision( QgsRasterProjector::Exact ); block.reset( proj.block( ref.band, rect, mNumOutputColumns, 1 ) ); } else { block.reset( ref.layer->dataProvider()->block( ref.band, rect, mNumOutputColumns, 1 ) ); } //for ( int i = 0; i < mNumOutputColumns; i++ ) // qDebug() << "Input: " << line << i << ref.varName << " = " << block->value( 0, i ); //qDebug() << "Writing buffer " << ref.index; Q_ASSERT( ref.bufferSize == static_cast<size_t>( block->data().size( ) ) ); queue.enqueueWriteBuffer( inputBuffers[ref.index], CL_TRUE, 0, ref.bufferSize, block->bits() ); } // Run the kernel queue.enqueueNDRangeKernel( kernel, 0, cl::NDRange( mNumOutputColumns ) ); // Write the result queue.enqueueReadBuffer( resultLineBuffer, CL_TRUE, 0, resultBufferSize, resultLine.get() ); //for ( int i = 0; i < mNumOutputColumns; i++ ) // qDebug() << "Output: " << line << i << " = " << resultLine[i]; if ( GDALRasterIO( outputRasterBand, GF_Write, 0, line, mNumOutputColumns, 1, resultLine.get(), mNumOutputColumns, 1, GDT_Float32, 0, 0 ) != CE_None ) { return CreateOutputError; } } if ( feedback && feedback->isCanceled() ) { //delete the dataset without closing (because it is faster) gdal::fast_delete_and_close( outputDataset, outputDriver, mOutputFile ); return Canceled; } inputBuffers.clear(); return Success; }
void ProcessDetectSurf::Process() { if (m_mesh->m_expDim > 2) { cerr << "Surface detection only implemented for 2D meshes" << endl; return; } int i, j; string surf = m_config["vol"].as<string>(); // Obtain vector of surface IDs from string. vector<unsigned int> surfs; if (surf != "-1") { ParseUtils::GenerateSeqVector(surf.c_str(), surfs); sort(surfs.begin(), surfs.end()); } // If we're running in verbose mode print out a list of surfaces. if (m_mesh->m_verbose) { cout << "ProcessDetectSurf: detecting surfaces"; if (surfs.size() > 0) { cout << " for surface" << (surfs.size() == 1 ? "" : "s") << " " << surf << endl; } } vector<ElementSharedPtr> &el = m_mesh->m_element[m_mesh->m_expDim]; map<int, EdgeInfo> edgeCount; set<int> doneIds; map<int, int> idMap; // Iterate over list of surface elements. for (i = 0; i < el.size(); ++i) { // Work out whether this lies on our surface of interest. if (surfs.size() > 0) { vector<int> inter, tags = el[i]->GetTagList(); sort(tags.begin(), tags.end()); set_intersection(surfs.begin(), surfs.end(), tags .begin(), tags .end(), back_inserter(inter)); // It doesn't continue to next element. if (inter.size() != 1) { continue; } } // List all edges. ElementSharedPtr elmt = el[i]; for (j = 0; j < elmt->GetEdgeCount(); ++j) { EdgeSharedPtr e = elmt->GetEdge(j); int eId = e->m_id; edgeCount[eId].count++; edgeCount[eId].edge = e; } doneIds.insert(elmt->GetId()); ASSERTL0(idMap.count(elmt->GetId()) == 0, "Shouldn't happen"); idMap[elmt->GetId()] = i; } CompositeMap::iterator cIt; unsigned int maxId = 0; for (cIt = m_mesh->m_composite.begin(); cIt != m_mesh->m_composite.end(); ++cIt) { maxId = std::max(cIt->first, maxId); } ++maxId; map<int, EdgeInfo>::iterator eIt; while (doneIds.size() > 0) { ElementSharedPtr start = m_mesh->m_element[m_mesh->m_expDim][idMap[*(doneIds.begin())]]; vector<ElementSharedPtr> block; FindContiguousSurface(start, doneIds, block); ASSERTL0(block.size() > 0, "Contiguous block not found"); // Loop over all edges in block. for (i = 0; i < block.size(); ++i) { // Find edge info. ElementSharedPtr elmt = block[i]; for (j = 0; j < elmt->GetEdgeCount(); ++j) { eIt = edgeCount.find(elmt->GetEdge(j)->m_id); ASSERTL0(eIt != edgeCount.end(), "Couldn't find edge"); eIt->second.group = maxId; } } ++maxId; } for (eIt = edgeCount.begin(); eIt != edgeCount.end(); ++eIt) { if (eIt->second.count > 1) { continue; } unsigned int compId = eIt->second.group; CompositeMap::iterator cIt = m_mesh->m_composite.find(compId); if (cIt == m_mesh->m_composite.end()) { CompositeSharedPtr comp(new Composite()); comp->m_id = compId; comp->m_tag = "E"; cIt = m_mesh->m_composite.insert(std::make_pair(compId, comp)).first; } vector<int> tags(1); tags[0] = compId; vector<NodeSharedPtr> nodeList(2); nodeList[0] = eIt->second.edge->m_n1; nodeList[1] = eIt->second.edge->m_n2; ElmtConfig conf(LibUtilities::eSegment, 1, false, false); ElementSharedPtr elmt = GetElementFactory(). CreateInstance(LibUtilities::eSegment,conf,nodeList,tags); elmt->SetEdgeLink(eIt->second.edge); cIt->second->m_items.push_back(elmt); } }
bool testDocumentToXML() { Node* p_text = new TextNode(string("Comme l'écriture d'un compilateur est une tâche fort complexe, le programmateur a tout intérêt à travailler.")); Node* titre_text = new TextNode(string("Réalisation d'un compilateur")); Node* resume_text = new TextNode(string("Ceci est extrait du livre \"Réaliser un compilateur : les outils Lex et Yacc\" de Nino Silverio.")); nodeList p_children = nodeList(); nodeList titre_children = nodeList(); nodeList resume_children = nodeList(); nodeList section_children = nodeList(); nodeList chapitre_children = nodeList(); nodeList rapport_children = nodeList(); ElementName titre = ElementName(string(""), string("titre")); ElementName p = ElementName(string("p"), string("p")); ElementName section = ElementName(string("section"), string("section")); ElementName chapitre = ElementName(string("chapitre"), string("resume")); ElementName resume = ElementName(string("resume"), string("chapitre")); ElementName rapport = ElementName(string("rapport"), string("rapport")); p_children.push_back(p_text); Node* p_elem = Element::createElement(&p, NULL, &p_children); titre_children.push_back(titre_text); Node* titre_elem = Element::createElement(&titre, NULL, &titre_children); section_children.push_back(titre_elem); section_children.push_back(p_elem); Node* section_elem = Element::createElement(§ion, NULL, §ion_children); chapitre_children.push_back(section_elem); Node* chapitre_elem = Element::createElement(&chapitre, NULL, &chapitre_children); resume_children.push_back(resume_text); Node* resume_elem = Element::createElement(&resume, NULL, &resume_children); rapport_children.push_back(resume_elem); rapport_children.push_back(chapitre_elem); Node* rapport_elem = Element::createElement(&rapport, NULL, &rapport_children); string line; string text = ""; ifstream xmlfile; const char * filename = "../../tests/testfile1.xml"; xmlfile.open(filename, ios::in); if(xmlfile.is_open()) { while (getline (xmlfile,line)){ //getline (xmlfile,myline,'\t'); text+=line; } } else { fail("testDocumentToXML", "Failed to open xml file in ifstream"); } //having problems with encoding, i will write outputs to a file ofstream outfile; outfile.open("../../tests/output.txt", ios::trunc); if (outfile.is_open()){ outfile<<rapport_elem->toXML(); } else { fail("testDocumentToXML", "Failed to write output file"); } // // if (result != expected) { // fail("simpleToXMLWithAttributes (to_xml)", "toXML did not answer expected result." << std::endl // << "Expected : " << std::endl << expected << std::endl // << "Got: " << std::endl << result << std::endl) // } // // delete b; // delete a; xmlfile.close(); outfile.close(); return true; }