void print_vector4f_col(std::ostream& os, const cml::vector4f& vec, int prec = 4, int width = 8)
{
	std::ios::fmtflags old_flags = os.flags(); 
	os.setf(ios::left, ios::adjustfield); 

	os << std::setprecision(prec) << std::setw(width) << std::setfill(' ') 
		<< vec[0] << ' ' << std::endl 
		<< std::setprecision(prec) << std::setw(width) << std::setfill(' ')
		<< vec[1] << ' ' << std::endl 
		<< std::setprecision(prec) << std::setw(width) << std::setfill(' ')
		<< vec[2] << ' ' << std::endl 
		<< std::setprecision(prec) << std::setw(width) << std::setfill(' ')
		<< vec[3] << endl; 

	os.setf(old_flags); 
}
Example #2
0
void print_matrix(std::ostream& os, const cml::matrix44f& mat, int prec = 4, int width = 8)
{
	std::ios::fmtflags old_flags = os.flags(); 
	os.setf(ios::left, ios::adjustfield); 

	// row #1
	os << std::setprecision(prec) << std::setw(width) << std::setfill(' ') 
		<< mat(0, 0) << ' ' 
		<< std::setprecision(prec) << std::setw(width) << std::setfill(' ')
		<< mat(0, 1) << ' '
		<< std::setprecision(prec) << std::setw(width) << std::setfill(' ')
		<< mat(0, 2) << ' ' 
		<< std::setprecision(prec) << std::setw(width) << std::setfill(' ')
		<< mat(0, 3) << endl; 

	// row #2
	os << std::setprecision(prec) << std::setw(width) << std::setfill(' ') 
		<< mat(1, 0) << ' ' 
		<< std::setprecision(prec) << std::setw(width) << std::setfill(' ')
		<< mat(1, 1) << ' '
		<< std::setprecision(prec) << std::setw(width) << std::setfill(' ')
		<< mat(1, 2) << ' ' 
		<< std::setprecision(prec) << std::setw(width) << std::setfill(' ')
		<< mat(1, 3) << endl; 
	
	// row #3  
	os << std::setprecision(prec) << std::setw(width) << std::setfill(' ') 
		<< mat(2, 0) << ' ' 
		<< std::setprecision(prec) << std::setw(width) << std::setfill(' ')
		<< mat(2, 1) << ' '
		<< std::setprecision(prec) << std::setw(width) << std::setfill(' ')
		<< mat(2, 2) << ' ' 
		<< std::setprecision(prec) << std::setw(width) << std::setfill(' ')
		<< mat(2, 3) << endl; 

	// row #4
	os << std::setprecision(prec) << std::setw(width) << std::setfill(' ') 
		<< mat(3, 0) << ' ' 
		<< std::setprecision(prec) << std::setw(width) << std::setfill(' ')
		<< mat(3, 1) << ' '
		<< std::setprecision(prec) << std::setw(width) << std::setfill(' ')
		<< mat(3, 2) << ' ' 
		<< std::setprecision(prec) << std::setw(width) << std::setfill(' ')
		<< mat(3, 3) << endl; 

	os.setf(old_flags); 
}
Example #3
0
void RateGenerator::printForUser(std::ostream &o, const std::string &sep, int l, bool left) const
{
    std::streamsize previous_precision = o.precision();
    std::ios_base::fmtflags previous_flags = o.flags();
    
    o << "[ ";
    o << std::fixed;
    o << std::setprecision(4);
    
    // print the RbMatrix with each column of equal width and each column centered on the decimal
    for (size_t i=0; i < size(); i++)
    {
        if (i == 0)
        {
            o << "[ ";
        }
        else
        {
            o << "  ";
        }
        
        for (size_t j = 0; j < size(); ++j)
        {
            if (j != 0)
            {
                o << ", ";
            }
            o << getRate( i, j, 1e-6,1.0);
        }
        o <<  " ]";
        
        if (i == size()-1)
        {
            o << " ]";
        }
        else
        {
            o << " ,\n";
        }
        
    }
    
    o.setf(previous_flags);
    o.precision(previous_precision);
    
}
inline
void
arma_ostream::print_elem(std::ostream& o, const std::complex<T>& x, const bool modify)
  {
  if( (x.real() != T(0)) || (x.imag() != T(0)) || (modify == false) )
    {
    std::ostringstream ss;
    ss.flags(o.flags());
    //ss.imbue(o.getloc());
    ss.precision(o.precision());
    
    ss << '(';
    
    const T a = x.real();
    
    if(arma_isfinite(a))
      {
      ss << a;
      }
    else
      {
      ss << ( arma_isinf(a) ? ((a <= T(0)) ? "-inf" : "+inf") : "nan" );
      }
    
    ss << ',';
    
    const T b = x.imag();
    
    if(arma_isfinite(b))
      {
      ss << b;
      }
    else
      {
      ss << ( arma_isinf(b) ? ((b <= T(0)) ? "-inf" : "+inf") : "nan" );
      }
    
    ss << ')';
    
    o << ss.str();
    }
  else
    {
    o << "(0,0)";
    }
  }
Example #5
0
void Container::report(std::ostream& out) {
	std::map<int, double> gpad;
	std::map<int, int> gpan;
	for (int i = 0; i < count; i++) {
		gpan[p[i].group] = 0;
		gpad[p[i].group] = 0;
	}
		
	for (int i = 0; i < count; i++)
	{
		gpan[p[i].group] = gpan[p[i].group] + 1;
		gpad[p[i].group] = gpad[p[i].group] + (p[i].gpa - gpad[p[i].group]) / gpan[p[i].group];
	}
	out.flags(std::ios::left);
	out << std::setw(10) << "√руппа" << std::setw(20) << "—редний балл" << "\n\n";
	for (std::map<int, double>::iterator it = gpad.begin(); it != gpad.end(); ++it)
		out << std::setw(10) << it->first << std::setw(20) << it->second << '\n';
}
inline
void
arma_ostream::print_elem(std::ostream& o, const std::complex<T>& x, const bool modify)
  {
  if( (x.real() != T(0)) || (x.imag() != T(0)) || (modify == false) )
    {
    std::ostringstream ss;
    ss.flags(o.flags());
    //ss.imbue(o.getloc());
    ss.precision(o.precision());
  
    ss << '(' << x.real() << ',' << x.imag() << ')';
    o << ss.str();
    }
  else
    {
    o << "(0,0)";
    }
  }
Example #7
0
void outFmtFlags(std::ios_base::fmtflags fmtFlags, std::ostream& os, const char* term)
{ //! Output strings describing all bits in @c std::ios_base::fmtflags.
  /*! @b Usage: @c outFmtFlags();
     For example, by default outputs to @c std::cerr \n
     \verbatim
     FormatFlags: skipws showbase right dec."
     \endverbatim
     \n
     Default parameter values are:\n
     \code
       void outFmtFlags(fmtflags fmtFlags = cout.flags(), ostream& os = cerr, const char* term = ".\n");
     \endcode
   */
  const int up = 16; // Words across page.
  const int count = 16;  // 16 because using unsigned short int (must be at least 16 bits).
  std::ios_base::fmtflags flags = os.flags(); // Save to restore.
  fmtFlags &= static_cast<std::ios_base::fmtflags>(0x7FFF);  // _Fmtmask // clear un-used bits.
  os << "IOS format flags (" << std::showbase << std::hex << fmtFlags << std::dec << ")" ; // hex value.
  if (fmtFlags != 0)
  {
    for(int i = 0, j = 1, hit = 0; i < count; ++i)
    {
      if ((fmtFlags & j) != 0)
      {
        if (hit == 0)
        { // First word no separator.
          os << ' ';
        }
        else
        {
          os << (( (hit % up) == 0) ? ",\n" : ", ");
        }
        os  << fmtFlagWords[i];
        ++hit; // Count to add space or newline as appropriate.
      }
      j <<= 1;
    }
  }
  os << term; // eg "\n" or ". "
  os.setf(flags);  // Restore.
}  // outFmtFlags
        SetScientificImpl (std::ostream& out) :
          out_ (out), originalFlags_ (out.flags())
        {
          typedef Teuchos::ScalarTraits<scalar_type> STS;
          typedef typename STS::magnitudeType magnitude_type;
          typedef Teuchos::ScalarTraits<magnitude_type> STM;

          // Print floating-point values in scientific notation.
          out << std::scientific;

          // We're writing decimal digits, so compute the number of
          // digits we need to get reasonable accuracy when reading
          // values back in.
          //
          // There is actually an algorithm, due to Guy Steele (yes,
          // Java's Guy Steele) et al., for idempotent printing of
          // finite-length floating-point values.  We should actually
          // implement that algorithm, but I don't have time for that
          // now.  Currently, I just print no more than (one decimal
          // digit more than (the number of decimal digits justified
          // by the precision of magnitude_type)).
          //
          // We need to use STM's log10() rather than (say) std::log10
          // here, because STM::base() returns a magnitude_type, not
          // one of C++'s standard integer types.
          const magnitude_type numDecDigits = STM::t() * STM::log10 (STM::base());

          // Round and add one.  The cast to int should not overflow
          // unless STM::t() is _extremely_ large, so we don't need to
          // check for that case here.
          const magnitude_type one = STM::one();
          const magnitude_type two = one + one;
          // Cast from magnitude_type to int, since std::ostream's
          // precision() method expects an int input.
          const int prec = 1 + Teuchos::as<int> ((two*numDecDigits + one) / two);

          // Set the number of (decimal) digits after the decimal
          // point to print.
          out.precision (prec);
        }
