Example #1
0
void MDBG::Debugger::Run (string filename)
{
    // Find the name of the process
    processinfo.fullpath = filename;
    processinfo.name = filename.substr(filename.find_last_of("/") + 1);

    // Fork the process
    switch(processinfo.pid = fork())
    {
        // Error
        case -1:
            throw MDBG::ExceptionDebugger("Can't fork process", EXCEPTION_INFOS);

        // Child
        case 0:
#ifdef DEBUG
            cout << " <*> Loading '" << processinfo.name << "' (pid " << getpid() << ") in the debugger..." << endl;
#endif
            if(ptrace(PT_TRACE_ME, 0, NULL, 0) < 0)
                throw MDBG::ExceptionDebugger("Can't trace application", EXCEPTION_INFOS);
            
            execl(processinfo.fullpath.c_str(), processinfo.name.c_str(), NULL);
            throw MDBG::ExceptionDebugger("Can't load application", EXCEPTION_INFOS);

        // Parent : 
        default:
            // And wait for the child to be fully loaded/attached
            WaitForIt();
            
            // Get the process name/argv/envv, and the task port of the child, and check if it's a 32 or 64 bits process
            SetupProcessName();
            SetupTaskPort();
            SetupMode();
    }
    
    // Ok, the debugger is now working. :)
    active = true;
}
RF_Asset_List::RF_Asset_List(string path)
{
    ///Por el momento, path es un directorio

    //Obtenemos el id del paquete de recursos
        const size_t it = path.find_last_of('/');
        id = path; id.erase(0,it+1);

    //Extraemos el nombre del directorio para insertarlo en el nombre;
        DIR *dir;

    //En *ent habrá información sobre el archivo que se está "sacando" a cada momento;
        struct dirent *ent;

    //Empezaremos a leer en el directorio actual;
        dir = opendir (path.c_str());

    //Miramos que no haya error
        if (dir == NULL)
        {
            RF_Engine::instance->Debug(("LoadAsset [Error]: No se puede abrir directorio " + path));
            return;
        }

    //Creamos un puntero con el seleccionaremos el fichero de configuración (si existe);
        ifstream fich(path + "/package.cfg");

        if(fich.is_open())
        {
            RF_Engine::instance->Debug((path + "/package.cfg"));

            string buffer;
            while(!fich.eof())
            {
                fich >> buffer;
                cfg.push_back(buffer);
            }
        }
Example #3
0
string getPath(const string& sFilename)
{
    if (sFilename.length() > 0 && sFilename.at(sFilename.length()-1) == '/') {
        return sFilename;
    }
#ifdef _WIN32
    int pos = int(sFilename.find_last_of("\\/"));
    string dirName;
    if (pos >= 0) {
        dirName = sFilename.substr(0, pos+1);
    } else {
        dirName = sFilename;
    }
#else
    char * pszBuffer = strdup(sFilename.c_str());

    string dirName(dirname(pszBuffer));
    free(pszBuffer);
    dirName += "/";
#endif

    return dirName;
}
Example #4
0
StringArray path_split(const string &fname)
{
    size_t      found = -1;
    StringArray r;

    r.clear();

    /* find / or \ */
    found = fname.find_last_of("/\\");

    if( found == string::npos ) {
        r.push_back("");
        r.push_back(fname);
        return r;
    }

    // folder
    r.push_back(fname.substr(0, found));
    // file
    r.push_back(fname.substr(found+1));

    return r;
}
string C_visu_IO::getBaseName(string fileName)
{
    size_t found = fileName.find_last_of(".");
    string str;
    if(found==string::npos)
    {
        str = fileName;
    }
    else
    {
        size_t S = fileName.size();
        if(found<S-7)
        {
            str = fileName;
        }
        else
        {
            str = fileName.substr(0,found);
        }
    }
    return str;

}
Example #6
0
void MtlLibrary :: setFileNameWithPath (const string& filename)
{
	assert(filename.compare("") != 0);
	assert(filename.find_last_of("/\\") == string::npos ||
	       filename.find_last_of("/\\") + 1 < filename.size());

	string lowercase = toLowercase(filename);

	size_t last_slash = lowercase.find_last_of("/\\");
	if(last_slash != string::npos)
	{
		last_slash++;
		m_file_name = lowercase.substr(last_slash);
		m_file_path = lowercase.substr(0, last_slash);
	}
	else
	{
		m_file_name = lowercase;
		m_file_path = "";
	}

	assert(invariant());
}
Example #7
0
Foam::scalar Foam::fileFormats::NASCore::parseNASCoord
(
    const string& s
)
{
    size_t expSign = s.find_last_of("+-");

    if (expSign != string::npos && expSign > 0 && !isspace(s[expSign-1]))
    {
        scalar mantissa = readScalar(IStringStream(s.substr(0, expSign))());
        scalar exponent = readScalar(IStringStream(s.substr(expSign+1))());

        if (s[expSign] == '-')
        {
            exponent = -exponent;
        }
        return mantissa * pow(10, exponent);
    }
    else
    {
        return readScalar(IStringStream(s)());
    }
}
Example #8
0
/***
  * get type 
  * return 1 if type is int
  * return 2 if type is float
  * return n+2 if type is char(n)
  ***/
int getType(string type){

	if(type=="int"){
		return 1;
	}
	if(type=="float"){
		return 2;
	}

	if(type.find("char(")==0){
		int right_bracket_pos = type.find_last_of(')');

		if(right_bracket_pos==-1||right_bracket_pos!=type.length()-1)
			return -1;
		string content = type.substr(5,right_bracket_pos-5);// 5 is length of char(
		trim(content);
		int t = toInt(content);
		if(t<=0 ||t>255)
			return -1;
		return t+2;
	}
	return -1;
}
double String2Double(string str)
{
	size_t i, len;
	size_t first_pos, last_pos;

	if("" == str)
		return 0.0;

	first_pos = str.find_first_of("\"");
	last_pos = str.find_last_of("\"");

	if(string::npos != first_pos && string::npos != last_pos && first_pos != last_pos)
		str = str.substr(first_pos+1, last_pos-1);

	len = str.length();
	for(i = 0; i < len; i++)
	{
		if(!isdigit(str[i]) && '.' != str[i])
			return 0.0;
	}

	return strtold(str.c_str(), NULL);
}
Example #10
0
void GameObj::load_model(string path){

    if(loaded_meshes.count(path) > 0){
		//We have already loaded this model
        meshes = loaded_meshes[path];
		return;
	}

	Assimp::Importer import;
	const aiScene* scene = import.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs);	

    if(!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) 
    {
        cout << "Error::ASSIMP::" << import.GetErrorString() << endl;
        return;
    }
	mesh_dir = path.substr(0, path.find_last_of('/'));

	process_node(scene->mRootNode, scene);

	//Store the loaded meshes for use in other objects
	loaded_meshes[path] = meshes;
}
/*
 * get the comment of one of version of a specified file
 * 
 * param name of file and number of version
 * return comment of this version
 */
