// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
int32_t VtkStructuredPointsReader::readLine(std::istream& in, char* result, size_t length)
{
  in.getline(result, length);
  if (in.fail())
  {
    if (in.eof())
    {
      return 0;
    }
    if (in.gcount() == length)
    {
      // Read kBufferSize chars; ignoring the rest of the line.
      in.clear();
      in.ignore(std::numeric_limits<int>::max(), '\n');
    }
  }
  return 1;
}
예제 #2
0
void readFastaEntry(std::istream& i,
		    std::string& name,
		    std::string& description,
		    std::string& sequence)
  throw (ParseException)
{
    char ch;
    char c[512];

    i.getline(c, 511);
    if (i) {
      if (c[0] != '>') {
	throw ParseException(std::string("FASTA file expected '>', got: '")
			     + c[0] + "'");
      }

      std::string nameDesc = c + 1;
      std::string::size_type spacepos = nameDesc.find(" ");
      name = nameDesc.substr(0, spacepos);
      description = (spacepos == std::string::npos
		     ? ""
		     : nameDesc.substr(spacepos));

      for (ch = i.get(); (ch != EOF) && (ch != '>'); ch = i.get()) {
	if ((ch != '\n') && (ch != '\r') && (ch != ' ')) {
	  if (((ch >= 'a') && (ch <= 'z'))
	      || ((ch >= 'A') && (ch <= 'Z'))
	      || (ch == '-') || (ch == '*')) {
	    sequence += ch;
	  } else {
	    throw ParseException
	      (std::string("Illegal character in FASTA file: '")
	       + (char)ch + "'");
	  }
	}

	if (i.peek() == EOF)
	  break;
      }

      if (ch == '>')
	i.putback(ch);
    }
}
예제 #3
0
    void Compression::ZlibDecompress (std::istream& is, std::ostream& os)
    {
	char buffer[32];
	is.getline (buffer, sizeof(buffer), '#');
	int size (atoi (buffer));
	if (size == 0) return;

	filtering_stream<input> fs;

	fs.push (zlib_decompressor());
	fs.push (restrict (is, 0, size));

	boost::iostreams::copy(fs, os);
	// fs.set_auto_close (false);
	fs.pop ();

	// Warning filtering stream is closed at destruction causing all underlying device to be clolsed as well.

    }
예제 #4
0
void LLMimeParser::Impl::scanPastSeparator(
	std::istream& istr,
	S32 limit,
	const std::string& sep)
{
	std::ostringstream ostr;
	ostr << SEPARATOR_PREFIX << sep;
	std::string separator = ostr.str();
	bool found_separator = false;
	while(!found_separator && continueParse())
	{
		// Subtract 1 from the limit so that we make sure not to read
		// past limit when we get() the newline.
		S32 max_get = llmin((S32)LINE_BUFFER_LENGTH, limit - mScanCount - 1);
		istr.getline(mBuffer, max_get, '\r');
		mScanCount += istr.gcount();
		if(istr.gcount() >= LINE_BUFFER_LENGTH - 1)
		{
			// that's way too long to be a separator, so ignore it.
			continue;
		}
		int c = istr.get();
		if(EOF == c)
		{
			mContinue = false;
			return;
		}
		++mScanCount;
		if(c != '\n')
		{
			mError = true;
			return;
		}
		if(mScanCount >= limit)
		{
			mContinue = false;
		}
		if(0 == LLStringUtil::compareStrings(std::string(mBuffer), separator))
		{
			found_separator = true;
		}
	}
}
예제 #5
0
void
cpu_tsdf::Octree::deserialize (std::istream &f)
{
  std::string root_type;
  f >> root_type;
  root_.reset (OctreeNode::instantiateByTypeString (root_type));
  char tmp[1024];
  do
  {
    f.getline (tmp, 1024);
  }
  while (!(tmp[0] == '#' && tmp[1] == 'O'));
  f.read ((char*)&res_x_, sizeof (size_t));
  f.read ((char*)&res_y_, sizeof (size_t));
  f.read ((char*)&res_z_, sizeof (size_t));
  f.read ((char*)&size_x_, sizeof (float));
  f.read ((char*)&size_y_, sizeof (float));
  f.read ((char*)&size_z_, sizeof (float));
  root_->deserialize (f);
}
예제 #6
0
void gl_mesh::LoadFromVxo(std::istream & File)
{
	// float must be 32 bits
	static_assert(sizeof(char) == sizeof(uint8_t));
	static_assert(sizeof(float) == sizeof(uint32_t));

	using io_facilities::readvar;
	
	// Mesh Name
	char String[256];
	File.getline(String, 256, '\0');
	m_Name = String;

	// Mesh Info
	size_t NbSubMeshes;
	readvar(File, NbSubMeshes, 4);
	readvar(File, m_NbVertices, 4);
	readvar(File, m_NbTextures, 4);

	m_SubMeshes.resize(NbSubMeshes);
	m_VArrays[vertex].resize(3 * m_NbVertices);
	m_VArrays[normal].resize(3 * m_NbVertices);

	for (size_t i = 0; i < m_NbTextures; ++i)
		m_VArrays[array_type(texture_coord0 + i)].resize(2 * m_NbVertices);

	// Load Mesh Data
	for (size_t i = 0; i < (m_NbVertices * 3); ++i)
		readvar(File, reinterpret_cast<uint32_t &>(m_VArrays[vertex][i]), 4);

	for (size_t i = 0; i < (m_NbVertices * 3); ++i)
		readvar(File, reinterpret_cast<uint32_t &>(m_VArrays[normal][i]), 4);

	for (size_t i = 0; i < m_NbTextures; ++i)
		for (size_t j = 0; j < (m_NbVertices * 2); ++j)
			readvar(File, reinterpret_cast<uint32_t &>(m_VArrays[array_type(texture_coord0 + i)][j]), 4);

	// Load Each SubMesh
	for (size_t i = 0; i < m_SubMeshes.size(); ++i)
		m_SubMeshes[i].LoadFromVXO(File);
}
예제 #7
0
void OTString::OTfgets(std::istream & ifs)
{
	// _WIN32
	static char * buffer = NULL;
	
	if (NULL == buffer)
	{
		buffer = new char[MAX_STRING_LENGTH]; // This only happens once. Static var.
		OT_ASSERT(NULL != buffer);
	}
	
	buffer[0] = '\0';
	// _end _WIN32
	
	if (ifs.getline(buffer, MAX_STRING_LENGTH-1)) // delimiter defaults to '\n'
	{
		buffer[strlen(buffer)] = '\0';
		
		Set(buffer);
	}	
}
예제 #8
0
 void SectionParser::parse(std::istream& input, ForceField& ff, int lineNo) {
   const int bufferSize = 65535;
   char buffer[bufferSize];
   std::string line;
   while(input.getline(buffer, bufferSize)) {
     ++lineNo;
     line = trimLeftCopy(buffer);
     //a line begins with "//" is comment
     // let's also call lines starting with # and ! as comments
     if (isEndSection(line)) {
       break;
     } else if ( line.empty() || 
                 (line.size() >= 2 && line[0] == '/' && line[1] == '/') ||
                 (line.size() >= 1 && line[0] == '#') || 
                 (line.size() >= 1 && line[0] == '!') ) {
       continue;
     } else {
       parseLine(ff, line, lineNo);
     }
   }
 }
예제 #9
0
  MOL_SPTR_VECT readFuncGroups(std::istream &inStream,int nToRead) {
    MOL_SPTR_VECT funcGroups;
    funcGroups.clear();
    if (inStream.bad()) {
      throw BadFileException("Bad stream contents.");
    }
    const int MAX_LINE_LEN = 512;
    char inLine[MAX_LINE_LEN];
    std::string tmpstr;
    int nRead=0;
    while (!inStream.eof() && (nToRead<0 || nRead<nToRead)) {
      inStream.getline(inLine, MAX_LINE_LEN,'\n');
      tmpstr = inLine;
      // parse the molecule on this line (if there is one)
      ROMol *mol = getSmarts(tmpstr);
      if (mol) {
	funcGroups.push_back(ROMOL_SPTR(mol));
	nRead++;
      }
    }
    return funcGroups;
  }
