text:
#pragma once

#include <boost/detail/atomic_count.hpp>
#include <boost/checked_delete.hpp>
#include <boost/intrusive_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <assert.h>

namespace xul {

template <typename T>
class intrusive_ptr_base : private boost::noncopyable
{
public:
    intrusive_ptr_base() : m_refs(0) {}

    friend void intrusive_ptr_add_ref(intrusive_ptr_base<T> const* s)
    {
        assert(s != 0);
        assert(s->m_refs >= 0);
        ++s->m_refs;
    }

    friend void intrusive_ptr_release(intrusive_ptr_base<T> const* s)
    {
        assert(s != 0);
        assert(s->m_refs > 0);
        if (--s->m_refs == 0)
        {
            boost::checked_delete(static_cast<T const*>(s));
        }
    }

    boost::intrusive_ptr<T> self()
    {
        return boost::intrusive_ptr<T>(static_cast<T*>(this));
    }

    boost::intrusive_ptr<const T> self() const
    {
        return boost::intrusive_ptr<const T>(static_cast<const T*>(this));
    }

    boost::intrusive_ptr<T> shared_from_this()
    {
        return boost::intrusive_ptr<T>(static_cast<T*>(this));
    }

    boost::intrusive_ptr<const T> shared_from_this() const
    {
        return boost::intrusive_ptr<const T>(static_cast<const T*>(this));
    }

    int refcount() const
    {
        return m_refs;
    }

private:
    /// reference counter for intrusive_ptr
    mutable boost::detail::atomic_count m_refs;
};

}

ext: hpp

max_stars_repo_name: hindsights/xul

max_issues_repo_name: hindsights/xul

max_forks_repo_name: hindsights/xul


text:
/**
 * @file backward_visitor.hpp
 * @author Marcus Edel
 *
 * This file provides an abstraction for the Backward() function for different
 * layers and automatically directs any parameter to the right layer type.
 *
 * mlpack is free software; you may redistribute it and/or modify it under the
 * terms of the 3-clause BSD license.  You should have received a copy of the
 * 3-clause BSD license along with mlpack.  If not, see
 * http://www.opensource.org/licenses/BSD-3-Clause for more information.
 */
#ifndef MLPACK_METHODS_ANN_VISITOR_BACKWARD_VISITOR_HPP
#define MLPACK_METHODS_ANN_VISITOR_BACKWARD_VISITOR_HPP

#include <mlpack/methods/ann/layer/layer_traits.hpp>
#include <mlpack/methods/ann/layer/layer_types.hpp>

#include <boost/variant.hpp>

namespace mlpack {
namespace ann {

/**
 * BackwardVisitor executes the Backward() function given the input, error and
 * delta parameter.
 */
class BackwardVisitor : public boost::static_visitor<void>
{
 public:
  //! Execute the Backward() function given the input, error and delta
  //! parameter.
  BackwardVisitor(arma::mat&& input, arma::mat&& error, arma::mat&& delta);

  //! Execute the Backward() function for the layer with the specified index.
  BackwardVisitor(arma::mat&& input, arma::mat&& error, arma::mat&& delta,
      const size_t index);

  //! Execute the Backward() function.
  template<typename LayerType>
  void operator()(LayerType* layer) const;

  void operator()(MoreTypes layer) const;

 private:
  //! The input parameter set.
  arma::mat&& input;

  //! The error parameter.
  arma::mat&& error;

  //! The delta parameter.
  arma::mat&& delta;

  //! The index of the layer to run.
  size_t index;

  //! Indicates whether to use index or not
  bool hasIndex;

  //! Execute the Backward() function if the module does not have Run()
  //! check.
  template<typename T>
  typename std::enable_if<
      !HasRunCheck<T, bool&(T::*)(void)>::value, void>::type
  LayerBackward(T* layer, arma::mat& input) const;

  //! Execute the Backward() function if the module is has Run() function.
  template<typename T>
  typename std::enable_if<
      HasRunCheck<T, bool&(T::*)(void)>::value, void>::type
  LayerBackward(T* layer, arma::mat& input) const;
};

} // namespace ann
} // namespace mlpack

// Include implementation.
#include "backward_visitor_impl.hpp"

#endif

max_stars_repo_name: tomjpsun/mlpack

max_issues_repo_name: tomjpsun/mlpack

max_forks_repo_name: tomjpsun/mlpack


text:
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <boost/math/special_functions/beta.hpp>
#include<boost/math/distributions.hpp>
#include <cmath>
#include "helpers.hpp"

using namespace std;
using namespace boost::math;

void computeIndices(const int n, const double beta, vector<vector<double> >& indices)
{
  #pragma omp parallel for
  for(int nn = n-1; nn >= 2; --nn)
  {
    for(int a = 1; a <= nn-1; ++a)
    {
      double p = computeAGI(beta, a, nn);
      indices[a-1][nn-a-1] = p;
    }
  }
}

void computeGittinsIndices(const int n, const double step, const double beta, vector<vector<double> >& indices)
{
  vector<vector<double> > tmpindices(n-1, vector<double>(n-1, 0));
  for(int a = 1; a < n; ++a)
  {
    tmpindices[a-1][n-a-1] = ((double)a/(double)n);
  }
  for(double p=(step/2.0); p <= 1.0; p+=step)
  {
    const double safe = p/(1-beta);
    for(int nn = n-1; nn >= 2; --nn)
    {
      for(int a = 1; a <= nn-1; ++a)
      {
        const double r = ((double)a/(double)nn);
        const double risky =  r*(1 + beta*tmpindices[a][nn-a-1]) + (1-r)*beta*tmpindices[a-1][nn-a];
        if(indices[a-1][nn-a-1] == 0 && safe > risky)
        {
          indices[a-1][nn-a-1] = p - step/2.0;
        }
        tmpindices[a-1][nn-a-1] = max(safe,risky);
      }
    }
  }
  /*for(int nn = n-1; nn >= 2; --nn)
  {
    for(int a = 1; a <= nn-1; ++a)
    {
      if(a > ceil(nn/2.0))
      {
        indices[a-1][nn-a-1] = 1 - step/2.0;
      }
    }
  }*/
}

void experiment(int n, double beta, double step)
{
  vector<vector<double> > gindices(n-1, vector<double>(n-1, 0));
  const static int maxnum = 500;
  /*cout << "computing gittins indices...." << endl;
  computeGittinsIndices(n,step,beta,gindices);*/
  cout << "loading gittins indices..." << endl;
  loadFromCSV("gixs_95.csv", gindices, maxnum, maxnum);

  cout << "checking values..." << endl;
  for(int a = 0; a < maxnum; ++a)
  {
    for(int b = 0; b < maxnum; ++b)
    {
      const double agi1 = computeAGI(beta, a + 1, a + b + 2);
      const double agi2 = computeAGI2(beta, a + 1, b + 1);
      const double agi2a = computeGeneralAGI(beta, a + 1, b + 1, 2);
      const double agi3 = computeGeneralAGI(beta, a + 1, b + 1, 3);
      const double agi4 = computeGeneralAGI(beta, a + 1, b + 1, 4);
      double eps = 1e-6;
      if (abs(agi2a - agi2) > eps)
      {
        cerr << "difference found in agi1 comp for a: " << a << ". b: " << b << ". agi2: " << agi2 << ". agi2a: " << agi2a << endl;
      }
      if (!(agi1 > agi2 - eps && agi2 > agi3 - eps && agi3 > agi4 - eps))
      {
        cerr << "unexpected order of indices. a = " << a << ". b = " << b << ". agi1: " << agi1 << ". agi2: " << agi2 << ". agi3:" << agi3 << ". agi4:" << agi4 << endl;
        //exit(1);
        //
      }

      if (agi1 < gindices[a][b] -eps)
      {
        cerr << "unexpected. a = " << a << ". b = " << b << ". agi1: " << agi1 << ". gidx: " << gindices[a][b] << endl;
      }
      if (agi2 < gindices[a][b] -eps)
      {
        cerr << "unexpected. a = " << a << ". b = " << b << ". agi2: " << agi2 << ". gidx: " << gindices[a][b] << endl;
      }
      if (agi3 < gindices[a][b] -eps)
      {
        cerr << "unexpected. a = " << a << ". b = " << b << ". agi3: " << agi3 << ". gidx: " << gindices[a][b] << endl;
      }
      if (agi4 < gindices[a][b] -eps)
      {
        cerr << "unexpected. a = " << a << ". b = " << b << ". agi4: " << agi4 << ". gidx: " << gindices[a][b] << endl;
      }
    }
  }

  cout << "done..." << endl;
}

void calculator()
{
  while(1)
  {
    double gamma, a, b;
    cin >> gamma;
    cin >> a;
    cin >> b;
    cout << std::setprecision(20) << computeAGI(gamma,a,a+b) << endl;
    cout << std::setprecision(20) << computeAGI2(gamma,a,b) << endl;
    cout << std::setprecision(20) << computeGeneralAGI(gamma,a,b,3) << endl;
  }
}

int main(int argc, const char** args)
{
  //this is bad lol
  //calculator();
  //cout << ::computeAGI2(0.99,3,3);
  if(argc != 3)
  {
    cerr << "need 2 arguments [n] [beta]" << endl;
    exit(1);
  }
  int n;
  string strnum = args[1];
  stringstream ss(strnum);
  ss >> n;

  double beta;
  string betastr = args[2];
  stringstream ssbeta(betastr);
  ssbeta >> beta;

  double step = 0.0001;
  experiment(n, beta, step);

  exit(0);
  vector<vector<double> > indices(n-1, vector<double>(n-1, 0));
  computeIndices(n, beta, indices);

  for(int i = 0; i < n-1; ++i)
  {
    for(int j=0; j < n-2; ++j)
    {
      cout << indices[i][j] << ", ";
    }
    cout << indices[i][n-2] << endl;
  }
}

ext: cpp

max_stars_repo_name: gutin/FastGittins

max_issues_repo_name: gutin/FastGittins

max_forks_repo_name: gutin/FastGittins


text: #include <boost/spirit/home/karma/directive/duplicate.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//          Copyright Oliver Kowalke 2009.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_TASKS_DETAIL_WORKER_H
#define BOOST_TASKS_DETAIL_WORKER_H

#include <cstddef>
#include <utility>

#include <boost/assert.hpp>
#include <boost/fiber.hpp>
#include <boost/function.hpp>
#include <boost/random.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/utility.hpp>

#include <boost/task/callable.hpp>
#include <boost/task/detail/config.hpp>
#include <boost/task/detail/wsq.hpp>
#include <boost/task/poolsize.hpp>
#include <boost/task/stacksize.hpp>

#include <boost/config/abi_prefix.hpp>

# if defined(BOOST_MSVC)
# pragma warning(push)
# pragma warning(disable:4251 4275)
# endif

namespace boost {
namespace tasks {
namespace detail {

struct worker_base
{
	virtual ~worker_base() {}

	virtual const thread::id get_id() const = 0;

	virtual void join() const = 0;

	virtual void interrupt() const = 0;

	virtual void put( callable const&) = 0;

	virtual bool try_steal( callable &) = 0;

	virtual void run() = 0;