string filearchiver::getComment(string file, int versionnum)throw (const char*){
    if (invalid)
        throw (noDB);
    
    string filename = file.substr(file.find_last_of("/")+1);
    
    const char* gcomment = "select comments from comments where file_version_id=?";
    int vid = this->getVersionID(filename,versionnum);
    string recomment;
    sql::PreparedStatement *pstmt = NULL;
    sql::ResultSet *rs = NULL;
    
    pstmt = dbcon->prepareStatement(gcomment);
    pstmt->setInt(1,vid);
    rs = pstmt->executeQuery();
    if (rs->next()){
        recomment = rs->getString(1);
    }
    delete rs;
    delete pstmt;

    return recomment;
}
vector<string> FaceFinder::FindFace(const string& inputImgFile,const string& outputImgFile)
{
    Mat image= imread(inputImgFile, -1);
    unsigned int lastindex = inputImgFile.find_last_of(".");
    string fileName;
    if (lastindex<=inputImgFile.size())
    {
        fileName=inputImgFile.substr(0, lastindex);
    }
    else
    {
        fileName=inputImgFile;
    }
    lastindex = fileName.find_last_of("/");
    if (lastindex<=fileName.size())
    {
        fileName=fileName.substr(lastindex+1, fileName.size());
    }

    vector<string> resultTexts=Find(&image,fileName);
    imwrite(outputImgFile.c_str(),image);
    return resultTexts;
}
void Polygon::findCoordsInLine(string line, int* coords)
{
	size_t posX = line.find_first_of("=") + 1; //знайти позицію першого символа після першого входження символа "="
	size_t posY = line.find_last_of("=") + 1;//знайти позицію першого символа після останнього входження символа "="

	coords[0] = -1;//ініціалізувати значеннями масив точок для ідентифікації відсутності знайдених координат
	coords[1] = -1;

	if(posX > 0 && posY > 0)//якщо символи знайдено
	{
		size_t countX = line.find_first_of(",") - posX;//знайти індекс першого входження символу "," та відняти від нього позицію першої цифри числа координати, щоб знайти довжину числа
		size_t countY = line.length() - posY;//отримати довжину стрічки та відняти від нього позицію першої цифри числа координати, щоб знайти довжину числа		

		if(countX > 0 && countY > 0)//якщо символи знайдено
		{
			int x = stoi(line.substr(posX,countX));//перетворити в число потрібну частину стрічки з координатами
			int y = stoi(line.substr(posY,countY));

			coords[0] = x;//заповнити масив значеннями
			coords[1] = y;
		}
	}
}
Example #14
0
POIDetecter::POIDetecter(string configFilePath, string mapfile)
{
	ifstream infile(configFilePath.c_str());
	if(!infile)
	{
		cout<< "config file is error" << endl;
	}
	size_t lastpos = configFilePath.find_last_of("\\/");
	string modelpath = configFilePath.substr(0, lastpos) + "/";

	string configline;
	while (getline(infile, configline))
	{
		configline = trim(configline);
		if(configline.empty())
		{
			continue;
		}
		vector<string> configitems = strsplit(configline, " \t");
		if(configitems.size() < 2)
		{
			continue;
		}
		int label = atoi(configitems[0].c_str());
		CascadeClassifier classifier;
		if(!classifier.load(modelpath + configitems[1]))
		{
			cout << "load model file fail, please check!" << endl;
		}
		classifierMap[label].push_back(classifier);
	}
	 
	if(!mapfile.empty())
	{
		loadWordMap(mapfile);
	}
}
Example #15
0
int ZooKeeper::create(
    const string& path,
    const string& data,
    const ACL_vector& acl,
    int flags,
    string* result,
    bool recursive)
{
  if (!recursive) {
    return impl->create(path, data, acl, flags, result).get();
  }

  // First check if the path exists.
  int code = impl->exists(path, false, NULL).get();
  if (code == ZOK) {
    return ZNODEEXISTS;
  }

  // Now recursively create the parent path.
  // NOTE: We don't use 'dirname()' to get the parent path here
  // because, it doesn't return the expected path when a path ends
  // with "/". For example, to create path "/a/b/", we want to
  // recursively create "/a/b", instead of just creating "/a".
  const string& parent = path.substr(0, path.find_last_of("/"));
  if (!parent.empty()) {
    code = create(parent, "", acl, 0, result, true);
    if (code != ZOK && code != ZNODEEXISTS) {
      return code;
    }
  }

  // Finally create the path.
  // TODO(vinod): Delete any intermediate nodes created if this fails.
  // This requires synchronization because the deletion might affect
  // other callers (different threads/processes) acting on this path.
  return impl->create(path, data, acl, flags, result).get();
}
Example #16
0
//===========================================================================
///	SaveSupervoxelLabels
///
///	Save labels in raster scan order.
//===========================================================================
void SLIC::SaveSupervoxelLabels(
    const int**&				labels,
    const int&					width,
    const int&					height,
    const int&					depth,
    const string&				filename,
    const string&				path)
{
#ifdef WINDOWS
    char fname[256];
    char extn[256];
    _splitpath(filename.c_str(), NULL, NULL, fname, extn);
    string temp = fname;
    string finalpath = path + temp + string(".dat");
#else
    string nameandextension = filename;
    size_t pos = filename.find_last_of("/");
    if(pos != string::npos)//if a slash is found, then take the filename with extension
    {
        nameandextension = filename.substr(pos+1);
    }
    string newname = nameandextension.replace(nameandextension.rfind(".")+1, 3, "dat");//find the position of the dot and replace the 3 characters following it.
    string finalpath = path+newname;
#endif

    int sz = width*height;
    ofstream outfile;
    outfile.open(finalpath.c_str(), ios::binary);
    for( int d = 0; d < depth; d++ )
    {
        for( int i = 0; i < sz; i++ )
        {
            outfile.write((const char*)&labels[d][i], sizeof(int));
        }
    }
    outfile.close();
}
Example #17
0
    Shapefile::Shapefile (string const filename, GeometryType layer_type, bool append)
    {
        name = filename.substr(0, filename.find_last_of('.'));
        geom_type = layer_type;
        layer = NULL;

        OGRRegisterAll();
        driver = OGRGetDriverByName(driver_name.c_str());
        if( driver == NULL ) {
            throw runtime_error( driver_name + " driver not available." );
        }

        ds = OGR_Dr_Open(driver, filename.c_str(), NULL);
        if (ds != NULL && !append) {
            OGR_DS_Destroy(ds);
            unlink(filename.c_str());
        }
        if (ds == NULL || !append) {
            ds = OGR_Dr_CreateDataSource(driver, filename.c_str(), NULL);
            if( ds == NULL ) {
                throw runtime_error(filename + " datasource creation failed.");
            }
        }

        layer = OGR_DS_GetLayer(ds, 0);
        if (layer != NULL && !append) {
            if (OGR_DS_DeleteLayer(ds, 0) != OGRERR_NONE) {
                throw runtime_error(filename + " existing layer can't be deleted.");
            }
        }
        if (layer == NULL) {
            layer = OGR_DS_CreateLayer(ds, name.c_str(), NULL, layer_type, NULL);
            if( layer == NULL ) {
                throw runtime_error(filename + " layer creation failed.");
            }
        }
    }