Example #9
0
void LVector::write(std::ostream& os, int maxorder) const
{
    int oldprec = os.precision(8);
    std::ios::fmtflags oldf = os.setf(std::ios::scientific,std::ios::floatfield);
    if (maxorder < 0 || maxorder > _order)
        maxorder = _order;
    os << _order << std::endl;
    for (int n=0; n<=maxorder; n++) {
        for(PQIndex pq(n,0); !pq.needsConjugation(); pq.decm()) {
            os << " " << std::setw(2) << pq.getP()
               << " " << std::setw(2) << pq.getQ() ;
            if (pq.isReal()) {
                os << " " << std::setw(15) << (*this)[pq].real() << std::endl;
            } else {
                os << " " << std::setw(15) << (*this)[pq].real()
                   << " " << std::setw(15) << (*this)[pq].imag() << std::endl;
            }
        }
    }
    os.precision(oldprec);
    os.flags(oldf);
}
Example #10
0
void CladogeneticProbabilityMatrix::printForUser(std::ostream &o, const std::string &sep, int l, bool left) const
{
    std::streamsize previous_precision = o.precision();
    std::ios_base::fmtflags previous_flags = o.flags();
    
    o << "[ ";
    o << std::fixed;
    o << std::setprecision(4);

    o << "\n";
    std::map<std::vector<unsigned>, double>::const_iterator it;
    for (it = eventMapProbs.begin(); it != eventMapProbs.end(); it++)
    {
        if (it != eventMapProbs.begin())
            o << ",\n";
        const std::vector<unsigned>& v = it->first;
        o << "  " << "( " << v[0] << " -> " << v[1] << ", " << v[2] << " ) = " << it->second;
    }
    o << "\n]\n";
    
    o.setf(previous_flags);
    o.precision(previous_precision);
}
Example #11
0
void Terminal_std
::legend(std::ostream &stream) const
{
	std::vector<const Reporter::group_t*> cols_groups;

	for(auto& r : this->reporters)
		if (r != nullptr)
			for (auto& g : r->get_groups())
				cols_groups.push_back(&g);
		else
			throw tools::runtime_error(__FILE__, __LINE__, __func__, "'this->reporters' contains null pointer.");


	std::ios::fmtflags f(stream.flags());

	// stream << "# " << "----------------------------------------------||---------------------------------" << std::endl; // line 1
	// stream << "# " << "          cols_groups[0].first.first          ||   cols_groups[1].first.first    " << std::endl; // line 2
	// stream << "# " << "          cols_groups[0].first.second         ||   cols_groups[1].first.second   " << std::endl; // line 3
	// stream << "# " << "----------------------------------------------||---------------------------------" << std::endl; // line 4
	// stream << "# " << "----------|-----------|-----------|-----------||----------|----------|-----------" << std::endl; // line 5
	// stream << "# " << "   (1.1)  |    (2.1)  |    (3.1)  |    (4.1)  ||   (5.1)  |   (6.1)  |   (7.1)   " << std::endl; // line 6
	// stream << "# " << "   (1.2)  |    (2.2)  |    (3.2)  |    (4.2)  ||   (5.2)  |   (6.2)  |   (7.2)   " << std::endl; // line 7
	// stream << "# " << "----------|-----------|-----------|-----------||----------|----------|-----------" << std::endl; // line 8
	// note (1.1) is "cols_groups[0].second[0].first"
	// note (1.2) is "cols_groups[0].second[0].second"
	// note (2.1) is "cols_groups[0].second[1].first"
	// note (2.2) is "cols_groups[0].second[1].second"
	// note (3.1) is "cols_groups[0].second[2].first"
	// note (3.2) is "cols_groups[0].second[2].second"
	// note (4.1) is "cols_groups[0].second[3].first"
	// note (4.2) is "cols_groups[0].second[3].second"
	// note (5.1) is "cols_groups[1].second[0].first"
	// note (5.2) is "cols_groups[1].second[0].second"
	// note (6.1) is "cols_groups[1].second[1].first"
	// note (6.2) is "cols_groups[1].second[1].second"
	// note (7.1) is "cols_groups[1].second[2].first"
	// note (7.2) is "cols_groups[1].second[2].second"

	assert(!cols_groups.empty());

	// print line 1 of the table
	stream << rang::tag::comment;
	for (unsigned i = 0; i < cols_groups.size(); i++)
	{
		assert(!cols_groups[i]->second.empty());

		const unsigned group_width = get_group_width(*cols_groups[i]);
		const auto n_separators = group_width + extra_spaces(cols_groups[i]->first, group_width);

		stream << legend_style << std::string(n_separators, line_separator) << rang::style::reset ;

		if (i < (cols_groups.size() -1)) // print group separator except for last
			stream << legend_style << group_separator << rang::style::reset ;
	}
	stream << std::endl;

	// print line 2 and 3 of the table (group title lines)
	for (auto l = 0; l < 2; l++)
	{
		stream << rang::tag::comment;
		for (unsigned i = 0; i < cols_groups.size(); i++)
		{
			const auto& text = l == 0 ? cols_groups[i]->first.first : cols_groups[i]->first.second;

			const unsigned group_width = get_group_width(*cols_groups[i]);
			int n_spaces = (int)group_width - (int)text.size();

			if (text.size() != std::max(cols_groups[i]->first.first.size(), cols_groups[i]->first.second.size()))
				n_spaces += extra_spaces(cols_groups[i]->first, group_width);


			const unsigned n_spaces_left  = (n_spaces >= 0) ? (unsigned)n_spaces/2 : 0;
			const unsigned n_spaces_right = (n_spaces >= 0) ? n_spaces - n_spaces_left : 0;

			stream << legend_style << std::string(n_spaces_left,  ' ') << rang::style::reset;
			stream << legend_style << text << rang::style::reset;
			stream << legend_style << std::string(n_spaces_right, ' ') << rang::style::reset;

			if (i < (cols_groups.size() -1)) // print group separator except for last
				stream << legend_style << group_separator << rang::style::reset;
		}
		stream << std::endl;
	}

	// print line 4 of the table
	stream << rang::tag::comment;
	for (unsigned i = 0; i < cols_groups.size(); i++)
	{
		const unsigned group_width = get_group_width(*cols_groups[i]);
		const auto n_separators = group_width + extra_spaces(cols_groups[i]->first, group_width);

		stream << legend_style << std::string(n_separators, line_separator) << rang::style::reset;

		if (i < (cols_groups.size() -1)) // print group separator except for last
			stream << legend_style << group_separator << rang::style::reset;
	}
	stream << std::endl;

	// print line 5 of the table
	stream << rang::tag::comment;
	for (unsigned i = 0; i < cols_groups.size(); i++)
	{
		const unsigned group_width = get_group_width(*cols_groups[i]);
		const auto n_extra = extra_spaces(cols_groups[i]->first, group_width);

		for (unsigned j = 0; j < cols_groups[i]->second.size(); j++)
		{
			auto n_separators = column_width;
			if (j == 0)
				n_separators += n_extra;

			stream << legend_style << std::string(n_separators, line_separator) << rang::style::reset;
			if (j < (cols_groups[i]->second.size() -1)) // print column separator except for last
				stream << legend_style << col_separator << rang::style::reset;
		}

		if (i < (cols_groups.size() -1)) // print group separator except for last
			stream << legend_style << group_separator << rang::style::reset;
	}
	stream << std::endl;

	// print line 6 and 7 of the table (column title lines)
	for (auto l = 0; l < 2; l++)
	{
		stream << rang::tag::comment;
		for (unsigned i = 0; i < cols_groups.size(); i++)
		{
			const unsigned group_width = get_group_width(*cols_groups[i]);
			const auto n_extra = extra_spaces(cols_groups[i]->first, group_width);

			for (unsigned j = 0; j < cols_groups[i]->second.size(); j++)
			{
				const auto& text = l == 0 ? cols_groups[i]->second[j].first : cols_groups[i]->second[j].second;
				int n_spaces = (int)column_width - (int)text.size() -1;

				if (j == 0)
					n_spaces += n_extra;

				if (n_spaces > 0)
					stream << legend_style << std::string(n_spaces,  ' ') << rang::style::reset;

				stream << legend_style << text + " " << rang::style::reset;

				if (j < (cols_groups[i]->second.size() -1)) // print column separator except for last
					stream << legend_style << col_separator << rang::style::reset;
			}

			if (i < (cols_groups.size() -1)) // print group separator except for last
				stream << legend_style << group_separator << rang::style::reset;
		}
		stream << std::endl;
	}

	// print line 8 of the table
	stream << rang::tag::comment;
	for (unsigned i = 0; i < cols_groups.size(); i++)
	{
		const unsigned group_width = get_group_width(*cols_groups[i]);
		const auto n_extra = extra_spaces(cols_groups[i]->first, group_width);

		for (unsigned j = 0; j < cols_groups[i]->second.size(); j++)
		{
			auto n_separators = column_width;
			if (j == 0)
				n_separators += n_extra;

			stream << legend_style << std::string(n_separators, line_separator) << rang::style::reset;
			if (j < (cols_groups[i]->second.size() -1)) // print column separator except for last
				stream << legend_style << col_separator << rang::style::reset;
		}

		if (i < (cols_groups.size() -1)) // print group separator except for last
			stream << legend_style << group_separator << rang::style::reset;
	}
	stream << std::endl;

	stream.flags(f);
}
Example #12
0
void MetadataWriter::writeAttr(std::ostream& out, TSK_INUM_T addr, const TSK_FS_ATTR* a) {
  out << "{"
      << j("flags", attrFlags(a->flags), true)
      << j("id", a->id)
      << j("name", a->name ? std::string(a->name): std::string(""))
      << j("size", a->size)
      << j("type", a->type)
      << j("rd_buf_size", a->rd.buf_size)
      << j("nrd_allocsize", a->nrd.allocsize)
      << j("nrd_compsize", a->nrd.compsize)
      << j("nrd_initsize", a->nrd.initsize)
      << j("nrd_skiplen", a->nrd.skiplen);

  if (a->flags & TSK_FS_ATTR_RES && a->rd.buf_size && a->rd.buf) {
    out << ", " << j(std::string("rd_buf")) << ":\"";
    std::ios::fmtflags oldFlags = out.flags();
    out << std::hex << std::setfill('0');
    size_t numBytes = std::min(a->rd.buf_size, (size_t)a->size);
    for (size_t i = 0; i < numBytes; ++i) {
      out << std::setw(2) << (unsigned int)a->rd.buf[i];
    }
    out.flags(oldFlags);
    out << "\"";
  }

  if (a->flags & TSK_FS_ATTR_NONRES) {
    out << ", \"nrd_runs\":[";
    uint64_t fo = 0; // file offset
    uint64_t slackFo = 0;
    uint64_t skipBytes = a->nrd.skiplen; // up from 32 bits to 64 for convenience
    const uint64_t mainSize  = (a->flags & TSK_FS_ATTR_COMP) ? a->nrd.allocsize: a->nrd.initsize;
    // if (addr == 3240) {
    //   std::cerr << "mainSize = " << mainSize << "\n";
    // }
    bool first = true;
    for (TSK_FS_ATTR_RUN* curRun = a->nrd.run; curRun; curRun = curRun->next) {
      if (TSK_FS_ATTR_RUN_FLAG_FILLER == curRun->flags) {
        // TO-DO: check on the exact semantics of this flag
        continue;
      }
      // normal case - make absolute offsets
      uint64_t beg = (curRun->addr * Fs->block_size) + Fs->offset,
               runEnd = beg + (curRun->len * Fs->block_size),
               end = runEnd;
      bool     trueSlack = false;
      // if (addr == 3240) {
      //   std::cerr << "beg = " << beg << ", end = " << end << ", len = " << (end - beg) << ", fo = " << fo << ", slackFo = " << slackFo << "\n";
      // }
      // if skipping, advance beg and decrement skipBytes accordingly
      if (skipBytes > 0) { // still towards beginning where skiplen is > 0
        uint64_t toSkip = std::min(end - beg, skipBytes);
        beg += toSkip;
        skipBytes -= toSkip;
      }
      if (beg < end) { // past skipping, we're onto data
        uint64_t bytesRemaining = mainSize - fo; // how much data left in file stream?
        if (beg + bytesRemaining < end) {
          end = beg + bytesRemaining; // end is now beginning of true slack
          trueSlack = true;
          // if (3240 == addr) {
          //   std::cerr << "bytesRemaining = " << bytesRemaining << ", end now =" << end << "\n";
          // }
        }
        if (beg < end) { // if false, we're fully into true slack, nothing of file left
          if (TSK_FS_ATTR_RUN_FLAG_NONE == curRun->flags) {
            // just normal data; sparse blocks will be made available as unallocated
            markDataRun(beg, end, fo, addr, a->id, false);
          }
          fo += (end - beg); // advances fo even if data run is sparse, which is critical
        }
        if (trueSlack) {
          // mark slack at end of allocated space
          if (TSK_FS_ATTR_RUN_FLAG_NONE == curRun->flags) { // but only if not sparse (yes, could have sparse slack)
            markDataRun(end, runEnd, slackFo, addr, a->id, true);
          }
          slackFo += (runEnd - end);
        }
      }
      // output data run as json
      if (!first) {
        out << ", ";
      }
      out << "{"
          << j("addr", curRun->addr, true)
          << j("flags", curRun->flags)
          << j("len", curRun->len)
          << j("offset", curRun->offset)
          << "}";
      first = false;
    }
    out << "]" << j("slack_size", slackFo);
  }
  out << "}";
}
Example #13
0
void RateAgeBetaShift::printSummary(std::ostream &o) const
{
    std::streamsize previousPrecision = o.precision();
    std::ios_base::fmtflags previousFlags = o.flags();
    
    o << std::fixed;
    o << std::setprecision(4);
    
    // print the name
    const std::string &n = getMoveName();
    size_t spaces = 40 - (n.length() > 40 ? 40 : n.length());
    o << n;
    for (size_t i = 0; i < spaces; ++i)
    {
        o << " ";
    }
    o << " ";
    
    // print the DagNode name
    const std::string &dn_name = (*nodes.begin())->getName();
    spaces = 20 - (dn_name.length() > 20 ? 20 : dn_name.length());
    o << dn_name;
    for (size_t i = 0; i < spaces; ++i)
    {
        o << " ";
    }
    o << " ";
    
    // print the weight
    int w_length = 4 - (int)log10(weight);
    for (int i = 0; i < w_length; ++i)
    {
        o << " ";
    }
    o << weight;
    o << " ";
    
    // print the number of tries
    int t_length = 9 - (int)log10(num_tried);
    for (int i = 0; i < t_length; ++i)
    {
        o << " ";
    }
    o << num_tried;
    o << " ";
    
    // print the number of accepted
    int a_length = 9;
    if (numAccepted > 0) a_length -= (int)log10(numAccepted);
    
    for (int i = 0; i < a_length; ++i)
    {
        o << " ";
    }
    o << numAccepted;
    o << " ";
    
    // print the acceptance ratio
    double ratio = numAccepted / (double)num_tried;
    if (num_tried == 0) ratio = 0;
    int r_length = 5;
    
    for (int i = 0; i < r_length; ++i)
    {
        o << " ";
    }
    o << ratio;
    o << " ";
    
//    proposal->printParameterSummary( o );
    o << "delta = " << delta;
    
    o << std::endl;
    
    o.setf(previousFlags);
    o.precision(previousPrecision);
    
}
Example #14
0
void
EncodeLocationForecast4::
encodePrecipitationPercentiles( const boost::posix_time::ptime &from, 
			                       std::ostream &ost, 
			                       miutil::Indent &indent )
{
	WEBFW_USE_LOGGER( "encode" );
	log4cpp::Priority::Value loglevel = WEBFW_GET_LOGLEVEL();

	int hours[] = { 6, 12, 24 };
	int n=sizeof( hours )/sizeof(hours[0]);
	ptime fromTime;
	ptime toTime;
	bool first;
	string prevProvider;
	string provider;
	ostringstream percentileOst;
	ostringstream outOst;

	percentileOst.flags( ost.flags() );
	percentileOst.precision( ost.precision() );
	
	outOst.flags( ost.flags() );
	outOst.precision( ost.precision() );
	
	for( int i=0; i<n; ++i ) {
		if( ! locationData->init( from ) )
			return;
			
		prevProvider.erase();	
		first = true;
		percentileOst.str("");
		
		while( locationData->hasNext() ) {
			LocationElem& location = *locationData->next();
			
			if( ! percentileOst.str().empty() ) {
			   ++nElements;
				ost << outOst.str();
				percentileOst.str("");
			}
		
			outOst.str("");
			
			IndentLevel level3( indent );
			provider = location.forecastprovider();
				
			if( prevProvider != provider && loglevel >= log4cpp::Priority::DEBUG )
				ost << level3.indent() << "<!-- Dataprovider: " << provider << " -->\n";
				
			prevProvider = provider;
				
			if( first ) {
				if( loglevel >= log4cpp::Priority::DEBUG )
					ost << level3.indent() << "<!-- PrecipPercentiles: " << hours[i] << " hours -->\n";

				first = false;
			}
			
			toTime = location.time();
			fromTime = toTime - boost::posix_time::hours( hours[i] );
			
			TimeTag timeTag( 	fromTime, toTime );
			timeTag.output( outOst, level3.indent() );
								
			IndentLevel level4( indent );
			LocationTag locationTag( latitude, longitude, altitude );
			locationTag.output( outOst, level4.indent() );
						
			IndentLevel level5( indent );
						
			PrecipitationPercentileTags precipPercentileTag( location, hours[i] );
			precipPercentileTag.output( percentileOst, level5.indent() );
			
			if( ! percentileOst.str().empty() )  
				outOst << percentileOst.str();
				
		}

		//May have one left over.
		if( ! percentileOst.str().empty() ) {
		   ++nElements;
			ost << outOst.str();
		}
	
	}
}
Example #15
0
File: main.cpp Project: CCJY/coliru
 Flagger(std::ostream& os) : os(os), flags(os.flags()) {}
