<commit_before>/*
 * Copyright (c) 2009 Digital Bazaar, Inc. All rights reserved.
 */
#include "db/data/TemplateInputStream.h"

#include "db/rt/Exception.h"

using namespace db::data;
using namespace db::io;
using namespace db::rt;

#define BUFFER_SIZE 2048
#define EOL         '\n'
#define ESCAPE      '\\'
#define VAR_START   '{'
#define VAR_END     '}'
#define SPECIAL     "\n\\{}"

TemplateInputStream::TemplateInputStream(
   DynamicObject& vars, bool strict, InputStream* is, bool cleanup) :
   FilterInputStream(is, cleanup),
   mTemplate(BUFFER_SIZE),
   mParsed(BUFFER_SIZE),
   mVars(vars),
   mStrict(strict)
{
   resetState();
}

TemplateInputStream::TemplateInputStream(InputStream* is, bool cleanup) :
   FilterInputStream(is, cleanup),
   mTemplate(BUFFER_SIZE),
   mParsed(BUFFER_SIZE),
   mStrict(false)
{
   resetState();
   mVars->setType(Map);
}

TemplateInputStream::~TemplateInputStream()
{
}

void TemplateInputStream::resetState()
{
   mTemplate.clear();
   mParsed.clear();
   mLineNumber = 0;
   mPosition = 0;
   mParsingVariable = false;
   mEscapeOn = false;
   mEndOfStream = false;
}

void TemplateInputStream::setInputStream(InputStream* is, bool cleanup)
{
   FilterInputStream::setInputStream(is, cleanup);
   resetState();
}

void TemplateInputStream::setVariables(DynamicObject& vars, bool strict)
{
   mVars = vars;
   mStrict = strict;
}

/**
 * Checks for a variable error.
 *
 * @param start the start of the data.
 * @param pos the position.
 *
 * @return true if there was no error, false if there was.
 */
static bool checkVariableError(const char* start, const char* pos)
{
   bool rval = true;

   switch(pos[0])
   {
      case EOL:
      case ESCAPE:
      case VAR_START:
      {
         // invalid character in variable name
         rval = false;
         break;
      }
      case VAR_END:
      {
         if((pos - start) == 0)
         {
            // empty variable name
            rval = false;
         }
         break;
      }
      default:
         break;
   }

   if(!rval)
   {
      ExceptionRef e = new Exception(
         "Variable names must start with a letter and contain only "
         "alphanumeric characters.",
         "db.data.TemplateInputStream.InvalidVariable");
      Exception::setLast(e, false);
   }

   return rval;
}

bool TemplateInputStream::process(const char* pos)
{
   bool rval = true;

   if(mParsingVariable)
   {
      // handle invalid variables
      rval = checkVariableError(mTemplate.data(), pos);
   }

   if(rval && mEscapeOn)
   {
      // escape IS on
      // character after ESCAPE must be VAR_START, VAR_END, or ESCAPE
      switch(pos[0])
      {
         case VAR_START:
         case VAR_END:
         case ESCAPE:
         {
            // write escaped character, turn escape off
            mTemplate.get(&mParsed, 1, true);
            mEscapeOn = false;
            mPosition++;
            break;
         }
         default:
         {
            // error, invalid escaped character
            ExceptionRef e = new Exception(
               "Unknown escaped character.",
               "db.data.TemplateInputStream.InvalidEscape");
            e->getDetails()["character"] = pos[0];
            Exception::setLast(e, false);
            rval = false;
            break;
         }
      }
   }
   else if(rval)
   {
      // escape is NOT on
      switch(pos[0])
      {
         case EOL:
         {
            // increase line number, reset position, and get character
            mLineNumber++;
            mPosition = 0;
            mTemplate.get(&mParsed, (pos - mTemplate.data()) + 1, true);
            break;
         }
         case ESCAPE:
         {
            // escape on, write data before ESCAPE and skip it
            mEscapeOn = true;
            mPosition += (pos - mTemplate.data()) + 1;
            mTemplate.get(&mParsed, pos - mTemplate.data(), true);
            mTemplate.clear(1);
            break;
         }
         case VAR_START:
         {
            // parsing variable on, write data before VAR_START and skip it
            mParsingVariable = true;
            mPosition += (pos - mTemplate.data()) + 1;
            mTemplate.get(&mParsed, pos - mTemplate.data(), true);
            mTemplate.clear(1);
            break;
         }
         case VAR_END:
         {
            // no longer parsing variable
            mParsingVariable = false;

            // get variable name, clear VAR_END
            int len = pos - mTemplate.data();
            char varname[len + 1];
            varname[len] = 0;
            mTemplate.get(varname, len);
            mTemplate.clear(1);

            // get variable value
            if(mVars->hasMember(varname))
            {
               // write value out to parsed data buffer
               const char* value = mVars[varname]->getString();
               mParsed.put(value, strlen(value), true);
               mPosition += len + 1;
            }
            else
            {
               if(mStrict)
               {
                  // missing variable
                  ExceptionRef e = new Exception(
                     "The substitution variable is currently not defined. "
                     "Variable substitution cannot occur with an undefined "
                     "variable.",
                     "db.data.TemplateInputStream.VariableNotFound");
                  e->getDetails()["name"] = varname;
                  Exception::setLast(e, false);
                  rval = false;
               }
               else
               {
                  mPosition += len + 1;
               }
            }
            break;
         }
      }
   }

   return rval;
}

const char* TemplateInputStream::getNext(const char* start)
{
   const char* rval = NULL;

   if(mEscapeOn)
   {
      rval = (start[0] == 0 ? NULL : start);
   }
   else
   {
      rval = strpbrk(start, SPECIAL);
   }

   return rval;
}

int TemplateInputStream::read(char* b, int length)
{
   int rval = 0;

   // while no error AND parsed is empty AND NOT when end of stream
   // and the template buffer is empty
   while(rval != -1 && mParsed.isEmpty() &&
         !(mEndOfStream && mTemplate.isEmpty()))
   {
      // see if more template data can be read
      if(!mEndOfStream)
      {
         // get template data from underlying stream
         // leave room for null-terminator
         rval = mTemplate.put(mInputStream, mTemplate.freeSpace() - 1);
         mEndOfStream = (rval == 0);
      }

      // there is data to parse if no IO error and template is not empty
      if(rval != -1 && !mTemplate.isEmpty())
      {
         // add null-terminator to template data to use string functions
         mTemplate.putByte(0, 1, false);

         // process all special characters
         bool parseError = false;
         const char* pos;
         while(!parseError && (pos = getNext(mTemplate.data())) != NULL)
         {
            parseError = !process(pos);
         }

         if(!parseError)
         {
            // corner-case where variable name does not terminate
            if(mParsingVariable && (mTemplate.isFull() || mEndOfStream))
            {
               ExceptionRef e = new Exception(
                  "Incomplete variable or variable name too large.",
                  "db.data.TemplateInputStream.InvalidVariable");
               Exception::setLast(e, false);
               parseError = true;
            }
            else if(!mParsingVariable && !mEscapeOn)
            {
               // no special characters in buffer
               mTemplate.get(&mParsed, mTemplate.length() - 1, false);
            }
         }

         if(parseError)
         {
            // create "near" string that failed parsing
            char nearStr[mTemplate.length()];
            strncpy(nearStr, mTemplate.data(), mTemplate.length());

            // include line, position, and part of string that was parsed
            // in the parse exception
            ExceptionRef e = new Exception(
               "Template parser error.",
               "db.data.TemplateInputStream.ParseError");
            e->getDetails()["line"] = mLineNumber;
            e->getDetails()["position"] = mPosition;
            e->getDetails()["near"] = nearStr;
            Exception::setLast(e, true);
            rval = -1;
         }

         // remove null-terminator
         mTemplate.trim(1);
      }
   }

   // return any parsed data
   if(rval != -1 && !mParsed.isEmpty())
   {
      rval = mParsed.get(b, length);
   }
   // corner-case where template ends in an escape character
   else if(mEndOfStream && mEscapeOn)
   {
      ExceptionRef e = new Exception(
         "Incomplete escape sequence at the end of the template.",
         "db.data.TemplateInputStream.IncompleteTemplate");
      Exception::setLast(e, false);
      rval = -1;
   }

   return rval;
}

bool TemplateInputStream::parse(OutputStream* os)
{
   bool rval = true;

   char tmp[BUFFER_SIZE];
   int numBytes;
   while(rval && (numBytes = read(tmp, BUFFER_SIZE)) > 0)
   {
      rval = os->write(tmp, numBytes);
   }

   if(numBytes < 0)
   {
      rval = false;
   }

   return rval;
}
<commit_msg>Ensure vars is a map.<commit_after>/*
 * Copyright (c) 2009 Digital Bazaar, Inc. All rights reserved.
 */
#include "db/data/TemplateInputStream.h"

#include "db/rt/Exception.h"

using namespace db::data;
using namespace db::io;
using namespace db::rt;

#define BUFFER_SIZE 2048
#define EOL         '\n'
#define ESCAPE      '\\'
#define VAR_START   '{'
#define VAR_END     '}'
#define SPECIAL     "\n\\{}"

TemplateInputStream::TemplateInputStream(
   DynamicObject& vars, bool strict, InputStream* is, bool cleanup) :
   FilterInputStream(is, cleanup),
   mTemplate(BUFFER_SIZE),
   mParsed(BUFFER_SIZE),
   mVars(vars),
   mStrict(strict)
{
   resetState();
   mVars->setType(Map);
}

TemplateInputStream::TemplateInputStream(InputStream* is, bool cleanup) :
   FilterInputStream(is, cleanup),
   mTemplate(BUFFER_SIZE),
   mParsed(BUFFER_SIZE),
   mStrict(false)
{
   resetState();
   mVars->setType(Map);
}

TemplateInputStream::~TemplateInputStream()
{
}

void TemplateInputStream::resetState()
{
   mTemplate.clear();
   mParsed.clear();
   mLineNumber = 0;
   mPosition = 0;
   mParsingVariable = false;
   mEscapeOn = false;
   mEndOfStream = false;
}

void TemplateInputStream::setInputStream(InputStream* is, bool cleanup)
{
   FilterInputStream::setInputStream(is, cleanup);
   resetState();
}

void TemplateInputStream::setVariables(DynamicObject& vars, bool strict)
{
   mVars = vars;
   mStrict = strict;
}

/**
 * Checks for a variable error.
 *
 * @param start the start of the data.
 * @param pos the position.
 *
 * @return true if there was no error, false if there was.
 */
static bool checkVariableError(const char* start, const char* pos)
{
   bool rval = true;

   switch(pos[0])
   {
      case EOL:
      case ESCAPE:
      case VAR_START:
      {
         // invalid character in variable name
         rval = false;
         break;
      }
      case VAR_END:
      {
         if((pos - start) == 0)
         {
            // empty variable name
            rval = false;
         }
         break;
      }
      default:
         break;
   }

   if(!rval)
   {
      ExceptionRef e = new Exception(
         "Variable names must start with a letter and contain only "
         "alphanumeric characters.",
         "db.data.TemplateInputStream.InvalidVariable");
      Exception::setLast(e, false);
   }

   return rval;
}

bool TemplateInputStream::process(const char* pos)
{
   bool rval = true;

   if(mParsingVariable)
   {
      // handle invalid variables
      rval = checkVariableError(mTemplate.data(), pos);
   }

   if(rval && mEscapeOn)
   {
      // escape IS on
      // character after ESCAPE must be VAR_START, VAR_END, or ESCAPE
      switch(pos[0])
      {
         case VAR_START:
         case VAR_END:
         case ESCAPE:
         {
            // write escaped character, turn escape off
            mTemplate.get(&mParsed, 1, true);
            mEscapeOn = false;
            mPosition++;
            break;
         }
         default:
         {
            // error, invalid escaped character
            ExceptionRef e = new Exception(
               "Unknown escaped character.",
               "db.data.TemplateInputStream.InvalidEscape");
            e->getDetails()["character"] = pos[0];
            Exception::setLast(e, false);
            rval = false;
            break;
         }
      }
   }
   else if(rval)
   {
      // escape is NOT on
      switch(pos[0])
      {
         case EOL:
         {
            // increase line number, reset position, and get character
            mLineNumber++;
            mPosition = 0;
            mTemplate.get(&mParsed, (pos - mTemplate.data()) + 1, true);
            break;
         }
         case ESCAPE:
         {
            // escape on, write data before ESCAPE and skip it
            mEscapeOn = true;
            mPosition += (pos - mTemplate.data()) + 1;
            mTemplate.get(&mParsed, pos - mTemplate.data(), true);
            mTemplate.clear(1);
            break;
         }
         case VAR_START:
         {
            // parsing variable on, write data before VAR_START and skip it
            mParsingVariable = true;
            mPosition += (pos - mTemplate.data()) + 1;
            mTemplate.get(&mParsed, pos - mTemplate.data(), true);
            mTemplate.clear(1);
            break;
         }
         case VAR_END:
         {
            // no longer parsing variable
            mParsingVariable = false;

            // get variable name, clear VAR_END
            int len = pos - mTemplate.data();
            char varname[len + 1];
            varname[len] = 0;
            mTemplate.get(varname, len);
            mTemplate.clear(1);

            // get variable value
            if(mVars->hasMember(varname))
            {
               // write value out to parsed data buffer
               const char* value = mVars[varname]->getString();
               mParsed.put(value, strlen(value), true);
               mPosition += len + 1;
            }
            else
            {
               if(mStrict)
               {
                  // missing variable
                  ExceptionRef e = new Exception(
                     "The substitution variable is currently not defined. "
                     "Variable substitution cannot occur with an undefined "
                     "variable.",
                     "db.data.TemplateInputStream.VariableNotFound");
                  e->getDetails()["name"] = varname;
                  Exception::setLast(e, false);
                  rval = false;
               }
               else
               {
                  mPosition += len + 1;
               }
            }
            break;
         }
      }
   }

   return rval;
}