/*
Trying to read offset and vertices data from file.
Return false if failed.
TODO: Read-error-check.
*/
bool CPathEstimator::ReadFile(string name) 
{

	unsigned int hash=Hash();
	char hashString[50];
	sprintf(hashString,"%u",hash);

	string filename = string("maps/paths/") + stupidGlobalMapname.substr(0, stupidGlobalMapname.find_last_of('.') + 1) + hashString + "." + name + ".zip";
	CArchiveZip file(filename);
	if (!file.IsOpen()) 
		return false;

	int fh = file.OpenFile("pathinfo");

	if (fh) {
		unsigned int filehash = 0;
 		//Check hash.
//		info->AddLine("%i",hash);
		file.ReadFile(fh, &filehash, 4);
		if(filehash != hash)
			return false;

		//Read block-center-offset data.
		int blocknr;
		for(blocknr = 0; blocknr < nbrOfBlocks; blocknr++) {
			file.ReadFile(fh, blockState[blocknr].sqrCenter, moveinfo->moveData.size() * sizeof(int2));
		}

		//Read vertices data.
		file.ReadFile(fh, vertex, nbrOfVertices * sizeof(float));
		
		//File read successful.
		return true;
	} else {
		return false;
	}
}
/*
Trying to write offset and vertices data to file.
*/
void CPathEstimator::WriteFile(string name) {
	// We need this directory to exist
	if (!filesystem.CreateDirectory("maps/paths"))
		return;

	unsigned int hash = Hash();
	char hashString[50];
	sprintf(hashString,"%u",hash);

	string filename = string("maps/paths/") + stupidGlobalMapname.substr(0, stupidGlobalMapname.find_last_of('.') + 1) + hashString + "." + name + ".zip";
	zipFile file;

	// open file for writing in a suitable location
	file = zipOpen(filesystem.LocateFile(filename, FileSystem::WRITE).c_str(), APPEND_STATUS_CREATE);

	if (file) {
		zipOpenNewFileInZip(file, "pathinfo", NULL, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_BEST_COMPRESSION);

		//Write hash.
		unsigned int hash = Hash();
		zipWriteInFileInZip(file, (void*)&hash, 4);

		//Write block-center-offsets.
		int blocknr;
		for(blocknr = 0; blocknr < nbrOfBlocks; blocknr++) {
			zipWriteInFileInZip(file, (void*)blockState[blocknr].sqrCenter, moveinfo->moveData.size() * sizeof(int2));
			//file.write((char*)blockState[blocknr].sqrCenter, moveinfo->moveData.size() * sizeof(int2));
		}

		//Write vertices.
		zipWriteInFileInZip(file, (void*)vertex, nbrOfVertices * sizeof(float));
		//file.write((char*)vertex, nbrOfVertices * sizeof(float));

		zipCloseFileInZip(file);
		zipClose(file, NULL);
	}
}
Example #20
0
void
RSSFeed::removeCDATA(const string & str, string &tmp)
{
	if (str.empty())
		return;
	//[-] PVS-Studio V808 string tmpVal;
	string::size_type findFirst = str.find("<![CDATA[");
	string::size_type findLast = str.find_last_of("]]>");
	if (findFirst == 0 && findLast == str.size() - 1)
	{
		tmp = str.substr(9, str.size() - 3 - 9);
	}
	else
	{
		tmp = str;
	}
	/*
	    tmp.reserve(tmpVal.length());
	    string::const_iterator end = tmpVal.end();
	    for(string::const_iterator i = tmpVal.begin(); i != end; ++i) {
	        tmp += (*i);
	    }
	*/
}
Example #21
0
void printBadEvents(string filename){
  string run = filename.substr(filename.find("_R000")+10, 1);
  int nrun = atoi(run.c_str());
  string fname(filename.substr(filename.find_last_of("/")+1) );
  cout << "FileName is " << fname.c_str() << endl;

  ofstream outfile;
  stringstream namefile;
  namefile << "BadEvents_" << nrun << ".txt";
  outfile.open(namefile.str().c_str());
  outfile << "Bad events in file " << fname.c_str() << endl; 

  TDirectory* topDir; 
  TFile* file = TFile::Open(filename.c_str());
  if (!file->IsOpen()) {
    cerr << "Failed to open " << filename << endl; 
    return;
  }
  string dir = "DQMData/Run " + run + "/ParticleFlow/Run summary/ElectronValidation/JetPtRes/BadEvents";
  topDir = dynamic_cast<TDirectory*>( file->Get(dir.c_str()));
  topDir->cd();
  if (topDir){
    TIter next(topDir->GetListOfKeys());
    TKey *key;
    while  ( (key = dynamic_cast<TKey*>(next())) ) {
      string sflag = key->GetName();
      string info(sflag.substr(1, sflag.find_first_of(">")-1 ) );
      string run(info.substr(0, info.find_first_of("_")) );
      string evt = info.substr( info.find_first_of("_")+1, info.find_last_of("_")-2);
      string ls(info.substr(info.find_last_of("_")+1,info.find_first_of("_")+1));
      string ptres = ( sflag.substr( sflag.find( "f=" ) + 2, 6 ) ).c_str();
      cout << "Event info: Run " << run << " LS " << ls << " Evt " << evt << " Jet Pt Res = " << ptres << endl; 
      outfile << "Event info: Run " << run << " LS " << ls << " Evt " << evt << " Jet Pt Res = " << ptres << endl; 
    }
  }
}
Example #22
0
/*
*写视频帧
*fullpathname	读取视频的全路径
*dstdir         保存目录
*/
void VedioWrite(string fullpathname,string dstdir)
{
	CvCapture *capture=cvCreateFileCapture(fullpathname.c_str());
	IplImage *frame;
	int w,h,fps,pos;
	string name;
	pos=fullpathname.find_last_of('\\');                               //找到最后一个‘\’的位置
	name=fullpathname.substr(pos+1,fullpathname.length()-3-1-pos)+"avi";  //成员方法substr,参数为:初始位置,长度

	w=cvGetCaptureProperty(capture,CV_CAP_PROP_FRAME_WIDTH);
	h=cvGetCaptureProperty(capture,CV_CAP_PROP_FRAME_HEIGHT);			//获取视频的属性
	fps=cvGetCaptureProperty(capture,CV_CAP_PROP_FPS);
	CvVideoWriter *writer=cvCreateVideoWriter((dstdir+"\\"+name).c_str(),-1,fps,cvSize(w,h));//成员方法c_str(),把string变成char*
	while(1)
	{
		frame=cvQueryFrame(capture);
		if(!frame) break;
		else
			cvWriteFrame(writer,frame);

	}
	cvReleaseCapture(&capture);
	cvReleaseVideoWriter(&writer);
}
Example #23
0
/*************************************************************
 * Reads and parses an obj file
 *************************************************************/