	virtual void yield() = 0;
};

template<
	typename Pool,
	typename Worker
>
class worker_object : public worker_base,
					  private noncopyable
{
private:
	class random_idx
	{
	private:
		rand48 rng_;
		uniform_int<> six_;
		variate_generator< rand48 &, uniform_int<> > die_;

	public:
		random_idx( std::size_t size) :
			rng_(),
			six_( 0, size - 1),
			die_( rng_, six_)
		{}

		std::size_t operator()()
		{ return die_(); }
	};

	typedef shared_ptr< thread >	thread_t;

	Pool						&	pool_;
	thread_t						thrd_;
	fibers::scheduler<
		typename Pool::ums_type > *	sched_;// TODO: make not as pointer if WIN32 Fiber API is replaced by assembler

	wsq								wsq_;
	bool							shtdwn_;
	std::size_t						stack_size_;
	random_idx						rnd_idx_;

	void execute_( callable & ca)
	{
		BOOST_ASSERT( ! ca.empty() );
		{
			context_guard lk( ca, thrd_);
			ca();
		}
		ca.clear();
		BOOST_ASSERT( ca.empty() );
	}

	bool try_take_global_callable_( callable & ca)
	{ return pool_.queue_.try_take( ca); }

	bool try_take_local_callable_( callable & ca)
	{ return wsq_.try_take( ca); }

	bool try_steal_other_callable_( callable & ca)
	{
		std::size_t idx( rnd_idx_() );
		for ( std::size_t j( 0); j < pool_.wg_.size(); ++j)
		{
			Worker other( pool_.wg_[idx]);
			if ( this_thread::get_id() == other.get_id() ) continue;
			if ( ++idx >= pool_.wg_.size() ) idx = 0;
			if ( other.try_steal( ca) )
				return true;
		}
		return false;
	}

	void run_()
	{
		while ( ! shutdown_() )
		{
			callable ca;
			if ( try_take_local_callable_( ca) ||
				 try_steal_other_callable_( ca) ||
				 try_take_global_callable_( ca) )
			{
				execute_( ca);
				if ( 0 < sched_->ready() ) return;
			}
			else
			{
				if ( 0 < sched_->ready() ) return;
				pool_.fsem_.wait();
			}
		}
	}

	bool shutdown_()
	{
		if ( shutdown__() && pool_.queue_.empty() && 0 == sched_->ready() )
			return true;
		else if ( shutdown_now__() )
			return true;
		return false;
	}

	bool shutdown__()
	{
		if ( ! shtdwn_)
			shtdwn_ = pool_.shtdwn_;
		return shtdwn_;
	}

	bool shutdown_now__()
	{ return pool_.shtdwn_now_; }

public:
	worker_object(
			Pool & pool,
			poolsize const& psize,
			stacksize const& stack_size,
			function< void() > const& fn) :
		pool_( pool),
		thrd_( new thread( fn) ),
		sched_(),
		wsq_( pool_.fsem_),
		shtdwn_( false),
		stack_size_( stack_size),
		rnd_idx_( psize)
	{ BOOST_ASSERT( ! fn.empty() ); }

	~worker_object()
	{ delete sched_; }

	const thread::id get_id() const
	{ return thrd_->get_id(); }

	void join() const
	{ thrd_->join(); }

	void
	interrupt() const
	{ thrd_->interrupt(); }

	void put( callable const& ca)
	{
		BOOST_ASSERT( ! ca.empty() );
		wsq_.put( ca);
	}

	bool try_steal( callable & ca)
	{ return wsq_.try_steal( ca); }

	void run()
	{
// TODO: remove if WIN32 Fiber API is replaced by assembler
		sched_ = new fibers::scheduler< typename Pool::ums_type >();

		BOOST_ASSERT( get_id() == this_thread::get_id() );

		sched_->make_fiber(
				bind(
					& worker_object::run_,
					this),
				stack_size_);
		while ( ! shutdown_() )
			sched_->run();
	}

	void yield()
	{
		sched_->make_fiber(
			bind(
				& worker_object::run_,
				this),
			stack_size_);
		this_fiber::yield();
	}
};

class BOOST_TASKS_DECL worker
{
private:
	static thread_specific_ptr< worker >	tss_;

	shared_ptr< worker_base >	impl_;

public:
	template< typename Pool >
	worker(
			Pool & pool,
			poolsize const& psize,
			stacksize const& stack_size,
			function< void() > const& fn) :
		impl_(
			new worker_object< Pool, worker >(
				pool,
				psize,
				stack_size,
				fn) )
	{}

	const thread::id get_id() const;

	void join() const;

	void interrupt() const;

	void put( callable const&);

	bool try_steal( callable &);

	void run();

	void yield();

	static worker * tss_get();
};

}}}

# if defined(BOOST_MSVC)
# pragma warning(pop)
# endif

#include <boost/config/abi_suffix.hpp>

#endif // BOOST_TASKS_DETAIL_WORKER_H

max_stars_repo_name: ghisguth/tasks

max_issues_repo_name: ghisguth/tasks

max_forks_repo_name: ghisguth/tasks


text:
// Boost test program for next() and prior() utilities.

// Copyright 2003 Daniel Walker.  Use, modification, and distribution
// are subject to the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or a copy at
// http://www.boost.org/LICENSE_1_0.txt.)

// See http://www.boost.org/libs/utility for documentation.

// Revision History 13 Dec 2003 Initial Version (Daniel Walker)

// next() and prior() are replacements for operator+ and operator- for
// non-random-access iterators. The semantics of these operators are
// such that after executing j = i + n, std::distance(i, j) equals
// n. Tests are provided to ensure next() has the same
// result. Parallel tests are provided for prior(). The tests call
// next() and prior() several times. next() and prior() are very
// simple functions, though, and it would be very strange if these
// tests were to fail.

#include <boost/core/lightweight_test.hpp>

#include <list>
#include <vector>

#include <boost/next_prior.hpp>

template<class RandomAccessIterator, class ForwardIterator>
bool plus_one_test(RandomAccessIterator first, RandomAccessIterator last, ForwardIterator first2)
{
    RandomAccessIterator i = first;
    ForwardIterator j = first2;
    while(i != last)
        i = i + 1, j = boost::next(j);
    return std::distance(first, i) == std::distance(first2, j);
}

template<class RandomAccessIterator, class ForwardIterator>
bool plus_n_test(RandomAccessIterator first, RandomAccessIterator last, ForwardIterator first2)
{
    RandomAccessIterator i = first;
    ForwardIterator j = first2;
    for(int n = 0; i != last; ++n)
        i = first + n, j = boost::next(first2, n);
    return std::distance(first, i) == std::distance(first2, j);
}

template<class RandomAccessIterator, class BidirectionalIterator>
bool minus_one_test(RandomAccessIterator first, RandomAccessIterator last, BidirectionalIterator last2)
{
    RandomAccessIterator i = last;
    BidirectionalIterator j = last2;
    while(i != first)
        i = i - 1, j = boost::prior(j);
    return std::distance(i, last) == std::distance(j, last2);
}

template<class RandomAccessIterator, class BidirectionalIterator>
bool minus_n_test(RandomAccessIterator first, RandomAccessIterator last, BidirectionalIterator last2)
{
    RandomAccessIterator i = last;
    BidirectionalIterator j = last2;
    for(int n = 0; i != first; ++n)
        i = last - n, j = boost::prior(last2, n);
    return std::distance(i, last) == std::distance(j, last2);
}

template<class Iterator, class Distance>
bool minus_n_unsigned_test(Iterator first, Iterator last, Distance size)
{
    Iterator i = boost::prior(last, size);
    return i == first;
}

int main(int, char*[])
{
    std::vector<int> x(8);
    std::list<int> y(x.begin(), x.end());

    // Tests with iterators
    BOOST_TEST(plus_one_test(x.begin(), x.end(), y.begin()));
    BOOST_TEST(plus_n_test(x.begin(), x.end(), y.begin()));
    BOOST_TEST(minus_one_test(x.begin(), x.end(), y.end()));
    BOOST_TEST(minus_n_test(x.begin(), x.end(), y.end()));
    BOOST_TEST(minus_n_unsigned_test(x.begin(), x.end(), x.size()));
    BOOST_TEST(minus_n_unsigned_test(y.begin(), y.end(), y.size()));

    BOOST_TEST(plus_one_test(x.rbegin(), x.rend(), y.begin()));
    BOOST_TEST(plus_n_test(x.rbegin(), x.rend(), y.begin()));
    BOOST_TEST(minus_one_test(x.rbegin(), x.rend(), y.end()));
    BOOST_TEST(minus_n_test(x.rbegin(), x.rend(), y.end()));
    BOOST_TEST(minus_n_unsigned_test(x.rbegin(), x.rend(), x.size()));
    BOOST_TEST(minus_n_unsigned_test(x.rbegin(), x.rend(), y.size()));

    // Test with pointers
    std::vector<int> z(x.size());
    int* p = &z[0];
    BOOST_TEST(plus_one_test(x.begin(), x.end(), p));
    BOOST_TEST(plus_n_test(x.begin(), x.end(), p));
    BOOST_TEST(minus_one_test(x.begin(), x.end(), p + z.size()));
    BOOST_TEST(minus_n_test(x.begin(), x.end(), p + z.size()));
    BOOST_TEST(minus_n_unsigned_test(p, p + z.size(), z.size()));

    // Tests with integers
    BOOST_TEST(boost::next(5) == 6);
    BOOST_TEST(boost::next(5, 7) == 12);
    BOOST_TEST(boost::prior(5) == 4);
    BOOST_TEST(boost::prior(5, 7) == -2);
    BOOST_TEST(boost::prior(5, 7u) == -2);

    return boost::report_errors();
}


text:
/**********************************************************************
 *  Copyright (c) 2008-2014, Alliance for Sustainable Energy.
 *  All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 **********************************************************************/

#include <pat_app/ExportXML.hpp>
#include <QFile>
#include <QDir>
#include <QDomDocument>
#include <QDomElement>
#include <pat_app/ExportXMLDialog.hpp>
#include <pat_app/PatApp.hpp>
#include <pat_app/PatMainWindow.hpp>

#include <analysisdriver/SimpleProject.hpp>

#include <analysis/Analysis.hpp>
#include <analysis/DataPoint.hpp>
#include <analysis/Problem.hpp>
#include <analysis/InputVariable.hpp>
#include <analysis/InputVariable_Impl.hpp>
#include <analysis/Measure.hpp>
#include <analysis/DataPoint.hpp>
#include <analysis/RubyMeasure.hpp>
#include <analysis/RubyMeasure_Impl.hpp>
#include <analysis/MeasureGroup.hpp>
#include <analysis/MeasureGroup_Impl.hpp>
#include <analysis/WorkflowStep.hpp>

#include <runmanager/lib/Job.hpp>
#include <runmanager/lib/Job_Impl.hpp>

#include <model/Model.hpp>
#include <model/Building.hpp>

#include <utilities/bcl/BCLMeasure.hpp>
#include <utilities/sql/SqlFile.hpp>
#include <utilities/units/Quantity.hpp>
#include <utilities/units/QuantityConverter.hpp>
#include <utilities/units/Unit.hpp>
#include <utilities/units/UnitFactory.hpp>

#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>

#include <QMessageBox>