const char* TemplateInputStream::getNext(const char* start)
{
   const char* rval = NULL;

   if(mEscapeOn)
   {
      rval = (start[0] == 0 ? NULL : start);
   }
   else
   {
      rval = strpbrk(start, SPECIAL);
   }

   return rval;
}

int TemplateInputStream::read(char* b, int length)
{
   int rval = 0;

   // while no error AND parsed is empty AND NOT when end of stream
   // and the template buffer is empty
   while(rval != -1 && mParsed.isEmpty() &&
         !(mEndOfStream && mTemplate.isEmpty()))
   {
      // see if more template data can be read
      if(!mEndOfStream)
      {
         // get template data from underlying stream
         // leave room for null-terminator
         rval = mTemplate.put(mInputStream, mTemplate.freeSpace() - 1);
         mEndOfStream = (rval == 0);
      }

      // there is data to parse if no IO error and template is not empty
      if(rval != -1 && !mTemplate.isEmpty())
      {
         // add null-terminator to template data to use string functions
         mTemplate.putByte(0, 1, false);

         // process all special characters
         bool parseError = false;
         const char* pos;
         while(!parseError && (pos = getNext(mTemplate.data())) != NULL)
         {
            parseError = !process(pos);
         }

         if(!parseError)
         {
            // corner-case where variable name does not terminate
            if(mParsingVariable && (mTemplate.isFull() || mEndOfStream))
            {
               ExceptionRef e = new Exception(
                  "Incomplete variable or variable name too large.",
                  "db.data.TemplateInputStream.InvalidVariable");
               Exception::setLast(e, false);
               parseError = true;
            }
            else if(!mParsingVariable && !mEscapeOn)
            {
               // no special characters in buffer
               mTemplate.get(&mParsed, mTemplate.length() - 1, false);
            }
         }

         if(parseError)
         {
            // create "near" string that failed parsing
            char nearStr[mTemplate.length()];
            strncpy(nearStr, mTemplate.data(), mTemplate.length());

            // include line, position, and part of string that was parsed
            // in the parse exception
            ExceptionRef e = new Exception(
               "Template parser error.",
               "db.data.TemplateInputStream.ParseError");
            e->getDetails()["line"] = mLineNumber;
            e->getDetails()["position"] = mPosition;
            e->getDetails()["near"] = nearStr;
            Exception::setLast(e, true);
            rval = -1;
         }

         // remove null-terminator
         mTemplate.trim(1);
      }
   }

   // return any parsed data
   if(rval != -1 && !mParsed.isEmpty())
   {
      rval = mParsed.get(b, length);
   }
   // corner-case where template ends in an escape character
   else if(mEndOfStream && mEscapeOn)
   {
      ExceptionRef e = new Exception(
         "Incomplete escape sequence at the end of the template.",
         "db.data.TemplateInputStream.IncompleteTemplate");
      Exception::setLast(e, false);
      rval = -1;
   }

   return rval;
}

bool TemplateInputStream::parse(OutputStream* os)
{
   bool rval = true;

   char tmp[BUFFER_SIZE];
   int numBytes;
   while(rval && (numBytes = read(tmp, BUFFER_SIZE)) > 0)
   {
      rval = os->write(tmp, numBytes);
   }

   if(numBytes < 0)
   {
      rval = false;
   }

   return rval;
}
<|endoftext|>


<commit_before>#include <specreader.hpp>

#include <backendbuilder.hpp>

#include <helper/keyhelper.hpp>

#include <unordered_set>

namespace kdb
{

namespace tools
{

SpecBackendBuilder::SpecBackendBuilder(BackendBuilderInit const & bbi) :
	MountBackendBuilder (bbi),
	nodes(0)
{}

SpecReader::SpecReader(BackendBuilderInit const & abbi) :
	bbi(abbi)
{}

SpecReader::~SpecReader()
{}

class SpecMountpointReader
{
private:
	KeySet ks;
	Key mp;
	KeySet backendConfig;
	KeySet mountConf;
	typedef std::unordered_map<Key, SpecBackendBuilder> Backends;
	Backends & backends;
	BackendBuilderInit const & bbi;
	SpecBackendBuilder bb;

public:
	SpecMountpointReader (Backends & b, BackendBuilderInit const & bbi_) :
		backends(b),
		bbi (bbi_),
		bb (bbi)
	{
	}

	void processKey (Key const & ck);
	SpecBackendBuilder readMountpointSpecification (KeySet const & cks);
};

namespace
{
bool startsWith(std::string const & str, std::string const & start)
{
	return std::equal(start.begin(), start.end(), str.begin());
}

bool isToBeIgnored (std::string const & name)
{
	// TODO: read from METADATA.ini
	return  startsWith (name, "infos") ||
		startsWith (name, "exports") ||
		startsWith (name, "constants") ||
		startsWith (name, "exports") ||

		startsWith (name, "fallback") ||
		startsWith (name, "override") ||
		startsWith (name, "namespace") ||
		name == "default" ||
		name == "context" ||

		startsWith (name, "callback") ||

		startsWith (name, "binary") ||

		startsWith (name, "opt") ||
		startsWith (name, "env") ||

		startsWith (name, "comment") ||
		startsWith (name, "description") ||
		startsWith (name, "see") ||
		startsWith (name, "rationale") ||
		startsWith (name, "example") ||

		name == "mountpoint" ||
		startsWith (name, "config"
		);
}
}

void SpecMountpointReader::processKey (Key const & ck)
{
	Key k (ck);
	k.rewindMeta();
	Key m;
	while ((m = k.nextMeta()))
	{
		std::string const & cn = "config/needs";
		if (startsWith (m.getName(), cn))
		{
			Key bKey = m.dup();
			bKey.setName ("user"+bKey.getName().substr(cn.length()));
			backendConfig.append (bKey);
		}
		else if (m.getName() == "infos/plugins")
		{
			bb.addPlugins (parseArguments(m.getString()));
		}
		else if (m.getName() == "infos/needs")
		{
			bb.needPlugin (m.getString());
		}
		else if (m.getName() == "infos/recommends")
		{
			bb.recommendPlugin (m.getString());
		}
		else if (isToBeIgnored (m.getName()))
		{}
		else
		{
			bb.needMetadata(m.getName());
		}
	}
}

SpecBackendBuilder SpecMountpointReader::readMountpointSpecification (KeySet const & cks)
{
	ks = cks;
	mp = ks.head().dup();

	Key rmp (mp.dup());
	helper::removeNamespace (rmp);

	bb.setMountpoint (rmp, mountConf);

	processKey (mp);
	bb.nodes ++; // count mp

	ks.lookup (mp, KDB_O_POP);

	ks.rewind(); // we need old fashioned loop, because it can handle ks.cut during iteration
	for (Key k = ks.next(); k; k = ks.next())
	{
		// search for mountpoint
		Key m = k.getMeta<const Key>("mountpoint");
		if (m)
		{
			SpecMountpointReader smr (backends, bbi);
			backends[k] = smr.readMountpointSpecification(ks.cut(k));
			continue;
		}

		processKey (k);
		bb.nodes ++;
	}

	bb.setBackendConfig (backendConfig);
	bb.useConfigFile (mp.getMeta<std::string>("mountpoint"));
	return bb;
}

void SpecReader::readSpecification (KeySet const & cks)
{
	KeySet ks (cks);
	Key mp;

	ks.rewind(); // we need old fashioned loop, because it can handle ks.cut during iteration
	for (Key k = ks.next(); k; k = ks.next())
	{
		// search for mountpoint
		Key m = k.getMeta<const Key>("mountpoint");
		if (m)
		{
			SpecMountpointReader smr (backends, bbi);
			backends[k] = smr.readMountpointSpecification(ks.cut(k));
		}
	}
}

}

}

<commit_msg>specreader: ignore type for generator<commit_after>#include <specreader.hpp>

#include <backendbuilder.hpp>

#include <helper/keyhelper.hpp>

#include <unordered_set>

namespace kdb
{

namespace tools
{

SpecBackendBuilder::SpecBackendBuilder(BackendBuilderInit const & bbi) :
	MountBackendBuilder (bbi),
	nodes(0)
{}

SpecReader::SpecReader(BackendBuilderInit const & abbi) :
	bbi(abbi)
{}

SpecReader::~SpecReader()
{}

class SpecMountpointReader
{
private:
	KeySet ks;
	Key mp;
	KeySet backendConfig;
	KeySet mountConf;
	typedef std::unordered_map<Key, SpecBackendBuilder> Backends;
	Backends & backends;
	BackendBuilderInit const & bbi;
	SpecBackendBuilder bb;

public:
	SpecMountpointReader (Backends & b, BackendBuilderInit const & bbi_) :
		backends(b),
		bbi (bbi_),
		bb (bbi)
	{
	}

	void processKey (Key const & ck);
	SpecBackendBuilder readMountpointSpecification (KeySet const & cks);
};

namespace
{
bool startsWith(std::string const & str, std::string const & start)
{
	return std::equal(start.begin(), start.end(), str.begin());
}

bool isToBeIgnored (std::string const & name)
{
	// TODO: read from METADATA.ini
	return  startsWith (name, "infos") ||
		startsWith (name, "exports") ||
		startsWith (name, "constants") ||
		startsWith (name, "exports") ||

		startsWith (name, "fallback") ||
		startsWith (name, "override") ||
		startsWith (name, "namespace") ||
		name == "default" ||
		name == "context" ||

		startsWith (name, "callback") ||

		startsWith (name, "binary") ||

		// code generator
		startsWith (name, "type") ||
		startsWith (name, "opt") ||
		startsWith (name, "env") ||

		// docu
		startsWith (name, "comment") ||
		startsWith (name, "description") ||
		startsWith (name, "see") ||
		startsWith (name, "rationale") ||
		startsWith (name, "example") ||

		name == "mountpoint" ||
		startsWith (name, "config"
		);
}
}

void SpecMountpointReader::processKey (Key const & ck)
{
	Key k (ck);
	k.rewindMeta();
	Key m;
	while ((m = k.nextMeta()))
	{
		std::string const & cn = "config/needs";
		if (startsWith (m.getName(), cn))
		{
			Key bKey = m.dup();
			bKey.setName ("user"+bKey.getName().substr(cn.length()));
			backendConfig.append (bKey);
		}
		else if (m.getName() == "infos/plugins")
		{
			bb.addPlugins (parseArguments(m.getString()));
		}
		else if (m.getName() == "infos/needs")
		{
			bb.needPlugin (m.getString());
		}
		else if (m.getName() == "infos/recommends")
		{
			bb.recommendPlugin (m.getString());
		}
		else if (isToBeIgnored (m.getName()))
		{}
		else
		{
			bb.needMetadata(m.getName());
		}
	}
}

SpecBackendBuilder SpecMountpointReader::readMountpointSpecification (KeySet const & cks)
{
	ks = cks;
	mp = ks.head().dup();

	Key rmp (mp.dup());
	helper::removeNamespace (rmp);

	bb.setMountpoint (rmp, mountConf);

	processKey (mp);
	bb.nodes ++; // count mp

	ks.lookup (mp, KDB_O_POP);

	ks.rewind(); // we need old fashioned loop, because it can handle ks.cut during iteration
	for (Key k = ks.next(); k; k = ks.next())
	{
		// search for mountpoint
		Key m = k.getMeta<const Key>("mountpoint");
		if (m)
		{
			SpecMountpointReader smr (backends, bbi);
			backends[k] = smr.readMountpointSpecification(ks.cut(k));
			continue;
		}

		processKey (k);
		bb.nodes ++;
	}

	bb.setBackendConfig (backendConfig);
	bb.useConfigFile (mp.getMeta<std::string>("mountpoint"));
	return bb;
}

void SpecReader::readSpecification (KeySet const & cks)
{
	KeySet ks (cks);
	Key mp;

	ks.rewind(); // we need old fashioned loop, because it can handle ks.cut during iteration
	for (Key k = ks.next(); k; k = ks.next())
	{
		// search for mountpoint
		Key m = k.getMeta<const Key>("mountpoint");
		if (m)
		{
			SpecMountpointReader smr (backends, bbi);
			backends[k] = smr.readMountpointSpecification(ks.cut(k));
		}
	}
}

}

}

