int backupfile(const std::string& filename, const std::string& backupname, int renamelevels){ std::fstream file(filename.c_str(),std::ios::in|std::ios::binary); if (!file.is_open()){ return -1; } ulti::mkdir(ulti::parentFolder(backupname).name,true); std::fstream fback; bool g2g = 0; int tries = 0; if (renamelevels>1){ for(int a = 0; a < renamelevels; a++){ std::stringstream ss(backupname); ss << backupname << ".back(" << a << ")"; fback.open(ss.str().c_str(),std::ios::in|std::ios::binary); if (!fback.is_open()){ fback.close(); fback.open(ss.str().c_str(),std::ios::out|std::ios::binary); if (!fback.is_open()){ continue; } fback << file.rdbuf(); std::stringstream ss2(backupname); ss2 << backupname << ".back(" << (a+1)%renamelevels << ")"; remove(ss2.str().c_str()); g2g=1; break; } else{ fback.close(); if (a == renamelevels-1 && tries == 0){ std::stringstream ss2(backupname); ss2 << backupname << ".back(" << 0 << ")"; remove(ss2.str().c_str()); tries++; a=-1; continue; } } } } else{ std::stringstream ss(backupname); ss << backupname << ".backup"; fback.open(ss.str().c_str(),std::ios::out|std::ios::binary); if (fback.is_open()){ fback << file.rdbuf(); g2g=1; } } file.close(); fback.close(); if (!g2g){ return -2; } return 1; }
bool CMessageCrypter::Decrypt(const string& vchPrivKey, const string& vchCiphertext, string& vchPlaintext) { try { AutoSeededRandomPool prng; StringSource ss(vchPrivKey, true /*pumpAll*/); Integer x; x.Decode(ss, ss.MaxRetrievable(), Integer::UNSIGNED); ECIES<ECP>::Decryptor decryptor; decryptor.AccessKey().AccessGroupParameters().Initialize(ASN1::secp256k1()); //make decryptor's access key using decoded private exponent's value decryptor.AccessKey().SetPrivateExponent(x); //check whether decryptor's access key is valid or not bool valid = decryptor.AccessKey().Validate(prng, 3); if(!valid) decryptor.AccessKey().ThrowIfInvalid(prng, 3); //decrypt the message using private key StringSource ss2 (vchCiphertext, true, new PK_DecryptorFilter(prng, decryptor, new StringSink(vchPlaintext) ) ); } catch(const CryptoPP::Exception& ex) { return false; } return true; }
// // Deterministically calculate a given "score" for a Masternode depending on how close it's hash is to // the proof of work for that block. The further away they are the better, the furthest will win the election // and get paid this block // uint256 CMasternode::CalculateScore(int mod, int64_t nBlockHeight) { if(chainActive.Tip() == NULL) return 0; uint256 hash = 0; uint256 aux = vin.prevout.hash + vin.prevout.n; if(!GetBlockHash(hash, nBlockHeight)) { LogPrintf("CalculateScore ERROR - nHeight %d - Returned 0\n", nBlockHeight); return 0; } CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << hash; uint256 hash2 = ss.GetHash(); CHashWriter ss2(SER_GETHASH, PROTOCOL_VERSION); ss2 << hash; ss2 << aux; uint256 hash3 = ss2.GetHash(); uint256 r = (hash3 > hash2 ? hash3 - hash2 : hash2 - hash3); return r; }
void test() { const pretype& const_pre_vector = pre_vector; local_check_equal(real_vector.size(), pre_vector.size()); local_check_equal(real_vector.empty(), pre_vector.empty()); for (Size s = 0; s < real_vector.size(); s++) { local_check(real_vector[s] == pre_vector[s]); local_check(&(pre_vector[s]) == &(pre_vector.begin()[s])); local_check(&(pre_vector[s]) == &*(pre_vector.begin() + s)); local_check(&(pre_vector[s]) == &*((pre_vector.end() + s) - real_vector.size())); } // local_check(realtype(pre_vector) == real_vector); local_check(pretype(real_vector.begin(), real_vector.end()) == pre_vector); local_check(pretype(pre_vector.begin(), pre_vector.end()) == pre_vector); size_t pos = 0; for (const T& v : pre_vector) { local_check(v == real_vector[pos++]); } for (const T& v : reverse_iterate(pre_vector)) { local_check(v == real_vector[--pos]); } for (const T& v : const_pre_vector) { local_check(v == real_vector[pos++]); } for (const T& v : reverse_iterate(const_pre_vector)) { local_check(v == real_vector[--pos]); } CDataStream ss1(SER_DISK, 0); CDataStream ss2(SER_DISK, 0); ss1 << real_vector; ss2 << pre_vector; local_check_equal(ss1.size(), ss2.size()); for (Size s = 0; s < ss1.size(); s++) { local_check_equal(ss1[s], ss2[s]); } }
void CSVMap::ConstructMap() { ifstream csvFile; csvFile.open(file_path_.c_str()); if(csvFile.is_open()) { string line; istringstream s(line); if(this->header_) { string header; //Record and skip header if(getline(csvFile, line)) { istringstream ss(line); while(getline(ss, header, ',')) this->headers_.push_back(header); } } while(getline(csvFile, line)) { istringstream ss(line); string column; Date* key_date = NULL; while(getline(ss, column, ',')) { if(key_date == NULL) { int string_date[3]; string splitdate; int count = 0; istringstream ss2(column); while(getline(ss2, splitdate, '/')) { string_date[count] = atoi(splitdate.c_str()); count++; } key_date = new Date(string_date[0], string_date[1], string_date[2]); } else this->csvmap_[*key_date].push_back(column); } delete key_date; } } else cout << "File not found.\n"; csvFile.close(); }
void unmap_path(string path, string fileid) { //cout << "in unmap_path" << endl; //cout << "path: " << path << " fileid: " << fileid << endl; string token = ""; string attr = ""; stringstream ss2(path.c_str()); while(getline(ss2, token, '/')) { //cout << "got token " << token << endl; if(strcmp(token.c_str(),"null")!=0) { if(attr.length()>0) { //cout << "removing map " << attr << " to " << token << endl; database_remove_val(fileid, attr, token); if(attr=="location") { int pos=find(server_ids.begin(),server_ids.end(),token)-server_ids.begin(); if( pos < server_ids.size() ) { database_remove_val(fileid, "server", servers.at(pos)); } } attr = ""; } else { attr = token; } } } //cout << "finished unmap_path" << endl << endl; }
static int xmp_unlink(const char *path) { //log_msg("in xmp_unlink"); //TODO: handle in vold somehow int res; string fileid=database_getval("name",basename(strdup(path))); string fromext=database_getval(fileid,"ext"); string file=append_path2(basename(strdup(path))); string attrs=database_getval(fromext,"attrs"); //cout << fromext << fileid << endl; //cout<<"HERE!"<<endl; database_remove_val(fileid,"attrs","all_"+fromext+"s"); //cout<<"THERE!"<<endl; //database_remove_val("all_"+fromext+"s",strdup(basename(strdup(from))),fileid); //cout<<"WHERE!"<<endl; string token=""; stringstream ss2(attrs.c_str()); while(getline(ss2,token,':')){ if(strcmp(token.c_str(),"null")!=0){ string cmd=database_getval(token+"gen","command"); string msg2=(cmd+" "+file).c_str(); FILE* stream=popen(msg2.c_str(),"r"); if(fgets(msg,200,stream)!=0){ database_remove_val(fileid,token,msg); } pclose(stream); } } path=append_path2(basename(strdup(path))); res = unlink(path); if (res == -1) return -errno; return 0; }
void process_file(string server, string fileid) { string file = database_getval(fileid, "name"); string ext = database_getval(fileid, "ext"); file = server + "/" + file; string attrs=database_getval(ext,"attrs"); string token=""; stringstream ss2(attrs.c_str()); while(getline(ss2,token,':')){ if(strcmp(token.c_str(),"null")!=0){ if(token == "name") { continue; } //cout << "========= looking at attr = " << token <<endl; string cmd=database_getval(token+"gen","command"); if(cmd=="null") { //cout << "command is null, skipping" << endl; continue; } string msg2=(cmd+" \""+file+"\"").c_str(); //cout << "========= issuing command = " << msg2 <<endl; FILE* stream=popen(msg2.c_str(),"r"); if(fgets(msg,200,stream)!=0){ //cout << "========= attr value = " << msg <<endl; database_setval(fileid,token,msg); } pclose(stream); } } }
/** * @function sendMsg */ bool sendMsg( BYTE _buf[BUFFER_SIZE] ) { // Cast as char* std::string text( (char*)_buf ); // Read lines std::vector<pos> values; std::stringstream ss( text ); std::string line; while( true ) { std::getline(ss, line); if( ss.eof() ) { break; } std::stringstream ss2(line); pos p; ss2 >> p.id >> p.x >> p.y >> p.z >> p.qw >> p.qx >> p.qy >> p.qz; values.push_back(p); } // Send msg sns_msg_tracker* msg; msg = sns_msg_tracker_alloc( values.size() ); msg->header.n = values.size(); for( int i = 0; i < msg->header.n; ++i ) { msg->u[i].x = values[i].x; msg->u[i].y = values[i].y; msg->u[i].z = values[i].z; msg->u[i].qx = values[i].qx; msg->u[i].qy = values[i].qy; msg->u[i].qz = values[i].qz; msg->u[i].qw = values[i].qw; msg->u[i].id = values[i].id; } return ( ach_put( &chan, msg, sns_msg_tracker_size( msg ) ) == ACH_OK ); }
void subtractBackground(const TString conf){ std::cout << "conf=" << conf << "\n"; // Read from configuration file only the location of the root files TString inputDir; Double_t lumi; Bool_t doWeight; ifstream ifs; ifs.open(conf.Data()); if (!ifs.is_open()) { std::cout << "failed to open file <" << conf << ">\n"; assert(ifs.is_open()); } string line; vector<TString> snamev; // sample name (for output file) vector<CSample*> samplev; // data/MC samples Int_t state=0; while(getline(ifs,line)) { if(line[0]=='#') continue; if(line[0]=='%') { state++; continue; } if(line[0]=='$') { samplev.push_back(new CSample()); stringstream ss(line); string chr; string sname; Int_t color; ss >> chr >> sname >> color; string label = line.substr(line.find('@')+1); snamev.push_back(sname); samplev.back()->label = label; samplev.back()->color = color; continue; } if(state==0) { // general settings stringstream ss1(line); ss1 >> lumi; getline(ifs,line); stringstream ss2(line); ss2 >> doWeight; getline(ifs,line); inputDir = TString(line); getline(ifs,line); // backwards compatibility for the input file if (line.size()>3) { // escale is defined TString escaleTag_loc=TString(line); getline(ifs,line); // check that it was correct to use this work-around if (line.find('%')!=std::string::npos) { std::cout << "backwards-compatibility code failure\n"; return; } } TString format_loc = TString(line); } else if(state==1) { // define data sample
void selectEleBDTGWithIPInfoEffTP(const TString conf, // input file const TString outputDir, // output directory const Bool_t matchGen = kFALSE // match to generator muons ) { gBenchmark->Start("selectEleLHEffTP"); //-------------------------------------------------------------------------------------------------------------- // Settings //============================================================================================================== //***************************************************************************************** //Setup MVA //***************************************************************************************** mithep::ElectronIDMVA *electronIDMVAWithIPInfo = new mithep::ElectronIDMVA(); electronIDMVAWithIPInfo->Initialize("BDTG method", "/home/sixie/CMSSW_analysis/src/MitPhysics/data/ElectronMVAWeights/Subdet0LowPt_WithIPInfo_BDTG.weights.xml", "/home/sixie/CMSSW_analysis/src/MitPhysics/data/ElectronMVAWeights/Subdet1LowPt_WithIPInfo_BDTG.weights.xml", "/home/sixie/CMSSW_analysis/src/MitPhysics/data/ElectronMVAWeights/Subdet2LowPt_WithIPInfo_BDTG.weights.xml", "/home/sixie/CMSSW_analysis/src/MitPhysics/data/ElectronMVAWeights/Subdet0HighPt_WithIPInfo_BDTG.weights.xml", "/home/sixie/CMSSW_analysis/src/MitPhysics/data/ElectronMVAWeights/Subdet1HighPt_WithIPInfo_BDTG.weights.xml", "/home/sixie/CMSSW_analysis/src/MitPhysics/data/ElectronMVAWeights/Subdet2HighPt_WithIPInfo_BDTG.weights.xml", mithep::ElectronIDMVA::kWithIPInfo); // mass region Double_t massLo; Double_t massHi; Double_t lumi; // luminosity (pb^-1) vector<TString> fnamev; // sample files vector<Int_t> typev; // dataset type vector<Double_t> xsecv; // per file cross section vector<TString> jsonv; // per file JSON file // // parse .conf file // ifstream ifs; ifs.open(conf.Data()); assert(ifs.is_open()); string line; Int_t state=0; while(getline(ifs,line)) { if(line[0]=='#') continue; if(line[0]=='%') { state++; continue; } if(state==0) { // general settings stringstream ss1(line); ss1 >> lumi; getline(ifs,line); stringstream ss2(line); ss2 >> massLo >> massHi; } else if(state==1) { // define data sample
void OutfitWindow::load(const bool oldConfig) { const Configuration *cfg; if (oldConfig) cfg = &config; else cfg = &serverConfig; memset(mItems, -1, sizeof(mItems)); memset(mItemColors, 1, sizeof(mItemColors)); for (unsigned o = 0; o < OUTFITS_COUNT; o++) { std::string outfit = cfg->getValue("Outfit" + toString(o), "-1"); std::string buf; std::stringstream ss(outfit); std::vector<int> tokens; while (ss >> buf) tokens.push_back(atoi(buf.c_str())); for (size_t i = 0, sz = tokens.size(); i < sz && i < OUTFIT_ITEM_COUNT; i++) { mItems[o][i] = tokens[i]; } outfit = cfg->getValue("OutfitColor" + toString(o), "1"); std::stringstream ss2(outfit); tokens.clear(); std::vector<unsigned char> tokens2; while (ss2 >> buf) tokens2.push_back(static_cast<unsigned char>(atoi(buf.c_str()))); for (size_t i = 0, sz = tokens2.size(); i < sz && i < OUTFIT_ITEM_COUNT; i++) { mItemColors[o][i] = tokens2[i]; } mItemsUnequip[o] = cfg->getValueBool("OutfitUnequip" + toString(o), true); } mAwayOutfit = cfg->getValue("OutfitAwayIndex", OUTFITS_COUNT - 1); if (mAwayOutfit >= static_cast<int>(OUTFITS_COUNT)) mAwayOutfit = static_cast<int>(OUTFITS_COUNT) - 1; if (mAwayOutfitCheck) mAwayOutfitCheck->setSelected(mAwayOutfit == mCurrentOutfit); }
void Rig::loadJSON(JSONNode root) { //JSONNode::const_iterator i = root.begin(); JSONNode::iterator i = root.begin(); auto version = root.find("version"); if (version == root.end()) { Logger::log(ERR, "No version specified for input file. Aborting load."); return; } else { stringstream ss; stringstream ss2(version->as_string()); ss << LumiverseCore_VERSION_MAJOR << "." << LumiverseCore_VERSION_MINOR; float libVer; float fileVer; ss >> libVer; ss2 >> fileVer; if (fileVer < libVer) { // Friendly warning if you're loading an old file. Logger::log(WARN, "File created against earlier version of Lumiverse. Check logs for any load problems."); } else if (fileVer > libVer) { // Loading newer file with older library. Logger::log(WARN, "File created against newer version of Lumiverse. Check logs for any load problems."); } } while (i != root.end()){ // get the node name and value as a string std::string nodeName = i->name(); if (nodeName == "devices") { loadDevices(*i); Logger::log(INFO, "Device load complete"); } else if (nodeName == "patches") { i->push_back(*root.find("jsonPath")); loadPatches(*i); Logger::log(INFO, "Patch load complete"); } else if (nodeName == "refreshRate") { setRefreshRate(i->as_int()); } //increment the iterator ++i; } }
TString subtractBackground(const TString conf, DYTools::TSystematicsStudy_t runMode=DYTools::NORMAL, const TString plotsDirExtraTag="", int performPUReweight=1){ std::cout << "\n\nRun mode: " << SystematicsStudyName(runMode) << "\n"; switch(runMode) { case DYTools::NORMAL: case DYTools::ESCALE_STUDY: case DYTools::ESCALE_STUDY_RND: break; default: std::cout << "subtractBackground is not ready for runMode=" << SystematicsStudyName(runMode) << "\n"; throw 2; } //-------------------------------------------------------------------------------------------------------------- // Settings //============================================================================================================== // Read from configuration file only the location of the root files TString inputDir; Double_t lumi; Bool_t doWeight; Bool_t hasData=false; ifstream ifs; ifs.open(conf.Data()); assert(ifs.is_open()); string line; int state=0; while(getline(ifs,line)) { if(line[0]=='#') continue; if(line[0]=='%') { state++; continue; } if(state==0) { stringstream ss1(line); ss1 >> lumi; getline(ifs,line); stringstream ss2(line); ss2 >> doWeight; getline(ifs,line); inputDir = TString(line); TString escaleTag_loc,format_loc; getline(ifs,line); stringstream ss3(line); ss3 >> escaleTag_loc; getline(ifs,line); format_loc = TString(line); state++; } else if (state==1) {
int CAddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src) const { CDataStream ss1(SER_GETHASH, 0); std::vector<unsigned char> vchGroupKey = GetGroup(); std::vector<unsigned char> vchSourceGroupKey = src.GetGroup(); ss1 << nKey << vchGroupKey << vchSourceGroupKey; uint64_t hash1 = Hash(ss1.begin(), ss1.end()).GetLow64(); CDataStream ss2(SER_GETHASH, 0); ss2 << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP); uint64_t hash2 = Hash(ss2.begin(), ss2.end()).GetLow64(); return hash2 % ADDRMAN_NEW_BUCKET_COUNT; }
int CAddrInfo::GetTriedBucket(const uint256& nKey) const { CDataStream ss1(SER_GETHASH, 0); std::vector<unsigned char> vchKey = GetKey(); ss1 << nKey << vchKey; uint64_t hash1 = Hash(ss1.begin(), ss1.end()).GetLow64(); CDataStream ss2(SER_GETHASH, 0); std::vector<unsigned char> vchGroupKey = GetGroup(); ss2 << nKey << vchGroupKey << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP); uint64_t hash2 = Hash(ss2.begin(), ss2.end()).GetLow64(); return hash2 % ADDRMAN_TRIED_BUCKET_COUNT; }
bool Chunk::load() { std::ifstream file(getPathFromCoords(mCoords)); if (!file) { return false; } std::string line; std::size_t layerCount; std::getline(file,line); { std::istringstream iss(line); iss >> layerCount; } for (std::size_t i = 0; i < layerCount; i++) { addLayer(); } sf::Vector2i coords = sf::Vector2i(); int z = 0; while (std::getline(file,line)) { std::stringstream ss1(line); std::string temp1; coords.x = 0; while (std::getline(ss1,temp1,';')) { std::stringstream ss2(temp1); std::string temp2; z = 0; while (std::getline(ss2,temp2,'-')) { int id; { std::istringstream iss(temp2); iss >> id; } setTileId(coords,z,id); z++; } coords.x++; } coords.y++; } file.close(); mNeedSave = false; return true; }
// // Deterministically calculate a given "score" for a Masternode depending on how close it's hash is to // the proof of work for that block. The further away they are the better, the furthest will win the election // and get paid this block // arith_uint256 CMasternode::CalculateScore(const uint256& blockHash) { uint256 aux = ArithToUint256(UintToArith256(vin.prevout.hash) + vin.prevout.n); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << blockHash; arith_uint256 hash2 = UintToArith256(ss.GetHash()); CHashWriter ss2(SER_GETHASH, PROTOCOL_VERSION); ss2 << blockHash; ss2 << aux; arith_uint256 hash3 = UintToArith256(ss2.GetHash()); return (hash3 > hash2 ? hash3 - hash2 : hash2 - hash3); }
void verticesGraph::buildGraph(char * fileName) { milesTraveled = 0; std::string firstLine,lines; std::string itemArray[20][20]; int m=0,quantity=0; std::ifstream inFile; inFile.open(fileName); if(inFile.good()) { getline(inFile,firstLine); std::stringstream ss1(firstLine); std::string items1; while(getline(ss1,items1,',')) { quantity+=1; } quantity-=1; while(getline(inFile,lines)) { int n=0; std::stringstream ss2(lines); std::string items2; while(getline(ss2,items2,',')) { itemArray[m][n]=items2; n+=1; } m+=1; } } for(int m=0;m<quantity;m++) { addVertex(itemArray[m][0]); } for(int m=0;m<quantity;m++) { for(int n=0;n<quantity;n++) { if(itemArray[m][n+1]!="-1"&&itemArray[m][n+1]!="0") { addEdge(itemArray[m][0],itemArray[n][0],atoi(itemArray[m][n+1].c_str())); } } } }
/** * @brief Decrypts input string stream using AES in GCM mode for * confidentiality and authenticity. * * @param cipher const reference to a byte vector with encrypted data. * @param messageData reference to a byte vector to hold decrypted data. * @param key const reference to a byte vector with the decryption key. * * @return true, if decryption is successful. */ bool FileCryptopp::decrypt( const std::vector<uint8_t>& cipher, std::vector<uint8_t>& messageData, const std::vector<uint8_t>& key ) { // Initial Vector (IV) for AES to XOR. std::vector<uint8_t> iv(CryptoPP::AES::BLOCKSIZE); std::string decryptedtext; // store decrypted message try { // Initialize AES. CryptoPP::GCM< AES >::Decryption e; // Set AES Key and load IV. e.SetKeyWithIV(key.data(), key.size(), iv.data()); /* Load encrypted data into an array source, then decrypt data using * a transformation filter. Dump the transformation using a string * sink into decryptedtext. */ ArraySource ss2( cipher.data(), cipher.size(), true, new CryptoPP::AuthenticatedDecryptionFilter( e, new StringSink(decryptedtext) ) // StreamTransformationFilter ); // StringSource } catch (const CryptoPP::Exception& e) { // Failed decryption. std::cerr << "Error decrypting file: " << e.what() << std::endl; return false; } // Append messageData with bytes from decryptedtext. for (int i = 0; i < decryptedtext.size(); i++) { messageData.push_back( 0xFF & static_cast<uint8_t>(decryptedtext[i]) ); } return true; }
void selectSingleMuTrigEffTP(const TString conf, // input file const TString outputDir, // output directory Int_t RunRange = 0, // Run Range const Bool_t matchGen = kFALSE // match to generator muons ) { gBenchmark->Start("selectSingleMuEffTP"); //-------------------------------------------------------------------------------------------------------------- // Settings //============================================================================================================== // mass region Double_t massLo; Double_t massHi; Double_t lumi; // luminosity (pb^-1) vector<TString> fnamev; // sample files vector<Int_t> typev; // dataset type vector<Double_t> xsecv; // per file cross section vector<TString> jsonv; // per file JSON file // // parse .conf file // ifstream ifs; ifs.open(conf.Data()); assert(ifs.is_open()); string line; Int_t state=0; while(getline(ifs,line)) { if(line[0]=='#') continue; if(line[0]=='%') { state++; continue; } if(state==0) { // general settings stringstream ss1(line); ss1 >> lumi; getline(ifs,line); stringstream ss2(line); ss2 >> massLo >> massHi; } else if(state==1) { // define data sample
void Test::LoadAnswers() { std::string buffer, number; std::ifstream file; file.open("../Data/Answers.csv"); if (!file.is_open()) throw std::exception("Error: file(Question.csv) is not opened!\n"); int question_num; while (!file.eof()) { std::getline(file, buffer); std::vector<std::string> data = ParseCSVString(buffer); if (!data.size()) break; number = data[0]; std::stringstream ss(number); ss >> question_num; Answer answer(data[1]); for (auto it = data.begin() + 2; it != data.end(); it++) { // read trait number int trait_, score_; number = *it; std::stringstream ss1(number); ss1 >> trait_; //read score it++; number = *it; std::stringstream ss2(number); ss2 >> score_; answer.AddPoint(trait_, score_); } questions[question_num].answers.push_back(answer); } file.close(); }
TEST_F(LoadPlanningModelsPr2, StateSpaces) { ompl_interface::ModelBasedStateSpaceSpecification spec1(kmodel_, "right_arm"); ompl_interface::ModelBasedStateSpace ss1(spec1); ss1.setup(); ompl_interface::ModelBasedStateSpaceSpecification spec2(kmodel_, "left_arm"); ompl_interface::ModelBasedStateSpace ss2(spec2); ss2.setup(); ompl_interface::ModelBasedStateSpaceSpecification spec3(kmodel_, "whole_body"); ompl_interface::ModelBasedStateSpace ss3(spec3); ss3.setup(); ompl_interface::ModelBasedStateSpaceSpecification spec4(kmodel_, "arms"); ompl_interface::ModelBasedStateSpace ss4(spec4); ss4.setup(); std::ofstream fout("ompl_interface_test_state_space_diagram2.dot"); ompl::base::StateSpace::Diagram(fout); }
//--------------------------------------------------------------------------- QString fileload(QVector<aln::s_inp> &vOrgSeq, QString alnfile, int &nrErrors) { QString fileName = alnfile; QVector <aln::s_inp> NN = vOrgSeq; int nn = nrErrors; nn++; //check file QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { return("ERROR - Could not open file!"); }//if QString str2; QTextStream ss2(&str2); ss2 << "Aln File: " << fileName << endl; return (str2); }
int compareVersion(string version1, string version2) { vector<int> v1, v2; int x; for (int i = 0; i < version1.size(); i++) if (version1[i] == '.') version1[i] = ' '; for (int i = 0; i < version2.size(); i++) if (version2[i] == '.') version2[i] = ' '; stringstream ss1(version1), ss2(version2); while (ss1 >> x) { v1.push_back(x); } while (ss2 >> x) { v2.push_back(x); } while (v1.size() > 0 && v1[v1.size() - 1] == 0 ) { if (v1[v1.size() - 1] == 0) v1.erase(v1.end() - 1); } while (v2.size() > 0 && v2[v2.size() - 1] == 0) { if (v2[v2.size() - 1] == 0) v2.erase(v2.end() - 1); } int i = 0, j = 0; for (; i < v1.size() && j < v2.size(); i++, j++) { if (v1[i] > v2[i]) return 1; if (v2[i] > v1[i]) return -1; } if (i < v1.size()) return 1; if (j < v2.size()) return -1; return 0; }
int main(int argc, char *argv[]) { if( argc < 5 ) { cerr << "Lack of args: need three args!" << endl; return -1; } ADDRINT nSizePower; stringstream ss(argv[1]); ss >> nSizePower; cerr << "Memory Size (in bytes):\t" << hex << (1<<nSizePower) << dec << endl; string szFile = argv[2]; ADDRINT nLineSizeShift; stringstream ss1(argv[3]); ss1 >> nLineSizeShift; bool bStackAllocator = true; stringstream ss2(argv[4]); ss2 >> bStackAllocator; CAllocator *allocator; if(bStackAllocator) allocator = new CStackAllocator(nSizePower, nLineSizeShift, szFile); else allocator = new CHeapAllocator(nSizePower, nLineSizeShift, szFile); allocator->run(); return 0; }
void RandomTree::_importOobSet(std::istream & fileStream) { if(fileStream.good()) { std::string buffer; std::getline(fileStream, buffer); std::stringstream ss(buffer); std::string firstStr; std::string nextStr; unsigned int idx; ss >> firstStr; if(firstStr == "<OobSet>") { ss >> nextStr; while(nextStr != "</OobSet>") { std::stringstream ss2(nextStr); ss2 >> idx; _oobSet.push_back(idx); ss >> nextStr; } }
int initializing_khan(char * mnt_dir) { //log_msg("In initialize\n"); unmounting(mnt_dir); //Opening root directory and creating if not present //cout<<"khan_root[0] is "<<servers.at(0)<<endl; if(NULL == opendir(servers.at(0).c_str())) { sprintf(msg,"Error msg on opening directory : %s\n",strerror(errno)); //log_msg(msg); //log_msg("Root directory might not exist..Creating\n"); string command = "mkdir " + servers.at(0); if (system(command.c_str()) < 0) { log_msg("Unable to create storage directory...Aborting\n"); exit(1); } } else { fprintf(stderr, "directory opened successfully\n"); } init_database(); //check if we've loaded metadata before string output=database_getval("setup","value"); if(output.compare("true")==0){ log_msg("Database was previously initialized."); tot_time+=(stop.tv_sec-start.tv_sec)+(stop.tv_nsec-start.tv_nsec)/BILLION; return 0; //setup has happened before } //if we have not setup, do so now //log_msg("it hasnt happened, setvalue then setup"); database_setval("setup","value","true"); //load metadata associatons for(int i=0; i<servers.size(); i++){ process_transducers(servers.at(i)); } //load metadata for each file on each server string types=database_getval("allfiles","types"); //cout << "================= types to look for ="<<types<<endl; for(int i=0; i<servers.size(); i++) { if(servers.at(i) == "cloud") { PyObject* myFunction = PyObject_GetAttrString(cloud_interface,(char*)"get_all_titles"); PyObject* myResult = PyObject_CallObject(myFunction, NULL); if(myResult==NULL) { PyErr_PrintEx(0); continue; } int n = PyList_Size(myResult); //cout << "SIZE = " << n << endl << flush; for(int j = 0; j<n; j++) { PyObject* title = PyList_GetItem(myResult, j); char* temp = PyString_AsString(title); if(temp==NULL) { PyErr_PrintEx(0); continue; } string filename = temp; //cout << "Checking " << filename << " ... " << endl << flush; if(database_getval("name",filename)=="null") { string fileid = database_setval("null","name",filename); string ext = strrchr(filename.c_str(),'.')+1; database_setval(fileid,"ext",ext); database_setval(fileid,"server",servers.at(i)); database_setval(fileid,"location",server_ids.at(i)); string attrs=database_getval(ext,"attrs"); string token=""; stringstream ss2(attrs.c_str()); PyObject* myFunction = PyObject_GetAttrString(cloud_interface,(char*)"get_metadata"); while(getline(ss2,token,':')){ if(strcmp(token.c_str(),"null")!=0){ //cout << "========= looking at attr = " << token << endl << flush; PyObject* arglist = PyTuple_New(2); PyTuple_SetItem(arglist, 0, PyString_FromString(filename.c_str())); PyTuple_SetItem(arglist, 1, PyString_FromString(token.c_str())); PyObject* myResult = PyObject_CallObject(myFunction, arglist); //cout << myResult << endl << flush; if(myResult==NULL) { PyErr_PrintEx(0); continue; } char* msg = PyString_AsString(myResult); if(!msg) { PyErr_PrintEx(0); continue; } string val = msg; Py_DECREF(arglist); Py_DECREF(myResult); //cout << "========= got val = " << val << endl << flush; if(val!="na") { database_setval(fileid,token,val); } } } } else { string fileid = database_getval("name", filename); database_setval(fileid,"server",servers.at(i)); database_setval(fileid,"location",server_ids.at(i)); } } } else { glob_t files; glob((servers.at(i)+"/*.*").c_str(),0,NULL,&files); for(int j=0; j<files.gl_pathc; j++) {//for each file string file = files.gl_pathv[j]; string ext = strrchr(file.c_str(),'.')+1; string filename=strrchr(file.c_str(),'/')+1; if(database_getval("name", filename) == "null") { string fileid = database_setval("null","name",filename); database_setval(fileid,"ext",ext); database_setval(fileid,"server",servers.at(i)); database_setval(fileid,"location",server_ids.at(i)); for(int k=0; k<server_ids.size(); k++) { database_setval(fileid, server_ids.at(k), "0"); } if(j%10==0) { cout << "processed file " << j << "\n"; } process_file(servers.at(i), fileid); } else { string fileid = database_getval("name",filename); database_setval(fileid,"server",servers.at(i)); database_setval(fileid,"location",server_ids.at(i)); } } } } //log_msg("At the end of initialize\n"); return 0; }
string Calculation::work() { /*原理:后缀队列里面的front为符号时,弹出数字栈中的第一个元素a 第二个元素 b 运算顺序b+-a 再把结果入数字栈*/ while(!num.empty())num.pop(); while(!Suf.empty()) { string t=Suf.front(); Suf.pop(); if(t=="")continue ; //cout<<t<<endl; if(t=="+"||t=="-"||t=="*"||t=="/") { double a; double b; string t1,t2; if(num.empty())t1+='0';//栈为空 就 为0 例如 -1000 == 0-1000 else { t1=num.top(); num.pop(); } if(num.empty())t2+='0'; else { t2=num.top(); num.pop(); } /*字符串转为数字*/ stringstream ss(t1); ss>>a; stringstream ss2(t2); ss2>>b; //cout<<a<<" "<<b<<" "<<t<<endl; if(t=="+") { stringstream tostring; tostring<<a+b; //cout<<tostring.str()<<endl; num.push(tostring.str()); /*数字转为字符串*/ } if(t=="-") { stringstream tostring; tostring<<b-a; //cout<<tostring.str()<<endl; num.push(tostring.str()); } if(t=="*") { stringstream tostring; tostring<<a*b; num.push(tostring.str()); } if(t=="/") { stringstream tostring; tostring<<b/a; num.push(tostring.str()); } } else {
int main(int argc, char **argv) { //You must call ros::init() first of all. ros::init() function needs to see argc and argv. The third argument is the name of the node ros::init(argc, argv, "PickerRobot"); // convert input parameters for Robot initialization from String to respective types std::string xString = argv[1]; std::string yString = argv[2]; //theta is arg3 std::string pickRangeString = argv[6]; double xPos = atof(xString.c_str()); double yPos = atof(yString.c_str()); double pickRange = (atof(pickRangeString.c_str()))/2+0.1; ROS_INFO("x start: %f", xPos); ROS_INFO("y start: %f", yPos); ROS_INFO("pick range %f",pickRange); //assign start and finish beacons from input parameters of launch file std::string startString = argv[4]; std::string finishString = argv[5]; std::stringstream ss(startString); ss >> startBeacon; std::stringstream ss2(finishString); ss2 >> finishBeacon; currentBeacon = startBeacon; //initialize the Picker robot with the correct position, velocity and state parameters. pickerRobot = PickerRobot(xPos,yPos,M_PI/2,0,0,"To next beacon",pickRange); //NodeHandle is the main access point to communicate with ros. ros::NodeHandle n; //picker robot advertise it node for its velocity message to be published. pickerRobot.robotNode_stage_pub=n.advertise<geometry_msgs::Twist>("cmd_vel",1000); //picker robot advertise it node for its status message to be published. ros::Publisher pub=n.advertise<se306project::robot_status>("status",1000); //subscribe to listen to messages coming from stage about is position relative to absolute frame pickerRobot.stageOdo_Sub = n.subscribe<nav_msgs::Odometry>("base_pose_ground_truth",1000, callBackStageOdm); //subscribe to obstacle detection pickerRobot.baseScan_Sub = n.subscribe<sensor_msgs::LaserScan>("base_scan", 1000,callBackLaserScan); // publish weedobstacle pickerRobot.weed_obstacle_pub = n.advertise<se306project::weed_status>("weed",1000); //TODO need to subscribe to all carriers //subscribe to other carrier std::string carrierStart(argv[7]); std::string carrierEnd(argv[8]); int a = atoi(carrierStart.c_str()); int b = atoi(carrierEnd.c_str()); int size = b-a+1; std::string topicName=""; //subscribing all the picker robot ros::Subscriber *carrierArray = new ros::Subscriber[size]; int index = 0; for (int i = a; i<=b; i++) { std::stringstream convert; convert << i; topicName = "/robot_" + convert.str() + "/status"; //subscribe to carrier robot's status message carrierArray[index] = n.subscribe<se306project::carrier_status>(topicName,1000,receiveCarrierRobotStatus); index++; } // assign beacon subscriber to the first beacon for this Picker robot's path. pickerRobot.subscribeNextBeacon(n); unsigned int num_readings = 100; double laser_frequency = 40; double ranges[num_readings]; double intensities[num_readings]; se306project::robot_status status_msg; ros::Rate loop_rate(10); //a count of howmany messages we have sent while (ros::ok()) { int count = 0; //assign to status message status_msg.my_counter = count++;//add counter to message to broadcast status_msg.status=pickerRobot.getStatus();//add status to message to broadcast //status_msg.status ="Full"; status_msg.pos_x=pickerRobot.getX(); //add x to message to broadcast status_msg.pos_y=pickerRobot.getY();//add y to message to broadcast status_msg.pos_theta=pickerRobot.getTheta(); //add angle to message to broadcast status_msg.obstacle = pickerRobot.getObstacleStatus(); pub.publish(status_msg);//publish the message for other node pickerRobot.stateLogic(n); ros::spinOnce(); loop_rate.sleep(); ++count; } delete[] carrierArray; return 0; }