/*!

  Pretty print a velocity twist matrix. The data are tabulated.
  The common widths before and after the decimal point
  are set with respect to the parameter maxlen.

  \param s Stream used for the printing.

  \param length The suggested width of each matrix element.
  The actual width grows in order to accomodate the whole integral part,
  and shrinks if the whole extent is not needed for all the numbers.
  \param intro The introduction which is printed before the matrix.
  Can be set to zero (or omitted), in which case
  the introduction is not printed.

  \return Returns the common total width for all matrix elements

  \sa std::ostream &operator<<(std::ostream &s, const vpArray2D<Type> &A)
*/
int
vpVelocityTwistMatrix::print(std::ostream& s, unsigned int length, char const* intro) const
{
  typedef std::string::size_type size_type;

  unsigned int m = getRows();
  unsigned int n = getCols();

  std::vector<std::string> values(m*n);
  std::ostringstream oss;
  std::ostringstream ossFixed;
  std::ios_base::fmtflags original_flags = oss.flags();

  // ossFixed <<std::fixed;
  ossFixed.setf ( std::ios::fixed, std::ios::floatfield );

  size_type maxBefore=0;  // the length of the integral part
  size_type maxAfter=0;   // number of decimals plus
  // one place for the decimal point
  for (unsigned int i=0;i<m;++i) {
    for (unsigned int j=0;j<n;++j){
      oss.str("");
      oss << (*this)[i][j];
      if (oss.str().find("e")!=std::string::npos){
        ossFixed.str("");
        ossFixed << (*this)[i][j];
        oss.str(ossFixed.str());
      }

      values[i*n+j]=oss.str();
      size_type thislen=values[i*n+j].size();
      size_type p=values[i*n+j].find('.');

      if (p==std::string::npos){
        maxBefore=vpMath::maximum(maxBefore, thislen);
        // maxAfter remains the same
      } else{
        maxBefore=vpMath::maximum(maxBefore, p);
        maxAfter=vpMath::maximum(maxAfter, thislen-p-1);
      }
    }
  }

  size_type totalLength=length;
  // increase totalLength according to maxBefore
  totalLength=vpMath::maximum(totalLength,maxBefore);
  // decrease maxAfter according to totalLength
  maxAfter=std::min(maxAfter, totalLength-maxBefore);
  if (maxAfter==1) maxAfter=0;

  // the following line is useful for debugging
  //std::cerr <<totalLength <<" " <<maxBefore <<" " <<maxAfter <<"\n";

  if (intro) s <<intro;
  s <<"["<<m<<","<<n<<"]=\n";

  for (unsigned int i=0;i<m;i++) {
    s <<"  ";
    for (unsigned int j=0;j<n;j++){
      size_type p=values[i*n+j].find('.');
      s.setf(std::ios::right, std::ios::adjustfield);
      s.width((std::streamsize)maxBefore);
      s <<values[i*n+j].substr(0,p).c_str();

      if (maxAfter>0){
        s.setf(std::ios::left, std::ios::adjustfield);
        if (p!=std::string::npos){
          s.width((std::streamsize)maxAfter);
          s <<values[i*n+j].substr(p,maxAfter).c_str();
        } else{
          assert(maxAfter>1);
          s.width((std::streamsize)maxAfter);
          s <<".0";
        }
      }

      s <<' ';
    }
    s <<std::endl;
  }

  s.flags(original_flags); // restore s to standard state

  return (int)(maxBefore+maxAfter);
}
Example #17
0
  /**
   *
   * Read species data from THERMO section records. 
   * 
   * @param names        List of species names (input).
   * @param species      Table of species objects holding data from records
   *                     in THERMO section (output). 
   * @param temp         Devault vector of temperature region boundaries
   *                     There are one more temperatures than there are
   *                     temperature regions.
   * @param allowExtThermoData   True if 'THERMO' specified, false if 
   *                             'THERMO ALL' specified.
   *
   * @return            True, if the THERMO section exists and the species
   *                    have all been successfully processed. False, if
   *                    the THERMO section doesn't exist or there were
   *                    additional problems.
   */
  bool CKParser::readNASA9ThermoSection(std::vector<string>& names, 
					speciesTable& species, vector_fp& temp, 
					int& optionFlag, std::ostream& log) {
    // String buffer for lines
    string s;
    vector<string> toks;
    string defaultDate="";
    int nreg = 2;
    int i;

    int nsp = static_cast<int>(names.size());

    // Comment string
    string comment;


    // if "THERMO ALL" specified, or if optionFlag is set to HasTempRange,
    // then the next line must be the default temperatures for the database.
    //
    //  This line will have nreg+2 tokens on it
    //    The last token is a date.
    if (0) {
      if (optionFlag == NoThermoDatabase || optionFlag == HasTempRange) {
	getCKLine(s, comment);
	getTokens(s, static_cast<int>(s.size()), toks);
	nreg = toks.size();
	if (nreg >= 1) {
	  temp.resize(nreg+1);
	  for (i = 0; i <= nreg; i++) {
	    temp[i] = de_atof(toks[i]);
	  }
	  defaultDate = toks[nreg+1];
	}
      
	if (verbose) {
	  log.flags(ios::showpoint | ios::fixed);
	  log.precision(2);
	  log << endl << " Default # of temperature regions: " << nreg << endl;
	  log << "          ";
	  for (i = 0; i <= nreg; i++) {
	    log << temp[i] << "  ";
	  }
	  log << endl;
	}
	checkNASA9Temps(log, temp);
      }
    }
    
    // Check to see that we expect to be reading a NASA9 formatted file
    if (!m_nasa9fmt) {
      throw CK_SyntaxError(log, 
			   "In NASA9 parser. However, we expect a different file format",
			   -1);
    }

    // now read in all species records that have names in list 'names'

    bool getAllSpecies = (nsp > 0 && match(names[0], "<ALL>"));
    if (getAllSpecies) names.clear();

    // Map between the number of times a species name appears in the database
    map<string, int> dup; // used to check for duplicate THERMO records
    bool already_read;

    while (1 > 0) {
      // If we don't have any more species to read, break
      if (nsp == 0) break;
      already_read = false;

      // Read a new species record from the section
      Species spec;
      readNASA9ThermoRecord(spec);

      // we signal the end of the section by putting <END> as a
      // species name. Break if you find the end of the section.
      if (spec.name == "<END>") {
	break;
      }
        
      // check for duplicate thermo data
      if (dup[spec.name] == 2) {
	log << "Warning: more than one THERMO record for "
	    << "species " << spec.name << endl;
	log << "Record at line " << m_line 
	    << " of " << m_ckfilename << " ignored." << endl;
	already_read = true;
      }
      // Set the record in the map to 2 to create a signal for the
      // next time.
      dup[spec.name] = 2;

      // Check to see whether we need this particlar species name
      if (!already_read && (getAllSpecies 
			    || (find(names.begin(), names.end(), spec.name) 
				< names.end()))) {

	// Add the species object to the map. Note we are
	// doing a copy constructor here, so we create a
	// lasting entry.
	species[spec.name] = spec;

	if (verbose) {        
	  log << endl << "found species " << spec.name;
	  log << " at line " << m_line 
	      << " of " << m_ckfilename;
	  writeSpeciesData(log, spec);
	}
	//checkTemps(log, spec.tlow, spec.tmid, spec.thigh);
	if (getAllSpecies) {
	  names.push_back(spec.name);
	  nsp = static_cast<int>(names.size());
	}
	else
	  nsp--;
      }
    }
    return true;
  }