<|endoftext|>


<commit_before>/*
 * starter_imagelist.cpp
 *
 *  Created on: Nov 23, 2010
 *      Author: Ethan Rublee
 *
 * A starter sample for using opencv, load up an imagelist
 * that was generated with imagelist_creator.cpp
 * easy as CV_PI right?
 */
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <vector>

using namespace cv;
using namespace std;

//hide the local functions in an unnamed namespace
namespace
{
void help(char** av)
{
  cout << "usage:" << av[0] << " image_list.yaml\n"
       << "\tThis is a starter sample, to get you up and going in a copy pasta fashion.\n"
       << "\tThe program reads in an list of images from a yaml or xml file and displays\n"
       << "one at a time\n"
       << "\tTry running imagelist_creator to generate a list of images." << endl;

}

bool readStringList(const string& filename, vector<string>& l)
{
  l.resize(0);
  FileStorage fs(filename, FileStorage::READ);
  if (!fs.isOpened())
    return false;
  FileNode n = fs.getFirstTopLevelNode();
  if (n.type() != FileNode::SEQ)
    return false;
  FileNodeIterator it = n.begin(), it_end = n.end();
  for (; it != it_end; ++it)
    l.push_back((string)*it);
  return true;
}

int process(vector<string> images)
{
  namedWindow("image",CV_WINDOW_KEEPRATIO); //resizable window;
  for (size_t i = 0; i < images.size(); i++)
  {
    Mat image = imread(images[i], CV_LOAD_IMAGE_GRAYSCALE); // do grayscale processing?
    imshow("image",image);
    cout << "Press a key to see the next image in the list." << endl;
    waitKey(); // wait indefinitely for a key to be pressed
  }
  return 0;
}

}

int main(int ac, char** av)
{

  if (ac != 2)
  {
    help(av);
    return 1;
  }
  std::string arg = av[1];
  vector<string> imagelist;

  if (!readStringList(arg,imagelist))
  {
    cerr << "Failed to read image list\n" << endl;
    help(av);
    return 1;
  }

  return process(imagelist);
}
<commit_msg>revamped<commit_after>/*
 * starter_imagelist.cpp
 *
 *  Created on: Nov 23, 2010
 *      Author: Ethan Rublee
 *
 * A starter sample for using opencv, load up an imagelist
 * that was generated with imagelist_creator.cpp
 * easy as CV_PI right?
 */
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <vector>

using namespace cv;
using namespace std;

//hide the local functions in an unnamed namespace
namespace
{
void help(char** av)
{
  cout << "\nThis program gets you started being able to read images from a list in a file\n"
		  "Usage:\n./" << av[0] << " image_list.yaml\n"
       << "\tThis is a starter sample, to get you up and going in a copy pasta fashion.\n"
       << "\tThe program reads in an list of images from a yaml or xml file and displays\n"
       << "one at a time\n"
       << "\tTry running imagelist_creator to generate a list of images.\n"
		"Using OpenCV version %s\n" << CV_VERSION << "\n" << endl;
}

bool readStringList(const string& filename, vector<string>& l)
{
  l.resize(0);
  FileStorage fs(filename, FileStorage::READ);
  if (!fs.isOpened())
    return false;
  FileNode n = fs.getFirstTopLevelNode();
  if (n.type() != FileNode::SEQ)
    return false;
  FileNodeIterator it = n.begin(), it_end = n.end();
  for (; it != it_end; ++it)
    l.push_back((string)*it);
  return true;
}

int process(vector<string> images)
{
  namedWindow("image",CV_WINDOW_KEEPRATIO); //resizable window;
  for (size_t i = 0; i < images.size(); i++)
  {
    Mat image = imread(images[i], CV_LOAD_IMAGE_GRAYSCALE); // do grayscale processing?
    imshow("image",image);
    cout << "Press a key to see the next image in the list." << endl;
    waitKey(); // wait indefinitely for a key to be pressed
  }
  return 0;
}

}

int main(int ac, char** av)
{

  if (ac != 2)
  {
    help(av);
    return 1;
  }
  std::string arg = av[1];
  vector<string> imagelist;

  if (!readStringList(arg,imagelist))
  {
    cerr << "Failed to read image list\n" << endl;
    help(av);
    return 1;
  }

  return process(imagelist);
}
<|endoftext|>


<commit_before>#include "Application.hpp"

// TODO: Remove this when the ResourceManager is done
#include <lug/Graphics/Builder/Camera.hpp>
#include <lug/Graphics/Builder/Light.hpp>
#include <lug/Graphics/Renderer.hpp>
#include <lug/Graphics/Scene/Scene.hpp>
#include <lug/Graphics/Vulkan/Renderer.hpp>
#include <lug/Math/Geometry/Trigonometry.hpp>

Application::Application() : lug::Core::Application::Application{{"hello", {0, 1, 0}}} {
    getRenderWindowInfo().windowInitInfo.title = "Hello";
}

bool Application::init(int argc, char* argv[]) {
    if (!lug::Core::Application::init(argc, argv)) {
        return false;
    }

    // Load scene
    lug::Graphics::Renderer* renderer = _graphics.getRenderer();
    lug::Graphics::Resource::SharedPtr<lug::Graphics::Resource> sceneResource = renderer->getResourceManager()->loadFile("models/DamagedHelmet/DamagedHelmet.gltf");
    if (!sceneResource) {
        return false;
    }

    _scene = lug::Graphics::Resource::SharedPtr<lug::Graphics::Scene::Scene>::cast(sceneResource);

    // Adjust the model
    {
        lug::Graphics::Scene::Node* node = _scene->getSceneNode("UnityGlTF_correctionMatrix");
        node->rotate(lug::Math::Geometry::radians(270.0f), {0.0f, 1.0f, 0.0f}, lug::Graphics::Node::TransformSpace::World);
    }

    // Attach camera
    {
        lug::Graphics::Builder::Camera cameraBuilder(*renderer);

        cameraBuilder.setFovY(45.0f);
        cameraBuilder.setZNear(0.1f);
        cameraBuilder.setZFar(100.0f);

        lug::Graphics::Resource::SharedPtr<lug::Graphics::Render::Camera::Camera> camera = cameraBuilder.build();
        if (!camera) {
            LUG_LOG.error("Application: Can't create the camera");
            return false;
        }

        lug::Graphics::Scene::Node* node = _scene->createSceneNode("camera");
        _scene->getRoot().attachChild(*node);

        node->attachCamera(camera);

        // Set initial position of the camera
        node->setPosition({5.0f, 0.0f, 0.0f}, lug::Graphics::Node::TransformSpace::World);
        // Look at once
        node->getCamera()->lookAt({0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f}, lug::Graphics::Node::TransformSpace::World);

        // Attach the camera node to the mover
        _cameraMover.setTargetNode(*node);
        _cameraMover.setEventSource(*_graphics.getRenderer()->getWindow());

        // Attach camera to RenderView
        {
            auto& renderViews = _graphics.getRenderer()->getWindow()->getRenderViews();

            LUG_ASSERT(renderViews.size() > 0, "There should be at least 1 render view");

            renderViews[0]->attachCamera(camera);
        }
    }

    // Attach ambient light to the root node
    {
        lug::Graphics::Builder::Light lightBuilder(*renderer);

        lightBuilder.setType(lug::Graphics::Render::Light::Type::Ambient);
        lightBuilder.setColor({0.01f, 0.01f, 0.01f, 1.0f});

        lug::Graphics::Resource::SharedPtr<lug::Graphics::Render::Light> light = lightBuilder.build();
        if (!light) {
            LUG_LOG.error("Application: Can't create the ambient light");
            return false;
        }

        _scene->getRoot().attachLight(light);
    }

    // Attach directional light
    {
        lug::Graphics::Builder::Light lightBuilder(*renderer);

        lightBuilder.setType(lug::Graphics::Render::Light::Type::Directional);
        lightBuilder.setColor({1.0f, 1.0f, 1.0f, 1.0f});
        lightBuilder.setDirection({-5.0f, -5.0f, 0.0f});

        lug::Graphics::Resource::SharedPtr<lug::Graphics::Render::Light> light = lightBuilder.build();
        if (!light) {
            LUG_LOG.error("Application: Can't create the directional light");
            return false;
        }

        lug::Graphics::Scene::Node* node = _scene->createSceneNode("light");
        _scene->getRoot().attachChild(*node);

        node->attachLight(light);
    }

    return true;
}

void Application::onEvent(const lug::Window::Event& event) {
    if (event.type == lug::Window::Event::Type::Close) {
        close();
    }
}

void Application::onFrame(const lug::System::Time& elapsedTime) {
    _cameraMover.onFrame(elapsedTime);
}
<commit_msg>Update light for a better rendering<commit_after>#include "Application.hpp"

// TODO: Remove this when the ResourceManager is done
#include <lug/Graphics/Builder/Camera.hpp>
#include <lug/Graphics/Builder/Light.hpp>
#include <lug/Graphics/Renderer.hpp>
#include <lug/Graphics/Scene/Scene.hpp>
#include <lug/Graphics/Vulkan/Renderer.hpp>
#include <lug/Math/Geometry/Trigonometry.hpp>

Application::Application() : lug::Core::Application::Application{{"hello", {0, 1, 0}}} {
    getRenderWindowInfo().windowInitInfo.title = "Hello";
}

bool Application::init(int argc, char* argv[]) {
    if (!lug::Core::Application::init(argc, argv)) {
        return false;
    }

    // Load scene
    lug::Graphics::Renderer* renderer = _graphics.getRenderer();
    lug::Graphics::Resource::SharedPtr<lug::Graphics::Resource> sceneResource = renderer->getResourceManager()->loadFile("models/DamagedHelmet/DamagedHelmet.gltf");
    if (!sceneResource) {
        return false;
    }

    _scene = lug::Graphics::Resource::SharedPtr<lug::Graphics::Scene::Scene>::cast(sceneResource);

    // Adjust the model
    {
        lug::Graphics::Scene::Node* node = _scene->getSceneNode("UnityGlTF_correctionMatrix");
        node->rotate(lug::Math::Geometry::radians(270.0f), {0.0f, 1.0f, 0.0f}, lug::Graphics::Node::TransformSpace::World);
    }

    // Attach camera
    {
        lug::Graphics::Builder::Camera cameraBuilder(*renderer);

        cameraBuilder.setFovY(45.0f);
        cameraBuilder.setZNear(0.1f);
        cameraBuilder.setZFar(100.0f);

        lug::Graphics::Resource::SharedPtr<lug::Graphics::Render::Camera::Camera> camera = cameraBuilder.build();
        if (!camera) {
            LUG_LOG.error("Application: Can't create the camera");
            return false;
        }

        lug::Graphics::Scene::Node* node = _scene->createSceneNode("camera");
        _scene->getRoot().attachChild(*node);

        node->attachCamera(camera);

        // Set initial position of the camera
        node->setPosition({5.0f, 0.0f, 0.0f}, lug::Graphics::Node::TransformSpace::World);
        // Look at once
        node->getCamera()->lookAt({0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f}, lug::Graphics::Node::TransformSpace::World);

        // Attach the camera node to the mover
        _cameraMover.setTargetNode(*node);
        _cameraMover.setEventSource(*_graphics.getRenderer()->getWindow());

        // Attach camera to RenderView
        {
            auto& renderViews = _graphics.getRenderer()->getWindow()->getRenderViews();

            LUG_ASSERT(renderViews.size() > 0, "There should be at least 1 render view");

            renderViews[0]->attachCamera(camera);
        }
    }

    // Attach ambient light to the root node
    {
        lug::Graphics::Builder::Light lightBuilder(*renderer);

        lightBuilder.setType(lug::Graphics::Render::Light::Type::Ambient);
        lightBuilder.setColor({0.01f, 0.01f, 0.01f, 1.0f});

        lug::Graphics::Resource::SharedPtr<lug::Graphics::Render::Light> light = lightBuilder.build();
        if (!light) {
            LUG_LOG.error("Application: Can't create the ambient light");
            return false;
        }

        _scene->getRoot().attachLight(light);
    }

    // Attach directional light
    {
        lug::Graphics::Builder::Light lightBuilder(*renderer);

        lightBuilder.setType(lug::Graphics::Render::Light::Type::Directional);
        lightBuilder.setColor({2.0f, 2.0f, 2.0f, 1.0f});
        lightBuilder.setDirection({-5.0f, -5.0f, -5.0f});

        lug::Graphics::Resource::SharedPtr<lug::Graphics::Render::Light> light = lightBuilder.build();
        if (!light) {
            LUG_LOG.error("Application: Can't create the directional light");
            return false;
        }

        lug::Graphics::Scene::Node* node = _scene->createSceneNode("light");
        _scene->getRoot().attachChild(*node);

        node->attachLight(light);
    }

    return true;
}