namespace openstudio {
namespace analysis {
namespace exportxml {

ExportXML::ExportXML()
{
}

ExportXML::~ExportXML()
{
}

bool ExportXML::exportXML(const analysisdriver::SimpleProject project, QString xmlFilePath)
{
  //get the analysis from the project
  Analysis analysis = project.analysis();

  //get all the alternatives
  DataPointVector dataPoints = analysis.dataPoints();
  std::vector<std::string> alternativeNames;
  Q_FOREACH(const DataPoint& datapoint, dataPoints) {
    alternativeNames.push_back(datapoint.name());
  }

  // open modal dialog
  QSharedPointer<ExportXMLDialog> dialog(new ExportXMLDialog(alternativeNames));
  //ExportXMLDialog dialog = new ExportXMLDialog(alternativeNames);

  std::string edaBaselineName = "No EDA Baseline";
  std::string proposedBaselineName = "No Proposed Baseline";
  std::string certificationBaselineName = "No Certification Baseline";

  if (dialog->exec()){
    // get the user selections
    edaBaselineName = dialog->getEDABaseline();
    proposedBaselineName = dialog->getProposedBaseline();
    certificationBaselineName = dialog->getCertificationBaseline();
  }else{
    // user canceled, stop the export process
    return false;
  }

  //start the xml file
  QDomDocument doc;
  doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");

  //analysis (first element)
  QDomElement analysisElem = doc.createElement("analysis");
  doc.appendChild(analysisElem);
  analysisElem.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");

  //simulation_software
  QDomElement softwareElem = doc.createElement("simulation_software");
  analysisElem.appendChild(softwareElem);
  QString softwareName = QString("OpenStudio");
  softwareElem.appendChild(doc.createTextNode(softwareName));

  //get the problem from the project
  Problem problem = analysis.problem();

  //get the input variables from the problem
  //std::vector<InputVariable> variables = problem.variables();

  //alternatives
  int numErrors = 0;
  QString errors;
  QDomElement alternativesElem = doc.createElement("alternatives");
  analysisElem.appendChild(alternativesElem);
  Q_FOREACH(const DataPoint& datapoint, dataPoints) {
    //export the alternative if it has the necessary results
    if ( boost::optional<Attribute> reportAttr = datapoint.getOutputAttribute("report")) {
      std::vector<WorkflowStepJob> jobs = problem.getJobsByWorkflowStep(datapoint, true);
      if ( boost::optional<QDomElement> alternativeElem = exportAlternative(doc, *reportAttr, datapoint, jobs, edaBaselineName, proposedBaselineName, certificationBaselineName) ) {
        alternativesElem.appendChild(*alternativeElem);
      }
    }else{
      numErrors += 1;
      errors += toQString(datapoint.name());
    }
    // drop this DataPoint's Model and SqlFile from memory
    datapoint.clearFileDataFromCache();
  }

  //warn the user if summary results were missing
  if ( numErrors > 0 ) {
    QMessageBox::warning(pat::PatApp::instance()->mainWindow, "Export XML Report - Warnings", errors + QString(" will be skipped; summary results not available.  Make sure you've run the reporting measure 'Xcel EDA Reporting and QAQC'"));
  }

  QFile file(xmlFilePath);
  if (file.open(QFile::WriteOnly)){
    QTextStream textStream(&file);
    textStream << doc.toString(2);
    file.close();
    return true;
  }

  return false;

}

boost::optional<QDomElement> ExportXML::exportAlternative(QDomDocument& doc,
                                                          Attribute& alternativeAttr,
                                                          analysis::DataPoint dataPt,
                                                          std::vector<WorkflowStepJob>& jobs,
                                                          std::string edaBaselineName,
                                                          std::string proposedBaselineName,
                                                          std::string certificationBaselineName)
{
  //start the alternative
  QDomElement alternative = doc.createElement("alternative");

  //name
  QDomElement nameElem = doc.createElement("name");
  alternative.appendChild(nameElem);
  QString name = toQString(dataPt.name());
  nameElem.appendChild(doc.createTextNode(name));

  //baseline type
  if ( dataPt.name() == edaBaselineName ) {
    QDomElement nameElem = doc.createElement("baseline_type");
    alternative.appendChild(nameElem);
    nameElem.appendChild(doc.createTextNode("EDA Baseline"));
  }

  if ( dataPt.name() == proposedBaselineName ) {
    QDomElement nameElem = doc.createElement("baseline_type");
    alternative.appendChild(nameElem);
    nameElem.appendChild(doc.createTextNode("Proposed Baseline"));
  }

  if ( dataPt.name() == certificationBaselineName ) {
    QDomElement nameElem = doc.createElement("baseline_type");
    alternative.appendChild(nameElem);
    nameElem.appendChild(doc.createTextNode("Certification Baseline"));
  }

  //description
  QDomElement descriptionElem = doc.createElement("description");
  alternative.appendChild(descriptionElem);
  QString description = toQString(dataPt.description());
  descriptionElem.appendChild(doc.createTextNode(description));

  //characteristics
  QDomElement characteristicsElem = doc.createElement("characteristics");
  alternative.appendChild(characteristicsElem);

  //building
  QDomElement buildingElem = doc.createElement("building");
  characteristicsElem.appendChild(buildingElem);

  //information stored under "results"
  if ( boost::optional<Attribute> oresultsAttr = alternativeAttr.findChildByName("results") ) {
    Attribute resultsAttr = *oresultsAttr;

    //floor_area
    QDomElement floorAreaElem = doc.createElement("floor_area");
    buildingElem.appendChild(floorAreaElem);
    if ( boost::optional<Attribute> condArea = resultsAttr.findChildByName("floor_area") ) {
      QString floorArea = QString::number(condArea->valueAsDouble());
      floorAreaElem.appendChild(doc.createTextNode(floorArea));
    }
    else {
      QString floorArea = "Building has no conditioned floor area";
      floorAreaElem.appendChild(doc.createTextNode(floorArea));
    }

    //number of measures in a design alt. differentiates whether it is called a measure
    //or a design alternative in Xcel EDA
    double numMeasures = 0.0;

    //measures
    QDomElement measuresElem = doc.createElement("measures");
    alternative.appendChild(measuresElem);
    Q_FOREACH(const WorkflowStepJob& job, jobs) {
      //record the details of the measure in the xml.
      if (boost::optional<QDomElement> measureElem = exportMeasure(doc, job)){
        measuresElem.appendChild(*measureElem);
        numMeasures += 1;
      }
    }

    //alternative_type
    QDomElement altTypeElem = doc.createElement("alternative_type");
    alternative.appendChild(altTypeElem);
    if ( numMeasures > 1 ) {
      QString altType = "design_alternative";
      altTypeElem.appendChild(doc.createTextNode(altType));
    }
    else {
      QString altType = "single_measure";
      altTypeElem.appendChild(doc.createTextNode(altType));
    }

    //results
    QDomElement resultsElem = doc.createElement("results");
    alternative.appendChild(resultsElem);

    //cash flows
    QDomElement cashFlowsElem = doc.createElement("cash_flows");
    resultsElem.appendChild(cashFlowsElem);
    if ( boost::optional<Attribute> cashFlowsAttr = resultsAttr.findChildByName("cash_flows") ) {
      Q_FOREACH( const Attribute & cashFlowAttr, cashFlowsAttr->valueAsAttributeVector()) {
        if ( boost::optional<QDomElement> cashFlowElem = exportCashFlow(doc, cashFlowAttr) ){
          cashFlowsElem.appendChild(*cashFlowElem);
        }
      }
    }

    //annual
    if ( boost::optional<Attribute> annualAttr = resultsAttr.findChildByName("annual") ) {
      if ( boost::optional<QDomElement> annualElem = exportAnnual(doc, *annualAttr) ){
        resultsElem.appendChild(*annualElem);
      }
    }

    //monthly
    if ( boost::optional<Attribute> monthlyAttr = resultsAttr.findChildByName("monthly") ) {
      if ( boost::optional<QDomElement> monthlyElem = exportMonthly(doc, *monthlyAttr) ){
        resultsElem.appendChild(*monthlyElem);
      }
    }

    //checks
    if ( boost::optional<Attribute> checksAttr = alternativeAttr.findChildByName("checks") ) {
      if ( boost::optional<QDomElement> checksElem = exportChecks(doc, *checksAttr) ){
        alternative.appendChild(*checksElem);
      }
    }

  }

  return alternative;
}

boost::optional<QDomElement> ExportXML::exportMeasure(QDomDocument& doc,
                                                      const WorkflowStepJob& wfJob)
{

    WorkflowStep step = wfJob.step;

    //skip
    if ( step.isInputVariable() == false ){
      return boost::none;
    }

    //skip fixed measures (present in all design alternatives)
    if (boost::optional<analysis::Measure> measure = wfJob.measure) {
      if (boost::optional<analysis::AnalysisObject> parObj = measure->parent()) {
        if (boost::optional<MeasureGroup> discVar = parObj->optionalCast<MeasureGroup>()) {
          if (discVar->measures(false).size() == 1) {
            return boost::none;
          }
        }
      }
    }

    //skip reporting measures
    if (boost::optional<analysis::Measure> measure = wfJob.measure) {
      if ( boost::optional<RubyMeasure> rubyMeasure = measure->optionalCast<RubyMeasure>() ) {
        if ( boost::optional<BCLMeasure> bclMeasure = rubyMeasure->measure() ) {
          if (bclMeasure->measureType() == MeasureType::ReportingMeasure ) {
            return boost::none;
          }
        }
      }
    }

    //skip post-process, pre-process, and energyplus jobs
    if ( step.isInputVariable()){
      boost::optional<runmanager::Job> job = wfJob.job;
      if (job == boost::none) {
        return boost::none;
      }
    }

    //this is a measure we want to record
    if (wfJob.job) {

      //start the measure
      QDomElement measureElem = doc.createElement("measure");

      if ( boost::optional<Measure> measure = wfJob.measure ) {

        //name
        QString measureName = "unknown";
        if ( boost::optional<RubyMeasure> rubyMeasure = measure->optionalCast<RubyMeasure>() ) {
          measureName = toQString(rubyMeasure->name());
        }
        QDomElement instanceNameElem = doc.createElement("name");
        measureElem.appendChild(instanceNameElem);
        instanceNameElem.appendChild(doc.createTextNode(measureName));

        //get information out of the measure
        QString measureId = "uuid unknown";
        QString category = "category unknown";
        if ( boost::optional<RubyMeasure> rubyMeasure = measure->optionalCast<RubyMeasure>() ) {
          if ( boost::optional<BCLMeasure> bclMeasure = rubyMeasure->measure() ) {
            measureId = toQString(bclMeasure->uid());
            category = toQString(bclMeasure->taxonomyTag());
          }
        }
        //id
        QDomElement measureIdElem = doc.createElement("id");
        measureElem.appendChild(measureIdElem);
        measureIdElem.appendChild(doc.createTextNode(measureId));

        //category
        QDomElement categoryElem = doc.createElement("category");
        measureElem.appendChild(categoryElem);
        categoryElem.appendChild(doc.createTextNode(category));

        //description
        QDomElement descElem = doc.createElement("description");
        measureElem.appendChild(descElem);
        QString desc = toQString(measure->description());
        descElem.appendChild(doc.createTextNode(desc));
      }

      //get the job errors
      runmanager::JobErrors jobErrs = wfJob.errors().get();

      //initial_condition
      std::string initCondMsg = "";
      std::vector<std::string> initConds =  jobErrs.initialConditions();
      Q_FOREACH(std::string initCond, initConds) {
        boost::regex re("^\\[.*\\]");
        initCond = boost::regex_replace(initCond,re,"");
        initCondMsg += initCond;
      }
      QDomElement initCondElem = doc.createElement("initial_condition");
      measureElem.appendChild(initCondElem);
      initCondElem.appendChild(doc.createTextNode(toQString(initCondMsg)));

      //final_condition
      std::string finCondMsg = "";
      std::vector<std::string> finConds =  jobErrs.finalConditions();
      Q_FOREACH(std::string finCond, finConds) {
        boost::regex re("^\\[.*\\]");
        finCond = boost::regex_replace(finCond,re,"");
        finCondMsg += finCond;
      }
      QDomElement finCondElem = doc.createElement("final_condition");
      measureElem.appendChild(finCondElem);
      finCondElem.appendChild(doc.createTextNode(toQString(finCondMsg)));

      return measureElem;
  }

    return boost::none;

}

boost::optional<QDomElement> ExportXML::exportCashFlow(QDomDocument& doc,
                                                       const Attribute& cashFlowAttr)
  {
    //start the cash flow
    QDomElement cashFlowElem = doc.createElement("cash_flow");

    //values
    QDomElement valuesElem = doc.createElement("values");
    Q_FOREACH( const Attribute & cashFlowValAttr, cashFlowAttr.valueAsAttributeVector()) {
      if ( cashFlowValAttr.name() == "type" ) {
        //cash flow type
        QDomElement cashFlowTypeElem = doc.createElement("type");
        cashFlowElem.appendChild(cashFlowTypeElem);
        cashFlowTypeElem.appendChild(doc.createTextNode(toQString(cashFlowValAttr.valueAsString())));
      }
      if ( cashFlowValAttr.name() == "year" ) {
        QDomElement yearValueElem = doc.createElement("year");
        valuesElem.appendChild(yearValueElem);
        QString annCashVal = QString::number(cashFlowValAttr.valueAsDouble() );
        yearValueElem.appendChild(doc.createTextNode(annCashVal));
      }
    }
    cashFlowElem.appendChild(valuesElem);

    return cashFlowElem;

  }

boost::optional<QDomElement> ExportXML::exportAnnual(QDomDocument& doc,
                                                      const Attribute& annualAttr)
{

  //start the annual results
  QDomElement annualElem = doc.createElement("annual");

  //consumption
  if ( boost::optional<Attribute> consumptionAttr = annualAttr.findChildByName("consumption") ) {

    QDomElement consumptionElem = doc.createElement("consumption");
    annualElem.appendChild(consumptionElem);

    Q_FOREACH( const Attribute & consumptionAttrVal, consumptionAttr->valueAsAttributeVector()) {

      //gas
      if ( consumptionAttrVal.name() == "gas" ) {
        QDomElement fuelTypeElem = doc.createElement("gas");
        consumptionElem.appendChild(fuelTypeElem);
        fuelTypeElem.appendChild(doc.createTextNode(QString::number(consumptionAttrVal.valueAsDouble())));
      }

      //electricity
      if ( consumptionAttrVal.name() == "electricity" ) {
        QDomElement fuelTypeElem = doc.createElement("electricity");
        consumptionElem.appendChild(fuelTypeElem);
        fuelTypeElem.appendChild(doc.createTextNode(QString::number(consumptionAttrVal.valueAsDouble())));
      }

      //other_energy
      if ( consumptionAttrVal.name() == "other_energy" ) {
        QDomElement fuelTypeElem = doc.createElement("other_energy");
        consumptionElem.appendChild(fuelTypeElem);
        fuelTypeElem.appendChild(doc.createTextNode(QString::number(consumptionAttrVal.valueAsDouble())));
      }

      //district_heating
      if ( consumptionAttrVal.name() == "district_heating" ) {
        QDomElement fuelTypeElem = doc.createElement("district_heating");
        consumptionElem.appendChild(fuelTypeElem);
        fuelTypeElem.appendChild(doc.createTextNode(QString::number(consumptionAttrVal.valueAsDouble())));
      }

      //district_cooling
      if ( consumptionAttrVal.name() == "district_cooling" ) {
        QDomElement fuelTypeElem = doc.createElement("district_cooling");
        consumptionElem.appendChild(fuelTypeElem);
        fuelTypeElem.appendChild(doc.createTextNode(QString::number(consumptionAttrVal.valueAsDouble())));
      }

      //water
      if ( consumptionAttrVal.name() == "water" ) {
        QDomElement fuelTypeElem = doc.createElement("water");
        consumptionElem.appendChild(fuelTypeElem);
        fuelTypeElem.appendChild(doc.createTextNode(QString::number(consumptionAttrVal.valueAsDouble())));
      }

    }
  } //end consumption

  //demand
  if ( boost::optional<Attribute> demandAttr = annualAttr.findChildByName("demand") ) {

    QDomElement demandElem = doc.createElement("demand");
    annualElem.appendChild(demandElem);

    Q_FOREACH( const Attribute & demandAttrVal, demandAttr->valueAsAttributeVector()) {

      //electricity_peak_demand
      if ( demandAttrVal.name() == "electricity_peak_demand" ) {
        QDomElement demandTypeElem = doc.createElement("electricity_peak_demand");
        demandElem.appendChild(demandTypeElem);
        demandTypeElem.appendChild(doc.createTextNode(QString::number(demandAttrVal.valueAsDouble())));
      }

      //electricity_annual_avg_peak_demand
      if ( demandAttrVal.name() == "electricity_annual_avg_peak_demand" ) {
        QDomElement demandTypeElem = doc.createElement("electricity_annual_avg_peak_demand");
        demandElem.appendChild(demandTypeElem);
        demandTypeElem.appendChild(doc.createTextNode(QString::number(demandAttrVal.valueAsDouble())));
      }

      //district_cooling_peak_demand
      if ( demandAttrVal.name() == "district_cooling_peak_demand" ) {
        QDomElement demandTypeElem = doc.createElement("district_cooling_peak_demand");
        demandElem.appendChild(demandTypeElem);
        demandTypeElem.appendChild(doc.createTextNode(QString::number(demandAttrVal.valueAsDouble())));
      }

    }
  } //end demand

  //utility_cost
  if ( boost::optional<Attribute> utilityCostAttr = annualAttr.findChildByName("utility_cost") ) {

    QDomElement utilityCostElem = doc.createElement("utility_cost");
    annualElem.appendChild(utilityCostElem);

    Q_FOREACH( const Attribute & utilityCostAttrVal, utilityCostAttr->valueAsAttributeVector()) {

      //electricity
      if ( utilityCostAttrVal.name() == "electricity" ) {
        QDomElement fuelTypeElem = doc.createElement("electricity");
        utilityCostElem.appendChild(fuelTypeElem);
        fuelTypeElem.appendChild(doc.createTextNode(QString::number(utilityCostAttrVal.valueAsDouble())));
      }

      //electricity_consumption_charge
      if ( utilityCostAttrVal.name() == "electricity_consumption_charge" ) {
        QDomElement fuelTypeElem = doc.createElement("electricity_consumption_charge");
        utilityCostElem.appendChild(fuelTypeElem);
        fuelTypeElem.appendChild(doc.createTextNode(QString::number(utilityCostAttrVal.valueAsDouble())));
      }

      //electricity_demand_charge
      if ( utilityCostAttrVal.name() == "electricity_demand_charge" ) {
        QDomElement fuelTypeElem = doc.createElement("electricity_demand_charge");
        utilityCostElem.appendChild(fuelTypeElem);
        fuelTypeElem.appendChild(doc.createTextNode(QString::number(utilityCostAttrVal.valueAsDouble())));
      }

      //gas
      if ( utilityCostAttrVal.name() == "gas" ) {
        QDomElement fuelTypeElem = doc.createElement("gas");
        utilityCostElem.appendChild(fuelTypeElem);
        fuelTypeElem.appendChild(doc.createTextNode(QString::number(utilityCostAttrVal.valueAsDouble())));
      }

      //other_energy
      if ( utilityCostAttrVal.name() == "other_energy" ) {
        QDomElement fuelTypeElem = doc.createElement("other_energy");
        utilityCostElem.appendChild(fuelTypeElem);
        fuelTypeElem.appendChild(doc.createTextNode(QString::number(utilityCostAttrVal.valueAsDouble())));
      }

      //district_heating
      if ( utilityCostAttrVal.name() == "district_heating" ) {
        QDomElement fuelTypeElem = doc.createElement("district_heating");
        utilityCostElem.appendChild(fuelTypeElem);
        fuelTypeElem.appendChild(doc.createTextNode(QString::number(utilityCostAttrVal.valueAsDouble())));
      }

      //district_cooling
      if ( utilityCostAttrVal.name() == "district_cooling" ) {
        QDomElement fuelTypeElem = doc.createElement("district_cooling");
        utilityCostElem.appendChild(fuelTypeElem);
        fuelTypeElem.appendChild(doc.createTextNode(QString::number(utilityCostAttrVal.valueAsDouble())));
      }

      //water
      if ( utilityCostAttrVal.name() == "water" ) {
        QDomElement fuelTypeElem = doc.createElement("water");
        utilityCostElem.appendChild(fuelTypeElem);
        fuelTypeElem.appendChild(doc.createTextNode(QString::number(utilityCostAttrVal.valueAsDouble())));
      }

      //total
      if ( utilityCostAttrVal.name() == "total" ) {
        QDomElement fuelTypeElem = doc.createElement("total");
        utilityCostElem.appendChild(fuelTypeElem);
        fuelTypeElem.appendChild(doc.createTextNode(QString::number(utilityCostAttrVal.valueAsDouble())));
      }

      //end_uses
      if ( utilityCostAttrVal.name() == "end_uses" ) {
        QDomElement endUsesElem = doc.createElement("end_uses");
        utilityCostElem.appendChild(endUsesElem);

        Q_FOREACH( const Attribute & endUsesAttrVal, utilityCostAttrVal.valueAsAttributeVector()) {
          QDomElement endUseElem = doc.createElement(toQString(endUsesAttrVal.name()));
          endUsesElem.appendChild(endUseElem);
          endUseElem.appendChild(doc.createTextNode(QString::number(endUsesAttrVal.valueAsDouble())));
        }

      } //end end_uses

    }
  } //end utility_cost

  return annualElem;
}

boost::optional<QDomElement> ExportXML::exportMonthly(QDomDocument& doc,
                                                      const Attribute& monthlyAttr)
  {

  //start the monthly results
  QDomElement monthlyElem = doc.createElement("monthly");

  //consumption
  if ( boost::optional<Attribute> consumptionAttr = monthlyAttr.findChildByName("consumption") ) {
    QDomElement consumptionElem = doc.createElement("consumption");
    monthlyElem.appendChild(consumptionElem);
    //loop through all end uses
    Q_FOREACH( const Attribute & endUseAttr, consumptionAttr->valueAsAttributeVector()) {
      QDomElement endUseElem = doc.createElement(toQString(endUseAttr.name()));
      consumptionElem.appendChild(endUseElem);
      //loop through all fuel types in this end use
      Q_FOREACH( const Attribute & fuelTypeAttr, endUseAttr.valueAsAttributeVector()) {
        QDomElement fuelTypeElem = doc.createElement(toQString(fuelTypeAttr.name()));
        endUseElem.appendChild(fuelTypeElem);
        //loop through all months in this fuel type in this end use
        Q_FOREACH( const Attribute & monthAttr, fuelTypeAttr.valueAsAttributeVector()) {
          QDomElement monthElem = doc.createElement(toQString(monthAttr.name()));
          fuelTypeElem.appendChild(monthElem);
          monthElem.appendChild(doc.createTextNode(QString::number(monthAttr.valueAsDouble())));
        }
      }
    }
  }

  //demand
  if ( boost::optional<Attribute> demandAttr = monthlyAttr.findChildByName("demand") ) {
    QDomElement demandElem = doc.createElement("demand");
    monthlyElem.appendChild(demandElem);
    //loop through all end uses
    Q_FOREACH( const Attribute & endUseAttr, demandAttr->valueAsAttributeVector()) {
      QDomElement endUseElem = doc.createElement(toQString(endUseAttr.name()));
      demandElem.appendChild(endUseElem);
      //loop through all fuel types in this end use
      Q_FOREACH( const Attribute & fuelTypeAttr, endUseAttr.valueAsAttributeVector()) {
        QDomElement fuelTypeElem = doc.createElement(toQString(fuelTypeAttr.name()));
        endUseElem.appendChild(fuelTypeElem);
        //loop through all months in this fuel type in this end use
        Q_FOREACH( const Attribute & monthAttr, fuelTypeAttr.valueAsAttributeVector()) {
          QDomElement monthElem = doc.createElement(toQString(monthAttr.name()));
          fuelTypeElem.appendChild(monthElem);
          monthElem.appendChild(doc.createTextNode(QString::number(monthAttr.valueAsDouble())));
        }
      }
    }
  }

  return monthlyElem;
}

boost::optional<QDomElement> ExportXML::exportChecks(QDomDocument& doc,
                                                      const Attribute& checksAttr)
  {

  //checks
  QDomElement checksElem = doc.createElement("checks");
  Q_FOREACH( const Attribute & checkAttr, checksAttr.valueAsAttributeVector()) {
    if ( checkAttr.name() == "check" ) {
      QDomElement checkElem = doc.createElement("check");
      checksElem.appendChild(checkElem);
      Q_FOREACH( const Attribute & checkValAttr, checkAttr.valueAsAttributeVector()) {
        if ( checkValAttr.name() == "name" ) {
          QDomElement elem = doc.createElement("name");
          checkElem.appendChild(elem);
          elem.appendChild(doc.createTextNode(toQString(checkValAttr.valueAsString())));
        }
        if ( checkValAttr.name() == "description" ) {
          QDomElement elem = doc.createElement("description");
          checkElem.appendChild(elem);
          elem.appendChild(doc.createTextNode(toQString(checkValAttr.valueAsString())));
        }
        if ( checkValAttr.name() == "category" ) {
          QDomElement elem = doc.createElement("category");
          checkElem.appendChild(elem);
          elem.appendChild(doc.createTextNode(toQString(checkValAttr.valueAsString())));
        }
        if ( checkValAttr.name() == "flag" ) {
          QDomElement elem = doc.createElement("flag");
          checkElem.appendChild(elem);
          elem.appendChild(doc.createTextNode(toQString(checkValAttr.valueAsString())));
        }
      }
    }
  }

  return checksElem;
}

} // exportxml
} // analysis
} // openstudio

