<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#include <Include/PlatformDefinitions.hpp>

#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <iostream>
#endif

#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/sax/SAXException.hpp>

#include <Include/XalanAutoPtr.hpp>

#include <XalanTransformer/XalanTransformer.hpp>

//#define XALAN_VQ_SPECIAL_TRACE
#if defined(XALAN_VQ_SPECIAL_TRACE)
#include "C:/Program Files/Rational/Quantify/pure.h"
#endif

#if !defined (XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::endl;
#endif

void
Usage()
{
	cerr << endl
		 << "Xalan version 1.3"
		 << endl
		 << "Usage: Xalan [options] source stylesheet"
		 << endl
	     << "Options:"
		 << endl
		 << "  -a                    Use xml-stylesheet PI, not the 'stylesheet' argument"
		 << endl
		 << "  -o filename           Write output to the specified file."
		 << endl
		 << "  -p name expression    Sets a stylesheet parameter."
		 << endl
		 << "  -v                    Validates source documents."
		 << endl
		 << "  -?                    Display this message."
		 << endl;
}

class Params
{
public:

	Params(unsigned long	maxParams) :
		m_validate(false),
		m_useStylesheetPI(false),
		m_inFileName(0),
		m_xslFileName(0),
		m_outFileName(0),
		m_params(),
		m_maxParams(maxParams),
		m_currentParam(0)
	{
	}

	bool
	addParam(
			const char*		name,
			const char*		expression)
	{
		if (m_currentParam == m_maxParams)
		{
			return false;
		}
		else
		{
			// Allocate memory if necessary...
			if (m_params.get() == 0)
			{
				m_params.reset(new ParamPair[m_maxParams]);
			}
			assert(m_params.get() != 0);

			m_params[m_currentParam].m_name = name;
			m_params[m_currentParam].m_expression = expression;

			++m_currentParam;

			return true;
		}
	};

	void
	setParams(XalanTransformer&		theTransformer)
	{
		theTransformer.setUseValidation(m_validate);

		for(unsigned long i = 0; i < m_currentParam; ++i)
		{
			theTransformer.setStylesheetParam(
				m_params[i].m_name,
				m_params[i].m_expression);
		}
	}

	bool			m_validate;
	bool			m_useStylesheetPI;

	const char*		m_inFileName;
	const char*		m_xslFileName;
	const char*		m_outFileName;

private:

	struct ParamPair
	{
		ParamPair() :
			m_name(0),
			m_expression(0)
		{
		}

		const char*		m_name;
		const char*		m_expression;
	};

	XalanArrayAutoPtr<ParamPair>	m_params;

	const unsigned long				m_maxParams;
	unsigned long					m_currentParam;
};

bool
getArgs(
			int					argc,
			const char*			argv[],
			Params&				params)
{
#if defined(XALAN_STRICT_ANSI_HEADERS)
	using std::strlen;
#endif

	bool fSuccess = true;

	for (int i = 1; i < argc && fSuccess == true; ++i)
	{
		if (argv[i][0] == '-')
		{
			if (strlen(argv[i]) != 2)
			{
				fSuccess = false;
			}
			else if (params.m_inFileName != 0 || params.m_xslFileName != 0)
			{
				fSuccess = false;
			}
			else if (argv[i][1] == 'a')
			{
				params.m_useStylesheetPI = true;
			}
			else if (argv[i][1] == 'o')
			{
				++i;

				if(i < argc && argv[i][0] != '-' &&
				   strlen(argv[i]) != 0)
				{
					params.m_outFileName = argv[i];
				}
				else
				{
					fSuccess = false;
				}
			}
			else if (argv[i][1] == 'p')
			{
				++i;

				if(i >= argc || argv[i][0] == '-')
				{
					fSuccess = false;
				}
				else
				{
					const char* const	name = argv[i];

					++i;

					// Don't check for '-' here, since that might
					// be a valid character in a parameter value.
					if(i >= argc)
					{
						fSuccess = false;
					}
					else
					{
						const char* const	value = argv[i];

						if (params.addParam(name, value) == false)
						{
							cerr << "Maximum numbers of stylesheets params has been exceeded!" << endl;

							fSuccess = false;
						}
					}
				}
			}
			else if (argv[i][1] == 'v')
			{
				params.m_validate = true;
			}
		}
		else if (params.m_inFileName == 0 &&
				 strlen(argv[i]) != 0)
		{
			params.m_inFileName = argv[i];

			if (strlen(params.m_inFileName) == 0)
			{
				fSuccess = false;
			}
		}
		else if (params.m_xslFileName == 0 &&
				 strlen(argv[i]) != 0 &&
				 params.m_useStylesheetPI == false)
		{
			params.m_xslFileName = argv[i];

			if (strlen(params.m_xslFileName) == 0)
			{
				fSuccess = false;
			}
		}
		else
		{
			fSuccess = false;
		}
	}

	if (fSuccess == true && params.m_inFileName == 0)
	{
		return false;
	}
	else if (params.m_xslFileName == 0 && params.m_useStylesheetPI == false)
	{
		return false;
	}
	else
	{
		return fSuccess;
	}
}

int
xsltMain(
			int				argc,
			const char*		argv[])

{
	int	theResult = -1;

	// Set the maximum number of params as half of argc - 1.
	// It's actually argc - 2, but that could get us into negative
	// numbers, so don't bother.  Also, always add 1, in case
	// (argc - 1) / 2 is 0.
	Params	theParams((argc - 1) / 2 + 1);

	if (getArgs(argc, argv, theParams) == false)
	{
		Usage();
	}
	else
	{
		// Call the static initializer for Xerces...
		XMLPlatformUtils::Initialize();

		// Initialize Xalan...
		XalanTransformer::initialize();

		{
			// Create a XalanTransformer instance...
			XalanTransformer	theTransformer;

			// Set any options...
			theParams.setParams(theTransformer);

			if (theParams.m_outFileName != 0)
			{
				theResult = theTransformer.transform(
						theParams.m_inFileName,
						theParams.m_xslFileName,
						theParams.m_outFileName);
			}
			else
			{
				theResult = theTransformer.transform(
						theParams.m_inFileName,
						theParams.m_xslFileName,
						cout);
			}

			if (theResult != 0)
			{
				cerr << theTransformer.getLastError() << endl;
			}
		}

		// Terminate Xalan...
		XalanTransformer::terminate();

		// Terminate Xerces...
		XMLPlatformUtils::Terminate();
	}

	return theResult;
}

int
main(
			int				argc,
			const char*		argv[])
{
#if !defined(XALAN_USE_ICU) && !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

#if defined(XALAN_VQ_SPECIAL_TRACE)
	QuantifyStopRecordingData();
#endif

    if (argc < 2)
	{
		Usage();

		return -1;
	}
	else
	{
		return xsltMain(argc, argv);
	}
}
<commit_msg>Removed unnecessary include.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#include <Include/PlatformDefinitions.hpp>

#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <iostream>
#endif

#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

#include <xercesc/util/PlatformUtils.hpp>

#include <Include/XalanAutoPtr.hpp>

#include <XalanTransformer/XalanTransformer.hpp>

//#define XALAN_VQ_SPECIAL_TRACE
#if defined(XALAN_VQ_SPECIAL_TRACE)
#include "C:/Program Files/Rational/Quantify/pure.h"
#endif

#if !defined (XALAN_NO_NAMESPACES)
using std::cerr;
using std::cout;
using std::endl;
#endif

void
Usage()
{
	cerr << endl
		 << "Xalan version 1.3"
		 << endl
		 << "Usage: Xalan [options] source stylesheet"
		 << endl
	     << "Options:"
		 << endl
		 << "  -a                    Use xml-stylesheet PI, not the 'stylesheet' argument"
		 << endl
		 << "  -o filename           Write output to the specified file."
		 << endl
		 << "  -p name expression    Sets a stylesheet parameter."
		 << endl
		 << "  -v                    Validates source documents."
		 << endl
		 << "  -?                    Display this message."
		 << endl;
}

class Params
{
public:

	Params(unsigned long	maxParams) :
		m_validate(false),
		m_useStylesheetPI(false),
		m_inFileName(0),
		m_xslFileName(0),
		m_outFileName(0),
		m_params(),
		m_maxParams(maxParams),
		m_currentParam(0)
	{
	}

	bool
	addParam(
			const char*		name,
			const char*		expression)
	{
		if (m_currentParam == m_maxParams)
		{
			return false;
		}
		else
		{
			// Allocate memory if necessary...
			if (m_params.get() == 0)
			{
				m_params.reset(new ParamPair[m_maxParams]);
			}
			assert(m_params.get() != 0);

			m_params[m_currentParam].m_name = name;
			m_params[m_currentParam].m_expression = expression;

			++m_currentParam;

			return true;
		}
	};

	void
	setParams(XalanTransformer&		theTransformer)
	{
		theTransformer.setUseValidation(m_validate);

		for(unsigned long i = 0; i < m_currentParam; ++i)
		{
			theTransformer.setStylesheetParam(
				m_params[i].m_name,
				m_params[i].m_expression);
		}
	}

	bool			m_validate;
	bool			m_useStylesheetPI;

	const char*		m_inFileName;
	const char*		m_xslFileName;
	const char*		m_outFileName;

private:

	struct ParamPair
	{
		ParamPair() :
			m_name(0),
			m_expression(0)
		{
		}

		const char*		m_name;
		const char*		m_expression;
	};

	XalanArrayAutoPtr<ParamPair>	m_params;

	const unsigned long				m_maxParams;
	unsigned long					m_currentParam;
};

bool
getArgs(
			int					argc,
			const char*			argv[],
			Params&				params)
{
#if defined(XALAN_STRICT_ANSI_HEADERS)
	using std::strlen;
#endif

	bool fSuccess = true;

	for (int i = 1; i < argc && fSuccess == true; ++i)
	{
		if (argv[i][0] == '-')
		{
			if (strlen(argv[i]) != 2)
			{
				fSuccess = false;
			}
			else if (params.m_inFileName != 0 || params.m_xslFileName != 0)
			{
				fSuccess = false;
			}
			else if (argv[i][1] == 'a')
			{
				params.m_useStylesheetPI = true;
			}
			else if (argv[i][1] == 'o')
			{
				++i;

				if(i < argc && argv[i][0] != '-' &&
				   strlen(argv[i]) != 0)
				{
					params.m_outFileName = argv[i];
				}
				else
				{
					fSuccess = false;
				}
			}
			else if (argv[i][1] == 'p')
			{
				++i;

				if(i >= argc || argv[i][0] == '-')
				{
					fSuccess = false;
				}
				else
				{
					const char* const	name = argv[i];

					++i;

					// Don't check for '-' here, since that might
					// be a valid character in a parameter value.
					if(i >= argc)
					{
						fSuccess = false;
					}
					else
					{
						const char* const	value = argv[i];

						if (params.addParam(name, value) == false)
						{
							cerr << "Maximum numbers of stylesheets params has been exceeded!" << endl;

							fSuccess = false;
						}
					}
				}
			}
			else if (argv[i][1] == 'v')
			{
				params.m_validate = true;
			}
		}
		else if (params.m_inFileName == 0 &&
				 strlen(argv[i]) != 0)
		{
			params.m_inFileName = argv[i];

			if (strlen(params.m_inFileName) == 0)
			{
				fSuccess = false;
			}
		}
		else if (params.m_xslFileName == 0 &&
				 strlen(argv[i]) != 0 &&
				 params.m_useStylesheetPI == false)
		{
			params.m_xslFileName = argv[i];

			if (strlen(params.m_xslFileName) == 0)
			{
				fSuccess = false;
			}
		}
		else
		{
			fSuccess = false;
		}
	}

	if (fSuccess == true && params.m_inFileName == 0)
	{
		return false;
	}
	else if (params.m_xslFileName == 0 && params.m_useStylesheetPI == false)
	{
		return false;
	}
	else
	{
		return fSuccess;
	}
}