void Application::onEvent(const lug::Window::Event& event) {
    if (event.type == lug::Window::Event::Type::Close) {
        close();
    }
}

void Application::onFrame(const lug::System::Time& elapsedTime) {
    _cameraMover.onFrame(elapsedTime);
}
<|endoftext|>


<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2009 Sage Weil <sage@newdream.net>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

using namespace std;

#include "config.h"

#include "common/ConfUtils.h"
#include "common/common_init.h"
#include "auth/Crypto.h"
#include "auth/Auth.h"

void usage()
{
  cout << " usage: [--gen-key] [--name=<name>] [--caps=<filename>] [--list] <filename>" << std::endl;
  exit(1);
}

int main(int argc, const char **argv)
{
  vector<const char*> args;
  argv_to_vec(argc, argv, args);
  env_to_vec(args);
  DEFINE_CONF_VARS(usage);
  common_init(args, "osdmaptool", false, false);

  const char *me = argv[0];

  const char *fn = 0;
  bool gen_key = false;
  bool list = false;
  const char *name = "";
  const char *caps_fn = NULL;

  FOR_EACH_ARG(args) {
    if (CONF_ARG_EQ("gen-key", 'g')) {
      CONF_SAFE_SET_ARG_VAL(&gen_key, OPT_BOOL);
    } else if (CONF_ARG_EQ("name", 'n')) {
      CONF_SAFE_SET_ARG_VAL(&name, OPT_STR);
    } else if (CONF_ARG_EQ("list", 'l')) {
      CONF_SAFE_SET_ARG_VAL(&list, OPT_BOOL);
    } else if (CONF_ARG_EQ("caps", '\0')) {
      CONF_SAFE_SET_ARG_VAL(&caps_fn, OPT_STR);
    } else if (!fn) {
      fn = args[i];
    } else
      usage();
  }
  if (!fn) {
    cerr << me << ": must specify filename" << std::endl;
    usage();
  }

  map<string, EntityAuth> keys_map;
  string s = name;

  if (caps_fn) {
    if (!name || !(*name)) {
      cerr << "can't specify caps without name" << std::endl;
      exit(1);
    }
  }

  CryptoKey key;
  key.create(CEPH_CRYPTO_AES);

  bufferlist bl;
  int r = bl.read_file(fn, true);
  if (r >= 0) {
    try {
      bufferlist::iterator iter = bl.begin();
      ::decode(keys_map, iter);
    } catch (buffer::error *err) {
      cerr << "error reading file " << fn << std::endl;
      exit(1);
    }
  } else if (r == -ENOENT) {
    cout << "creating " << fn << std::endl;
  } else {
    cerr << "can't open " << fn << ": " << strerror(errno) << std::endl;
    exit(1);
  }

  if (gen_key) {
    keys_map[s].key = key;
  }

  if (list) {
    map<string, EntityAuth>::iterator iter = keys_map.begin();
    for (; iter != keys_map.end(); ++iter) {
      string n = iter->first;
      if (n.empty()) {
        cout << "<default key>" << std::endl;
      } else {
        cout << n << std::endl;
      }
      cout << "\tkey: " << iter->second.key << std::endl;
      map<string, bufferlist>::iterator capsiter = iter->second.caps.begin();
      for (; capsiter != iter->second.caps.end(); ++capsiter) {
        bufferlist::iterator dataiter = capsiter->second.begin();
        string caps;
        ::decode(caps, dataiter);
	cout << "\tcaps: [" << capsiter->first << "] " << caps << std::endl;
      }
    }
  }

  if (caps_fn) {
    map<string, bufferlist>& caps = keys_map[s].caps;
    ConfFile *cf = new ConfFile(caps_fn);
    if (!cf->parse()) {
      cerr << "could not parse caps file " << caps_fn << std::endl;
      exit(1);
    }
    const char *key_names[] = { "mon", "osd", "mds", NULL };
    for (int i=0; key_names[i]; i++) {
      char *val;
      cf->read("global", key_names[i], &val, NULL);
      if (val) {
        bufferlist bl;
        ::encode(val, bl);
        string s(key_names[i]);
        caps[s] = bl;
        free(val);
      }
    }
  }

  if (gen_key) {
    bufferlist bl2;
    ::encode(keys_map, bl2);
    r = bl2.write_file(fn);

    if (r < 0) {
      cerr << "could not write " << fn << std::endl;
    }
  }

  return 0;
}
<commit_msg>authtool: add --print-key, -p option<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2009 Sage Weil <sage@newdream.net>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

using namespace std;

#include "config.h"

#include "common/ConfUtils.h"
#include "common/common_init.h"
#include "auth/Crypto.h"
#include "auth/Auth.h"

void usage()
{
  cout << " usage: [--gen-key] [--name=<name>] [--caps=<filename>] [--list] [--print-key] <filename>" << std::endl;
  exit(1);
}

int main(int argc, const char **argv)
{
  vector<const char*> args;
  argv_to_vec(argc, argv, args);
  env_to_vec(args);
  DEFINE_CONF_VARS(usage);
  common_init(args, "osdmaptool", false, false);

  const char *me = argv[0];

  const char *fn = 0;
  bool gen_key = false;
  bool list = false;
  bool print_key = true;
  const char *name = "";
  const char *caps_fn = NULL;

  FOR_EACH_ARG(args) {
    if (CONF_ARG_EQ("gen-key", 'g')) {
      CONF_SAFE_SET_ARG_VAL(&gen_key, OPT_BOOL);
    } else if (CONF_ARG_EQ("name", 'n')) {
      CONF_SAFE_SET_ARG_VAL(&name, OPT_STR);
    } else if (CONF_ARG_EQ("list", 'l')) {
      CONF_SAFE_SET_ARG_VAL(&list, OPT_BOOL);
    } else if (CONF_ARG_EQ("caps", '\0')) {
      CONF_SAFE_SET_ARG_VAL(&caps_fn, OPT_STR);
    } else if (CONF_ARG_EQ("print-key", 'p')) {
      CONF_SAFE_SET_ARG_VAL(&print_key, OPT_BOOL);
    } else if (!fn) {
      fn = args[i];
    } else
      usage();
  }
  if (!fn) {
    cerr << me << ": must specify filename" << std::endl;
    usage();
  }

  map<string, EntityAuth> keys_map;
  string s = name;

  if (caps_fn) {
    if (!name || !(*name)) {
      cerr << "can't specify caps without name" << std::endl;
      exit(1);
    }
  }

  bufferlist bl;
  int r = bl.read_file(fn, true);
  if (r >= 0) {
    try {
      bufferlist::iterator iter = bl.begin();
      ::decode(keys_map, iter);
    } catch (buffer::error *err) {
      cerr << "error reading file " << fn << std::endl;
      exit(1);
    }
  } else if (r == -ENOENT) {
    cout << "creating " << fn << std::endl;
  } else {
    cerr << "can't open " << fn << ": " << strerror(errno) << std::endl;
    exit(1);
  }

  if (gen_key) {
    CryptoKey key;
    key.create(CEPH_CRYPTO_AES);
    keys_map[s].key = key;
  } else if (list) {
    map<string, EntityAuth>::iterator iter = keys_map.begin();
    for (; iter != keys_map.end(); ++iter) {
      string n = iter->first;
      if (n.empty()) {
        cout << "<default key>" << std::endl;
      } else {
        cout << n << std::endl;
      }
      cout << "\tkey: " << iter->second.key << std::endl;
      map<string, bufferlist>::iterator capsiter = iter->second.caps.begin();
      for (; capsiter != iter->second.caps.end(); ++capsiter) {
        bufferlist::iterator dataiter = capsiter->second.begin();
        string caps;
        ::decode(caps, dataiter);
	cout << "\tcaps: [" << capsiter->first << "] " << caps << std::endl;
      }
    }
  } else if (print_key) {
    if (keys_map.count(s))
      cout << keys_map[s].key << std::endl;
    else
      cerr << "entity " << s << " not found" << std::endl;
  }

  if (caps_fn) {
    map<string, bufferlist>& caps = keys_map[s].caps;
    ConfFile *cf = new ConfFile(caps_fn);
    if (!cf->parse()) {
      cerr << "could not parse caps file " << caps_fn << std::endl;
      exit(1);
    }
    const char *key_names[] = { "mon", "osd", "mds", NULL };
    for (int i=0; key_names[i]; i++) {
      char *val;
      cf->read("global", key_names[i], &val, NULL);
      if (val) {
        bufferlist bl;
        ::encode(val, bl);
        string s(key_names[i]);
        caps[s] = bl;
        free(val);
      }
    }
  }

  if (gen_key) {
    bufferlist bl2;
    ::encode(keys_map, bl2);
    r = bl2.write_file(fn);

    if (r < 0) {
      cerr << "could not write " << fn << std::endl;
    }
  }

  return 0;
}
<|endoftext|>


<commit_before>#pragma once
#include <string>
#include <sstream>
#include "But/assert.hpp"
#include "But/NotNull.hpp"
#include "But/Exception.hpp"
#include "detail/parse.hpp"
#include "Invalid.hpp"
#include "detail/argumentsCount.hpp"

namespace But
{
namespace Format
{

/** @brief represents a parsed format, from a given text with. set of parameters can be applied to get a final message.
 *  @note format of the parameter is defined by its type, via toFieldInfo() function. it
 *        is not specified for a given type usage. this way formatting for a given parameters
 *        is always constant.
 */
template<size_t ArgumentsCount, size_t MaxSegments>
class ParsedCompiletime final
{
public:
  using const_iterator = typename Container::ArrayWithSize<detail::Segment, MaxSegments>::const_iterator;

  /** @brief parses input format and constructs the object.
   *  @param format - format is a string with positional arguments, in a form:
   *          $N - expands to N-th argument.
   *          ${N} - the same as $N.
   *          ${N#some text} - the same as $N, but allowing some textual description along (useful for translations!).
   *          $$ - liternal '$' character.
   *  @note all numbers are 0-based (i.e. 1st argument has index 0).
   *  @note ADL-based to_string(x) free function is used to convert 'X' into a string. strings are then used to add to a stream.
   */
  constexpr explicit ParsedCompiletime(char const* format):
    ps_{ detail::parseCt<MaxSegments>(format) },
    format_{format}
  {
    BUT_ASSERT( expectedArguments() == detail::argumentsCount(ps_) );
  }

  auto inputFormat() const { return format_; }
  static constexpr size_t expectedArguments() { return ArgumentsCount; }

  const_iterator begin() const { return ps_.segments_.begin(); }
  const_iterator end() const { return ps_.segments_.end(); }

private:
  const detail::ParsedFormatCt<MaxSegments> ps_;
  char const* format_;
};

/** @brief ParsedCompiletime-equivalent, but working with runtime arguments.
 */
class ParsedRuntime final
{
public:
  using const_iterator = std::vector<detail::Segment>::const_iterator;

  BUT_DEFINE_EXCEPTION(ArityError, Exception, "invalid number of arguments for a format");

  explicit ParsedRuntime(std::string format):
    format_{ But::makeSharedNN<std::string>( std::move(format) ) },
    ps_{ detail::parseRt( format_->c_str() ) },
    argumentsCount_{ detail::argumentsCount(ps_) }
  { }

  auto& inputFormat() const { return format_; }
  size_t expectedArguments() const { return argumentsCount_; }
  void validateArgumentsCount(const size_t arguments) const
  {
    if( arguments != expectedArguments() )
      BUT_THROW(ArityError, "expected " << expectedArguments() << " arguments - got " << arguments << " instead");
  }

  const_iterator begin() const { return ps_.segments_.begin(); }
  const_iterator end() const { return ps_.segments_.end(); }

private:
  const But::NotNullShared<const std::string> format_;  // NOTE: shared pointer is needed since string make use of SSO!
  const detail::ParsedFormatRt ps_;
  const size_t argumentsCount_;
};

}
}
<commit_msg>all runtime parsed format is now kept in shared pointer<commit_after>#pragma once
#include <string>
#include <sstream>
#include "But/assert.hpp"
#include "But/NotNull.hpp"
#include "But/Exception.hpp"
#include "detail/parse.hpp"
#include "Invalid.hpp"
#include "detail/argumentsCount.hpp"

namespace But
{
namespace Format
{

/** @brief represents a parsed format, from a given text with. set of parameters can be applied to get a final message.
 *  @note format of the parameter is defined by its type, via toFieldInfo() function. it
 *        is not specified for a given type usage. this way formatting for a given parameters
 *        is always constant.
 */
template<size_t ArgumentsCount, size_t MaxSegments>
class ParsedCompiletime final
{
public:
  using const_iterator = typename Container::ArrayWithSize<detail::Segment, MaxSegments>::const_iterator;