예제 #10
0
int do_tell(ai::PL::KnowledgeBase &kb, int interactive, char *buf, std::istream &in, std::ostream &out)
{
    char * sentence = 0;
    if(strlen(buf) > 4)
    {
        sentence = &buf[4];
    }
    else
    {
        if(interactive)
        {
            out << "tell> " << std::flush;
        }
        in.getline(buf, BUF_SIZE);
        sentence = buf;
    }
    kb.AddSentence(sentence);
    if(!interactive)
    {
        out << "tell " << sentence << std::endl;
    }
    return 0;
}
예제 #11
0
void
SimpleConfig::parse_config (std::istream &is, KeyValueRepository &config)
{
    char *conf_line = new char [SCIM_MAX_CONFIG_LINE_LENGTH];

    while (!is.eof()) {
        is.getline(conf_line, SCIM_MAX_CONFIG_LINE_LENGTH);
        if (!is.eof()) {
            String normalized_line = trim_blank(conf_line);

            if ((normalized_line.find_first_of("#") > 0) && (normalized_line.length() != 0)) {
                if (normalized_line.find_first_of("=") == String::npos) {
                    SCIM_DEBUG_CONFIG(2) << " Invalid config line : " << normalized_line << "\n";
                    continue;
                }

                if (normalized_line[0] == '=') {
                    SCIM_DEBUG_CONFIG(2) << " Invalid config line : " << normalized_line << "\n";
                    continue;
                }

                String param = get_param_portion(normalized_line);
                KeyValueRepository::iterator i = config.find(param);

                if (i != config.end()) {
                    SCIM_DEBUG_CONFIG(2) << " Config entry " << normalized_line << " has been read.\n";
                } else {
                    String value = get_value_portion (normalized_line); 
                    config [param] = value;
                    SCIM_DEBUG_CONFIG(2) << " Config entry " << param << "=" << value << " is successfully read.\n";
                }
            }
        }
    }

    delete [] conf_line;
}
예제 #12
0
void process(const char* filename, std::istream& ifs, std::ostream& ofs, 
    std::ostream& indexfs)
{
    int n = 1024;
    char tmpbuf[1024];
    char tag[128];
    char entry[1024];

    while (!ifs.eof())
    {
        ifs.getline(tmpbuf,n);
        if (ifs.eof())
            break;
        ofs << tmpbuf;

        char* index;
        if ((index = strstr(tmpbuf, "BZINDEX")) != 0) {
            char* index2 = strstr(index, "-->");
            if (index2 != 0)
                index2[-1] = 0;
            index += 8;

            sprintf(tag, "index%05d", tagnum++);
            ofs << "<a name=\"" << tag << "\">";

            makeEntry(entry, index);
            indexfs << index << " |"
                    << entry << "|"
                    << filename << "#" << tag << std::endl;

//            std::cout << "Found tag: \"" << index << "\"" << std::endl;
        }

        ofs << std::endl;
    }
}
예제 #13
0
std::string LoadObj(
  std::vector<shape_t>& shapes,
  std::vector<material_t>& materials,   // [output]
  std::istream& inStream,
  MaterialReader& readMatFn)
{
  std::stringstream err;

  std::vector<float> v;
  std::vector<float> vn;
  std::vector<float> vt;
  std::vector<std::vector<vertex_index> > faceGroup;
  std::string name;

  // material
  std::map<std::string, int> material_map;
  std::map<vertex_index, unsigned int> vertexCache;
  int  material = -1;

  shape_t shape;

  int maxchars = 8192;  // Alloc enough size.
  std::vector<char> buf(maxchars);  // Alloc enough size.
  while (inStream.peek() != -1) {
    inStream.getline(&buf[0], maxchars);

    std::string linebuf(&buf[0]);

    // Trim newline '\r\n' or '\n'
    if (linebuf.size() > 0) {
      if (linebuf[linebuf.size()-1] == '\n') linebuf.erase(linebuf.size()-1);
    }
    if (linebuf.size() > 0) {
      if (linebuf[linebuf.size()-1] == '\r') linebuf.erase(linebuf.size()-1);
    }

    // Skip if empty line.
    if (linebuf.empty()) {
      continue;
    }

    // Skip leading space.
    const char* token = linebuf.c_str();
    token += strspn(token, " \t");

    assert(token);
    if (token[0] == '\0') continue; // empty line

    if (token[0] == '#') continue;  // comment line

    // vertex
    if (token[0] == 'v' && isSpace((token[1]))) {
      token += 2;
      float x, y, z;
      parseFloat3(x, y, z, token);
      v.push_back(x);
      v.push_back(y);
      v.push_back(z);
      continue;
    }

    // normal
    if (token[0] == 'v' && token[1] == 'n' && isSpace((token[2]))) {
      token += 3;
      float x, y, z;
      parseFloat3(x, y, z, token);
      vn.push_back(x);
      vn.push_back(y);
      vn.push_back(z);
      continue;
    }

    // texcoord
    if (token[0] == 'v' && token[1] == 't' && isSpace((token[2]))) {
      token += 3;
      float x, y;
      parseFloat2(x, y, token);
      vt.push_back(x);
      vt.push_back(y);
      continue;
    }

    // face
    if (token[0] == 'f' && isSpace((token[1]))) {
      token += 2;
      token += strspn(token, " \t");

      std::vector<vertex_index> face;
      while (!isNewLine(token[0])) {
        vertex_index vi = parseTriple(token, v.size() / 3, vn.size() / 3, vt.size() / 2);
        face.push_back(vi);
        int n = strspn(token, " \t\r");
        token += n;
      }

      faceGroup.push_back(face);

      continue;
    }

    // use mtl
    if ((0 == strncmp(token, "usemtl", 6)) && isSpace((token[6]))) {

      char namebuf[4096];
      token += 7;
      sscanf(token, "%s", namebuf);

      faceGroup.clear();

      if (material_map.find(namebuf) != material_map.end()) {
        material = material_map[namebuf];
      } else {
        // { error!! material not found }
        material = -1;
      }

      continue;

    }

    // load mtl
    if ((0 == strncmp(token, "mtllib", 6)) && isSpace((token[6]))) {
      char namebuf[4096];
      token += 7;
      sscanf(token, "%s", namebuf);

      std::string err_mtl = readMatFn(namebuf, materials, material_map);
      if (!err_mtl.empty()) {
        faceGroup.clear();  // for safety
        return err_mtl;
      }

      continue;
    }

    // group name
    if (token[0] == 'g' && isSpace((token[1]))) {

      // flush previous face group.
      bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, material, name, true);
      if (ret) {
        shapes.push_back(shape);
      }

      shape = shape_t();

      //material = -1;
      faceGroup.clear();

      std::vector<std::string> names;
      while (!isNewLine(token[0])) {
        std::string str = parseString(token);
        names.push_back(str);
        token += strspn(token, " \t\r"); // skip tag
      }

      assert(names.size() > 0);

      // names[0] must be 'g', so skipt 0th element.
      if (names.size() > 1) {
        name = names[1];
      } else {
        name = "";
      }

      continue;
    }

    // object name
    if (token[0] == 'o' && isSpace((token[1]))) {

      // flush previous face group.
      bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, material, name, true);
      if (ret) {
        shapes.push_back(shape);
      }

      //material = -1;
      faceGroup.clear();
      shape = shape_t();

      // @todo { multiple object name? }
      char namebuf[4096];
      token += 2;
      sscanf(token, "%s", namebuf);
      name = std::string(namebuf);


      continue;
    }

    // Ignore unknown command.
  }

  bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, material, name, true);
  if (ret) {
    shapes.push_back(shape);
  }
  faceGroup.clear();  // for safety

  return err.str();
}
예제 #14
0
std::string LoadMtl (
  std::map<std::string, int>& material_map,
  std::vector<material_t>& materials,
  std::istream& inStream)
{
  material_map.clear();
  std::stringstream err;

  material_t material;

  int maxchars = 8192;  // Alloc enough size.
  std::vector<char> buf(maxchars);  // Alloc enough size.
  while (inStream.peek() != -1) {
    inStream.getline(&buf[0], maxchars);

    std::string linebuf(&buf[0]);

    // Trim newline '\r\n' or '\n'
    if (linebuf.size() > 0) {
      if (linebuf[linebuf.size()-1] == '\n') linebuf.erase(linebuf.size()-1);
    }
    if (linebuf.size() > 0) {
      if (linebuf[linebuf.size()-1] == '\r') linebuf.erase(linebuf.size()-1);
    }

    // Skip if empty line.
    if (linebuf.empty()) {
      continue;
    }

    // Skip leading space.
    const char* token = linebuf.c_str();
    token += strspn(token, " \t");

    assert(token);
    if (token[0] == '\0') continue; // empty line

    if (token[0] == '#') continue;  // comment line

    // new mtl
    if ((0 == strncmp(token, "newmtl", 6)) && isSpace((token[6]))) {
      // flush previous material.
      if (!material.name.empty())
      {
          material_map.insert(std::pair<std::string, int>(material.name, materials.size()));
          materials.push_back(material);
      }

      // initial temporary material
      InitMaterial(material);

      // set new mtl name
      char namebuf[4096];
      token += 7;
      sscanf(token, "%s", namebuf);
      material.name = namebuf;
      continue;
    }

    // ambient
    if (token[0] == 'K' && token[1] == 'a' && isSpace((token[2]))) {
      token += 2;
      float r, g, b;
      parseFloat3(r, g, b, token);
      material.ambient[0] = r;
      material.ambient[1] = g;
      material.ambient[2] = b;
      continue;
    }

    // diffuse
    if (token[0] == 'K' && token[1] == 'd' && isSpace((token[2]))) {
      token += 2;
      float r, g, b;
      parseFloat3(r, g, b, token);
      material.diffuse[0] = r;
      material.diffuse[1] = g;
      material.diffuse[2] = b;
      continue;
    }

    // specular
    if (token[0] == 'K' && token[1] == 's' && isSpace((token[2]))) {
      token += 2;
      float r, g, b;
      parseFloat3(r, g, b, token);
      material.specular[0] = r;
      material.specular[1] = g;
      material.specular[2] = b;
      continue;
    }

    // transmittance
    if (token[0] == 'K' && token[1] == 't' && isSpace((token[2]))) {
      token += 2;
      float r, g, b;
      parseFloat3(r, g, b, token);
      material.transmittance[0] = r;
      material.transmittance[1] = g;
      material.transmittance[2] = b;
      continue;
    }

    // ior(index of refraction)
    if (token[0] == 'N' && token[1] == 'i' && isSpace((token[2]))) {
      token += 2;
      material.ior = parseFloat(token);
      continue;
    }

    // emission
    if(token[0] == 'K' && token[1] == 'e' && isSpace(token[2])) {
      token += 2;
      float r, g, b;
      parseFloat3(r, g, b, token);
      material.emission[0] = r;
      material.emission[1] = g;
      material.emission[2] = b;
      continue;
    }

    // shininess
    if(token[0] == 'N' && token[1] == 's' && isSpace(token[2])) {
      token += 2;
      material.shininess = parseFloat(token);
      continue;
    }

    // illum model
    if (0 == strncmp(token, "illum", 5) && isSpace(token[5])) {
      token += 6;
      material.illum = parseInt(token);
      continue;
    }

    // dissolve
    if ((token[0] == 'd' && isSpace(token[1]))) {
      token += 1;
      material.dissolve = parseFloat(token);
      continue;
    }
    if (token[0] == 'T' && token[1] == 'r' && isSpace(token[2])) {
      token += 2;
      material.dissolve = parseFloat(token);
      continue;
    }

    // ambient texture
    if ((0 == strncmp(token, "map_Ka", 6)) && isSpace(token[6])) {
      token += 7;
      material.ambient_texname = token;
      continue;
    }

    // diffuse texture
    if ((0 == strncmp(token, "map_Kd", 6)) && isSpace(token[6])) {
      token += 7;
      material.diffuse_texname = token;
      continue;
    }

    // specular texture
    if ((0 == strncmp(token, "map_Ks", 6)) && isSpace(token[6])) {
      token += 7;
      material.specular_texname = token;
      continue;
    }

    // normal texture
    if ((0 == strncmp(token, "map_Ns", 6)) && isSpace(token[6])) {
      token += 7;
      material.normal_texname = token;
      continue;
    }

    // unknown parameter
    const char* _space = strchr(token, ' ');
    if(!_space) {
      _space = strchr(token, '\t');
    }
    if(_space) {
      int len = _space - token;
      std::string key(token, len);
      std::string value = _space + 1;
      material.unknown_parameter.insert(std::pair<std::string, std::string>(key, value));
    }
  }
  // flush last material.
  material_map.insert(std::pair<std::string, int>(material.name, materials.size()));
  materials.push_back(material);

  return err.str();
}
예제 #15
0
unsigned int ilf::createILF( std::istream &infile, std::ofstream &outfile )
{
    unsigned int total = 0;
    char temp[512];

    // Write form with dummy size
    unsigned int form0Position = outfile.tellp();
    writeFormHeader( outfile, 0, "INLY" );
    // Write form with dummy size
    unsigned int form1Position = outfile.tellp();
    writeFormHeader( outfile, 0, "0000" );

    while( !infile.eof() )
    {
	unsigned int nodeSize = 0;

	infile.getline( temp, 512, ':' );
	if( infile.eof() ) { break; };
	std::string objectFilename;
	infile >> objectFilename;
	std::cout << objectFilename << std::endl;
	nodeSize += static_cast<unsigned int>( objectFilename.size() + 1 );

	infile.getline( temp, 512, ':' );
	std::string objectZone;
	infile >> objectZone;
	std::cout << objectZone << std::endl;
	nodeSize += static_cast<unsigned int>( objectZone.size() + 1 );

	// 'Transform matrix:' line
	infile.getline( temp, 512, ':' );

	std::cout.flags ( std::ios_base::showpoint );
	std::cout << std::dec;
	std::cout.flags( std::ios_base::fixed );
	float x[12];
	for( unsigned int i = 0; i < 12; ++i )
	{
	    std::cout.width( 10 );
	    infile >> x[i];
	    nodeSize += sizeof( float );
	    std::cout << x[i] << " ";
	}
	std::cout << std::endl;

	// Blank line
	infile.getline( temp, 512 );

	total += writeRecordHeader( outfile, "NODE", nodeSize );
	outfile.write( objectFilename.c_str(),
		       static_cast<unsigned int>( objectFilename.size()+1 )
	    );
	outfile.write( objectZone.c_str(),
		       static_cast<unsigned int>( objectZone.size()+1 )
	    );
	outfile.write( (char*)x, sizeof( float ) * 12 );
	total += nodeSize;
    }

    // Rewrite form with proper size.
    outfile.seekp( form1Position, std::ios_base::beg );
    total += writeFormHeader( outfile, total+4, "0000" );

    // Rewrite form with proper size.
    outfile.seekp( form0Position, std::ios_base::beg );
    total += writeFormHeader( outfile, total+4, "INLY" );

    return total;
}
예제 #16
0
BIO_NS_START