int
xsltMain(
			int				argc,
			const char*		argv[])

{
	int	theResult = -1;

	// Set the maximum number of params as half of argc - 1.
	// It's actually argc - 2, but that could get us into negative
	// numbers, so don't bother.  Also, always add 1, in case
	// (argc - 1) / 2 is 0.
	Params	theParams((argc - 1) / 2 + 1);

	if (getArgs(argc, argv, theParams) == false)
	{
		Usage();
	}
	else
	{
		// Call the static initializer for Xerces...
		XMLPlatformUtils::Initialize();

		// Initialize Xalan...
		XalanTransformer::initialize();

		{
			// Create a XalanTransformer instance...
			XalanTransformer	theTransformer;

			// Set any options...
			theParams.setParams(theTransformer);

			if (theParams.m_outFileName != 0)
			{
				theResult = theTransformer.transform(
						theParams.m_inFileName,
						theParams.m_xslFileName,
						theParams.m_outFileName);
			}
			else
			{
				theResult = theTransformer.transform(
						theParams.m_inFileName,
						theParams.m_xslFileName,
						cout);
			}

			if (theResult != 0)
			{
				cerr << theTransformer.getLastError() << endl;
			}
		}

		// Terminate Xalan...
		XalanTransformer::terminate();

		// Terminate Xerces...
		XMLPlatformUtils::Terminate();
	}

	return theResult;
}

int
main(
			int				argc,
			const char*		argv[])
{
#if !defined(XALAN_USE_ICU) && !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

#if defined(XALAN_VQ_SPECIAL_TRACE)
	QuantifyStopRecordingData();
#endif

    if (argc < 2)
	{
		Usage();

		return -1;
	}
	else
	{
		return xsltMain(argc, argv);
	}
}
<|endoftext|>


<commit_before>#include "gtest/gtest.h"

#include "test_utils/test_utils.hpp"

#include "cpputil/math_utils.hpp"

#include "Models/ChisqModel.hpp"
#include "Models/PosteriorSamplers/IndependentMvnVarSampler.hpp"
#include "Models/StateSpace/MultivariateStateSpaceModel.hpp"
#include "Models/StateSpace/StateModels/LocalLevelStateModel.hpp"
#include "Models/StateSpace/PosteriorSamplers/SharedLocalLevelPosteriorSampler.hpp"
#include "Models/StateSpace/PosteriorSamplers/MultivariateStateSpaceModelSampler.hpp"
#include "distributions.hpp"
#include "LinAlg/Array.hpp"

namespace {

  using namespace BOOM;
  using std::endl;
  using std::cout;

  class MultivariateStateSpaceModelTest : public ::testing::Test {
   protected:
    MultivariateStateSpaceModelTest()
        : sigma_obs_(.25) {
      GlobalRng::rng.seed(8675310);
    }

    // Generate fake parameters, simulate the state, and simulate observed data.
    // Args:
    //   time_dimension:  The number of time points to simulate.
    //   ydim:  The dimension of the response to simulate.
    //   nfactors:  The number of factors in the state.
    void McmcSetup(int time_dimension, int ydim, int nfactors) {
      if (nfactors >= ydim) {
        report_error("The number of factors should be less than ydim.");
      }
      Vector state = rnorm_vector(nfactors, 0, 1);
      state_.resize(nfactors, time_dimension);
      observed_data_.resize(time_dimension, ydim);
      observation_coefficients_.resize(ydim, nfactors);
      observation_coefficients_.randomize();
      innovation_sigsq_ = Vector(nfactors);
      innovation_sigsq_.randomize();
      innovation_sigsq_ *= innovation_sigsq_;
      Vector innovation_sd = sqrt(innovation_sigsq_);
      for (int i = 0; i < observation_coefficients_.nrow(); ++i) {
        for (int j = i; j < observation_coefficients_.ncol(); ++j) {
          observation_coefficients_(i, j) = 0.0;
        }
        if (i < observation_coefficients_.ncol()) {
          observation_coefficients_(i, i) = 1.0;
        }
      }

      for (int i = 0; i < time_dimension; ++i) {
        state += rnorm_vector(nfactors, 0, 1) * innovation_sd;
        state_.col(i) = state;
        observed_data_.row(i) = observation_coefficients_ * state
            + rnorm_vector(ydim, 0, sigma_obs_);
      }
    }

    Matrix observed_data_;
    Matrix state_;
    Matrix observation_coefficients_;
    Vector innovation_sigsq_;
    double sigma_obs_;
  };

  //===========================================================================
  TEST_F(MultivariateStateSpaceModelTest, EmptyTest) {}

  //===========================================================================
  TEST_F(MultivariateStateSpaceModelTest, ConstructorTest) {
    MultivariateStateSpaceModel model(3);
  }

  //===========================================================================
  TEST_F(MultivariateStateSpaceModelTest, BaseClassTest) {
    MultivariateStateSpaceModel model(3);

    IndependentMvnModel *obs = model.observation_model();
    EXPECT_TRUE(obs != nullptr);
    EXPECT_EQ(obs->dim(), 3);
    EXPECT_EQ(0, model.number_of_state_models());
    EXPECT_EQ(0, model.state_dimension());
    EXPECT_EQ(0, model.time_dimension());
  }

  //===========================================================================
  TEST_F(MultivariateStateSpaceModelTest, ModelMatricesTest) {
    int ydim = 3;
    int nfactors = 2;
    int time_dimension = 10;
    McmcSetup(time_dimension, ydim, nfactors);

    MultivariateStateSpaceModel model(ydim);
    for (int i = 0; i < time_dimension; ++i) {
      NEW(PartiallyObservedVectorData, data_point)(observed_data_.row(i));
      model.add_data(data_point);
    }

    NEW(SharedLocalLevelStateModel, state_model)(nfactors, &model);
    model.add_shared_state(state_model);

    Selector fully_observed(ydim, true);
    EXPECT_EQ(model.observation_coefficients(0, fully_observed)->nrow(), ydim);
    EXPECT_EQ(model.observation_coefficients(0, fully_observed)->ncol(),
              nfactors);
  }

  //===========================================================================
  // TODO: move this to a function that depends on ydim.  Test with ydim == 2 to
  // catch the low-dimensional update.
  TEST_F(MultivariateStateSpaceModelTest, DrawHighDimensionalStateTest) {
    int time_dimension = 100;
    int ydim = 3;
    int nfactors = 2;
    int niter = 200;
    McmcSetup(time_dimension, ydim, nfactors);

    NEW(MultivariateStateSpaceModel, model)(ydim);
    cout << "raw data: " << endl;
    for (int i = 0; i < observed_data_.nrow(); ++i) {
      NEW(PartiallyObservedVectorData, data_point)(observed_data_.row(i));
      model->add_data(data_point);
    }

    NEW(SharedLocalLevelStateModel, state_model)(nfactors, model.get());
    // Initial state mean and variance.
    Vector initial_state_mean(2, 0.0);
    SpdMatrix initial_state_variance(2, 1.0);
    state_model->set_initial_state_mean(initial_state_mean);
    state_model->set_initial_state_variance(initial_state_variance);

    // Prior distribution and posterior sampler.
    std::vector<Ptr<GammaModelBase>> innovation_precision_priors;
    for (int i = 0; i < nfactors; ++i) {
      innovation_precision_priors.push_back(
          new ChisqModel(1, sqrt(innovation_sigsq_[i])));
    }
    Matrix observation_coefficient_prior_mean(nfactors, ydim, 0.0);
    NEW(SharedLocalLevelPosteriorSampler, state_model_sampler)(
        state_model.get(),
        innovation_precision_priors,
        observation_coefficient_prior_mean,
        1.0);
    state_model->set_method(state_model_sampler);
    // Done configuring, so add the state model.
    for (int i = 0; i < nfactors; ++i) {
      state_model->innovation_model(i)->set_sigsq(innovation_sigsq_[i]);
    }

    state_model->coefficient_model()->set_Beta(
        observation_coefficients_.transpose());
    model->add_shared_state(state_model);

    // Check that the model matrices are as expected.
    int time_index = 2;
    Matrix transition = model->state_transition_matrix(time_index)->dense();
    EXPECT_TRUE(MatrixEquals(transition, SpdMatrix(2, 1.0)));

    state_model->coefficient_model()->set_Beta(observation_coefficients_.transpose());
    Matrix observation_coefficients = model->observation_coefficients(
        time_index, Selector(ydim, true))->dense();
    EXPECT_EQ(observation_coefficients.nrow(), observation_coefficients_.nrow());
    EXPECT_EQ(observation_coefficients.ncol(), observation_coefficients_.ncol());
    EXPECT_TRUE(MatrixEquals(observation_coefficients_, observation_coefficients))
        << endl << "correct observation matrix: " << endl
        << observation_coefficients_ << endl
        << "what the model has: " << endl
        << observation_coefficients;

    // Need a prior for the observation model.
    std::vector<Ptr<GammaModelBase>> observation_model_priors;
    for (int i = 0; i < ydim; ++i) {
      observation_model_priors.push_back(new GammaModel(1, 1));
    }
    NEW(IndependentMvnVarSampler, observation_model_sampler)(
        model->observation_model(),
        observation_model_priors);
    model->observation_model()->set_method(observation_model_sampler);
    model->observation_model()->set_sigsq(Vector(ydim, square(sigma_obs_)));

    // Set the global sampler for the model.
    NEW(MultivariateStateSpaceModelSampler, sampler)(model.get());
    model->set_method(sampler);

    Array state_draws({niter, model->state_dimension(), model->time_dimension()});

    for (int i = 0; i < niter; ++i) {
      model->sample_posterior();
      state_draws.slice(i, -1, -1) = model->state();
    }

    auto status = CheckMcmcMatrix(state_draws.slice(-1, 0, -1).to_matrix(),
                                  state_.row(0), .95, true, "factor1.txt");
    EXPECT_TRUE(status.ok) << status.error_message();

    // The imputed values of the state should fall within the range of the data
    // at time t.
    EXPECT_EQ("",
              CheckWithinRage(state_draws.slice(-1, 0, -1).to_matrix(),
                              Vector(state_.row(0)) - 10 * sigma_obs_,
                              Vector(state_.row(0)) + 10 * sigma_obs_));

    EXPECT_EQ("",
              CheckWithinRage(state_draws.slice(-1, 1, -1).to_matrix(),
                              Vector(state_.row(1)) - 10 * sigma_obs_,
                              Vector(state_.row(1)) + 10 * sigma_obs_));

    auto status2 = CheckMcmcMatrix(state_draws.slice(-1, 1, -1).to_matrix(),
                                  state_.row(1), .95, true, "factor2.txt");
    EXPECT_TRUE(status2.ok) << status2.error_message();
  }

}  // namespace
<commit_msg>Tweak to multivariate_test for new RNG.<commit_after>#include "gtest/gtest.h"