  /** @brief parses input format and constructs the object.
   *  @param format - format is a string with positional arguments, in a form:
   *          $N - expands to N-th argument.
   *          ${N} - the same as $N.
   *          ${N#some text} - the same as $N, but allowing some textual description along (useful for translations!).
   *          $$ - liternal '$' character.
   *  @note all numbers are 0-based (i.e. 1st argument has index 0).
   *  @note ADL-based to_string(x) free function is used to convert 'X' into a string. strings are then used to add to a stream.
   */
  constexpr explicit ParsedCompiletime(char const* format):
    ps_{ detail::parseCt<MaxSegments>(format) },
    format_{format}
  {
    BUT_ASSERT( expectedArguments() == detail::argumentsCount(ps_) );
  }

  auto inputFormat() const { return format_; }
  static constexpr size_t expectedArguments() { return ArgumentsCount; }

  const_iterator begin() const { return ps_.segments_.begin(); }
  const_iterator end() const { return ps_.segments_.end(); }

private:
  const detail::ParsedFormatCt<MaxSegments> ps_;
  char const* format_;
};

/** @brief ParsedCompiletime-equivalent, but working with runtime arguments.
 */
class ParsedRuntime final
{
private:
  struct Data final
  {
    explicit Data(std::string&& format):
      format_{ std::move(format) },
      ps_{ detail::parseRt( format_.c_str() ) },
      argumentsCount_{ detail::argumentsCount(ps_) }
    { }

    Data(Data const&) = delete;
    Data& operator=(Data const&) = delete;

    Data(Data&&) = delete;
    Data& operator=(Data&&) = delete;

    const std::string format_;
    const detail::ParsedFormatRt ps_;
    const size_t argumentsCount_;
  };

public:
  using const_iterator = std::vector<detail::Segment>::const_iterator;

  BUT_DEFINE_EXCEPTION(ArityError, Exception, "invalid number of arguments for a format");

  explicit ParsedRuntime(std::string format):
    data_{ makeSharedNN<Data>( std::move(format) ) }
  { }

  auto& inputFormat() const { return data_->format_; }
  size_t expectedArguments() const { return data_->argumentsCount_; }
  void validateArgumentsCount(const size_t arguments) const
  {
    if( arguments != expectedArguments() )
      BUT_THROW(ArityError, "expected " << expectedArguments() << " arguments - got " << arguments << " instead");
  }

  const_iterator begin() const { return data_->ps_.segments_.begin(); }
  const_iterator end() const { return data_->ps_.segments_.end(); }

private:
  // NOTE: shared pointer is needed since string make use of SSO. therefor we can keep all the state shared, for free.
  But::NotNullShared<const Data> data_;
};

}
}
<|endoftext|>


<commit_before>#include "numeric/numeric.h"
#include "numeric/numeric_op.h"
#include "numeric/numeric_value.h"
#include "numeric/numeric_width.h"
#include "numeric/wide_op.h"

#include "iroha/test_util.h"

#include <assert.h>
#include <iostream>

using namespace iroha;
using namespace std;

namespace {

class Tool {
public:
  static uint64_t GetValue(const Numeric &n, int idx) {
    ASSERT(n.type_.IsWide());
    return n.GetArray().value_[idx];
  }
};

}  // namespace

void Shift() {
  TEST_CASE("Shift");
  Numeric n;
  n.type_.SetWidth(512);
  Op::Clear(n.type_, n.GetMutableArray());
  n.SetValue0(0xfffffffffffffff0ULL);
  cout << "n=" << n.Format() << "\n";
  ASSERT_EQ(0xfffffffffffffff0UL, n.GetValue0());
  ASSERT_EQ(0, Tool::GetValue(n, 1));

  Numeric m;
  m.type_.SetWidth(512);
  Op::Clear(m.type_, m.GetMutableArray());
  // Left
  cout << "Left Shift\n";
  WideOp::Shift(n.GetArray(), 1, true, m.GetMutableArray());
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(1, Tool::GetValue(m, 1));

  WideOp::Shift(n.GetArray(), 64, true, m.GetMutableArray());
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(0, Tool::GetValue(m, 0));
  ASSERT_EQ(Tool::GetValue(n, 0), Tool::GetValue(m, 1));

  WideOp::Shift(n.GetArray(), 65, true, m.GetMutableArray());
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(1, Tool::GetValue(m, 2));

  WideOp::Shift(n.GetArray(), 385, true, m.GetMutableArray());
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(1, Tool::GetValue(m, 7));

  // Right
  cout << "Right Shift\n";
  n = m;
  WideOp::Shift(n.GetArray(), 0, false, m.GetMutableArray());
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(1, Tool::GetValue(m, 7));

  WideOp::Shift(n.GetArray(), 64, false, m.GetMutableArray());
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(1, Tool::GetValue(m, 6));

  WideOp::Shift(n.GetArray(), 65, false, m.GetMutableArray());
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(0xfffffffffffffff0ULL, Tool::GetValue(m, 5));
}

void Concat() {
  TEST_CASE("Concat");
  Numeric m, n;
  Numeric::Clear(m.type_, m.GetMutableArray());
  m.type_.SetWidth(64);
  m.SetValue0(0x5555555555555550ULL);
  Numeric::Clear(n.type_, n.GetMutableArray());
  n.type_.SetWidth(63);
  n.SetValue0(0x5555555555555550ULL);
  Numeric r;
  Op::Concat(m.GetArray(), m.type_, n.GetArray(), n.type_,
	     r.GetMutableArray(), &r.type_);
  cout << "r=" << r.Format() << "\n";
  ASSERT(r.type_.GetWidth() == 127);
  ASSERT_EQ(0x5555555555555550ULL, Tool::GetValue(r, 0));
  ASSERT_EQ(0x2aaaaaaaaaaaaaa8ULL, Tool::GetValue(r, 1));
}

void Fixup() {
  TEST_CASE("Fixup");
  Numeric n;
  Numeric::Clear(n.type_, n.GetMutableArray());
  n.type_.SetWidth(68);
  n.SetValue0(0xfffffffffffffff0ULL);
  Numeric m;
  WideOp::Shift(n.GetArray(), 16, true, m.GetMutableArray());
  m.type_ = n.type_;
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(65535, Tool::GetValue(m, 1));

  Op::FixupValueWidth(m.type_, m.GetMutableArray());
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(15, Tool::GetValue(m, 1));
}

void Basic() {
  TEST_CASE("Basic");
  Numeric n;
  n.type_.SetWidth(64);
  n.type_.SetIsSigned(true);
  n.SetValue0(0xfffffffffffffff0ULL);
  cout << "n=" << n.Format() << "\n";
  n.SetValue0(15);
  cout << "n=" << n.Format() << "\n";

  Numeric w;
  w.type_.SetWidth(512);
  Op::Clear(w.type_, w.GetMutableArray());
  cout << "w=" << w.Format() << "\n";
  ASSERT(Op::IsZero(w.type_, w.GetArray()));
}

void ExtraWide() {
  TEST_CASE("ExtraWide");
  Numeric n;
  Numeric::Clear(n.type_, n.GetMutableArray());
  n.SetValue0(2);
  n.type_.SetWidth(1024);
  Numeric::MayExpandStorage(nullptr, &n);
  ASSERT(n.GetValue0() == 2);

  Numeric nn;
  nn.type_.SetWidth(768);
  Numeric::MayPopulateStorage(nn.type_, nullptr, nn.GetMutableArray());

  Op::SelectBits(n.GetArray(), n.type_,
		 768, 1, nn.GetMutableArray(), nullptr);
  ASSERT(nn.GetValue0() == 1);

  Numeric m;
  Op::SelectBits(n.GetArray(), n.type_,
		 512, 1, m.GetMutableArray(), nullptr);
  ASSERT(m.GetValue0() == 1);
}

void Set() {
  TEST_CASE("Set");
  Numeric s;
  Numeric::Clear(s.type_, s.GetMutableArray());
  s.SetValue0(1);
  s.type_.SetWidth(64);

  Numeric d;
  d.type_.SetWidth(64);
  Op::Set(s.type_, s.GetArray(), d.type_, d.GetMutableArray());
  ASSERT(d.GetValue0() == 1);
}

void Eq() {
  TEST_CASE("Eq");
  Numeric n1, n2;
  n1.type_.SetWidth(8);
  n1.SetValue0(0x105);
  n2.type_.SetWidth(8);
  n2.SetValue0(0x05);
  ASSERT(Op::Eq(n1.type_, n1.GetArray(), n2.GetArray()));
  n1.type_.SetWidth(9);
  ASSERT(!Op::Eq(n1.type_, n1.GetArray(), n2.GetArray()));
}

int main(int argc, char **argv) {
  cout << "sizeof(width)=" << sizeof(NumericWidth) << "\n";
  cout << "sizeof(numeric)=" << sizeof(Numeric) << "\n";

  Basic();
  Shift();
  Concat();
  Fixup();
  ExtraWide();
  Set();
  Eq();

  return 0;
}
<commit_msg>Add a test of numeric parser.<commit_after>#include "numeric/numeric.h"
#include "numeric/numeric_literal.h"
#include "numeric/numeric_op.h"
#include "numeric/numeric_value.h"
#include "numeric/numeric_width.h"
#include "numeric/wide_op.h"

#include "iroha/test_util.h"

#include <assert.h>
#include <iostream>

using namespace iroha;
using namespace std;

namespace {

class Tool {
public:
  static uint64_t GetValue(const Numeric &n, int idx) {
    ASSERT(n.type_.IsWide());
    return n.GetArray().value_[idx];
  }
};

}  // namespace

void Shift() {
  TEST_CASE("Shift");
  Numeric n;
  n.type_.SetWidth(512);
  Op::Clear(n.type_, n.GetMutableArray());
  n.SetValue0(0xfffffffffffffff0ULL);
  cout << "n=" << n.Format() << "\n";
  ASSERT_EQ(0xfffffffffffffff0UL, n.GetValue0());
  ASSERT_EQ(0, Tool::GetValue(n, 1));

  Numeric m;
  m.type_.SetWidth(512);
  Op::Clear(m.type_, m.GetMutableArray());
  // Left
  cout << "Left Shift\n";
  WideOp::Shift(n.GetArray(), 1, true, m.GetMutableArray());
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(1, Tool::GetValue(m, 1));

  WideOp::Shift(n.GetArray(), 64, true, m.GetMutableArray());
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(0, Tool::GetValue(m, 0));
  ASSERT_EQ(Tool::GetValue(n, 0), Tool::GetValue(m, 1));

  WideOp::Shift(n.GetArray(), 65, true, m.GetMutableArray());
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(1, Tool::GetValue(m, 2));

  WideOp::Shift(n.GetArray(), 385, true, m.GetMutableArray());
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(1, Tool::GetValue(m, 7));

  // Right
  cout << "Right Shift\n";
  n = m;
  WideOp::Shift(n.GetArray(), 0, false, m.GetMutableArray());
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(1, Tool::GetValue(m, 7));

  WideOp::Shift(n.GetArray(), 64, false, m.GetMutableArray());
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(1, Tool::GetValue(m, 6));

  WideOp::Shift(n.GetArray(), 65, false, m.GetMutableArray());
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(0xfffffffffffffff0ULL, Tool::GetValue(m, 5));
}

void Concat() {
  TEST_CASE("Concat");
  Numeric m, n;
  Numeric::Clear(m.type_, m.GetMutableArray());
  m.type_.SetWidth(64);
  m.SetValue0(0x5555555555555550ULL);
  Numeric::Clear(n.type_, n.GetMutableArray());
  n.type_.SetWidth(63);
  n.SetValue0(0x5555555555555550ULL);
  Numeric r;
  Op::Concat(m.GetArray(), m.type_, n.GetArray(), n.type_,
	     r.GetMutableArray(), &r.type_);
  cout << "r=" << r.Format() << "\n";
  ASSERT(r.type_.GetWidth() == 127);
  ASSERT_EQ(0x5555555555555550ULL, Tool::GetValue(r, 0));
  ASSERT_EQ(0x2aaaaaaaaaaaaaa8ULL, Tool::GetValue(r, 1));
}

void Fixup() {
  TEST_CASE("Fixup");
  Numeric n;
  Numeric::Clear(n.type_, n.GetMutableArray());
  n.type_.SetWidth(68);
  n.SetValue0(0xfffffffffffffff0ULL);
  Numeric m;
  WideOp::Shift(n.GetArray(), 16, true, m.GetMutableArray());
  m.type_ = n.type_;
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(65535, Tool::GetValue(m, 1));

  Op::FixupValueWidth(m.type_, m.GetMutableArray());
  cout << "m=" << m.Format() << "\n";
  ASSERT_EQ(15, Tool::GetValue(m, 1));
}