Example #18
0
static bool writeCluster(
	std::ostream &out, int depth,
	const ClusterArray < std::vector<edge> > &edgeMap,
	const ClusterGraph &C, const ClusterGraphAttributes *CA, const cluster &c,
	int &clusterId)
{
	std::ios_base::fmtflags currentFlags = out.flags();
	out.flags(currentFlags | std::ios::fixed);
	bool result = out.good();

	if(result) {
		if (C.rootCluster() == c) {
			writeHeader(out, depth++, CA);
		} else {
			GraphIO::indent(out, depth++) << "subgraph cluster" << clusterId << " {\n";
		}
		clusterId++;

		bool whitespace; // True if a whitespace should printed (readability).

		whitespace = false;
		if (CA) {
			writeAttributes(out, depth, *CA, c);
			whitespace = true;
		}

		if (whitespace) {
			out << "\n";
		}

		// Recursively export all subclusters.
		whitespace = false;
		for (cluster child : c->children) {
			writeCluster(out, depth, edgeMap, C, CA, child, clusterId);
			whitespace = true;
		}

		if (whitespace) {
			out << "\n";
		}

		// Then, print all nodes whithout an adjacent edge.
		whitespace = false;
		for (node v : c->nodes) {
			whitespace |= writeNode(out, depth, CA, v);
		}

		if (whitespace) {
			out << "\n";
		}

		// Finally, we print all edges for this cluster (ugly version for now).
		const std::vector<edge> &edges = edgeMap[c];
		whitespace = false;
		for (auto &e : edges) {
			whitespace |= writeEdge(out, depth, CA, e);
		}

		GraphIO::indent(out, --depth) << "}\n";
	}

	out.flags(currentFlags);

	return result;
}
Example #19
0
void  
EncodeLocationForecast4::
encodeMoment( const boost::posix_time::ptime &from, 
			     std::ostream &ost, 
		        miutil::Indent &indent )
{
   WEBFW_USE_LOGGER( "encode" );
   log4cpp::Priority::Value loglevel = WEBFW_GET_LOGLEVEL();

   int countProviderChange=0; //used to stop endless loops.
	ostringstream tmpOst;
	ostringstream momentOst;
	WeatherSymbolDataBuffer symbolDataBuffer;
	SymbolConfList symbolConfList;
	boost::posix_time::ptime dataFrom;
	boost::posix_time::ptime currentTime;
	boost::posix_time::ptime currentFrom( from );
	string prevForecastprovider;
	bool hasMomentData;
		
	tmpOst.flags( ost.flags() );
	tmpOst.precision( ost.precision() );
	
	momentOst.flags( ost.flags() );
	momentOst.precision( ost.precision() );
	
	dataFrom = from - boost::posix_time::hours( symbolConf.maxHours() );

	currentTime = dataFrom;
	//We must collect data from 'from' - time
	//to fill up symbolDataBuffer with data so
	//we can generate Symbols from the first
	//dataset in the output, but we shall not
	//deliver the data between 'dataFrom' to 'from'
	//in the output.
	if( ! locationData->init( dataFrom ) )
		return;

	curItBreakTimes = breakTimes.end();
	
	while( locationData->hasNext() ) {
		SymbolDataElement symbolData;
		LocationElem &location = *locationData->next();
		location.config = config_;
		
		//Just fill the buffer if the dataset is before, the currentFrom time,
		//ie do not output the data.
		if( currentTime >= currentFrom && ! momentOst.str().empty() ) {
		   ++nElements;
			ost << tmpOst.str();
			momentOst.str("");
		}
			
		currentTime = location.time();
		tmpOst.str("");
		momentOst.str("");

		{ //Begin Block
			IndentLevel level3( indent );
			TimeTag timeTag( location.time(), location.time() );
			timeTag.output( tmpOst, level3.indent() );
	
			IndentLevel level4( indent );
			LocationTag locationTag( latitude, longitude, altitude );
			locationTag.output( tmpOst, level4.indent() );
	
			IndentLevel level5( indent );
			MomentTags1 momentTags( location, symbolData, projectionHelper, config_->isForecast );
			momentTags.output( momentOst, level5.indent() );
		
			hasMomentData = false;
			if( ! momentOst.str().empty() ) {
				hasMomentData = true;

				if( currentTime >= currentFrom )
					updateBreakTimes( location.forecastprovider(), location.time() );

				if( prevForecastprovider.empty() )
					prevForecastprovider = location.forecastprovider();
				else if( prevForecastprovider != location.forecastprovider()
						 && countProviderChange < 10) {
					++countProviderChange;
					if( loglevel >= log4cpp::Priority::DEBUG ) {
						ost << "<!-- Change provider: " <<  prevForecastprovider<< " -> " << location.forecastprovider()
							<< " (" << location.time() << ") -->\n";
					}
					prevForecastprovider = location.forecastprovider();
					currentFrom =  location.time();
					dataFrom =  currentFrom - boost::posix_time::hours( symbolConf.maxHours() );
					locationData->init( dataFrom, location.forecastprovider() );
					hasMomentData = false;
					momentOst.str("");
					symbolDataBuffer.clear();
				}

				if( hasMomentData ) {
					symbolDataBuffer.add( location.time(), symbolData );
					tmpOst << momentOst.str();
				}

			}
		} //End Block

		if( hasMomentData ) {
			symbolConfList = symbolConf.get( location.forecastprovider() );

			if( loglevel >= log4cpp::Priority::DEBUG ) {
				tmpOst << "<!-- provider: " <<  location.forecastprovider() << "\n";

				for( int i=0; i < symbolConfList.size(); ++i ) {
					tmpOst << "  symbolConf [" << i << "]: " << symbolConfList[i] << "\n";
				}
				tmpOst << " -->\n";
			}

			encodePeriods( location, symbolDataBuffer,
						   symbolConfList , tmpOst, indent, currentTime >= currentFrom  );
		}
	}

	//May have one leftover.
	if( ! momentOst.str().empty() && currentTime >= currentFrom) {
	   ++nElements;
		ost << tmpOst.str();
	}
}
Example #20
0
File: plot.cpp Project: emsr/tr2
  void
  plot_func(std::ostream & out,
            std::function<Num (Num)> funk,
            Num x1, Num x2,
            const std::string & t1, const std::string & t2,
            const std::string & tx, const std::string & ty)
  {
    using len_t = decltype(t1.length());
    const len_t ISCREEN = 101;
    const len_t JSCREEN = 42;
    const char CORNER = '+';
    const char BLANK = ' ';
    const char XZERO = '.';
    const char YZERO = '-';
    const char YBORDER = '|';
    const char XBORDER = '-';
    const char FUNCPT = 'x';

    std::vector<std::string> screen(ISCREEN, std::string(JSCREEN, BLANK));
    std::string title1(ISCREEN, BLANK);
    std::string title2(ISCREEN, BLANK);
    std::string titlex(ISCREEN, BLANK);
    std::string titley(JSCREEN, BLANK);

    //
    //  Massage titles.
    //
    int len1 = std::min(t1.length(), ISCREEN);
    for (int j = 0; j < len1; ++j)
      title1[static_cast<int>((ISCREEN - len1)/2.0) + j] = t1[j];

    int len2 = std::min(t2.length(), ISCREEN);
    for (int j = 0; j < len2; ++j)
      title2[static_cast<int>((ISCREEN - len2)/2.0) + j] = t2[j];

    int lenx = std::min(tx.length(), ISCREEN);
    for (int j = 0; j < lenx; ++j)
      titlex[static_cast<int>((ISCREEN - lenx)/2.0) + j] = tx[j];

    int leny = std::min(ty.length(), JSCREEN);
    for (int j = 0; j < leny; ++j)
      titley.at(static_cast<int>((JSCREEN + leny)/2.0) - j) = ty.at(j);

    screen[0][0] = screen[0][JSCREEN - 1] = screen[ISCREEN - 1][0] = screen[ISCREEN - 1][JSCREEN - 1] = CORNER;

    for(int j = 1; j < JSCREEN - 1; ++j)
      screen[0][j] = screen[ISCREEN - 1][j] = YBORDER;

    for(int i = 1; i < ISCREEN - 1; ++i)
      screen[i][0] = screen[i][JSCREEN - 1] = XBORDER;

    //
    //  Evaluate the function over the requested interval.
    //  Keep track of the maximum and minimum values of the function.
    //  With this logic, the interval from ysml to ybig will always
    //  include the x axis (y == 0).
    //
    Num dx = (x2 - x1) / (ISCREEN - 1);
    Num x = x1;
    int izero = -1;
    if (x1 < 0.0 && x2 > 0.0)
      {
        izero = -(ISCREEN * x1) / (x2 - x1);
        for (int j = 1; j < JSCREEN - 1; ++j)
          screen.at(izero).at(j) = XZERO;
      }
    Num ysml = std::numeric_limits<Num>::max();
    Num ybig = -std::numeric_limits<Num>::max();
    std::vector<Num> y(ISCREEN);
    for (int i = 0; i < ISCREEN; ++i)
      {
        y[i] = funk(x);
        if (y[i] < ysml)
          ysml = y[i];
        if (y[i] > ybig)
          ybig = y[i];
        x += dx;
      }
    if (ysml > 0.0)
      ysml = 0.0;
    if (ybig < 0.0)
      ybig = 0.0;
    if (ybig == ysml)
      {
        ybig += 0.5;
        ybig -= 0.5;
      }
    Num djy = (JSCREEN - 1) / (ybig - ysml);
    int jzero = static_cast<int>(-ysml * djy);
    for (int i = 1; i < ISCREEN - 1; ++i)
      {
        screen.at(i).at(jzero) = YZERO;
        int j = static_cast<int>((y[i] - ysml) * djy);
        screen.at(i).at(j) = FUNCPT;
      }

    auto old_prec = out.precision(4);
    auto old_flags = out.flags(out.flags() | std::ios::showpoint);

    //
    //  Print title(s)
    //
    if (len1 > 0)
      {
        out << std::endl;
        if (leny > 0)
          out << "   ";
        for (int i = 0; i < 12; ++i)
          out << BLANK;
        out << title1 << std::endl;
      }
    if (len2 > 0)
      {
        out << std::endl;
        if (leny > 0)
          out << "   ";
        for (int i = 0; i < 12; ++i)
          out << BLANK;
        out << title2 << std::endl;
      }
    out << std::endl;

    //
    //  Print upper limit and top line.
    //
    if (leny > 0)
      out << ' ' << titley[JSCREEN - 1] << ' ';
    out << ' ' << std::setw(10) << std::showpos << ybig << ' ';
    for (int i = 0; i < ISCREEN; ++i)
      out << screen[i][JSCREEN - 1];
    out << std::endl;

    //
    //  Print graph.
    //
    for (int j = JSCREEN - 2; j >= 1; --j)
      {
        if (leny > 0)
          out << ' ' << titley[j] << ' ';
        if (j == jzero)
          out << ' ' << std::setw(10) << std::showpos << 0.0 << ' ';
        else
          for (int i = 0; i < 12; ++i)
            out << BLANK;
        for (int i = 0; i < ISCREEN; ++i)
          out << screen[i][j];
        out << std::endl;
      }

    //
    //  Print lower limit and bottom line.
    //
    if (leny > 0)
      out << ' ' << titley[0] << ' ';
    out << ' ' << std::setw(10) << std::showpos << ysml << ' ';
    for (int i = 0; i < ISCREEN; ++i)
      out << screen[i][0];
    out << std::endl;

    //
    //  Print lower and upper x limits.
    //
    if (leny > 0)
      out << "   ";
    out << "      "
        << std::setw(10) << std::showpos << x1;
    if (izero > -1)
      {
        out << std::setw(izero - 10) << ""
            << std::setw(10) << 0.0
            << std::setw(ISCREEN - 11 - izero) << "";
      }
    else
      out << std::setw(ISCREEN - 11) << "";
    out << std::setw(10) << std::showpos << x2 << std::endl;

    if (lenx > 0)
      {
        out << std::endl;
        if (leny > 0)
          out << "   ";
        for (int i = 0; i < 12; ++i)
          out << BLANK;
        out << titlex << std::endl;
      }
    out << std::endl;

    out.flags(old_flags);
    out.precision(old_prec);
  }