bool
SiteData::parse(std::istream & stream, SiteData::vector_t & result)
{
	typedef boost::tokenizer< boost::char_separator<char> > tokenizer;
	unsigned line_count = 0;

	//for each entry
	while (stream)
	{
		SiteData::ptr_t site_data(new SiteData);

		{
			//get the line
			char buf[16384];
			stream.getline(buf, sizeof(buf));
			++line_count;
			string line(buf);

			//tokenize the line
			boost::char_separator<char> sep(",");
			tokenizer tok(line, sep);

			//extract the values
			tokenizer::iterator tok_iter = tok.begin();

			site_data->site.table_id = SITE_DATA;
			if (tok.end() == tok_iter)
			{
				return false;
			}
			site_data->site.entry_idx = atoi(tok_iter->c_str());
			++tok_iter;

			if (tok.end() == tok_iter)
			{
				return false;
			}
			++tok_iter;

			if (tok.end() == tok_iter)
			{
				return false;
			}
			site_data->site_sequence = *tok_iter;
			++tok_iter;
		}

		while (stream)
		{
			SiteDataGene gene;

			//get the next line
			char buf[32768];
			stream.getline(buf, sizeof(buf));
			++line_count;
			string line(buf);

			//tokenize the line
			boost::char_separator<char> sep(",");
			tokenizer tok(line, sep);

			//extract the values
			tokenizer::iterator tok_iter = tok.begin();

			//is it a blank line?
			if (tok_iter == tok.end())
			{
				break;
			}

			gene.ensembl_id = *tok_iter;
			++tok_iter;

			if (tok.end() == tok_iter)
			{
				return false;
			}
			gene.index = atoi(tok_iter->c_str());
			++tok_iter;

			if (tok.end() == tok_iter)
			{
				return false;
			}
			gene.length = atoi(tok_iter->c_str());
			++tok_iter;

			if (tok.end() == tok_iter)
			{
				return false;
			}
			gene.region_name = *tok_iter;
			++tok_iter;

			if (tok.end() == tok_iter)
			{
				return false;
			}
			gene.start = atoi(tok_iter->c_str());
			++tok_iter;

			if (tok.end() == tok_iter)
			{
				return false;
			}
			gene.end = atoi(tok_iter->c_str());
			++tok_iter;

			if (tok.end() != tok_iter)
			{
				gene.sequence = *tok_iter;
				++tok_iter;
			}

			//we should be at the end
			if (tok.end() != tok_iter)
			{
				return false;
			}

			site_data->genes.push_back(gene);
		}

		result.push_back(site_data);
	}

	const bool reached_end = stream.eof();

	return reached_end;
}
예제 #17
0
/**
 * Method parses passed input stream and returns the vector of parsed ACL with corresponding rules.
 *
 * @param inputStream reference to input stream std::istream containing input configuration.
 * @return smart pointer containing the pointer to the vector of ACL with rules.
 */