#include "test_utils/test_utils.hpp"

#include "cpputil/math_utils.hpp"

#include "Models/ChisqModel.hpp"
#include "Models/PosteriorSamplers/IndependentMvnVarSampler.hpp"
#include "Models/StateSpace/MultivariateStateSpaceModel.hpp"
#include "Models/StateSpace/StateModels/LocalLevelStateModel.hpp"
#include "Models/StateSpace/PosteriorSamplers/SharedLocalLevelPosteriorSampler.hpp"
#include "Models/StateSpace/PosteriorSamplers/MultivariateStateSpaceModelSampler.hpp"
#include "distributions.hpp"
#include "LinAlg/Array.hpp"

namespace {

  using namespace BOOM;
  using std::endl;
  using std::cout;

  class MultivariateStateSpaceModelTest : public ::testing::Test {
   protected:
    MultivariateStateSpaceModelTest()
        : sigma_obs_(.25) {
      GlobalRng::rng.seed(8675310);
    }

    // Generate fake parameters, simulate the state, and simulate observed data.
    // Args:
    //   time_dimension:  The number of time points to simulate.
    //   ydim:  The dimension of the response to simulate.
    //   nfactors:  The number of factors in the state.
    void McmcSetup(int time_dimension, int ydim, int nfactors) {
      if (nfactors >= ydim) {
        report_error("The number of factors should be less than ydim.");
      }
      Vector state = rnorm_vector(nfactors, 0, 1);
      state_.resize(nfactors, time_dimension);
      observed_data_.resize(time_dimension, ydim);
      observation_coefficients_.resize(ydim, nfactors);
      observation_coefficients_.randomize();
      innovation_sigsq_ = Vector(nfactors);
      innovation_sigsq_.randomize();
      innovation_sigsq_ *= innovation_sigsq_;
      Vector innovation_sd = sqrt(innovation_sigsq_);
      for (int i = 0; i < observation_coefficients_.nrow(); ++i) {
        for (int j = i; j < observation_coefficients_.ncol(); ++j) {
          observation_coefficients_(i, j) = 0.0;
        }
        if (i < observation_coefficients_.ncol()) {
          observation_coefficients_(i, i) = 1.0;
        }
      }

      for (int i = 0; i < time_dimension; ++i) {
        state += rnorm_vector(nfactors, 0, 1) * innovation_sd;
        state_.col(i) = state;
        observed_data_.row(i) = observation_coefficients_ * state
            + rnorm_vector(ydim, 0, sigma_obs_);
      }
    }

    Matrix observed_data_;
    Matrix state_;
    Matrix observation_coefficients_;
    Vector innovation_sigsq_;
    double sigma_obs_;
  };

  //===========================================================================
  TEST_F(MultivariateStateSpaceModelTest, EmptyTest) {}

  //===========================================================================
  TEST_F(MultivariateStateSpaceModelTest, ConstructorTest) {
    MultivariateStateSpaceModel model(3);
  }

  //===========================================================================
  TEST_F(MultivariateStateSpaceModelTest, BaseClassTest) {
    MultivariateStateSpaceModel model(3);

    IndependentMvnModel *obs = model.observation_model();
    EXPECT_TRUE(obs != nullptr);
    EXPECT_EQ(obs->dim(), 3);
    EXPECT_EQ(0, model.number_of_state_models());
    EXPECT_EQ(0, model.state_dimension());
    EXPECT_EQ(0, model.time_dimension());
  }

  //===========================================================================
  TEST_F(MultivariateStateSpaceModelTest, ModelMatricesTest) {
    int ydim = 3;
    int nfactors = 2;
    int time_dimension = 10;
    McmcSetup(time_dimension, ydim, nfactors);

    MultivariateStateSpaceModel model(ydim);
    for (int i = 0; i < time_dimension; ++i) {
      NEW(PartiallyObservedVectorData, data_point)(observed_data_.row(i));
      model.add_data(data_point);
    }

    NEW(SharedLocalLevelStateModel, state_model)(nfactors, &model);
    model.add_shared_state(state_model);

    Selector fully_observed(ydim, true);
    EXPECT_EQ(model.observation_coefficients(0, fully_observed)->nrow(), ydim);
    EXPECT_EQ(model.observation_coefficients(0, fully_observed)->ncol(),
              nfactors);
  }

  //===========================================================================
  // TODO: move this to a function that depends on ydim.  Test with ydim == 2 to
  // catch the low-dimensional update.
  TEST_F(MultivariateStateSpaceModelTest, DrawHighDimensionalStateTest) {
    int time_dimension = 100;
    int ydim = 3;
    int nfactors = 2;
    int niter = 200;
    McmcSetup(time_dimension, ydim, nfactors);

    NEW(MultivariateStateSpaceModel, model)(ydim);
    cout << "raw data: " << endl;
    for (int i = 0; i < observed_data_.nrow(); ++i) {
      NEW(PartiallyObservedVectorData, data_point)(observed_data_.row(i));
      model->add_data(data_point);
    }

    NEW(SharedLocalLevelStateModel, state_model)(nfactors, model.get());
    // Initial state mean and variance.
    Vector initial_state_mean(2, 0.0);
    SpdMatrix initial_state_variance(2, 1.0);
    state_model->set_initial_state_mean(initial_state_mean);
    state_model->set_initial_state_variance(initial_state_variance);

    // Prior distribution and posterior sampler.
    std::vector<Ptr<GammaModelBase>> innovation_precision_priors;
    for (int i = 0; i < nfactors; ++i) {
      innovation_precision_priors.push_back(
          new ChisqModel(1, sqrt(innovation_sigsq_[i])));
    }
    Matrix observation_coefficient_prior_mean(nfactors, ydim, 0.0);
    NEW(SharedLocalLevelPosteriorSampler, state_model_sampler)(
        state_model.get(),
        innovation_precision_priors,
        observation_coefficient_prior_mean,
        1.0);
    state_model->set_method(state_model_sampler);
    // Done configuring, so add the state model.
    for (int i = 0; i < nfactors; ++i) {
      state_model->innovation_model(i)->set_sigsq(innovation_sigsq_[i]);
    }

    state_model->coefficient_model()->set_Beta(
        observation_coefficients_.transpose());
    model->add_shared_state(state_model);

    // Check that the model matrices are as expected.
    int time_index = 2;
    Matrix transition = model->state_transition_matrix(time_index)->dense();
    EXPECT_TRUE(MatrixEquals(transition, SpdMatrix(2, 1.0)));

    state_model->coefficient_model()->set_Beta(observation_coefficients_.transpose());
    Matrix observation_coefficients = model->observation_coefficients(
        time_index, Selector(ydim, true))->dense();
    EXPECT_EQ(observation_coefficients.nrow(), observation_coefficients_.nrow());
    EXPECT_EQ(observation_coefficients.ncol(), observation_coefficients_.ncol());
    EXPECT_TRUE(MatrixEquals(observation_coefficients_, observation_coefficients))
        << endl << "correct observation matrix: " << endl
        << observation_coefficients_ << endl
        << "what the model has: " << endl
        << observation_coefficients;

    // Need a prior for the observation model.
    std::vector<Ptr<GammaModelBase>> observation_model_priors;
    for (int i = 0; i < ydim; ++i) {
      observation_model_priors.push_back(new GammaModel(1, 1));
    }
    NEW(IndependentMvnVarSampler, observation_model_sampler)(
        model->observation_model(),
        observation_model_priors);
    model->observation_model()->set_method(observation_model_sampler);
    model->observation_model()->set_sigsq(Vector(ydim, square(sigma_obs_)));

    // Set the global sampler for the model.
    NEW(MultivariateStateSpaceModelSampler, sampler)(model.get());
    model->set_method(sampler);

    Array state_draws({niter, model->state_dimension(), model->time_dimension()});

    for (int i = 0; i < niter; ++i) {
      model->sample_posterior();
      state_draws.slice(i, -1, -1) = model->state();
    }

    auto status = CheckMcmcMatrix(state_draws.slice(-1, 0, -1).to_matrix(),
                                  state_.row(0), .95, true, "factor1.txt");
    EXPECT_TRUE(status.ok) << status;

    EXPECT_EQ("", CheckStochasticProcess(
        state_draws.slice(-1, 0, -1).to_matrix(),
        Vector(state_.row(0)),
        .95, .10, "factor1.txt"));

    // The explained variance ratio had to be adjusted for this test, but by
    // visual inspection it looks fine.
    EXPECT_EQ("", CheckStochasticProcess(
        state_draws.slice(-1, 1, -1).to_matrix(),
        Vector(state_.row(1)),
        .95, .50, "factor2.txt"));

  }

}  // namespace
<|endoftext|>


<commit_before><commit_msg>delete<commit_after><|endoftext|>


<commit_before>//===-- WebAssemblyMCTargetDesc.cpp - WebAssembly Target Descriptions -----===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file provides WebAssembly-specific target descriptions.
///
//===----------------------------------------------------------------------===//

#include "WebAssemblyMCTargetDesc.h"
#include "InstPrinter/WebAssemblyInstPrinter.h"
#include "WebAssemblyMCAsmInfo.h"
#include "WebAssemblyTargetStreamer.h"
#include "llvm/MC/MCCodeGenInfo.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;

#define DEBUG_TYPE "wasm-mc-target-desc"

#define GET_INSTRINFO_MC_DESC
#include "WebAssemblyGenInstrInfo.inc"

#define GET_SUBTARGETINFO_MC_DESC
#include "WebAssemblyGenSubtargetInfo.inc"

#define GET_REGINFO_MC_DESC
#include "WebAssemblyGenRegisterInfo.inc"

static MCAsmInfo *createMCAsmInfo(const MCRegisterInfo & /*MRI*/,
                                  const Triple &TT) {
  return new WebAssemblyMCAsmInfo(TT);
}

static MCInstrInfo *createMCInstrInfo() {
  MCInstrInfo *X = new MCInstrInfo();
  InitWebAssemblyMCInstrInfo(X);
  return X;
}

static MCInstPrinter *createMCInstPrinter(const Triple & /*T*/,
                                          unsigned SyntaxVariant,
                                          const MCAsmInfo &MAI,
                                          const MCInstrInfo &MII,
                                          const MCRegisterInfo &MRI) {
  assert(SyntaxVariant == 0);
  return new WebAssemblyInstPrinter(MAI, MII, MRI);
}

static MCCodeEmitter *createCodeEmitter(const MCInstrInfo &MCII,
                                        const MCRegisterInfo & /*MRI*/,
                                        MCContext &Ctx) {
  return createWebAssemblyMCCodeEmitter(MCII, Ctx);
}

static MCAsmBackend *createAsmBackend(const Target & /*T*/,
                                      const MCRegisterInfo & /*MRI*/,
                                      const Triple &TT, StringRef /*CPU*/) {
  return createWebAssemblyAsmBackend(TT);
}

