bool SimpleAlias() { std::string input = "- &alias test\n- *alias"; std::stringstream stream(input); YAML::Parser parser(stream); YAML::Node doc; parser.GetNextDocument(doc); std::string output; doc[0] >> output; if(output != "test") return false; doc[1] >> output; if(output != "test") return false; if(doc.size() != 2) return false; return true; }
// Test conversion to and from yaml node TYPED_TEST(AllMatrixTests, YamlConvert) { typedef typename TestFixture::Matrix Matrix; typedef typename TestFixture::Scalar T; // This array has more elements than we will need. // The element type must match the matrix! const T inputArray[18] = { 0.01f, 1.02f, 2.03f, 3.04f, 4.05f, 5.06f, 6.07f, 7.08f, 8.09f, 9.10f, 10.11f, 11.12f, 12.13f, 13.14f, 14.15f, 15.16f, 16.17f, 17.18f }; Matrix matrix(inputArray); YAML::Node node; ASSERT_NO_THROW(node = matrix); EXPECT_TRUE(node.IsSequence()); EXPECT_EQ(matrix.rows(), node.size()); ASSERT_NO_THROW({Matrix expected = node.as<Matrix>();});
bool DepthObstacleGrid::initializeDepth(const std::string &filename, double depth_variance){ std::ifstream fin(filename.c_str()); if(fin.fail()) { std::cerr << "Could not open input stream from file" << filename.c_str() << std::endl; return false; } YAML::Parser parser(fin); YAML::Node doc; Eigen::Vector3d vec; Eigen::Vector3d last_vec(NAN, NAN, NAN); std::cout << "Read yml" << std::endl; while(parser.GetNextDocument(doc)) { std::cout << "Doc size: " << doc.size() << std::endl; for(int i = 0; i < doc.size(); i++){ //const YAML::Node& node = doc["values"]; doc[i]["position"] >> vec; std::cout << "Vec: " << vec.transpose() << std::endl; if(vec.y() == last_vec.y() && vec.x() - last_vec.x() > resolution ){ for(double x = last_vec.x() ; x < vec.x(); x += resolution){ setDepth(x, vec.y(), last_vec.z(), depth_variance); } } if(vec.y() != last_vec.y() && last_vec.x() < ( - position.x()) + span.x() ){ for(double x = last_vec.x() + resolution; x <= (- position.x()) + span.x() ; x += resolution){ setDepth( x, last_vec.y(), last_vec.z(), depth_variance); } } if(vec.y() != last_vec.y() && vec.x() > ( - position.x())){ for(double x = -position.x() ; x < vec.x() ; x += resolution){ setDepth( x, vec.y(), last_vec.z(), depth_variance); } } if(vec.y() - last_vec.y() > resolution){ for( double y = last_vec.y() + resolution; y < vec.y(); y+= resolution){ for( double x = - position.x(); x < (- position.x()) + span.x() ; x += resolution){ setDepth(x, y, last_vec.z(), depth_variance); } } } setDepth(vec.x(), vec.y(), vec.z(), depth_variance); last_vec = vec; } } return true; }
void MidiRouter::readFile(QString fileName) { clear(); QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { emit(mappingError("cannot open file: " + fileName)); return; } QTextStream in(&file); YAML::Node root = YAML::Load(in.readAll().toStdString()); if (!root.IsMap()) { emit(mappingError("mapping is not a map in " + fileName)); return; } for (auto kv: std::map<QString, int>({{"master", -1}, {"player0", 0}, {"player1", 1}})) { const QString key = kv.first; const int player = kv.second; if (!root[key]) continue; YAML::Node parent = root[key]; if (!parent.IsSequence()) emit(mappingError(key + " is not a sequence in " + fileName)); for (unsigned int i = 0; i < parent.size(); i++) { YAML::Node node = parent[i]; MidiMapPtr mmap = QSharedPointer<MidiMap>::create(); mmap->player_index = player; try { if (node["trigger"]) { mmap->signal_name = node["trigger"].as<QString>(); mmap->mapping_type = TRIGGER; try { if (!find_midi(node, mmap, yamls_trigger_map)) emit(mappingError(key + " could not find trigger mapping in element " + QString::number(i))); } catch (std::runtime_error& e) { emit(mappingError(key + QString::fromStdString(e.what()) + " in element " + QString::number(i))); } } else if (node["continuous"]) { mmap->signal_name = node["continuous"].as<QString>(); mmap->mapping_type = CONTINUOUS; try { if (!find_midi(node, mmap, yamls_cc_map)) emit(mappingError(key + " could not find cc mapping in element " + QString::number(i))); } catch (std::runtime_error& e) { emit(mappingError(key + QString::fromStdString(e.what()) + " in element " + QString::number(i))); } } else if (node["twos_complement"]) { mmap->signal_name = node["twos_complement"].as<QString>(); mmap->mapping_type = TWOS_COMPLEMENT; try { if (!find_midi(node, mmap, yamls_cc_map)) emit(mappingError(key + " could not find trigger mapping in element " + QString::number(i))); } catch (std::runtime_error& e) { emit(mappingError(key + QString::fromStdString(e.what()) + " in element " + QString::number(i))); } } else { emit(mappingError(key + " no supported mapping found in midi mapping element " + QString::number(i))); return; } if (node["mult"]) mmap->multiplier = node["mult"].as<double>(); if (node["offset"]) mmap->offset = node["offset"].as<double>(); //XXX search for conflicting maps and warn mMappings.push_back(mmap); } catch (YAML::Exception& e) { emit(mappingError(key + " exception processing midi mapping element " + QString::number(i) + " " + QString(e.what()))); return; } catch(...) { emit(mappingError(key + " exception processing midi mapping element " + QString::number(i))); return; } } } }
bool Article::ArticleData::ParseYaml(const ArticleData& defaultValues) { YAML::Node config = YAML::Load(m_RawYaml); if (config.size() <= 0) return false; if (config["m_Ignore"] != NULL) m_Ignore = config["m_Ignore"].as<bool>(); else m_Ignore = defaultValues.m_Ignore; if (config["m_Hidden"] != NULL) m_Hidden = config["m_Hidden"].as<bool>(); else m_Hidden = defaultValues.m_Hidden; if (config["m_Order"] != NULL) m_Order = config["m_Order"].as<int>(); else m_Order = defaultValues.m_Order; if (config["m_IsHomepage"] != NULL) m_IsHomepage = config["m_IsHomepage"].as<bool>(); else m_IsHomepage = defaultValues.m_IsHomepage; if (config["m_Title"] != NULL) m_Title = config["m_Title"].as<std::string>(); else m_Title = defaultValues.m_Title; if (config["m_Language"] != NULL) m_Language = config["m_Language"].as<std::string>(); else m_Language = defaultValues.m_Language; if (config["m_Link"] != NULL) m_Link = config["m_Link"].as<std::string>(); else m_Link = defaultValues.m_Link; m_ExternalLink = m_Link.find("http://") != std::string::npos; if (config["m_Date"] != NULL) { std::string dateString = config["m_Date"].as<std::string>(); m_Date = boost::gregorian::from_string(dateString); } else m_Date = defaultValues.m_Date; YAML::Node tags = config["m_Tags"]; if (tags != NULL) { for (unsigned i = 0; i < tags.size(); i++) { std::string tag = tags[i].as<std::string>(); bool tagFound = false; for (auto it = m_Tags.begin(); it != m_Tags.end(); ++it) { if (*it == tag) { tagFound = true; break; } } if (!tagFound) m_Tags.push_back(tag); } } else m_Tags = defaultValues.m_Tags; if (m_Content.empty()) m_Content = defaultValues.m_Content; return true; }
void GenerateReportData(const Game& game, std::list<Message>& messages, const std::list<Plugin>& plugins, const std::string& masterlistVersion, const std::string& masterlistDate, const bool masterlistUpdateEnabled) { YAML::Node oldDetails; GetOldReportDetails(game.ReportDataPath(), oldDetails); //Need to output YAML as a JSON Javascript variable. YAML::Emitter yout; yout.SetOutputCharset(YAML::EscapeNonAscii); yout.SetStringFormat(YAML::DoubleQuoted); yout.SetBoolFormat(YAML::TrueFalseBool); yout.SetSeqFormat(YAML::Flow); yout.SetMapFormat(YAML::Flow); BOOST_LOG_TRIVIAL(debug) << "Generating JSON report data."; yout << YAML::BeginMap; yout << YAML::Key << "lootVersion" << YAML::Value << IntToString(g_version_major) + "." + IntToString(g_version_minor) + "." + IntToString(g_version_patch); yout << YAML::Key << "masterlist" << YAML::BeginMap << YAML::Key << "updaterEnabled" << YAML::Value; if (masterlistUpdateEnabled) yout << boost::locale::translate("Enabled").str(); else yout << boost::locale::translate("Disabled").str(); yout << YAML::Key << "revision" << YAML::Value << masterlistVersion << YAML::Key << "date" << YAML::Value << masterlistDate << YAML::EndMap; if (!plugins.empty()) { BOOST_LOG_TRIVIAL(debug) << "Generating JSON plugin data."; YAML::Emitter tempout; tempout.SetOutputCharset(YAML::EscapeNonAscii); tempout.SetStringFormat(YAML::DoubleQuoted); tempout.SetBoolFormat(YAML::TrueFalseBool); tempout.SetSeqFormat(YAML::Flow); tempout.SetMapFormat(YAML::Flow); tempout << YAML::BeginSeq; for (std::list<Plugin>::const_iterator it = plugins.begin(), endit = plugins.end(); it != endit; ++it) { WritePlugin(tempout, *it, game); } tempout << YAML::EndSeq; YAML::Node node = YAML::Load(tempout.c_str()); if (AreDetailsEqual(node, oldDetails)) messages.push_front(loot::Message(loot::Message::say, boost::locale::translate("There have been no changes in the Details tab since LOOT was last run for this game.").str())); //Need to generate output twice because passing the node causes !<!> to be written before every key and value for some reason. yout << YAML::Key << "plugins" << YAML::Value << YAML::BeginSeq; for (std::list<Plugin>::const_iterator it = plugins.begin(), endit = plugins.end(); it != endit; ++it) { WritePlugin(yout, *it, game); } yout << YAML::EndSeq; } else if (oldDetails.size() == 0) messages.push_front(loot::Message(loot::Message::say, boost::locale::translate("There have been no changes in the Details tab since LOOT was last run for this game.").str())); if (!messages.empty()) { BOOST_LOG_TRIVIAL(debug) << "Generating JSON general message data."; yout << YAML::Key << "globalMessages" << YAML::Value << YAML::BeginSeq; for (std::list<Message>::const_iterator it = messages.begin(), endit = messages.end(); it != endit; ++it) { WriteMessage(yout, *it); } yout << YAML::EndSeq; } BOOST_LOG_TRIVIAL(debug) << "Generating text translations."; yout << YAML::Key << "l10n" << YAML::BeginMap << YAML::Key << "txtSummarySec" << YAML::Value << boost::locale::translate("Summary").str() << YAML::Key << "txtSummary" << YAML::Value << boost::locale::translate("Summary").str() << YAML::Key << "txtLootVersion" << YAML::Value << boost::locale::translate("LOOT Version").str() << YAML::Key << "txtMasterlistRevision" << YAML::Value << boost::locale::translate("Masterlist Revision").str() << YAML::Key << "txtMasterlistDate" << YAML::Value << boost::locale::translate("Masterlist Date").str() << YAML::Key << "txtMasterlistUpdating" << YAML::Value << boost::locale::translate("Masterlist Updating").str() << YAML::Key << "txtTotalMessageNo" << YAML::Value << boost::locale::translate("Total Number of Messages").str() << YAML::Key << "txtTotalWarningNo" << YAML::Value << boost::locale::translate("Number of Warnings").str() << YAML::Key << "txtTotalErrorNo" << YAML::Value << boost::locale::translate("Number of Errors").str() << YAML::Key << "txtGeneralMessages" << YAML::Value << boost::locale::translate("General Messages").str() << YAML::Key << "txtDetailsSec" << YAML::Value << boost::locale::translate("Details").str() << YAML::Key << "filtersToggle" << YAML::Value << boost::locale::translate("Filters").str() << YAML::Key << "txtHideVersionNumbers" << YAML::Value << boost::locale::translate("Hide Version Numbers").str() << YAML::Key << "txtHideCRCs" << YAML::Value << boost::locale::translate("Hide CRCs").str() << YAML::Key << "txtHideBashTags" << YAML::Value << boost::locale::translate("Hide Bash Tag Suggestions").str() << YAML::Key << "txtHideNotes" << YAML::Value << boost::locale::translate("Hide Notes").str() << YAML::Key << "txtHideDoNotCleanMessages" << YAML::Value << boost::locale::translate("Hide 'Do Not Clean' Messages").str() << YAML::Key << "txtHideInactivePluginMessages" << YAML::Value << boost::locale::translate("Hide Inactive Plugin Messages").str() << YAML::Key << "txtHideAllPluginMessages" << YAML::Value << boost::locale::translate("Hide All Plugin Messages").str() << YAML::Key << "txtHideMessagelessPlugins" << YAML::Value << boost::locale::translate("Hide Messageless Plugins").str() << YAML::Key << "txtPluginsHidden" << YAML::Value << boost::locale::translate("Plugins hidden").str() << YAML::Key << "txtMessagesHidden" << YAML::Value << boost::locale::translate("Messages hidden").str() << YAML::EndMap; yout << YAML::EndMap; loot::ofstream out(game.ReportDataPath()); out << "var data = " << yout.c_str(); out.close(); }
View::View(node_id_t node_id, std::string cf) : node_id_(node_id), master_id_(0), period_(500) { LOG_INFO("loading config file %s ...", cf.c_str()); YAML::Node config; if (cf.empty()) { // default only one node config = YAML::LoadFile("config/localhost-1.yaml"); node_id_ = 0; } else { config = YAML::LoadFile(cf); } if (config == NULL) { printf("cannot open config file: %s.", cf.c_str()); } YAML::Node nodes = config["host"]; YAML::Node lease = config["lease"]; for (std::size_t i = 0; i < nodes.size(); i++) { YAML::Node node = nodes[i]; std::string name = node["name"].as<std::string>(); std::string addr = node["addr"].as<std::string>(); uint32_t port = node["port"].as<int>(); // set a node in view host_info_t host_info = host_info_t(name, addr, port); host_nodes_.push_back(host_info); } size_ = host_nodes_.size(); if (lease) { master_id_ = lease["master_id"].as<int>(); period_ = lease["period"].as<int>(); } else { LOG_INFO("No lease Node Found, using default master_id/0 period/500"); } #if MODE_TYPE == 1 YAML::Node rs = config["rs"]; if (rs) { rs_x_ = rs["x"].as<int>(); rs_n_ = rs["n"].as<int>(); rs_qr_ = rs["qr"].as<int>(); rs_qw_ = rs["qw"].as<int>(); rs_f_ = rs["f"].as<int>(); } else { LOG_INFO("No RS Node Found!!, using Default function to compute"); rs_n_ = size_; if (rs_n_ == 1) { rs_x_ = 1; } else { if (rs_n_ % 2 == 0) { rs_x_ = 2; } else { rs_x_ = 3; } } rs_qr_ = (rs_n_ + rs_x_) / 2; rs_qw_ = rs_qr_; rs_f_ = rs_n_ - rs_qr_; } #endif if (node_id_ >= size_) { std::cout << "Node_Id " << node_id_ << " > host_nodes_.size " << size_ << "Invalid!" << std::endl; std::cout << "Set Node_Id = 0" << std::endl; node_id_ = 0; } LOG_INFO("config file loaded"); }
void Config::parseWatcher(const YAML::Node& node) { size_t asterisk_count; if(node.size() >= 1 && node.IsMap()) for (YAML::const_iterator iter=node.begin();iter!=node.end();++iter) { std::string key = iter->first.as<std::string>(); YAML::Node value = iter->second; Util::lowercase(key); if(key == "filter") { if(!value.IsSequence()) std::cerr << "ERROR!\n"; for(YAML::const_iterator filter_iter=value.begin(); filter_iter!=value.end(); ++filter_iter) { asterisk_count = 0; std::string val = filter_iter->as<std::string>(); for(size_t i = 0; i < val.length(); i++) if(val[i] == '*') asterisk_count++; LOG(logger, DEBUG, "Filter: %s", val.c_str()); if(asterisk_count > 1) throw std::runtime_error("Could not open file"); mWatch.filters.push_back(val); } } else if(key == "include") { if(!value.IsSequence() && !value.IsScalar()) std::cerr << "ERROR!\n"; if(value.IsSequence()) { for(YAML::const_iterator filter_iter=value.begin(); filter_iter!=value.end(); ++filter_iter) { LOG(logger, DEBUG, "Include: %s", filter_iter->as<std::string>().c_str()); mWatch.include.push_back(filter_iter->as<std::string>()); } } else if(value.IsScalar()) { LOG(logger, DEBUG, "Include: %s", value.as<std::string>().c_str()); mWatch.include.push_back(value.as<std::string>()); } } else if(key == "exclude") { if(!value.IsSequence() && !value.IsScalar()) std::cerr << "ERROR!\n"; if(value.IsSequence()) { for(YAML::const_iterator filter_iter=value.begin(); filter_iter!=value.end(); ++filter_iter) { LOG(logger, DEBUG, "Exclude: %s", filter_iter->as<std::string>().c_str()); mWatch.exclude.push_back(filter_iter->as<std::string>()); } } else if(value.IsScalar()) { LOG(logger, DEBUG, "Exclude: %s", value.as<std::string>().c_str()); mWatch.exclude.push_back(value.as<std::string>()); } } else LOG(logger, DEBUG, "Value: %s\n", value.as<std::string>().c_str()); } }
static void yaml_traverse(struct VMGlobals* g, const YAML::Node & node, PyrObject *parent, PyrSlot *slot) { YAML::NodeType::value type = node.Type(); string out; PyrObject *result = NULL; switch (type) { case YAML::NodeType::Scalar: node >> out; result = (PyrObject*)newPyrString(g->gc, out.c_str(), 0, true); SetObject(slot, result); if(parent) g->gc->GCWriteNew(parent, result); // we know result is white so we can use GCWriteNew break; case YAML::NodeType::Sequence: result = newPyrArray(g->gc, node.size(), 0, true); SetObject(slot, result); if(parent) g->gc->GCWriteNew(parent, result); // we know result is white so we can use GCWriteNew for (unsigned int i = 0; i < node.size(); i++) { const YAML::Node & subnode = node[i]; result->size++; yaml_traverse(g, subnode, result, result->slots+i); } break; case YAML::NodeType::Map: { result = instantiateObject( g->gc, s_dictionary->u.classobj, 0, false, true ); SetObject(slot, result); if(parent) g->gc->GCWriteNew(parent, result); // we know result is white so we can use GCWriteNew PyrObject *array = newPyrArray(g->gc, node.size()*2, 0, true); result->size = 2; SetObject(result->slots, array); // array SetInt(result->slots+1, node.size()); // size g->gc->GCWriteNew(result, array); // we know array is white so we can use GCWriteNew int j = 0; for (YAML::Iterator i = node.begin(); i != node.end(); ++i) { const YAML::Node & key = i.first(); const YAML::Node & value = i.second(); key >> out; PyrObject *pkey = (PyrObject*)newPyrString(g->gc, out.c_str(), 0, true); SetObject(array->slots+j, pkey); array->size++; g->gc->GCWriteNew(array, pkey); // we know pkey is white so we can use GCWriteNew array->size++; yaml_traverse(g, value, array, array->slots+j+1); j += 2; } break; } case YAML::NodeType::Null: SetNil(slot); break; default: postfl("WARNING: yaml_traverse(): unknown/unsupported node type\n"); SetNil(slot); } }
// Safely gets the YAML value from the sequence of YAML values. If provided // index is out-of-bounds we return a null value. inline const YAML::Node safe_get_value(const YAML::Node& seq, std::size_t idx) { static const auto null_value = YAML::Node{}; return idx >= seq.size() ? null_value : seq[idx]; }
Reflectable reflectable_from_yaml(const YAML::Node& value) { Reflectable refl{}; if (value.IsMap()) { ctti::reflect(refl, [&value](auto fi) { using field_type = typename decltype(fi)::type; try { const auto& query = value[fi.name()]; if (query) fi.get() = yaml::deserialize<field_type>(query); else fi.get() = yaml::deserialize<field_type>({}); } catch (deserialize_error& ex) { std::string msg = "error when deserializing field " + std::string(fi.name()); ex.add(msg.c_str()); throw; } }); } else if (value.IsSequence()) { if (value.size() > ctti::total_num_fields<Reflectable>()) { throw deserialize_error{"sequence size is greater than " "declared struct's field " "count"}; } ctti::reflect(refl, [&value, index = 0U](auto fi) mutable { using field_type = typename decltype(fi)::type; try { if (index < value.size()) fi.get() = yaml::deserialize<field_type>(value[index]); else fi.get() = yaml::deserialize<field_type>({}); ++index; } catch (deserialize_error& ex) { std::string msg = "error when deserializing element " + std::to_string(index); ex.add(msg.c_str()); throw; } }); } else { throw deserialize_error{"type must be a sequence or map but is " + yaml_type_name(value)}; } return refl; }
STKUNIT_UNIT_TEST(nodeRegistry, test_parallel_1_0) { EXCEPTWATCH; MPI_Barrier( MPI_COMM_WORLD ); // start_demo_nodeRegistry_test_parallel_1 percept::PerceptMesh eMesh(3u); unsigned p_size = eMesh.get_parallel_size(); unsigned p_rank = eMesh.get_rank(); Util::setRank(eMesh.get_rank()); eMesh.new_mesh(percept::GMeshSpec(std::string("1x1x")+toString(p_size)+std::string("|bbox:0,0,0,1,1,1"))); // prepare for adding some quadratic elements mesh::Part& block_hex_20 = eMesh.get_fem_meta_data()->declare_part("block_hex_20", eMesh.element_rank()); /// set cell topology for the part block_hex_20 mesh::fem::set_cell_topology< shards::Hexahedron<20> >( block_hex_20 ); stk_classic::io::put_io_part_attribute(block_hex_20); eMesh.commit(); eMesh.print_info(); eMesh.save_as("./cube1x1x2_hex-20-orig.e"); mesh::Part* block_hex_8 = const_cast<mesh::Part *>(eMesh.getPart("block_1")); NodeRegistry nodeRegistry(eMesh); nodeRegistry.initialize(); if (p_size <= 2) { // pick an element on the processor boundary unsigned elem_num_local = 1; unsigned elem_num_ghost = 2; if (p_size == 1) elem_num_ghost = 1; stk_classic::mesh::Entity* element_local_p = eMesh.get_bulk_data()->get_entity(eMesh.element_rank(), elem_num_local); stk_classic::mesh::Entity* element_ghost_p = eMesh.get_bulk_data()->get_entity(eMesh.element_rank(), elem_num_ghost); if (p_rank == 1) { element_local_p = eMesh.get_bulk_data()->get_entity(eMesh.element_rank(), elem_num_ghost); element_ghost_p = eMesh.get_bulk_data()->get_entity(eMesh.element_rank(), elem_num_local); } dw() << "P["<<p_rank<<"] elem_num_local = " << elem_num_local << DWENDL; dw() << "P["<<p_rank<<"] elem_num_ghost = " << elem_num_ghost << DWENDL; stk_classic::mesh::Entity& element_local = *element_local_p; stk_classic::mesh::Entity& element_ghost = *element_ghost_p; std::cout << "P["<<p_rank<<"] element_local = " << element_local << std::endl; std::cout << "P["<<p_rank<<"] element_ghost = " << element_ghost << std::endl; // choose edges to be used for new node locations (i.e., this would model a serendipity-like element with only edge Lagrange nodes) stk_classic::mesh::EntityRank stk_mesh_Edge = 1; NeededEntityType needed_entity_rank( stk_mesh_Edge, 1u); std::vector<NeededEntityType> needed_entity_ranks(1, needed_entity_rank); /* * 1st of three steps to create and associate new nodes - register need for new nodes, then check if node is remote, then get * from remote proc if necessary; finally, the local node database is ready to be queried * * The pattern is to begin the step, loop over all elements (including ghosts) and invoke the local operation * The method doForAllSubEntities is a utility for performing the operation on all the sub entities. * If more granularity is desired, the member functions can be invoked directly for a particular sub-entity. */ nodeRegistry.beginRegistration(); nodeRegistry.doForAllSubEntities(&NodeRegistry::registerNeedNewNode, element_local, needed_entity_ranks); nodeRegistry.doForAllSubEntities(&NodeRegistry::registerNeedNewNode, element_ghost, needed_entity_ranks); nodeRegistry.endRegistration(); std::cout << "P["<<p_rank<<"] nodeRegistry size = " << nodeRegistry.total_size() << std::endl; std::cout << "P["<<p_rank<<"] nodeRegistry lsize = " << nodeRegistry.local_size() << std::endl; dw() << "P["<<p_rank<<"] nodeRegistry size = " << nodeRegistry.total_size() << DWENDL; dw() << "P["<<p_rank<<"] nodeRegistry lsize = " << nodeRegistry.local_size() << DWENDL; // could do local create of elements here nodeRegistry.beginLocalMeshMods(); nodeRegistry.endLocalMeshMods(); // check if the newly requested nodes are local or remote nodeRegistry.beginCheckForRemote(); nodeRegistry.doForAllSubEntities(&NodeRegistry::checkForRemote, element_local, needed_entity_ranks); nodeRegistry.doForAllSubEntities(&NodeRegistry::checkForRemote, element_ghost, needed_entity_ranks); nodeRegistry.endCheckForRemote(); // get the new nodes from other procs if they are nonlocal nodeRegistry.beginGetFromRemote(); nodeRegistry.doForAllSubEntities(&NodeRegistry::getFromRemote, element_local, needed_entity_ranks); nodeRegistry.doForAllSubEntities(&NodeRegistry::getFromRemote, element_ghost, needed_entity_ranks); nodeRegistry.endGetFromRemote(); // now we can get the new node's id and entity unsigned iSubDimOrd = 4u; if (p_rank) { iSubDimOrd = 0u; } NodeIdsOnSubDimEntityType& nodeIds_onSE_0 = *( nodeRegistry.getNewNodesOnSubDimEntity(element_local, needed_entity_rank.first, iSubDimOrd)); stk_classic::mesh::Entity* node_0 = eMesh.get_bulk_data()->get_entity(stk_classic::mesh::fem::FEMMetaData::NODE_RANK, nodeIds_onSE_0[0]->identifier()); // should be the same node on each proc std::cout << "P[" << p_rank << "] nodeId_0 = " << nodeIds_onSE_0 << " node_0= " << node_0 << std::endl; // end_demo #if STK_ADAPT_HAVE_YAML_CPP if (p_size == 1) { if (1) { YAML::Emitter out; out << YAML::Anchor("NodeRegistry::map"); out << YAML::BeginMap; out << YAML::Key << YAML::BeginSeq << 1 << 2 << YAML::EndSeq << YAML::Value << YAML::BeginSeq << -1 << -2 << YAML::EndSeq; out << YAML::Key << 1; out << YAML::Value << 2; out << YAML::Key << 3; out << YAML::Value << 4; out << YAML::EndMap; //std::cout << "out=\n" << out.c_str() << "\n=out" << std::endl; std::string expected_result = "&NodeRegistry::map\n?\n - 1\n - 2\n:\n - -1\n - -2\n1: 2\n3: 4"; //std::cout << "out2=\n" << expected_result << std::endl; STKUNIT_EXPECT_TRUE(expected_result == std::string(out.c_str())); } YAML::Emitter yaml; std::cout << "\nnodeRegistry.serialize_write(yaml)" << std::endl; SerializeNodeRegistry::serialize_write(nodeRegistry, yaml, 0); //std::cout << yaml.c_str() << std::endl; if (!yaml.good()) { std::cout << "Emitter error: " << yaml.good() << " " <<yaml.GetLastError() << "\n"; STKUNIT_EXPECT_TRUE(false); } std::ofstream file1("out.yaml"); file1 << yaml.c_str(); file1.close(); std::ifstream file2("out.yaml"); YAML::Parser parser(file2); YAML::Node doc; try { while(parser.GetNextDocument(doc)) { std::cout << "\n read doc.Type() = " << doc.Type() << " doc.Tag()= " << doc.Tag() << " doc.size= " << doc.size() << std::endl; if (doc.Type() == YAML::NodeType::Map) { for(YAML::Iterator it=doc.begin();it!=doc.end();++it) { int key, value; std::cout << "read it.first().Type() = " << it.first().Type() << " it.first().Tag()= " << it.first().Tag() << std::endl; std::cout << "read it.second().Type() = " << it.second().Type() << " it.second().Tag()= " << it.second().Tag() << std::endl; const YAML::Node& keySeq = it.first(); for(YAML::Iterator itk=keySeq.begin();itk!=keySeq.end();++itk) { *itk >> key; std::cout << "read key= " << key << std::endl; } const YAML::Node& valSeq = it.second(); for(YAML::Iterator itv=valSeq.begin();itv!=valSeq.end();++itv) { *itv >> value; std::cout << "read value= " << value << std::endl; } } } } } catch(YAML::ParserException& e) { std::cout << e.what() << "\n"; STKUNIT_EXPECT_TRUE(false); } file2.close(); std::ifstream file3("out.yaml"); NodeRegistry nrNew(eMesh); SerializeNodeRegistry::serialize_read(nrNew, file3); YAML::Emitter yaml3; std::cout << "\nnrNew.serialize_write(yaml3)" << std::endl; SerializeNodeRegistry::serialize_write(nrNew, yaml3, 0); std::cout << yaml3.c_str() << std::endl; //exit(1); } #endif // start_demo_nodeRegistry_test_parallel_1_quadratic_elem // change element to be a serendipity quadratic element eMesh.get_bulk_data()->modification_begin(); //getCellTopologyData< shards::Node >() const CellTopologyData *const cell_topo_data =stk_classic::percept::PerceptMesh::get_cell_topology(block_hex_20); CellTopology cell_topo(cell_topo_data); for (unsigned isd = 0; isd < 12; isd++) { nodeRegistry.makeCentroidCoords(element_local, needed_entity_rank.first, isd); NodeIdsOnSubDimEntityType& nodeIds_onSE_0_loc = *( nodeRegistry.getNewNodesOnSubDimEntity(element_local, needed_entity_rank.first, isd)); stk_classic::mesh::Entity* node = eMesh.get_bulk_data()->get_entity(stk_classic::mesh::fem::FEMMetaData::NODE_RANK, nodeIds_onSE_0_loc[0]->identifier()); unsigned edge_ord = 8u + isd; //unsigned n_edge_ord = cell_topo_data->edge[isd].topology->node_count; //std::cout << "n_edge_ord = " << n_edge_ord << std::endl; edge_ord = cell_topo_data->edge[isd].node[2]; eMesh.get_bulk_data()->declare_relation(element_local, *node, edge_ord); } std::vector<stk_classic::mesh::Part*> add_parts(1, &block_hex_20); std::vector<stk_classic::mesh::Part*> remove_parts(1, block_hex_8); eMesh.get_bulk_data()->change_entity_parts( element_local, add_parts, remove_parts ); eMesh.get_bulk_data()->modification_end(); eMesh.print_info("After quadratic"); eMesh.save_as("./cube1x1x2_hex-20.e"); //exit(1); }
int parse_yaml(std::string config_file) { rect_t matrix_rect = {0, 0, 0, 0}; simulator_ptr sim = NULL; surface_ptr surf = NULL; output_ptr out = NULL; YAML::Node config = YAML::LoadFile(config_file); if(config.size() == 0 || !(config)) { fprintf(stderr, "config file incomplete or empty!. exiting\n"); return -1; } for(YAML::const_iterator j = config.begin();j != config.end(); ++j) { YAML::Node pattern_node = config[j->first.as<std::string>()]; YAML::Node matrix = pattern_node["matrix"].as<YAML::Node>(); YAML::Node matrixsim = pattern_node["matrixsim"].as<YAML::Node>(); YAML::Node protocol = pattern_node["protocol"].as<YAML::Node>(); YAML::Node pattern = pattern_node["pattern"].as<YAML::Node>(); // a first test to see if pattern exist nothing else matters if it doesn't // exist. std::string pname; if(pattern) { pname = pattern["job"].as<std::string>(); } else { fprintf(stderr, "exiting because no pattern exist/selected. \n" "config-node: %s\n", j->first.as<std::string>().c_str()); return -1; } if(matrix) { matrix_rect.x = matrix["x"].as<int>(); matrix_rect.y = matrix["y"].as<int>(); matrix_rect.width = matrix["width"].as<int>(); matrix_rect.height = matrix["height"].as<int>(); } else { fprintf(stderr, "%s: no valid dimensions found. exiting.\n" "config-node: %s\n", pname.c_str(), j->first.as<std::string>().c_str()); return -1; } if(matrixsim) { int pixelsize = matrixsim["pixelsize"].as<int>(); bool fullscreen = false; if(matrixsim["fullscreen"]) fullscreen = matrixsim["fullscreen"].as<bool>(); /* there is a small leak here, probably due to SDL */ sim = simulator_ptr(new MatrixSimulator(matrix_rect, pixelsize, fullscreen)); } else { fprintf(stderr, "%s: running pattern without simulator.\n" "config-node: %s\n", pname.c_str(), j->first.as<std::string>().c_str()); } if(protocol) { std::string type = protocol["type"].as<std::string>(); out = builder.protocol_builder(type, protocol); if(out == NULL) { fprintf(stderr, "%s couldn't be created. not sending.\n", type.c_str()); } } else { fprintf(stderr, "%s: no protocol found. not sending.\n" "config-node: %s\n", pname.c_str(), j->first.as<std::string>().c_str()); } // after all this we are sure pattern exist. // because we did a test for that earlier. std::string name = pattern["job"].as<std::string>().c_str(); surf = builder.surface_builder(name, matrix_rect, pattern); if(surf == NULL) { fprintf(stderr, "%s couldn't be created. exiting. \n", name.c_str()); return -1; } pattern_ptr pat = pattern_ptr(new Pattern_t()); pat->surf = std::move(surf); pat->sim = std::move(sim); pat->out = std::move(out); patternjobs.register_pattern(pat); } // so far so good! lets return 0 for that! return 0; }
void NodeSerialization::decode(const YAML::Node& node) { if (!node.IsMap()) { throw YAML::InvalidNode(); } _pluginID = node["PluginID"].as<std::string>(); if (node["PresetName"]) { _encodeType = eNodeSerializationTypePresets; // This is a presets or pyplug _presetsIdentifierLabel = node["PresetName"].as<std::string>(); if (node["PresetIcon"]) { _presetsIconFilePath = node["PresetIcon"].as<std::string>(); } if (node["PresetShortcutKey"]) { _presetShortcutSymbol = node["PresetShortcutKey"].as<int>(); } if (node["PresetShortcutModifiers"]) { _presetShortcutPresetModifiers = node["PresetShortcutModifiers"].as<int>(); } } if (node["Name"]) { _nodeScriptName = node["Name"].as<std::string>(); } if (node["Label"]) { _nodeLabel = node["Label"].as<std::string>(); } else { _nodeLabel = _nodeScriptName; } if (node["Version"]) { YAML::Node versionNode = node["Version"]; if (versionNode.size() != 2) { throw YAML::InvalidNode(); } _pluginMajorVersion = versionNode[0].as<int>(); _pluginMinorVersion = versionNode[1].as<int>(); } tryDecodeInputsMap(node, "Inputs", &_inputs); tryDecodeInputsMap(node, "Masks", &_masks); if (node["Params"]) { YAML::Node paramsNode = node["Params"]; for (std::size_t i = 0; i < paramsNode.size(); ++i) { KnobSerializationPtr s(new KnobSerialization); s->decode(paramsNode[i]); _knobsValues.push_back(s); } } if (node["UserPages"]) { YAML::Node pagesNode = node["UserPages"]; for (std::size_t i = 0; i < pagesNode.size(); ++i) { GroupKnobSerializationPtr s(new GroupKnobSerialization); s->decode(pagesNode[i]); _userPages.push_back(s); } } if (node["PagesOrder"]) { YAML::Node pagesOrder = node["PagesOrder"]; for (std::size_t i = 0; i < pagesOrder.size(); ++i) { _pagesIndexes.push_back(pagesOrder[i].as<std::string>()); } } if (node["Children"]) { YAML::Node childrenNode = node["Children"]; for (std::size_t i = 0; i < childrenNode.size(); ++i) { NodeSerializationPtr s(new NodeSerialization); s->decode(childrenNode[i]); _children.push_back(s); } } if (node["TableItems"]) { _tableModel.reset(new KnobItemsTableSerialization); _tableModel->decode(node["TableItems"]); } if (node["Preset"]) { _presetInstanceLabel = node["Preset"].as<std::string>(); } if (node["NewLayers"]) { YAML::Node layersNode = node["NewLayers"]; for (std::size_t i = 0; i < layersNode.size(); ++i) { ImagePlaneDescSerialization s; s.decode(layersNode[i]); _userComponents.push_back(s); } } if (node["Pos"]) { YAML::Node posNode = node["Pos"]; if (posNode.size() != 2) { throw YAML::InvalidNode(); } _nodePositionCoords[0] = posNode[0].as<double>(); _nodePositionCoords[1] = posNode[1].as<double>(); } if (node["Size"]) { YAML::Node sizeNode = node["Size"]; if (sizeNode.size() != 2) { throw YAML::InvalidNode(); } _nodeSize[0] = sizeNode[0].as<double>(); _nodeSize[1] = sizeNode[1].as<double>(); } if (node["Color"]) { YAML::Node colorNode = node["Color"]; if (colorNode.size() != 3) { throw YAML::InvalidNode(); } _nodeColor[0] = colorNode[0].as<double>(); _nodeColor[1] = colorNode[1].as<double>(); _nodeColor[2] = colorNode[2].as<double>(); } if (node["OverlayColor"]) { YAML::Node colorNode = node["OverlayColor"]; if (colorNode.size() != 3) { throw YAML::InvalidNode(); } _overlayColor[0] = colorNode[0].as<double>(); _overlayColor[1] = colorNode[1].as<double>(); _overlayColor[2] = colorNode[2].as<double>(); } if (node["ViewerParamsOrder"]) { YAML::Node viewerParamsOrderNode = node["ViewerParamsOrder"]; for (std::size_t i = 0; i < viewerParamsOrderNode.size(); ++i) { _viewerUIKnobsOrder.push_back(viewerParamsOrderNode[i].as<std::string>()); } } } // NodeSerialization::decode
void CurveSerialization::decode(const YAML::Node& node) { if (!node.IsSequence()) { return; } if (node.size() == 0) { return; } CurveDecodeStateEnum state = eCurveDecodeStateMayExpectInterpolation; std::string interpolation; KeyFrameSerialization keyframe; bool pushKeyFrame = false; for (std::size_t i = 0; i < node.size(); ++i) { YAML::Node keyNode = node[i]; switch (state) { case eCurveDecodeStateMayExpectInterpolation: if (pushKeyFrame) { keys.push_back(keyframe); // Reset keyframe keyframe.interpolation.clear(); keyframe.time = keyframe.value = keyframe.leftDerivative = keyframe.rightDerivative = 0.; } try { // First try to get a time. Conversion of a string to double always fails but string to double does not keyframe.time = keyNode.as<double>(); // OK we read a valid time, assume the interpolation is the same as the previous // No interpolation, use the interpolation set previously. // If interpolation is not set, set interpolation to linear if (interpolation.empty()) { interpolation = kKeyframeSerializationTypeLinear; } keyframe.interpolation = interpolation; state = eCurveDecodeStateExpectValue; } catch (const YAML::BadConversion& /*e*/) { // OK we read an interpolation and set the curve interpolation so far if needed keyframe.interpolation = keyNode.as<std::string>(); // No interpolation, use the interpolation set previously. // If interpolation is not set, set interpolation to linear if (interpolation.empty()) { interpolation = keyframe.interpolation; } state = eCurveDecodeStateExpectTime; } break; case eCurveDecodeStateExpectTime: keyframe.time = keyNode.as<double>(); state = eCurveDecodeStateExpectValue; break; case eCurveDecodeStateExpectValue: keyframe.value = keyNode.as<double>(); // Depending on interpolation we may expect derivatives if (keyframe.interpolation == kKeyframeSerializationTypeFree || keyframe.interpolation == kKeyframeSerializationTypeBroken) { state = eCurveDecodeStateMayExpectRightDerivative; } else { state = eCurveDecodeStateMayExpectInterpolation; } break; case eCurveDecodeStateMayExpectRightDerivative: keyframe.rightDerivative = keyNode.as<double>(); if (keyframe.interpolation == kKeyframeSerializationTypeBroken) { state = eCurveDecodeStateMayExpectLeftDerivative; } else { state = eCurveDecodeStateMayExpectInterpolation; } break; case eCurveDecodeStateMayExpectLeftDerivative: keyframe.leftDerivative = keyNode.as<double>(); state = eCurveDecodeStateMayExpectInterpolation; break; } pushKeyFrame = true; } if (pushKeyFrame) { keys.push_back(keyframe); } }
void Network::loadFromBundle(const std::string& name) { if (! StringUtils::endsWith(name, ".nta")) NTA_THROW << "loadFromBundle: bundle extension must be \".nta\""; std::string fullPath = Path::normalize(Path::makeAbsolute(name)); if (! Path::exists(fullPath)) NTA_THROW << "Path " << fullPath << " does not exist"; std::string networkStructureFilename = Path::join(fullPath, "network.yaml"); std::ifstream f(networkStructureFilename.c_str()); YAML::Parser parser(f); YAML::Node doc; bool success = parser.GetNextDocument(doc); if (!success) NTA_THROW << "Unable to find YAML document in network structure file " << networkStructureFilename; if (doc.Type() != YAML::NodeType::Map) NTA_THROW << "Invalid network structure file -- does not contain a map"; // Should contain Version, Regions, Links if (doc.size() != 3) NTA_THROW << "Invalid network structure file -- contains " << doc.size() << " elements"; // Extra version const YAML::Node *node = doc.FindValue("Version"); if (node == NULL) NTA_THROW << "Invalid network structure file -- no version"; int version; *node >> version; if (version != 2) NTA_THROW << "Invalid network structure file -- only version 2 supported"; // Regions const YAML::Node *regions = doc.FindValue("Regions"); if (regions == NULL) NTA_THROW << "Invalid network structure file -- no regions"; if (regions->Type() != YAML::NodeType::Sequence) NTA_THROW << "Invalid network structure file -- regions element is not a list"; for (YAML::Iterator region = regions->begin(); region != regions->end(); region++) { // Each region is a map -- extract the 5 values in the map if ((*region).Type() != YAML::NodeType::Map) NTA_THROW << "Invalid network structure file -- bad region (not a map)"; if ((*region).size() != 5) NTA_THROW << "Invalid network structure file -- bad region (wrong size)"; // 1. name node = (*region).FindValue("name"); if (node == NULL) NTA_THROW << "Invalid network structure file -- region has no name"; std::string name; *node >> name; // 2. nodeType node = (*region).FindValue("nodeType"); if (node == NULL) NTA_THROW << "Invalid network structure file -- region " << name << " has no node type"; std::string nodeType; *node >> nodeType; // 3. dimensions node = (*region).FindValue("dimensions"); if (node == NULL) NTA_THROW << "Invalid network structure file -- region " << name << " has no dimensions"; if ((*node).Type() != YAML::NodeType::Sequence) NTA_THROW << "Invalid network structure file -- region " << name << " dimensions specified incorrectly"; Dimensions dimensions; for (YAML::Iterator valiter = (*node).begin(); valiter != (*node).end(); valiter++) { size_t val; (*valiter) >> val; dimensions.push_back(val); } // 4. phases node = (*region).FindValue("phases"); if (node == NULL) NTA_THROW << "Invalid network structure file -- region" << name << "has no phases"; if ((*node).Type() != YAML::NodeType::Sequence) NTA_THROW << "Invalid network structure file -- region " << name << " phases specified incorrectly"; std::set<UInt32> phases; for (YAML::Iterator valiter = (*node).begin(); valiter != (*node).end(); valiter++) { UInt32 val; (*valiter) >> val; phases.insert(val); } // 5. label node = (*region).FindValue("label"); if (node == NULL) NTA_THROW << "Invalid network structure file -- region" << name << "has no label"; std::string label; *node >> label; Region *r = addRegionFromBundle(name, nodeType, dimensions, fullPath, label); setPhases_(r, phases); } const YAML::Node *links = doc.FindValue("Links"); if (links == NULL) NTA_THROW << "Invalid network structure file -- no links"; if (links->Type() != YAML::NodeType::Sequence) NTA_THROW << "Invalid network structure file -- links element is not a list"; for (YAML::Iterator link = links->begin(); link != links->end(); link++) { // Each link is a map -- extract the 5 values in the map if ((*link).Type() != YAML::NodeType::Map) NTA_THROW << "Invalid network structure file -- bad link (not a map)"; if ((*link).size() != 6) NTA_THROW << "Invalid network structure file -- bad link (wrong size)"; // 1. type node = (*link).FindValue("type"); if (node == NULL) NTA_THROW << "Invalid network structure file -- link does not have a type"; std::string linkType; *node >> linkType; // 2. params node = (*link).FindValue("params"); if (node == NULL) NTA_THROW << "Invalid network structure file -- link does not have params"; std::string params; *node >> params; // 3. srcRegion (name) node = (*link).FindValue("srcRegion"); if (node == NULL) NTA_THROW << "Invalid network structure file -- link does not have a srcRegion"; std::string srcRegionName; *node >> srcRegionName; // 4. srcOutput node = (*link).FindValue("srcOutput"); if (node == NULL) NTA_THROW << "Invalid network structure file -- link does not have a srcOutput"; std::string srcOutputName; *node >> srcOutputName; // 5. destRegion node = (*link).FindValue("destRegion"); if (node == NULL) NTA_THROW << "Invalid network structure file -- link does not have a destRegion"; std::string destRegionName; *node >> destRegionName; // 6. destInput node = (*link).FindValue("destInput"); if (node == NULL) NTA_THROW << "Invalid network structure file -- link does not have a destInput"; std::string destInputName; *node >> destInputName; if (!regions_.contains(srcRegionName)) NTA_THROW << "Invalid network structure file -- link specifies source region '" << srcRegionName << "' but no such region exists"; Region* srcRegion = regions_.getByName(srcRegionName); if (!regions_.contains(destRegionName)) NTA_THROW << "Invalid network structure file -- link specifies destination region '" << destRegionName << "' but no such region exists"; Region* destRegion = regions_.getByName(destRegionName); Output* srcOutput = srcRegion->getOutput(srcOutputName); if (srcOutput == NULL) NTA_THROW << "Invalid network structure file -- link specifies source output '" << srcOutputName << "' but no such name exists"; Input* destInput = destRegion->getInput(destInputName); if (destInput == NULL) NTA_THROW << "Invalid network structure file -- link specifies destination input '" << destInputName << "' but no such name exists"; // Create the link itself destInput->addLink(linkType, params, srcOutput); } // links }
void KnobSerialization::decodeValueNode(const std::string& viewName, const YAML::Node& node) { int nDims = 1; bool isMainNodeSequence = node.IsSequence() && _dataType != eSerializationValueVariantTypeTable; if (isMainNodeSequence) { nDims = node.size(); } PerDimensionValueSerializationVec& dimVec = _values[viewName]; initValuesVec(this, &dimVec, nDims); for (int i = 0; i < nDims; ++i) { YAML::Node dimNode = isMainNodeSequence ? node[i] : node; if (!dimNode.IsMap()) { // This is a value decodeValueFromNode(dimNode, dimVec[i]._value, _dataType); dimVec[i]._serializeValue = true; } else { // !isMap // Always look for an animation curve if (dimNode["Curve"]) { // Curve dimVec[i]._animationCurve.decode(dimNode["Curve"]); } // Look for a link or expression if (dimNode["pyMultiExpr"]) { dimVec[i]._expression = dimNode["pyMultiExpr"].as<std::string>(); dimVec[i]._expresionHasReturnVariable = true; dimVec[i]._expressionLanguage = kKnobSerializationExpressionLanguagePython; } else if (dimNode["pyExpr"]) { dimVec[i]._expression = dimNode["pyExpr"].as<std::string>(); dimVec[i]._expressionLanguage = kKnobSerializationExpressionLanguagePython; } else if (dimNode["exprtk"]) { dimVec[i]._expression = dimNode["exprtk"].as<std::string>(); dimVec[i]._expressionLanguage = kKnobSerializationExpressionLanguageExprtk; } else { // This is most likely a regular slavr/master link bool gotLink = false; if (dimNode["N"]) { dimVec[i]._slaveMasterLink.masterNodeName = dimNode["N"].as<std::string>(); gotLink = true; } if (dimNode["T"]) { dimVec[i]._slaveMasterLink.masterTableItemName = dimNode["T"].as<std::string>(); gotLink = true; } if (dimNode["K"]) { dimVec[i]._slaveMasterLink.masterKnobName = dimNode["K"].as<std::string>(); gotLink = true; } if (dimNode["D"]) { dimVec[i]._slaveMasterLink.masterDimensionName = dimNode["D"].as<std::string>(); gotLink = true; } if (dimNode["V"]) { dimVec[i]._slaveMasterLink.masterViewName = dimNode["V"].as<std::string>(); gotLink = true; } dimVec[i]._slaveMasterLink.hasLink = gotLink; } } // isMap } } //decodeValueNode
int main() { using namespace std; YAML::Node allNode = YAML::LoadFile("smurf.yaml"); YAML::Node npcNodes = allNode["NPCS"]; // // go through all NPCS blocks on yaml file (only read NPCS) string NPCDescription; string NPCId; vector<string> npcKeywords; string NPCLongDesc; string NPCShortDesc; for(int i = 0; (unsigned)i < npcNodes.size(); i++) { NPCDescription =""; NPCId= ""; npcKeywords.clear(); NPCLongDesc =""; NPCShortDesc=" "; YAML::Node descriptionNode = npcNodes[i]["description"]; //string npcDescription; for(int j = 0; j < descriptionNode.size(); j++){ NPCDescription += descriptionNode[j].as<string>(); } NPCId = npcNodes[i]["id"].as<string>(); YAML::Node keywordsNode = npcNodes[i]["keywords"]; for(int k = 0; k < keywordsNode.size(); k++){ npcKeywords.push_back(keywordsNode[k].as<string>()); } YAML::Node longdescNode = npcNodes[i]["longdesc"]; for(int k = 0; k < longdescNode.size(); k++){ NPCLongDesc += longdescNode[k].as<string>(); } NPCShortDesc = npcNodes[i]["shortdesc"].as<string>(); cout <<"--New NPC Created!--"<< endl; cout << NPCDescription << endl<<endl; cout << NPCId << endl<<endl; cout << "Keywords: " << endl; for (auto & keyword : npcKeywords) { cout << keyword << ", "; } cout << endl << endl <<NPCLongDesc << endl<<endl; cout << NPCShortDesc << endl<<endl; } // string description = npcNodes[i]["description"].as<string>(); // createNPC() // cout << description << endl << endl; // cout << id << endl << endl; //npcKeywords.push_back(keywords); //cout << "Keyword" << npcKeywords << endl << endl; //cout << "Keyword" << npcKeywords << endl << endl; // cout << longdesc << endl << endl; // cout << shortdesc << endl << endl; // void createNPC(){ // } // cout << endl << endl << npcNodes[0]["description"] << endl; // string npcID = rootNode[i]["id"].as<string>(); // // get npc keyword (string or vector<string> ?) // string npcKeyword = rootNode[i]["keywords"].as<string>(); // // get long desc // string npcLongDesc = rootNode[i]["longdesc"].as<string>(); // // get short desc // string npcShortDesc = rootNode[i]["shortdesc"].as<string>(); // // (the name of vector which store npc).push_back all informations read from yaml // npcVector.push_back(NPC(npcDescription,npcID,npcKeyword,npcLongDesc,npcShortDesc)); // // get description // YAML::Node descriptionNode = rootNode[i]["description"]; // std::string npcDescription; // for(int j = 0; (unsigned)j < descriptionNode.size(); j++){ // npcDescription += descriptionNode[j].as<std::string>()+" "; // std::cout << npcDescription; // } // } // // get npc id // string npcID = rootNode[i]["id"].as<string>(); // // get npc keyword (string or vector<string> ?) // string npcKeyword = rootNode[i]["keywords"].as<string>(); // // get long desc // string npcLongDesc = rootNode[i]["longdesc"].as<string>(); // // get short desc // string npcShortDesc = rootNode[i]["shortdesc"].as<string>(); // // (the name of vector which store npc).push_back all informations read from yaml // npcVector.push_back(NPC(npcDescription,npcID,npcKeyword,npcLongDesc,npcShortDesc)); return 0; }
void KnobSerialization::decode(const YAML::Node& node) { if (!node.IsMap()) { return; } // Set the flag to true if the user use this object directly to encode after _mustSerialize = true; _scriptName = node["Name"].as<std::string>(); // Check for nodes bool dataTypeSet = false; static const std::string typesToCheck[6] = { kKnobSerializationDataTypeKeyBool, kKnobSerializationDataTypeKeyInt, kKnobSerializationDataTypeKeyDouble, kKnobSerializationDataTypeKeyString, kKnobSerializationDataTypeKeyTable, kKnobSerializationDataTypeKeyNone }; for (int i = 0; i < 6; ++i) { if (checkForValueNode(node, typesToCheck[i])) { dataTypeSet = true; break; } } for (int i = 0; i < 6; ++i) { if (checkForDefaultValueNode(node, typesToCheck[i], dataTypeSet)) { break; } } if (node["ParametricCurves"]) { YAML::Node curveNode = node["ParametricCurves"]; ParametricExtraData *data = getOrCreateExtraData<ParametricExtraData>(_extraData); if (curveNode.IsMap()) { for (YAML::const_iterator it = curveNode.begin(); it!=curveNode.end(); ++it) { std::string viewName = it->first.as<std::string>(); YAML::Node curvesViewNode = it->second; std::list<CurveSerialization>& curvesList = data->parametricCurves[viewName]; for (std::size_t i = 0; i < curvesViewNode.size(); ++i) { CurveSerialization s; s.decode(curvesViewNode[i]); curvesList.push_back(s); } } } else { std::list<CurveSerialization>& curvesList = data->parametricCurves["Main"]; for (std::size_t i = 0; i < curveNode.size(); ++i) { CurveSerialization s; s.decode(curveNode[i]); curvesList.push_back(s); } } } if (node["TextAnim"]) { YAML::Node curveNode = node["TextAnim"]; TextExtraData *data = getOrCreateExtraData<TextExtraData>(_extraData); if (curveNode.IsMap()) { // Multi-view for (YAML::const_iterator it = curveNode.begin(); it!=curveNode.end(); ++it) { std::string viewName = it->first.as<std::string>(); YAML::Node keysForViewNode = it->second; std::map<double, std::string>& keysForView = data->keyframes[viewName]; // If type = 0 we expect a int, otherwise a string int type = 0; std::pair<double, std::string> p; for (std::size_t i = 0; i < keysForViewNode.size(); ++i) { if (type == 0) { p.first = keysForViewNode[i].as<double>(); type = 1; } else if (type == 1) { type = 0; p.second = keysForViewNode[i].as<std::string>(); keysForView.insert(p); } } } } else { // If type = 0 we expect a int, otherwise a string std::map<double, std::string>& keysForView = data->keyframes["Main"]; int type = 0; std::pair<double, std::string> p; for (std::size_t i = 0; i < curveNode.size(); ++i) { if (type == 0) { p.first = curveNode[i].as<double>(); type = 1; } else if (type == 1) { type = 0; p.second = curveNode[i].as<std::string>(); keysForView.insert(p); } } } } if (node["FontColor"]) { YAML::Node n = node["FontColor"]; if (n.size() != 3) { throw YAML::InvalidNode(); } TextExtraData *data = getOrCreateExtraData<TextExtraData>(_extraData); data->fontColor[0] = n[0].as<double>(); data->fontColor[1] = n[1].as<double>(); data->fontColor[2] = n[2].as<double>(); } if (node["FontSize"]) { TextExtraData *data = getOrCreateExtraData<TextExtraData>(_extraData); data->fontSize = node["FontSize"].as<int>(); } if (node["Font"]) { TextExtraData *data = getOrCreateExtraData<TextExtraData>(_extraData); data->fontFamily = node["Font"].as<std::string>(); } if (node["NDims"]) { // This is a user knob _isUserKnob = true; _typeName = node["TypeName"].as<std::string>(); _dimension = node["NDims"].as<int>(); if (node["Label"]) { _label = node["Label"].as<std::string>(); } else { _label = _scriptName; } if (node["Hint"]) { _tooltip = node["Hint"].as<std::string>(); } if (node["Persistent"]) { _isPersistent = node["Persistent"].as<bool>(); } else { _isPersistent = true; } if (node["UncheckedIcon"]) { _iconFilePath[0] = node["UncheckedIcon"].as<std::string>(); } if (node["CheckedIcon"]) { _iconFilePath[1] = node["CheckedIcon"].as<std::string>(); } // User specific data if (node["Entries"]) { // This is a choice ChoiceExtraData *data = new ChoiceExtraData; _extraData.reset(data); YAML::Node entriesNode = node["Entries"]; for (std::size_t i = 0; i < entriesNode.size(); ++i) { data->_entries.push_back(entriesNode[i].as<std::string>()); } // Also look for hints... if (node["Hints"]) { YAML::Node hintsNode = node["Hints"]; for (std::size_t i = 0; i < hintsNode.size(); ++i) { data->_helpStrings.push_back(hintsNode[i].as<std::string>()); } } } if (node["Min"]) { ValueExtraData* data = getOrCreateExtraData<ValueExtraData>(_extraData); data->min = node["Min"].as<double>(); } if (node["Max"]) { ValueExtraData* data = getOrCreateExtraData<ValueExtraData>(_extraData); data->max = node["Max"].as<double>(); } if (node["DisplayMin"]) { ValueExtraData* data = getOrCreateExtraData<ValueExtraData>(_extraData); data->dmin = node["DisplayMin"].as<double>(); } if (node["DisplayMax"]) { ValueExtraData* data = getOrCreateExtraData<ValueExtraData>(_extraData); data->dmax = node["DisplayMax"].as<double>(); } if (node["FileTypes"]) { FileExtraData* data = getOrCreateExtraData<FileExtraData>(_extraData); YAML::Node fileTypesNode = node["FileTypes"]; for (std::size_t i = 0; i < fileTypesNode.size(); ++i) { data->filters.push_back(fileTypesNode[i].as<std::string>()); } } } // isUserKnob if (node["InViewerLayout"]) { _inViewerContextItemLayout = node["InViewerLayout"].as<std::string>(); _hasViewerInterface = true; } if (node["InViewerSpacing"]) { _inViewerContextItemSpacing = node["InViewerSpacing"].as<int>(); _hasViewerInterface = true; } if (_isUserKnob) { if (node["InViewerLabel"]) { _inViewerContextLabel = node["InViewerLabel"].as<std::string>(); _hasViewerInterface = true; } if (node["InViewerIconUnchecked"]) { _inViewerContextIconFilePath[0] = node["InViewerIconUnchecked"].as<std::string>(); _hasViewerInterface = true; } if (node["InViewerIconChecked"]) { _inViewerContextIconFilePath[1] = node["InViewerIconChecked"].as<std::string>(); _hasViewerInterface = true; } } if (node["Props"]) { YAML::Node propsNode = node["Props"]; for (std::size_t i = 0; i < propsNode.size(); ++i) { std::string prop = propsNode[i].as<std::string>(); if (prop == "Secret") { _isSecret = true; } else if (prop == "Disabled") { _disabled = true; } else if (prop == "NoNewLine") { _triggerNewLine = false; } else if (prop == "NoEval") { _evaluatesOnChange = false; } else if (prop == "AnimatesChanged") { _animatesChanged = true; } else if (prop == "Volatile") { _isPersistent = false; } else if (prop == "IsLabel") { TextExtraData* data = getOrCreateExtraData<TextExtraData>(_extraData); data->label = true; data->multiLine = false; data->richText = false; } else if (prop == "MultiLine") { TextExtraData* data = getOrCreateExtraData<TextExtraData>(_extraData); data->label = false; data->multiLine = true; data->richText = false; } else if (prop == "RichText") { TextExtraData* data = getOrCreateExtraData<TextExtraData>(_extraData); data->richText = true; } else if (prop == "MultiPath") { PathExtraData* data = getOrCreateExtraData<PathExtraData>(_extraData); data->multiPath = node["MultiPath"].as<bool>(); } else if (prop == "Sequences") { FileExtraData* data = getOrCreateExtraData<FileExtraData>(_extraData); data->useSequences = node["Sequences"].as<bool>(); } else if (prop == "ExistingFiles") { FileExtraData* data = getOrCreateExtraData<FileExtraData>(_extraData); data->useExistingFiles = node["ExistingFiles"].as<bool>(); } else if (prop == "Italic") { TextExtraData *data = getOrCreateExtraData<TextExtraData>(_extraData); data->italicActivated = true; } else if (prop == "Bold") { TextExtraData *data = getOrCreateExtraData<TextExtraData>(_extraData); data->boldActivated = true; } else { std::cerr << "WARNING: Unrecognized parameter property " << prop << std::endl; } } } } // KnobSerialization::decode
void PathPlanningWidget::loadPointsFromFile() { /*! Slot that takes care of opening a previously saved Way-Points yaml file. Opens Qt Dialog for selecting the file, opens the file and parses the data. After reading and parsing the data from the file, the information regarding the pose of the Way-Points is send to the RQT and the RViz so they can update their enviroments. */ QString fileName = QFileDialog::getOpenFileName(this, tr("Open Way Points File"), "", tr("Way Points (*.yaml);;All Files (*)")); if (fileName.isEmpty()) { ui_.tabWidget->setEnabled(true); ui_.progressBar->hide(); return; } else { ui_.tabWidget->setEnabled(false); ui_.progressBar->show(); QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::information(this, tr("Unable to open file"), file.errorString()); file.close(); ui_.tabWidget->setEnabled(true); ui_.progressBar->hide(); return; } //clear all the scene before loading all the new points from the file!! clearAllPoints_slot(); ROS_INFO_STREAM("Opening the file: "<<fileName.toStdString()); std::ifstream fin(fileName.toStdString().c_str()); YAML::Node doc; #ifdef HAVE_NEW_YAMLCPP doc = YAML::Load(fin); #else YAML::Parser parser(fin); parser.GetNextDocument(doc); #endif //define double for percent of completion double percent_complete; int end_of_doc = doc.size(); for (size_t i = 0; i < end_of_doc; i++) { std::string name; geometry_msgs::Pose pose; tf::Transform pose_tf; double x,y,z,rx, ry, rz; doc[i]["name"] >> name; doc[i]["point"][0] >> x; doc[i]["point"][1] >> y; doc[i]["point"][2] >> z; doc[i]["point"][3] >> rx; doc[i]["point"][4] >> ry; doc[i]["point"][5] >> rz; rx = DEG2RAD(rx); ry = DEG2RAD(ry); rz = DEG2RAD(rz); pose_tf = tf::Transform(tf::createQuaternionFromRPY(rx,ry,rz),tf::Vector3(x,y,z)); percent_complete = (i+1)*100/end_of_doc; ui_.progressBar->setValue(percent_complete); Q_EMIT addPoint(pose_tf); } ui_.tabWidget->setEnabled(true); ui_.progressBar->hide(); } }
int main() { using namespace std; YAML::Node allNode = YAML::LoadFile("spells.yaml"); // YAML::Node allNode = YAML::LoadFile("gameYaml/spells.yaml"); YAML::Node spellsNode = allNode["defense"]; string effect; string mana; string name; string minLevel; string duration; string hitchar; string hitvict; for(int i = 0; (unsigned)i < spellsNode.size(); i++) { mana = " "; name = " "; minLevel = " "; duration = " "; if (spellsNode[i]["Effect"]){ effect = spellsNode[i]["Effect"].as<string>(); } else { effect = "No effect"; } if (spellsNode[i]["Hitchar"]){ hitchar = spellsNode[i]["Hitchar"].as<string>(); } else { hitchar = "No Hitchar"; } if (spellsNode[i]["Hitvict"]){ hitvict = spellsNode[i]["Hitvict"].as<string>(); } else { hitvict = "No Hitvict"; } if (spellsNode[i]["Duration"]){ duration = spellsNode[i]["Duration"].as<string>(); } else { duration = "No Duration"; } if (spellsNode[i]["MinLevel"]){ minLevel = spellsNode[i]["MinLevel"].as<string>(); } else { minLevel = "No minLevel"; } mana = spellsNode[i]["Mana"].as<string>(); name = spellsNode[i]["Name"].as<string>(); cout << "----DEFENSE SPELLS " << " -----" << endl; cout << "Name:" << name << endl << endl; cout << "Hitvict: " << hitchar << endl << endl; cout << "Hitchar: " << hitvict << endl << endl; cout << "Mana: " << mana << endl << endl; cout << "Effect: " << effect << endl << endl; cout << "minLevel: " << minLevel << endl << endl; cout << "duration: " << duration << endl << endl; } return 0; }