void Basic() {
  TEST_CASE("Basic");
  Numeric n;
  n.type_.SetWidth(64);
  n.type_.SetIsSigned(true);
  n.SetValue0(0xfffffffffffffff0ULL);
  cout << "n=" << n.Format() << "\n";
  n.SetValue0(15);
  cout << "n=" << n.Format() << "\n";

  Numeric w;
  w.type_.SetWidth(512);
  Op::Clear(w.type_, w.GetMutableArray());
  cout << "w=" << w.Format() << "\n";
  ASSERT(Op::IsZero(w.type_, w.GetArray()));
}

void ExtraWide() {
  TEST_CASE("ExtraWide");
  Numeric n;
  Numeric::Clear(n.type_, n.GetMutableArray());
  n.SetValue0(2);
  n.type_.SetWidth(1024);
  Numeric::MayExpandStorage(nullptr, &n);
  ASSERT(n.GetValue0() == 2);

  Numeric nn;
  nn.type_.SetWidth(768);
  Numeric::MayPopulateStorage(nn.type_, nullptr, nn.GetMutableArray());

  Op::SelectBits(n.GetArray(), n.type_,
		 768, 1, nn.GetMutableArray(), nullptr);
  ASSERT(nn.GetValue0() == 1);

  Numeric m;
  Op::SelectBits(n.GetArray(), n.type_,
		 512, 1, m.GetMutableArray(), nullptr);
  ASSERT(m.GetValue0() == 1);
}

void Set() {
  TEST_CASE("Set");
  Numeric s;
  Numeric::Clear(s.type_, s.GetMutableArray());
  s.SetValue0(1);
  s.type_.SetWidth(64);

  Numeric d;
  d.type_.SetWidth(64);
  Op::Set(s.type_, s.GetArray(), d.type_, d.GetMutableArray());
  ASSERT(d.GetValue0() == 1);
}

void Eq() {
  TEST_CASE("Eq");
  Numeric n1, n2;
  n1.type_.SetWidth(8);
  n1.SetValue0(0x105);
  n2.type_.SetWidth(8);
  n2.SetValue0(0x05);
  ASSERT(Op::Eq(n1.type_, n1.GetArray(), n2.GetArray()));
  n1.type_.SetWidth(9);
  ASSERT(!Op::Eq(n1.type_, n1.GetArray(), n2.GetArray()));
}

void Literal() {
  NumericLiteral nl;
  nl = nl.Parse("123");
  ASSERT(nl.value == 123);
  ASSERT(nl.width < 0);
  nl = nl.Parse("0b1010");
  ASSERT(nl.value == 10);
  ASSERT(nl.width == 4);
  nl = nl.Parse("0xa0");
  ASSERT(nl.value == 160);
  ASSERT(nl.width < 0);
}

int main(int argc, char **argv) {
  cout << "sizeof(width)=" << sizeof(NumericWidth) << "\n";
  cout << "sizeof(numeric)=" << sizeof(Numeric) << "\n";

  Basic();
  Shift();
  Concat();
  Fixup();
  ExtraWide();
  Set();
  Eq();
  Literal();

  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: app.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: kso $ $Date: 2001-02-12 16:50:50 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "app.hxx"
#include "wrapper.hxx"

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#include <offmgr/app.hxx>
#include <comphelper/processfactory.hxx>
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif

#include <setup2/installer.hxx>
#include <svtools/pathoptions.hxx>
#include <unotools/configmgr.hxx>
#include <vcl/msgbox.hxx>

#define DEFINE_CONST_UNICODE(CONSTASCII)        UniString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII##))

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

void PreloadConfigTrees()
{
    // these tree are preloaded to get a faster startup for the office
    Sequence <rtl::OUString> aPreloadPathList(6);
    aPreloadPathList[0] =  rtl::OUString::createFromAscii("org.openoffice.Office.Common");
    aPreloadPathList[1] =  rtl::OUString::createFromAscii("org.openoffice.ucb.Configuration");
    aPreloadPathList[2] =  rtl::OUString::createFromAscii("org.openoffice.Office.Writer");
    aPreloadPathList[3] =  rtl::OUString::createFromAscii("org.openoffice.Office.WriterWeb");
    aPreloadPathList[4] =  rtl::OUString::createFromAscii("org.openoffice.Office.Calc");
    aPreloadPathList[5] =  rtl::OUString::createFromAscii("org.openoffice.Office.Impress");

    Reference< XMultiServiceFactory > xProvider(
            ::comphelper::getProcessServiceFactory()->createInstance(::rtl::OUString::createFromAscii("com.sun.star.configuration.ConfigurationProvider")), UNO_QUERY);

    Any aValue;
    aValue <<= aPreloadPathList;

    Reference < com::sun::star::beans::XPropertySet > (xProvider, UNO_QUERY)->setPropertyValue(rtl::OUString::createFromAscii("PrefetchNodes"), aValue );
}

void ReplaceStringHookProc( UniString& rStr )
{
    static String aBrandName;
    static String aVersion;
    static String aExtension;

    static int nAll = 0, nPro = 0;

    if ( !aBrandName.Len() )
    {
        Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );
        rtl::OUString aTmp;
        aRet >>= aTmp;
        aBrandName = aTmp;

        aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTVERSION );
        aRet >>= aTmp;
        aVersion = aTmp;

        aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTEXTENSION );
        aRet >>= aTmp;
        aExtension = aTmp;
    }

    nAll++;
    if ( rStr.SearchAscii( "%PRODUCT" ) != STRING_NOTFOUND )
    {
        nPro++;
        rStr.SearchAndReplaceAllAscii( "%PRODUCTNAME", aBrandName );
        rStr.SearchAndReplaceAllAscii( "%PRODUCTVERSION", aVersion );
        rStr.SearchAndReplaceAllAscii( "%PRODUCTEXTENSION", aExtension );
    }
}

Desktop aDesktop;

Desktop::Desktop()
{
}

void Desktop::Main()
{
    ResMgr::SetReadStringHook( ReplaceStringHookProc );
    SetAppName( DEFINE_CONST_UNICODE("soffice") );
//  Read the common configuration items for optimization purpose
    PreloadConfigTrees();

    Installer* pInstaller = new Installer;
    pInstaller->InitializeInstallation( Application::GetAppFileName() );
    delete pInstaller;

    SvtPathOptions* pPathOptions = new SvtPathOptions;
    RegisterServices();
    OfficeWrapper* pWrapper = new OfficeWrapper( ::comphelper::getProcessServiceFactory() );
//    Reference < XComponent > xWrapper( ::utl::getProcessServiceFactory()->createInstance( DEFINE_CONST_UNICODE("com.sun.star.office.OfficeWrapper" ) ), UNO_QUERY );
    SfxApplicationClass::Main();
//    xWrapper->dispose();

    if( pWrapper!=NULL)
    {
        delete pWrapper;
        pWrapper=NULL;
    }

    delete pPathOptions;
    utl::ConfigManager::RemoveConfigManager();
}

void Desktop::SystemSettingsChanging( AllSettings& rSettings, Window* pFrame )
{
    OFF_APP()->SystemSettingsChanging( rSettings, pFrame );
}

<commit_msg>#84160# & #84161# first initialization for the local soffice<commit_after>/*************************************************************************
 *
 *  $RCSfile: app.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: mav $ $Date: 2001-02-23 11:22:36 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "app.hxx"
#include "wrapper.hxx"

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#include <offmgr/app.hxx>
#include <comphelper/processfactory.hxx>
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif

#include <setup2/installer.hxx>
#include <svtools/pathoptions.hxx>
#include <unotools/configmgr.hxx>
#include <vcl/msgbox.hxx>

#define DEFINE_CONST_UNICODE(CONSTASCII)        UniString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII##))

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

void PreloadConfigTrees()
{
    // these tree are preloaded to get a faster startup for the office
    Sequence <rtl::OUString> aPreloadPathList(6);
    aPreloadPathList[0] =  rtl::OUString::createFromAscii("org.openoffice.Office.Common");
    aPreloadPathList[1] =  rtl::OUString::createFromAscii("org.openoffice.ucb.Configuration");
    aPreloadPathList[2] =  rtl::OUString::createFromAscii("org.openoffice.Office.Writer");
    aPreloadPathList[3] =  rtl::OUString::createFromAscii("org.openoffice.Office.WriterWeb");
    aPreloadPathList[4] =  rtl::OUString::createFromAscii("org.openoffice.Office.Calc");
    aPreloadPathList[5] =  rtl::OUString::createFromAscii("org.openoffice.Office.Impress");

    Reference< XMultiServiceFactory > xProvider(
            ::comphelper::getProcessServiceFactory()->createInstance(::rtl::OUString::createFromAscii("com.sun.star.configuration.ConfigurationProvider")), UNO_QUERY);

    Any aValue;
    aValue <<= aPreloadPathList;

    Reference < com::sun::star::beans::XPropertySet > (xProvider, UNO_QUERY)->setPropertyValue(rtl::OUString::createFromAscii("PrefetchNodes"), aValue );
}

void ReplaceStringHookProc( UniString& rStr )
{
    static String aBrandName;
    static String aVersion;
    static String aExtension;

    static int nAll = 0, nPro = 0;

    if ( !aBrandName.Len() )
    {
        Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );
        rtl::OUString aTmp;
        aRet >>= aTmp;
        aBrandName = aTmp;

        aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTVERSION );
        aRet >>= aTmp;
        aVersion = aTmp;

        aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTEXTENSION );
        aRet >>= aTmp;
        aExtension = aTmp;
    }

    nAll++;
    if ( rStr.SearchAscii( "%PRODUCT" ) != STRING_NOTFOUND )
    {
        nPro++;
        rStr.SearchAndReplaceAllAscii( "%PRODUCTNAME", aBrandName );
        rStr.SearchAndReplaceAllAscii( "%PRODUCTVERSION", aVersion );
        rStr.SearchAndReplaceAllAscii( "%PRODUCTEXTENSION", aExtension );
    }
}

Desktop aDesktop;

Desktop::Desktop()
{
}

void Desktop::Main()
{
    ResMgr::SetReadStringHook( ReplaceStringHookProc );
    SetAppName( DEFINE_CONST_UNICODE("soffice") );

    bool bTerminate = false;
    int nParamCount = GetCommandLineParamCount();

    for( int nActParam = 0; nActParam < nParamCount ; nActParam++ )
    {
        String sActParam = GetCommandLineParam( nActParam );
        if( sActParam.EqualsIgnoreCaseAscii("-terminate_after_init") )
        {
            bTerminate = true;
            break;
        }
    }

//  Read the common configuration items for optimization purpose
//  do not do it if terminate flag was specified, to avoid exception
    if( !bTerminate )
        PreloadConfigTrees();

//  The only step that should be done if terminate flag was specified
//  Typically called by the plugin only
    Installer* pInstaller = new Installer;
    pInstaller->InitializeInstallation( Application::GetAppFileName() );
    delete pInstaller;

    if( !bTerminate )
    {
        SvtPathOptions* pPathOptions = new SvtPathOptions;
        RegisterServices();
        OfficeWrapper* pWrapper = new OfficeWrapper( ::comphelper::getProcessServiceFactory() );
//      Reference < XComponent > xWrapper( ::utl::getProcessServiceFactory()->createInstance( DEFINE_CONST_UNICODE("com.sun.star.office.OfficeWrapper" ) ), UNO_QUERY );
        SfxApplicationClass::Main();
//      xWrapper->dispose();

        if( pWrapper!=NULL)
        {
            delete pWrapper;
            pWrapper=NULL;
        }

        delete pPathOptions;
    }

    utl::ConfigManager::RemoveConfigManager();
}

void Desktop::SystemSettingsChanging( AllSettings& rSettings, Window* pFrame )
{
    OFF_APP()->SystemSettingsChanging( rSettings, pFrame );
}

<|endoftext|>


<commit_before>#include "IntakeBall.h"

/**
 * Namespace commands with implementation
 * of IntakeBall command functions.
 */
namespace commands
{

// Constructor:
IntakeBall::IntakeBall(Intake * intake) : Command("IntakeBall")
{
	intake_ = intake;
	can_run_ = true;
	SetInterruptible(true);
}

// Main functions:
void IntakeBall::Initialize()
{
	std::cout << "Intake : IntakeBall : Started" << std::endl;
	if (intake_->GetState() == State_t::OFF)
	{
		intake_->SetState(State_t::TAKING);
		intake_->TakeBall(true);
	}
	else
	{
		std::cout << "ERROR: Invalid starting state (Should be \"OFF\")" << std::endl;
		Cancel();
	}
}

bool IntakeBall::IsFinished()
{
	return intake_->CheckSwitch();
}

void IntakeBall::End()
{
	std::cout << "Intake : IntakeBall : Ended" << std::endl;
	intake_->Stop();
	intake_->SetState(State_t::HOLDING);
}

void IntakeBall::Interrupted()
{
	std::cout << "Intake : IntakeBall : Interrupted " << std::endl;
	intake_->Stop();
	intake_->SetState(State_t::OFF);
}

} // end namespace commands
<commit_msg>bugfix<commit_after>#include "IntakeBall.h"