static MCSubtargetInfo *createMCSubtargetInfo(const Triple &TT, StringRef CPU,
                                              StringRef FS) {
  return createWebAssemblyMCSubtargetInfoImpl(TT, CPU, FS);
}

static MCTargetStreamer *
createObjectTargetStreamer(MCStreamer &S, const MCSubtargetInfo & /*STI*/) {
  return new WebAssemblyTargetELFStreamer(S);
}

static MCTargetStreamer *createAsmTargetStreamer(MCStreamer &S,
                                                 formatted_raw_ostream &OS,
                                                 MCInstPrinter * /*InstPrint*/,
                                                 bool /*isVerboseAsm*/) {
  return new WebAssemblyTargetAsmStreamer(S, OS);
}

// Force static initialization.
extern "C" void LLVMInitializeWebAssemblyTargetMC() {
  for (Target *T : {&TheWebAssemblyTarget32, &TheWebAssemblyTarget64}) {
    // Register the MC asm info.
    RegisterMCAsmInfoFn X(*T, createMCAsmInfo);

    // Register the MC instruction info.
    TargetRegistry::RegisterMCInstrInfo(*T, createMCInstrInfo);

    // Register the MCInstPrinter.
    TargetRegistry::RegisterMCInstPrinter(*T, createMCInstPrinter);

    // Register the MC code emitter.
    TargetRegistry::RegisterMCCodeEmitter(*T, createCodeEmitter);

    // Register the ASM Backend.
    TargetRegistry::RegisterMCAsmBackend(*T, createAsmBackend);

    // Register the MC subtarget info.
    TargetRegistry::RegisterMCSubtargetInfo(*T, createMCSubtargetInfo);

    // Register the object target streamer.
    TargetRegistry::RegisterObjectTargetStreamer(*T,
                                                 createObjectTargetStreamer);
    // Register the asm target streamer.
    TargetRegistry::RegisterAsmTargetStreamer(*T, createAsmTargetStreamer);
  }
}
<commit_msg>[WebAsssembly] Register the MC register info.<commit_after>//===-- WebAssemblyMCTargetDesc.cpp - WebAssembly Target Descriptions -----===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file provides WebAssembly-specific target descriptions.
///
//===----------------------------------------------------------------------===//

#include "WebAssemblyMCTargetDesc.h"
#include "InstPrinter/WebAssemblyInstPrinter.h"
#include "WebAssemblyMCAsmInfo.h"
#include "WebAssemblyTargetStreamer.h"
#include "llvm/MC/MCCodeGenInfo.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TargetRegistry.h"
using namespace llvm;

#define DEBUG_TYPE "wasm-mc-target-desc"

#define GET_INSTRINFO_MC_DESC
#include "WebAssemblyGenInstrInfo.inc"

#define GET_SUBTARGETINFO_MC_DESC
#include "WebAssemblyGenSubtargetInfo.inc"

#define GET_REGINFO_MC_DESC
#include "WebAssemblyGenRegisterInfo.inc"

static MCAsmInfo *createMCAsmInfo(const MCRegisterInfo & /*MRI*/,
                                  const Triple &TT) {
  return new WebAssemblyMCAsmInfo(TT);
}

static MCInstrInfo *createMCInstrInfo() {
  MCInstrInfo *X = new MCInstrInfo();
  InitWebAssemblyMCInstrInfo(X);
  return X;
}

static MCRegisterInfo *createMCRegisterInfo(const Triple & /*T*/) {
  MCRegisterInfo *X = new MCRegisterInfo();
  InitWebAssemblyMCRegisterInfo(X, 0);
  return X;
}

static MCInstPrinter *createMCInstPrinter(const Triple & /*T*/,
                                          unsigned SyntaxVariant,
                                          const MCAsmInfo &MAI,
                                          const MCInstrInfo &MII,
                                          const MCRegisterInfo &MRI) {
  assert(SyntaxVariant == 0);
  return new WebAssemblyInstPrinter(MAI, MII, MRI);
}

static MCCodeEmitter *createCodeEmitter(const MCInstrInfo &MCII,
                                        const MCRegisterInfo & /*MRI*/,
                                        MCContext &Ctx) {
  return createWebAssemblyMCCodeEmitter(MCII, Ctx);
}

static MCAsmBackend *createAsmBackend(const Target & /*T*/,
                                      const MCRegisterInfo & /*MRI*/,
                                      const Triple &TT, StringRef /*CPU*/) {
  return createWebAssemblyAsmBackend(TT);
}

static MCSubtargetInfo *createMCSubtargetInfo(const Triple &TT, StringRef CPU,
                                              StringRef FS) {
  return createWebAssemblyMCSubtargetInfoImpl(TT, CPU, FS);
}

static MCTargetStreamer *
createObjectTargetStreamer(MCStreamer &S, const MCSubtargetInfo & /*STI*/) {
  return new WebAssemblyTargetELFStreamer(S);
}

static MCTargetStreamer *createAsmTargetStreamer(MCStreamer &S,
                                                 formatted_raw_ostream &OS,
                                                 MCInstPrinter * /*InstPrint*/,
                                                 bool /*isVerboseAsm*/) {
  return new WebAssemblyTargetAsmStreamer(S, OS);
}

// Force static initialization.
extern "C" void LLVMInitializeWebAssemblyTargetMC() {
  for (Target *T : {&TheWebAssemblyTarget32, &TheWebAssemblyTarget64}) {
    // Register the MC asm info.
    RegisterMCAsmInfoFn X(*T, createMCAsmInfo);

    // Register the MC instruction info.
    TargetRegistry::RegisterMCInstrInfo(*T, createMCInstrInfo);

    // Register the MC register info.
    TargetRegistry::RegisterMCRegInfo(*T, createMCRegisterInfo);

    // Register the MCInstPrinter.
    TargetRegistry::RegisterMCInstPrinter(*T, createMCInstPrinter);

    // Register the MC code emitter.
    TargetRegistry::RegisterMCCodeEmitter(*T, createCodeEmitter);

    // Register the ASM Backend.
    TargetRegistry::RegisterMCAsmBackend(*T, createAsmBackend);

    // Register the MC subtarget info.
    TargetRegistry::RegisterMCSubtargetInfo(*T, createMCSubtargetInfo);

    // Register the object target streamer.
    TargetRegistry::RegisterObjectTargetStreamer(*T,
                                                 createObjectTargetStreamer);
    // Register the asm target streamer.
    TargetRegistry::RegisterAsmTargetStreamer(*T, createAsmTargetStreamer);
  }
}
<|endoftext|>


<commit_before>#include <fcntl.h>

extern "C" {
#include "signconf/signconf_task.h"
#include "shared/file.h"
#include "shared/duration.h"
}

#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>

#include "xmlext-pb/xmlext-rd.h"
#include "xmlext-pb/xmlext-wr.h"
#include "signconf/signconf.pb.h"
#include "policy/kasp.pb.h"
#include "keystate/keystate.pb.h"

static const char *module_str = "signconf_task";

void WriteSignConf(const std::string &path, ::ods::signconf::SignerConfigurationDocument *doc)
{
    write_pb_message_to_xml_file(doc,path.c_str());
}

/*
 * ForEvery zone Z in zonelist do
 *   if flag signerConfNeedsWriting is set then
 *      Assign the data from the zone and associated policy to the signer configuration object
 *      Write signer configuration XML file at the correct location taken from zonedata signerconfiguration field in the zone
 */