Example #21
0
void Container::print(std::ostream& out) {\
	out.flags(std::ios::left);
	out << std::setw(3) << '#' << std::setw(20) << "‘амили¤" << std::setw(10) << "√руппа" << std::setw(20) << "—редний балл" << "\n\n";
	for (int i = 0; i < count; i++)
		out << std::setw(3) << (i + 1) << std::setw(20) << p[i].name << std::setw(10) << p[i].group << std::setw(20) << p[i].gpa << std::endl;
}
Example #22
0
StreamFormatScope::StreamFormatScope(std::ostream& out)
    : d_out(out), d_format_flags(out.flags()), d_precision(out.precision())
{
}
Example #23
0
// virtual
S32 LLSDNotationFormatter::format(const LLSD& data, std::ostream& ostr, U32 options) const
{
	S32 format_count = 1;
	switch(data.type())
	{
	case LLSD::TypeMap:
	{
		ostr << "{";
		bool need_comma = false;
		LLSD::map_const_iterator iter = data.beginMap();
		LLSD::map_const_iterator end = data.endMap();
		for(; iter != end; ++iter)
		{
			if(need_comma) ostr << ",";
			need_comma = true;
			ostr << '\'';
			serialize_string((*iter).first, ostr);
			ostr << "':";
			format_count += format((*iter).second, ostr);
		}
		ostr << "}";
		break;
	}

	case LLSD::TypeArray:
	{
		ostr << "[";
		bool need_comma = false;
		LLSD::array_const_iterator iter = data.beginArray();
		LLSD::array_const_iterator end = data.endArray();
		for(; iter != end; ++iter)
		{
			if(need_comma) ostr << ",";
			need_comma = true;
			format_count += format(*iter, ostr);
		}
		ostr << "]";
		break;
	}

	case LLSD::TypeUndefined:
		ostr << "!";
		break;

	case LLSD::TypeBoolean:
		if(mBoolAlpha ||
#if( LL_WINDOWS || LL_MINGW32 || __GNUC__ > 2)
		   (ostr.flags() & std::ios::boolalpha)
#else
		   (ostr.flags() & 0x0100)
#endif
			)
		{
			ostr << (data.asBoolean()
					 ? NOTATION_TRUE_SERIAL : NOTATION_FALSE_SERIAL);
		}
		else
		{
			ostr << (data.asBoolean() ? 1 : 0);
		}
		break;

	case LLSD::TypeInteger:
		ostr << "i" << data.asInteger();
		break;

	case LLSD::TypeReal:
		ostr << "r";
		if(mRealFormat.empty())
		{
			ostr << data.asReal();
		}
		else
		{
			formatReal(data.asReal(), ostr);
		}
		break;

	case LLSD::TypeUUID:
		ostr << "u" << data.asUUID();
		break;

	case LLSD::TypeString:
		ostr << '\'';
		serialize_string(data.asString(), ostr);
		ostr << '\'';
		break;

	case LLSD::TypeDate:
		ostr << "d\"" << data.asDate() << "\"";
		break;

	case LLSD::TypeURI:
		ostr << "l\"";
		serialize_string(data.asString(), ostr);
		ostr << "\"";
		break;

	case LLSD::TypeBinary:
	{
		// *FIX: memory inefficient.
		std::vector<U8> buffer = data.asBinary();
		ostr << "b(" << buffer.size() << ")\"";
		if(buffer.size()) ostr.write((const char*)&buffer[0], buffer.size());
		ostr << "\"";
		break;
	}

	default:
		// *NOTE: This should never happen.
		ostr << "!";
		break;
	}
	return format_count;
}
S32 LLSDXMLFormatter::format_impl(const LLSD& data, std::ostream& ostr, U32 options, U32 level) const
{
	S32 format_count = 1;
	std::string pre;
	std::string post;

	if (options & LLSDFormatter::OPTIONS_PRETTY)
	{
		for (U32 i = 0; i < level; i++)
		{
			pre += "    ";
		}
		post = "\n";
	}

	switch(data.type())
	{
	case LLSD::TypeMap:
		if(0 == data.size())
		{
			ostr << pre << "<map />" << post;
		}
		else
		{
			ostr << pre << "<map>" << post;
			LLSD::map_const_iterator iter = data.beginMap();
			LLSD::map_const_iterator end = data.endMap();
			for(; iter != end; ++iter)
			{
				ostr << pre << "<key>" << escapeString((*iter).first) << "</key>" << post;
				format_count += format_impl((*iter).second, ostr, options, level + 1);
			}
			ostr << pre <<  "</map>" << post;
		}
		break;

	case LLSD::TypeArray:
		if(0 == data.size())
		{
			ostr << pre << "<array />" << post;
		}
		else
		{
			ostr << pre << "<array>" << post;
			LLSD::array_const_iterator iter = data.beginArray();
			LLSD::array_const_iterator end = data.endArray();
			for(; iter != end; ++iter)
			{
				format_count += format_impl(*iter, ostr, options, level + 1);
			}
			ostr << pre << "</array>" << post;
		}
		break;

	case LLSD::TypeUndefined:
		ostr << pre << "<undef />" << post;
		break;

	case LLSD::TypeBoolean:
		ostr << pre << "<boolean>";
		if(mBoolAlpha ||
#if( LL_WINDOWS || __GNUC__ > 2)
		   (ostr.flags() & std::ios::boolalpha)
#else
		   (ostr.flags() & 0x0100)
#endif
			)
		{
			ostr << (data.asBoolean() ? "true" : "false");
		}
		else
		{
			ostr << (data.asBoolean() ? 1 : 0);
		}
		ostr << "</boolean>" << post;
		break;

	case LLSD::TypeInteger:
		ostr << pre << "<integer>" << data.asInteger() << "</integer>" << post;
		break;

	case LLSD::TypeReal:
		ostr << pre << "<real>";
		if(mRealFormat.empty())
		{
			ostr << data.asReal();
		}
		else
		{
			formatReal(data.asReal(), ostr);
		}
		ostr << "</real>" << post;
		break;

	case LLSD::TypeUUID:
		if(data.asUUID().isNull()) ostr << pre << "<uuid />" << post;
		else ostr << pre << "<uuid>" << data.asUUID() << "</uuid>" << post;
		break;

	case LLSD::TypeString:
		if(data.asString().empty()) ostr << pre << "<string />" << post;
		else ostr << pre << "<string>" << escapeString(data.asString()) <<"</string>" << post;
		break;

	case LLSD::TypeDate:
		ostr << pre << "<date>" << data.asDate() << "</date>" << post;
		break;

	case LLSD::TypeURI:
		ostr << pre << "<uri>" << escapeString(data.asString()) << "</uri>" << post;
		break;

	case LLSD::TypeBinary:
	{
		LLSD::Binary buffer = data.asBinary();
		if(buffer.empty())
		{
			ostr << pre << "<binary />" << post;
		}
		else
		{
			// *FIX: memory inefficient.
			// *TODO: convert to use LLBase64
			ostr << pre << "<binary encoding=\"base64\">";
			int b64_buffer_length = apr_base64_encode_len(buffer.size());
			char* b64_buffer = new char[b64_buffer_length];
			b64_buffer_length = apr_base64_encode_binary(
				b64_buffer,
				&buffer[0],
				buffer.size());
			ostr.write(b64_buffer, b64_buffer_length - 1);
			delete[] b64_buffer;
			ostr << "</binary>" << post;
		}
		break;
	}
	default:
		// *NOTE: This should never happen.
		ostr << pre << "<undef />" << post;
		break;
	}
	return format_count;
}
Example #25
0
		z(std::ostream& s) : str(s), fl(s.flags()) { }
