int main(int argc, char **argv) { if (argc < 2 || argv[1][0] == '-') { cerr << "Usage: " << argv[0] << " <TPIE_stream_input> [<MBR_output_file>]" << endl << "(if the output file name is missing, the .mbr extension is added to the input file name)" << endl; exit(-1); } char *output_filename = new char[strlen(argv[1])+5]; if (argc == 3 && argv[2][0] != '-') { strcpy(output_filename, argv[2]); } else { strcpy(output_filename, argv[1]); strcat(output_filename, ".mbr"); } cerr << "Working..."; AMI_STREAM<rectangle> input_stream(argv[1], AMI_READ_STREAM); input_stream.persist(PERSIST_PERSISTENT); cerr << "Stream length : " << input_stream.stream_len() << endl; MBRScanner scan(output_filename); AMI_scan(&input_stream, &scan); cerr << "done." << endl; }
text_generator::text_generator(std::string input_file) : words_number(0) { std::ifstream input_stream(input_file.c_str()); std::string line; const char space_delimeter = ' '; while (getline(input_stream, line)) { std::istringstream line_stream(line); std::string word; while (getline(line_stream, word, space_delimeter)) { word.erase(std::remove_if(word.begin(), word.end(), [](char c) { return std::ispunct(c) || !std::isprint(c); }), word.end()); if (word.length()) { std::map<std::string, long long>::iterator it = words_frequency.find(word); if (it != words_frequency.end()) { it->second++; } else { words_frequency.insert(std::pair<std::string, long long>(word, 1)); } words_number++; } } } double cur_border = 0; for (auto &map_entry : words_frequency) { std::string word = map_entry.first; long long frequency = map_entry.second; double probability = ((double) frequency) / words_number; words_probability.insert(std::pair<double, std::string>(cur_border + probability, word)); cur_border += probability; } }
TensorStream* TensorStream::FromFile(std::string path, std::vector<unsigned int> class_colors) { std::string listtensor_regex = "list:.*;.*;.*;.*"; #ifdef BUILD_BOOST bool is_listtensor = boost::regex_match(path, boost::regex(listtensor_regex, boost::regex::extended)); #else bool is_listtensor = std::regex_match(path, std::regex(listtensor_regex, std::regex::extended)); #endif if(is_listtensor) { LOGDEBUG << "Is list tensor, loading..."; ListTensorStream* lts = new ListTensorStream(class_colors); lts->LoadFile(path); return lts; } std::ifstream input_stream(path, std::ios::in | std::ios::binary); if(!input_stream.good()) { FATAL("Cannot open file: " << path); } uint64_t magic = 0; input_stream.read((char*)&magic, sizeof(uint64_t)/sizeof(char)); input_stream.close(); if(magic == CN24_CTS_MAGIC) { LOGDEBUG << "Is compressed tensor, loading..."; CompressedTensorStream* cts = new CompressedTensorStream(); cts->LoadFile(path); return cts; } else { LOGDEBUG << "Is float tensor, loading..."; FloatTensorStream* fts = new FloatTensorStream(); fts->LoadFile(path); return fts; } }
void MyFrame::OnLoad(wxCommandEvent& event) { wxFileDialog openFileDialog(this, L"打开发票文件", "", "", L"文本文件(*.txt)|*.txt", wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (openFileDialog.ShowModal() == wxID_CANCEL) return; std::ifstream input_stream(openFileDialog.GetPath().ToStdString(), std::ifstream::binary); if (!input_stream) return; input_stream.seekg(0, input_stream.end); int length = input_stream.tellg(); input_stream.seekg(0, input_stream.beg); char * buffer = new char [length]; input_stream.read (buffer,length); if (!input_stream) std::cout << L"错误: 只读取了" << input_stream.gcount() << L" 字节"; this->invoice_list->SetValue(buffer); input_stream.close(); delete[] buffer; }
bool PdfPlugin::LoadDoc(cpcl::IOStream *input, plcl::Doc **r) { cpcl::IOStream *input_ = input->Clone(); if (!input_) { cpcl::Error(cpcl::StringPieceFromLiteral("PdfPlugin::LoadDoc(): IOStream::Clone() fails")); return false; } std::tr1::shared_ptr<cpcl::IOStream> input_guard(input_); if (!CheckHeader(input_guard.get())) return false; input_guard->Seek(0, SEEK_SET, NULL); GooString *owner_pw(0), *user_pw(0); Object obj; obj.initNull(); std::auto_ptr<BaseStream> input_stream(new WrapperStream(input_guard, 0, gFalse, 0, &obj)); std::auto_ptr<PDFDoc> doc(new PDFDoc(input_stream.get(), owner_pw, user_pw)); // if ctor throw, then PDFDoc.dtor i.e. ~PDFDoc() {...} NOT called, so no delete input_stream, and its safe input_stream.release(); if (doc->isOk() != gTrue) { cpcl::Error(cpcl::StringPieceFromLiteral("PdfPlugin::LoadDoc(): unable to open pdf document")); return false; } std::auto_ptr<PdfDoc> pdf_doc(new PdfDoc(doc->getNumPages())); pdf_doc->doc.reset(doc.release()); // also because class use dynamic resources, its safe to release pointer, but not pass in ctor // because ctor may fail for example if memory allocation fails, and in that case resources become abadoned // yeah, BUT if pass reference to auto_ptr, then ownership transfered only AFTER memory allocation to object and BEFORE user ctor // so, if memory allocation fails, then ownership not yet transfered and auto_ptr<> doc free resources // in other case, if user ctor failed, then ownership transfered to auto_ptr<> PdfDoc::doc, and all constructed class fields be deleted, without user dtor(that not called anyway) if (r) *r = pdf_doc.release(); return true; }
adobe::dictionary_t parse_input_dictionary(const bfs::path& input_path) { std::string path_str(input_path.native_file_string()); std::ifstream input_stream(path_str.c_str()); adobe::array_t token_stream; adobe::virtual_machine_t vm; if (!adobe::expression_parser(input_stream, adobe::line_position_t("input_dictionary")).is_expression(token_stream)) return adobe::dictionary_t(); vm.evaluate(token_stream); const adobe::dictionary_t result(vm.back().cast<adobe::dictionary_t>()); vm.pop_back(); std::cout << "--" << std::endl << "Initializing sheet with the following input dictionary: " << adobe::begin_asl_cel << result << adobe::end_asl_cel << std::endl << "--" << std::endl; return result; }
unsigned int FloatTensorStream::LoadFile(std::string path) { std::ifstream input_stream(path, std::ios::binary | std::ios::in); if(!input_stream.good()) { FATAL("Cannot open file: " << path); } #ifdef BUILD_POSIX int input_fd = open(path.c_str(), O_RDONLY); if(input_fd < 0) { FATAL("Cannot open file: " << path); } #endif // Go through file std::cout << std::endl << std::flush; while (!input_stream.eof()) { Tensor* tensor = new Tensor(); #ifdef BUILD_POSIX tensor->Deserialize (input_stream, false, true, input_fd); #else tensor->Deserialize (input_stream, false); #endif if (tensor->elements() == 0) break; tensors_.push_back(tensor); std::cout << "." << std::flush; input_stream.peek(); } return 0; }
bool SocketToTF::updateTransformFromSocketTransform(zmq::message_t& message) { socket_to_tf::TransformStamped transform; boost::iostreams::basic_array_source<char> source((char*)message.data(), message.size()); boost::iostreams::stream<boost::iostreams::basic_array_source <char> > input_stream(source); boost::archive::binary_iarchive ia(input_stream); ia >> transform; if (boost::math::isfinite(transform.x) && boost::math::isfinite(transform.y) && boost::math::isfinite(transform.z) && boost::math::isfinite(transform.qx) && boost::math::isfinite(transform.qy) && boost::math::isfinite(transform.qz) && boost::math::isfinite(transform.qw)) { transform_stamped_.transform.translation.x = transform.x; transform_stamped_.transform.translation.y = transform.y; transform_stamped_.transform.translation.z = transform.z; transform_stamped_.transform.rotation.x = transform.qx; transform_stamped_.transform.rotation.y = transform.qy; transform_stamped_.transform.rotation.z = transform.qz; transform_stamped_.transform.rotation.w = transform.qw; transform_stamped_.child_frame_id = transform.source_frame; transform_stamped_.header.frame_id = transform.target_frame; transform_stamped_.header.stamp.sec = transform.timestamp_seconds; transform_stamped_.header.stamp.nsec = transform.timestamp_nanoseconds; std::stringstream ss_data; ss_data << "{ " << transform.x << " " << transform.y << " " << transform.z << " " << transform.qx << " " << transform.qy << " " << transform.qz << " " << transform.qw << " " << transform.source_frame << " " << transform.target_frame << " }"; std::string transform_data = ss_data.str(); ROS_INFO_STREAM("Received message with size " << message.size() << ": " << transform_data); return true; } return false; }
void parseSeqs(string filename, SeqSet &data) { ifstream input; SeqStream input_stream(openSeqFile(filename, input)); if(!input_stream.good()) { throw("File stream is in a bad state"); } string format = guessFormat(input_stream); if(format == "fasta") { try { parseFasta(input_stream, filename, data); } catch(...) { input.close(); throw; } } else if(format == "fastq") { try { parseFastq(input_stream, filename, data); } catch(...) { input.close(); throw; } } else { input.close(); throw("Unrecognized format"); } input.close(); }
void ScoreArray::load(const string &file) { TRACE_ERR("loading data from " << file << endl); inputfilestream input_stream(file); // matches a stream with a file. Opens the file istream* is = &input_stream; load(is); input_stream.close(); }
int json_test() { hbc::file_input_stream input_stream("json/watch_on_mobile.json"); hbc::json_pull parser(&input_stream); parse_objects(parser, 0); return 0; }
znModel::znModel() : m_ini_file(NULL) { // Use ini file to save all user settings. wxString folder = wxStandardPaths::Get().GetAppDocumentsDir() + wxFileName::GetPathSeparator() + "Zailor" + wxFileName::GetPathSeparator(); wxFileName::Mkdir(folder, 0777, wxPATH_MKDIR_FULL); m_ini_file_name = wxStandardPaths::Get().GetExecutablePath(); m_ini_file_name = folder + wxFileName(m_ini_file_name).GetName() + wxT(".ini"); if (::wxFileExists(m_ini_file_name) == true) { // An ini file is found, it has been created before. // Read its content. wxFileInputStream input_stream(m_ini_file_name); if (input_stream.IsOk() == true) { m_ini_file = new wxFileConfig(input_stream); // The ini file has been read correctly. // Initialize the missing options if any. for (std::map<int, znIniProperty>::const_iterator iter = g_ini_property.begin(); iter != g_ini_property.end(); iter++) { int key = iter->first; znIniProperty value = iter->second; if (m_ini_file->Exists(value.m_name) == false) { // The option is missing from the existing ini file. // Probably a newly added option. // Set it to its default value. SetUserOption(key, value.m_default_value); } } } } if (m_ini_file == NULL) { // No valid ini file is found. // Create a new one. m_ini_file = new wxFileConfig(); // Set initial values for all the options since the ini file has been newly created. for (std::map<int, znIniProperty>::iterator iter = g_ini_property.begin(); iter != g_ini_property.end(); iter++) { int key = iter->first; znIniProperty value = iter->second; SetUserOption(key, value.m_default_value); } } }
GraphEdgeCostsIF * InputUtils::impl::RAM::GR::readCosts( char const * const filename, std::string const & scenarioName) throw (IOExceptions::FileNotFountException) { GraphEdgeCostsIF * graphCosts { }; EdgeCount numberOfEdgeCosts { }; std::size_t fileSize { }; char buffer[IOUtils::impl::BUFFER_SIZE] { }; try { boost::interprocess::file_mapping mappedFile(filename, boost::interprocess::read_only); boost::interprocess::mapped_region mappedRegionOfFile(mappedFile, boost::interprocess::read_only); fileSize = mappedRegionOfFile.get_size(); boost::interprocess::bufferstream input_stream( static_cast<char*>(mappedRegionOfFile.get_address()), fileSize); while (!input_stream.eof()) { switch (input_stream.get()) { case IOUtils::impl::GR::COMMENT_LINE_NUMERIC: INFO_NOARG(logger, LogBundleKey::IOU_IGNORING_COMMENT_LINE_WHILE_READING) ; input_stream.ignore(IOUtils::impl::MAX_STREAM_SIZE, '\n'); break; case IOUtils::impl::GR::PROBLEM_DEF_LINE_NUMERIC: input_stream.getline(buffer, IOUtils::impl::MAX_CHARS_IN_LINE); numberOfEdgeCosts = InputUtils::impl::RAM::GR::getNumberOfEdgeCosts(buffer); graphCosts = new GraphEdgeCostsImpl { numberOfEdgeCosts, scenarioName, false }; break; case IOUtils::impl::GR::ARC_DEF_LINE_NUMERIC: input_stream.getline(buffer, IOUtils::impl::MAX_CHARS_IN_LINE); graphCosts->push_back( InputUtils::impl::RAM::GR::getCost(buffer)); break; default: WARN_NOARG(logger, LogBundleKey::IOU_IGNORING_UNRECOGNISED_LINE_WHILE_READING) ; break; } } INFO(logger, LogBundleKey::IOU_END_OF_READ_COSTS, filename, LogStringUtils::edgeCostSetDescription(graphCosts, "\t").c_str()); return graphCosts; } catch (boost::interprocess::interprocess_exception& e) { throw IOExceptions::FileNotFountException(filename); } }
bool SocketToTF::updateTransformFromSocketPointTranslation(zmq::message_t& message) { socket_to_tf::PointTranslation point_translation; if (use_boost_to_parse_point_translation_message_) { boost::iostreams::basic_array_source<char> source((char*)message.data(), message.size()); boost::iostreams::stream<boost::iostreams::basic_array_source <char> > input_stream(source); boost::archive::binary_iarchive ia(input_stream); ia >> point_translation; } else {
bool CSerialEntityXML::LoadFromXml(const char *pFileName) { bool ret; char *buffer(new char[BUFSIZ]); try { XML_Parser xml_parser; std::ifstream input_stream(pFileName); std::streamsize len; int done; CSerialEntityXML *pUserDataEnt(this); if (input_stream.is_open()) { try { xml_parser = XML_ParserCreate(NULL); try { XML_SetUserData(xml_parser, &pUserDataEnt); XML_SetElementHandler(xml_parser, XmlElementStart, XmlElementEnd); input_stream.seekg(0, input_stream.beg); do { input_stream.read(buffer, BUFSIZ); len = input_stream.gcount(); done = len < BUFSIZ; if (XML_Parse(xml_parser, buffer, (int)len, done) == XML_STATUS_ERROR) { throw new ExceptionSerialization(D_E_ID_ERR_SERIAL, "Xml·ÖÎö³ö´í£¡"); } } while (!done); } catch (...) { XML_ParserFree(xml_parser); throw; } XML_ParserFree(xml_parser); } catch(...) { input_stream.close(); throw; } input_stream.close(); ret = true; } else ret = false; } catch(...) { delete [] buffer; throw; } delete [] buffer; return ret; }
int main () { std::cout << "Basic EmbeddedTime testing" << std::endl; std::cout << std::endl; std::cout << "Testing constructors..." << std::endl; Time _t1; Time _t2(1, 23, 30, 300); Time _t2bis(0, 23, 30, 300); Time _t3(1, 23, 30, 300, 500); Time _t4("01:23:30:300"); Time _t5(_t3); std::cout << std::endl; std::cout << "Testing operators..." << std::endl; std::cout << (_t2 - _t2bis) << std::endl; std::cout << (_t2 + _t2bis) << std::endl; _t1 = _t4; std::cout << _t1 << std::endl; std::cout << (_t4 == _t2) << std::endl; std::cout << (_t4 != _t2) << std::endl; std::cout << (_t2 < _t2bis) << std::endl; std::cout << std::endl; std::ifstream input_stream("input.ev"); Time t; int a; input_stream >> t >> a; assert(t.hours() == 1); assert(t.minutes() == 59); assert(t.seconds() == 59); assert(t.mseconds() == 37); assert(a = 42); while (input_stream >> t >> a) { std::cout << "reading line" << std::endl; assert(t.hours() == 2); assert(t.minutes() == 42); assert(t.seconds() == 42); assert(t.mseconds() == 42); assert(a = 42); } std::cout << "Testing realtime..." << std::endl; Time::initializeTimer(); Time t1 = Time::currentTime(); sleep(1); Time t2 = Time::currentTime(); sleep(1); Time t3 = Time::currentTime(); std::cout << "Current time and difference with the previous" << std::endl; std::cout << t1 << std::endl; std::cout << t2 << ": " << (t2 - t1) << std::endl; std::cout << t3 << ": " << (t3 - t2) << std::endl; return 0; }
GraphIF * InputUtils::impl::RAM::VA::readGraph(char const * const filename) throw (IOExceptions::FileNotFountException) { GraphIF * graph { }; EdgeCount idxEdgeCounter { }; std::size_t fileSize { }; char* buffer { }; rapidjson::Document jsonDoc { }; rapidjson::Value::MemberIterator vertexList { }; rapidjson::Value::MemberIterator edgeList { }; rapidjson::Value::MemberIterator endValue { }; rapidjson::Value::ConstMemberIterator it { }; try { boost::interprocess::file_mapping mappedFile(filename, boost::interprocess::read_only); boost::interprocess::mapped_region mappedRegionOfFile(mappedFile, boost::interprocess::read_only); fileSize = mappedRegionOfFile.get_size(); boost::interprocess::bufferstream input_stream( static_cast<char*>(mappedRegionOfFile.get_address()), fileSize); jsonDoc.Parse(input_stream.buffer().first); endValue = jsonDoc.MemberEnd(); vertexList = jsonDoc.FindMember(IOUtils::impl::VA::VERTEX_LIST_KEY); if (vertexList != endValue) { edgeList = jsonDoc.FindMember(IOUtils::impl::VA::EDGE_LIST_KEY); if (edgeList != endValue) { graph = InputUtils::impl::RAM::VA::createGraph( vertexList->value, edgeList->value.MemberCount()); idxEdgeCounter = 0; it = edgeList->value.MemberEnd(); for (rapidjson::Value::ConstMemberIterator itBegin = edgeList->value.MemberBegin(); itBegin != it; ++itBegin) { InputUtils::impl::RAM::VA::addEdge(idxEdgeCounter, itBegin, graph); idxEdgeCounter += 1; } } } INFO(logger, LogBundleKey::IOU_END_OF_READ, filename, LogStringUtils::graphDescription(graph, "\t").c_str()); return graph; } catch (boost::interprocess::interprocess_exception& e) { throw IOExceptions::FileNotFountException(filename); } }
GraphIF * InputUtils::impl::RAM::GR::readGraph(char const * const filename) throw (IOExceptions::FileNotFountException) { GraphIF * graph { }; EdgeCount idxEdgeCounter { }; std::size_t fileSize { }; char buffer[IOUtils::impl::BUFFER_SIZE] { }; try { boost::interprocess::file_mapping mappedFile(filename, boost::interprocess::read_only); boost::interprocess::mapped_region mappedRegionOfFile(mappedFile, boost::interprocess::read_only); fileSize = mappedRegionOfFile.get_size(); boost::interprocess::bufferstream input_stream( static_cast<char*>(mappedRegionOfFile.get_address()), fileSize); while (!input_stream.eof()) { switch (input_stream.get()) { case IOUtils::impl::GR::COMMENT_LINE_NUMERIC: INFO_NOARG(logger, LogBundleKey::IOU_IGNORING_COMMENT_LINE_WHILE_READING) ; input_stream.ignore(IOUtils::impl::MAX_STREAM_SIZE, '\n'); break; case IOUtils::impl::GR::PROBLEM_DEF_LINE_NUMERIC: input_stream.getline(buffer, IOUtils::impl::MAX_CHARS_IN_LINE); graph = InputUtils::impl::RAM::GR::createGraph(buffer); idxEdgeCounter = 0; break; case IOUtils::impl::GR::ARC_DEF_LINE_NUMERIC: input_stream.getline(buffer, IOUtils::impl::MAX_CHARS_IN_LINE); InputUtils::impl::RAM::GR::addEdge(idxEdgeCounter, buffer, graph); idxEdgeCounter += 1; break; default: WARN_NOARG(logger, LogBundleKey::IOU_IGNORING_UNRECOGNISED_LINE_WHILE_READING) ; break; } } INFO(logger, LogBundleKey::IOU_END_OF_READ, filename, LogStringUtils::graphDescription(graph, "\t").c_str()); return graph; } catch (boost::interprocess::interprocess_exception& e) { throw IOExceptions::FileNotFountException(filename); } }
shared_ptr<Event> IPCEventTransport::deserializeEvent(message_queue_size_type& received_size){ string incoming_data(receive_buffer, received_size); std::istringstream input_stream(incoming_data); iarchive serialized_archive(input_stream); shared_ptr<Event> event; serialized_archive >> event; return event; }
void FeatureData::load(const string &file) { TRACE_ERR("loading feature data from " << file << endl); inputfilestream input_stream(file); // matches a stream with a file. Opens the file if (!input_stream) { throw runtime_error("Unable to open feature file: " + file); } istream* is = &input_stream; load(is); input_stream.close(); }
void FFM::loadModel(std::string inputDir) { std::ifstream input_stream((char*)(inputDir + "bw.csv").c_str(), std::ios::out); std::string tmp; int count = 0; while ( input_stream >> tmp ) { W[count] = atof(tmp.c_str()); count++; } input_stream.close(); }
void CNetScheduleJobSerializer::LoadJobInput(const string& source_file) { CNcbiIfstream input_stream(source_file.c_str(), CNcbiIfstream::binary); if (input_stream.fail() && !input_stream.eof()) { NCBI_THROW_FMT(CIOException, eRead, "Error while reading job input from '" << source_file << '\''); } string header; getline(input_stream, header); CAttrListParser attr_parser; attr_parser.Reset(header); CAttrListParser::ENextAttributeType attr_type; CTempString attr_name; string attr_value; size_t attr_column; #define ATTR_POS " at column " << attr_column while ((attr_type = attr_parser.NextAttribute(&attr_name, &attr_value, &attr_column)) != CAttrListParser::eNoMoreAttributes) { if (attr_name == "affinity") m_Job.affinity = attr_value; else if (attr_name == "group") m_Job.group = attr_value; else if (attr_name == "exclusive") { m_Job.mask = CNetScheduleAPI::eExclusiveJob; continue; } else { NCBI_THROW_FMT(CArgException, eInvalidArg, "unknown attribute '" << attr_name << "'" ATTR_POS); } if (attr_type != CAttrListParser::eAttributeWithValue) { NCBI_THROW_FMT(CArgException, eInvalidArg, "attribute '" << attr_name << "' requires a value" ATTR_POS); } } if (!input_stream.eof()) { CStringOrBlobStorageWriter job_input_writer( numeric_limits<size_t>().max(), NULL, m_Job.input); CWStream job_input_ostream(&job_input_writer, 0, NULL); NcbiStreamCopy(job_input_ostream, input_stream); } CDirEntry file_name(source_file); m_Job.job_id = file_name.GetBase(); }
int main (int argc, char* argv[]) { std::string input_str; std::getline(std::cin, input_str); std::istringstream input_stream(input_str); std::vector<std::string> string_to_sort; std::vector<int> int_to_sort; std::vector<bool> is_integer; while (input_stream) { std::string str_token; int int_token = 0; input_stream >> str_token; if (((int_token = atoi(str_token.c_str()))!= 0)|| str_token == "0")// if the token is actually an integer { int_to_sort.push_back(int_token); is_integer.push_back(true); } else { string_to_sort.push_back(str_token); is_integer.push_back(false); } if (input_stream.eof()) { break; } } std::sort(string_to_sort.begin(),string_to_sort.end()); std::sort(int_to_sort.begin(), int_to_sort.end()); std::vector<bool>::iterator bool_it = is_integer.begin(); do { if (*bool_it) { std::cout<<int_to_sort.front(); int_to_sort.erase(int_to_sort.begin()); } else { std::cout<<string_to_sort.front(); string_to_sort.erase(string_to_sort.begin()); } ++bool_it; if (bool_it != is_integer.end()) { std::cout<<" "; } }while (bool_it != is_integer.end()); }
void PolicyEditor::loadFile(QString file_name){ QFile file(file_name); if (!file.open(QIODevice::ReadOnly)) return; QTextStream input_stream(&file); QString text = input_stream.readAll(); file.close(); _loadingFile = true; setPlainText(text); setFile(file_name); _loadingFile = false; }
TEST_F(TextFormatTest, ParseStringEscape) { // Create a parse string with escpaed characters in it. string parse_string = "optional_string: " + kEscapeTestStringEscaped + "\n"; io::ArrayInputStream input_stream(parse_string.data(), parse_string.size()); TextFormat::Parse(&input_stream, &proto_); // Compare. EXPECT_EQ(kEscapeTestString, proto_.optional_string()); }
void TEST_ArchiveType(const DataType &datum, const std::string &data_name, const std::string &archive_name, int flags = boost::archive::no_header) { std::cout << data_name << ": " << std::setw(9) << archive_name << " ---> " << std::flush; try { std::string datum_saved; try { try { std::ostringstream output_stream; SaveArchive s_archive(output_stream, flags); s_archive & boost::serialization::make_nvp("MLBTest", datum); datum_saved.assign(output_stream.str()); } catch (const std::exception &except) { ThrowException("Serialization save attempt failed: " + std::string(except.what())); } DataType datum_loaded; try { std::istringstream input_stream(datum_saved); LoadArchive l_archive(input_stream, flags); l_archive & boost::serialization::make_nvp("MLBTest", datum_loaded); } catch (const std::exception &except) { ThrowException("Serialization load attempt failed: " + std::string(except.what())); } if ((datum < datum_loaded) || (datum_loaded < datum)) { std::ostringstream o_str; o_str << "Comparison of original data (" << datum << ") with loaded " "result of serialization (" << datum_loaded << ") revealed " "differences."; ThrowException(o_str.str()); } } catch (const std::exception &except) { Rethrow(except, "Failure in regression test for boost::serialization " "of type '" + data_name + "' with serialization archive type '" + archive_name + "': " + std::string(except.what())); } std::cout << "OK (serialized size = " << static_cast<unsigned int>(datum_saved.size()) << ")" << std::endl; } catch (const std::exception &except) { std::cout << "FAILED: " << except.what() << std::endl; throw; } }
GraphEdgeCostsIF * InputUtils::impl::RAM::VA::readCosts( char const * const filename, std::string const & scenarioName) throw (IOExceptions::FileNotFountException) { GraphEdgeCostsIF * graphCosts { }; std::size_t fileSize { }; char* buffer { }; rapidjson::Document jsonDoc { }; rapidjson::Value::MemberIterator edgeList { }; rapidjson::Value::MemberIterator endValue { }; rapidjson::Value::ConstMemberIterator it { }; try { boost::interprocess::file_mapping mappedFile(filename, boost::interprocess::read_only); boost::interprocess::mapped_region mappedRegionOfFile(mappedFile, boost::interprocess::read_only); fileSize = mappedRegionOfFile.get_size(); boost::interprocess::bufferstream input_stream( static_cast<char*>(mappedRegionOfFile.get_address()), fileSize); jsonDoc.Parse(input_stream.buffer().first); edgeList = jsonDoc.FindMember(IOUtils::impl::VA::EDGE_LIST_KEY); if (edgeList != endValue) { graphCosts = new GraphEdgeCostsImpl { (EdgeCount) edgeList->value.MemberCount(), scenarioName, false }; it = edgeList->value.MemberEnd(); for (rapidjson::Value::ConstMemberIterator itBegin = edgeList->value.MemberBegin(); itBegin != it; ++itBegin) { graphCosts->push_back( InputUtils::impl::RAM::VA::getCost(itBegin)); } } INFO(logger, LogBundleKey::IOU_END_OF_READ_COSTS, filename, LogStringUtils::edgeCostSetDescription(graphCosts, "\t").c_str()); return graphCosts; } catch (boost::interprocess::interprocess_exception& e) { throw IOExceptions::FileNotFountException(filename); } }
TEST_F(TextFormatTest, ParseFloatWithSuffix) { // Test that we can parse a floating-point value with 'f' appended to the // end. This is needed for backwards-compatibility with proto1. // Have it parse a float with the 'f' suffix. string parse_string = "optional_float: 1.0f\n"; io::ArrayInputStream input_stream(parse_string.data(), parse_string.size()); TextFormat::Parse(&input_stream, &proto_); // Compare. EXPECT_EQ(1.0, proto_.optional_float()); }
TEST_F(TextFormatTest, OptionalColon) { // Test that we can place a ':' after the field name of a nested message, // even though we don't have to. string parse_string = "optional_nested_message: { bb: 1}\n"; io::ArrayInputStream input_stream(parse_string.data(), parse_string.size()); TextFormat::Parse(&input_stream, &proto_); // Compare. EXPECT_TRUE(proto_.has_optional_nested_message()); EXPECT_EQ(1, proto_.optional_nested_message().bb()); }
TEST_F(TextFormatTest, Comments) { // Test that comments are ignored. string parse_string = "optional_int32: 1 # a comment\n" "optional_int64: 2 # another comment"; io::ArrayInputStream input_stream(parse_string.data(), parse_string.size()); TextFormat::Parse(&input_stream, &proto_); // Compare. EXPECT_EQ(1, proto_.optional_int32()); EXPECT_EQ(2, proto_.optional_int64()); }