void
perform_signconf(int sockfd, engineconfig_type *config)
{
    char buf[ODS_SE_MAXLINE];
	const char *policyfile = config->policy_filename;
    const char *datastore = config->datastore;
    int fd;

	GOOGLE_PROTOBUF_VERIFY_VERSION;

    // Read the zonelist and policies in from the same directory as
    // the database, use serialized protocolbuffer for now, but switch
    // to using database table ASAP.

    bool bFailedToLoad = false;

    ::ods::kasp::KaspDocument *kaspDoc = new ::ods::kasp::KaspDocument;
    {
        std::string policypb(datastore);
        policypb += ".policy.pb";
        int fd = open(policypb.c_str(),O_RDONLY);
        if (kaspDoc->ParseFromFileDescriptor(fd)) {
            ods_log_debug("[%s] policies have been loaded",
                          module_str);
        } else {
            ods_log_error("[%s] policies could not be loaded from \"%s\"",
                          module_str,policypb.c_str());
            bFailedToLoad = true;
        }
        close(fd);
    }

    ::ods::keystate::KeyStateDocument *keystateDoc =
        new ::ods::keystate::KeyStateDocument;
    {
        std::string keystatepb(datastore);
        keystatepb += ".keystate.pb";
        int fd = open(keystatepb.c_str(),O_RDONLY);
        if (keystateDoc->ParseFromFileDescriptor(fd)) {
            ods_log_debug("[%s] keystates have been loaded",
                          module_str);
        } else {
            ods_log_error("[%s] keystates could not be loaded from \"%s\"",
                          module_str,keystatepb.c_str());
            bFailedToLoad = true;
        }
        close(fd);
    }

    if (bFailedToLoad) {
        delete kaspDoc;
        delete keystateDoc;
        ods_log_error("[%s] unable to continue",
                      module_str);
        return ;
    }

    // Go through all the zones and run the enforcer for every one of them.
    for (int i=0; i<keystateDoc->zones_size(); ++i) {

        const ::ods::keystate::EnforcerZone &ks_zone = keystateDoc->zones(i);

        if (!ks_zone.signconf_needs_writing())
            continue;

        const ::ods::kasp::KASP &
        kasp = kaspDoc->kasp();

        //printf("%s\n",zone.name().c_str());

        const ::ods::kasp::Policy *policy = NULL;

        for (int p=0; p<kasp.policies_size(); ++p) {
            // lookup the policy associated with this zone
            // printf("%s\n",kasp.policies(p).name().c_str());
            if (kasp.policies(p).name() == ks_zone.policy()) {
                policy = &kasp.policies(p);
                ods_log_debug("[%s] policy %s found for zone %s",
                              module_str,policy->name().c_str(),
                              ks_zone.name().c_str());
                break;
            }
        }

        if (policy == NULL) {
            ods_log_error("[%s] policy %s could not be found for zone %s",
                          module_str,ks_zone.policy().c_str(),
                          ks_zone.name().c_str());
            ods_log_error("[%s] unable to enforce zone %s",
                          module_str,ks_zone.name().c_str());
            continue;
        }

        ::ods::signconf::SignerConfigurationDocument *doc  = new ::ods::signconf::SignerConfigurationDocument;
        ::ods::signconf::Zone *sc_zone = doc->mutable_signerconfiguration()->mutable_zone();
        sc_zone->set_name(ks_zone.name());

        // Get the Signatures parameters straight from the policy.
        ::ods::signconf::Signatures *sc_sigs = sc_zone->mutable_signatures();
        const ::ods::kasp::Signatures &kp_sigs = policy->signatures();

        sc_sigs->set_resign( kp_sigs.resign() );
        sc_sigs->set_refresh( kp_sigs.refresh() );
        sc_sigs->set_valdefault( kp_sigs.valdefault() );
        sc_sigs->set_valdenial( kp_sigs.valdenial() );
        sc_sigs->set_jitter( kp_sigs.jitter() );
        sc_sigs->set_inceptionoffset( kp_sigs.inceptionoffset() );

        // Get the Denial parameters straight from the policy
        ::ods::signconf::Denial *sc_denial = sc_zone->mutable_denial();
        const ::ods::kasp::Denial &kp_denial = policy->denial();

        if (kp_denial.has_nsec() && kp_denial.has_nsec3()) {
            ods_log_error("[%s] policy %s contains both NSEC and NSEC3 in Denial for zone %s",
                          module_str,ks_zone.policy().c_str(),
                          ks_zone.name().c_str());
            // skip to the next zone.
            continue;
        } else {
            if (!kp_denial.has_nsec() && !kp_denial.has_nsec3()) {
                ods_log_error("[%s] policy %s does not contains NSEC or NSEC3 in Denial for zone %s",
                              module_str,ks_zone.policy().c_str(),
                              ks_zone.name().c_str());
                // skip to the next zone.
                continue;
            } else {
                // NSEC
                if(!kp_denial.has_nsec())
                    sc_denial->clear_nsec();
                else
                    sc_denial->mutable_nsec();

                // NSEC3
                if (!kp_denial.has_nsec3())
                    sc_denial->clear_nsec3();
                else {
                    ::ods::signconf::NSEC3 *sc_nsec3 = sc_denial->mutable_nsec3();
                    const ::ods::kasp::NSEC3 &kp_nsec3 = kp_denial.nsec3();
                    if (kp_nsec3.has_optout())
                        sc_nsec3->set_optout( kp_nsec3.optout() );
                    else
                        sc_nsec3->clear_optout();
                    sc_nsec3->set_algorithm( kp_nsec3.algorithm() );
                    sc_nsec3->set_iterations( kp_nsec3.iterations() );
                    sc_nsec3->set_salt( kp_nsec3.salt() );
                }
            }
        }

        // Get the Keys from the zone data and add them to the signer
        // configuration
        ::ods::signconf::Keys *sc_keys = sc_zone->mutable_keys();
        sc_keys->set_ttl( policy->keys().ttl() );

        for (int k=0; k<ks_zone.keys_size(); ++k) {
            const ::ods::keystate::KeyData &ks_key = ks_zone.keys(k);
            ::ods::signconf::Key* sc_key = sc_keys->add_keys();

            // TODO: is this correct ?
            if (ks_key.role() == ::ods::keystate::ZSK)
                sc_key->set_flags( 256 ); // ZSK
            else
                sc_key->set_flags( 257 ); // KSK,CSK

            sc_key->set_algorithm( ks_key.algorithm() );
            sc_key->set_locator( ks_key.locator() );
            sc_key->set_ksk( ks_key.role() ==  ::ods::keystate::KSK || ks_key.role() ==  ::ods::keystate::CSK );
            sc_key->set_zsk( ks_key.role() ==  ::ods::keystate::ZSK || ks_key.role() ==  ::ods::keystate::CSK );
            sc_key->set_publish( ks_key.publish() );

            // The deactivate flag was intended to allow smooth key rollover.
            // With the deactivate flag present a normal rollover would be
            // performed where signatures would be replaced immmediately.
            // With deactivate flag not present a smooth rollover would be
            // performed where signatures that had not yet passed there refresh
            // timestamp could be recycled and gradually replaced with
            // new signatures.
            // sc_key->set_deactivate( !ks_key.active() );
        }

        const ::ods::kasp::Zone &kp_zone = policy->zone();
        sc_zone->set_ttl( kp_zone.ttl() );
        sc_zone->set_min( kp_zone.min() );
        sc_zone->set_serial( (::ods::signconf::serial) kp_zone.serial() );

        if (policy->audit_size() > 0)
            sc_zone->set_audit(true);
        else
            sc_zone->clear_audit();

        WriteSignConf(ks_zone.signconf_path(), doc);

        delete doc;
    }

    delete kaspDoc;
    delete keystateDoc;
}

static task_type *
signconf_task_perform(task_type *task)
{
    perform_signconf(-1,(engineconfig_type *)task->context);
    task_cleanup(task);
    return NULL;
}

task_type *
signconf_task(engineconfig_type *config, const char *what, const char * who)
{
    task_id what_id = task_register(what,
                                 "signconf_task_perform",
                                 signconf_task_perform);
	return task_create(what_id, time_now(), who, (void*)config);
}
<commit_msg>Turn off signconf_needs_writing flag after writing the signer configuration to disk.<commit_after>#include <fcntl.h>

extern "C" {
#include "signconf/signconf_task.h"
#include "shared/file.h"
#include "shared/duration.h"
}

#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>

#include "xmlext-pb/xmlext-rd.h"
#include "xmlext-pb/xmlext-wr.h"
#include "signconf/signconf.pb.h"
#include "policy/kasp.pb.h"
#include "keystate/keystate.pb.h"

static const char *module_str = "signconf_task";

void WriteSignConf(const std::string &path,
                   ::ods::signconf::SignerConfigurationDocument *doc)
{
    write_pb_message_to_xml_file(doc,path.c_str());
}

/*
 * ForEvery zone Z in zonelist do
 *   if flag signerConfNeedsWriting is set then
 *      Assign the data from the zone and associated policy to the signer
 *          configuration object
 *      Write signer configuration XML file at the correct location taken
 *          from zonedata signerconfiguration field in the zone
 */
void
perform_signconf(int sockfd, engineconfig_type *config)
{
    char buf[ODS_SE_MAXLINE];
	const char *policyfile = config->policy_filename;
    const char *datastore = config->datastore;
    int fd;

	GOOGLE_PROTOBUF_VERIFY_VERSION;

    // Read the zonelist and policies in from the same directory as
    // the database, use serialized protocolbuffer for now, but switch
    // to using database table ASAP.

    bool bFailedToLoad = false;

    ::ods::kasp::KaspDocument *kaspDoc = new ::ods::kasp::KaspDocument;
    {
        std::string policypb(datastore);
        policypb += ".policy.pb";
        int fd = open(policypb.c_str(),O_RDONLY);
        if (kaspDoc->ParseFromFileDescriptor(fd)) {
            ods_log_debug("[%s] policies have been loaded",
                          module_str);
        } else {
            ods_log_error("[%s] policies could not be loaded from \"%s\"",
                          module_str,policypb.c_str());
            bFailedToLoad = true;
        }
        close(fd);
    }

    ::ods::keystate::KeyStateDocument *keystateDoc =
        new ::ods::keystate::KeyStateDocument;
    {
        std::string keystatepb(datastore);
        keystatepb += ".keystate.pb";
        int fd = open(keystatepb.c_str(),O_RDONLY);
        if (keystateDoc->ParseFromFileDescriptor(fd)) {
            ods_log_debug("[%s] keystates have been loaded",
                          module_str);
        } else {
            ods_log_error("[%s] keystates could not be loaded from \"%s\"",
                          module_str,keystatepb.c_str());
            bFailedToLoad = true;
        }
        close(fd);
    }

    if (bFailedToLoad) {
        delete kaspDoc;
        delete keystateDoc;
        ods_log_error("[%s] unable to continue",
                      module_str);
        return ;
    }

    // Go through all the zones and write signer configuration when required.
    for (int i=0; i<keystateDoc->zones_size(); ++i) {

        ::ods::keystate::EnforcerZone *ks_zone = keystateDoc->mutable_zones(i);

        if (!ks_zone->signconf_needs_writing())
            continue;

        const ::ods::kasp::KASP &
        kasp = kaspDoc->kasp();

        //printf("%s\n",zone.name().c_str());

        const ::ods::kasp::Policy *policy = NULL;

        for (int p=0; p<kasp.policies_size(); ++p) {
            // lookup the policy associated with this zone
            // printf("%s\n",kasp.policies(p).name().c_str());
            if (kasp.policies(p).name() == ks_zone->policy()) {
                policy = &kasp.policies(p);
                ods_log_debug("[%s] policy %s found for zone %s",
                              module_str,policy->name().c_str(),
                              ks_zone->name().c_str());
                break;
            }
        }

        if (policy == NULL) {
            ods_log_error("[%s] policy %s could not be found for zone %s",
                          module_str,ks_zone->policy().c_str(),
                          ks_zone->name().c_str());
            ods_log_error("[%s] unable to enforce zone %s",
                          module_str,ks_zone->name().c_str());
            continue;
        }

        ::ods::signconf::SignerConfigurationDocument *doc  = new ::ods::signconf::SignerConfigurationDocument;
        ::ods::signconf::Zone *sc_zone = doc->mutable_signerconfiguration()->mutable_zone();
        sc_zone->set_name(ks_zone->name());

        // Get the Signatures parameters straight from the policy.
        ::ods::signconf::Signatures *sc_sigs = sc_zone->mutable_signatures();
        const ::ods::kasp::Signatures &kp_sigs = policy->signatures();

        sc_sigs->set_resign( kp_sigs.resign() );
        sc_sigs->set_refresh( kp_sigs.refresh() );
        sc_sigs->set_valdefault( kp_sigs.valdefault() );
        sc_sigs->set_valdenial( kp_sigs.valdenial() );
        sc_sigs->set_jitter( kp_sigs.jitter() );
        sc_sigs->set_inceptionoffset( kp_sigs.inceptionoffset() );

        // Get the Denial parameters straight from the policy
        ::ods::signconf::Denial *sc_denial = sc_zone->mutable_denial();
        const ::ods::kasp::Denial &kp_denial = policy->denial();

        if (kp_denial.has_nsec() && kp_denial.has_nsec3()) {
            ods_log_error("[%s] policy %s contains both NSEC and NSEC3 in Denial for zone %s",
                          module_str,ks_zone->policy().c_str(),
                          ks_zone->name().c_str());
            // skip to the next zone.
            continue;
        } else {
            if (!kp_denial.has_nsec() && !kp_denial.has_nsec3()) {
                ods_log_error("[%s] policy %s does not contains NSEC or NSEC3 in Denial for zone %s",
                              module_str,ks_zone->policy().c_str(),
                              ks_zone->name().c_str());
                // skip to the next zone.
                continue;
            } else {
                // NSEC
                if(!kp_denial.has_nsec())
                    sc_denial->clear_nsec();
                else
                    sc_denial->mutable_nsec();

                // NSEC3
                if (!kp_denial.has_nsec3())
                    sc_denial->clear_nsec3();
                else {
                    ::ods::signconf::NSEC3 *sc_nsec3 = sc_denial->mutable_nsec3();
                    const ::ods::kasp::NSEC3 &kp_nsec3 = kp_denial.nsec3();
                    if (kp_nsec3.has_optout())
                        sc_nsec3->set_optout( kp_nsec3.optout() );
                    else
                        sc_nsec3->clear_optout();
                    sc_nsec3->set_algorithm( kp_nsec3.algorithm() );
                    sc_nsec3->set_iterations( kp_nsec3.iterations() );
                    sc_nsec3->set_salt( kp_nsec3.salt() );
                }
            }
        }

        // Get the Keys from the zone data and add them to the signer
        // configuration
        ::ods::signconf::Keys *sc_keys = sc_zone->mutable_keys();
        sc_keys->set_ttl( policy->keys().ttl() );

        for (int k=0; k<ks_zone->keys_size(); ++k) {
            const ::ods::keystate::KeyData &ks_key = ks_zone->keys(k);
            ::ods::signconf::Key* sc_key = sc_keys->add_keys();

            // TODO: is this correct ?
            if (ks_key.role() == ::ods::keystate::ZSK)
                sc_key->set_flags( 256 ); // ZSK
            else
                sc_key->set_flags( 257 ); // KSK,CSK

            sc_key->set_algorithm( ks_key.algorithm() );
            sc_key->set_locator( ks_key.locator() );
            sc_key->set_ksk( ks_key.role() ==  ::ods::keystate::KSK || ks_key.role() ==  ::ods::keystate::CSK );
            sc_key->set_zsk( ks_key.role() ==  ::ods::keystate::ZSK || ks_key.role() ==  ::ods::keystate::CSK );
            sc_key->set_publish( ks_key.publish() );

            // The deactivate flag was intended to allow smooth key rollover.
            // With the deactivate flag present a normal rollover would be
            // performed where signatures would be replaced immmediately.
            // With deactivate flag not present a smooth rollover would be
            // performed where signatures that had not yet passed there refresh
            // timestamp could be recycled and gradually replaced with
            // new signatures.
            // sc_key->set_deactivate( !ks_key.active() );
        }

        const ::ods::kasp::Zone &kp_zone = policy->zone();
        sc_zone->set_ttl( kp_zone.ttl() );
        sc_zone->set_min( kp_zone.min() );
        sc_zone->set_serial( (::ods::signconf::serial) kp_zone.serial() );

        if (policy->audit_size() > 0)
            sc_zone->set_audit(true);
        else
            sc_zone->clear_audit();

        WriteSignConf(ks_zone->signconf_path(), doc);

        ks_zone->set_signconf_needs_writing(false);

        delete doc;
    }

    // Persist the keystate zones back to disk as they may have
    // been changed while writing the signer configurations
    if (keystateDoc->IsInitialized()) {
        std::string datapath(datastore);
        datapath += ".keystate.pb";
        int fd = open(datapath.c_str(),O_WRONLY|O_CREAT, 0644);
        if (keystateDoc->SerializeToFileDescriptor(fd)) {
            ods_log_debug("[%s] key states have been updated",
                          module_str);

            (void)snprintf(buf, ODS_SE_MAXLINE,
                           "update of key states completed.\n");
            ods_writen(sockfd, buf, strlen(buf));
        } else {
            (void)snprintf(buf, ODS_SE_MAXLINE,
                           "error: key states file could not be written.\n");
            ods_writen(sockfd, buf, strlen(buf));
        }
        close(fd);
    } else {
        (void)snprintf(buf, ODS_SE_MAXLINE,
                       "error: a message in the key states is missing "
                       "mandatory information.\n");
        ods_writen(sockfd, buf, strlen(buf));
    }

    delete kaspDoc;
    delete keystateDoc;
}