/**
 * Namespace commands with implementation
 * of IntakeBall command functions.
 */
namespace commands
{

// Constructor:
IntakeBall::IntakeBall(Intake * intake) : Command("IntakeBall")
{
	intake_ = intake;
	SetInterruptible(true);
}

// Main functions:
void IntakeBall::Initialize()
{
	std::cout << "Intake : IntakeBall : Started" << std::endl;
	if (intake_->GetState() == State_t::OFF)
	{
		intake_->SetState(State_t::TAKING);
		intake_->TakeBall(true);
	}
	else
	{
		std::cout << "ERROR: Invalid starting state (Should be \"OFF\")" << std::endl;
		Cancel();
	}
}

bool IntakeBall::IsFinished()
{
	return intake_->CheckSwitch();
}

void IntakeBall::End()
{
	std::cout << "Intake : IntakeBall : Ended" << std::endl;
	intake_->Stop();
	intake_->SetState(State_t::HOLDING);
}

void IntakeBall::Interrupted()
{
	std::cout << "Intake : IntakeBall : Interrupted " << std::endl;
	intake_->Stop();
	intake_->SetState(State_t::OFF);
}

} // end namespace commands
<|endoftext|>


<commit_before>#include "convergence/final_checker_or_n.h"

#include <memory>
#include <optional>

#include <gtest/gtest.h>

#include "convergence/status.h"
#include "convergence/moments/tests/multi_moment_checker_mock.h"
#include "data/moment_types.h"
#include "test_helpers/gmock_wrapper.h"

namespace {

using ::testing::_;
using ::testing::Expectation;
using ::testing::NiceMock;
using ::testing::Return;
using namespace bart::convergence;

class ConvergenceFinalCheckerOrNMultiMomentTest : public ::testing::Test {
 protected:
  using FinalMultiMomentChecker =
      FinalCheckerOrN<bart::data::MomentsMap , moments::MultiMomentCheckerI>;

  std::unique_ptr<NiceMock<moments::MultiMomentCheckerMock>> checker_ptr;

  bart::data::MomentVector moment_map_one, moment_map_two;
  void SetUp() override;
};

void ConvergenceFinalCheckerOrNMultiMomentTest::SetUp() {
  checker_ptr = std::make_unique<NiceMock<moments::MultiMomentCheckerMock>>();
  ON_CALL(*checker_ptr, CheckIfConverged(_,_))
      .WillByDefault(Return(true));
  ON_CALL(*checker_ptr, delta())
      .WillByDefault(Return(std::nullopt));
  ON_CALL(*checker_ptr, failed_index())
      .WillByDefault(Return(std::nullopt));
}

// -- CUSTOM ASSERTION FOR COMPARING STATUS STRUCTS --

::testing::AssertionResult CompareStatus(const Status lhs, const Status rhs) {
  if (lhs.iteration_number != rhs.iteration_number) {
    return ::testing::AssertionFailure() << "Iteration number mismatch "
                                         << lhs.iteration_number << " != "
                                         << rhs.iteration_number;
  } else if (lhs.max_iterations != rhs.max_iterations) {
    return ::testing::AssertionFailure() << "Max iteration number mismatch "
                                         << lhs.max_iterations << " != "
                                         << rhs.max_iterations;
  } else if (lhs.is_complete != rhs.is_complete) {
    return ::testing::AssertionFailure() << "Convergence completion mismatch "
                                         << lhs.is_complete << " != "
                                         << rhs.is_complete;
  } else if (lhs.failed_index != rhs.failed_index) {
    return ::testing::AssertionFailure() << "Failed index mismatch "
                                         << lhs.failed_index.value_or(-1) << " != "
                                         << rhs.failed_index.value_or(-1);
  } else if (lhs.delta != rhs.delta) {
    return ::testing::AssertionFailure() << "Delta mismatch "
                                         << lhs.delta.value_or(-1) << " != "
                                         << rhs.delta.value_or(-1);
  }
  return ::testing::AssertionSuccess();
}

TEST_F(ConvergenceFinalCheckerOrNMultiMomentTest, Constructor) {
  FinalMultiMomentChecker test_checker(std::move(checker_ptr));

  EXPECT_EQ(checker_ptr, nullptr);
}

//// Verify setters and getters work properly
//TEST_F(ConvergenceFinalCheckerOrNMultiMomentTest, SettersAndGetters) {
//  FinalMultiMomentChecker test_checker(std::move(checker_ptr));
//
//  EXPECT_EQ(test_checker.max_iterations(), 100);
//  test_checker.SetMaxIterations(50);
//  EXPECT_EQ(test_checker.max_iterations(), 50);
//
//  EXPECT_EQ(test_checker.iteration(), 0);
//  test_checker.SetIteration(10);
//  EXPECT_EQ(test_checker.iteration(), 10);
//}
//
//// -- CONVERGENCE TESTS --
//
//TEST_F(ConvergenceFinalCheckerOrNMultiMomentTest, GoodConvergence) {
//  FinalMultiMomentChecker test_checker(std::move(checker_ptr));
//  Status good_convergence = {1, 100, true, std::nullopt, std::nullopt};
//  auto result = test_checker.CheckFinalConvergence(moment_map_one, moment_map_two);
//  EXPECT_TRUE(CompareStatus(result, good_convergence));
//}
//
//TEST_F(ConvergenceFinalCheckerOrNMultiMomentTest, GoodConvergenceAfterBad) {
//  Expectation bad_convergence = EXPECT_CALL(*checker_ptr, CheckIfConverged(_,_))
//      .Times(5)
//      .WillRepeatedly(Return(false));
//  EXPECT_CALL(*checker_ptr, CheckIfConverged(_,_))
//      .After(bad_convergence)
//      .WillOnce(Return(true));
//
//  FinalMultiMomentChecker test_checker(std::move(checker_ptr));
//  Status result, good_convergence = {6, 100, true, std::nullopt, std::nullopt};
//
//  for (int i = 0; i < 6; ++i)
//    result = test_checker.CheckFinalConvergence(moment_map_one, moment_map_two);
//
//  EXPECT_TRUE(CompareStatus(result, good_convergence));
//}
//
//TEST_F(ConvergenceFinalCheckerOrNMultiMomentTest, BadConvergenceAfterGood) {
//
//  auto delta = std::make_optional<double>(0.123);
//
//  Expectation good_convergence = EXPECT_CALL(*checker_ptr, CheckIfConverged(_,_))
//      .Times(5)
//      .WillRepeatedly(Return(true));
//  EXPECT_CALL(*checker_ptr, delta())
//      .Times(5)
//      .WillRepeatedly(::testing::DoDefault());
//  Expectation bad_convergence = EXPECT_CALL(*checker_ptr, CheckIfConverged(_,_))
//      .After(good_convergence)
//      .WillOnce(Return(false));
//  EXPECT_CALL(*checker_ptr, delta())
//      .After(bad_convergence)
//      .WillOnce(Return(delta));
//
//  FinalMultiMomentChecker test_checker(std::move(checker_ptr));
//  Status result, expected = {6, 100, false, std::nullopt, delta};
//
//  for (int i = 0; i < 6; ++i)
//    result = test_checker.CheckFinalConvergence(moment_map_one, moment_map_two);
//
//  EXPECT_TRUE(CompareStatus(result, expected));
//}
//
//TEST_F(ConvergenceFinalCheckerOrNMultiMomentTest, MaxIterationsReached) {
//
//  auto delta = std::make_optional<double>(0.123);
//
//  ON_CALL(*checker_ptr, CheckIfConverged(_,_))
//      .WillByDefault(Return(false));
//  ON_CALL(*checker_ptr, delta())
//      .WillByDefault(Return(delta));
//
//  FinalMultiMomentChecker test_checker(std::move(checker_ptr));
//  Status result, expected = {10, 10, true, std::nullopt, delta};
//
//  test_checker.SetMaxIterations(10).SetIteration(9);
//
//  result = test_checker.CheckFinalConvergence(moment_map_one, moment_map_two);
//
//  EXPECT_TRUE(CompareStatus(result, expected));
//}
//
//
//
//// -- ERRORS --
//// Verify setters and getters throw the correct errors
//TEST_F(ConvergenceFinalCheckerOrNMultiMomentTest, SettersBadValues) {
//  FinalMultiMomentChecker test_checker(std::move(checker_ptr));
//
//  EXPECT_ANY_THROW(test_checker.SetIteration(-10));
//  EXPECT_ANY_THROW(test_checker.SetMaxIterations(-10));
//  EXPECT_ANY_THROW(test_checker.SetMaxIterations(0));
//
//}

} // namespace

<commit_msg>finished adding tests for FinalCheckerOrN for MomentsMap<commit_after>#include "convergence/final_checker_or_n.h"

#include <memory>
#include <optional>

#include <gtest/gtest.h>

#include "convergence/status.h"
#include "convergence/moments/tests/multi_moment_checker_mock.h"
#include "data/moment_types.h"
#include "test_helpers/gmock_wrapper.h"

namespace {

using ::testing::_;
using ::testing::Expectation;
using ::testing::NiceMock;
using ::testing::Return;
using namespace bart::convergence;

class ConvergenceFinalCheckerOrNMultiMomentTest : public ::testing::Test {
 protected:
  using FinalMultiMomentChecker =
      FinalCheckerOrN<bart::data::MomentsMap , moments::MultiMomentCheckerI>;

  std::unique_ptr<NiceMock<moments::MultiMomentCheckerMock>> checker_ptr;

  bart::data::MomentsMap moment_map_one, moment_map_two;
  void SetUp() override;
};

void ConvergenceFinalCheckerOrNMultiMomentTest::SetUp() {
  checker_ptr = std::make_unique<NiceMock<moments::MultiMomentCheckerMock>>();
  ON_CALL(*checker_ptr, CheckIfConverged(_,_))
      .WillByDefault(Return(true));
  ON_CALL(*checker_ptr, delta())
      .WillByDefault(Return(std::nullopt));
  ON_CALL(*checker_ptr, failed_index())
      .WillByDefault(Return(std::nullopt));
}

// -- CUSTOM ASSERTION FOR COMPARING STATUS STRUCTS --

::testing::AssertionResult CompareStatus(const Status lhs, const Status rhs) {
  if (lhs.iteration_number != rhs.iteration_number) {
    return ::testing::AssertionFailure() << "Iteration number mismatch "
                                         << lhs.iteration_number << " != "
                                         << rhs.iteration_number;
  } else if (lhs.max_iterations != rhs.max_iterations) {
    return ::testing::AssertionFailure() << "Max iteration number mismatch "
                                         << lhs.max_iterations << " != "
                                         << rhs.max_iterations;
  } else if (lhs.is_complete != rhs.is_complete) {
    return ::testing::AssertionFailure() << "Convergence completion mismatch "
                                         << lhs.is_complete << " != "
                                         << rhs.is_complete;
  } else if (lhs.failed_index != rhs.failed_index) {
    return ::testing::AssertionFailure() << "Failed index mismatch "
                                         << lhs.failed_index.value_or(-1) << " != "
                                         << rhs.failed_index.value_or(-1);
  } else if (lhs.delta != rhs.delta) {
    return ::testing::AssertionFailure() << "Delta mismatch "
                                         << lhs.delta.value_or(-1) << " != "
                                         << rhs.delta.value_or(-1);
  }
  return ::testing::AssertionSuccess();
}

TEST_F(ConvergenceFinalCheckerOrNMultiMomentTest, Constructor) {
  FinalMultiMomentChecker test_checker(std::move(checker_ptr));

  EXPECT_EQ(checker_ptr, nullptr);
}

// Verify setters and getters work properly
TEST_F(ConvergenceFinalCheckerOrNMultiMomentTest, SettersAndGetters) {
  FinalMultiMomentChecker test_checker(std::move(checker_ptr));

  EXPECT_EQ(test_checker.max_iterations(), 100);
  test_checker.SetMaxIterations(50);
  EXPECT_EQ(test_checker.max_iterations(), 50);

  EXPECT_EQ(test_checker.iteration(), 0);
  test_checker.SetIteration(10);
  EXPECT_EQ(test_checker.iteration(), 10);
}

// -- CONVERGENCE TESTS --

TEST_F(ConvergenceFinalCheckerOrNMultiMomentTest, GoodConvergence) {
  FinalMultiMomentChecker test_checker(std::move(checker_ptr));
  Status good_convergence = {1, 100, true, std::nullopt, std::nullopt};

  auto result = test_checker.CheckFinalConvergence(moment_map_one, moment_map_two);
  EXPECT_TRUE(CompareStatus(result, good_convergence));
  EXPECT_TRUE(CompareStatus(test_checker.convergence_status(),
                            good_convergence));
  EXPECT_TRUE(test_checker.convergence_is_complete());
}

TEST_F(ConvergenceFinalCheckerOrNMultiMomentTest, GoodConvergenceAfterBad) {
  Expectation bad_convergence = EXPECT_CALL(*checker_ptr, CheckIfConverged(_,_))
      .Times(5)
      .WillRepeatedly(Return(false));
  EXPECT_CALL(*checker_ptr, CheckIfConverged(_,_))
      .After(bad_convergence)
      .WillOnce(Return(true));

  FinalMultiMomentChecker test_checker(std::move(checker_ptr));
  Status result, good_convergence = {6, 100, true, std::nullopt, std::nullopt};

  for (int i = 0; i < 6; ++i)
    result = test_checker.CheckFinalConvergence(moment_map_one, moment_map_two);

  EXPECT_TRUE(CompareStatus(result, good_convergence));
  EXPECT_TRUE(test_checker.convergence_is_complete());
}

TEST_F(ConvergenceFinalCheckerOrNMultiMomentTest, BadConvergenceAfterGood) {

  auto delta = std::make_optional<double>(0.123);
  auto failed_index = std::make_optional<int>(5);

  Expectation good_convergence = EXPECT_CALL(*checker_ptr, CheckIfConverged(_,_))
      .Times(5)
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*checker_ptr, delta())
      .Times(5)
      .WillRepeatedly(::testing::DoDefault());
  EXPECT_CALL(*checker_ptr, failed_index())
      .Times(5)
      .WillRepeatedly(::testing::DoDefault());
  Expectation bad_convergence = EXPECT_CALL(*checker_ptr, CheckIfConverged(_,_))
      .After(good_convergence)
      .WillOnce(Return(false));
  EXPECT_CALL(*checker_ptr, delta())
      .After(bad_convergence)
      .WillOnce(Return(delta));
  EXPECT_CALL(*checker_ptr, failed_index())
      .After(bad_convergence)
      .WillOnce(Return(failed_index));