max_stars_repo_name: ORNL-BTRIC/OpenStudio

max_issues_repo_name: ORNL-BTRIC/OpenStudio

max_forks_repo_name: ORNL-BTRIC/OpenStudio


text:
//
//  cookie.hpp
//  fibio
//
//  Created by Chen Xu on 14/10/25.
//  Copyright (c) 2014 0d0a.com. All rights reserved.
//

#ifndef fibio_http_common_cookie_hpp
#define fibio_http_common_cookie_hpp

#include <cstdint>
#include <string>
#include <map>
#include <list>
#include <chrono>
#include <boost/lexical_cast.hpp>
#include <fibio/http/common/common_types.hpp>
#include <fibio/http/common/request.hpp>
#include <fibio/http/common/response.hpp>

namespace fibio { namespace http { namespace common {
    typedef std::chrono::time_point<std::chrono::system_clock> timepoint_type;

    struct cookie {
        std::string name;
        std::string value;
        std::string path;
        std::string domain;
        timepoint_type expires;
        bool secure=false;
        bool http_only=false;

        cookie(const std::string &s);
        cookie()=default;

        template<typename T>
        T get() const {
            return boost::lexical_cast<T>(value);
        }

        template<typename T>
        void set(const T &t) {
            value=boost::lexical_cast<std::string>(t);
        }

