int main(){ time_t t; srand((unsigned)(2)); int n=5; pid_t child[5]; int i,k,m,response[5]; int fd1[5][2],fd2[5][2]; int random_no,element; /*creating 2 pipes followed by fork to provide 2 pipes between each parent and child pair and then loading the child.c file into each child fd1 is file descriptor for parent->child pipe fd2 is file descriptor for child->parent pipe index 0 => reading endfile descriptor index 1 => writing end file descriptor*/ for(i=0;i<5;i++){ while(pipe(fd1[i])!=0) perror("ERROR "); while(pipe(fd2[i])!=0) perror("ERROR "); child[i]=fork(); if(child[i]==0){ char *argv[8]; int j; for (j = 0; j < 7; j++) argv[j]=(char*)malloc(11*sizeof(char)); sprintf(argv[0],"%s","child"); sprintf(argv[1],"%s","child"); sprintf(argv[2],"%s%d%s","data_",i+1,".txt"); sprintf(argv[3],"%d",fd1[i][0]); sprintf(argv[4],"%d",fd1[i][1]); sprintf(argv[5],"%d",fd2[i][0]); sprintf(argv[6],"%d",fd2[i][1]); argv[7]=NULL; if(execv(argv[0],argv)==-1) perror("ERROR "); } } //closing unused ends of pipe for(i=0;i<5;i++){ close(fd1[i][0]); close(fd2[i][1]); } //alloting id's to the children for(i=0;i<5;i++){ char buf[MAX]; sprintf(buf,"%d",i+1); writer(fd1[i],buf); } //waiting to receive READY signal from children for(i=0;i<5;i++){ char buf[MAX]; reader(fd2[i],buf); } printf("Parent READY\n"); k=(n%2==0)?(n*5)/2-1:(n*5+1)/2-1; // finding median while(1){ // randomly asking for a pivot element from a child do{ char bufr[MAX]; random_no = rand()%5; printf("Parent sends REQUEST to child %d\n",random_no+1); sprintf(bufr,"%d",REQUEST); writer(fd1[random_no],bufr); char bufw[MAX]; reader(fd2[random_no],bufw); element=atoi(bufw); printf("Parent receives PIVOT %d from child %d\n",element,random_no+1); }while(element==-1); //sending pivot element to each child printf("Parent broadcasts PIVOT %d to all children\n",element); for(i=0;i<5;i++){ char buf[MAX],sig[MAX]; sprintf(buf,"%d",element); sprintf(sig,"%d",PIVOT); writer(fd1[i],sig); writer(fd1[i],buf); } //finding total no of elements larger than the current pivot among all the children m=0; for(i=0;i<5;i++){ char buf[MAX]; reader(fd2[i],buf); response[i]=atoi(buf); m+=response[i]; } /*m>k => no of elements larger than pivot is >k => we need to consider only those elements which are larger than current pivot so parent sends SMALL signal to children asking them to drop elements smaller than current pivot*/ if(m>k){ char sig[MAX]; sprintf(sig,"%d",SMALL); for(i=0;i<5;i++) writer(fd1[i],sig); } /*m<k => no of elements larger than pivot is <k => we need to consider only those elements which are smaller than current pivot so parent sends LARGE signal to children asking them to drop elements larger than current pivot*/ else if(m<k){ char sig[MAX]; sprintf(sig,"%d",LARGE); for(i=0;i<5;i++) writer(fd1[i],sig); k-=m; //break; } // parent detects that the current pivot is required median. It sends terminating signal to each child else{ printf("Parent: m=%d+%d+%d+%d+%d = %d , %d is median\n",response[0],response[1],response[2],response[3],response[4],m,element); printf("Parent sends kill signals to all children\n"); break; } // READY signal for synchronization for(i=0;i<5;i++){ char buf[MAX]; reader(fd2[i],buf); } } sleep(1); for(i=0;i<5;i++) kill(child[i],SIGINT); for(i=0;i<5;i++) wait(); //close all pipes for(i=0;i<5;i++){ close(fd1[i][0]); close(fd1[i][1]); close(fd2[i][0]); close(fd2[i][1]); } return 0; }
/** * @brief SDSMemoryNode::reciveMns * @param mns */ void SDSMemoryNode::reciveMns(char * message){ cout<<message<<endl; Document doc; doc.ParseInsitu(message); if(doc.IsObject()){ if(doc.HasMember("protocolo")){ if(doc["protocolo"].IsString()){ string comando; comando=doc["protocolo"].GetString(); if(comando=="d_calloc"){ if(doc.HasMember("pSize")){ if(doc["pSize"].IsInt()){ int pSize= doc["pSize"].GetInt(); d_calloc(pSize); } } } else if(comando=="d_status"){ d_status(); } else{ d_pointer_size pointerSize; if(doc.HasMember("dir")){ if(doc["dir"].IsInt()){ int pDir= doc["dir"].GetInt(); pointerSize.pointer.dirMemory=pDir; } } if(doc.HasMember("pSize")){ if(doc["pSize"].IsInt()){ int pSize= doc["pSize"].GetInt(); pointerSize.bytes=pSize; } } if(comando=="d_free"){ d_free(pointerSize); } else{ //Documento para en caso de que se quiera obtener el dato StringBuffer s; Writer<StringBuffer> writer(s); writer.StartObject(); writer.String("dato"); int status; bystream statusBystream; if(doc.HasMember("tipo")){ if(doc["tipo"].IsString()){ string tipo= doc["tipo"].GetString(); if(tipo=="char"){ if(comando=="d_set"){ if(doc.HasMember("dato")){ if(doc["dato"].IsString()){ //Parsear a char char pData =*(const_cast<char *>(doc["dato"].GetString())); status= Manejador.setearDatoChar(pointerSize,pData); } } } if(comando=="d_get"){ statusBystream=Manejador.obtenerDatoChar(pointerSize); writer.String(&(statusBystream.datachar)); } } else if(tipo=="int"){ if(comando=="d_set"){ if(doc.HasMember("dato")){ if(doc["dato"].IsInt()){ //Parsear a int int pData =doc["dato"].GetInt(); status= Manejador.setearDatoInt(pointerSize,pData); } } } if(comando=="d_get"){ statusBystream=Manejador.obtenerDatoInt(pointerSize); writer.Int(statusBystream.dataint); } } else if(tipo=="bool"){ //Parsear a bool //status= Manejador.setearDatoBool(pointerSize,pData); } else if(tipo=="float"){ //parsear a float // status= Manejador.setearDatoFloat(pointerSize,pData); } else if(tipo=="arrayint"){ //parsear a arreglo de int // status= Manejador.setearDatoArrayInt(pointerSize,pData); } else if(tipo=="arraychar"){ //Parsear a arreglos de char //status= Manejador.setearDatoArrayChar(pointerSize,pData); } else if(tipo=="long"){ //Parsear a long // status= Manejador.setearDatoLong(pointerSize,pData); } else if(tipo=="double"){ //Parsear a double // status= Manejador.setearDatoDouble(pointerSize,pData); } if(comando=="d_set"){ d_set(status); } if(comando=="d_get"){ writer.String("status"); writer.Int(statusBystream.status); writer.EndObject(); const char* mensaje=s.GetString(); cout<<"Enviando... "<<mensaje<<endl; puerto->sentMns(mensaje,client); } }} } } } } } }
int main(int argc, char* argv[]) { std::string output_filename; static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"output", required_argument, 0, 'o'}, {0, 0, 0, 0} }; while (1) { int c = getopt_long(argc, argv, "ho:", long_options, 0); if (c == -1) break; switch (c) { case 'h': print_help(); exit(return_code_ok); case 'o': output_filename = optarg; break; default: exit(return_code_fatal); } } if (output_filename.empty()) { std::cerr << "Missing -o/--output=OSMFILE option\n"; exit(return_code_cmdline); } if (optind != argc - 1) { std::cerr << "Usage: osmcoastline_filter [OPTIONS] OSMFILE\n"; exit(return_code_cmdline); } osmium::io::Header header; header.set("generator", "osmcoastline_filter"); header.add_box(osmium::Box(-180.0, -90.0, 180.0, 90.0)); osmium::io::File infile(argv[optind]); try { osmium::io::Writer writer(output_filename, header); std::set<osmium::object_id_type> ids; osmium::memory::Buffer output_buffer(10240); { osmium::io::Reader reader(infile, osmium::osm_entity_bits::way); while (auto input_buffer = reader.read()) { for (auto it = input_buffer.begin<const osmium::Way>(); it != input_buffer.end<const osmium::Way>(); ++it) { const char* natural = it->get_value_by_key("natural"); if (natural && !strcmp(natural, "coastline")) { output_buffer.add_item(*it); output_buffer.commit(); if (output_buffer.committed() >= 10240) { osmium::memory::Buffer new_buffer(10240); std::swap(output_buffer, new_buffer); writer(std::move(new_buffer)); } for (const auto& nr : it->nodes()) { ids.insert(nr.ref()); } } } } reader.close(); } { osmium::io::Reader reader(infile, osmium::osm_entity_bits::node); while (auto input_buffer = reader.read()) { for (auto it = input_buffer.begin<const osmium::Node>(); it != input_buffer.end<const osmium::Node>(); ++it) { const char* natural = it->get_value_by_key("natural"); if ((ids.find(it->id()) != ids.end()) || (natural && !strcmp(natural, "coastline"))) { output_buffer.add_item(*it); output_buffer.commit(); if (output_buffer.committed() >= 10240) { osmium::memory::Buffer new_buffer(10240); std::swap(output_buffer, new_buffer); writer(std::move(new_buffer)); } } } } reader.close(); } if (output_buffer.committed() > 0) { writer(std::move(output_buffer)); } writer.close(); } catch (osmium::io_error& e) { std::cerr << "io error: " << e.what() << "'\n"; exit(return_code_fatal); } google::protobuf::ShutdownProtobufLibrary(); }
size_t printTo(Print &print) const { JsonWriter writer(print); downcast().writeTo(writer); return writer.bytesWritten(); }
void WriterTest::testWriterOstreamConfig(void) { std::stringstream stream(""); Config config; Writer writer(stream, config); }
/* Run FabMap on a test dataset */ int openFABMAP(std::string testPath, of2::FabMap *fabmap, std::string vocabPath, std::string resultsPath, bool addNewOnly) { cv::FileStorage fs; //ensure not overwriting results std::ifstream checker; checker.open(resultsPath.c_str()); if(checker.is_open()) { std::cerr << resultsPath << ": Results already present" << std::endl; checker.close(); return -1; } //load the vocabulary std::cout << "Loading Vocabulary" << std::endl; fs.open(vocabPath, cv::FileStorage::READ); cv::Mat vocab; fs["Vocabulary"] >> vocab; if (vocab.empty()) { std::cerr << vocabPath << ": Vocabulary not found" << std::endl; return -1; } fs.release(); //load the test data fs.open(testPath, cv::FileStorage::READ); cv::Mat testImageDescs; fs["BOWImageDescs"] >> testImageDescs; if(testImageDescs.empty()) { std::cerr << testPath << ": Test data not found" << std::endl; return -1; } fs.release(); //running openFABMAP std::cout << "Running openFABMAP" << std::endl; std::vector<of2::IMatch> matches; std::vector<of2::IMatch>::iterator l; cv::Mat confusion_mat(testImageDescs.rows, testImageDescs.rows, CV_64FC1); confusion_mat.setTo(0); // init to 0's if (!addNewOnly) { //automatically comparing a whole dataset fabmap->compare(testImageDescs, matches, true); for(l = matches.begin(); l != matches.end(); l++) { if(l->imgIdx < 0) { confusion_mat.at<double>(l->queryIdx, l->queryIdx) = l->match; } else { confusion_mat.at<double>(l->queryIdx, l->imgIdx) = l->match; } } } else { //criteria for adding locations used for(int i = 0; i < testImageDescs.rows; i++) { matches.clear(); //compare images individually fabmap->compare(testImageDescs.row(i), matches); bool new_place_max = true; for(l = matches.begin(); l != matches.end(); l++) { if(l->imgIdx < 0) { //add the new place to the confusion matrix 'diagonal' confusion_mat.at<double>(i, matches.size()-1) = l->match; } else { //add the score to the confusion matrix confusion_mat.at<double>(i, l->imgIdx) = l->match; } //test for new location maximum if(l->match > matches.front().match) { new_place_max = false; } } if(new_place_max) { fabmap->add(testImageDescs.row(i)); } } } //save the result as plain text for ease of import to Matlab std::ofstream writer(resultsPath.c_str()); for(int i = 0; i < confusion_mat.rows; i++) { for(int j = 0; j < confusion_mat.cols; j++) { writer << confusion_mat.at<double>(i, j) << " "; } writer << std::endl; } writer.close(); return 0; }
int main(int argc, char **argv) { pugi::xml_document svg_xml; TCLAP::UnlabeledValueArg<std::string> svg_filename( "svg_filename", "SVG file name", true, "", "PipelineFile" ); TCLAP::UnlabeledValueArg<std::string> vtu_filename( "vtu_filename", "SVG file name", true, "", "PipelineFile" ); try { TCLAP::CmdLine cmd("SVG to vtu converter", ' ', "1.0"); cmd.add( svg_filename ); cmd.add( vtu_filename ); cmd.parse( argc, argv ); pugi::xml_parse_result result = svg_xml.load_file( svg_filename.getValue().c_str() ); if (!result) { std::cerr << "Error loading or parsing XML file " << svg_filename.getValue().c_str() << std::endl; std::cerr << "XML error: " << result.description() << std::endl; return 0; } } catch (TCLAP::ArgException &e) // catch any exceptions { std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; } MeshType mesh; pugi::xml_node svg_node = svg_xml.child("svg"); pugi::xml_node g_node = svg_node.child("g"); for (pugi::xml_node path_node = g_node.child("path"); path_node; path_node = path_node.next_sibling("path")) { std::string tmp = path_node.attribute("d").as_string(); std::cout << tmp << std::endl; PointType translate = viennagrid::make_point(0,0); pugi::xml_attribute transform_attribute = path_node.attribute("transform"); if ( !transform_attribute.empty() ) { std::string transform_str = transform_attribute.as_string(); if (transform_str.find("translate") != std::string::npos) { // std::cout << "translate x = " << ) << std::endl; // std::cout << "translate y = " << transform_str.substr( transform_str.find(",")+1, transform_str.find(")")-transform_str.find(",")-1 ) << std::endl; double x = atof( transform_str.substr( transform_str.find("(")+1, transform_str.find(",")-transform_str.find("(")-1 ).c_str() ); double y = atof( transform_str.substr( transform_str.find(",")+1, transform_str.find(")")-transform_str.find(",")-1 ).c_str() ); translate = viennagrid::make_point(x,y); } else { std::cerr << transform_str << " is an invalid transform (currently only translate is supported)" << std::endl; return 0; } } add_svg_polyline(mesh, tmp, translate); } int fixes = 0; do { MeshType tmp; fixes = eliminate_nonconformities(mesh, tmp); mesh = tmp; std::cout << "Fix count = " << fixes << std::endl; } while (fixes != 0); std::string output_filename = vtu_filename.getValue().c_str(); if (output_filename.find(".vtu")) output_filename = output_filename.substr( 0, output_filename.find(".vtu") ); if (output_filename.find(".pvd")) output_filename = output_filename.substr( 0, output_filename.find(".pvd") ); viennagrid::io::vtk_writer<MeshType> writer; writer(mesh, output_filename); // viennamesh::context_handle context; // // viennamesh::algorithm_handle mesher = context.make_algorithm("triangle_make_mesh"); // mesher.set_input( "mesh", mesh.internal() ); // mesher.set_input("cell_size", 10.0); // { // viennamesh::LoggingStack s("tetgen_make_mesh"); // mesher.run(); // } // // viennamesh::algorithm_handle mesh_writer = context.make_algorithm("mesh_writer"); // mesh_writer.set_default_source(mesher); // mesh_writer.set_input( "filename", "half_aircraft_mesh.vtu" ); // { // viennamesh::LoggingStack s("mesh_writer"); // mesh_writer.run(); // } }
void BenchmarkAnalogsReader::run(const int &groupNum, const int &analogsNum) { const QString dbName(QString::number(groupNum) + "_" + QString::number(analogsNum) + "_" + "_BAR_tdb"); const QString fileName(QString::number(groupNum) + "_" + QString::number(analogsNum) + "_" + "_BAR_tf.csv"); DataBaseInfo info; info.setDataBaseName(dbName); info.setUserName("root"); info.setPassword("1234"); QThread::msleep(100); qInfo() << "-------Benchmark for write and read analogs-------"; qInfo() << groupNum << " groupNum, " << analogsNum << " analogsNum"; if(!DataBase::remDataBase(info)) { qWarning() << "cannot remove test-db in begin of Benchmark"; return; } if(!TestUtility::removeFile(fileName)) { qWarning() << "cannot remove test-file in begin of Benchmark"; return; } QList<ID> IdList; {//запись в файл AnalogsTable table = AnalogsTableGenerator::generateTable(groupNum, analogsNum); IdList = AnalogsTableGenerator::generateRandomIdList(table); const bool isWritedToFile = CsvFile::write(table, fileName); if(!isWritedToFile) { qWarning() << "cannot write table to file"; return; } } QElapsedTimer timer; bool isImported = false; {//импорт из файла AnalogsWriter writer(info); timer.start(); isImported = writer.importFromFile(fileName); qInfo() << "import from file " << timer.elapsed(); } if(!isImported) { DataBase::remDataBase(info); TestUtility::removeFile(fileName); qWarning() << "cannot import from file"; return; } {//чтение из базы AnalogsReader reader(info); timer.start(); const AnalogsTable table = reader.fetch(IdList); Q_UNUSED(table) qInfo() << "read from db " << timer.elapsed(); } if(!DataBase::remDataBase(info)) { qWarning() << "cannot remove test-db in end of Benchmark"; return; } if(!TestUtility::removeFile(fileName)) { qWarning() << "cannot remove test-file in end of Benchmark"; return; } qInfo() << "----End of benchmark for write and read analogs---" << endl; }
KoFilter::ConversionStatus EpubFile::writeOpf(KoStore *epubStore, QHash<QString, QString> &metadata) { if (!epubStore->open(pathPrefix() + "content.opf")) { kDebug(30503) << "Can not create content.opf ."; return KoFilter::CreationError; } KoStoreDevice opfDevice(epubStore); KoXmlWriter writer(&opfDevice); //FIXME: Write <?xml version="1.0"?> -> FIXED writer.startDocument(NULL,NULL,NULL); // FIXME: Get the unique identifier writer.startElement("package"); writer.addAttribute("version", "2.0"); writer.addAttribute("xmlns", "http://www.idpf.org/2007/opf"); writer.addAttribute("xmlns:dc", "http://purl.org/dc/elements/1.1/"); writer.addAttribute("xmlns:opf", "http://www.idpf.org/2007/opf"); writer.addAttribute("unique-identifier", "BookId"); // FIXME: Where to get this? // ==== metadata ==== writer.startElement("metadata"); // Required elements are: title, language and identifier writer.startElement("dc:title"); writer.addTextNode(metadata.value("title")); writer.endElement(); // dc:title writer.startElement("meta"); writer.addAttribute("name", "cover"); writer.addAttribute("content", "cover-image"); writer.endElement(); writer.startElement("dc:language"); if (!metadata.value("language").isEmpty()) writer.addTextNode(metadata.value("language")); else writer.addTextNode("en"); writer.endElement(); // dc:language writer.startElement("dc:identifier"); writer.addAttribute("id", "BookId"); writer.addAttribute("opf:scheme", "ISBN"); writer.addTextNode("123456789X"); // FIXME: Where to get this? writer.endElement(); // dc:identifier writer.startElement("dc:creator"); writer.addTextNode(metadata.value("creator")); // It's the "Author" profile name writer.endElement(); // dc:creator writer.startElement("dc:subject"); writer.addTextNode(""); // FIXME: Here should come suject info with form : Fiction & Fantasy & ... writer.endElement(); // dc:subject // FIXME: many more (optional) writer.endElement(); // metadata // ==== manifest ==== writer.startElement("manifest"); // Write manifest entry for each embedded file. foreach(FileInfo *file, files()) { // Since paths are relative from where this file is, remove // the common prefix from the reference. QString relativeFilename = file->m_fileName; if (relativeFilename.startsWith(pathPrefix())) relativeFilename = relativeFilename.right(relativeFilename.size() - pathPrefix().size()); writer.startElement("item"); writer.addAttribute("id", file->m_id); writer.addAttribute("href", relativeFilename); writer.addAttribute("media-type", file->m_mimetype); writer.endElement(); // item }
void indri::api::Parameters::write( std::string& text ) { std::auto_ptr<indri::xml::XMLNode> root( toXML() ); indri::xml::XMLWriter writer( root.get() ); writer.write( text ); }
void Config::save() { Writer writer("config"); writer.start_list("supertux-config"); writer.write("profile", profile); writer.write("show_fps", show_fps); writer.write("developer", developer_mode); if(is_christmas()) { writer.write("christmas", christmas_mode); } writer.write("transitions_enabled", transitions_enabled); writer.write("locale", locale); writer.start_list("video"); writer.write("fullscreen", use_fullscreen); writer.write("video", VideoSystem::get_video_string(video)); writer.write("vsync", try_vsync); writer.write("fullscreen_width", fullscreen_size.width); writer.write("fullscreen_height", fullscreen_size.height); writer.write("fullscreen_refresh_rate", fullscreen_refresh_rate); writer.write("window_width", window_size.width); writer.write("window_height", window_size.height); writer.write("aspect_width", aspect_size.width); writer.write("aspect_height", aspect_size.height); writer.write("magnification", magnification); writer.end_list("video"); writer.start_list("audio"); writer.write("sound_enabled", sound_enabled); writer.write("music_enabled", music_enabled); writer.end_list("audio"); writer.start_list("control"); { writer.start_list("keymap"); keyboard_config.write(writer); writer.end_list("keymap"); writer.start_list("joystick"); joystick_config.write(writer); writer.end_list("joystick"); } writer.end_list("control"); writer.start_list("addons"); for(auto addon : addons) { writer.start_list("addon"); writer.write("id", addon.id); writer.write("enabled", addon.enabled); writer.end_list("addon"); } writer.end_list("addons"); writer.end_list("supertux-config"); }
bool PointDLists::Editor::read(yarp::os::ConnectionReader& connection) { if (!isValid()) return false; yarp::os::idl::WireReader reader(connection); reader.expectAccept(); if (!reader.readListHeader()) return false; int len = reader.getLength(); if (len==0) { yarp::os::idl::WireWriter writer(reader); if (writer.isNull()) return true; if (!writer.writeListHeader(1)) return false; writer.writeString("send: 'help' or 'patch (param1 val1) (param2 val2)'"); return true; } std::string tag; if (!reader.readString(tag)) return false; if (tag=="help") { yarp::os::idl::WireWriter writer(reader); if (writer.isNull()) return true; if (!writer.writeListHeader(2)) return false; if (!writer.writeTag("many",1, 0)) return false; if (reader.getLength()>0) { std::string field; if (!reader.readString(field)) return false; if (field=="name") { if (!writer.writeListHeader(1)) return false; if (!writer.writeString("std::string name")) return false; } if (field=="firstList") { if (!writer.writeListHeader(1)) return false; if (!writer.writeString("std::vector<PointD> firstList")) return false; } if (field=="secondList") { if (!writer.writeListHeader(1)) return false; if (!writer.writeString("std::vector<PointD> secondList")) return false; } } if (!writer.writeListHeader(4)) return false; writer.writeString("*** Available fields:"); writer.writeString("name"); writer.writeString("firstList"); writer.writeString("secondList"); return true; } bool nested = true; bool have_act = false; if (tag!="patch") { if ((len-1)%2 != 0) return false; len = 1 + ((len-1)/2); nested = false; have_act = true; } for (int i=1; i<len; i++) { if (nested && !reader.readListHeader(3)) return false; std::string act; std::string key; if (have_act) { act = tag; } else { if (!reader.readString(act)) return false; } if (!reader.readString(key)) return false; // inefficient code follows, bug paulfitz to improve it if (key == "name") { will_set_name(); if (!obj->nested_read_name(reader)) return false; did_set_name(); } else if (key == "firstList") { will_set_firstList(); if (!obj->nested_read_firstList(reader)) return false; did_set_firstList(); } else if (key == "secondList") { will_set_secondList(); if (!obj->nested_read_secondList(reader)) return false; did_set_secondList(); } else { // would be useful to have a fallback here } } reader.accept(); yarp::os::idl::WireWriter writer(reader); if (writer.isNull()) return true; writer.writeListHeader(1); writer.writeVocab(VOCAB2('o','k')); return true; }
bool PointDLists::write(yarp::os::ConnectionWriter& connection) const { yarp::os::idl::WireWriter writer(connection); if (!writer.writeListHeader(3)) return false; return write(writer); }
/// handles requests for EchoService void EchoService::operator()(HTTPRequestPtr& request, TCPConnectionPtr& tcp_conn) { // this web service uses static text to test the mixture of "copied" with // "static" (no-copy) text static const std::string REQUEST_ECHO_TEXT("[Request Echo]"); static const std::string REQUEST_HEADERS_TEXT("[Request Headers]"); static const std::string QUERY_PARAMS_TEXT("[Query Parameters]"); static const std::string COOKIE_PARAMS_TEXT("[Cookie Parameters]"); static const std::string POST_CONTENT_TEXT("[POST Content]"); static const std::string USER_INFO_TEXT("[USER Info]"); // Set Content-type to "text/plain" (plain ascii text) HTTPResponseWriterPtr writer(HTTPResponseWriter::create(tcp_conn, *request, boost::bind(&TCPConnection::finish, tcp_conn))); writer->getResponse().setContentType(HTTPTypes::CONTENT_TYPE_TEXT); // write request information writer->writeNoCopy(REQUEST_ECHO_TEXT); writer->writeNoCopy(HTTPTypes::STRING_CRLF); writer->writeNoCopy(HTTPTypes::STRING_CRLF); writer << "Request method: " << request->getMethod() << HTTPTypes::STRING_CRLF << "Resource originally requested: " << request->getOriginalResource() << HTTPTypes::STRING_CRLF << "Resource delivered: " << request->getResource() << HTTPTypes::STRING_CRLF << "Query string: " << request->getQueryString() << HTTPTypes::STRING_CRLF << "HTTP version: " << request->getVersionMajor() << '.' << request->getVersionMinor() << HTTPTypes::STRING_CRLF << "Content length: " << (unsigned long)request->getContentLength() << HTTPTypes::STRING_CRLF << HTTPTypes::STRING_CRLF; // write request headers writer->writeNoCopy(REQUEST_HEADERS_TEXT); writer->writeNoCopy(HTTPTypes::STRING_CRLF); writer->writeNoCopy(HTTPTypes::STRING_CRLF); std::for_each(request->getHeaders().begin(), request->getHeaders().end(), boost::bind(&writeDictionaryTerm, writer, _1, false)); writer->writeNoCopy(HTTPTypes::STRING_CRLF); // write query parameters writer->writeNoCopy(QUERY_PARAMS_TEXT); writer->writeNoCopy(HTTPTypes::STRING_CRLF); writer->writeNoCopy(HTTPTypes::STRING_CRLF); std::for_each(request->getQueryParams().begin(), request->getQueryParams().end(), boost::bind(&writeDictionaryTerm, writer, _1, true)); writer->writeNoCopy(HTTPTypes::STRING_CRLF); // write cookie parameters writer->writeNoCopy(COOKIE_PARAMS_TEXT); writer->writeNoCopy(HTTPTypes::STRING_CRLF); writer->writeNoCopy(HTTPTypes::STRING_CRLF); std::for_each(request->getCookieParams().begin(), request->getCookieParams().end(), boost::bind(&writeDictionaryTerm, writer, _1, false)); writer->writeNoCopy(HTTPTypes::STRING_CRLF); // write POST content writer->writeNoCopy(POST_CONTENT_TEXT); writer->writeNoCopy(HTTPTypes::STRING_CRLF); writer->writeNoCopy(HTTPTypes::STRING_CRLF); if (request->getContentLength() != 0) { writer->write(request->getContent(), request->getContentLength()); writer->writeNoCopy(HTTPTypes::STRING_CRLF); writer->writeNoCopy(HTTPTypes::STRING_CRLF); } // if authenticated, write user info PionUserPtr user = request->getUser(); if (user) { writer->writeNoCopy(USER_INFO_TEXT); writer->writeNoCopy(HTTPTypes::STRING_CRLF); writer->writeNoCopy(HTTPTypes::STRING_CRLF); writer << "User authenticated, username: " << user->getUsername(); writer->writeNoCopy(HTTPTypes::STRING_CRLF); } // send the writer writer->send(); }
void writer_init(void* arg) { int ret = writer(); corethread_exit((void *)ret); return; }
void saveAsDialog(const ContextReader& reader, const char* dlgTitle, bool markAsSaved) { const Document* document = reader.document(); std::string filename; if (!m_filename.empty()) { filename = m_filename; } else { filename = document->filename(); char exts[4096]; get_writable_extensions(exts, sizeof(exts)); for (;;) { std::string newfilename = app::show_file_selector(dlgTitle, filename, exts); if (newfilename.empty()) return; filename = newfilename; // Ask if the user wants overwrite the existent file. int ret = 0; if (base::is_file(filename)) { ret = ui::Alert::show("Warning<<The file already exists, overwrite it?<<%s||&Yes||&No||&Cancel", base::get_file_name(filename).c_str()); // Check for read-only attribute. if (ret == 1) { if (!confirmReadonly(filename)) ret = 2; // Select file again. else break; } } else break; // "yes": we must continue with the operation... if (ret == 1) { break; } // "cancel" or <esc> per example: we back doing nothing else if (ret != 2) return; // "no": we must back to select other file-name } } { ContextWriter writer(reader); Document* documentWriter = writer.document(); std::string oldFilename = documentWriter->filename(); // Change the document file name documentWriter->setFilename(filename.c_str()); m_selectedFilename = filename; // Save the document save_document_in_background(writer.context(), documentWriter, markAsSaved); if (documentWriter->isModified()) documentWriter->setFilename(oldFilename); update_screen_for_document(documentWriter); } }
qint32 HTransportSinkService::getStateVariables( quint32 instanceId, const QSet<QString>& stateVariableNames, QString* stateVariableValuePairs) { HLOG2(H_AT, H_FUN, h_ptr->m_loggingIdentifier); Q_ASSERT(stateVariableValuePairs); HRendererConnection* mediaConnection = m_owner->findConnectionByAvTransportId(instanceId); if (!mediaConnection) { return HAvTransportInfo::InvalidInstanceId; } QString retVal; QXmlStreamWriter writer(&retVal); writer.setCodec("UTF-8"); writer.writeStartDocument(); writer.writeStartElement("stateVariableValuePairs"); writer.writeDefaultNamespace("urn:schemas-upnp-org:av:avs"); writer.writeAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); writer.writeAttribute("xsi:schemaLocation", "urn:schemas-upnp-org:av:avs " \ "http://www.upnp.org/schemas/av/avs.xsd"); QSet<QString> stateVarNames; if (stateVariableNames.contains("*")) { stateVarNames = HAvTransportInfo::stateVariablesSetupData().names(); QSet<QString>::iterator it = stateVarNames.begin(); for(; it != stateVarNames.end();) { if (it->startsWith("A_ARG") || *it == "LastChange") { it = stateVarNames.erase(it); } else { ++it; } } } else { stateVarNames = stateVariableNames; } foreach(QString svName, stateVarNames) { svName = svName.trimmed(); if (svName.compare("LastChange", Qt::CaseInsensitive) == 0 || svName.startsWith("A_ARG", Qt::CaseInsensitive)) { return HAvTransportInfo::InvalidStateVariableList; } bool ok = false; QString value = mediaConnection->info()->value(svName, &ok); if (ok) { writer.writeStartElement("stateVariable"); writer.writeAttribute("variableName", svName); writer.writeCharacters(value); writer.writeEndElement(); } else { HLOG_WARN(QString("Could not get the value of state variable [%1]").arg(svName)); return HAvTransportInfo::InvalidStateVariableList; } }
void config_cache::write_file(std::string file_path, const config& cfg) { filesystem::scoped_ostream stream = filesystem::ostream_file(file_path); config_writer writer(*stream, true, game_config::cache_compression_level); writer.write(cfg); }
int bamcat(libmaus::util::ArgInfo const & arginfo) { if ( isatty(STDOUT_FILENO) ) { ::libmaus::exception::LibMausException se; se.getStream() << "Refusing write binary data to terminal, please redirect standard output to pipe or file." << std::endl; se.finish(); throw se; } int const level = libmaus::bambam::BamBlockWriterBaseFactory::checkCompressionLevel(arginfo.getValue<int>("level",getDefaultLevel())); int const verbose = arginfo.getValue<int>("verbose",getDefaultVerbose()); int const streaming = arginfo.getValue<int>("streaming",getDefaultStreaming()); std::vector<std::string> inputfilenames = arginfo.getPairValues("I"); for ( uint64_t i = 0; i < arginfo.restargs.size(); ++i ) inputfilenames.push_back(arginfo.restargs[i]); libmaus::bambam::BamCat bamdec(inputfilenames, false /* put rank */, streaming); libmaus::bambam::BamAlignment const & algn = bamdec.getAlignment(); libmaus::bambam::BamHeader const & header = bamdec.getHeader(); ::libmaus::bambam::BamHeader::unique_ptr_type uphead(updateHeader(arginfo,header)); /* * start index/md5 callbacks */ std::string const tmpfilenamebase = arginfo.getValue<std::string>("tmpfile",arginfo.getDefaultTmpFileName()); std::string const tmpfileindex = tmpfilenamebase + "_index"; ::libmaus::util::TempFileRemovalContainer::addTempFile(tmpfileindex); std::string md5filename; std::string indexfilename; std::vector< ::libmaus::lz::BgzfDeflateOutputCallback * > cbs; ::libmaus::lz::BgzfDeflateOutputCallbackMD5::unique_ptr_type Pmd5cb; if ( arginfo.getValue<unsigned int>("md5",getDefaultMD5()) ) { if ( arginfo.hasArg("md5filename") && arginfo.getUnparsedValue("md5filename","") != "" ) md5filename = arginfo.getUnparsedValue("md5filename",""); else std::cerr << "[V] no filename for md5 given, not creating hash" << std::endl; if ( md5filename.size() ) { ::libmaus::lz::BgzfDeflateOutputCallbackMD5::unique_ptr_type Tmd5cb(new ::libmaus::lz::BgzfDeflateOutputCallbackMD5); Pmd5cb = UNIQUE_PTR_MOVE(Tmd5cb); cbs.push_back(Pmd5cb.get()); } } libmaus::bambam::BgzfDeflateOutputCallbackBamIndex::unique_ptr_type Pindex; if ( arginfo.getValue<unsigned int>("index",getDefaultIndex()) ) { if ( arginfo.hasArg("indexfilename") && arginfo.getUnparsedValue("indexfilename","") != "" ) indexfilename = arginfo.getUnparsedValue("indexfilename",""); else std::cerr << "[V] no filename for index given, not creating index" << std::endl; if ( indexfilename.size() ) { libmaus::bambam::BgzfDeflateOutputCallbackBamIndex::unique_ptr_type Tindex(new libmaus::bambam::BgzfDeflateOutputCallbackBamIndex(tmpfileindex)); Pindex = UNIQUE_PTR_MOVE(Tindex); cbs.push_back(Pindex.get()); } } std::vector< ::libmaus::lz::BgzfDeflateOutputCallback * > * Pcbs = 0; if ( cbs.size() ) Pcbs = &cbs; /* * end md5/index callbacks */ ::libmaus::bambam::BamWriter::unique_ptr_type writer(new ::libmaus::bambam::BamWriter(std::cout,*uphead,level,Pcbs)); libmaus::bambam::BamWriter::stream_type & bamoutstr = writer->getStream(); if ( verbose ) { uint64_t c = 0; while ( bamdec.readAlignment() ) { algn.serialise(bamoutstr); if ( ((++c) & ((1ull<<20)-1)) == 0 ) std::cerr << "[V] " << c << std::endl; } std::cerr << "[V] " << c << std::endl; } else while ( bamdec.readAlignment() ) algn.serialise(bamoutstr); writer.reset(); if ( Pmd5cb ) { Pmd5cb->saveDigestAsFile(md5filename); } if ( Pindex ) { Pindex->flush(std::string(indexfilename)); } return EXIT_SUCCESS; }
int main(int argc, char* argv[]) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"from-format", required_argument, 0, 'f'}, {"to-format", required_argument, 0, 't'}, {0, 0, 0, 0} }; std::string input_format; std::string output_format; while (true) { int c = getopt_long(argc, argv, "dhf:t:", long_options, 0); if (c == -1) { break; } switch (c) { case 'h': print_help(); exit(0); case 'f': input_format = optarg; break; case 't': output_format = optarg; break; default: exit(1); } } std::string input; std::string output; int remaining_args = argc - optind; if (remaining_args > 2) { std::cerr << "Usage: " << argv[0] << " [OPTIONS] [INFILE [OUTFILE]]" << std::endl; exit(1); } else if (remaining_args == 2) { input = argv[optind]; output = argv[optind+1]; } else if (remaining_args == 1) { input = argv[optind]; } osmium::io::File infile(input, input_format); osmium::io::File outfile(output, output_format); if (infile.has_multiple_object_versions() && !outfile.has_multiple_object_versions()) { std::cerr << "Warning! You are converting from an OSM file with (potentially) several versions of the same object to one that is not marked as such.\n"; } try { osmium::io::Reader reader(infile); osmium::io::Header header = reader.header(); header.set("generator", "osmium_convert"); osmium::io::Writer writer(outfile, header, osmium::io::overwrite::allow); while (osmium::memory::Buffer buffer = reader.read()) { writer(std::move(buffer)); } writer.close(); reader.close(); } catch (std::exception& e) { std::cerr << e.what() << "\n"; exit(1); } google::protobuf::ShutdownProtobufLibrary(); }
void MainWindow::save() { QString currentDirSave = ""; if((Canvas *)ui->tabWidget->currentWidget()) { QRect currentRect = ((Canvas*)ui->tabWidget->currentWidget())->viewport()->rect(); ((Canvas*)ui->tabWidget->currentWidget())->adjustSize(); QRect rect = ((Canvas*)ui->tabWidget->currentWidget())->drawRect().toRect(); QPixmap pixmap(rect.width(), rect.height()); QPainter painter(&pixmap); painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing); ((Canvas*)ui->tabWidget->currentWidget())->render(&painter, rect, rect); painter.end(); ((Canvas*)ui->tabWidget->currentWidget())->resize(currentRect.width(), currentRect.height()); QString selfilter = tr("JPEG (*.jpg *.jpeg)"); QString fileName = QFileDialog::getSaveFileName( this, tr("Save Dialog"), currentDirSave, tr("All files (*.*);;JPEG (*.jpg *.jpeg);;PNG (*.png);;XML (*.xml)" ), &selfilter ); if(!fileName.isEmpty()) { if(selfilter == "JPEG (*.jpg *.jpeg)" || selfilter == "PNG (*.png)") { if(selfilter == "JPEG (*.jpg *.jpeg)") { fileName += ".jpg"; } else { fileName += ".png"; } QStringList list = fileName.split("/"); for(int i = 0; i < list.size() - 1; ++i) { currentDirSave += list.at(i) + "/"; } QStringList listFormat = fileName.split("."); const char * format = listFormat.at(listFormat.size() - 1).toStdString().c_str(); pixmap.save(fileName, format); ui->tabWidget->setTabText(ui->tabWidget->currentIndex(), list.at(list.size() - 1)); } else if(selfilter == "XML (*.xml)") { fileName += ".xml"; QFile _file(fileName); _file.open(QIODevice::WriteOnly | QIODevice::Text); QXmlStreamWriter writer(&_file); writer.setAutoFormatting(true); writer.writeStartDocument("1.0"); writer.writeComment("I am a good old rebel"); Canvas * current = (Canvas *)ui->tabWidget->currentWidget(); Scene * tmpScene = current->getCurrentScene(); if(tmpScene) { writer.writeStartElement("scene"); writer.writeStartElement("rect"); writer.writeStartElement("topLeft"); writer.writeAttribute("x", QString::number(currentRect.topLeft().x())); writer.writeAttribute("y", QString::number(currentRect.topLeft().y())); writer.writeEndElement(); writer.writeStartElement("bottomRight"); writer.writeAttribute("x", QString::number(currentRect.bottomRight().x())); writer.writeAttribute("y", QString::number(currentRect.bottomRight().y())); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndElement(); for(auto &i : tmpScene->shapes) { writer.writeStartElement("shape"); writer.writeStartElement("rect"); writer.writeStartElement("topLeft"); writer.writeAttribute("x", QString::number(i->boundingRect().topLeft().x())); writer.writeAttribute("y", QString::number(i->boundingRect().topLeft().y())); writer.writeEndElement(); writer.writeStartElement("bottomRight"); writer.writeAttribute("x", QString::number(i->boundingRect().bottomRight().x())); writer.writeAttribute("y", QString::number(i->boundingRect().bottomRight().y())); writer.writeEndElement(); writer.writeEndElement(); writer.writeStartElement("brush"); writer.writeAttribute("color", QString::number(i->brush().color().value())); writer.writeEndElement(); writer.writeStartElement("pen"); writer.writeAttribute("color", QString::number(i->pen().color().value())); writer.writeAttribute("width", QString::number(i->pen().width())); writer.writeEndElement(); writer.writeTextElement("ShapeType", QString::number(i->type())); writer.writeEndElement(); writer.writeEndDocument(); } for(auto &i : tmpScene->lines) { writer.writeStartElement("shape"); writer.writeStartElement("rect"); writer.writeStartElement("topLeft"); writer.writeAttribute("x", QString::number(i->boundingRect().topLeft().x())); writer.writeAttribute("y", QString::number(i->boundingRect().topLeft().y())); writer.writeEndElement(); writer.writeStartElement("bottomRight"); writer.writeAttribute("x", QString::number(i->boundingRect().bottomRight().x())); writer.writeAttribute("y", QString::number(i->boundingRect().bottomRight().y())); writer.writeEndElement(); writer.writeEndElement(); writer.writeStartElement("brush"); writer.writeAttribute("color", QString::number(i->brush().color().value())); writer.writeEndElement(); writer.writeStartElement("pen"); writer.writeAttribute("color", QString::number(i->pen().color().value())); writer.writeAttribute("width", QString::number(i->pen().width())); writer.writeEndElement(); writer.writeTextElement("ShapeType", QString::number(i->type())); writer.writeEndElement(); writer.writeEndDocument(); } } } } } }
bool yarprobotinterfaceRpc_exit::write(yarp::os::ConnectionWriter& connection) { yarp::os::idl::WireWriter writer(connection); if (!writer.writeListHeader(1)) return false; if (!writer.writeTag("exit",1,1)) return false; return true; }
void WriterTest::testWriterOstream(void) { std::stringstream stream(""); Writer writer(stream); }
bool yarprobotinterfaceRpc::read(yarp::os::ConnectionReader& connection) { yarp::os::idl::WireReader reader(connection); reader.expectAccept(); if (!reader.readListHeader()) { reader.fail(); return false; } yarp::os::ConstString tag = reader.readTag(); bool direct = (tag=="__direct__"); if (direct) tag = reader.readTag(); while (!reader.isError()) { // TODO: use quick lookup, this is just a test if (tag == "get_phase") { std::string _return; _return = get_phase(); yarp::os::idl::WireWriter writer(reader); if (!writer.isNull()) { if (!writer.writeListHeader(1)) return false; if (!writer.writeString(_return)) return false; } reader.accept(); return true; } if (tag == "get_level") { int32_t _return; _return = get_level(); yarp::os::idl::WireWriter writer(reader); if (!writer.isNull()) { if (!writer.writeListHeader(1)) return false; if (!writer.writeI32(_return)) return false; } reader.accept(); return true; } if (tag == "get_robot") { std::string _return; _return = get_robot(); yarp::os::idl::WireWriter writer(reader); if (!writer.isNull()) { if (!writer.writeListHeader(1)) return false; if (!writer.writeString(_return)) return false; } reader.accept(); return true; } if (tag == "is_ready") { bool _return; _return = is_ready(); yarp::os::idl::WireWriter writer(reader); if (!writer.isNull()) { if (!writer.writeListHeader(1)) return false; if (!writer.writeBool(_return)) return false; } reader.accept(); return true; } if (tag == "quit") { std::string _return; _return = quit(); yarp::os::idl::WireWriter writer(reader); if (!writer.isNull()) { if (!writer.writeListHeader(1)) return false; if (!writer.writeString(_return)) return false; } reader.accept(); return true; } if (tag == "bye") { std::string _return; _return = bye(); yarp::os::idl::WireWriter writer(reader); if (!writer.isNull()) { if (!writer.writeListHeader(1)) return false; if (!writer.writeString(_return)) return false; } reader.accept(); return true; } if (tag == "exit") { std::string _return; _return = exit(); yarp::os::idl::WireWriter writer(reader); if (!writer.isNull()) { if (!writer.writeListHeader(1)) return false; if (!writer.writeString(_return)) return false; } reader.accept(); return true; } if (tag == "help") { std::string functionName; if (!reader.readString(functionName)) { functionName = "--all"; } std::vector<std::string> _return=help(functionName); yarp::os::idl::WireWriter writer(reader); if (!writer.isNull()) { if (!writer.writeListHeader(2)) return false; if (!writer.writeTag("many",1, 0)) return false; if (!writer.writeListBegin(BOTTLE_TAG_INT, static_cast<uint32_t>(_return.size()))) return false; std::vector<std::string> ::iterator _iterHelp; for (_iterHelp = _return.begin(); _iterHelp != _return.end(); ++_iterHelp) { if (!writer.writeString(*_iterHelp)) return false; } if (!writer.writeListEnd()) return false; } reader.accept(); return true; } if (reader.noMore()) { reader.fail(); return false; } yarp::os::ConstString next_tag = reader.readTag(); if (next_tag=="") break; tag = tag + "_" + next_tag; } return false; }
void CL_DomDocument::save(CL_IODevice &output, bool insert_whitespace) { CL_XMLWriter writer(output); writer.set_insert_whitespace(insert_whitespace); std::vector<CL_DomNode> node_stack; CL_DomNode cur_node = get_first_child(); while (!cur_node.is_null()) { // Create opening node: CL_XMLToken opening_node; opening_node.type = (CL_XMLToken::TokenType) cur_node.get_node_type(); opening_node.variant = cur_node.has_child_nodes() ? CL_XMLToken::BEGIN : CL_XMLToken::SINGLE; opening_node.name = cur_node.get_node_name(); opening_node.value = cur_node.get_node_value(); if (cur_node.is_element()) { CL_DomNamedNodeMap attributes = cur_node.get_attributes(); int length = attributes.get_length(); for (int i = 0; i < length; ++i) { CL_DomAttr attribute = attributes.item(i).to_attr(); opening_node.attributes.push_back( CL_XMLToken::Attribute( attribute.get_name(), attribute.get_value())); } } writer.write(opening_node); // Create any possible child nodes: if (cur_node.has_child_nodes()) { node_stack.push_back(cur_node); cur_node = cur_node.get_first_child(); continue; } // Create closing nodes until we reach next opening node in tree: while (true) { if (cur_node.has_child_nodes()) { CL_XMLToken closing_node; closing_node.type = (CL_XMLToken::TokenType) cur_node.get_node_type(); closing_node.name = cur_node.get_node_name(); closing_node.variant = CL_XMLToken::END; writer.write(closing_node); } cur_node = cur_node.get_next_sibling(); if (!cur_node.is_null()) break; if (node_stack.empty()) break; cur_node = node_stack.back(); node_stack.pop_back(); } } }
bool yarprobotinterfaceRpc_get_level::write(yarp::os::ConnectionWriter& connection) { yarp::os::idl::WireWriter writer(connection); if (!writer.writeListHeader(2)) return false; if (!writer.writeTag("get_level",1,2)) return false; return true; }
int bamreset(::libmaus2::util::ArgInfo const & arginfo) { if ( isatty(STDIN_FILENO) ) { ::libmaus2::exception::LibMausException se; se.getStream() << "Refusing to read binary data from terminal, please redirect standard input to pipe or file." << std::endl; se.finish(); throw se; } if ( isatty(STDOUT_FILENO) ) { ::libmaus2::exception::LibMausException se; se.getStream() << "Refusing write binary data to terminal, please redirect standard output to pipe or file." << std::endl; se.finish(); throw se; } int const level = libmaus2::bambam::BamBlockWriterBaseFactory::checkCompressionLevel(arginfo.getValue<int>("level",getDefaultLevel())); int const verbose = arginfo.getValue<int>("verbose",getDefaultVerbose()); int const resetsortorder = arginfo.getValue<int>("resetsortorder",getDefaultResetSortOrder()); ::libmaus2::bambam::BamDecoder dec(std::cin,false); ::libmaus2::bambam::BamHeader const & header = dec.getHeader(); std::string headertext = header.text; // no replacement header file given if ( ! arginfo.hasArg("resetheadertext") ) { // remove SQ lines std::vector<libmaus2::bambam::HeaderLine> allheaderlines = libmaus2::bambam::HeaderLine::extractLines(headertext); std::ostringstream upheadstr; for ( uint64_t i = 0; i < allheaderlines.size(); ++i ) if ( allheaderlines[i].type != "SQ" ) upheadstr << allheaderlines[i].line << std::endl; headertext = upheadstr.str(); } // replace header given in file else { std::string const headerfilename = arginfo.getUnparsedValue("resetheadertext",""); uint64_t const headerlen = libmaus2::util::GetFileSize::getFileSize(headerfilename); libmaus2::aio::InputStreamInstance CIS(headerfilename); libmaus2::autoarray::AutoArray<char> ctext(headerlen,false); CIS.read(ctext.begin(),headerlen); headertext = std::string(ctext.begin(),ctext.end()); } // add PG line to header headertext = libmaus2::bambam::ProgramHeaderLineSet::addProgramLine( headertext, "bamreset", // ID "bamreset", // PN arginfo.commandline, // CL ::libmaus2::bambam::ProgramHeaderLineSet(headertext).getLastIdInChain(), // PP std::string(PACKAGE_VERSION) // VN ); // construct new header libmaus2::bambam::BamHeader uphead(headertext); if ( resetsortorder ) uphead.changeSortOrder("unknown"); /* * start index/md5 callbacks */ std::string const tmpfilenamebase = arginfo.getValue<std::string>("tmpfile",arginfo.getDefaultTmpFileName()); std::string const tmpfileindex = tmpfilenamebase + "_index"; ::libmaus2::util::TempFileRemovalContainer::addTempFile(tmpfileindex); uint32_t const excludeflags = libmaus2::bambam::BamFlagBase::stringToFlags( arginfo.getValue<std::string>("exclude",getDefaultExcludeFlags())); std::string md5filename; std::string indexfilename; std::vector< ::libmaus2::lz::BgzfDeflateOutputCallback * > cbs; ::libmaus2::lz::BgzfDeflateOutputCallbackMD5::unique_ptr_type Pmd5cb; if ( arginfo.getValue<unsigned int>("md5",getDefaultMD5()) ) { if ( libmaus2::bambam::BamBlockWriterBaseFactory::getMD5FileName(arginfo) != std::string() ) md5filename = libmaus2::bambam::BamBlockWriterBaseFactory::getMD5FileName(arginfo); else std::cerr << "[V] no filename for md5 given, not creating hash" << std::endl; if ( md5filename.size() ) { ::libmaus2::lz::BgzfDeflateOutputCallbackMD5::unique_ptr_type Tmd5cb(new ::libmaus2::lz::BgzfDeflateOutputCallbackMD5); Pmd5cb = UNIQUE_PTR_MOVE(Tmd5cb); cbs.push_back(Pmd5cb.get()); } } libmaus2::bambam::BgzfDeflateOutputCallbackBamIndex::unique_ptr_type Pindex; if ( arginfo.getValue<unsigned int>("index",getDefaultIndex()) ) { if ( libmaus2::bambam::BamBlockWriterBaseFactory::getIndexFileName(arginfo) != std::string() ) indexfilename = libmaus2::bambam::BamBlockWriterBaseFactory::getIndexFileName(arginfo); else std::cerr << "[V] no filename for index given, not creating index" << std::endl; if ( indexfilename.size() ) { libmaus2::bambam::BgzfDeflateOutputCallbackBamIndex::unique_ptr_type Tindex(new libmaus2::bambam::BgzfDeflateOutputCallbackBamIndex(tmpfileindex)); Pindex = UNIQUE_PTR_MOVE(Tindex); cbs.push_back(Pindex.get()); } } std::vector< ::libmaus2::lz::BgzfDeflateOutputCallback * > * Pcbs = 0; if ( cbs.size() ) Pcbs = &cbs; /* * end md5/index callbacks */ ::libmaus2::bambam::BamWriter::unique_ptr_type writer(new ::libmaus2::bambam::BamWriter(std::cout,uphead,level,Pcbs)); libmaus2::timing::RealTimeClock rtc; rtc.start(); libmaus2::bambam::BamAlignment & algn = dec.getAlignment(); uint64_t c = 0; bool const resetaux = arginfo.getValue<int>("resetaux",getDefaultResetAux()); libmaus2::bambam::BamAuxFilterVector::unique_ptr_type const prgfilter(libmaus2::bambam::BamAuxFilterVector::parseAuxFilterList(arginfo)); libmaus2::bambam::BamAuxFilterVector const * rgfilter = prgfilter.get(); while ( dec.readAlignment() ) { bool const keep = resetAlignment(algn,resetaux /* reset aux */,excludeflags,rgfilter); if ( keep ) algn.serialise(writer->getStream()); if ( verbose && (++c & (1024*1024-1)) == 0 ) std::cerr << "[V] " << c/(1024*1024) << " " << (c / rtc.getElapsedSeconds()) << std::endl; } writer.reset(); if ( Pmd5cb ) { Pmd5cb->saveDigestAsFile(md5filename); } if ( Pindex ) { Pindex->flush(std::string(indexfilename)); } return EXIT_SUCCESS; }
void dlgPackageExporter::slot_export_package(){ //#ifndef Q_OS_WIN // filePath = ui->filePath->text(); //#endif QFile file_xml( filePath ); if( file_xml.open( QIODevice::WriteOnly ) ) { XMLexport writer( mpHost ); //write trigs QList<QTreeWidgetItem *> items = treeWidget->findItems(QString("Triggers"), Qt::MatchExactly, 0); QTreeWidgetItem * top = items.first(); QList<QTreeWidgetItem *> trigList; recurseTree(top,trigList); for (int i=0;i<trigList.size();i++){ QTreeWidgetItem * item = trigList.at(i); if (item->checkState(0) == Qt::Unchecked && triggerMap.contains(item)){ triggerMap[item]->exportItem = false; } else if (item->checkState(0) == Qt::Checked && triggerMap.contains(item) && triggerMap[item]->mModuleMasterFolder){ triggerMap[item]->mModuleMasterFolder=false; modTriggerMap.insert(item, triggerMap[item]); } } items = treeWidget->findItems(QString("Timers"), Qt::MatchExactly, 0); top = items.first(); QList<QTreeWidgetItem *> timerList; recurseTree(top,timerList); for (int i=0;i<timerList.size();i++){ QTreeWidgetItem * item = timerList.at(i); if (item->checkState(0) == Qt::Unchecked && timerMap.contains(item)){ timerMap[item]->exportItem = false; } else if (item->checkState(0) == Qt::Checked && timerMap.contains(item) && timerMap[item]->mModuleMasterFolder){ timerMap[item]->mModuleMasterFolder=false; modTimerMap.insert(item, timerMap[item]); } } items = treeWidget->findItems(QString("Aliases"), Qt::MatchExactly, 0); top = items.first(); QList<QTreeWidgetItem *> aliasList; recurseTree(top,aliasList); for (int i=0;i<aliasList.size();i++){ QTreeWidgetItem * item = aliasList.at(i); if (item->checkState(0) == Qt::Unchecked && aliasMap.contains(item)){ aliasMap[item]->exportItem = false; } else if (item->checkState(0) == Qt::Checked && aliasMap.contains(item) && aliasMap[item]->mModuleMasterFolder){ aliasMap[item]->mModuleMasterFolder=false; modAliasMap.insert(item, aliasMap[item]); } } items = treeWidget->findItems(QString("Buttons"), Qt::MatchExactly, 0); top = items.first(); QList<QTreeWidgetItem *> actionList; recurseTree(top,actionList); for (int i=0;i<actionList.size();i++){ QTreeWidgetItem * item = actionList.at(i); if (item->checkState(0) == Qt::Unchecked && actionMap.contains(item)){ actionMap[item]->exportItem = false; } else if (item->checkState(0) == Qt::Checked && actionMap.contains(item) && actionMap[item]->mModuleMasterFolder){ actionMap[item]->mModuleMasterFolder=false; modActionMap.insert(item, actionMap[item]); } } items = treeWidget->findItems(QString("Scripts"), Qt::MatchExactly, 0); top = items.first(); QList<QTreeWidgetItem *> scriptList; recurseTree(top,scriptList); for (int i=0;i<scriptList.size();i++){ QTreeWidgetItem * item = scriptList.at(i); if (item->checkState(0) == Qt::Unchecked && scriptMap.contains(item)){ scriptMap[item]->exportItem = false; } else if (item->checkState(0) == Qt::Checked && scriptMap.contains(item) && scriptMap[item]->mModuleMasterFolder){ scriptMap[item]->mModuleMasterFolder=false; modScriptMap.insert(item, scriptMap[item]); } } items = treeWidget->findItems(QString("Keys"), Qt::MatchExactly, 0); top = items.first(); QList<QTreeWidgetItem *> keyList; recurseTree(top,keyList); for (int i=0;i<keyList.size();i++){ QTreeWidgetItem * item = keyList.at(i); if (item->checkState(0) == Qt::Unchecked && keyMap.contains(item)){ keyMap[item]->exportItem = false; } else if (item->checkState(0) == Qt::Checked && keyMap.contains(item) && keyMap[item]->mModuleMasterFolder){ keyMap[item]->mModuleMasterFolder=false; modKeyMap.insert(item, keyMap[item]); } } writer.exportGenericPackage(&file_xml); file_xml.close(); //now fix all the stuff we weren't exporting //trigger, timer, alias,action,script, keys for (int i=0;i<trigList.size();i++){ QTreeWidgetItem * item = trigList.at(i); if (triggerMap.contains(item)){ triggerMap[item]->exportItem = true; } if (modTriggerMap.contains(item)){ modTriggerMap[item]->mModuleMasterFolder = true; } } for (int i=0;i<timerList.size();i++){ QTreeWidgetItem * item = timerList.at(i); if (timerMap.contains(item)){ timerMap[item]->exportItem = true; } if (modTimerMap.contains(item)){ modTimerMap[item]->mModuleMasterFolder = true; } } for (int i=0;i<actionList.size();i++){ QTreeWidgetItem * item = actionList.at(i); if (actionMap.contains(item)){ actionMap[item]->exportItem = true; } if (modActionMap.contains(item)){ modActionMap[item]->mModuleMasterFolder = true; } } for (int i=0;i<scriptList.size();i++){ QTreeWidgetItem * item = scriptList.at(i); if (scriptMap.contains(item)){ scriptMap[item]->exportItem = true; } if (modScriptMap.contains(item)){ modScriptMap[item]->mModuleMasterFolder = true; } } for (int i=0;i<keyList.size();i++){ QTreeWidgetItem * item = keyList.at(i); if (keyMap.contains(item)){ keyMap[item]->exportItem = true; } if (modKeyMap.contains(item)){ modKeyMap[item]->mModuleMasterFolder = true; } } for (int i=0;i<aliasList.size();i++){ QTreeWidgetItem * item = aliasList.at(i); if (aliasMap.contains(item)){ aliasMap[item]->exportItem = true; } if (modAliasMap.contains(item)){ modAliasMap[item]->mModuleMasterFolder = true; } } //#ifdef Q_OS_WIN JlCompress::compressDir(zip, tempDir ); // #else // ui->infoLabel->setText("Exported package to "+filePath); // #endif } else { ui->infoLabel->setText("Failed to export - couldn't open "+filePath+" for writing in. Do you have the necessary permissions to write to that folder?"); } close(); }
bool get(const std::string &name, T &val) { attribute_writer<T> writer(name, val); serialize(writer); return writer.success(); }
static void handle_preprocess_command(const commandline_options& cmdline_opts) { preproc_map input_macros; if( cmdline_opts.preprocess_input_macros ) { std::string file = *cmdline_opts.preprocess_input_macros; if ( filesystem::file_exists( file ) == false ) { std::cerr << "please specify an existing file. File "<< file <<" doesn't exist.\n"; return; } std::cerr << SDL_GetTicks() << " Reading cached defines from: " << file << "\n"; config cfg; try { filesystem::scoped_istream stream = filesystem::istream_file( file ); read( cfg, *stream ); } catch (config::error & e) { std::cerr << "Caught a config error while parsing file '" << file << "':\n" << e.message << std::endl; } int read = 0; // use static preproc_define::read_pair(config) to make a object for (const config::any_child &value : cfg.all_children_range()) { const preproc_map::value_type def = preproc_define::read_pair( value.cfg ); input_macros[def.first] = def.second; ++read; } std::cerr << SDL_GetTicks() << " Read " << read << " defines.\n"; } const std::string resourceToProcess(*cmdline_opts.preprocess_path); const std::string targetDir(*cmdline_opts.preprocess_target); Uint32 startTime = SDL_GetTicks(); // if the users add the SKIP_CORE define we won't preprocess data/core bool skipCore = false; bool skipTerrainGFX = false; // the 'core_defines_map' is the one got from data/core macros preproc_map defines_map( input_macros ); if ( cmdline_opts.preprocess_defines ) { // add the specified defines for (const std::string &define : *cmdline_opts.preprocess_defines) { if (define.empty()){ std::cerr << "empty define supplied\n"; continue; } LOG_PREPROC << "adding define: " << define << '\n'; defines_map.insert(std::make_pair(define, preproc_define(define))); if (define == "SKIP_CORE") { std::cerr << "'SKIP_CORE' defined.\n"; skipCore = true; } else if (define == "NO_TERRAIN_GFX") { std::cerr << "'NO_TERRAIN_GFX' defined." << std::endl; skipTerrainGFX = true; } } } // add the WESNOTH_VERSION define defines_map["WESNOTH_VERSION"] = preproc_define(game_config::wesnoth_version.str()); std::cerr << "added " << defines_map.size() << " defines.\n"; // preprocess core macros first if we don't skip the core if (skipCore == false) { std::cerr << "preprocessing common macros from 'data/core' ...\n"; // process each folder explicitly to gain speed preprocess_resource(game_config::path + "/data/core/macros",&defines_map); if (skipTerrainGFX == false) preprocess_resource(game_config::path + "/data/core/terrain-graphics",&defines_map); std::cerr << "acquired " << (defines_map.size() - input_macros.size()) << " 'data/core' defines.\n"; } else std::cerr << "skipped 'data/core'\n"; // preprocess resource std::cerr << "preprocessing specified resource: " << resourceToProcess << " ...\n"; preprocess_resource(resourceToProcess, &defines_map, true,true, targetDir); std::cerr << "acquired " << (defines_map.size() - input_macros.size()) << " total defines.\n"; if ( cmdline_opts.preprocess_output_macros ) { std::string outputFileName = "_MACROS_.cfg"; if (!cmdline_opts.preprocess_output_macros->empty()) { outputFileName = *cmdline_opts.preprocess_output_macros; } std::string outputPath = targetDir + "/" + outputFileName; std::cerr << "writing '" << outputPath << "' with " << defines_map.size() << " defines.\n"; filesystem::scoped_ostream out = filesystem::ostream_file(outputPath); if (!out->fail()) { config_writer writer(*out,false); for(preproc_map::iterator itor = defines_map.begin(); itor != defines_map.end(); ++itor) { (*itor).second.write(writer, (*itor).first); } } else std::cerr << "couldn't open the file.\n"; } std::cerr << "preprocessing finished. Took "<< SDL_GetTicks() - startTime << " ticks.\n"; }