std::string URLData::clearURL(std::string str) { //clean php URLs if (str.find("?")!=std::string::npos) { std::size_t found = str.find("?"); if (found!=std::string::npos) str = str.substr(0, found); } //clean js URLs if (str.rfind(";")!=std::string::npos) { std::size_t found = str.rfind(";"); if (found!=std::string::npos) str = str.substr(0, found); } //delete the last / if (str.back() == '/') { str.erase (str.end()-1, str.end()); } //delete the root URL for insa-lyon.fr URLs if (str.find("insa-lyon.fr")!=std::string::npos) { if (str.find(".fr:90")!=std::string::npos) { std::size_t found = str.find("90"); if (found!=std::string::npos) str = str.substr(found+2, str.size()); } else if (str.find(".fr")!=std::string::npos) { std::size_t found = str.find(".fr"); if (found!=std::string::npos) str = str.substr(found+3, str.size()); } } //delete the root URL for intranet-if URLs if (str.find("intranet-if")!=std::string::npos) { if (str.find("90")!=std::string::npos) { std::size_t found = str.find("90"); if (found!=std::string::npos) str = str.substr(found+2, str.size()); } } //Clean and order URLs from google if (str.find("google")!=std::string::npos) { str = "Google"; } //Clean and order URLs from facebook if (str.find("facebook")!=std::string::npos) { str = "Facebook"; } return str; }
Strings searchDirectory( const std::string& directory, const std::string& pattern ) { Strings files; #ifdef _MSC_VER WIN32_FIND_DATA file; const std::string search = directory.empty() ? pattern : directory + '\\' + pattern; HANDLE hSearch = FindFirstFile( search.c_str(), &file ); if( hSearch == INVALID_HANDLE_VALUE ) { EQVERB << "Error finding the first file to match " << pattern << " in " << directory << std::endl; FindClose( hSearch ); return files; } files.push_back( file.cFileName ); while( FindNextFile( hSearch, &file )) files.push_back( file.cFileName ); FindClose( hSearch ); #else const size_t findPos = pattern.find( '*' ); if( findPos == std::string::npos ) { EQASSERTINFO( 0, "Unimplemented" ); return files; } const std::string first = pattern.substr( 0, findPos ); const std::string second = pattern.substr( findPos + 1 ); DIR* dir = opendir( directory.c_str() ); if( dir == 0 ) { EQVERB << "Can't open directory " << directory << std::endl; return files; } struct dirent* entry; while(( entry = readdir( dir )) != 0 ) { const std::string candidate( entry->d_name ); if( candidate.find( first ) != 0 ) continue; // doesn't start with filename const size_t end = candidate.rfind( second ); if( end == std::string::npos || // not found end + second.size() < candidate.size( )) // not at the end { continue; } files.push_back( entry->d_name ); } closedir(dir); #endif return files; }
void ColorTableManager::ImportColorTable(const std::string &ctFileName) { if(ctFileName.size() > 3 && ctFileName.substr(ctFileName.size() - 3) == ".ct") { // // Read the color table from the XML file. // DataNode *node = ReadConfigFile(ctFileName.c_str()); if(node != 0) { std::string ctName; std::string::size_type pos = ctFileName.rfind(VISIT_SLASH_STRING); if(pos == std::string::npos) ctName = ctFileName; else ctName = ctFileName.substr(pos + 1, ctFileName.size() - pos - 1 - 3); // Look for the ColorTable node. DataNode *node2 = node->SearchForNode("ColorTable"); if(node2 == 0) return; ColorControlPointList ccpl2; ccpl2.SetFromNode(node2); ccpl2.SetExternalFlag(true); if (ccpl2.GetCategoryName() == std::string("")) { if (importingPersonal) ccpl2.SetCategoryName("UserDefined"); else ccpl2.SetCategoryName("Standard"); } // Check for errors that would break code down the line int ii; bool broken = false; for (ii = 0 ; ii < ccpl2.GetNumControlPoints() ; ii++) { float pos = ccpl2[ii].GetPosition(); if (pos < 0.0f || pos > 1.0) { broken = true; break; } if (ii >= 1) { float prevPos = ccpl2[ii-1].GetPosition(); if (prevPos > pos) { broken = true; break; } } } if (broken) { debug4 << "Could not read " << ctFileName.c_str() << "!" << endl; } else { ctAtts->AddColorTable(ctName, ccpl2); debug4 << "Imported color table " << ctFileName.c_str() << " as " << ctName.c_str() << endl; } delete node; } else debug4 << "Could not read " << ctFileName.c_str() << "!" << endl; } }
std::string LLViewerParcelMedia::extractDomain(std::string url) { static std::string last_region = "@"; if (url.empty()) { return url; } LLStringUtil::toLower(url); size_t pos = url.find("//"); if (pos != std::string::npos) { size_t count = url.size() - pos + 2; url = url.substr(pos + 2, count); } // Check that there is at least one slash in the URL and add a trailing // one if not (for media/audio URLs such as http://mydomain.net) if (url.find('/') == std::string::npos) { url += '/'; } // If there's a user:password@ part, remove it pos = url.find('@'); if (pos != std::string::npos && pos < url.find('/')) // if '@' is not before the first '/', then it's not a user:password { size_t count = url.size() - pos + 1; url = url.substr(pos + 1, count); } std::string current_region = gAgent.getRegion()->getHost().getHostName(); if (!current_region.size()) { current_region = gAgent.getRegion()->getHost().getIPString(); } if (url.find(current_region) == 0 || url.find(last_region) == 0) { // This must be a scripted object rezzed in the region: // extend the concept of "domain" to encompass the // scripted object server id and avoid blocking all other // objects at once in this region... // Get rid of any port number pos = url.find('/'); // We earlier made sure that there's one url = current_region + url.substr(pos); pos = url.find('?'); if (pos != std::string::npos) { // Get rid of any parameter url = url.substr(0, pos); } pos = url.rfind('/'); if (pos != std::string::npos) { // Get rid of the filename, if any, keeping only the server + path url = url.substr(0, pos); } } else { pos = url.find(':'); if (pos != std::string::npos && pos < url.find('/')) { // Keep anything before the port number and strip the rest off url = url.substr(0, pos); } else { pos = url.find('/'); // We earlier made sure that there's one url = url.substr(0, pos); } } // Remember this region, so to cope with requests occuring just after a // TP out of it. last_region = gAgent.getRegion()->getHost().getHostName(); if (!last_region.size()) { last_region = gAgent.getRegion()->getHost().getIPString(); } return url; }
std::string Tfile::getFolder(std::string filePath) { return filePath.substr(0,filePath.rfind('/')+1); }
void Map::saveOtbm(const std::string& fileName, const UIWidgetPtr&/* pbar*/) { FileStreamPtr fin = g_resources.createFile(fileName); if(!fin) stdext::throw_exception(stdext::format("failed to open file '%s' for write", fileName)); fin->cache(); std::string dir; if(fileName.find_last_of('/') == std::string::npos) dir = g_resources.getWorkDir(); else dir = fileName.substr(0, fileName.find_last_of('/')); uint32 version = 0; if(g_things.getOtbMajorVersion() < ClientVersion820) version = 1; else version = 2; /// Usually when a map has empty house/spawn file it means the map is new. /// TODO: Ask the user for a map name instead of those ugly uses of substr std::string::size_type sep_pos; std::string houseFile = getHouseFile(); std::string spawnFile = getSpawnFile(); std::string cpyf; if((sep_pos = fileName.rfind('.')) != std::string::npos && stdext::ends_with(fileName, ".otbm")) cpyf = fileName.substr(0, sep_pos); if(houseFile.empty()) houseFile = cpyf + "-houses.xml"; if(spawnFile.empty()) spawnFile = cpyf + "-spawns.xml"; /// we only need the filename to save to, the directory should be resolved by the OTBM loader not here if((sep_pos = spawnFile.rfind('/')) != std::string::npos) spawnFile = spawnFile.substr(sep_pos + 1); if((sep_pos = houseFile.rfind('/')) != std::string::npos) houseFile = houseFile.substr(sep_pos + 1); fin->addU32(0); // file version OutputBinaryTreePtr root(new OutputBinaryTree(fin)); { root->addU32(version); Size mapSize = getSize(); root->addU16(mapSize.width()); root->addU16(mapSize.height()); root->addU32(g_things.getOtbMajorVersion()); root->addU32(g_things.getOtbMinorVersion()); root->startNode(OTBM_MAP_DATA); { // own description. for(const auto& desc : getDescriptions()) { root->addU8(OTBM_ATTR_DESCRIPTION); root->addString(desc); } // special one root->addU8(OTBM_ATTR_DESCRIPTION); root->addString(stdext::format("Saved with %s v%s", g_app.getName(), g_app.getVersion())); // spawn file. root->addU8(OTBM_ATTR_SPAWN_FILE); root->addString(spawnFile); // house file. if(version > 1) { root->addU8(OTBM_ATTR_HOUSE_FILE); root->addString(houseFile); } int px = -1, py = -1, pz =-1; bool firstNode = true; for(uint8_t z = 0; z <= Otc::MAX_Z; ++z) { for(const auto& it : m_tileBlocks[z]) { const TileBlock& block = it.second; for(const TilePtr& tile : block.getTiles()) { if(!tile || tile->isEmpty()) continue; const Position& pos = tile->getPosition(); if(!pos.isValid()) continue; if(pos.x < px || pos.x >= px + 256 || pos.y < py || pos.y >= py + 256 || pos.z != pz) { if(!firstNode) root->endNode(); /// OTBM_TILE_AREA firstNode = false; root->startNode(OTBM_TILE_AREA); px = pos.x & 0xFF00; py = pos.y & 0xFF00; pz = pos.z; root->addPos(Position(px, py, pz)); } root->startNode(tile->isHouseTile() ? OTBM_HOUSETILE : OTBM_TILE); root->addPoint(Point(pos.x, pos.y) & 0xFF); if(tile->isHouseTile()) root->addU32(tile->getHouseId()); if(tile->getFlags()) { root->addU8(OTBM_ATTR_TILE_FLAGS); root->addU32(tile->getFlags()); } const auto& itemList = tile->getItems(); const ItemPtr& ground = tile->getGround(); if(ground) { // Those types are called "complex" needs other stuff to be written. // For containers, there is container items, for depot, depot it and so on. if(!ground->isContainer() && !ground->isDepot() && !ground->isDoor() && !ground->isTeleport()) { root->addU8(OTBM_ATTR_ITEM); root->addU16(ground->getServerId()); } else ground->serializeItem(root); } for(const ItemPtr& item : itemList) if(!item->isGround()) item->serializeItem(root); root->endNode(); // OTBM_TILE } } } if(!firstNode) root->endNode(); // OTBM_TILE_AREA root->startNode(OTBM_TOWNS); for(const TownPtr& town : g_towns.getTowns()) { root->addU32(town->getId()); root->addString(town->getName()); root->addPos(town->getPos()); } root->endNode(); if(version > 1) { root->startNode(OTBM_WAYPOINTS); for(const auto& it : m_waypoints) { root->addString(it.second); root->addPos(it.first); } root->endNode(); } } root->endNode(); // OTBM_MAP_DATA } root->endNode(); fin->flush(); fin->close(); }
std::string fileExtension(const std::string &file) { return file.substr(file.rfind(".")+1, file.length()-file.rfind(".")-1); }
int main(int argc, char *argv[]) { std::ios::sync_with_stdio(); argv0 = argv[0]; { size_t slash = argv0.rfind('/'); argv0 = slash==std::string::npos ? argv0 : argv0.substr(slash+1); if (0==argv0.substr(0, 3).compare("lt-")) argv0 = argv0.substr(3); } int argno = 1; for (/*void*/; argno<argc && '-'==argv[argno][0]; ++argno) { if (!strcmp(argv[argno], "--")) { ++argno; break; } else if (!strcmp(argv[argno], "--help") || !strcmp(argv[argno], "-h")) { ::usage(0); } else if (!strcmp(argv[argno], "--delete")) { opt.delete_old_data = true; } else if (!strncmp(argv[argno], "--exclude-functions=", 20)) { opt.exclude_functions_table = argv[argno]+20; } else if (!strcmp(argv[argno], "--no-delete")) { opt.delete_old_data = false; } else if (!strncmp(argv[argno], "--relation=", 11)) { opt.relation_id = strtol(argv[argno]+11, NULL, 0); } else { std::cerr <<argv0 <<": unknown switch: " <<argv[argno] <<"\n" <<argv0 <<": see --help for more info\n"; exit(1); } }; if (argno+1!=argc) ::usage(1); time_t start_time = time(NULL); SqlDatabase::ConnectionPtr conn = SqlDatabase::Connection::create(argv[argno++]); SqlDatabase::TransactionPtr tx = conn->transaction(); // Save ourself in the history if we're modifying the database. int64_t cmd_id=-1; if (opt.delete_old_data) cmd_id = CloneDetection::start_command(tx, argc, argv, "clearing funcsim data for relation #"+ StringUtility::numberToString(opt.relation_id), start_time); // The 32-func-similarity tool needs this index, so we might as well create it here when we're running serially. The // semantic_outputvalues table can be HUGE depending on how the analysis is configured (i.e., whether it saves output // values as a vector or set, whether it saves function calls and system calls, etc.). Since creating the index could take // a few minutes, we'd rather not create it if it alread exists, but PostgreSQL v8 doesn't have a "CREATE INDEX IF NOT // EXISTS" ability. Therefore, try to create the index right away before we make any other changes, and if creation fails // then start a new transaction (because the current one is hosed). std::cerr <<argv0 <<": creating output group index (could take a while)\n"; try { SqlDatabase::TransactionPtr tx = conn->transaction(); tx->execute("create index idx_ogroups_hashkey on semantic_outputvalues(hashkey)"); tx->commit(); } catch (const SqlDatabase::Exception&) { std::cerr <<argv0 <<": idx_ogroups_hashkey index already exists; NOT dropping and recreating\n"; } // Delete old data. if (opt.delete_old_data) tx->statement("delete from semantic_funcsim where relation_id = ?")->bind(0, opt.relation_id)->execute(); // Get the list of functions that should appear in the worklist. std::cerr <<argv0 <<": obtaining function list\n"; std::string stmt1 = "create temporary table tmp_tested_funcs as" " select distinct fio.func_id as func_id" " from semantic_fio as fio"; if (!opt.exclude_functions_table.empty()) { std::vector<std::string> parts = StringUtility::split('.', opt.exclude_functions_table, 2, true); if (parts.size()<2) parts.push_back("func_id"); stmt1 += " left join " + parts.front() + " as exclude" " on fio.func_id = exclude." + parts.back() + " where exclude." + parts.back() + " is null"; } tx->execute(stmt1); // Create pairs of function IDs for those functions which have been tested and for which no similarity measurement has been // computed. (FIXME: We should probably recompute similarity that might have changed due to rerunning tests or running the // same function but with more input groups. [Robb P. Matzke 2013-06-19]) std::cerr <<argv0 <<": creating work list\n"; SqlDatabase::StatementPtr stmt2 = tx->statement("select distinct f1.func_id as func1_id, f2.func_id as func2_id" " from tmp_tested_funcs as f1" " join tmp_tested_funcs as f2 on f1.func_id < f2.func_id" " except" " select func1_id, func2_id from semantic_funcsim as sim" " where sim.relation_id = ?"); stmt2->bind(0, opt.relation_id); for (SqlDatabase::Statement::iterator row=stmt2->begin(); row!=stmt2->end(); ++row) std::cout <<row.get<int>(0) <<"\t" <<row.get<int>(1) <<"\n"; if (cmd_id>=0) CloneDetection::finish_command(tx, cmd_id, "cleared funcsim table for relation #"+ StringUtility::numberToString(opt.relation_id)); tx->commit(); return 0; }
static inline const std::string removeLastExtension( const std::string & name ) { std::string::size_type idx = name.rfind( '.' ); return ( ( idx < name.length() )? name.substr( 0,idx ) : name ); }
bool StringUtils::endsWith(const std::string& input, const std::string& end) { return input.rfind(end) == (input.size() - end.size()); }
void CLNF::Read_CLNF(std::string clnf_location) { std::cout << "clnf_location = " << clnf_location << std::endl; // Location of modules std::ifstream locations(clnf_location.c_str(), std::ios_base::in); if(!locations.is_open()) { std::cout << "Couldn't open the CLNF model file aborting" << std::endl; std::cout.flush(); return; } std::string line; std::vector<std::string> intensity_expert_locations; std::vector<std::string> depth_expert_locations; std::vector<std::string> ccnf_expert_locations; // The other module locations should be defined as relative paths from the main model // boost::filesystem::path root = boost::filesystem::path(clnf_location).parent_path(); std::string root; std::string temp("/"); std::size_t found = clnf_location.rfind(temp); if (found!=std::string::npos) root = clnf_location.substr(0, found); // The main file contains the references to other files while (!locations.eof()) { getline(locations, line); std::stringstream lineStream(line); std::string module; std::string location; // figure out which module is to be read from which file lineStream >> module; getline(lineStream, location); if(location.size() > 0) location.erase(location.begin()); // remove the first space // remove carriage return at the end for compatibility with unix systems if(location.size() > 0 && location.at(location.size()-1) == '\r') { location = location.substr(0, location.size()-1); } // append the lovstion to root location (boost syntax) // location = (root / location).string(); location = root + temp + location; if (module.compare("PDM") == 0) { std::cout << "Reading the PDM module from: " << location << "...."; pdm.Read(location); std::cout << "Done" << std::endl; } else if (module.compare("Triangulations") == 0) { std::cout << "Reading the Triangulations module from: " << location << "...."; std::ifstream triangulationFile(location.c_str(), std::ios_base::in); LandmarkDetector::SkipComments(triangulationFile); int numViews; triangulationFile >> numViews; // read in the triangulations triangulations.resize(numViews); for(int i = 0; i < numViews; ++i) { LandmarkDetector::SkipComments(triangulationFile); LandmarkDetector::ReadMat(triangulationFile, triangulations[i]); } std::cout << "Done" << std::endl; } else if(module.compare("PatchesIntensity") == 0)
//---------------------------------------------------------------------------------------------------------------------- void Globals::initialise(const std::string& cfgFnm) { // Defaults m_settings = 0; m_fnm.clear(); // Current directory of the executable bfs::path currentPath ( bfs::current_path() ); std::string currentPathStr = currentPath.string(); // Look for config file in current exe's directory or in subfolder specified in argument std::string pathToConfig; if(cfgFnm.empty()) { #if DEBUGGING std::cout << "No config file specified. Searching in local directory '" << currentPathStr << "'." << std::endl; #endif // No config file name given, so load first in base directory with xml ending. bfs::directory_iterator end_itr; for (bfs::directory_iterator itr(currentPath); itr != end_itr; ++itr) { // If it's not a directory ... if (!is_directory(itr->status())) { // ... and the filename contains the xml ending const std::string& fnm = itr->path().filename().string(); if(fnm.find(".xml") != std::string::npos) { m_fnm = fnm; pathToConfig = itr->path().string(); #if DEBUGGING std::cout << "Found config file '" << m_fnm << "'." << std::endl; #endif break; } } } } else { std::string pathHomeExpanded = pathExpandHome(cfgFnm); // Global paths start with a forward slash '/', local paths don't. if (pathHomeExpanded[0] == '/' && bfs::exists(pathHomeExpanded)) { m_fnm = pathHomeExpanded.substr(pathHomeExpanded.rfind('/') + 1); pathToConfig = pathHomeExpanded; #if 0 std::cout << "Found specified config file in ABSOLUTE path '" << pathToConfig << "'." << std::endl; #endif } else { const std::string localPath = currentPathStr + "/" + pathHomeExpanded; if(bfs::exists(localPath)) { m_fnm = cfgFnm.substr(cfgFnm.rfind('/') + 1); pathToConfig = localPath; #if 0 std::cout << "Found specified config file in LOCAL path '" << pathToConfig << "'." << std::endl; #endif } } } // If we have a valid config filename, load it if(!pathToConfig.empty()) { try { m_settings = new ci::XmlTree(ci::loadFile(pathToConfig)); } catch (rapidxml::parse_error& e) { std::cout << "XML parse error trying to read config: '" << e.what() << "'. Aborting!" << std::endl; } } else { #if DEBUGGING std::cout << "No config file specified. Not loading any settings! '" << std::endl; #endif } // Choose folder to save output file. It's either a hard-coded subfolder of current directory, // or one specified in config file std::string outputDir(currentPathStr + "/Output/"); if(m_settings && m_settings->hasChild("Config/Globals/OutputFolder")) { std::string dir = m_settings->getChild("Config/Globals/OutputFolder").getAttributeValue<std::string>("Name"); if(!dir.empty()) { // Expand home directory: replaces '~' if appropriate dir = pathExpandHome(dir); // Absolute or relative path? if(dir[0] != '/') { outputDir = currentPathStr + "/" + dir + "/"; } else { outputDir = dir + "/"; } } } // Create a new directory based on current data and time and store the path for global access time_t now = time(NULL); static const int TimeMaxChar = 128; char dateTime[TimeMaxChar]; dateTime[0] = '\0'; strftime(dateTime, TimeMaxChar, "%y_%m_%d__%H_%M_%S", localtime(&now)); // Finally create the data directory m_dataDir = outputDir + dateTime + "/"; bfs::create_directories(boost::filesystem::path(m_dataDir)); }
int main(int argc, char *argv[]) { std::ios::sync_with_stdio(); argv0 = argv[0]; { size_t slash = argv0.rfind('/'); argv0 = slash==std::string::npos ? argv0 : argv0.substr(slash+1); if (0==argv0.substr(0, 3).compare("lt-")) argv0 = argv0.substr(3); } Switches opt; int argno = 1; for (/*void*/; argno<argc && '-'==argv[argno][0]; ++argno) { if (!strcmp(argv[argno], "--")) { ++argno; break; } else if (!strcmp(argv[argno], "--help") || !strcmp(argv[argno], "-h")) { ::usage(0); } else if (!strncmp(argv[argno], "--entry=", 8)) { opt.entry_vas.insert(strtoull(argv[argno]+8, NULL, 0)); } else if (!strcmp(argv[argno], "--file=list") || !strcmp(argv[argno], "--files=list")) { opt.list_files = true; } else if (!strncmp(argv[argno], "--file=", 7) || !strncmp(argv[argno], "--files=", 8)) { std::vector<std::string> ids = StringUtility::split(",", strchr(argv[argno], '=')+1, (size_t)-1, true); for (size_t i=0; i<ids.size(); ++i) { const char *s = ids[i].c_str(); char *rest; errno = 0; int id = strtoul(s, &rest, 0); if (errno || rest==s || *rest) { std::cerr <<argv0 <<": invalid file ID: " <<ids[i] <<"\n"; exit(1); } opt.files.insert(id); } } else if (!strncmp(argv[argno], "--function=", 11) || !strncmp(argv[argno], "--functions=", 12)) { std::vector<std::string> ids = StringUtility::split(",", strchr(argv[argno], '=')+1, (size_t)-1, true); if (ids.size()==1 && isalpha(ids[0][0]) && ids[0].find_first_of('.')!=std::string::npos) { std::vector<std::string> words = StringUtility::split(".", ids[0]); if (words.size()!=2 || !SqlDatabase::is_valid_table_name(words[0]) || !SqlDatabase::is_valid_table_name(words[1])) { std::cerr <<argv0 <<": --function switch needs either IDs or a database TABLE.COLUMN\n"; exit(1); } opt.function_table = words[0]; opt.function_column = words[1]; } else { for (size_t i=0; i<ids.size(); ++i) { const char *s = ids[i].c_str(); char *rest; errno = 0; int id = strtoul(s, &rest, 0); if (errno || rest==s || *rest) { std::cerr <<argv0 <<": invalid function ID: " <<ids[i] <<"\n"; exit(1); } opt.functions.insert(id); } } } else if (!strncmp(argv[argno], "--first-fuzz=", 13)) { opt.first_fuzz = strtoul(argv[argno]+13, NULL, 0); } else if (!strncmp(argv[argno], "--name=", 7)) { opt.names.insert(argv[argno]+7); } else if (!strncmp(argv[argno], "--nfuzz=", 8)) { opt.nfuzz = strtoul(argv[argno]+8, NULL, 0); opt.nfuzz_set = true; } else if (!strncmp(argv[argno], "--size=", 7)) { opt.ninsns = strtoul(argv[argno]+7, NULL, 0); } else if (!strcmp(argv[argno], "--specimen=list") || !strcmp(argv[argno], "--specimens=list")) { opt.list_specimens = true; } else if (!strncmp(argv[argno], "--specimen=", 11) || !strncmp(argv[argno], "--specimens=", 12)) { std::vector<std::string> ids = StringUtility::split(",", strchr(argv[argno], '=')+1, (size_t)-1, true); for (size_t i=0; i<ids.size(); ++i) { const char *s = ids[i].c_str(); char *rest; errno = 0; int id = strtoul(s, &rest, 0); if (errno || rest==s || *rest) { std::cerr <<argv0 <<": invalid specimen ID: " <<ids[i] <<"\n"; exit(1); } opt.specimens.insert(id); } } else { std::cerr <<argv0 <<": unrecognized switch: " <<argv[argno] <<"\n" <<"see \"" <<argv0 <<" --help\" for usage info.\n"; exit(1); } } if (argno+1!=argc) ::usage(1); SqlDatabase::TransactionPtr tx = SqlDatabase::Connection::create(argv[argno++])->transaction(); // List the ID numbers and names for all specimen files if (opt.list_specimens) { SqlDatabase::Table<int, std::string> specimens; specimens.insert(tx->statement("select file.id, file.name" " from (select distinct specimen_id as id from semantic_functions) as specimen" " join semantic_files as file on specimen.id = file.id" " order by file.name")); specimens.headers("File ID", "Specimen Name"); specimens.print(std::cout); return 0; } // List the ID numbers and names for all files containing functions if (opt.list_files) { SqlDatabase::Table<int, std::string> files; files.insert(tx->statement("select file.id, file.name" " from (select distinct file_id as id from semantic_functions) as used" " join semantic_files as file on used.id = file.id" " order by file.name")); files.headers("File ID", "Binary File Name"); files.print(std::cout); return 0; } // Sanity checks if (!opt.functions.empty() && !opt.function_table.empty()) { std::cerr <<argv0 <<": --function=ID and --function=TABLE are mutually exclusive\n"; exit(1); } if (0==tx->statement("select count(*) from semantic_functions")->execute_int()) { std::cerr <<argv0 <<": database has no functions; nothing to test\n"; return 0; } if (0==tx->statement("select count(*) from semantic_inputvalues")->execute_int()) { std::cerr <<argv0 <<": database has no input groups; nothing to test\n"; return 0; } // Create table tmp_functions containing IDs for selected functions and their specimen IDs std::vector<std::string> constraints; if (!opt.entry_vas.empty()) constraints.push_back("func.entry_va " + SqlDatabase::in(opt.entry_vas)); if (!opt.names.empty()) constraints.push_back("func.name " + SqlDatabase::in_strings(opt.names, tx->driver())); if (!opt.specimens.empty()) constraints.push_back("func.specimen_id " + SqlDatabase::in(opt.specimens)); if (!opt.files.empty()) constraints.push_back("func.file_id " + SqlDatabase::in(opt.files)); if (!opt.functions.empty()) constraints.push_back("func.id " + SqlDatabase::in(opt.functions)); if (opt.ninsns>0) constraints.push_back("func.ninsns >= " + StringUtility::numberToString(opt.ninsns)); std::string sql1 = "select func.id, func.specimen_id from semantic_functions as func"; if (!opt.function_table.empty()) sql1 += " join "+opt.function_table+" as flist on func.id = flist."+opt.function_column; if (!constraints.empty()) sql1 += " where " + StringUtility::join(" and ", constraints); tx->execute("create temporary table tmp_functions as " + sql1); // Create table tmp_inputgroups containing IDs for selected input groups std::string sql2 = "select distinct igroup_id from semantic_inputvalues where igroup_id >= " + StringUtility::numberToString(opt.first_fuzz); if (opt.nfuzz_set) sql2 += " and igroup_id < " + StringUtility::numberToString(opt.first_fuzz+opt.nfuzz); tx->execute("create temporary table tmp_inputgroups as " + sql2); // Create tmp_pending as the cross product of functions and inputgroups except for those already tested tx->execute("create temporary table tmp_pending as" " select func.specimen_id as specimen_id, func.id as func_id, igroup.igroup_id as igroup_id" " from tmp_functions as func" " join tmp_inputgroups as igroup" " on igroup.igroup_id is not null" // "on" clause and "is not null" (rather than "true") for portability " except" " select func.specimen_id, func.id, fio.igroup_id" " from semantic_fio as fio" " join semantic_functions as func on fio.func_id=func.id"); SqlDatabase::StatementPtr stmt = tx->statement("select distinct specimen_id, func_id, igroup_id" " from tmp_pending" " order by specimen_id, igroup_id, func_id"); for (SqlDatabase::Statement::iterator row=stmt->begin(); row!=stmt->end(); ++row) std::cout <<row.get<int>(0) <<"\t" <<row.get<int>(1) <<"\t" <<row.get<int>(2) <<"\n"; // no need to commit, but if we change this in the future, be sure to add begin_command()/finish_command() return 0; }
void Browser::GetDirectory(std::string dir, std::string subdir) { if (dir.empty()) dir = "/"; int highlightme = -1; itsScrollBeginning = 0; if (itsBrowsedDir != dir) w->Reset(); itsBrowsedDir = dir; locale_to_utf(dir); for (size_t i = 0; i < w->Size(); ++i) if (w->at(i).type == itSong) delete w->at(i).song; w->Clear(); if (dir != "/") { MPD::Item parent; size_t slash = dir.rfind("/"); parent.song = reinterpret_cast<MPD::Song *>(1); // in that way we assume that's really parent dir parent.name = slash != std::string::npos ? dir.substr(0, slash) : "/"; parent.type = itDirectory; utf_to_locale(parent.name); w->AddOption(parent); } MPD::ItemList list; # ifndef WIN32 isLocal() ? GetLocalDirectory(list) : Mpd.GetDirectory(dir, list); # else Mpd.GetDirectory(dir, list); # endif // !WIN32 if (!isLocal()) // local directory is already sorted sort(list.begin(), list.end(), CaseInsensitiveSorting()); for (MPD::ItemList::iterator it = list.begin(); it != list.end(); ++it) { switch (it->type) { case itPlaylist: { utf_to_locale(it->name); w->AddOption(*it); break; } case itDirectory: { utf_to_locale(it->name); if (it->name == subdir) highlightme = w->Size(); w->AddOption(*it); break; } case itSong: { bool bold = 0; for (size_t i = 0; i < myPlaylist->Items->Size(); ++i) { if (myPlaylist->Items->at(i).GetHash() == it->song->GetHash()) { bold = 1; break; } } w->AddOption(*it, bold); break; } } } if (highlightme >= 0) w->Highlight(highlightme); }
std::string removeFileExtension(const std::string file) { return file.substr(0,file.rfind(".")); }
void Emulator::Load(bool add_only) { Stop(); try { Init(); // Load game list (maps ABCD12345 IDs to /dev_bdvd/ locations) YAML::Node games = YAML::Load(fs::file{fs::get_config_dir() + "/games.yml", fs::read + fs::create}.to_string()); if (!games.IsMap()) { games.reset(); } LOG_NOTICE(LOADER, "Path: %s", m_path); const std::string elf_dir = fs::get_parent_dir(m_path); // Load PARAM.SFO (TODO) const auto _psf = psf::load_object([&] { if (fs::file sfov{elf_dir + "/sce_sys/param.sfo"}) { return sfov; } else { return fs::file(elf_dir + "/../PARAM.SFO"); } }()); m_title = psf::get_string(_psf, "TITLE", m_path); m_title_id = psf::get_string(_psf, "TITLE_ID"); const auto _cat = psf::get_string(_psf, "CATEGORY"); LOG_NOTICE(LOADER, "Title: %s", GetTitle()); LOG_NOTICE(LOADER, "Serial: %s", GetTitleID()); // Initialize data/cache directory m_cache_path = fs::get_data_dir(m_title_id, m_path); LOG_NOTICE(LOADER, "Cache: %s", GetCachePath()); // Load custom config-0 if (fs::file cfg_file{m_cache_path + "/config.yml"}) { LOG_NOTICE(LOADER, "Applying custom config: %s/config.yml", m_cache_path); g_cfg.from_string(cfg_file.to_string()); } // Load custom config-1 if (fs::file cfg_file{fs::get_config_dir() + "data/" + m_title_id + "/config.yml"}) { LOG_NOTICE(LOADER, "Applying custom config: data/%s/config.yml", m_title_id); g_cfg.from_string(cfg_file.to_string()); } // Load custom config-2 if (fs::file cfg_file{m_path + ".yml"}) { LOG_NOTICE(LOADER, "Applying custom config: %s.yml", m_path); g_cfg.from_string(cfg_file.to_string()); } LOG_NOTICE(LOADER, "Used configuration:\n%s\n", g_cfg.to_string()); // Load patches from different locations fxm::check_unlocked<patch_engine>()->append(fs::get_config_dir() + "data/" + m_title_id + "/patch.yml"); fxm::check_unlocked<patch_engine>()->append(m_cache_path + "/patch.yml"); // Mount all devices const std::string emu_dir_ = g_cfg.vfs.emulator_dir; const std::string emu_dir = emu_dir_.empty() ? fs::get_config_dir() : emu_dir_; const std::string home_dir = g_cfg.vfs.app_home; std::string bdvd_dir = g_cfg.vfs.dev_bdvd; vfs::mount("dev_hdd0", fmt::replace_all(g_cfg.vfs.dev_hdd0, "$(EmulatorDir)", emu_dir)); vfs::mount("dev_hdd1", fmt::replace_all(g_cfg.vfs.dev_hdd1, "$(EmulatorDir)", emu_dir)); vfs::mount("dev_flash", fmt::replace_all(g_cfg.vfs.dev_flash, "$(EmulatorDir)", emu_dir)); vfs::mount("dev_usb", fmt::replace_all(g_cfg.vfs.dev_usb000, "$(EmulatorDir)", emu_dir)); vfs::mount("dev_usb000", fmt::replace_all(g_cfg.vfs.dev_usb000, "$(EmulatorDir)", emu_dir)); vfs::mount("app_home", home_dir.empty() ? elf_dir + '/' : fmt::replace_all(home_dir, "$(EmulatorDir)", emu_dir)); // Detect boot location const std::string hdd0_game = vfs::get("/dev_hdd0/game/"); const std::string hdd0_disc = vfs::get("/dev_hdd0/disc/"); if (_cat == "DG" && m_path.find(hdd0_game) != -1) { // Booting disc game from wrong location LOG_ERROR(LOADER, "Disc game %s found at invalid location /dev_hdd0/game/", m_title_id); // Move and retry from correct location if (fs::rename(elf_dir + "/../../", hdd0_disc + elf_dir.substr(hdd0_game.size()) + "/../../")) { LOG_SUCCESS(LOADER, "Disc game %s moved to special location /dev_hdd0/disc/", m_title_id); return SetPath(hdd0_disc + m_path.substr(hdd0_game.size())), Load(); } else { LOG_ERROR(LOADER, "Failed to move disc game %s to /dev_hdd0/disc/ (%s)", m_title_id, fs::g_tls_error); return; } } // Booting disc game if (_cat == "DG" && bdvd_dir.empty()) { // Mount /dev_bdvd/ if necessary if (auto pos = elf_dir.rfind("/PS3_GAME/") + 1) { bdvd_dir = elf_dir.substr(0, pos); } } // Booting patch data if (_cat == "GD" && bdvd_dir.empty()) { // Load /dev_bdvd/ from game list if available if (auto node = games[m_title_id]) { bdvd_dir = node.Scalar(); } else { LOG_FATAL(LOADER, "Disc directory not found. Try to run the game from the actual game disc directory."); } } // Check /dev_bdvd/ if (!bdvd_dir.empty() && fs::is_dir(bdvd_dir)) { fs::file sfb_file; vfs::mount("dev_bdvd", bdvd_dir); LOG_NOTICE(LOADER, "Disc: %s", vfs::get("/dev_bdvd")); if (!sfb_file.open(vfs::get("/dev_bdvd/PS3_DISC.SFB")) || sfb_file.size() < 4 || sfb_file.read<u32>() != ".SFB"_u32) { LOG_ERROR(LOADER, "Invalid disc directory for the disc game %s", m_title_id); return; } const std::string bdvd_title_id = psf::get_string(psf::load_object(fs::file{vfs::get("/dev_bdvd/PS3_GAME/PARAM.SFO")}), "TITLE_ID"); if (bdvd_title_id != m_title_id) { LOG_ERROR(LOADER, "Unexpected disc directory for the disc game %s (found %s)", m_title_id, bdvd_title_id); return; } // Store /dev_bdvd/ location games[m_title_id] = bdvd_dir; YAML::Emitter out; out << games; fs::file(fs::get_config_dir() + "/games.yml", fs::rewrite).write(out.c_str(), out.size()); } else if (_cat == "DG" || _cat == "GD") { LOG_ERROR(LOADER, "Failed to mount disc directory for the disc game %s", m_title_id); return; } if (add_only) { LOG_NOTICE(LOADER, "Finished to add data to games.yml by boot for: %s", m_path); return; } // Check game updates const std::string hdd0_boot = hdd0_game + m_title_id + "/USRDIR/EBOOT.BIN"; if (_cat == "DG" && fs::is_file(hdd0_boot)) { // Booting game update LOG_SUCCESS(LOADER, "Updates found at /dev_hdd0/game/%s/!", m_title_id); return SetPath(hdd0_boot), Load(); } // Mount /host_root/ if necessary if (g_cfg.vfs.host_root) { vfs::mount("host_root", {}); } // Open SELF or ELF fs::file elf_file(m_path); if (!elf_file) { LOG_ERROR(LOADER, "Failed to open executable: %s", m_path); return; } // Check SELF header if (elf_file.size() >= 4 && elf_file.read<u32>() == "SCE\0"_u32) { const std::string decrypted_path = m_cache_path + "boot.elf"; fs::stat_t encrypted_stat = elf_file.stat(); fs::stat_t decrypted_stat; // Check modification time and try to load decrypted ELF if (fs::stat(decrypted_path, decrypted_stat) && decrypted_stat.mtime == encrypted_stat.mtime) { elf_file.open(decrypted_path); } else { // Decrypt SELF elf_file = decrypt_self(std::move(elf_file)); if (fs::file elf_out{decrypted_path, fs::rewrite}) { elf_out.write(elf_file.to_vector<u8>()); elf_out.close(); fs::utime(decrypted_path, encrypted_stat.atime, encrypted_stat.mtime); } else { LOG_ERROR(LOADER, "Failed to create boot.elf"); } } } ppu_exec_object ppu_exec; ppu_prx_object ppu_prx; spu_exec_object spu_exec; arm_exec_object arm_exec; if (!elf_file) { LOG_ERROR(LOADER, "Failed to decrypt SELF: %s", m_path); return; } else if (ppu_exec.open(elf_file) == elf_error::ok) { // PS3 executable g_system = system_type::ps3; m_state = system_state::ready; GetCallbacks().on_ready(); vm::ps3::init(); if (m_elf_path.empty()) { if (m_path.find(hdd0_game) != -1) { m_elf_path = "/dev_hdd0/game/" + m_path.substr(hdd0_game.size()); } else if (!bdvd_dir.empty() && fs::is_dir(bdvd_dir)) { //Disc games are on /dev_bdvd/ size_t pos = m_path.rfind("PS3_GAME"); m_elf_path = "/dev_bdvd/" + m_path.substr(pos); } else { //For homebrew m_elf_path = "/host_root/" + m_path; } LOG_NOTICE(LOADER, "Elf path: %s", m_elf_path); } ppu_load_exec(ppu_exec); fxm::import<GSRender>(Emu.GetCallbacks().get_gs_render); // TODO: must be created in appropriate sys_rsx syscall } else if (ppu_prx.open(elf_file) == elf_error::ok) { // PPU PRX (experimental) g_system = system_type::ps3; m_state = system_state::ready; GetCallbacks().on_ready(); vm::ps3::init(); ppu_load_prx(ppu_prx, m_path); } else if (spu_exec.open(elf_file) == elf_error::ok) { // SPU executable (experimental) g_system = system_type::ps3; m_state = system_state::ready; GetCallbacks().on_ready(); vm::ps3::init(); spu_load_exec(spu_exec); } else if (arm_exec.open(elf_file) == elf_error::ok) { // ARMv7 executable g_system = system_type::psv; m_state = system_state::ready; GetCallbacks().on_ready(); vm::psv::init(); if (m_elf_path.empty()) { m_elf_path = "host_root:" + m_path; LOG_NOTICE(LOADER, "Elf path: %s", m_elf_path); } arm_load_exec(arm_exec); } else { LOG_ERROR(LOADER, "Invalid or unsupported file format: %s", m_path); LOG_WARNING(LOADER, "** ppu_exec -> %s", ppu_exec.get_error()); LOG_WARNING(LOADER, "** ppu_prx -> %s", ppu_prx.get_error()); LOG_WARNING(LOADER, "** spu_exec -> %s", spu_exec.get_error()); LOG_WARNING(LOADER, "** arm_exec -> %s", arm_exec.get_error()); return; } if (g_cfg.misc.autostart && IsReady()) { Run(); } else if (IsPaused()) { m_state = system_state::ready; GetCallbacks().on_ready(); } } catch (const std::exception& e) { LOG_FATAL(LOADER, "%s thrown: %s", typeid(e).name(), e.what()); Stop(); } }
/*! Parses a Position Weight Matrices string Parses string containing position weight matrix definitions \param[in] std::string file */ bool PWM::parse(const std::string& matrix){ size_t thresh = matrix.find("THRESHOLD DEFINITION"); size_t track = matrix.find("TRACK SYMBOL DEFINITIONS"); size_t ambig = matrix.find("AMBIGUOUS SYMBOL DEFINITIONS"); size_t pwm = matrix.find("POSITION WEIGHT DEFINITIONS"); size_t back = matrix.find("BACKGROUND DEFINITION"); size_t space = matrix.find("SPACER DEFINITIONS"); size_t blank; size_t nlChar; if (thresh != std::string::npos){ blank=matrix.find("\n\n",thresh); size_t nlCharEq = matrix.rfind("####\n",blank); size_t nlCharNum= matrix.rfind("====\n",blank); //Check for optional dividing line if (nlCharEq!=std::string::npos){ nlChar=nlCharEq+5; } else if (nlCharNum!=std::string::npos){ nlChar=nlCharNum+5; } else{ //No divider line nlChar=matrix.find("\n",thresh); nlChar++; } std::string thr (matrix.substr(nlChar,blank-nlChar)); if (!_parseThreshold(thr)){ return false; } } if (track != std::string::npos){ blank=matrix.find("\n\n",track); size_t nlCharEq = matrix.rfind("####\n",blank); size_t nlCharNum= matrix.rfind("====\n",blank); //Check for optional dividing line if (nlCharEq!=std::string::npos){ nlChar=nlCharEq+5; } else if (nlCharNum!=std::string::npos){ nlChar=nlCharNum+5; } else{ //No divider line nlChar=matrix.find("\n",track); nlChar++; } std::string trck (matrix.substr(nlChar,blank-nlChar)); if (!_parseTrack(trck)){ return false; } } else{ std::cerr << "Required section: TRACK SYMBOL DEFINITIONS missing from the model" << std::endl; return false; } if (ambig != std::string::npos){ blank=matrix.find("\n\n",ambig); size_t nlCharEq = matrix.rfind("####\n",blank); size_t nlCharNum= matrix.rfind("====\n",blank); //Check for optional dividing line if (nlCharEq!=std::string::npos){ nlChar=nlCharEq+5; } else if (nlCharNum!=std::string::npos){ nlChar=nlCharNum+5; } else{ //No divider line nlChar=matrix.find("\n",ambig); nlChar++; } std::string amb(matrix.substr(nlChar,blank-nlChar)); if (!_parseAmbiguous(amb)){ return false; } } if (back!= std::string::npos){ blank=matrix.find("\n\n",back); size_t nlCharEq = matrix.rfind("####\n",blank); size_t nlCharNum= matrix.rfind("====\n",blank); //Check for optional dividing line if (nlCharEq!=std::string::npos){ nlChar=nlCharEq+5; } else if (nlCharNum!=std::string::npos){ nlChar=nlCharNum+5; } else{ //No divider line nlChar=matrix.find("\n",back); nlChar++; } std::string background(matrix.substr(nlChar,blank-nlChar)); if (!_parseBackground(background)){ return false; } } //Parse the positions if (pwm != std::string::npos){ std::string positions = matrix.substr(pwm); _parsePositions(positions); } //Parse the Spacer Information if (space != std::string::npos){ blank=matrix.find("\n\n",space); size_t nlCharEq = matrix.rfind("####\n",blank); size_t nlCharNum= matrix.rfind("====\n",blank); //Check for optional dividing line if (nlCharEq!=std::string::npos){ nlChar=nlCharEq+5; } else if (nlCharNum!=std::string::npos){ nlChar=nlCharNum+5; } else{ //No divider line nlChar=matrix.find("\n",space); nlChar++; } std::string spacer(matrix.substr(nlChar,blank-nlChar)); if (!_parseSpacer(spacer)){ return false; } } _finalizeTransitions(); return true; }
int ZLUnixFSManager::findArchiveFileNameDelimiter(const std::string &path) const { return path.rfind(':'); }
void gererateRecursisively(FolderInfo *folder, const std::string &root, const std::string &path, const std::string &rel = "") { std::ofstream myfile; std::string filename = root + "/" + path + "index.html"; myfile.open(filename); if (!myfile) { std::cerr << "Error generating " << filename << std::endl; return; } std::string data_path = data_url ? std::string(data_url) : (rel + "../data"); unsigned int pos = root.rfind('/', root.size()-2); std::string project = pos < root.size() ? root.substr(pos+1) : root; std::string breadcrumb = path; std::string parent; pos = path.rfind('/', path.size()-2); if (pos < path.size()) { breadcrumb = path.substr(pos+1); unsigned int next_pos; while (pos > 0 && (next_pos = path.rfind('/', pos-1)) < path.size()) { if (pos != next_pos +1) { parent += "../"; breadcrumb = "<a href='" +parent +"'>" + path.substr(next_pos + 1, pos - next_pos - 1) + "</a>/" + breadcrumb; } pos = next_pos; } if (pos > 1) { parent += "../"; breadcrumb = "<a href='" +parent +"'>" + path.substr(0, pos) + "</a>/" + breadcrumb; } } breadcrumb = "<a href='../" +parent +"'>" + project + "</a>/" + breadcrumb; myfile << "<!doctype html>\n" "<head><title>Index of " << path << " - Woboq Code Browser</title>" "<link rel=\"stylesheet\" href=\"" << data_path << "/indexstyle.css\"/>\n"; myfile << "<script type=\"text/javascript\" src=\"" << data_path << "/jquery/jquery.min.js\"></script>\n"; myfile << "<script type=\"text/javascript\" src=\"" << data_path << "/jquery/jquery-ui.min.js\"></script>\n"; myfile << "<script>var path = '"<< path <<"'; var root_path = '"<< rel <<"'; var project='"<< project <<"'; </script>\n" "<script src='" << data_path << "/indexscript.js'></script>\n" "</head>\n<body>\n"; myfile << "<h1><a href='http://code.woboq.org'>Woboq Code Browser</a></h1>\n"; myfile << "<p><input id='searchline' placeholder='Search for a file' type='text'/></p>\n"; myfile << "<h2> Index of <em>" << breadcrumb << "</em></h2>\n"; myfile << "<hr/><table id='tree'>\n"; //if (!path.empty()) { myfile << " <tr><td class='parent'> <a href='../'>../</a></td></tr>\n"; } for (auto it : folder->subfolders) { const std::string &name = it.first; if (it.second) { gererateRecursisively(it.second.get(), root, path+name+"/", rel + "../"); myfile << "<tr><td class='folder'><a href='"<< name <<"/' class='opener' data-path='" << path << name << "'>[+]</a> " "<a href='" << name << "/'>" << name << "/</a></td></tr>\n"; } else { myfile << "<tr><td class='file'> <a href='" << name << ".html'>" << name << "</a></td></tr>\n"; } } myfile << "</table>" "<hr/><p id='footer'>\n" "Powered by <a href='http://woboq.com'><img alt='Woboq' src='http://code.woboq.org/woboq-16.png' width='41' height='16' /></a> <a href='http://code.woboq.org'>Code Browser</a> " CODEBROWSER_VERSION "\n</p>\n</body></html>\n"; }
std::string Tfile::fullPathFromRelativeFile(const std::string &filename, const std::string &relativeFile) { return relativeFile.substr(0, relativeFile.rfind('/')+1) + (filename); }
bool Viewport::changeMap(const std::string &path) { // Clean up floor items, beings and particles floorItemManager->clear(); beingManager->clear(); // Close the popup menu on map change so that invalid options can't be // executed. closePopupMenu(); // Unset the map of the player so that its particles are cleared before // being deleted in the next step if (player_node) player_node->setMap(NULL); particleEngine->clear(); mMapName = path.substr(0, path.rfind(".")); // Store full map path in global var std::string mapPath = "maps/" + mMapName + ".tmx"; ResourceManager *resman = ResourceManager::getInstance(); if (!resman->exists(mapPath)) mapPath += ".gz"; // Attempt to load the new map Map *newMap = MapReader::readMap(mapPath); if (!newMap) { logger->log("Error while loading %s", mapPath.c_str()); new OkDialog(_("Could not load map"), strprintf(_("Error while loading %s"), mapPath.c_str())); } // Notify the minimap and beingManager about the map change minimap->setMap(newMap); beingManager->setMap(newMap); particleEngine->setMap(newMap); keyboard.refreshActiveKeys(); // Initialize map-based particle effects if (newMap) newMap->initializeParticleEffects(particleEngine); // Start playing new music file when necessary std::string oldMusic = mCurrentMap ? mCurrentMap->getMusicFile() : ""; std::string newMusic = newMap ? newMap->getMusicFile() : ""; if (newMusic != oldMusic) sound.playMusic(newMusic); if (mCurrentMap) destroy(mCurrentMap); setMap(newMap); MessageOut outMsg(CMSG_MAP_LOADED); return true; }
void Map::loadOtbm(const std::string& fileName, const UIWidgetPtr& pbar) { FileStreamPtr fin = g_resources.openFile(fileName); if(!fin) stdext::throw_exception(stdext::format("Unable to load map '%s'", fileName)); fin->cache(); if(!g_things.isOtbLoaded()) stdext::throw_exception("OTB isn't loaded yet to load a map."); if(fin->getU32()) stdext::throw_exception("Unknown file version detected"); BinaryTreePtr root = fin->getBinaryTree(); if(root->getU8()) stdext::throw_exception("could not read root property!"); uint32 headerVersion = root->getU32(); if(headerVersion > 3) stdext::throw_exception(stdext::format("Unknown OTBM version detected: %u.", headerVersion)); setWidth(root->getU16()); setHeight(root->getU16()); uint32 headerMajorItems = root->getU8(); if(headerMajorItems > g_things.getOtbMajorVersion()) { stdext::throw_exception(stdext::format("This map was saved with different OTB version. read %d what it's supposed to be: %d", headerMajorItems, g_things.getOtbMajorVersion())); } root->skip(3); uint32 headerMinorItems = root->getU32(); if(headerMinorItems > g_things.getOtbMinorVersion()) { g_logger.warning(stdext::format("This map needs an updated OTB. read %d what it's supposed to be: %d or less", headerMinorItems, g_things.getOtbMinorVersion())); } BinaryTreePtr node = root->getChildren()[0]; if(node->getU8() != OTBM_MAP_DATA) stdext::throw_exception("Could not read root data node"); while (node->canRead()) { uint8 attribute = node->getU8(); std::string tmp = node->getString(); switch (attribute) { case OTBM_ATTR_DESCRIPTION: setDescription(tmp); break; case OTBM_ATTR_SPAWN_FILE: setSpawnFile(fileName.substr(0, fileName.rfind('/') + 1) + tmp); break; case OTBM_ATTR_HOUSE_FILE: setHouseFile(fileName.substr(0, fileName.rfind('/') + 1) + tmp); break; default: stdext::throw_exception(stdext::format("Invalid attribute '%d'", (int)attribute)); } } for(const BinaryTreePtr& nodeMapData : node->getChildren()) { uint8 mapDataType = nodeMapData->getU8(); if(mapDataType == OTBM_TILE_AREA) { Position basePos = nodeMapData->getPosition(); unsigned int pbarvalue=0; for(const BinaryTreePtr &nodeTile : nodeMapData->getChildren()) { uint8 type = nodeTile->getU8(); if(type != OTBM_TILE && type != OTBM_HOUSETILE) stdext::throw_exception(stdext::format("invalid node tile type %d", (int)type)); HousePtr house = nullptr; uint32 flags = TILESTATE_NONE; Position pos = basePos + nodeTile->getPoint(); if(type == OTBM_HOUSETILE) { uint32 hId = nodeTile->getU32(); TilePtr tile = getOrCreateTile(pos); if(!(house = g_houses.getHouse(hId))) { house = HousePtr(new House(hId)); g_houses.addHouse(house); } house->setTile(tile); } while(nodeTile->canRead()) { uint8 tileAttr = nodeTile->getU8(); switch (tileAttr) { case OTBM_ATTR_TILE_FLAGS: { uint32 _flags = nodeTile->getU32(); if((_flags & TILESTATE_PROTECTIONZONE) == TILESTATE_PROTECTIONZONE) flags |= TILESTATE_PROTECTIONZONE; else if((_flags & TILESTATE_OPTIONALZONE) == TILESTATE_OPTIONALZONE) flags |= TILESTATE_OPTIONALZONE; else if((_flags & TILESTATE_HARDCOREZONE) == TILESTATE_HARDCOREZONE) flags |= TILESTATE_HARDCOREZONE; if((_flags & TILESTATE_NOLOGOUT) == TILESTATE_NOLOGOUT) flags |= TILESTATE_NOLOGOUT; if((_flags & TILESTATE_REFRESH) == TILESTATE_REFRESH) flags |= TILESTATE_REFRESH; break; } case OTBM_ATTR_ITEM: { addThing(Item::createFromOtb(nodeTile->getU16()), pos); break; } default: { stdext::throw_exception(stdext::format("invalid tile attribute %d at pos %s", (int)tileAttr, stdext::to_string(pos))); } } } for(const BinaryTreePtr& nodeItem : nodeTile->getChildren()) { if(nodeItem->getU8() != OTBM_ITEM) stdext::throw_exception("invalid item node"); ItemPtr item = Item::createFromOtb(nodeItem->getU16()); item->unserializeItem(nodeItem); if(item->isContainer()) { for(const BinaryTreePtr& containerItem : nodeItem->getChildren()) { if(containerItem->getU8() != OTBM_ITEM) stdext::throw_exception("invalid container item node"); ItemPtr cItem = Item::createFromOtb(containerItem->getU16()); cItem->unserializeItem(containerItem); item->addContainerItem(cItem); } } if(house && item->isMoveable()) { g_logger.warning(stdext::format("Movable item found in house: %d at pos %s - escaping...", item->getId(), stdext::to_string(pos))); item.reset(); } addThing(item, pos); } if(const TilePtr& tile = getTile(pos)) { if(house) tile->setHouseId(house->getId()); tile->setFlags((tileflags_t)flags); //if(!(++pbarvalue % 8192) && pbar); } } } else if(mapDataType == OTBM_TOWNS) { TownPtr town = nullptr; for(const BinaryTreePtr &nodeTown : nodeMapData->getChildren()) { if(nodeTown->getU8() != OTBM_TOWN) stdext::throw_exception("invalid town node."); uint32 townId = nodeTown->getU32(); std::string townName = nodeTown->getString(); Position townCoords = nodeTown->getPosition(); if(!(town = g_towns.getTown(townId))) { town = TownPtr(new Town(townId, townName, townCoords)); g_towns.addTown(town); } } } else if(mapDataType == OTBM_WAYPOINTS && headerVersion > 1) { for(const BinaryTreePtr &nodeWaypoint : nodeMapData->getChildren()) { if(nodeWaypoint->getU8() != OTBM_WAYPOINT) stdext::throw_exception("invalid waypoint node."); std::string name = nodeWaypoint->getString(); Position waypointPos = nodeWaypoint->getPosition(); if(waypointPos.isValid() && !name.empty() && m_waypoints.find(waypointPos) == m_waypoints.end()) m_waypoints.insert(std::make_pair(waypointPos, name)); } } else stdext::throw_exception(stdext::format("Unknown map data node %d", (int)mapDataType)); } fin->close(); }
inline bool endsWith(const std::string& s, const std::string& suffix) { return s.rfind(suffix) == s.length() - suffix.length(); }
bool IOMap::loadMap(Map* map, const std::string& identifier) { int64_t start = OTSYS_TIME(); FileLoader f; if (!f.openFile(identifier.c_str(), "OTBM")) { std::ostringstream ss; ss << "Could not open the file " << identifier << '.'; setLastErrorString(ss.str()); return false; } uint32_t type; PropStream propStream; NODE root = f.getChildNode(nullptr, type); if (!f.getProps(root, propStream)) { setLastErrorString("Could not read root property."); return false; } OTBM_root_header root_header; if (!propStream.read(root_header)) { setLastErrorString("Could not read header."); return false; } uint32_t headerVersion = root_header.version; if (headerVersion <= 0) { //In otbm version 1 the count variable after splashes/fluidcontainers and stackables //are saved as attributes instead, this solves alot of problems with items //that is changed (stackable/charges/fluidcontainer/splash) during an update. setLastErrorString("This map need to be upgraded by using the latest map editor version to be able to load correctly."); return false; } if (headerVersion > 2) { setLastErrorString("Unknown OTBM version detected."); return false; } if (root_header.majorVersionItems < 3) { setLastErrorString("This map need to be upgraded by using the latest map editor version to be able to load correctly."); return false; } if (root_header.majorVersionItems > Items::dwMajorVersion) { setLastErrorString("The map was saved with a different items.otb version, an upgraded items.otb is required."); return false; } if (root_header.minorVersionItems < CLIENT_VERSION_810) { setLastErrorString("This map needs to be updated."); return false; } if (root_header.minorVersionItems > Items::dwMinorVersion) { std::cout << "[Warning - IOMap::loadMap] This map needs an updated items.otb." << std::endl; } std::cout << "> Map size: " << root_header.width << "x" << root_header.height << '.' << std::endl; map->width = root_header.width; map->height = root_header.height; NODE nodeMap = f.getChildNode(root, type); if (type != OTBM_MAP_DATA) { setLastErrorString("Could not read data node."); return false; } if (!f.getProps(nodeMap, propStream)) { setLastErrorString("Could not read map data attributes."); return false; } std::string mapDescription; std::string tmp; uint8_t attribute; while (propStream.read<uint8_t>(attribute)) { switch (attribute) { case OTBM_ATTR_DESCRIPTION: if (!propStream.readString(mapDescription)) { setLastErrorString("Invalid description tag."); return false; } break; case OTBM_ATTR_EXT_SPAWN_FILE: if (!propStream.readString(tmp)) { setLastErrorString("Invalid spawn tag."); return false; } map->spawnfile = identifier.substr(0, identifier.rfind('/') + 1); map->spawnfile += tmp; break; case OTBM_ATTR_EXT_HOUSE_FILE: if (!propStream.readString(tmp)) { setLastErrorString("Invalid house tag."); return false; } map->housefile = identifier.substr(0, identifier.rfind('/') + 1); map->housefile += tmp; break; default: setLastErrorString("Unknown header node."); return false; } } NODE nodeMapData = f.getChildNode(nodeMap, type); while (nodeMapData != NO_NODE) { if (f.getError() != ERROR_NONE) { setLastErrorString("Invalid map node."); return false; } if (type == OTBM_TILE_AREA) { if (!f.getProps(nodeMapData, propStream)) { setLastErrorString("Invalid map node."); return false; } OTBM_Destination_coords area_coord; if (!propStream.read(area_coord)) { setLastErrorString("Invalid map node."); return false; } uint16_t base_x = area_coord.x; uint16_t base_y = area_coord.y; uint16_t z = area_coord.z; NODE nodeTile = f.getChildNode(nodeMapData, type); while (nodeTile != NO_NODE) { if (f.getError() != ERROR_NONE) { setLastErrorString("Could not read node data."); return false; } if (type != OTBM_TILE && type != OTBM_HOUSETILE) { setLastErrorString("Unknown tile node."); return false; } if (!f.getProps(nodeTile, propStream)) { setLastErrorString("Could not read node data."); return false; } OTBM_Tile_coords tile_coord; if (!propStream.read(tile_coord)) { setLastErrorString("Could not read tile position."); return false; } uint16_t x = base_x + tile_coord.x; uint16_t y = base_y + tile_coord.y; bool isHouseTile = false; House* house = nullptr; Tile* tile = nullptr; Item* ground_item = nullptr; uint32_t tileflags = TILESTATE_NONE; if (type == OTBM_HOUSETILE) { uint32_t houseId; if (!propStream.read<uint32_t>(houseId)) { std::ostringstream ss; ss << "[x:" << x << ", y:" << y << ", z:" << z << "] Could not read house id."; setLastErrorString(ss.str()); return false; } house = map->houses.addHouse(houseId); if (!house) { std::ostringstream ss; ss << "[x:" << x << ", y:" << y << ", z:" << z << "] Could not create house id: " << houseId; setLastErrorString(ss.str()); return false; } tile = new HouseTile(x, y, z, house); house->addTile(static_cast<HouseTile*>(tile)); isHouseTile = true; } //read tile attributes while (propStream.read<uint8_t>(attribute)) { switch (attribute) { case OTBM_ATTR_TILE_FLAGS: { uint32_t flags; if (!propStream.read<uint32_t>(flags)) { std::ostringstream ss; ss << "[x:" << x << ", y:" << y << ", z:" << z << "] Failed to read tile flags."; setLastErrorString(ss.str()); return false; } if ((flags & OTBM_TILEFLAG_PROTECTIONZONE) != 0) { tileflags |= TILESTATE_PROTECTIONZONE; } else if ((flags & OTBM_TILEFLAG_NOPVPZONE) != 0) { tileflags |= TILESTATE_NOPVPZONE; } else if ((flags & OTBM_TILEFLAG_PVPZONE) != 0) { tileflags |= TILESTATE_PVPZONE; } if ((flags & OTBM_TILEFLAG_NOLOGOUT) != 0) { tileflags |= TILESTATE_NOLOGOUT; } break; } case OTBM_ATTR_ITEM: { Item* item = Item::CreateItem(propStream); if (!item) { std::ostringstream ss; ss << "[x:" << x << ", y:" << y << ", z:" << z << "] Failed to create item."; setLastErrorString(ss.str()); return false; } if (isHouseTile && item->isMoveable()) { std::cout << "[Warning - IOMap::loadMap] Moveable item with ID: " << item->getID() << ", in house: " << house->getId() << ", at position [x: " << x << ", y: " << y << ", z: " << z << "]." << std::endl; delete item; } else { if (item->getItemCount() <= 0) { item->setItemCount(1); } if (tile) { tile->internalAddThing(item); item->startDecaying(); item->setLoadedFromMap(true); } else if (item->isGroundTile()) { delete ground_item; ground_item = item; } else { tile = createTile(ground_item, item, x, y, z); tile->internalAddThing(item); item->startDecaying(); item->setLoadedFromMap(true); } } break; } default: std::ostringstream ss; ss << "[x:" << x << ", y:" << y << ", z:" << z << "] Unknown tile attribute."; setLastErrorString(ss.str()); return false; } } NODE nodeItem = f.getChildNode(nodeTile, type); while (nodeItem) { if (type != OTBM_ITEM) { std::ostringstream ss; ss << "[x:" << x << ", y:" << y << ", z:" << z << "] Unknown node type."; setLastErrorString(ss.str()); return false; } PropStream stream; if (!f.getProps(nodeItem, stream)) { setLastErrorString("Invalid item node."); return false; } Item* item = Item::CreateItem(stream); if (!item) { std::ostringstream ss; ss << "[x:" << x << ", y:" << y << ", z:" << z << "] Failed to create item."; setLastErrorString(ss.str()); return false; } if (!item->unserializeItemNode(f, nodeItem, stream)) { std::ostringstream ss; ss << "[x:" << x << ", y:" << y << ", z:" << z << "] Failed to load item " << item->getID() << '.'; setLastErrorString(ss.str()); delete item; return false; } if (isHouseTile && item->isMoveable()) { std::cout << "[Warning - IOMap::loadMap] Moveable item with ID: " << item->getID() << ", in house: " << house->getId() << ", at position [x: " << x << ", y: " << y << ", z: " << z << "]." << std::endl; delete item; } else { if (item->getItemCount() <= 0) { item->setItemCount(1); } if (tile) { tile->internalAddThing(item); item->startDecaying(); item->setLoadedFromMap(true); } else if (item->isGroundTile()) { delete ground_item; ground_item = item; } else { tile = createTile(ground_item, item, x, y, z); tile->internalAddThing(item); item->startDecaying(); item->setLoadedFromMap(true); } } nodeItem = f.getNextNode(nodeItem, type); } if (!tile) { tile = createTile(ground_item, nullptr, x, y, z); } tile->setFlag(static_cast<tileflags_t>(tileflags)); map->setTile(x, y, z, tile); nodeTile = f.getNextNode(nodeTile, type); } } else if (type == OTBM_TOWNS) { NODE nodeTown = f.getChildNode(nodeMapData, type); while (nodeTown != NO_NODE) { if (type != OTBM_TOWN) { setLastErrorString("Unknown town node."); return false; } if (!f.getProps(nodeTown, propStream)) { setLastErrorString("Could not read town data."); return false; } uint32_t townId; if (!propStream.read<uint32_t>(townId)) { setLastErrorString("Could not read town id."); return false; } Town* town = map->towns.getTown(townId); if (!town) { town = new Town(townId); map->towns.addTown(townId, town); } std::string townName; if (!propStream.readString(townName)) { setLastErrorString("Could not read town name."); return false; } town->setName(townName); OTBM_Destination_coords town_coords; if (!propStream.read(town_coords)) { setLastErrorString("Could not read town coordinates."); return false; } town->setTemplePos(Position(town_coords.x, town_coords.y, town_coords.z)); nodeTown = f.getNextNode(nodeTown, type); } } else if (type == OTBM_WAYPOINTS && headerVersion > 1) { NODE nodeWaypoint = f.getChildNode(nodeMapData, type); while (nodeWaypoint != NO_NODE) { if (type != OTBM_WAYPOINT) { setLastErrorString("Unknown waypoint node."); return false; } if (!f.getProps(nodeWaypoint, propStream)) { setLastErrorString("Could not read waypoint data."); return false; } std::string name; if (!propStream.readString(name)) { setLastErrorString("Could not read waypoint name."); return false; } OTBM_Destination_coords waypoint_coords; if (!propStream.read(waypoint_coords)) { setLastErrorString("Could not read waypoint coordinates."); return false; } map->waypoints[name] = Position(waypoint_coords.x, waypoint_coords.y, waypoint_coords.z); nodeWaypoint = f.getNextNode(nodeWaypoint, type); } } else { setLastErrorString("Unknown map node."); return false; } nodeMapData = f.getNextNode(nodeMapData, type); } std::cout << "> Map loading time: " << (OTSYS_TIME() - start) / (1000.) << " seconds." << std::endl; return true; }
/*! Returns the extension of the file or an empty string if the file has no extension. If checkFile flag is set, it will check first if the pathname denotes a directory and so return an empty string and second it will check if the file denoted by the pathanme exists. If so, it will return the extension if present. \param pathname : The pathname of the file we want to get the extension. \param checkFile : If true, the file must exist otherwise an empty string will be returned. \return The extension of the file or an empty string if the file has no extension. or if the pathname is empty. */ std::string vpIoTools::getFileExtension(const std::string& pathname, const bool checkFile) { if(checkFile && (vpIoTools::checkDirectory(pathname) || !vpIoTools::checkFilename(pathname))) { return ""; } //On Unix, or on the Mac std::string sep = "/"; std::string altsep = ""; std::string extsep = "."; #if defined(_WIN32) sep = "\\"; altsep = "/"; extsep = "."; #endif //Python 2.7.8 module. //# Split a path in root and extension. //# The extension is everything starting at the last dot in the last //# pathname component; the root is everything before that. //# It is always true that root + ext == p. // //# Generic implementation of splitext, to be parametrized with //# the separators //def _splitext(p, sep, altsep, extsep): // """Split the extension from a pathname. // // Extension is everything from the last dot to the end, ignoring // leading dots. Returns "(root, ext)"; ext may be empty.""" // // sepIndex = p.rfind(sep) // if altsep: // altsepIndex = p.rfind(altsep) // sepIndex = max(sepIndex, altsepIndex) // // dotIndex = p.rfind(extsep) // if dotIndex > sepIndex: // # skip all leading dots // filenameIndex = sepIndex + 1 // while filenameIndex < dotIndex: // if p[filenameIndex] != extsep: // return p[:dotIndex], p[dotIndex:] // filenameIndex += 1 // // return p, '' int sepIndex = (int)pathname.rfind(sep); if(!altsep.empty()) { int altsepIndex = (int)pathname.rfind(altsep); sepIndex = (std::max)(sepIndex, altsepIndex); } size_t dotIndex = pathname.rfind(extsep); if(dotIndex != std::string::npos) { //The extsep character exists if((sepIndex != (int)std::string::npos && (int)dotIndex > sepIndex) || sepIndex == (int)std::string::npos) { if(sepIndex == (int)std::string::npos) { sepIndex = -1; } size_t filenameIndex = (size_t)(sepIndex + 1); while(filenameIndex < dotIndex) { if(pathname.compare(filenameIndex, 1, extsep) != 0) { return pathname.substr(dotIndex); } filenameIndex++; } } } return ""; }
std::string getFilenameFromPath( const std::string & path ) { int ind = path.rfind('/',path.size()); return path.substr( ind+1, path.size() ); }
CommandTypes parseArguments(int argc, char **argv) { bool has_file = false; bool has_c = false; bool has_x = false; bool has_o = false; bool has_d = false; bool has_h = false; bool inputKC = false; for (int i = 1; i < argc; ++i) { char *arg = argv[i]; if (arg[0] == '-') { switch (arg[1]) { case 'c': if (!has_c) { if (!has_x) { has_c = true; toNative = false; } else { showError("Cannot use both -c and -x.\n"); showHelp(); return CommandTypes::Invalid; } } else { showHelp(); return CommandTypes::Invalid; } break; case 'x': if (!has_x) { if (!has_c) { has_x = true; toNative = true; } else { showError("Cannot use both -c and -x.\n"); showHelp(); return CommandTypes::Invalid; } } else { showHelp(); return CommandTypes::Invalid; } break; case 'i': { if (arg[2]) { includeFiles.push_back(arg + 2); } else { showError("Include file option given but no file specified.\n"); showHelp(); return CommandTypes::Invalid; } } break; case 'o': if (!has_o) { if (arg[2]) { has_o = true; outputfile = arg + 2; } else { showError("Output file option given but no file specified.\n"); showHelp(); return CommandTypes::Invalid; } } else { showHelp(); return CommandTypes::Invalid; } break; case 'd': if (!has_d) { has_d = true; hasDebugInfo = true; } else { showHelp(); return CommandTypes::Invalid; } break; case 'h': if (!has_h) { has_h = true; } else { showHelp(); return CommandTypes::Invalid; } break; default: showHelp(); return CommandTypes::Invalid; } } else { if (!has_file) { has_file = true; inputfile = arg; auto dotpos = inputfile.rfind('.'); if (dotpos == std::string::npos) { showError("Unknown input file type.\n"); showHelp(); return CommandTypes::Invalid; } std::string ext = inputfile.substr(dotpos + 1); if (!strcmp(ext.c_str(), "kc")) { inputKC = true; } else { inputfileNoExt = inputfile.substr(0, dotpos); } } else { showError("Possibly duplicate input file.\n"); return CommandTypes::Invalid; } } } if (has_h) showHelp(true); if (!has_file) { if (has_c || has_x || has_d || has_o || includeFiles.size()) { return CommandTypes::Invalid; } else { showHelp(true); return CommandTypes::None; } } else { if (has_c || has_x || !inputKC) { if (!inputKC) { if (!has_o) { outputfile = inputfileNoExt; outputfile.append(toNative ? EXESUFFIX : ".kc"); } if (has_c) return CommandTypes::Compile; else if (has_x) return CommandTypes::CompileNative; else return CommandTypes::CompileAndRun; } else { showError("Input file appears to be in compiled format.\n"); return CommandTypes::Invalid; } } else { if (has_d || has_o || includeFiles.size()) { showHelp(); return CommandTypes::Invalid; } else { return CommandTypes::Run; } } return CommandTypes::None; } }
static std::string database_GetValue(std::string entry) { int index = entry.rfind('='); return entry.substr(index + 1); }
static std::string get_include_file_path(const std::string &source, const std::string &var, const std::string &lit, bool documentRoot) { if (var.empty()) { // absolute path if (!lit.empty() && lit[0] == '/') { return lit; } // relative path to document root if (documentRoot) { return lit; } struct stat sb; // relative path to containing file's directory if (source.empty() && (stat(lit.c_str(), &sb) == 0)) { return lit; } size_t pos = source.rfind('/'); std::string resolved; if (pos != std::string::npos) { resolved = source.substr(0, pos + 1) + lit; if (stat(resolved.c_str(), &sb) == 0) { return resolved; } } // if file cannot be found, resolve it using search paths for (unsigned int i = 0; i < Option::IncludeSearchPaths.size(); i++) { auto const filename = Option::IncludeSearchPaths[i] + "/" + lit; if (stat(filename.c_str(), &sb) == 0) { return filename; } } // try still use relative path to containing file's directory if (!resolved.empty()) { return resolved; } return lit; } // [IncludeRoot] . 'string' auto const iter = Option::IncludeRoots.find(var); if (iter != Option::IncludeRoots.end()) { auto includeRoot = iter->second; if (!includeRoot.empty()) { if (includeRoot[0] == '/') includeRoot = includeRoot.substr(1); if (includeRoot.empty() || includeRoot[includeRoot.size()-1] != '/') { includeRoot += "/"; } } if (!lit.empty() && lit[0] == '/') { includeRoot += lit.substr(1); } else { includeRoot += lit; } return includeRoot; } return ""; }
std::string GetPathFromFilename(std::string filename) { return filename.substr(0, filename.rfind("\\") + 1); }