        bool expired() const {
            return expires<=std::chrono::system_clock::now();
        }

        bool effective(const std::string &url) const;
        bool effective(const parsed_url_type &url) const;

        std::string to_string() const;
        static std::pair<std::string, cookie> from_string(const std::string &s);
    };

    typedef std::map<std::string, cookie> cookie_map;

    bool is_subdomain(const std::string &sd, const std::string &d);

    void parse_cookie(const header_map &h, cookie_map &cookies, bool set);

    struct cookie_jar {
        typedef std::map<std::string, common::cookie_map, common::iless> cookie_storage;

        // Save cookies within response into cookie jar
        void save_cookie(const std::string &full_url, const response &resp);
        // Load effective cookies into request
        void load_cookie(const std::string &full_url, request &req);

    private:
        void add_cookie(const common::cookie &c);
        cookie_storage storage_;
    };
}}} // End of namespace fibio::http::common

#endif

max_stars_repo_name: qicosmos/fibio

max_issues_repo_name: qicosmos/fibio

max_forks_repo_name: qicosmos/fibio


text:
/*
   Copyright 2020-2021 The Silkworm Authors

   Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#pragma once
#ifndef SILKWORM_STAGEDSYNC_RECOVERY_WORKER_HPP_
#define SILKWORM_STAGEDSYNC_RECOVERY_WORKER_HPP_

#include <atomic>
#include <csignal>
#include <string>

#include <boost/signals2.hpp>
#include <ethash/keccak.hpp>

#include <silkworm/concurrency/worker.hpp>
#include <silkworm/crypto/ecdsa.hpp>
#include <silkworm/db/util.hpp>

namespace silkworm::stagedsync::recovery {

//! \brief A recovery package
struct RecoveryPackage {
    BlockNum block_num;     // Block number this package refers to
    ethash::hash256 hash;   // Keccak hash of transaction's rlp representation
    bool odd_y_parity;      // Whether y parity is odd (https://eips.ethereum.org/EIPS/eip-155)
    uint8_t signature[64];  // Signature of transaction
};

//! \brief A threaded worker in charge to recover sender's addresses from transaction signatures
//! \remarks Inherits from silkworm::Worker
class RecoveryWorker final : public silkworm::Worker {
  public:
    //! \brief Status of Recovery worker
    enum class Status {
        Idle = 0,          // Waiting for task
        Working = 1,       // Processing task
        ResultsReady = 2,  // Results ready to collect
        Error = 3,         // Some error encountered. Higher level RecoveryFarm should stop processing
        Aborted = 4,       // A user request for cancellation has been intercepted
    };

    //! \brief Creates an instance of recovery worker
    //! \param [in] id : unique identifier for this instance
    //! \param [in] data_size: sets the amount of memory to allocate for recovered addresses
    //! \remarks data_size is expressed as number of transactions to recover per batch times address size
    explicit RecoveryWorker(uint32_t id, size_t data_size);

    //! \brief Feed the worker with a new set of data to process
    //! \param [in] batch_id : identifier of work batch
    //! \param [in] batch : collection of work packages
    void set_work(uint32_t batch_id, std::vector<RecoveryPackage>& farm_batch);

    //! \brief Return the instance unique identifier
    uint32_t get_id() const { return id_; };

    //! \brief Return the current batch identifier this instance is working on
    uint32_t get_batch_id() const { return batch_id_; };

    //! \brief Return the last error encountered by this Recoverer
    //! \return A string. If empty means no error found
    std::string get_error() const;

    //! \brief Return the Status of this Recoverer
    Status get_status() const;

    //! \brief Serves the processed results to higher level
    //! \param [in/out] out_results : a reference to a vector for results
    //! \return True if the accrued results have been fed into out_results. False otherwise
    //! \remarks This operates oa swap of contents among instance held results and provided reference
    bool pull_results(std::vector<std::pair<BlockNum, ByteView>>& out_results);

    //! \brief Signals connected handlers a task is completed
    boost::signals2::signal<void(RecoveryWorker* sender)> signal_completed;

  private:
    const uint32_t id_;                                     // Current worker identifier
    size_t data_size_;                                      // Size of the recovery data buffer
    uint32_t batch_id_{0};                                  // Current batch identifier
    std::vector<RecoveryPackage> batch_;                    // Batch to process
    uint8_t* data_{nullptr};                                // Pointer to data where results are stored
    secp256k1_context* context_;                            // Elliptic curve context;
    std::vector<std::pair<BlockNum, ByteView>> results_{};  // Results per block pointing to data area
    std::string last_error_{};                              // Description of last error occurrence
    std::atomic<Status> status_{Status::Idle};              // Status of worker

    //! \brief Basic recovery work loop
    //! \remarks Overrides Worker::work()
    void work() final;
};

}  // namespace silkworm::stagedsync::recovery

#endif

max_stars_repo_name: mriccobene/silkworm

max_issues_repo_name: mriccobene/silkworm

max_forks_repo_name: mriccobene/silkworm


text:
#include "db/DB.hpp"

#include <snappy.h>

#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <limits>

#include "base/Logging.hpp"
#include "base/TimeStamp.hpp"
#include "base/WaitGroup.hpp"
#include "db/DB.pb.h"
#include "db/HttpParser.hpp"
#include "db/db_querier.h"
#include "label/EqualMatcher.hpp"
#include "querier/SeriesSetInterface.hpp"
#include "tsdbutil/tsdbutils.hpp"

namespace tsdb {
namespace db {

DB::DB(const std::string& dir, leveldb::DB* db)
    : dir_(dir),
      db_(db),
      head_(new head::HeadType(0, dir, dir, db)),
      cached_querier_(nullptr) {
#if USE_PROTOBUF
  init_http_proto_server();
#else
  init_http_json_server();
#endif
}

void DB::init_http_proto_server() {
  server_.Post("/insert", [this](const httplib::Request& req,
                                 httplib::Response& res) {
    if (!this->cached_appender_) this->cached_appender_ = this->appender();
    std::string data;
    snappy::Uncompress(req.body.data(), req.body.size(), &data);
    InsertSamples samples;
    InsertResults results;
    samples.ParseFromString(data);
    for (int i = 0; i < samples.samples_size(); i++) {
      InsertSample* sample = samples.mutable_samples(i);
      if (sample->type() == InsertSample_InsertType_TS) {
        if (sample->mutable_lset()->tags_size() == 0) {
          leveldb::Status s = this->cached_appender_->add_fast(
              sample->id(), sample->t(), sample->v(0));
          if (!s.ok())
            Add(&results, 0, {});
          else
            Add(&results, sample->id(), {});
        } else {
          label::Labels lset;
          NewTags(&lset, sample->mutable_lset());
          std::pair<uint64_t, leveldb::Status> p =
              this->cached_appender_->add(lset, sample->t(), sample->v(0));
          Add(&results, p.first, {});
        }
      } else if (sample->type() == InsertSample_InsertType_GROUP) {
        std::vector<double> vals;
        for (int j = 0; j < sample->v_size(); j++) vals.push_back(sample->v(j));
        if (sample->mutable_lset()->tags_size() == 0) {
          if (sample->slots_size() == 0) {
            leveldb::Status s =
                this->cached_appender_->add(sample->id(), sample->t(), vals);
            if (!s.ok())
              Add(&results, 0, {});
            else
              Add(&results, sample->id(), {});
          } else {
            std::vector<int> slots;
            for (int j = 0; j < sample->slots_size(); j++)
              vals.push_back(sample->slots(j));
            this->cached_appender_->add(sample->id(), slots, sample->t(), vals);
          }
        } else {
          uint64_t id;
          std::vector<int> slots;
          label::Labels lset;
          NewTags(&lset, sample->mutable_lset());
          std::vector<label::Labels> lsets;
          for (int j = 0; j < sample->lsets_size(); j++) {
            label::Labels l;
            NewTags(&l, sample->mutable_lsets(j));
            lsets.push_back(std::move(l));
          }
          this->cached_appender_->add(lset, lsets, sample->t(), vals, &id,
                                      &slots);
          Add(&results, id, slots);
        }
      }
    }

    this->cached_appender_->commit();
    data.clear();
    results.SerializeToString(&data);
    res.set_content(data, "text/plain");
  });

  server_.Post(
      "/query", [this](const httplib::Request& req, httplib::Response& res) {
        QueryRequest request;
        request.ParseFromString(req.body);

        if (!this->cached_querier_)
          this->cached_querier_ = this->querier(request.mint(), request.maxt());
        if (this->cached_querier_->mint() != request.mint() ||
            this->cached_querier_->maxt() != request.maxt()) {
          delete this->cached_querier_;
          this->cached_querier_ = querier(request.mint(), request.maxt());
        }
        std::vector<::tsdb::label::MatcherInterface*> matchers;
        for (int i = 0; i < request.lset().tags_size(); i++)
          matchers.push_back(new ::tsdb::label::EqualMatcher(
              request.lset().tags(i).name(), request.lset().tags(i).value()));

        QueryResults results;
        uint64_t id;

        std::unique_ptr<::tsdb::querier::SeriesSetInterface> ss =
            this->cached_querier_->select(matchers);
        while (ss->next()) {
          std::unique_ptr<::tsdb::querier::SeriesInterface> series = ss->at();
          id = ss->current_tsid();

          if (series->type() == tsdb::querier::kTypeSeries) {
            QueryResult* result = results.add_results();
            std::unique_ptr<::tsdb::querier::SeriesIteratorInterface> it =
                series->iterator();
            while (it->next()) {
              QuerySample* sample = result->add_values();
              sample->set_t(it->at().first);
              sample->set_v(it->at().second);
            }

            if (request.return_metric()) {
              Tags* tags = result->mutable_metric();
              NewTags(series->labels(), tags);
            }
            result->set_id(id);
          } else if (series->type() == tsdb::querier::kTypeGroup) {
            QueryResult* result = results.add_results();
            result->set_id(id);
            while (series->next()) {
              QueryGroupSample* sample = result->add_series();
              std::unique_ptr<::tsdb::querier::SeriesIteratorInterface> it =
                  series->iterator();
              while (it->next()) {
                QuerySample* sample2 = sample->add_values();
                sample2->set_t(it->at().first);
                sample2->set_v(it->at().second);
              }

              if (request.return_metric()) {
                label::Labels lset;
                series->labels(lset);
                Tags* tags = sample->mutable_metric();
                NewTags(lset, tags);
              }
            }
          }
        }

        for (size_t i = 0; i < matchers.size(); i++) delete matchers[i];

        std::string data, compressed_data;
        results.SerializeToString(&data);
        snappy::Compress(data.data(), data.size(), &compressed_data);
        res.set_content(compressed_data, "text/plain");
      });

  std::thread t([this]() { this->server_.listen("127.0.0.1", 9966); });
  t.detach();
}

void DB::init_http_json_server() {
  server_.Post("/insert", [this](const httplib::Request& req,
                                 httplib::Response& res) {
    if (!this->cached_appender_) this->cached_appender_ = this->appender();
    InsertParser parser(req.body);
    InsertResultEncoder encoder;
    while (parser.next()) {
      if (parser.type() == kTS) {
        if (parser.lset().empty())
          this->cached_appender_->add_fast(parser.id(), parser.t(),
                                           parser.v()[0]);
        else {
          std::pair<uint64_t, leveldb::Status> p = this->cached_appender_->add(
              parser.lset(), parser.t(), parser.v()[0]);
          encoder.add(p.first, {});
        }
      } else if (parser.type() == kGroup) {
        if (parser.lset().empty()) {
          if (parser.slots().empty())
            this->cached_appender_->add(parser.id(), parser.t(), parser.v());
          else
            this->cached_appender_->add(parser.id(), parser.slots(), parser.t(),
                                        parser.v());
        } else {
          uint64_t id;
          std::vector<int> slots;
          this->cached_appender_->add(parser.lset(), parser.lsets(), parser.t(),
                                      parser.v(), &id, &slots);
          encoder.add(id, slots);
        }
      }
    }
    this->cached_appender_->commit();
    encoder.close();
    res.set_content(encoder.str(), "text/plain");
  });

  server_.Post(
      "/query", [this](const httplib::Request& req, httplib::Response& res) {
        QueryParser parser(req.body);
        if (parser.error()) {
          res.set_content(parser.error().error(), "text/plain");
          return;
        }
        if (!this->cached_querier_)
          this->cached_querier_ = this->querier(parser.mint(), parser.maxt());
        if (this->cached_querier_->mint() != parser.mint() &&
            this->cached_querier_->maxt() != parser.maxt()) {
          delete this->cached_querier_;
          this->cached_querier_ = querier(parser.mint(), parser.maxt());
        }
        std::vector<::tsdb::label::MatcherInterface*> matchers;
        for (const auto& l : parser.matchers())
          matchers.push_back(new ::tsdb::label::EqualMatcher(l.label, l.value));

        QueryResultEncoder encoder;
        uint64_t id;

        std::unique_ptr<::tsdb::querier::SeriesSetInterface> ss =
            this->cached_querier_->select(matchers);
        while (ss->next()) {
          std::unique_ptr<::tsdb::querier::SeriesInterface> series = ss->at();
          id = ss->current_tsid();

          if (series->type() == tsdb::querier::kTypeSeries) {
            std::vector<int64_t> timestamps;
            std::vector<double> values;
            std::unique_ptr<::tsdb::querier::SeriesIteratorInterface> it =
                series->iterator();
            while (it->next()) {
              timestamps.push_back(it->at().first);
              values.push_back(it->at().second);
            }

            if (parser.metric() == 1)
              encoder.write(series->labels(), id, timestamps, values);
            else
              encoder.write({}, id, timestamps, values);
          } else if (series->type() == tsdb::querier::kTypeGroup) {
            std::vector<std::vector<int64_t>> timestamps;
            std::vector<std::vector<double>> values;
            std::vector<label::Labels> lsets;
            while (series->next()) {
              std::vector<int64_t> tmp_times;
              std::vector<double> tmp_values;
              std::unique_ptr<::tsdb::querier::SeriesIteratorInterface> it =
                  series->iterator();
              while (it->next()) {
                tmp_times.push_back(it->at().first);
                tmp_values.push_back(it->at().second);
              }

              if (parser.metric() == 1) {
                label::Labels lset;
                series->labels(lset);
                lsets.push_back(std::move(lset));
              }
              timestamps.push_back(std::move(tmp_times));
              values.push_back(std::move(tmp_values));
            }
            if (parser.metric() == 1)
              encoder.write({}, lsets, id, {}, timestamps, values);
            else
              encoder.write({}, {}, id, {}, timestamps, values);
          }
        }

        for (size_t i = 0; i < matchers.size(); i++) delete matchers[i];

        encoder.close();
        res.set_content(encoder.str(), "text/plain");
      });

  std::thread t([this]() { this->server_.listen("127.0.0.1", 9966); });
  t.detach();
}

DB::~DB() {
  if (cached_querier_) delete cached_querier_;
  delete db_;
  server_.stop();
}

void DB::purge_time(int64_t timestamp) {
  db_->PurgeTime(timestamp);
  head_->purge_time(timestamp);
}

}  // namespace db
}  // namespace tsdb

max_stars_repo_name: naivewong/timeunion

max_issues_repo_name: naivewong/timeunion

max_forks_repo_name: naivewong/timeunion


text:
/*
// Copyright (c) 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#pragma once

#include <boost/container/flat_map.hpp>
#include <node.hpp>
#include <utils/json_utils.hpp>

namespace redfish
{

/**
 * SystemsCollection derived class for delivering ComputerSystems Collection
 * Schema
 */