std::auto_ptr< boost::ptr_vector< AccessControlList > > HpInputParser::parse(std::istream& inputStream)
{
    /* use smart pointer to store address and control allocated memory */
    m_aclsVector = auto_ptr< boost::ptr_vector< AccessControlList > >(new boost::ptr_vector< AccessControlList >);

    char buffer[256];

    /* read whole input till EOF */
    while ( !inputStream.eof() )
    {
        inputStream.getline(buffer, 256);
        unsigned tmp_extracted = 0;

        char* tmp_buffer = buffer;

        /* skip white characters at the beginning */
        if ( isspace(buffer[0]) )
        {
            skipWhiteChars(buffer, tmp_extracted);
            tmp_buffer += tmp_extracted;
        }

        /* find out the type of command in line */
        int cmd = parseCommand(tmp_buffer, tmp_extracted);

        /*************************/
        /* command "access-list" */
        if ( cmd == CMD_ACCESS_LIST )
        {
            tmp_buffer += tmp_extracted;        /* shift after "access-list " to first character after it */

            skipWhiteChars(tmp_buffer, tmp_extracted);
            tmp_buffer += tmp_extracted;

            int aclNum = parseAccessListNumber(tmp_buffer, tmp_extracted);
            tmp_buffer += tmp_extracted;        /* shift after the number of ACL to the first next character */

            skipWhiteChars(tmp_buffer, tmp_extracted);
            tmp_buffer += tmp_extracted;

            /* skip REMARK command */
            if ( parseAction(tmp_buffer, tmp_extracted) == CMD_ACL_RULE_REMARK )
            {
                continue;
            }

            /* get ACL to add new rule */
            AccessControlList* tmp_curentAcl = getAclByName(aclNum);

            /* parse and add rule to ACL (but ONLY IPv4) */
            if ( resolveAccessListType(aclNum) != ERROR_FLAG )
            {
                tmp_curentAcl->pushBack(handleAccessList(aclNum, tmp_curentAcl->size(), tmp_buffer).release());
            }
        }
        /****************************/
        /* command "ip access-list" */
        else if ( cmd == CMD_IP_ACCESS_LIST )
        {
            tmp_buffer += tmp_extracted;        /* shift after "ip access-list " to first next character */

            int aclType = resolveAccessListType(tmp_buffer, tmp_extracted);
            if ( aclType == ERROR_FLAG )
            {
                continue;
            }

            tmp_buffer += tmp_extracted;        /* shift after "typ acl" to first next character */
            /* get ACL to add new rule */
            AccessControlList* tmp_curentAcl = getAclByName(parseAccessListName(tmp_buffer));

            /* reading rules of named ACL */
            while ( !inputStream.eof() )
            {
                inputStream.getline(buffer, 256);
                tmp_buffer = buffer;

                /* get the type of rule in line */
                if ( isspace(buffer[0]) )
                {
                    skipWhiteChars(buffer, tmp_extracted);
                    tmp_buffer += tmp_extracted;
                }

                /* if there is sequence number before the command -> skip */
                int tmp = 0;
                while ( isdigit(tmp_buffer[tmp]) )
                {
                    tmp++;
                }
                if ( tmp != 0 )
                {
                    tmp_buffer += tmp;
                    skipWhiteChars(tmp_buffer, tmp_extracted);
                    tmp_buffer += tmp_extracted;
                }

                /* find out the type of the rule in line */
                int cmd = parseCommand(tmp_buffer, tmp_extracted);

                /* if the rule is REMARK -> continue to the next */
                if ( cmd == CMD_ACL_RULE_REMARK )
                {
                    continue;
                }
                /* if there was EXIT command */
                else if ( cmd == CMD_EXIT )
                {
                    break;
                }
                /* if it is not the rule of named ACL, return read line and break the cycle! */
                else if ( cmd != CMD_IP_ACCESS_LIST_RULE )
                {
                    rollbackStream(inputStream, inputStream.gcount());
                    break;
                }

                /* the rule of the standard ACL */
                if ( aclType == ACL_STANDARD )
                {
                    tmp_curentAcl->pushBack(handleStandardRule(tmp_curentAcl->size(), tmp_buffer).release());
                }
                /* the rule of the extended ACL */
                else
                {
                    tmp_curentAcl->pushBack(handleExtendedRule(tmp_curentAcl->size(), tmp_buffer).release());
                }
            }
        }
        else
        {
            continue;
        }
    }

    /* clear the map */
    m_aclsByName.clear();

    return m_aclsVector;
}
예제 #18
0
// virtual
BOOL LLInventoryItem::importLegacyStream(std::istream& input_stream)
{
	// *NOTE: Changing the buffer size will require changing the scanf
	// calls below.
	char buffer[MAX_STRING];	/* Flawfinder: ignore */
	char keyword[MAX_STRING];	/* Flawfinder: ignore */
	char valuestr[MAX_STRING];	/* Flawfinder: ignore */
	char junk[MAX_STRING];	/* Flawfinder: ignore */
	BOOL success = TRUE;

	keyword[0] = '\0';
	valuestr[0] = '\0';

	mInventoryType = LLInventoryType::IT_NONE;
	mAssetUUID.setNull();
	while(success && input_stream.good())
	{
		input_stream.getline(buffer, MAX_STRING);
		sscanf(	/* Flawfinder: ignore */
			buffer,
			" %254s %254s",
			keyword, valuestr);
		if(0 == strcmp("{",keyword))
		{
			continue;
		}
		if(0 == strcmp("}", keyword))
		{
			break;
		}
		else if(0 == strcmp("item_id", keyword))
		{
			mUUID.set(valuestr);
		}
		else if(0 == strcmp("parent_id", keyword))
		{
			mParentUUID.set(valuestr);
		}
		else if(0 == strcmp("permissions", keyword))
		{
			success = mPermissions.importLegacyStream(input_stream);
		}
		else if(0 == strcmp("sale_info", keyword))
		{
			// Sale info used to contain next owner perm. It is now in
			// the permissions. Thus, we read that out, and fix legacy
			// objects. It's possible this op would fail, but it
			// should pick up the vast majority of the tasks.
			BOOL has_perm_mask = FALSE;
			U32 perm_mask = 0;
			success = mSaleInfo.importLegacyStream(input_stream, has_perm_mask, perm_mask);
			if(has_perm_mask)
			{
				if(perm_mask == PERM_NONE)
				{
					perm_mask = mPermissions.getMaskOwner();
				}
				// fair use fix.
				if(!(perm_mask & PERM_COPY))
				{
					perm_mask |= PERM_TRANSFER;
				}
				mPermissions.setMaskNext(perm_mask);
			}
		}
		else if(0 == strcmp("shadow_id", keyword))
		{
			mAssetUUID.set(valuestr);
			LLXORCipher cipher(MAGIC_ID.mData, UUID_BYTES);
			cipher.decrypt(mAssetUUID.mData, UUID_BYTES);
		}
		else if(0 == strcmp("asset_id", keyword))
		{
			mAssetUUID.set(valuestr);
		}
		else if(0 == strcmp("type", keyword))
		{
			mType = LLAssetType::lookup(valuestr);
		}
		else if(0 == strcmp("inv_type", keyword))
		{
			mInventoryType = LLInventoryType::lookup(std::string(valuestr));
		}
		else if(0 == strcmp("flags", keyword))
		{
			sscanf(valuestr, "%x", &mFlags);
		}
		else if(0 == strcmp("name", keyword))
		{
			//strcpy(valuestr, buffer + strlen(keyword) + 3);
			// *NOTE: Not ANSI C, but widely supported.
			sscanf(	/* Flawfinder: ignore */
				buffer,
				" %254s%254[\t]%254[^|]",
				keyword, junk, valuestr);

			// IW: sscanf chokes and puts | in valuestr if there's no name
			if (valuestr[0] == '|')
			{
				valuestr[0] = '\000';
			}

			mName.assign(valuestr);
			LLStringUtil::replaceNonstandardASCII(mName, ' ');
			LLStringUtil::replaceChar(mName, '|', ' ');
		}
		else if(0 == strcmp("desc", keyword))
		{
			//strcpy(valuestr, buffer + strlen(keyword) + 3);
			// *NOTE: Not ANSI C, but widely supported.
			sscanf(	/* Flawfinder: ignore */
				buffer,
				" %254s%254[\t]%254[^|]",
				keyword, junk, valuestr);

			if (valuestr[0] == '|')
			{
				valuestr[0] = '\000';
			}

			mDescription.assign(valuestr);
			LLStringUtil::replaceNonstandardASCII(mDescription, ' ');
			/* TODO -- ask Ian about this code
			const char *donkey = mDescription.c_str();
			if (donkey[0] == '|')
			{
				llerrs << "Donkey" << llendl;
			}
			*/
		}
		else if(0 == strcmp("creation_date", keyword))
		{
			S32 date;
			sscanf(valuestr, "%d", &date);
			mCreationDate = date;
		}
		else
		{
			llwarns << "unknown keyword '" << keyword
					<< "' in inventory import of item " << mUUID << llendl;
		}
	}

	// Need to convert 1.0 simstate files to a useful inventory type
	// and potentially deal with bad inventory tyes eg, a landmark
	// marked as a texture.
	if((LLInventoryType::IT_NONE == mInventoryType)
	   || !inventory_and_asset_types_match(mInventoryType, mType))
	{
		lldebugs << "Resetting inventory type for " << mUUID << llendl;
		mInventoryType = LLInventoryType::defaultForAssetType(mType);
	}
	return success;
}
S32 LLSDXMLParser::Impl::parseLines(std::istream& input, LLSD& data)
{
	XML_Status status = XML_STATUS_OK;

	data = LLSD();

	static const int BUFFER_SIZE = 1024;

	//static char last_buffer[ BUFFER_SIZE ];
	//std::streamsize last_num_read;

	// Must get rid of any leading \n, otherwise the stream gets into an error/eof state
	clear_eol(input);

	while( !mGracefullStop
		&& input.good() 
		&& !input.eof())
	{
		void* buffer = XML_GetBuffer(mParser, BUFFER_SIZE);
		/*
		 * If we happened to end our last buffer right at the end of the llsd, but the
		 * stream is still going we will get a null buffer here.  Check for mGracefullStop.
		 * -- I don't think this is actually true - zero 2008-05-09
		 */
		if (!buffer)
		{
			break;
		}
		
		// Get one line
		input.getline((char*)buffer, BUFFER_SIZE);
		std::streamsize num_read = input.gcount();

		//memcpy( last_buffer, buffer, num_read );
		//last_num_read = num_read;

		if ( num_read > 0 )
		{
			if (!input.good() )
			{	// Clear state that's set when we run out of buffer
				input.clear();
			}
		
			// Re-insert with the \n that was absorbed by getline()
			char * text = (char *) buffer;
			if ( text[num_read - 1] == 0)
			{
				text[num_read - 1] = '\n';
			}
		}

		status = XML_ParseBuffer(mParser, (int)num_read, false);
		if (status == XML_STATUS_ERROR)
		{
			break;
		}
	}

	if (status != XML_STATUS_ERROR
		&& !mGracefullStop)
	{	// Parse last bit
		status = XML_ParseBuffer(mParser, 0, true);
	}
	
	if (status == XML_STATUS_ERROR  
		&& !mGracefullStop)
	{
		if (mEmitErrors)
		{
			LL_INFOS() << "LLSDXMLParser::Impl::parseLines: XML_STATUS_ERROR" << LL_ENDL;
		}
		return LLSDParser::PARSE_FAILURE;
	}

	clear_eol(input);
	data = mResult;
	return mParseCount;
}
예제 #20
0
/**
 * Considerably more efficient than std::getline.
 */