Example #26
0
bool sillyCgSolve(
  const Thyra::LinearOpBase<Scalar> &A,
  const Thyra::VectorBase<Scalar> &b,
  const int maxNumIters,
  const typename Teuchos::ScalarTraits<Scalar>::magnitudeType tolerance,
  const Teuchos::Ptr<Thyra::VectorBase<Scalar> > &x,
  std::ostream &out
  )
{

  // Create some typedefs and some other stuff to make the code cleaner
  typedef Teuchos::ScalarTraits<Scalar> ST; typedef typename ST::magnitudeType ScalarMag;
  const Scalar one = ST::one(), zero = ST::zero();  using Teuchos::as;
  using Teuchos::RCP; using Thyra::VectorSpaceBase; using Thyra::VectorBase;
  using Thyra::NOTRANS; using Thyra::V_V; using Thyra::apply;


  // Validate input
  THYRA_ASSERT_LINEAR_OP_VEC_APPLY_SPACES("sillyCgSolve()", A, Thyra::NOTRANS, *x, &b);
  Teuchos::EVerbosityLevel vl = Teuchos::VERB_MEDIUM;

  std::ios::fmtflags fmt(out.flags());

  out << "\nStarting CG solver ...\n" << std::scientific << "\ndescribe A:\n"<<describe(A, vl)
      << "\ndescribe b:\n"<<describe(b, vl)<<"\ndescribe x:\n"<<describe(*x, vl)<<"\n";

  // Initialization
  const RCP<const VectorSpaceBase<Scalar> > space = A.domain();
  const RCP<VectorBase<Scalar> > r = createMember(space);
  // r = -A*x + b
  V_V(r.ptr(), b); apply<Scalar>(A, NOTRANS, *x, r.ptr(), -one, one);
  const ScalarMag r0_nrm = norm(*r);
  if (r0_nrm==zero) return true;
  const RCP<VectorBase<Scalar> > p = createMember(space), q = createMember(space);
  Scalar rho_old = -one;

  // Perform the iterations
  for( int iter = 0; iter <= maxNumIters; ++iter ) {

    // Check convergence and output iteration
    const ScalarMag r_nrm = norm(*r);
    const bool isConverged = r_nrm/r0_nrm <= tolerance;
    if( iter%(maxNumIters/10+1) == 0 || iter == maxNumIters || isConverged ) {
      out << "Iter = " << iter << ", ||b-A*x||/||b-A*x0|| = " << (r_nrm/r0_nrm) << std::endl;
      if( r_nrm/r0_nrm < tolerance ) {
        out.flags(fmt);
        return true; // Success!
      }
    }

    // Compute iteration
    const Scalar rho = inner(*r, *r);        // <r,r>              -> rho
    if (iter==0) V_V(p.ptr(), *r);           // r                  -> p   (iter == 0)
    else Vp_V( p.ptr(), *r, rho/rho_old );   // r+(rho/rho_old)*p  -> p   (iter  > 0)
    apply<Scalar>(A, NOTRANS, *p, q.ptr());  // A*p                -> q
    const Scalar alpha = rho/inner(*p, *q);  // rho/<p,q>          -> alpha
    Vp_StV( x, +alpha, *p );                 // +alpha*p + x       -> x
    Vp_StV( r.ptr(), -alpha, *q );           // -alpha*q + r       -> r
    rho_old = rho;                           // rho                -> rho_old (for next iter)

  }

  out.flags(fmt);
  return false; // Failure
} // end sillyCgSolve
S32 LLSDXMLFormatter::format_impl(const LLSD& data, std::ostream& ostr, U32 options, U32 level) const
{
	S32 format_count = 1;
	std::string pre;
	std::string post;

	if (options & LLSDFormatter::OPTIONS_PRETTY)
	{
		for (U32 i = 0; i < level; i++)
		{
			pre += "    ";
		}
		post = "\n";
	}

	switch(data.type())
	{
	case LLSD::TypeMap:
		if(0 == data.size())
		{
			ostr << pre << "<map />" << post;
		}
		else
		{
			ostr << pre << "<map>" << post;
			LLSD::map_const_iterator iter = data.beginMap();
			LLSD::map_const_iterator end = data.endMap();
			for(; iter != end; ++iter)
			{
				ostr << pre << "<key>" << escapeString((*iter).first) << "</key>" << post;
				format_count += format_impl((*iter).second, ostr, options, level + 1);
			}
			ostr << pre <<  "</map>" << post;
		}
		break;

	case LLSD::TypeArray:
		if(0 == data.size())
		{
			ostr << pre << "<array />" << post;
		}
		else
		{
			ostr << pre << "<array>" << post;
			LLSD::array_const_iterator iter = data.beginArray();
			LLSD::array_const_iterator end = data.endArray();
			for(; iter != end; ++iter)
			{
				format_count += format_impl(*iter, ostr, options, level + 1);
			}
			ostr << pre << "</array>" << post;
		}
		break;

	case LLSD::TypeUndefined:
		ostr << pre << "<undef />" << post;
		break;

	case LLSD::TypeBoolean:
		ostr << pre << "<boolean>";
		if(mBoolAlpha ||
		   (ostr.flags() & std::ios::boolalpha)
			)
		{
			ostr << (data.asBoolean() ? "true" : "false");
		}
		else
		{
			ostr << (data.asBoolean() ? 1 : 0);
		}
		ostr << "</boolean>" << post;
		break;

	case LLSD::TypeInteger:
		ostr << pre << "<integer>" << data.asInteger() << "</integer>" << post;
		break;

	case LLSD::TypeReal:
		ostr << pre << "<real>";
		if(mRealFormat.empty())
		{
			ostr << data.asReal();
		}
		else
		{
			formatReal(data.asReal(), ostr);
		}
		ostr << "</real>" << post;
		break;

	case LLSD::TypeUUID:
		if(data.asUUID().isNull()) ostr << pre << "<uuid />" << post;
		else ostr << pre << "<uuid>" << data.asUUID() << "</uuid>" << post;
		break;

	case LLSD::TypeString:
		if(data.asStringRef().empty()) ostr << pre << "<string />" << post;
		else ostr << pre << "<string>" << escapeString(data.asStringRef()) <<"</string>" << post;
		break;

	case LLSD::TypeDate:
		ostr << pre << "<date>" << data.asDate() << "</date>" << post;
		break;

	case LLSD::TypeURI:
		ostr << pre << "<uri>" << escapeString(data.asString()) << "</uri>" << post;
		break;

	case LLSD::TypeBinary:
	{
		const LLSD::Binary& buffer = data.asBinary();
		if(buffer.empty())
		{
			ostr << pre << "<binary />" << post;
		}
		else
		{
			ostr << pre << "<binary encoding=\"base64\">";
			ostr << LLBase64::encode(&buffer[0], buffer.size());
			ostr << "</binary>" << post;
		}
		break;
	}
	default:
		// *NOTE: This should never happen.
		ostr << pre << "<undef />" << post;
		break;
	}
	return format_count;
}
Example #28
0
	print_init(std::ostream& os) : os(os), saveflags(os.flags())
	{
		os << std::fixed << std::setprecision(4);
	}