static task_type *
signconf_task_perform(task_type *task)
{
    perform_signconf(-1,(engineconfig_type *)task->context);
    task_cleanup(task);
    return NULL;
}

task_type *
signconf_task(engineconfig_type *config, const char *what, const char * who)
{
    task_id what_id = task_register(what,
                                 "signconf_task_perform",
                                 signconf_task_perform);
	return task_create(what_id, time_now(), who, (void*)config);
}
<|endoftext|>


<commit_before>#include "selfdrive/common/params.h"

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif  // _GNU_SOURCE

#include <dirent.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>

#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <unordered_map>

#include "selfdrive/common/swaglog.h"
#include "selfdrive/common/util.h"
#include "selfdrive/hardware/hw.h"

namespace {

volatile sig_atomic_t params_do_exit = 0;
void params_sig_handler(int signal) {
  params_do_exit = 1;
}

int fsync_dir(const char* path) {
  int fd = HANDLE_EINTR(open(path, O_RDONLY, 0755));
  if (fd < 0) {
    return -1;
  }

  int result = fsync(fd);
  int result_close = close(fd);
  if (result_close < 0) {
    result = result_close;
  }
  return result;
}

int mkdir_p(std::string path) {
  char * _path = (char *)path.c_str();

  for (char *p = _path + 1; *p; p++) {
    if (*p == '/') {
      *p = '\0'; // Temporarily truncate
      if (mkdir(_path, 0775) != 0) {
        if (errno != EEXIST) return -1;
      }
      *p = '/';
    }
  }
  if (mkdir(_path, 0775) != 0) {
    if (errno != EEXIST) return -1;
  }
  return 0;
}

bool create_params_path(const std::string &param_path, const std::string &key_path) {
  // Make sure params path exists
  if (!util::file_exists(param_path) && mkdir_p(param_path) != 0) {
    return false;
  }

  // See if the symlink exists, otherwise create it
  if (!util::file_exists(key_path)) {
    // 1) Create temp folder
    // 2) Set permissions
    // 3) Symlink it to temp link
    // 4) Move symlink to <params>/d

    std::string tmp_path = param_path + "/.tmp_XXXXXX";
    // this should be OK since mkdtemp just replaces characters in place
    char *tmp_dir = mkdtemp((char *)tmp_path.c_str());
    if (tmp_dir == NULL) {
      return false;
    }

    std::string link_path = std::string(tmp_dir) + ".link";
    if (symlink(tmp_dir, link_path.c_str()) != 0) {
      return false;
    }

    // don't return false if it has been created by other
    if (rename(link_path.c_str(), key_path.c_str()) != 0 && errno != EEXIST) {
      return false;
    }
  }

  return true;
}

void ensure_params_path(const std::string &params_path) {
  if (!create_params_path(params_path, params_path + "/d")) {
    throw std::runtime_error(util::string_format("Failed to ensure params path, errno=%d", errno));
  }
}

class FileLock {
 public:
  FileLock(const std::string& file_name, int op) : fn_(file_name), op_(op) {}

  void lock() {
    fd_ = HANDLE_EINTR(open(fn_.c_str(), O_CREAT, 0775));
    if (fd_ < 0) {
      LOGE("Failed to open lock file %s, errno=%d", fn_.c_str(), errno);
      return;
    }
    if (HANDLE_EINTR(flock(fd_, op_)) < 0) {
      LOGE("Failed to lock file %s, errno=%d", fn_.c_str(), errno);
    }
  }