bool getline(std::istream& stream, std::string &buffer)
{
  stream.getline(staticBuffer, sizeof(staticBuffer));
  buffer = staticBuffer;
  return stream.good();
}
예제 #21
0
파일: FileList.cpp 프로젝트: corburn/ISIS
  /**
   * Loads list of files from a stream.
   * This takes in a stream and loads a file list from it. The lines in the stream
   * are considered separate entries, and comments are ignored. comments are
   * considered to be any line starting with a '#' or '//', and anything after any
   * whitespace following the first text on the line.
   *
   * @param in An input stream containing a list of files.
   *
   */
  void FileList::read(std::istream &in) {
    // Read each file and put it in the vector
    char buf[65536];
    Isis::IString s;
    bool bHasQuotes = false;

    in.getline(buf, 65536);
    bool isComment = false;
    while (!in.eof()) {
      s = buf;
      string::size_type loc = s.find("\"", 0);

      if (loc != string::npos) {
        bHasQuotes = true;
      }

      if (bHasQuotes) {
        s = s.TrimHead("\"");
        s = s.TrimTail("\"");
      }

      s = s.TrimHead(" \n\r\t\v");

      isComment = false;
      if(strlen(buf) == 0) {
        in.getline(buf, 65536);
        continue;
      }
      for (int index = 0; index < (int)strlen(buf); index++) {
        if (buf[index] == '#' || (buf[index] == '/' && buf[index+1] == '/')) {
          isComment = true;
          break;
        }
        else if(buf[index] == ' ') {
          continue;
        }
        else {
          isComment = false;
          break;
        }
      }
      if (isComment) {
        in.getline(buf, 65536);
        continue;
      }
      else {

        if(bHasQuotes) {
          s = s.Token(" \n\r\t\v");
        }
        else {
          s = s.Token(" \n\r\t\v,");
        }

        this->push_back(s.ToQt());
        in.getline(buf, 65536);
      }
    }
    if (this->size() == 0) {
      string msg = "Input Stream Empty";
      throw IException(IException::User, msg, _FILEINFO_);
    }
  }