void ObjectLoader::loadFile(string filename)
{
  // Store Directory
  int endOfDirectory = filename.find_last_of("/");
  mDirectory = filename.substr(0, endOfDirectory) + '/';

  // Open File
  ifstream fin;
  fin.open(filename.c_str());

  // Check For Success
  if (fin.fail()){
    cout << "Error: Could not open " << filename << endl;
    return;
  }

  // Read File
  string header;
  while (fin >> header){
    if (header == "#") getline(fin, header); // Comment
    else if (header == "v") readVertex(fin);
    else if (header == "vt") readTexCoord(fin);
    else if (header == "vn") readNormal(fin);
    else if (header == "f"){
      readFace(fin);
      if (mTriangles) mIndForMaterial[mIndForMaterial.size() - 1] += 3;
      else mIndForMaterial[mIndForMaterial.size() - 1] += 6;
    }
    else if (header == "mtllib") loadMaterials(fin);
    else if (header == "usemtl"){
      fin >> header;
      mCurrentMaterial = mMaterialMap[header];
      mMatNumber.push_back(mCurrentMaterial);
      mIndForMaterial.push_back(0);
    }
    else getline(fin, header); // Unimplemented
Example #24
0
//拡張子を調べる
EXTENSIONS getExtension(string filename) {
	int index = filename.find_last_of('.');
	string extension = filename.substr(index+1);
	if (strcmp(extension.c_str(), "")==0) {
		//拡張子無し
		return EXT_NONE;
	} else if (strcmp(extension.c_str(), "wav")==0 || strcmp(extension.c_str(), "WAV")==0) {
		return EXT_WAVE;
	} else if (strcmp(extension.c_str(), "mp3")==0 || strcmp(extension.c_str(), "MP3")==0) {
		return EXT_MP3;
	} else if (strcmp(extension.c_str(), "mid")==0 || strcmp(extension.c_str(), "MID")==0) {
		return EXT_MID;
	} else if (strcmp(extension.c_str(), "fbx")==0 || strcmp(extension.c_str(), "FBX")==0) {
		return EXT_FBX;
	} else if (strcmp(extension.c_str(), "png")==0 || strcmp(extension.c_str(), "PNG")==0) {
		return EXT_PNG;
	} else if (strcmp(extension.c_str(), "jpg")==0 || strcmp(extension.c_str(), "JPG")==0) {
		return EXT_JPG;
	} else if (strcmp(extension.c_str(), "bmp")==0 || strcmp(extension.c_str(), "BMP")==0) {
		return EXT_BMP;
	} else {
		return EXT_UNKNOWN;
	}
}
Example #25
0
	bool XlsWriter::writeToFile( const string &filePath, const XlsBookStruct &xlsBook ){
		string folderPath = filePath.substr( 0, filePath.find_last_of('/', filePath.size() )+1 );
		if( !createDir( folderPath ) )  return false;
	
		workbook wb;
		worksheet *ws;
		xf_t *xf = wb.xformat();
		ws = wb.sheet("sheet1");

		for( XlsBookStruct::const_iterator citerSheet = xlsBook.begin(); citerSheet != xlsBook.end(); ++citerSheet ){
			int line( 0), column(0);
			for( XlsSheetStruct::const_iterator citerRow = citerSheet->begin(); citerRow != citerSheet->end(); ++citerRow ){
				++line;
				column = 0;
				for( XlsRowStruct::const_iterator citer = citerRow->begin(); citer != citerRow->end(); ++citer ){
					ws->label( line, column++, *citer, xf);
				}
			}
		}

		wb.Dump( filePath);

		return true;
	}
Example #26
0
// extract topbname in the hierarchy from a full sc_module name
// ex: name=top.module1.submodule2.module =>
//            3       2          1      0
//     pos=2
// return: top.module1
string utils_extract_topname(string name, int pos) {

  int idx=0;
  string return_name;

  for(int i=0; i<=pos; i++) {
    //cout << "i=" << i << endl;
    //idx=name.find_last_of('.');
    idx=name.find_last_of(HIERARCHY_CHAR);
    //cout << "idx=" << idx << endl;
    if(idx<0) {
      if(i==pos) {
        return name;
      } else {
        return "";
      }
    }
    return_name = name;
    name = name.substr(0,idx);
  }

  return return_name;

}
Example #27
0
void header::add_CONTIG_descriptor(const string &in, int index)
{
	size_t found_end=in.find_last_of(">");
	string details = in.substr(0, found_end);

	vector<string> tokens;
	tokenize(details, ',', tokens);
	Field_description I;
	I.Field = "contig";
	bool id_found = false;
	vector<string> entry;

	for (unsigned int ui=0; ui<tokens.size(); ui++)
	{
		tokenize(tokens[ui], '=', entry);
		if (entry[0] == "ID")
		{
			I.ID = entry[1];
			id_found = true;
		}
		else if (entry[0] == "length") I.Length = entry[1];
		else if (entry[0] == "assembly") I.Assembly = entry[1];
		else
		{
			if (I.Other != "")
				I.Other += ",";
			I.Other += tokens[ui];
		}
	}
	if (id_found == false)
		LOG.warning("CONTIG declaration found without ID: "+ in + "\n");

	parsed_lines.push_back(I);
	CONTIG_map[index] = I;
	CONTIG_reverse_map[I.ID] = index;
}
Example #28
0
// Error for a missing file
NoSuchFileException::NoSuchFileException(const string &fileName)
{
  strncpy(_message, "Could not open file ", _MessageSize - _FileNameSize - 1);
  /* If the file name (which may include the full path) is smaller than
    the space available, just copy it. Otherwise, try to remove the path
    and just use the filename. Note that a standard string substring can't
    be used here, because it alloates memory which in turn could cause an
    exception */
  if (fileName.length() < _FileNameSize)
    strncat(_message, fileName.c_str(), _FileNameSize);
  else {
    unsigned int startPos = fileName.find_last_of('/');
    if (startPos == string::npos)
        startPos = 0; // No directory information
    else if ((fileName.length() - startPos) < _FileNameSize)
        // File name less than space available, copy some of the path also
        startPos = fileName.length() - _FileNameSize - 1; // One char for NUL
    else
        startPos++; // Don't include the slash
    // NOTE: Hacky C style pointer arithmetric, needed by the function signature
    strncat(_message, fileName.c_str() + startPos, _FileNameSize);
  } // File name too long
  _message[_MessageSize - 1] = '\0'; // Ensure string is terminated
}
Example #29
0
string BinarySerialize::getConatinerElementClassName(void* _1, string className)
{
	AMEFObject* root = (AMEFObject*)_1;
	string stlclassName = className;
	if(stlclassName.find(">")!=string::npos)
	{
		className = stlclassName.substr(stlclassName.find("<")+1);
		className = className.substr(0, className.find(">"));
	}
	else
	{
		className = stlclassName.substr(stlclassName.find("<")+1);
		if(className.find(",")!=string::npos)
		{
			className = className.substr(0, className.find_last_of(','));
		}
	}
	/*if(stlclassName.find("-")!=string::npos)
	{
		className = stlclassName.substr(stlclassName.find("-")+1);
	}*/
	StringUtil::trim(className);
	return className;
}
Example #30
0
		// cleaning method for URL only
		// Note : This function is made to keep things DRY
		void clean_path_( string& input )
		{
			if( input.length() == 0 ) return;

			int write_index = 0;
			int check_index = 0;
			while( check_index < input.length() ){
				if( input[check_index] == '\\' ){
					check_index = input.find_first_not_of( '\\', check_index );
					if( check_index != -1 ){
						check_index--;
					} else {
						check_index = input.find_last_of( '\\' );
					}
				}

				input[write_index] = input[check_index];
				write_index++;
				check_index++;
			}


			if( write_index != input.length() ) input.resize( write_index + 1 );
		}