  FinalMultiMomentChecker test_checker(std::move(checker_ptr));
  Status result, expected = {6, 100, false, failed_index, delta};

  for (int i = 0; i < 6; ++i)
    result = test_checker.CheckFinalConvergence(moment_map_one, moment_map_two);

  EXPECT_TRUE(CompareStatus(result, expected));
  EXPECT_FALSE(test_checker.convergence_is_complete());
}
//
TEST_F(ConvergenceFinalCheckerOrNMultiMomentTest, MaxIterationsReached) {

  auto delta = std::make_optional<double>(0.123);
  auto failed_index = std::make_optional<int>(5);

  ON_CALL(*checker_ptr, CheckIfConverged(_,_))
      .WillByDefault(Return(false));
  ON_CALL(*checker_ptr, delta())
      .WillByDefault(Return(delta));
  ON_CALL(*checker_ptr, failed_index())
      .WillByDefault(Return(failed_index));

  FinalMultiMomentChecker test_checker(std::move(checker_ptr));
  Status result, expected = {10, 10, true, failed_index, delta};

  test_checker.SetMaxIterations(10).SetIteration(9);

  result = test_checker.CheckFinalConvergence(moment_map_one, moment_map_two);

  EXPECT_TRUE(CompareStatus(result, expected));
  EXPECT_TRUE(test_checker.convergence_is_complete());
}

// -- ERRORS --
// Verify setters and getters throw the correct errors
TEST_F(ConvergenceFinalCheckerOrNMultiMomentTest, SettersBadValues) {
  FinalMultiMomentChecker test_checker(std::move(checker_ptr));

  EXPECT_ANY_THROW(test_checker.SetIteration(-10));
  EXPECT_ANY_THROW(test_checker.SetMaxIterations(-10));
  EXPECT_ANY_THROW(test_checker.SetMaxIterations(0));

}

} // namespace

<|endoftext|>


<commit_before><commit_msg>Revert "Cleanly remove an extension again that cannot be activated while installing it"<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include "dict/dict.hh"
#include <cstdlib>

#include <tr1/unordered_map>

using namespace std;
using namespace tr1;

#define DSIZE 1000
//000

/**
 * clock function
 */
#ifdef __unix__

#include <sys/time.h>
inline double gettime(){
  timeval tv;
  gettimeofday(&tv,NULL);
  return static_cast<double>(tv.tv_sec)+static_cast<double>(tv.tv_usec)/1000000.0;
}

#else

#include <ctime>
inline double gettime() {
  return static_cast<double>(clock())/CLOCKS_PER_SEC;
}

#endif

void dict_bench(int data1[DSIZE], int data2[DSIZE]) {
  dict::dict<int,int> dic;
  double beg_t = gettime();
  int count = 0;

  for(int i=0; i < DSIZE; i++) {
    dic.put(data1[i], data1[i]);
  }
  std::cout << " put: " << gettime()-beg_t << " #" << dic.size() << std::endl;

  beg_t = gettime();
  count = 0;
  for(int i=0; i < DSIZE; i++) {
    if(dic.contains(data1[i]))
      count++;
  }
  std::cout << " get1: " << gettime()-beg_t << " #" << count << std::endl;

  count = 0;
  for(int i=0; i < DSIZE; i++) {
    if(dic.contains(data2[i]))
      count++;
  }
  std::cout << " get2: " << gettime()-beg_t << " #" << count << std::endl;
}

void unorderedmap_bench(int data1[DSIZE], int data2[DSIZE]) {
  unordered_map<int,int> dic;
  double beg_t = gettime();
  int count = 0;

  for(int i=0; i < DSIZE; i++) {
    dic[data1[i]] = data1[i];
  }
  std::cout << " put: " << gettime()-beg_t << " #" << dic.size() << std::endl;

  beg_t = gettime();
  count = 0;
  for(int i=0; i < DSIZE; i++) {
    if(dic.find(data1[i]) != dic.end())
      count++;
  }
  std::cout << " get1: " << gettime()-beg_t << " #" << count << std::endl;

  count = 0;
  for(int i=0; i < DSIZE; i++) {
    if(dic.find(data2[i]) != dic.end())
      count++;
  }
  std::cout << " get2: " << gettime()-beg_t << " #" << count << std::endl;
}

int main(int argc, char** argv) {
  int data1[DSIZE];
  int data2[DSIZE];

  for(int i=0; i < DSIZE; i++) {
    data1[i] = rand() % (DSIZE*5);
    data2[i] = rand() % (DSIZE*5);
  }

  double beg_t = gettime();
  std::cout << "dict: " << std::endl;
  dict_bench(data1, data2);
  std::cout << " => total: " << gettime()-beg_t << std::endl << std::endl;;

  beg_t = gettime();
  std::cout << "unorderedmap: " << std::endl;
  unorderedmap_bench(data1, data2);
  std::cout << " => total: " << gettime()-beg_t << std::endl << std::endl;;
  /*
  dict::dict<int, int> d;
  int key = atoi(argv[1]);

  for(int i=0; i < 100; i++)
    d.put(i, i*10);

  std::cout << key << ": " << (d.contains(key) ? d.get(key) : -1) << std::endl;
  */
  return 0;
}
<commit_msg>rehash時にnode.nextを上書きしてしまう問題を修正<commit_after>#include <iostream>
#include "dict/dict.hh"
#include <cstdlib>

#include <tr1/unordered_map>

using namespace std;
using namespace tr1;

#define DSIZE 1000000

/**
 * clock function
 */
#ifdef __unix__

#include <sys/time.h>
inline double gettime(){
  timeval tv;
  gettimeofday(&tv,NULL);
  return static_cast<double>(tv.tv_sec)+static_cast<double>(tv.tv_usec)/1000000.0;
}

#else

#include <ctime>
inline double gettime() {
  return static_cast<double>(clock())/CLOCKS_PER_SEC;
}

#endif

void dict_bench(int data1[DSIZE], int data2[DSIZE]) {
  dict::dict<int,int> dic;
  double beg_t = gettime();
  int count = 0;

  for(int i=0; i < DSIZE; i++) {
    dic.put(data1[i], data1[i]);
  }
  std::cout << " put: " << gettime()-beg_t << " #" << dic.size() << std::endl;

  beg_t = gettime();
  count = 0;
  for(int i=0; i < DSIZE; i++) {
    if(dic.contains(data1[i]))
      count++;
  }
  std::cout << " get1: " << gettime()-beg_t << " #" << count << std::endl;

  count = 0;
  for(int i=0; i < DSIZE; i++) {
    if(dic.contains(data2[i]))
      count++;
  }
  std::cout << " get2: " << gettime()-beg_t << " #" << count << std::endl;
}

void unorderedmap_bench(int data1[DSIZE], int data2[DSIZE]) {
  unordered_map<int,int> dic;
  double beg_t = gettime();
  int count = 0;

  for(int i=0; i < DSIZE; i++) {
    dic[data1[i]] = data1[i];
  }
  std::cout << " put: " << gettime()-beg_t << " #" << dic.size() << std::endl;

  beg_t = gettime();
  count = 0;
  for(int i=0; i < DSIZE; i++) {
    if(dic.find(data1[i]) != dic.end())
      count++;
  }
  std::cout << " get1: " << gettime()-beg_t << " #" << count << std::endl;

  count = 0;
  for(int i=0; i < DSIZE; i++) {
    if(dic.find(data2[i]) != dic.end())
      count++;
  }
  std::cout << " get2: " << gettime()-beg_t << " #" << count << std::endl;
}

int main(int argc, char** argv) {
  int data1[DSIZE];
  int data2[DSIZE];

  for(int i=0; i < DSIZE; i++) {
    data1[i] = rand() % (DSIZE*5);
    data2[i] = rand() % (DSIZE*5);
  }

  double beg_t = gettime();
  std::cout << "dict: " << std::endl;
  dict_bench(data1, data2);
  std::cout << " => total: " << gettime()-beg_t << std::endl << std::endl;;

  beg_t = gettime();
  std::cout << "unorderedmap: " << std::endl;
  unorderedmap_bench(data1, data2);
  std::cout << " => total: " << gettime()-beg_t << std::endl << std::endl;;
  /*
  dict::dict<int, int> d;
  int key = atoi(argv[1]);

  for(int i=0; i < 100; i++)
    d.put(i, i*10);

  std::cout << key << ": " << (d.contains(key) ? d.get(key) : -1) << std::endl;
  */
  return 0;
}
<|endoftext|>


<commit_before>/**
 * C. Estaciones espaciales
 * https://omegaup.com/arena/problem/Estaciones-Espaciales#problems
 * Si representamos una estacion como un vertice de un grafo, y los tuneles que las conectan como una
 * arista del grafo, entonces necesitamos encontrar el tamano de la menor covertura por vertices.
 */
#include <iostream>
#include <vector>

using namespace std;

int main() {
    int n;
    cin >> n;
    vector<vector<int>> G(n);	//Grafo G
    for (int i = 1; i < n; ++i) {
        int x;
        cin >> x;
        G[x - 1].push_back(i);
    }
    vector<vector<int>> DP(n, vector<int>(2));	//tabla con el numero de agentes requeridos para cada arbol
    for (int u = n - 1; u >= 0; --u) {		//iteracion bottom-up
        int taken[] = {0, 0};
        for (int v : G[u]) {
            taken[0] += DP[v][0];
            taken[1] += DP[v][1];
        }
        DP[u][0] = 1 + taken[1];
        DP[u][1] = min(1 + taken[1], taken[0]);	//numero de agentes requeridos
    }
    cout << DP[0][1] << endl;
}
<commit_msg>Added comments<commit_after>/**
 * C. Estaciones espaciales
 * https://omegaup.com/arena/problem/Estaciones-Espaciales#problems
 * Si representamos una estacion como un vertice de un grafo, y los tuneles que las conectan como una
 * arista del grafo, entonces necesitamos encontrar el tamano de la menor covertura por vertices.
 * El hecho que exista solo un camino entre dos vertices hace que el grafo sea un arbol.
 */
#include <iostream>
#include <vector>

using namespace std;

int main() {
    int n;
    cin >> n;
    vector<vector<int>> G(n);	//Grafo G
    for (int i = 1; i < n; ++i) {
        int x;
        cin >> x;
        G[x - 1].push_back(i);
    }
    vector<vector<int>> DP(n, vector<int>(2));	//tabla con el numero de agentes requeridos para cada arbol
    for (int u = n - 1; u >= 0; --u) {		//iteracion bottom-up
        int taken[] = {0, 0};
        for (int v : G[u]) {
            taken[0] += DP[v][0];
            taken[1] += DP[v][1];
        }
        DP[u][0] = 1 + taken[1];
        DP[u][1] = min(1 + taken[1], taken[0]);	//numero de agentes requeridos
    }
    cout << DP[0][1] << endl;
}
<|endoftext|>