//------------------------------------------------------------------------------
// printMessage(): Recursive function to print all fields in this message
//---------------------------------------------------------------------------
void PrintSelected::printMessage(std::ostream& soutFields, std::ostream& soutVals, const google::protobuf::Message* const msg)
{
   std::streamsize oldWidth = soutFields.width();
   std::ostream::fmtflags oldFlags = soutFields.flags();

   const google::protobuf::Descriptor* descriptor = msg->GetDescriptor();
   const google::protobuf::Reflection* reflection = msg->GetReflection();

   const google::protobuf::Message& root = *msg;
   std::string msgName = descriptor->name();

   int fieldCount = descriptor->field_count();

   const google::protobuf::FieldDescriptor* fieldDescriptor = nullptr;

   std::string msgDivider = ";   ";
   std::string fieldDivider = ", ";

   bool lastField = false;

   if (fieldCount > 0) {
      for (int i = 0; i < fieldCount; i++) {
         if ((i+1) == fieldCount) lastField = true;

         // Get field descriptor (includes messages)
         fieldDescriptor = descriptor->field(i);

         // what type is this field?
         google::protobuf::FieldDescriptor::CppType cppType = fieldDescriptor->cpp_type();

         if (cppType == google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) {

            // do the same again for this message, etc.
            const google::protobuf::Message& sub_message = reflection->GetMessage(root, fieldDescriptor);
            printMessage(soutFields, soutVals, &sub_message);
         }
         else {
            // not a message: Print the field
            if (reflection->HasField(root, fieldDescriptor)) {
               soutFields <<  std::left << std::setw(12) << fieldDescriptor->name(); // Field name

               // get the value
               switch (cppType) {
                  case google::protobuf::FieldDescriptor::CPPTYPE_STRING: {
                     soutVals <<  std::left << std::setw(12)<<  reflection->GetString(root, fieldDescriptor);
                     break;
                  }
                  case google::protobuf::FieldDescriptor::CPPTYPE_INT32: {
                     soutVals <<  std::left << std::setw(12)<<  reflection->GetInt32(root, fieldDescriptor);
                     break;
                  }
                  case google::protobuf::FieldDescriptor::CPPTYPE_INT64: {
                     soutVals <<  std::left << std::setw(12)<< reflection->GetInt64(root, fieldDescriptor);
                     break;
                  }
                  case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: {
                     soutVals <<  std::left << std::setw(12)<< reflection->GetUInt32(root, fieldDescriptor);
                     break;
                  }
                  case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: {
                     soutVals <<  std::left << std::setw(12)<< reflection->GetUInt64(root, fieldDescriptor);
                     break;
                  }
                  case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: {
                     soutVals  <<  std::left << std::setw(12)<< reflection->GetDouble(root, fieldDescriptor);
                     break;
                  }
                  case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: {
                     soutVals  <<  std::left << std::setw(12)<< reflection->GetFloat(root, fieldDescriptor);
                     break;
                  }
                  case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: {
                     soutVals <<  std::left << std::setw(12)<< reflection->GetBool(root, fieldDescriptor);
                     break;
                  }
                  case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: {
                     const google::protobuf::EnumValueDescriptor* enumVal = reflection->GetEnum(root, fieldDescriptor);
                     int enumIndex = enumVal->index();
                     soutVals <<  std::left << std::setw(12)<<  enumIndex;
                     break;
                  }
                  default: {
                     soutVals << "   \t";
                     break;
                  }
               }
            }  // end if has field
            else {
               // This field had no data. We should skip it
            }
            if (lastField) {
               // print message divider
               soutFields << msgDivider;
               soutVals << msgDivider;
            }
            else {
               // print field Divider
               soutFields << fieldDivider;
               soutVals << fieldDivider;
            }
         }
      }
   }

   soutFields.width( oldWidth );
   soutFields.setf( oldFlags );
}
Example #30
0
void Hashtable::Generate_Length_Report(/* INOUT */ std::ostream &os) const
//-------------------------------------------------
// Pre : os is valid ostream 
// Post: Length Report is Written to standard output
//-------------------------------------------------
{
	//
	//-- save io stream settings ---
	std::ios_base::fmtflags io_flags = os.flags();
	int io_precision = os.precision();
	char io_fill = os.fill();

	int total_bucket_lengths = 0;
	int total_buckets_with_collisions = 0;


	os  << std::left
		<< std::setw(16)
		<< "PRIMARY BUCKETS:"
		<< std::endl
		<< std::endl;

	for(int bnum =	FIRST_PRIMARY; bnum <= LAST_PRIMARY; bnum++)
	{
		os << std::left
		   << std::setw(7)
		   << "Bucket"
		   << std::setw(2)
		   << bnum + 1
		   << std::setw(3)
		   << ": "
		   << buckets_[bnum].Count()
		   << std::endl;
		
		if (buckets_[bnum].Count() > 1)
		{
			total_buckets_with_collisions++;
			total_bucket_lengths += buckets_[bnum].Count();
		}
	}

	os  << std::left
		<< std::setw(16)
		<< std::endl;

	os  << std::left
		<< std::setw(16)
		<< "Average Chain Length:" 
		<< std::setprecision(0)
		<< std::setw(16)
		<< (total_bucket_lengths / total_buckets_with_collisions)
		<< std::endl
		<< std::endl;


    //
	// --- restore io stream settings ---
	os.flags(io_flags);
	os.precision(io_precision);
	os.fill(io_fill);

	return;
}