  void unlock() { close(fd_); }

private:
  int fd_ = -1, op_;
  std::string fn_;
};

std::unordered_map<std::string, uint32_t> keys = {
    {"AccessToken", CLEAR_ON_MANAGER_START | DONT_LOG},
    {"ApiCache_DriveStats", PERSISTENT},
    {"ApiCache_Device", PERSISTENT},
    {"ApiCache_Owner", PERSISTENT},
    {"ApiCache_NavDestinations", PERSISTENT},
    {"AthenadPid", PERSISTENT},
    {"CalibrationParams", PERSISTENT},
    {"CarBatteryCapacity", PERSISTENT},
    {"CarParams", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT | CLEAR_ON_IGNITION_ON},
    {"CarParamsCache", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
    {"CarVin", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT | CLEAR_ON_IGNITION_ON},
    {"CommunityFeaturesToggle", PERSISTENT},
    {"ControlsReady", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT | CLEAR_ON_IGNITION_ON},
    {"CurrentRoute", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON},
    {"DisableRadar", PERSISTENT}, // WARNING: THIS DISABLES AEB
    {"EndToEndToggle", PERSISTENT},
    {"CompletedTrainingVersion", PERSISTENT},
    {"DisablePowerDown", PERSISTENT},
    {"DisableUpdates", PERSISTENT},
    {"EnableWideCamera", CLEAR_ON_MANAGER_START},
    {"DoUninstall", CLEAR_ON_MANAGER_START},
    {"DongleId", PERSISTENT},
    {"GitDiff", PERSISTENT},
    {"GitBranch", PERSISTENT},
    {"GitCommit", PERSISTENT},
    {"GitRemote", PERSISTENT},
    {"GithubSshKeys", PERSISTENT},
    {"GithubUsername", PERSISTENT},
    {"HardwareSerial", PERSISTENT},
    {"HasAcceptedTerms", PERSISTENT},
    {"IsDriverViewEnabled", CLEAR_ON_MANAGER_START},
    {"IMEI", PERSISTENT},
    {"IsLdwEnabled", PERSISTENT},
    {"IsMetric", PERSISTENT},
    {"IsOffroad", CLEAR_ON_MANAGER_START},
    {"IsOnroad", PERSISTENT},
    {"IsRHD", PERSISTENT},
    {"IsTakingSnapshot", CLEAR_ON_MANAGER_START},
    {"IsUpdateAvailable", CLEAR_ON_MANAGER_START},
    {"UploadRaw", PERSISTENT},
    {"LastAthenaPingTime", CLEAR_ON_MANAGER_START},
    {"LastGPSPosition", PERSISTENT},
    {"LastUpdateException", PERSISTENT},
    {"LastUpdateTime", PERSISTENT},
    {"LiveParameters", PERSISTENT},
    {"MapboxToken", PERSISTENT | DONT_LOG},
    {"NavDestination", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_OFF},
    {"NavSettingTime24h", PERSISTENT},
    {"OpenpilotEnabledToggle", PERSISTENT},
    {"PandaFirmware", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
    {"PandaFirmwareHex", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
    {"PandaDongleId", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
    {"PandaHeartbeatLost", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_OFF},
    {"Passive", PERSISTENT},
    {"PrimeRedirected", PERSISTENT},
    {"RecordFront", PERSISTENT},
    {"RecordFrontLock", PERSISTENT},  // for the internal fleet
    {"ReleaseNotes", PERSISTENT},
    {"ShouldDoUpdate", CLEAR_ON_MANAGER_START},
    {"SubscriberInfo", PERSISTENT},
    {"SshEnabled", PERSISTENT},
    {"TermsVersion", PERSISTENT},
    {"Timezone", PERSISTENT},
    {"TrainingVersion", PERSISTENT},
    {"UpdateAvailable", CLEAR_ON_MANAGER_START},
    {"UpdateFailedCount", CLEAR_ON_MANAGER_START},
    {"Version", PERSISTENT},
    {"VisionRadarToggle", PERSISTENT},
    {"Offroad_ChargeDisabled", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
    {"Offroad_ConnectivityNeeded", CLEAR_ON_MANAGER_START},
    {"Offroad_ConnectivityNeededPrompt", CLEAR_ON_MANAGER_START},
    {"Offroad_TemperatureTooHigh", CLEAR_ON_MANAGER_START},
    {"Offroad_PandaFirmwareMismatch", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
    {"Offroad_InvalidTime", CLEAR_ON_MANAGER_START},
    {"Offroad_IsTakingSnapshot", CLEAR_ON_MANAGER_START},
    {"Offroad_NeosUpdate", CLEAR_ON_MANAGER_START},
    {"Offroad_UpdateFailed", CLEAR_ON_MANAGER_START},
    {"Offroad_HardwareUnsupported", CLEAR_ON_MANAGER_START},
    {"Offroad_UnofficialHardware", CLEAR_ON_MANAGER_START},
    {"Offroad_NvmeMissing", CLEAR_ON_MANAGER_START},
    {"ForcePowerDown", CLEAR_ON_MANAGER_START},
    {"JoystickDebugMode", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_OFF},
};

} // namespace

Params::Params() : params_path(Path::params()) {
  static std::once_flag once_flag;
  std::call_once(once_flag, ensure_params_path, params_path);
}

Params::Params(const std::string &path) : params_path(path) {
  ensure_params_path(params_path);
}

bool Params::checkKey(const std::string &key) {
  return keys.find(key) != keys.end();
}

ParamKeyType Params::getKeyType(const std::string &key) {
  return static_cast<ParamKeyType>(keys[key]);
}

int Params::put(const char* key, const char* value, size_t value_size) {
  // Information about safely and atomically writing a file: https://lwn.net/Articles/457667/
  // 1) Create temp file
  // 2) Write data to temp file
  // 3) fsync() the temp file
  // 4) rename the temp file to the real name
  // 5) fsync() the containing directory
  std::string tmp_path = params_path + "/.tmp_value_XXXXXX";
  int tmp_fd = mkstemp((char*)tmp_path.c_str());
  if (tmp_fd < 0) return -1;

  int result = -1;
  do {
    // Write value to temp.
    ssize_t bytes_written = HANDLE_EINTR(write(tmp_fd, value, value_size));
    if (bytes_written < 0 || (size_t)bytes_written != value_size) {
      result = -20;
      break;
    }

    // fsync to force persist the changes.
    if ((result = fsync(tmp_fd)) < 0) break;

    FileLock file_lock(params_path + "/.lock", LOCK_EX);
    std::lock_guard<FileLock> lk(file_lock);

    // Move temp into place.
    std::string path = params_path + "/d/" + std::string(key);
    if ((result = rename(tmp_path.c_str(), path.c_str())) < 0) break;

    // fsync parent directory
    path = params_path + "/d";
    result = fsync_dir(path.c_str());
  } while (false);

  close(tmp_fd);
  remove(tmp_path.c_str());
  return result;
}

int Params::remove(const char *key) {
  FileLock file_lock(params_path + "/.lock", LOCK_EX);
  std::lock_guard<FileLock> lk(file_lock);
  // Delete value.
  std::string path = params_path + "/d/" + key;
  int result = ::remove(path.c_str());
  if (result != 0) {
    result = ERR_NO_VALUE;
    return result;
  }
  // fsync parent directory
  path = params_path + "/d";
  return fsync_dir(path.c_str());
}

std::string Params::get(const char *key, bool block) {
  std::string path = params_path + "/d/" + key;
  if (!block) {
    return util::read_file(path);
  } else {
    // blocking read until successful
    params_do_exit = 0;
    void (*prev_handler_sigint)(int) = std::signal(SIGINT, params_sig_handler);
    void (*prev_handler_sigterm)(int) = std::signal(SIGTERM, params_sig_handler);

    std::string value;
    while (!params_do_exit) {
      if (value = util::read_file(path); !value.empty()) {
        break;
      }
      util::sleep_for(100);  // 0.1 s
    }

    std::signal(SIGINT, prev_handler_sigint);
    std::signal(SIGTERM, prev_handler_sigterm);
    return value;
  }
}

std::map<std::string, std::string> Params::readAll() {
  FileLock file_lock(params_path + "/.lock", LOCK_SH);
  std::lock_guard<FileLock> lk(file_lock);

  std::string key_path = params_path + "/d";
  return util::read_files_in_dir(key_path);
}

void Params::clearAll(ParamKeyType key_type) {
  for (auto &[key, type] : keys) {
    if (type & key_type) {
      remove(key);
    }
  }
}
<commit_msg>Params::put:  fixed the wrong call to Params::remove instead of global ::remove (#21974)<commit_after>#include "selfdrive/common/params.h"

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif  // _GNU_SOURCE

#include <dirent.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>

#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <unordered_map>

#include "selfdrive/common/swaglog.h"
#include "selfdrive/common/util.h"
#include "selfdrive/hardware/hw.h"

namespace {

volatile sig_atomic_t params_do_exit = 0;
void params_sig_handler(int signal) {
  params_do_exit = 1;
}

int fsync_dir(const char* path) {
  int fd = HANDLE_EINTR(open(path, O_RDONLY, 0755));
  if (fd < 0) {
    return -1;
  }

  int result = fsync(fd);
  int result_close = close(fd);
  if (result_close < 0) {
    result = result_close;
  }
  return result;
}

int mkdir_p(std::string path) {
  char * _path = (char *)path.c_str();

  for (char *p = _path + 1; *p; p++) {
    if (*p == '/') {
      *p = '\0'; // Temporarily truncate
      if (mkdir(_path, 0775) != 0) {
        if (errno != EEXIST) return -1;
      }
      *p = '/';
    }
  }
  if (mkdir(_path, 0775) != 0) {
    if (errno != EEXIST) return -1;
  }
  return 0;
}

bool create_params_path(const std::string &param_path, const std::string &key_path) {
  // Make sure params path exists
  if (!util::file_exists(param_path) && mkdir_p(param_path) != 0) {
    return false;
  }

  // See if the symlink exists, otherwise create it
  if (!util::file_exists(key_path)) {
    // 1) Create temp folder
    // 2) Set permissions
    // 3) Symlink it to temp link
    // 4) Move symlink to <params>/d

    std::string tmp_path = param_path + "/.tmp_XXXXXX";
    // this should be OK since mkdtemp just replaces characters in place
    char *tmp_dir = mkdtemp((char *)tmp_path.c_str());
    if (tmp_dir == NULL) {
      return false;
    }

    std::string link_path = std::string(tmp_dir) + ".link";
    if (symlink(tmp_dir, link_path.c_str()) != 0) {
      return false;
    }

    // don't return false if it has been created by other
    if (rename(link_path.c_str(), key_path.c_str()) != 0 && errno != EEXIST) {
      return false;
    }
  }

  return true;
}

void ensure_params_path(const std::string &params_path) {
  if (!create_params_path(params_path, params_path + "/d")) {
    throw std::runtime_error(util::string_format("Failed to ensure params path, errno=%d", errno));
  }
}

class FileLock {
 public:
  FileLock(const std::string& file_name, int op) : fn_(file_name), op_(op) {}

  void lock() {
    fd_ = HANDLE_EINTR(open(fn_.c_str(), O_CREAT, 0775));
    if (fd_ < 0) {
      LOGE("Failed to open lock file %s, errno=%d", fn_.c_str(), errno);
      return;
    }
    if (HANDLE_EINTR(flock(fd_, op_)) < 0) {
      LOGE("Failed to lock file %s, errno=%d", fn_.c_str(), errno);
    }
  }

  void unlock() { close(fd_); }

private:
  int fd_ = -1, op_;
  std::string fn_;
};

std::unordered_map<std::string, uint32_t> keys = {
    {"AccessToken", CLEAR_ON_MANAGER_START | DONT_LOG},
    {"ApiCache_DriveStats", PERSISTENT},
    {"ApiCache_Device", PERSISTENT},
    {"ApiCache_Owner", PERSISTENT},
    {"ApiCache_NavDestinations", PERSISTENT},
    {"AthenadPid", PERSISTENT},
    {"CalibrationParams", PERSISTENT},
    {"CarBatteryCapacity", PERSISTENT},
    {"CarParams", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT | CLEAR_ON_IGNITION_ON},
    {"CarParamsCache", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
    {"CarVin", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT | CLEAR_ON_IGNITION_ON},
    {"CommunityFeaturesToggle", PERSISTENT},
    {"ControlsReady", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT | CLEAR_ON_IGNITION_ON},
    {"CurrentRoute", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON},
    {"DisableRadar", PERSISTENT}, // WARNING: THIS DISABLES AEB
    {"EndToEndToggle", PERSISTENT},
    {"CompletedTrainingVersion", PERSISTENT},
    {"DisablePowerDown", PERSISTENT},
    {"DisableUpdates", PERSISTENT},
    {"EnableWideCamera", CLEAR_ON_MANAGER_START},
    {"DoUninstall", CLEAR_ON_MANAGER_START},
    {"DongleId", PERSISTENT},
    {"GitDiff", PERSISTENT},
    {"GitBranch", PERSISTENT},
    {"GitCommit", PERSISTENT},
    {"GitRemote", PERSISTENT},
    {"GithubSshKeys", PERSISTENT},
    {"GithubUsername", PERSISTENT},
    {"HardwareSerial", PERSISTENT},
    {"HasAcceptedTerms", PERSISTENT},
    {"IsDriverViewEnabled", CLEAR_ON_MANAGER_START},
    {"IMEI", PERSISTENT},
    {"IsLdwEnabled", PERSISTENT},
    {"IsMetric", PERSISTENT},
    {"IsOffroad", CLEAR_ON_MANAGER_START},
    {"IsOnroad", PERSISTENT},
    {"IsRHD", PERSISTENT},
    {"IsTakingSnapshot", CLEAR_ON_MANAGER_START},
    {"IsUpdateAvailable", CLEAR_ON_MANAGER_START},
    {"UploadRaw", PERSISTENT},
    {"LastAthenaPingTime", CLEAR_ON_MANAGER_START},
    {"LastGPSPosition", PERSISTENT},
    {"LastUpdateException", PERSISTENT},
    {"LastUpdateTime", PERSISTENT},
    {"LiveParameters", PERSISTENT},
    {"MapboxToken", PERSISTENT | DONT_LOG},
    {"NavDestination", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_OFF},
    {"NavSettingTime24h", PERSISTENT},
    {"OpenpilotEnabledToggle", PERSISTENT},
    {"PandaFirmware", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
    {"PandaFirmwareHex", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
    {"PandaDongleId", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
    {"PandaHeartbeatLost", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_OFF},
    {"Passive", PERSISTENT},
    {"PrimeRedirected", PERSISTENT},
    {"RecordFront", PERSISTENT},
    {"RecordFrontLock", PERSISTENT},  // for the internal fleet
    {"ReleaseNotes", PERSISTENT},
    {"ShouldDoUpdate", CLEAR_ON_MANAGER_START},
    {"SubscriberInfo", PERSISTENT},
    {"SshEnabled", PERSISTENT},
    {"TermsVersion", PERSISTENT},
    {"Timezone", PERSISTENT},
    {"TrainingVersion", PERSISTENT},
    {"UpdateAvailable", CLEAR_ON_MANAGER_START},
    {"UpdateFailedCount", CLEAR_ON_MANAGER_START},
    {"Version", PERSISTENT},
    {"VisionRadarToggle", PERSISTENT},
    {"Offroad_ChargeDisabled", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
    {"Offroad_ConnectivityNeeded", CLEAR_ON_MANAGER_START},
    {"Offroad_ConnectivityNeededPrompt", CLEAR_ON_MANAGER_START},
    {"Offroad_TemperatureTooHigh", CLEAR_ON_MANAGER_START},
    {"Offroad_PandaFirmwareMismatch", CLEAR_ON_MANAGER_START | CLEAR_ON_PANDA_DISCONNECT},
    {"Offroad_InvalidTime", CLEAR_ON_MANAGER_START},
    {"Offroad_IsTakingSnapshot", CLEAR_ON_MANAGER_START},
    {"Offroad_NeosUpdate", CLEAR_ON_MANAGER_START},
    {"Offroad_UpdateFailed", CLEAR_ON_MANAGER_START},
    {"Offroad_HardwareUnsupported", CLEAR_ON_MANAGER_START},
    {"Offroad_UnofficialHardware", CLEAR_ON_MANAGER_START},
    {"Offroad_NvmeMissing", CLEAR_ON_MANAGER_START},
    {"ForcePowerDown", CLEAR_ON_MANAGER_START},
    {"JoystickDebugMode", CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_OFF},
};

} // namespace

Params::Params() : params_path(Path::params()) {
  static std::once_flag once_flag;
  std::call_once(once_flag, ensure_params_path, params_path);
}

Params::Params(const std::string &path) : params_path(path) {
  ensure_params_path(params_path);
}

bool Params::checkKey(const std::string &key) {
  return keys.find(key) != keys.end();
}

ParamKeyType Params::getKeyType(const std::string &key) {
  return static_cast<ParamKeyType>(keys[key]);
}

int Params::put(const char* key, const char* value, size_t value_size) {
  // Information about safely and atomically writing a file: https://lwn.net/Articles/457667/
  // 1) Create temp file
  // 2) Write data to temp file
  // 3) fsync() the temp file
  // 4) rename the temp file to the real name
  // 5) fsync() the containing directory
  std::string tmp_path = params_path + "/.tmp_value_XXXXXX";
  int tmp_fd = mkstemp((char*)tmp_path.c_str());
  if (tmp_fd < 0) return -1;

  int result = -1;
  do {
    // Write value to temp.
    ssize_t bytes_written = HANDLE_EINTR(write(tmp_fd, value, value_size));
    if (bytes_written < 0 || (size_t)bytes_written != value_size) {
      result = -20;
      break;
    }

    // fsync to force persist the changes.
    if ((result = fsync(tmp_fd)) < 0) break;

    FileLock file_lock(params_path + "/.lock", LOCK_EX);
    std::lock_guard<FileLock> lk(file_lock);

    // Move temp into place.
    std::string path = params_path + "/d/" + std::string(key);
    if ((result = rename(tmp_path.c_str(), path.c_str())) < 0) break;

    // fsync parent directory
    path = params_path + "/d";
    result = fsync_dir(path.c_str());
  } while (false);

  close(tmp_fd);
  ::unlink(tmp_path.c_str());
  return result;
}

int Params::remove(const char *key) {
  FileLock file_lock(params_path + "/.lock", LOCK_EX);
  std::lock_guard<FileLock> lk(file_lock);
  // Delete value.
  std::string path = params_path + "/d/" + key;
  int result = ::remove(path.c_str());
  if (result != 0) {
    result = ERR_NO_VALUE;
    return result;
  }
  // fsync parent directory
  path = params_path + "/d";
  return fsync_dir(path.c_str());
}

std::string Params::get(const char *key, bool block) {
  std::string path = params_path + "/d/" + key;
  if (!block) {
    return util::read_file(path);
  } else {
    // blocking read until successful
    params_do_exit = 0;
    void (*prev_handler_sigint)(int) = std::signal(SIGINT, params_sig_handler);
    void (*prev_handler_sigterm)(int) = std::signal(SIGTERM, params_sig_handler);

    std::string value;
    while (!params_do_exit) {
      if (value = util::read_file(path); !value.empty()) {
        break;
      }
      util::sleep_for(100);  // 0.1 s
    }

    std::signal(SIGINT, prev_handler_sigint);
    std::signal(SIGTERM, prev_handler_sigterm);
    return value;
  }
}

std::map<std::string, std::string> Params::readAll() {
  FileLock file_lock(params_path + "/.lock", LOCK_SH);
  std::lock_guard<FileLock> lk(file_lock);

  std::string key_path = params_path + "/d";
  return util::read_files_in_dir(key_path);
}

void Params::clearAll(ParamKeyType key_type) {
  for (auto &[key, type] : keys) {
    if (type & key_type) {
      remove(key);
    }
  }
}
<|endoftext|>


<commit_before>AliAnalysisTask *AddTaskPIDResponse(Bool_t isMC=kFALSE, Bool_t autoMCesd=kTRUE)
{
// Macro to connect a centrality selection task to an existing analysis manager.
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskPIDResponse", "No analysis manager to connect to.");
    return 0x0;
  }

  AliVEventHandler *inputHandler=mgr->GetInputEventHandler();

  //case of multi input event handler (needed for mixing)
  if (inputHandler->IsA() == AliMultiInputEventHandler::Class()) {
    printf("========================================================================================\n");
    printf("PIDResponse: AliMultiInputEventHandler detected, initialising AliPIDResponseInputHandler\n");
    printf("========================================================================================\n");
    AliMultiInputEventHandler *multiInputHandler=(AliMultiInputEventHandler*)inputHandler;

    AliPIDResponseInputHandler *pidResponseIH = new AliPIDResponseInputHandler();
    multiInputHandler->AddInputEventHandler(pidResponseIH);

    if (autoMCesd &&
        multiInputHandler->GetFirstInputEventHandler()->IsA()==AliESDInputHandler::Class() &&
        multiInputHandler->GetFirstMCEventHandler()
       ) isMC=kTRUE;
    pidResponseIH->SetIsMC(isMC);

    return 0x0;
  }

  // standard with task
  printf("========================================================================================\n");
  printf("PIDResponse: Initialising AliAnalysisTaskPIDResponse\n");
  printf("========================================================================================\n");

  if ( autoMCesd && (inputHandler->IsA() == AliESDInputHandler::Class()) ) {
    isMC=mgr->GetMCtruthEventHandler()!=0x0;
  }

  AliAnalysisTaskPIDResponse *pidTask = new AliAnalysisTaskPIDResponse("PIDResponseTask");
//   pidTask->SelectCollisionCandidates(AliVEvent::kMB);
  pidTask->SetIsMC(isMC);
  mgr->AddTask(pidTask);

//   AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("PIDResponseQA",
//     TList::Class(), AliAnalysisManager::kOutputContainer,
//     "PIDResponseQA.root");

  mgr->ConnectInput(pidTask, 0, mgr->GetCommonInputContainer());
//   mgr->ConnectOutput(pidTask,1,coutput1);

  return pidTask;
}
<commit_msg>o add option for tune on data<commit_after>AliAnalysisTask *AddTaskPIDResponse(Bool_t isMC=kFALSE, Bool_t autoMCesd=kTRUE,Bool_t tuneOnData=kFALSE,Int_t recoPass=2)
{
// Macro to connect a centrality selection task to an existing analysis manager.
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskPIDResponse", "No analysis manager to connect to.");
    return 0x0;
  }

  AliVEventHandler *inputHandler=mgr->GetInputEventHandler();

  //case of multi input event handler (needed for mixing)
  if (inputHandler->IsA() == AliMultiInputEventHandler::Class()) {
    printf("========================================================================================\n");
    printf("PIDResponse: AliMultiInputEventHandler detected, initialising AliPIDResponseInputHandler\n");
    printf("========================================================================================\n");
    AliMultiInputEventHandler *multiInputHandler=(AliMultiInputEventHandler*)inputHandler;

    AliPIDResponseInputHandler *pidResponseIH = new AliPIDResponseInputHandler();
    multiInputHandler->AddInputEventHandler(pidResponseIH);

    if (autoMCesd &&
        multiInputHandler->GetFirstInputEventHandler()->IsA()==AliESDInputHandler::Class() &&
        multiInputHandler->GetFirstMCEventHandler()
       ) isMC=kTRUE;
    pidResponseIH->SetIsMC(isMC);

    return 0x0;
  }

  // standard with task
  printf("========================================================================================\n");
  printf("PIDResponse: Initialising AliAnalysisTaskPIDResponse\n");
  printf("========================================================================================\n");

  if ( autoMCesd && (inputHandler->IsA() == AliESDInputHandler::Class()) ) {
    isMC=mgr->GetMCtruthEventHandler()!=0x0;
  }

  AliAnalysisTaskPIDResponse *pidTask = new AliAnalysisTaskPIDResponse("PIDResponseTask");
//   pidTask->SelectCollisionCandidates(AliVEvent::kMB);
  pidTask->SetIsMC(isMC);
  if(isMC&&tuneOnData) pidTask->SetTuneOnData(kTRUE,recoPass);
  mgr->AddTask(pidTask);

//   AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("PIDResponseQA",
//     TList::Class(), AliAnalysisManager::kOutputContainer,
//     "PIDResponseQA.root");

  mgr->ConnectInput(pidTask, 0, mgr->GetCommonInputContainer());
//   mgr->ConnectOutput(pidTask,1,coutput1);

  return pidTask;
}
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2015 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   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.
*/

#include <Interface/Modules/Fields/ReportFieldGeometryMeasuresDialog.h>
#include <Modules/Legacy/Fields/ReportFieldGeometryMeasures.h>

using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms::Fields;

ReportFieldGeometryMeasuresDialog::ReportFieldGeometryMeasuresDialog(const std::string& name, ModuleStateHandle state,
  QWidget* parent /* = 0 */)
  : ModuleDialogGeneric(state, parent)
{
  setupUi(this);
  setWindowTitle(QString::fromStdString(name));
  fixSize();

  //addCheckBoxManager(truncateDistanceCheckBox_, Parameters::Truncate);
  //addCheckBoxManager(truncateDistanceCheckBox_, Parameters::Truncate);
  //addCheckBoxManager(truncateDistanceCheckBox_, Parameters::Truncate);
  //addCheckBoxManager(truncateDistanceCheckBox_, Parameters::Truncate);
  //addCheckBoxManager(truncateDistanceCheckBox_, Parameters::Truncate);
  //addCheckBoxManager(truncateDistanceCheckBox_, Parameters::Truncate);
  //addComboBoxManager(dataTypeComboBox_, Parameters::OutputFieldDatatype);
}
<commit_msg>UI hookup<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2015 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   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.
*/

#include <Interface/Modules/Fields/ReportFieldGeometryMeasuresDialog.h>
#include <Modules/Legacy/Fields/ReportFieldGeometryMeasures.h>

using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms::Fields;

ReportFieldGeometryMeasuresDialog::ReportFieldGeometryMeasuresDialog(const std::string& name, ModuleStateHandle state,
  QWidget* parent /* = 0 */)
  : ModuleDialogGeneric(state, parent)
{
  setupUi(this);
  setWindowTitle(QString::fromStdString(name));
  fixSize();

  addCheckBoxManager(xPositionCheckBox_, Parameters::XPositionFlag);
  addCheckBoxManager(yPositionCheckBox_, Parameters::YPositionFlag);
  addCheckBoxManager(zPositionCheckBox_, Parameters::ZPositionFlag);
  addCheckBoxManager(indexCheckBox_, Parameters::IndexFlag);
  addCheckBoxManager(sizeCheckBox_, Parameters::SizeFlag);
  addCheckBoxManager(normalsCheckBox_, Parameters::NormalsFlag);
  addComboBoxManager(simplexComboBox_, Parameters::MeasureLocation);
}
<|endoftext|>