class SystemsCollection : public Node
{
  public:
    SystemsCollection(CrowApp &app) : Node(app, "/redfish/v1/Systems/")
    {
        entityPrivileges = {
            {boost::beast::http::verb::get, {{"Login"}}},
            {boost::beast::http::verb::head, {{"Login"}}},
            {boost::beast::http::verb::patch, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::put, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::delete_, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
    }

  private:
    void doGet(crow::Response &res, const crow::Request &req,
               const std::vector<std::string> &params) override
    {
        BMCWEB_LOG_DEBUG << "Get list of available boards.";
        std::shared_ptr<AsyncResp> asyncResp = std::make_shared<AsyncResp>(res);
        res.jsonValue["@odata.type"] =
            "#ComputerSystemCollection.ComputerSystemCollection";
        res.jsonValue["@odata.id"] = "/redfish/v1/Systems";
        res.jsonValue["@odata.context"] =
            "/redfish/v1/"
            "$metadata#ComputerSystemCollection.ComputerSystemCollection";
        res.jsonValue["Name"] = "Computer System Collection";

        nlohmann::json &systemArrary = res.jsonValue["Members"];
        systemArrary.push_back({{"@odata.id", "/redfish/v1/Systems/system1"}});
        systemArrary.push_back({{"@odata.id", "/redfish/v1/Systems/system2"}});
        systemArrary.push_back({{"@odata.id", "/redfish/v1/Systems/system3"}});
        res.jsonValue["Memebers@odata.count"] = systemArrary.size();
        res.end();
    }
};

/**
 * SystemActionsReset class supports handle POST method for Reset action.
 * The class retrieves and sends data directly to D-Bus.
 */
class SystemActionsReset : public Node
{
  public:
    SystemActionsReset(CrowApp &app) :
        Node(app, "/redfish/v1/Systems/<str>/Actions/ComputerSystem.Reset/",
             std::string())
    {
        entityPrivileges = {
            {boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
    }

  private:
    /**
     * Function handles POST method request.
     * Analyzes POST body message before sends Reset request data to D-Bus.
     */
    void doPost(crow::Response &res, const crow::Request &req,
                const std::vector<std::string> &params) override
    {
    }
};

/**
 * Systems derived class for delivering Computer Systems Schema.
 */
class Systems : public Node
{
  public:
    /*
     * Default Constructor
     */
    Systems(CrowApp &app) :
        Node(app, "/redfish/v1/Systems/<str>/", std::string())
    {
        entityPrivileges = {
            {boost::beast::http::verb::get, {{"Login"}}},
            {boost::beast::http::verb::head, {{"Login"}}},
            {boost::beast::http::verb::patch, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::put, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::delete_, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
    }

  private:
    /**
     * Functions triggers appropriate requests on DBus
     */
    void doGet(crow::Response &res, const crow::Request &req,
               const std::vector<std::string> &params) override
    {
        // Check if there is required param, truly entering this shall be
        // impossible
        if (params.size() != 1)
        {
            messages::internalError(res);
            res.end();
            return;
        }

        const std::string &name = params[0];

        res.jsonValue["@odata.type"] = "#ComputerSystem.v1_5_1.ComputerSystem";
        res.jsonValue["@odata.context"] =
            "/redfish/v1/$metadata#ComputerSystem.ComputerSystem";
        res.jsonValue["SystemType"] = "Physical";
        res.jsonValue["Description"] = "Computer System";
        res.jsonValue["Boot"]["BootSourceOverrideEnabled"] =
            "Disabled"; // TODO(Dawid), get real boot data
        res.jsonValue["Boot"]["BootSourceOverrideTarget"] =
            "None"; // TODO(Dawid), get real boot data
        res.jsonValue["Boot"]["BootSourceOverrideMode"] =
            "Legacy"; // TODO(Dawid), get real boot data
        res.jsonValue["Boot"]
                     ["BootSourceOverrideTarget@Redfish.AllowableValues"] = {
            "None",      "Pxe",       "Hdd", "Cd",
            "BiosSetup", "UefiShell", "Usb"}; // TODO(Dawid), get real boot
                                              // data
        res.jsonValue["ProcessorSummary"]["Count"] = 2;
        res.jsonValue["ProcessorSummary"]["Status"]["State"] = "Enabled";
        res.jsonValue["MemorySummary"]["TotalSystemMemoryGiB"] = 96;
        res.jsonValue["MemorySummary"]["Status"]["State"] = "Enabled";
        res.jsonValue["@odata.id"] = "/redfish/v1/Systems/" + name;

        res.jsonValue["Processors"] = {
            {"@odata.id", "/redfish/v1/Systems/" + name + "/Processors"}};
        res.jsonValue["Memory"] = {
            {"@odata.id", "/redfish/v1/Systems/" + name + "/Memory"}};
        // TODO Need to support ForceRestart.
        res.jsonValue["Actions"]["#ComputerSystem.Reset"] = {
            {"target",
             "/redfish/v1/Systems/" + name + "/Actions/ComputerSystem.Reset"},
            {"ResetType@Redfish.AllowableValues",
             {"On", "ForceOff", "GracefulRestart", "GracefulShutdown"}}};

        res.jsonValue["LogServices"] = {
            {"@odata.id", "/redfish/v1/Systems/" + name + "/LogServices"}};

        res.end();
    }

    void doPatch(crow::Response &res, const crow::Request &req,
                 const std::vector<std::string> &params) override
    {
    }
};

class ProcessorCollection : public Node
{
  public:
    ProcessorCollection(CrowApp &app) :
        Node(app, "/redfish/v1/Systems/<str>/Processors", std::string())
    {
        entityPrivileges = {
            {boost::beast::http::verb::get, {{"Login"}}},
            {boost::beast::http::verb::head, {{"Login"}}},
            {boost::beast::http::verb::patch, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::put, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::delete_, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
    }

  private:
    void getProcessorList(const std::string &chassis_name,
                          std::shared_ptr<AsyncResp> asyncResp)
    {
        nlohmann::json &chassisArray = asyncResp->res.jsonValue["Members"];
        chassisArray = nlohmann::json::array();
        chassisArray.push_back(
            {{"@odata.id",
              "/redfish/v1/Systems/" + chassis_name + "/Processors/cpu0"}});
        chassisArray.push_back(
            {{"@odata.id",
              "/redfish/v1/Systems/" + chassis_name + "/Processors/cpu1"}});
        asyncResp->res.jsonValue["Members@odata.count"] = chassisArray.size();
    }

    void doGet(crow::Response &res, const crow::Request &req,
               const std::vector<std::string> &params) override
    {
        if (params.size() != 1)
        {
            messages::internalError(res);
            res.end();
            return;
        }
        const std::string &chassisId = params[0];

        res.jsonValue["@odata.type"] =
            "#ProcessorCollection.ProcessorCollection";
        res.jsonValue["@odata.id"] =
            "/redfish/v1/Systems/" + chassisId + "/Processors";
        res.jsonValue["@odata.context"] =
            "/redfish/v1/$metadata#ProcessorCollection.ProcessorCollection";
        res.jsonValue["Name"] = "Processors Collection";
        auto asyncResp = std::make_shared<AsyncResp>(res);
        getProcessorList(chassisId, asyncResp);
    }
};

class MemoryCollection : public Node
{
  public:
    MemoryCollection(CrowApp &app) :
        Node(app, "/redfish/v1/Systems/<str>/Memory", std::string())
    {
        entityPrivileges = {
            {boost::beast::http::verb::get, {{"Login"}}},
            {boost::beast::http::verb::head, {{"Login"}}},
            {boost::beast::http::verb::patch, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::put, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::delete_, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
    }

  private:
    void getMemoryList(const std::string &chassis_name,
                       std::shared_ptr<AsyncResp> asyncResp)
    {
        nlohmann::json &chassisArray = asyncResp->res.jsonValue["Members"];
        chassisArray = nlohmann::json::array();
        chassisArray.push_back(
            {{"@odata.id",
              "/redfish/v1/Systems/" + chassis_name + "/Memory/mem0"}});
        chassisArray.push_back(
            {{"@odata.id",
              "/redfish/v1/Systems/" + chassis_name + "/Memory/mem1"}});
        chassisArray.push_back(
            {{"@odata.id",
              "/redfish/v1/Systems/" + chassis_name + "/Memory/mem2"}});
        chassisArray.push_back(
            {{"@odata.id",
              "/redfish/v1/Systems/" + chassis_name + "/Memory/mem3"}});
        asyncResp->res.jsonValue["Members@odata.count"] = chassisArray.size();
    }

    void doGet(crow::Response &res, const crow::Request &req,
               const std::vector<std::string> &params) override
    {
        if (params.size() != 1)
        {
            messages::internalError(res);
            res.end();
            return;
        }
        const std::string &chassisId = params[0];

        res.jsonValue["@odata.type"] = "#MemoryCollection.MemoryCollection";
        res.jsonValue["@odata.id"] =
            "/redfish/v1/Systems/" + chassisId + "/Memory";
        res.jsonValue["@odata.context"] =
            "/redfish/v1/$metadata#MemoryCollection.MemoryCollection";
        res.jsonValue["Name"] = "Memory Collection";
        auto asyncResp = std::make_shared<AsyncResp>(res);
        getMemoryList(chassisId, asyncResp);
    }
};

class Processor : public Node
{
  public:
    /*
     * Default Constructor
     */
    Processor(CrowApp &app) :
        Node(app, "/redfish/v1/Systems/<str>/Processors/<str>", std::string(),
             std::string())
    {
        entityPrivileges = {
            {boost::beast::http::verb::get, {{"Login"}}},
            {boost::beast::http::verb::head, {{"Login"}}},
            {boost::beast::http::verb::patch, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::put, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::delete_, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
    }

  private:
    /**
     * Functions triggers appropriate requests on DBus
     */
    void doGet(crow::Response &res, const crow::Request &req,
               const std::vector<std::string> &params) override
    {
        // Check if there is required param, truly entering this shall be
        // impossible
        if (params.size() != 2)
        {
            messages::internalError(res);
            res.end();
            return;
        }
        const std::string &systemId = params[0];
        const std::string &processorId = params[1];

        res.jsonValue["@odata.id"] =
            "/redfish/v1/Systems/" + systemId + "/Processors/" + processorId;
        res.jsonValue["@odata.type"] = "#Processor.v1_3_2.Processor";
        res.jsonValue["@odata.context"] =
            "/redfish/v1/$metadata#Processor.Processor";
        res.jsonValue["Manufacturer"] = "Intel";
        res.jsonValue["Model"] = "Intel(R) Xeon(R) Platinum 8176 CPU @ 2.10GHz";
        res.jsonValue["MaxSpeedMHz"] = 2100;
        res.jsonValue["TDPWatts"] = 165;
        res.jsonValue["TotalCores"] = 28;

        nlohmann::json &status = res.jsonValue["Status"];
        status["State"] = "Enabled";
        status["Health"] = "OK";
        status["HealthRollup"] = {};
        res.end();
    }
};
class Memory : public Node
{
  public:
    /*
     * Default Constructor
     */
    Memory(CrowApp &app) :
        Node(app, "/redfish/v1/Systems/<str>/Memory/<str>", std::string(),
             std::string())
    {
        entityPrivileges = {
            {boost::beast::http::verb::get, {{"Login"}}},
            {boost::beast::http::verb::head, {{"Login"}}},
            {boost::beast::http::verb::patch, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::put, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::delete_, {{"ConfigureComponents"}}},
            {boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
    }

  private:
    /**
     * Functions triggers appropriate requests on DBus
     */
    void doGet(crow::Response &res, const crow::Request &req,
               const std::vector<std::string> &params) override
    {
        // Check if there is required param, truly entering this shall be
        // impossible
        if (params.size() != 2)
        {
            messages::internalError(res);
            res.end();
            return;
        }
        // Check if there is required param, truly entering this shall be

        const std::string &systemId = params[0];
        const std::string &memId = params[1];

        res.jsonValue["@odata.id"] =
            "/redfish/v1/Systems/" + systemId + "/Memory/" + memId;
        res.jsonValue["@odata.type"] = "#Memory.v1_0_0.Memory";
        res.jsonValue["@odata.context"] = "/redfish/v1/$metadata#Memory.Memory";
        res.jsonValue["CapacityMiB"] = 16 * 1024;
        res.jsonValue["Meanufacturer"] = "Samsung";
        if (memId == "mem0")
            res.jsonValue["SerialNumber"] = "390FB680";
        else if (memId == "mem1")
            res.jsonValue["SerialNumber"] = "393BE2A3";
        else if (memId == "mem2")
            res.jsonValue["SerialNumber"] = "390FCBBD";
        else if (memId == "mem3")
            res.jsonValue["SerialNumber"] = "39359D7F";
        else
            res.jsonValue["SerialNumber"] = "39359D93";
        nlohmann::json &status = res.jsonValue["Status"];
        status["State"] = "Enabled";
        status["Health"] = "OK";
        status["HealthRollup"] = {};

        res.jsonValue["AllowedSpeedsMHz"] = 2133;
        res.end();
    }
};
} // namespace redfish

max_stars_repo_name: inspur-bmc/rmcweb

max_issues_repo_name: inspur-bmc/rmcweb

max_forks_repo_name: inspur-bmc/rmcweb


text:
/* vim:set ts=3 sw=3 sts=3 et: */
/**
 * Copyright © 2008-2013 Last.fm Limited
 *
 * This file is part of libmoost.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

/// \file
/// Mock key value store connections for testing.
/// Doesn't persist anything but multiple mock connections
/// will access the same underlying singleton in-memory store.

#ifndef FM_LAST_KVSTORE_MOCK_CONNECTION_HPP
#define FM_LAST_KVSTORE_MOCK_CONNECTION_HPP

#include "i_kyoto_tycoon_connection.h"

#include <string>
#include <vector>
#include <map>
#include <ctime>

#include <boost/thread/mutex.hpp>

namespace moost { namespace kvstore {

class DefaultAccessPolicy
{
public:
   template <class StoreT>
   static boost::shared_array<char> get(StoreT& store, const char* pkey, size_t ksize, size_t& vsize)
   {
      std::string key(pkey, ksize);
      return store.get(key, vsize);
   }

   // throws on failure, supply key "fail" to force failure
   template <class StoreT>
   static void set(StoreT& store, const char* pkey, size_t ksize, const char* pval, size_t vsize)
   {
      std::string key(pkey, ksize);
      store.set(key, pval, vsize);
   }

   // throws on failure, supply key "fail" to force failure
   template <class StoreT>
   static void cache(StoreT& store, const char* pkey, size_t ksize, const char* pval, size_t vsize, int expiryTime)
   {
      std::string key(pkey, ksize);
      store.cache(key, pval, vsize, expiryTime);
   }
};

template <class AccessPolicy = DefaultAccessPolicy>
class MockKyotoTycoonConnection : public IKyotoTycoonConnection
{
public:

   MockKyotoTycoonConnection() : isOpen_(false) { }

   ~MockKyotoTycoonConnection() { close(); }

   void open(const std::string& /*host*/, int /*port*/, int /*timeoutMs*/)
   {
      if (isOpen_) { throw std::runtime_error("The connection is already open"); }
      // initialize singleton
      store();
      isOpen_ = true;
   }

   void close()
   {
      isOpen_ = false;
   }

public:

   // if key is found then return value is a C-style string
   // of length vsize (not including the trailing null byte)
   boost::shared_array<char> get(const void* pkey, size_t ksize, size_t& vsize) const
   {
      assert_data_store_open();
      return AccessPolicy::get(store(), reinterpret_cast<const char *>(pkey), ksize, vsize);
   }

   // throws on failure, supply key "fail" to force failure
   virtual void set(const void* pkey, size_t ksize, const void* pval, size_t vsize) const
   {
      assert_data_store_open();
      AccessPolicy::set(store(), reinterpret_cast<const char *>(pkey), ksize, reinterpret_cast<const char *>(pval), vsize);
   }

   // throws on failure, supply key "fail" to force failure
   virtual void cache(const void* pkey, size_t ksize, const void* pval, size_t vsize, boost::int64_t expirySecs) const
   {
      assert_data_store_open();
      boost::int64_t expiryTime = time(0) + expirySecs;
      AccessPolicy::cache(store(), reinterpret_cast<const char *>(pkey), ksize, reinterpret_cast<const char *>(pval), vsize, expiryTime);
   }

private:

   void assert_data_store_open() const
   {
      assert(isOpen_);
      if (!isOpen_)
         throw std::runtime_error("Mock Kyoto Tycoon connection not open");
   }

private:

   class Store
   {
   private:

      typedef std::vector<char> entry_t;
      typedef std::map<std::string, entry_t> store_t;
      typedef std::map<std::string, time_t> expiry_store_t;

      mutable boost::mutex mutex_;  // synchronize access to store and expiry store
      store_t db_;
      expiry_store_t expiry_;

   public:

      // return a copy of the stored char*
      // or 0 if not found
      boost::shared_array<char> get(const std::string& key, size_t& vsize) const
      {
         boost::shared_array<char> val;
         vsize = 0;
         time_t expiry;

         boost::mutex::scoped_lock lock(mutex_);

         if (!get(key, expiry, expiry_) || expiry >= time(0))
         {
            entry_t entry;
            if (get(key, entry, db_))
            {
               vsize = entry.size();
               val.reset(new char[vsize+1]);
               memcpy(val.get(), &entry[0], entry.size());
               val[vsize] = 0;
            }
         }

         return val;
      }

      void set(const std::string& key, const char* val, size_t vsize)
      {
         boost::mutex::scoped_lock lock(mutex_);
         db_[key].assign(val, val + vsize);
         // remove any existing expiry time for key
         expiry_store_t::iterator it = expiry_.find(key);
         if (it != expiry_.end())
            expiry_.erase(it);
      }

     void cache(const std::string& key, const char* val, size_t vsize, boost::int64_t expirySecs)
      {
         boost::mutex::scoped_lock lock(mutex_);
         db_[key].assign(val, val + vsize);
         expiry_[key] = time(0) + static_cast<time_t>(expirySecs);
      }

   private:

      template <typename TKey, typename TVal, typename TMap>
      bool get(const TKey& key, TVal& val, TMap& store) const
      {
         typename TMap::const_iterator it = store.find(key);
         bool found = (it != store.end());
         if (found)
            val = it->second;
         return found;
      }
   };

   bool isOpen_;

   // singleton store
   static Store& store()
   {
      static Store store_;
      return store_;
   }
};

}}  // end namespace

#endif

max_stars_repo_name: lastfm/libmoost

max_issues_repo_name: lastfm/libmoost

max_forks_repo_name: lastfm/libmoost


text: #include <boost/units/is_unit.hpp>


text:
/*
 * Copyright (c) 2013, Christian Gehring, Hannes Sommer, Paul Furgale, Remo Diethelm
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Autonomous Systems Lab, ETH Zurich nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Christian Gehring, Hannes Sommer, Paul Furgale,
 * Remo Diethelm BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
*/

#include <iostream>

#include <Eigen/Core>

#include <gtest/gtest.h>

#include "kindr/rotations/RotationDiffEigen.hpp"
#include "kindr/common/gtest_eigen.hpp"
#include "kindr/common/common.hpp"

namespace rot = kindr::rotations::eigen_impl;

template <typename ImplementationPair>
struct RotationDiffPairTest : public ::testing::Test {
  typedef typename ImplementationPair::first_type Rotation;
  typedef typename Rotation::Scalar RotationScalar;
  typedef typename ImplementationPair::second_type RotationDiff;
  typedef typename RotationDiff::Scalar RotationDiffScalar;
  typedef rot::LocalAngularVelocity<RotationDiffScalar, RotationDiff::Usage> LocalAngularVelocity;
  typedef typename rot::AngleAxis<RotationScalar, Rotation::Usage> AngleAxis;
  std::vector<Rotation> rotations;
  std::vector<LocalAngularVelocity> angularVelocities;

  RotationDiffPairTest() {
    rotations.push_back(Rotation());   // identity rotation
    rotations.push_back(Rotation(AngleAxis(kindr::common::internal::NumTraits<RotationScalar>::dummy_precision()/10.0, 1.0, 0, 0)));  // small angle
    rotations.push_back(Rotation(AngleAxis(kindr::common::internal::NumTraits<RotationScalar>::dummy_precision()/10.0, 0, 1.0, 0)));  // small angle
    rotations.push_back(Rotation(AngleAxis(kindr::common::internal::NumTraits<RotationScalar>::dummy_precision()/10.0, 0, 0, 1.0)));  // small angle
    rotations.push_back(Rotation(AngleAxis(1.3, 1.0, 0, 0))); // large angle
    rotations.push_back(Rotation(AngleAxis(1.3, 0, 1.0, 0))); // large angle
    rotations.push_back(Rotation(AngleAxis(1.3, 0, 0, 1.0))); // large angle

    angularVelocities.push_back(LocalAngularVelocity());  // zero velocity
    angularVelocities.push_back(LocalAngularVelocity(kindr::common::internal::NumTraits<RotationScalar>::dummy_precision()/10.0, 0.0, 0.0));
    angularVelocities.push_back(LocalAngularVelocity(0.0, kindr::common::internal::NumTraits<RotationScalar>::dummy_precision()/10.0, 0.0));
    angularVelocities.push_back(LocalAngularVelocity(0.0, 0.0, kindr::common::internal::NumTraits<RotationScalar>::dummy_precision()/10.0));
    angularVelocities.push_back(LocalAngularVelocity(0.1, 0.0, 0.0));
    angularVelocities.push_back(LocalAngularVelocity(0.0, 0.1, 0.0));
    angularVelocities.push_back(LocalAngularVelocity(0.0, 0.0, 0.1));

    angularVelocities.push_back(LocalAngularVelocity(2.2, 3.3, 4.4));
  }

};

typedef ::testing::Types<
  std::pair<rot::RotationQuaternionAD, rot::RotationQuaternionDiffAD>,
  std::pair<rot::RotationQuaternionAF, rot::RotationQuaternionDiffAF>,
  std::pair<rot::RotationQuaternionPD, rot::RotationQuaternionDiffPD>,
  std::pair<rot::RotationQuaternionPF, rot::RotationQuaternionDiffPF>,

  std::pair<rot::RotationMatrixAD, rot::RotationMatrixDiffAD>,
  std::pair<rot::RotationMatrixAF, rot::RotationMatrixDiffAF>,
  std::pair<rot::RotationMatrixPD, rot::RotationMatrixDiffPD>,
  std::pair<rot::RotationMatrixPF, rot::RotationMatrixDiffPF>,

//  std::pair<rot::EulerAnglesZyxAD, rot::EulerAnglesZyxDiffAD>,
//  std::pair<rot::EulerAnglesZyxAF, rot::EulerAnglesZyxDiffAF>,
  std::pair<rot::EulerAnglesZyxPD, rot::EulerAnglesZyxDiffPD>,
  std::pair<rot::EulerAnglesZyxPF, rot::EulerAnglesZyxDiffPF>,

//  std::pair<rot::EulerAnglesXyzAD, rot::EulerAnglesXyzDiffAD>,
//  std::pair<rot::EulerAnglesXyzAF, rot::EulerAnglesXyzDiffAF>,
  std::pair<rot::EulerAnglesXyzPD, rot::EulerAnglesXyzDiffPD>,
  std::pair<rot::EulerAnglesXyzPF, rot::EulerAnglesXyzDiffPF>
> TypeRotationAndRotationDiffPairs;

TYPED_TEST_CASE(RotationDiffPairTest, TypeRotationAndRotationDiffPairs);

TYPED_TEST(RotationDiffPairTest, testConversionToLocalAngularVelocity)
{
  typedef typename TestFixture::RotationDiff RotationDiff;
  typedef typename TestFixture::LocalAngularVelocity LocalAngularVelocity;

  for (auto rotation : this->rotations) {
     for (auto angularVelocity : this->angularVelocities) {
       RotationDiff rotDiff(rotation, angularVelocity);
       LocalAngularVelocity angularVelocity2(rotation, rotDiff);
//       LocalAngularVelocity angularVelocity3 = rotDiff.template cast<LocalAngularVelocity>(rotation);
       ASSERT_NEAR(angularVelocity.x(),angularVelocity2.x(),1e-6) << "rotation: " << rotation << " angularVelocity: " << angularVelocity  << " angularVelocity2: " << angularVelocity2 << " rotDiff: " << rotDiff;
       ASSERT_NEAR(angularVelocity.y(),angularVelocity2.y(),1e-6) << "rotation: " << rotation << " angularVelocity: " << angularVelocity  << " angularVelocity2: " << angularVelocity2 << " rotDiff: " << rotDiff;
       ASSERT_NEAR(angularVelocity.z(),angularVelocity2.z(),1e-6) << "rotation: " << rotation << " angularVelocity: " << angularVelocity  << " angularVelocity2: " << angularVelocity2 << " rotDiff: " << rotDiff;
     }
  }
}

template <typename ImplementationPair>
struct RotationDiffSingleTest : public ::testing::Test {
  typedef typename ImplementationPair::first_type RotationQuaternion;
  typedef typename RotationQuaternion::Scalar RotationScalar;
  typedef typename ImplementationPair::second_type RotationQuaternionDiff;
  typedef typename RotationQuaternionDiff::Scalar RotationDiffScalar;
  typedef rot::LocalAngularVelocity<RotationDiffScalar, RotationQuaternionDiff::Usage> LocalAngularVelocity;
//  typedef rot::GlobalAngularVelocity<RotationDiffScalar, RotationDiff::Usage> GlobalAngularVelocity;
  typedef typename rot::AngleAxis<RotationScalar, RotationQuaternion::Usage> AngleAxis;
  std::vector<RotationQuaternion> rotationQuaternions;
  std::vector<LocalAngularVelocity> angularVelocities;

  RotationDiffSingleTest() {
    rotationQuaternions.push_back(RotationQuaternion(AngleAxis()));   // identity rotation
    rotationQuaternions.push_back(RotationQuaternion(AngleAxis(kindr::common::internal::NumTraits<RotationScalar>::dummy_precision()/10.0, 1.0, 0, 0)));  // small angle
    rotationQuaternions.push_back(RotationQuaternion(AngleAxis(kindr::common::internal::NumTraits<RotationScalar>::dummy_precision()/10.0, 0, 1.0, 0)));  // small angle
    rotationQuaternions.push_back(RotationQuaternion(AngleAxis(kindr::common::internal::NumTraits<RotationScalar>::dummy_precision()/10.0, 0, 0, 1.0)));  // small angle
    rotationQuaternions.push_back(RotationQuaternion(AngleAxis(1.3, 1.0, 0, 0))); // large angle
    rotationQuaternions.push_back(RotationQuaternion(AngleAxis(1.3, 0, 1.0, 0))); // large angle
    rotationQuaternions.push_back(RotationQuaternion(AngleAxis(1.3, 0, 0, 1.0))); // large angle

    angularVelocities.push_back(LocalAngularVelocity());  // zero velocity
    angularVelocities.push_back(LocalAngularVelocity(kindr::common::internal::NumTraits<RotationScalar>::dummy_precision()/10.0, 0.0, 0.0));
    angularVelocities.push_back(LocalAngularVelocity(0.0, kindr::common::internal::NumTraits<RotationScalar>::dummy_precision()/10.0, 0.0));
    angularVelocities.push_back(LocalAngularVelocity(0.0, 0.0, kindr::common::internal::NumTraits<RotationScalar>::dummy_precision()/10.0));
    angularVelocities.push_back(LocalAngularVelocity(0.1, 0.0, 0.0));
    angularVelocities.push_back(LocalAngularVelocity(0.0, 0.1, 0.0));
    angularVelocities.push_back(LocalAngularVelocity(0.0, 0.0, 0.1));

    angularVelocities.push_back(LocalAngularVelocity(2.2, 3.3, 4.4));
  }

};

typedef ::testing::Types<
  std::pair<rot::RotationQuaternionAD, rot::RotationQuaternionDiffAD>,
  std::pair<rot::RotationQuaternionAF, rot::RotationQuaternionDiffAF>,
  std::pair<rot::RotationQuaternionPD, rot::RotationQuaternionDiffPD>,
  std::pair<rot::RotationQuaternionPF, rot::RotationQuaternionDiffPF>
> QuaternionTypes;

TYPED_TEST_CASE(RotationDiffSingleTest, QuaternionTypes);

TYPED_TEST(RotationDiffSingleTest, testConversionToLocalAngularVelocity)
{
  typedef typename TestFixture::RotationQuaternionDiff RotationQuaternionDiff;
  typedef typename TestFixture::LocalAngularVelocity LocalAngularVelocity;

  for (auto rotQuat : this->rotationQuaternions) {
     for (auto angularVelocity : this->angularVelocities) {
       RotationQuaternionDiff rotQuatDiff(rotQuat, angularVelocity);

       LocalAngularVelocity angularVelocity2(2.0*rotQuat.getLocalQuaternionDiffMatrix()*rotQuatDiff.vector());
       ASSERT_NEAR(angularVelocity.x(),angularVelocity2.x(),1e-3) << "rquat: " << rotQuat;
       ASSERT_NEAR(angularVelocity.y(),angularVelocity2.y(),1e-3);
       ASSERT_NEAR(angularVelocity.z(),angularVelocity2.z(),1e-3);

       RotationQuaternionDiff rotQuatDiff2(0.5*rotQuat.getLocalQuaternionDiffMatrix().transpose()*angularVelocity.vector());
       ASSERT_NEAR(rotQuatDiff.w(),rotQuatDiff2.w(),1e-3);
       ASSERT_NEAR(rotQuatDiff.x(),rotQuatDiff2.x(),1e-3);
       ASSERT_NEAR(rotQuatDiff.y(),rotQuatDiff2.y(),1e-3);
       ASSERT_NEAR(rotQuatDiff.z(),rotQuatDiff2.z(),1e-3);
     }
  }
}

max_stars_repo_name: wxmerkt/ihmc-open-robotics-software

max_issues_repo_name: wxmerkt/ihmc-open-robotics-software

max_forks_repo_name: wxmerkt/ihmc-open-robotics-software


text:
#define BOOST_TEST_MODULE TestOutputFormatter
#include <boost/test/unit_test.hpp>
#include <descr.hxx>
#include <output.hxx>

BOOST_AUTO_TEST_CASE(TestOutputFormatter)
{

  std::shared_ptr<BackupCatalog> catalog(nullptr);
  std::shared_ptr<OutputFormatConfiguration> output_configuration(nullptr);
  std::shared_ptr<OutputFormatter> formatter(nullptr);

  /*
   * OutputFormatter requires a configuration instance for
   * output parameters.
   */
  BOOST_REQUIRE_NOT_THROW( output_configuration
                           = std::make_shared<OutputFormatConfiguration>() );

  BOOST_REQUIRE_NO_THROW( catalog
                          = std::make_shared<BackupCatalog>(".pg_backup_ctl.sqlite") );

  /*
   * Instantiation of OutputFormatter should throw, since catalog not opened.
   */
  BOOST_CHECK_THROW( OutputFormatter::formatter(output_configuration,
                                                catalog,
                                                nullptr) );

}

ext: cxx