예제 #22
0
  void BehaviorModel::load(std::istream& is)
  {
    /* uid model factory prop1 = jsonVal1 prop2 = jsonval2
    *  uid a.b -> c.d [filterExp]
    *
    */
    char line[1024];
    while (is.good())
    {
      line[0] = 0;
      is.getline(line, 1024);
      std::string s(line);
      boost::trim(s);
      if (s.empty() || s[0] == '#')
        continue;
      std::stringstream st(s);
      std::string uid, p1, p2;
      bool isTransition = false;
      st >> uid >> p1 >> p2;
      if (p2.empty())
        continue;
      if (p2 == "->")
      {
        isTransition = true;
        st >> p2;
      }
      if (!isTransition)
      {
        BehaviorModel::Node& state = nodes[uid];
        state.uid = uid;
        state.interface = p1;
        state.factory = p2;

        std::string parameters;
        std::getline(st,parameters);
        size_t p = 0;
        std::string::const_iterator begin = parameters.begin();
        while (p <= parameters.size())
        {
          size_t eq = parameters.find_first_of('=', p);
          if (eq == parameters.npos)
          { // check for remaining data
            std::string remain = parameters.substr(p);
            boost::trim(remain);
            if (!remain.empty())
              throw std::runtime_error("Trailing data: " + remain);
            break;
          }
          std::string name = parameters.substr(p, eq-p);
          boost::algorithm::trim(name);
          qi::AnyValue gValue;
          size_t end = decodeJSON(begin + eq + 1, begin + parameters.size(), gValue) - begin;
          state.parameters[name] = gValue;
          p = end;
        }
      }
      else
      {
        BehaviorModel::Transition transition;
        std::string parameters;
        std::getline(st,parameters);
        boost::trim(parameters);
        if (!parameters.empty())
          transition.filter = decodeJSON(parameters);
        transition.uid = uid;
        transition.src = splitString2(p1, '.');
        transition.dst = splitString2(p2, '.');
        transitions[transition.uid] = transition;
      }
    }
예제 #23
0
bool ConfigArray::load(std::istream &sin, string &s)
{
    s.erase();
    for (;;){
        if (sin.eof() || sin.fail()){
            s = "";
            return true;
        }
        char buf[1024];
        sin.getline(buf, sizeof(buf));
        string line(buf);
        for (;line[0] == '[';){
            string name = line.c_str() + 1;
            char *p = strchr((char*)(name.c_str()), ']');
            if (p){
                *p = 0;
                list<ConfigValue*>::iterator it;
                for (it = values.begin(); it != values.end(); it++){
                    if (!(*it)->isList) continue;
                    if (strcmp(name.c_str(), (*it)->m_name.c_str())) continue;
                    ConfigList *list = static_cast<ConfigList*>(*it);
                    list->load(sin, line);
                    break;
                }
                if (it != values.end()){
                    if (line == "[]"){
                        if (sin.eof() || sin.fail()){
                            s = "";
                            return true;
                        }
                        sin.getline(buf, sizeof(buf));
                        line = buf;
                    }
                    continue;
                }
            }
            s = line;
            return true;
        }
        if (line.size() == 0) continue;
        char *p = strchr(line.c_str(), '=');
        if (p == NULL){
            log(L_WARN, "Bad string in config %s", line.c_str());
            continue;
        }
        *p = 0;
        p++;
        list<ConfigValue*>::iterator it;
        for (it = values.begin(); it != values.end(); it++){
            if (strcmp(line.c_str(), (*it)->m_name.c_str())) continue;
            string unquoted;
            for (; *p; p++){
                if (*p != '\\'){
                    unquoted += *p;
                    continue;
                }
                p++;
                if (*p == 0) break;
                switch (*p){
                case '\\':
                    unquoted += '\\';
                    break;
                case 'n':
                    unquoted += '\n';
                    break;
                case 't':
                    unquoted += '\t';
                    break;
                case 'x':
                    if (p[1] && p[2]){
                        char c = 0;
                        c = (fromHex(p[1]) << 4) + fromHex(p[2]);
                        unquoted += c;
                        p += 2;
                    }
                    break;
                default:
                    p--;
                }
            }
            (*it)->load(unquoted);
            break;
        }
        if (it == values.end())
            log(L_WARN, "Bad key %s in config", line.c_str());
    }
    return true;
}
예제 #24
0
static std::string ReadZStr(std::istream& file)
{
	char cstr[1024];
	file.getline(cstr, sizeof(cstr), 0);
	return std::string(cstr);
}
BOOL LLPermissions::importStream(std::istream& input_stream)
{
	init(LLUUID::null, LLUUID::null, LLUUID::null, LLUUID::null);
	const S32 BUFSIZE = 16384;

	// *NOTE: Changing the buffer size will require changing the scanf
	// calls below.
	char buffer[BUFSIZE];	/* Flawfinder: ignore */
	char keyword[256];	/* Flawfinder: ignore */
	char valuestr[256];	/* Flawfinder: ignore */
	char uuid_str[256];	/* Flawfinder: ignore */
	U32 mask;

	keyword[0]  = '\0';
	valuestr[0] = '\0';

	while (input_stream.good())
	{
		input_stream.getline(buffer, BUFSIZE);
		if (input_stream.eof())
		{
			llwarns << "Bad permissions: early end of input stream"
					<< llendl;
			return FALSE;
		}
		if (input_stream.fail())
		{
			llwarns << "Bad permissions: failed to read from input stream"
					<< llendl;
			return FALSE;
		}
		sscanf( /* Flawfinder: ignore */
			buffer,
			" %255s %255s",
			keyword, valuestr);
		if (!strcmp("{", keyword))
		{
			continue;
		}
		if (!strcmp("}",keyword))
		{
			break;
		}
		else if (!strcmp("creator_mask", keyword))
		{
			// legacy support for "creator" masks
			sscanf(valuestr, "%x", &mask);
			mMaskBase = mask;
			fixFairUse();
		}
		else if (!strcmp("base_mask", keyword))
		{
			sscanf(valuestr, "%x", &mask);
			mMaskBase = mask;
			//fixFairUse();
		}
		else if (!strcmp("owner_mask", keyword))
		{
			sscanf(valuestr, "%x", &mask);
			mMaskOwner = mask;
		}
		else if (!strcmp("group_mask", keyword))
		{
			sscanf(valuestr, "%x", &mask);
			mMaskGroup = mask;
		}
		else if (!strcmp("everyone_mask", keyword))
		{
			sscanf(valuestr, "%x", &mask);
			mMaskEveryone = mask;
		}
		else if (!strcmp("next_owner_mask", keyword))
		{
			sscanf(valuestr, "%x", &mask);
			mMaskNextOwner = mask;
		}
		else if (!strcmp("creator_id", keyword))
		{
			sscanf(valuestr, "%255s", uuid_str);	/* Flawfinder: ignore */
			mCreator.set(uuid_str);
		}
		else if (!strcmp("owner_id", keyword))
		{
			sscanf(valuestr, "%255s", uuid_str);	/* Flawfinder: ignore */
			mOwner.set(uuid_str);
		}
		else if (!strcmp("last_owner_id", keyword))
		{
			sscanf(valuestr, "%255s", uuid_str);	/* Flawfinder: ignore */
			mLastOwner.set(uuid_str);
		}
		else if (!strcmp("group_id", keyword))
		{
			sscanf(valuestr, "%255s", uuid_str);	/* Flawfinder: ignore */
			mGroup.set(uuid_str);
		}
		else if (!strcmp("group_owned", keyword))
		{
			sscanf(valuestr, "%d", &mask);
			if(mask) mIsGroupOwned = true;
			else mIsGroupOwned = false;
		}
		else
		{
			llwarns << "unknown keyword " << keyword 
					<< " in permissions import" << llendl;
		}
	}
	fix();
	return TRUE;
}
예제 #26
0
bool PolyModel::loadModel(std::istream& istr, bool reverse)
{
	int vertex_count;
	int face_count;
	string data;

	if (!istr.good())
		return false;

	char line[1024];
	istr.getline(line, 1024);

	std::istringstream sstr(line);
	sstr >> data >> vertex_count >> face_count;

	//store readbuffer
	std::streambuf* backup;
	backup = sstr.rdbuf();
	//get position
	sstr.seekg(0, sstr.cur);
	int cur = sstr.tellg();

	std::string attrib_type;
	bool has_texcoords = false;
	while (!sstr.eof() && sstr.good()) {
		sstr >> attrib_type;
		if (attrib_type == "tex-coords1")
			has_texcoords = true;
	}
	sstr.seekg(cur-1, sstr.beg);
	string test;
	sstr >> test;
	
	m_verts.resize(vertex_count);
	m_polys.resize(face_count);

	m_center = 0.0f;
	m_max_bounding = -numeric_limits<float>::max();
	m_min_bounding = numeric_limits<float>::max();
    
    // Read in all the points
	//sstr << backup;
	
	float x, y, z;
	for (int i=0; i < vertex_count;i++){
		char new_line[1024];
		istr.getline(new_line, 1024);
		std::istringstream new_sstr(new_line);
		new_sstr >> x >> y >> z;
		m_verts[i] = Vec3f(x, y, z);
	}
    // Read in all the polygons (triangles)
	int vertex_p_poly;
	for (int i=0; i < face_count; i++){
		char new_line[1024];
		istr.getline(new_line, 1024);
		std::istringstream new_sstr(new_line);
		new_sstr >> vertex_p_poly;
		vector<int> vTemp(vertex_p_poly);
		for (int j=0; j < vertex_p_poly; j++){
			new_sstr >> vTemp[j];
		}
		m_polys[i]=vTemp;
	}
	// Read in all texture coordinates
	if (has_texcoords){
		int Num_cord;
		while (!istr.eof() && istr.good()){
			char new_line[1024];
			istr.getline(new_line, 1024);
			std::istringstream new_sstr(new_line);
			new_sstr >> Num_cord;
			vector<float> fTemp(Num_cord);
			for (int j = 0; j < Num_cord; j++){
				new_sstr >> fTemp[j];
			}
			m_tex_cord.insert(m_tex_cord.end(), fTemp);
		}
	}
	//compute 
	computeFaceNormals();
	computeVertexNormals();

	//set rotation to identity
	//SetRotationIndentity();
	//SetTransformIndentity();
	//TranslateMatrix = Mat4f(
	//	1.0f, 0.0f, 0.0f, 0.0f,
	//	0.0f, 1.0f, 0.0f, 0.0f,
	//	0.0f, 0.0f, 1.0f, 0.0f,
	//	0.0f, 0.0f, 0.0f, 1.0f
	//	);
	
	return true;
}
예제 #27
0
// virtual
BOOL LLInventoryCategory::importLegacyStream(std::istream& input_stream)
{
	// *NOTE: Changing the buffer size will require changing the scanf
	// calls below.
	char buffer[MAX_STRING];	/* Flawfinder: ignore */
	char keyword[MAX_STRING];	/* Flawfinder: ignore */
	char valuestr[MAX_STRING];	/* Flawfinder: ignore */

	keyword[0] = '\0';
	valuestr[0] = '\0';
	while(input_stream.good())
	{
		input_stream.getline(buffer, MAX_STRING);
		sscanf(	/* Flawfinder: ignore */
			buffer,
			" %254s %254s",
			keyword, valuestr);
		if(0 == strcmp("{",keyword))
		{
			continue;
		}
		if(0 == strcmp("}", keyword))
		{
			break;
		}
		else if(0 == strcmp("cat_id", keyword))
		{
			mUUID.set(valuestr);
		}
		else if(0 == strcmp("parent_id", keyword))
		{
			mParentUUID.set(valuestr);
		}
		else if(0 == strcmp("type", keyword))
		{
			mType = LLAssetType::lookup(valuestr);
		}
		else if(0 == strcmp("pref_type", keyword))
		{
			mPreferredType = LLAssetType::lookup(valuestr);
		}
		else if(0 == strcmp("name", keyword))
		{
			//strcpy(valuestr, buffer + strlen(keyword) + 3);
			// *NOTE: Not ANSI C, but widely supported.
			sscanf(	/* Flawfinder: ignore */
				buffer,
				" %254s %254[^|]",
				keyword, valuestr);
			mName.assign(valuestr);
			LLStringUtil::replaceNonstandardASCII(mName, ' ');
			LLStringUtil::replaceChar(mName, '|', ' ');
		}
		else
		{
			llwarns << "unknown keyword '" << keyword
					<< "' in inventory import category "  << mUUID << llendl;
		}
	}
	return TRUE;
}
bool PlanParser::parsePlan(std::istream & is, Plan & plan_)
{
    vector<DurativeAction> & plan = plan_.actions;

    bool ret = true;
    plan.clear();

    // what is failure vs. empty is
    if(!is.good())
        return false;

    char buf[4096];
    memset(buf, 0, 4096);
    while(!is.eof()) {
        is.getline(buf, 4095);
        //printf("%s\n", buf);
        if(strlen(buf) == 0)    //skip empty line
            continue;

        DurativeAction action;

        QString line = buf;
        if(line.startsWith(";"))    // comment line
            continue;

        // should read like:
        // 7.00070000: (explore robot7 t15 t16) [1.00000000]
        QStringList sl1 = line.trimmed().split(":");
        if(sl1.size() != 2) {
            ROS_WARN("unparsable plan line: \"%s\"", buf);
            ret = false;
            continue;
        }
        bool ok;
        action.startTime = -1;
        action.startTime = sl1[0].toDouble(&ok);
        if(!ok) {
            ROS_WARN("unparsable plan line: \"%s\"", buf);
            ret = false;
            continue;
        }

        QString rest = sl1[1].trimmed();
        // (explore robot7 t15 t16) [1.00000000]
        QRegExp re("\\((.*)\\) *\\[(.*)\\]");
        if(rest.indexOf(re) < 0) {
            ROS_WARN("unparsable plan line: \"%s\"", buf);
            ret = false;
            continue;
        }
        if(re.captureCount() != 2) {
            ROS_WARN("unparsable plan line: \"%s\"", buf);
            ret = false;
            continue;
        }
        QString actionDesc = re.cap(1);
        QString durationDesc = re.cap(2);
        action.duration = -1;
        action.duration = durationDesc.toDouble(&ok);
        if(!ok) {
            ROS_WARN("unparsable plan line: \"%s\"", buf);
            ret = false;
            continue;
        }

        QStringList actionS = actionDesc.split(" ", QString::SkipEmptyParts);
        if(actionS.size() < 1) {
            ROS_WARN("unparsable plan line: \"%s\"", buf);
            ret = false;
            continue;
        }

        action.name = qPrintable(actionS[0]);
        for(int i = 1; i < actionS.size(); i++) {
            action.parameters.push_back(qPrintable(actionS[i]));
        }
        plan.push_back(action);
    }

    return ret;
}
예제 #29
0
파일: dockResult.C 프로젝트: HeyJJ/ball
		// read dock result from file
		bool DockResult::readDockResult(std::istream& file)
			throw()
		{
			// read first two lines with line numbers of INIFile and PDBFile
			Size INI_lines, PDB_lines;
			file >> INI_lines;
			file >> PDB_lines;
			// first: read INI part from result file in INIFile
			INIFile INI_in;
			char buffer[2000];
			for (Position p = 0; p <= INI_lines; p++)
			{
				if (!file.getline(&(buffer[0]), 2000))
				{
					Log.error() << "Error while reading Dock Result file, could not read INI part! " << __FILE__ << " " << __LINE__ << std::endl;
					return false;
				}

				if (!INI_in.appendLine(buffer))
				{
					Log.error() << "Error while reading Dock Result file, could not read INI part! "  << __FILE__ << " " << __LINE__<< std::endl;
					return false;
				}
			}
			// read INIFile, fill DockResult
			// read algorithm name
			if (!INI_in.hasEntry("ALGORITHM", "name")) return false;
			docking_algorithm_ = INI_in.getValue("ALGORITHM", "name");
			// read algorithm options
			if (!INI_in.hasSection("ALGORITHM_OPTIONS")) return false;
			INIFile::LineIterator it = INI_in.getSectionFirstLine("ALGORITHM_OPTIONS");
			it.getSectionNextLine();
			for (; +it; it.getSectionNextLine())
			{
				String line(*it);
				docking_options_.set(line.before("="), line.after("="));
			}

			// there can be several stored scorings
			// assumption: there are not more than 9999999!!!
			for (Position p = 0; p < 9999999; p++)
			{
				// read scoring name
				if (!INI_in.hasEntry("SCORING_NAME_" + String(p), "name")) break;
        String name = INI_in.getValue("SCORING_NAME_" + String(p), "name");
				// read scoring options
        Options options;
				it = INI_in.getSectionFirstLine("SCORING_OPTIONS_" + String(p));
				it.getSectionNextLine();
				for (; +it; it.getSectionNextLine())
				{
					String line(*it);
					options.set(line.before("="), line.after("="));
				}
				// read scores
				vector<float> scores;
				it = INI_in.getSectionFirstLine("SCORES_" + String(p));
				it.getSectionNextLine();
				for (; +it; it.getSectionNextLine())
				{
					String line(*it);
					try
						{
							scores.push_back(((line.after("=")).toString()).toFloat());
						}
					catch (Exception::InvalidFormat)
						{
							Log.error() << "Conversion from String to float failed: invalid format! " << __FILE__ << " " << __LINE__ << std::endl;
							return false;
						}
				}
				// read snapshot order
				vector<Index> snapshot_order;
				it = INI_in.getSectionFirstLine("SNAPSHOT_ORDER_" + String(p));
				it.getSectionNextLine();
				for (; +it; it.getSectionNextLine())
				{
					String line(*it);
					try
						{
							snapshot_order.push_back(((line.after("=")).toString()).toInt());
						}
					catch (Exception::InvalidFormat)
						{
							Log.error() << "Conversion from String to int failed: invalid format! " << __FILE__ << " " << __LINE__ << std::endl;
							return false;
						}
				}
				// add new Scoring_ to vector scorings_
				scorings_.push_back(Scoring_(name, options, scores, snapshot_order));
			}

			// second: read PDB part from result file in a temporary PDBFile
			String PDB_temp;
			File::createTemporaryFilename(PDB_temp);
			PDBFile PDB_in(PDB_temp, std::ios::out);
			for (Position p = 0; p < PDB_lines; p++)
			{
				if (!file.getline(&(buffer[0]), 2000))
				{
					Log.error() << "Error while reading Dock Result file, could not read PDB part! " << __FILE__ << " " << __LINE__ << std::endl;
					return false;
				}
				PDB_in << buffer << std::endl;
			}

			// read PDBFile, fill system
			PDB_in.reopen(std::ios::in);
			System s;
			PDB_in >> s;
			// create new ConformationSet and set the docked system
			if (conformation_set_)
			{
				delete conformation_set_;
			}
			conformation_set_ = new ConformationSet(s);
			// set scoring of ConformationSet
			vector < ConformationSet::Conformation > conformations;
			ConformationSet::Conformation conf;
			vector<float> last_scores = scorings_[scorings_.size()-1].scores_;
			for (Position i = 0; i < last_scores.size(); i++)
			{
				conf.first = i;
				conf.second = last_scores[i];
				conformations.push_back(conf);
			}
			conformation_set_->setScoring(conformations);

			// third: read DCD part from result file in temporary DCDFile
			String DCD_temp;
			File::createTemporaryFilename(DCD_temp);
			std::ofstream DCD_in(DCD_temp.c_str(), std::ios::out | std::ios::binary);
			char c;
			while (file.good())
			{
				file.get(c);
				DCD_in << c;
			}
			DCD_in.close();
			// read the snapshots from DCDFile
			if (!conformation_set_->readDCDFile(DCD_temp))
			{
				Log.error() << "Error while reading Dock Result file, could not read DCD part! " << __FILE__ << " " << __LINE__ << std::endl;
				return false;
			};

			// remove temporary files
			File::remove(PDB_temp);
			File::remove(DCD_temp);

			return true;
		}
예제 #30
0
// virtual
LLWearable::EImportResult LLWearable::importStream( std::istream& input_stream, LLAvatarAppearance* avatarp )
{
	// *NOTE: changing the type or size of this buffer will require
	// changes in the fscanf() code below.
	// We are using a local max buffer size here to avoid issues
	// if MAX_STRING size changes.
	const U32 PARSE_BUFFER_SIZE = 2048;
	char buffer[PARSE_BUFFER_SIZE];		/* Flawfinder: ignore */
	char uuid_buffer[37];	/* Flawfinder: ignore */

	// This data is being generated on the viewer.
	// Impose some sane limits on parameter and texture counts.
	const S32 MAX_WEARABLE_ASSET_TEXTURES = 100;
	const S32 MAX_WEARABLE_ASSET_PARAMETERS = 1000;

	if(!avatarp)
	{
		return LLWearable::FAILURE;
	}

	// read header and version 
	if (!getNextPopulatedLine(input_stream, buffer, PARSE_BUFFER_SIZE))
	{
		LL_WARNS() << "Failed to read wearable asset input stream." << LL_ENDL;
		return LLWearable::FAILURE;
	}
	if ( 1 != sscanf( /* Flawfinder: ignore */
				buffer,
				"LLWearable version %d\n",
				&mDefinitionVersion ) )
	{
		return LLWearable::BAD_HEADER;
	}

	// Hack to allow wearables with definition version 24 to still load.
	// This should only affect lindens and NDA'd testers who have saved wearables in 2.0
	// the extra check for version == 24 can be removed before release, once internal testers
	// have loaded these wearables again. See hack pt 2 at bottom of function to ensure that
	// these wearables get re-saved with version definition 22.
	if( mDefinitionVersion > LLWearable::sCurrentDefinitionVersion && mDefinitionVersion != 24 )
	{
		LL_WARNS() << "Wearable asset has newer version (" << mDefinitionVersion << ") than XML (" << LLWearable::sCurrentDefinitionVersion << ")" << LL_ENDL;
		return LLWearable::FAILURE;
	}

	// name may be empty
    if (!input_stream.good())
	{
		LL_WARNS() << "Bad Wearable asset: early end of input stream " 
				<< "while reading name" << LL_ENDL;
		return LLWearable::FAILURE;
	}
	input_stream.getline(buffer, PARSE_BUFFER_SIZE);
	mName = buffer;

	// description may be empty
	if (!input_stream.good())
	{
		LL_WARNS() << "Bad Wearable asset: early end of input stream " 
				<< "while reading description" << LL_ENDL;
		return LLWearable::FAILURE;
	}
	input_stream.getline(buffer, PARSE_BUFFER_SIZE);
	mDescription = buffer;

	// permissions may have extra empty lines before the correct line
	if (!getNextPopulatedLine(input_stream, buffer, PARSE_BUFFER_SIZE))
	{
		LL_WARNS() << "Bad Wearable asset: early end of input stream " 
				<< "while reading permissions" << LL_ENDL;
		return LLWearable::FAILURE;
	}
	S32 perm_version = -1;
	if ( 1 != sscanf( buffer, " permissions %d\n", &perm_version ) ||
		 perm_version != 0 )
	{
		LL_WARNS() << "Bad Wearable asset: missing valid permissions" << LL_ENDL;
		return LLWearable::FAILURE;
	}
	if( !mPermissions.importStream( input_stream ) )
	{
		return LLWearable::FAILURE;
	}

	// sale info
	if (!getNextPopulatedLine(input_stream, buffer, PARSE_BUFFER_SIZE))
	{
		LL_WARNS() << "Bad Wearable asset: early end of input stream " 
				<< "while reading sale info" << LL_ENDL;
		return LLWearable::FAILURE;
	}
	S32 sale_info_version = -1;
	if ( 1 != sscanf( buffer, " sale_info %d\n", &sale_info_version ) ||
		sale_info_version != 0 )
	{
		LL_WARNS() << "Bad Wearable asset: missing valid sale_info" << LL_ENDL;
		return LLWearable::FAILURE;
	}
	// Sale info used to contain next owner perm. It is now in the
	// permissions. Thus, we read that out, and fix legacy
	// objects. It's possible this op would fail, but it should pick
	// up the vast majority of the tasks.
	BOOL has_perm_mask = FALSE;
	U32 perm_mask = 0;
	if( !mSaleInfo.importStream(input_stream, has_perm_mask, perm_mask) )
	{
		return LLWearable::FAILURE;
	}
	if(has_perm_mask)
	{
		// fair use fix.
		if(!(perm_mask & PERM_COPY))
		{
			perm_mask |= PERM_TRANSFER;
		}
		mPermissions.setMaskNext(perm_mask);
	}

	// wearable type
	if (!getNextPopulatedLine(input_stream, buffer, PARSE_BUFFER_SIZE))
	{
		LL_WARNS() << "Bad Wearable asset: early end of input stream " 
				<< "while reading type" << LL_ENDL;
		return LLWearable::FAILURE;
	}
	S32 type = -1;
	if ( 1 != sscanf( buffer, "type %d\n", &type ) )
	{
		LL_WARNS() << "Bad Wearable asset: bad type" << LL_ENDL;
		return LLWearable::FAILURE;
	}
	if( 0 <= type && type < LLWearableType::WT_COUNT )
	{
		setType((LLWearableType::EType)type, avatarp);
	}
	else
	{
		mType = LLWearableType::WT_COUNT;
		LL_WARNS() << "Bad Wearable asset: bad type #" << type <<  LL_ENDL;
		return LLWearable::FAILURE;
	}

	// parameters header
	if (!getNextPopulatedLine(input_stream, buffer, PARSE_BUFFER_SIZE))
	{
		LL_WARNS() << "Bad Wearable asset: early end of input stream " 
				<< "while reading parameters header" << LL_ENDL;
		return LLWearable::FAILURE;
	}
	S32 num_parameters = -1;
	if ( 1 != sscanf( buffer, "parameters %d\n", &num_parameters ) )
	{
		LL_WARNS() << "Bad Wearable asset: missing parameters block" << LL_ENDL;
		return LLWearable::FAILURE;
	}
	if ( num_parameters > MAX_WEARABLE_ASSET_PARAMETERS )
	{
		LL_WARNS() << "Bad Wearable asset: too many parameters, "
				<< num_parameters << LL_ENDL;
		return LLWearable::FAILURE;
	}
	if( num_parameters != mVisualParamIndexMap.size() )
	{
		LL_WARNS() << "Wearable parameter mismatch. Reading in " 
				<< num_parameters << " from file, but created " 
				<< mVisualParamIndexMap.size() 
				<< " from avatar parameters. type: " 
				<<  getType() << LL_ENDL;
	}

	// parameters
	S32 i;
	for( i = 0; i < num_parameters; i++ )
	{
		if (!getNextPopulatedLine(input_stream, buffer, PARSE_BUFFER_SIZE))
		{
			LL_WARNS() << "Bad Wearable asset: early end of input stream " 
					<< "while reading parameter #" << i << LL_ENDL;
			return LLWearable::FAILURE;
		}
		S32 param_id = 0;
		F32 param_weight = 0.f;
		if ( 2 != sscanf( buffer, "%d %f\n", &param_id, &param_weight ) )
		{
			LL_WARNS() << "Bad Wearable asset: bad parameter, #" << i << LL_ENDL;
			return LLWearable::FAILURE;
		}
		mSavedVisualParamMap[param_id] = param_weight;
	}

	// textures header
	if (!getNextPopulatedLine(input_stream, buffer, PARSE_BUFFER_SIZE))
	{
		LL_WARNS() << "Bad Wearable asset: early end of input stream " 
				<< "while reading textures header" << i << LL_ENDL;
		return LLWearable::FAILURE;
	}
	S32 num_textures = -1;
	if ( 1 != sscanf( buffer, "textures %d\n", &num_textures) )
	{
		LL_WARNS() << "Bad Wearable asset: missing textures block" << LL_ENDL;
		return LLWearable::FAILURE;
	}
	if ( num_textures > MAX_WEARABLE_ASSET_TEXTURES )
	{
		LL_WARNS() << "Bad Wearable asset: too many textures, "
				<< num_textures << LL_ENDL;
		return LLWearable::FAILURE;
	}

	// textures
	for( i = 0; i < num_textures; i++ )
	{
		if (!getNextPopulatedLine(input_stream, buffer, PARSE_BUFFER_SIZE))
		{
			LL_WARNS() << "Bad Wearable asset: early end of input stream " 
					<< "while reading textures #" << i << LL_ENDL;
			return LLWearable::FAILURE;
		}
		S32 te = 0;
		if ( 2 != sscanf(   /* Flawfinder: ignore */
				buffer,
				"%d %36s\n",
				&te, uuid_buffer) )
		{
				LL_WARNS() << "Bad Wearable asset: bad texture, #" << i << LL_ENDL;
				return LLWearable::FAILURE;
		}
	
		if( !LLUUID::validate( uuid_buffer ) )
		{
				LL_WARNS() << "Bad Wearable asset: bad texture uuid: " 
						<< uuid_buffer << LL_ENDL;
				return LLWearable::FAILURE;
		}
		LLUUID id = LLUUID(uuid_buffer);
		LLGLTexture* image = gTextureManagerBridgep->getFetchedTexture( id );
		if( mTEMap.find(te) != mTEMap.end() )
		{
			delete mTEMap[te];
		}
		if( mSavedTEMap.find(te) != mSavedTEMap.end() )
		{
			delete mSavedTEMap[te];
		}
	
		LLUUID textureid(uuid_buffer);
		mTEMap[te] = new LLLocalTextureObject(image, textureid);
		mSavedTEMap[te] = new LLLocalTextureObject(image, textureid);
		createLayers(te, avatarp);
	}

	// copy all saved param values to working params
	revertValues();

	return LLWearable::SUCCESS;
}