<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__MULTIVARIATE__CONTINUOUS__MULTI_GP_HPP__
#define __STAN__PROB__DISTRIBUTIONS__MULTIVARIATE__CONTINUOUS__MULTI_GP_HPP__

#include <boost/random/normal_distribution.hpp>
#include <boost/random/variate_generator.hpp>

#include <stan/math/matrix_error_handling.hpp>
#include <stan/math/error_handling.hpp>
#include <stan/prob/constants.hpp>
#include <stan/prob/traits.hpp>
#include <stan/agrad/agrad.hpp>
#include <stan/meta/traits.hpp>
#include <stan/agrad/matrix.hpp>
#include <stan/math/matrix/dot_product.hpp>
#include <stan/math/matrix/log.hpp>
#include <stan/math/matrix/log_determinant.hpp>
#include <stan/math/matrix/mdivide_right_spd.hpp>
#include <stan/math/matrix/multiply.hpp>
#include <stan/math/matrix/rows_dot_product.hpp>
#include <stan/math/matrix/subtract.hpp>
#include <stan/math/matrix/sum.hpp>

namespace stan {
  namespace prob {
    // MultiGP(y|Sigma,w)   [y.rows() = w.size(), y.cols() = Sigma.rows();
    //                            Sigma symmetric, non-negative, definite]
    /**
     * The log of a multivariate Gaussian Process for the given y, Sigma, and
     * w.  y is a dxN matrix, where each column is a different observation and each
     * row is a different output dimension.  The Guassian Process is assumed to
     * have a scaled kernel matrix with a different scale for each output dimension.
     * This distribution is equivalent to:
     *    for (i in 1:d) row(y,i) ~ multi_normal(0,(1/w[i])*Sigma).
     *
     * @param y A dxN matrix
     * @param Sigma The NxN kernel matrix
     * @param w A d-dimensional vector of positve inverse scale parameters for each output.
     * @return The log of the multivariate GP density.
     * @throw std::domain_error if Sigma is not square, not symmetric,
     * or not semi-positive definite.
     * @tparam T_y Type of scalar.
     * @tparam T_covar Type of kernel.
     * @tparam T_w Type of weight.
     */
    template <bool propto,
    typename T_y, typename T_covar, typename T_w,
    class Policy>
    typename boost::math::tools::promote_args<T_y,T_w,T_covar>::type
    multi_gp_log(const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
                 const Eigen::Matrix<T_covar,Eigen::Dynamic,Eigen::Dynamic>& Sigma,
                 const Eigen::Matrix<T_w,Eigen::Dynamic,1>& w,
                 const Policy&) {
      static const char* function = "stan::prob::multi_gp_log(%1%)";
      typename boost::math::tools::promote_args<T_y,T_w,T_covar>::type lp(0.0);

      using stan::math::log;
      using stan::math::sum;
      using stan::math::check_not_nan;
      using stan::math::check_size_match;
      using stan::math::check_positive;
      using stan::math::check_pos_definite;
      using stan::math::check_finite;
      using stan::math::check_symmetric;
      using stan::math::dot_product;
      using stan::math::rows_dot_product;
      using stan::math::mdivide_right_spd;
      using stan::math::log_determinant;

      if (!check_size_match(function,
                            Sigma.rows(), "Rows of kernel matrix",
                            Sigma.cols(), "columns of kernel matrix",
                            &lp, Policy()))
        return lp;
      if (!check_positive(function, Sigma.rows(), "Kernel matrix rows", &lp, Policy()))
        return lp;
      if (!check_symmetric(function, Sigma, "Kernel matrix", &lp, Policy()))
        return lp;
      if (!check_pos_definite(function, Sigma, "Kernel matrix", &lp, Policy()))
        return lp;
      if (!check_size_match(function,
                            y.rows(), "Size of random variable",
                            w.size(), "Size of location parameter",
                            &lp, Policy()))
        return lp;
      if (!check_size_match(function,
                            y.cols(), "Size of random variable",
                            Sigma.rows(), "rows of covariance parameter",
                            &lp, Policy()))
        return lp;
      if (!check_finite(function, w, "Kernel scales", &lp, Policy()))
        return lp;
      if (!check_positive(function, w, "Kernel scales", &lp, Policy()))
        return lp;
      if (!check_not_nan(function, y, "Random variable", &lp, Policy()))
        return lp;

      if (y.rows() == 0)
        return lp;

      if (include_summand<propto>::value)
        lp += NEG_LOG_SQRT_TWO_PI * y.rows() * y.cols();

      if (include_summand<propto,T_covar>::value) {
        lp -= (0.5 * y.rows()) * log_determinant(Sigma);
      }

      if (include_summand<propto,T_w>::value) {
        lp += (0.5 * y.cols()) * sum(log(w));
      }

      if (include_summand<propto,T_y,T_w,T_covar>::value) {
        Eigen::Matrix<typename
        boost::math::tools::promote_args<T_covar,T_y>::type,
        Eigen::Dynamic, Eigen::Dynamic> y_Kinv(mdivide_right_spd(y,Sigma));

        lp -= 0.5 * dot_product(rows_dot_product(y_Kinv,y),w);
      }
      return lp;
    }

    template <bool propto,
    typename T_y, typename T_loc, typename T_covar>
    inline
    typename boost::math::tools::promote_args<T_y,T_loc,T_covar>::type
    multi_gp_log(const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
                 const Eigen::Matrix<T_covar,Eigen::Dynamic,Eigen::Dynamic>& Sigma,
                 const Eigen::Matrix<T_loc,Eigen::Dynamic,1>& w) {
      return multi_gp_log<propto>(y,Sigma,w,stan::math::default_policy());
    }

    template <typename T_y, typename T_loc, typename T_covar,
    class Policy>
    inline
    typename boost::math::tools::promote_args<T_y,T_loc,T_covar>::type
    multi_gp_log(const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
                 const Eigen::Matrix<T_covar,Eigen::Dynamic,Eigen::Dynamic>& Sigma,
                 const Eigen::Matrix<T_loc,Eigen::Dynamic,1>& w,
                 const Policy&){
      return multi_gp_log<false>(y,Sigma,w,Policy());
    }

    template <typename T_y, typename T_loc, typename T_covar>
    inline
    typename boost::math::tools::promote_args<T_y,T_loc,T_covar>::type
    multi_gp_log(const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
                 const Eigen::Matrix<T_covar,Eigen::Dynamic,Eigen::Dynamic>& Sigma,
                 const Eigen::Matrix<T_loc,Eigen::Dynamic,1>& w) {
      return multi_gp_log<false>(y,Sigma,w,stan::math::default_policy());
    }
  }
}

#endif
<commit_msg>Use log_determinant_spd in multi_gp_log.<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__MULTIVARIATE__CONTINUOUS__MULTI_GP_HPP__
#define __STAN__PROB__DISTRIBUTIONS__MULTIVARIATE__CONTINUOUS__MULTI_GP_HPP__

#include <boost/random/normal_distribution.hpp>
#include <boost/random/variate_generator.hpp>

#include <stan/math/matrix_error_handling.hpp>
#include <stan/math/error_handling.hpp>
#include <stan/prob/constants.hpp>
#include <stan/prob/traits.hpp>
#include <stan/agrad/agrad.hpp>
#include <stan/meta/traits.hpp>
#include <stan/agrad/matrix.hpp>
#include <stan/math/matrix/dot_product.hpp>
#include <stan/math/matrix/log.hpp>
#include <stan/math/matrix/log_determinant_spd.hpp>
#include <stan/math/matrix/mdivide_right_spd.hpp>
#include <stan/math/matrix/multiply.hpp>
#include <stan/math/matrix/rows_dot_product.hpp>
#include <stan/math/matrix/subtract.hpp>
#include <stan/math/matrix/sum.hpp>

namespace stan {
  namespace prob {
    // MultiGP(y|Sigma,w)   [y.rows() = w.size(), y.cols() = Sigma.rows();
    //                            Sigma symmetric, non-negative, definite]
    /**
     * The log of a multivariate Gaussian Process for the given y, Sigma, and
     * w.  y is a dxN matrix, where each column is a different observation and each
     * row is a different output dimension.  The Guassian Process is assumed to
     * have a scaled kernel matrix with a different scale for each output dimension.
     * This distribution is equivalent to:
     *    for (i in 1:d) row(y,i) ~ multi_normal(0,(1/w[i])*Sigma).
     *
     * @param y A dxN matrix
     * @param Sigma The NxN kernel matrix
     * @param w A d-dimensional vector of positve inverse scale parameters for each output.
     * @return The log of the multivariate GP density.
     * @throw std::domain_error if Sigma is not square, not symmetric,
     * or not semi-positive definite.
     * @tparam T_y Type of scalar.
     * @tparam T_covar Type of kernel.
     * @tparam T_w Type of weight.
     */
    template <bool propto,
    typename T_y, typename T_covar, typename T_w,
    class Policy>
    typename boost::math::tools::promote_args<T_y,T_w,T_covar>::type
    multi_gp_log(const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
                 const Eigen::Matrix<T_covar,Eigen::Dynamic,Eigen::Dynamic>& Sigma,
                 const Eigen::Matrix<T_w,Eigen::Dynamic,1>& w,
                 const Policy&) {
      static const char* function = "stan::prob::multi_gp_log(%1%)";
      typename boost::math::tools::promote_args<T_y,T_w,T_covar>::type lp(0.0);

      using stan::math::log;
      using stan::math::sum;
      using stan::math::check_not_nan;
      using stan::math::check_size_match;
      using stan::math::check_positive;
      using stan::math::check_pos_definite;
      using stan::math::check_finite;
      using stan::math::check_symmetric;
      using stan::math::dot_product;
      using stan::math::rows_dot_product;
      using stan::math::mdivide_right_spd;
      using stan::math::log_determinant_spd;

      if (!check_size_match(function,
                            Sigma.rows(), "Rows of kernel matrix",
                            Sigma.cols(), "columns of kernel matrix",
                            &lp, Policy()))
        return lp;
      if (!check_positive(function, Sigma.rows(), "Kernel matrix rows", &lp, Policy()))
        return lp;
      if (!check_finite(function, Sigma, "Kernel", &lp, Policy()))
        return lp;
      if (!check_symmetric(function, Sigma, "Kernel matrix", &lp, Policy()))
        return lp;
      if (!check_pos_definite(function, Sigma, "Kernel matrix", &lp, Policy()))
        return lp;
      if (!check_size_match(function,
                            y.rows(), "Size of random variable",
                            w.size(), "Size of location parameter",
                            &lp, Policy()))
        return lp;
      if (!check_size_match(function,
                            y.cols(), "Size of random variable",
                            Sigma.rows(), "rows of covariance parameter",
                            &lp, Policy()))
        return lp;
      if (!check_finite(function, w, "Kernel scales", &lp, Policy()))
        return lp;
      if (!check_positive(function, w, "Kernel scales", &lp, Policy()))
        return lp;
      if (!check_not_nan(function, y, "Random variable", &lp, Policy()))
        return lp;

      if (y.rows() == 0)
        return lp;

      if (include_summand<propto>::value) {
        lp += NEG_LOG_SQRT_TWO_PI * y.rows() * y.cols();
      }

      if (include_summand<propto,T_covar>::value) {
        lp -= (0.5 * y.rows()) * log_determinant_spd(Sigma);
      }

      if (include_summand<propto,T_w>::value) {
        lp += (0.5 * y.cols()) * sum(log(w));
      }

      if (include_summand<propto,T_y,T_w,T_covar>::value) {
        Eigen::Matrix<typename
        boost::math::tools::promote_args<T_covar,T_y>::type,
        Eigen::Dynamic, Eigen::Dynamic> y_Kinv(mdivide_right_spd(y,Sigma));

        lp -= 0.5 * dot_product(rows_dot_product(y_Kinv,y),w);
      }
      return lp;
    }

    template <bool propto,
    typename T_y, typename T_loc, typename T_covar>
    inline
    typename boost::math::tools::promote_args<T_y,T_loc,T_covar>::type
    multi_gp_log(const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
                 const Eigen::Matrix<T_covar,Eigen::Dynamic,Eigen::Dynamic>& Sigma,
                 const Eigen::Matrix<T_loc,Eigen::Dynamic,1>& w) {
      return multi_gp_log<propto>(y,Sigma,w,stan::math::default_policy());
    }

    template <typename T_y, typename T_loc, typename T_covar,
    class Policy>
    inline
    typename boost::math::tools::promote_args<T_y,T_loc,T_covar>::type
    multi_gp_log(const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
                 const Eigen::Matrix<T_covar,Eigen::Dynamic,Eigen::Dynamic>& Sigma,
                 const Eigen::Matrix<T_loc,Eigen::Dynamic,1>& w,
                 const Policy&){
      return multi_gp_log<false>(y,Sigma,w,Policy());
    }

    template <typename T_y, typename T_loc, typename T_covar>
    inline
    typename boost::math::tools::promote_args<T_y,T_loc,T_covar>::type
    multi_gp_log(const Eigen::Matrix<T_y,Eigen::Dynamic,Eigen::Dynamic>& y,
                 const Eigen::Matrix<T_covar,Eigen::Dynamic,Eigen::Dynamic>& Sigma,
                 const Eigen::Matrix<T_loc,Eigen::Dynamic,1>& w) {
      return multi_gp_log<false>(y,Sigma,w,stan::math::default_policy());
    }
  }
}

#endif
<|endoftext|>


<commit_before>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*          All contents are licensed under LGPL V2.1           */
/*             See LICENSE for full restrictions                */
/****************************************************************/
#include "AsymmetricCrossTermBarrierFunctionMaterial.h"

template<>
InputParameters validParams<AsymmetricCrossTermBarrierFunctionMaterial>()
{
  InputParameters params = validParams<CrossTermBarrierFunctionBase>();
  params.addClassDescription("Free energy contribution asymmetric across interfaces between arbitrary pairs of phases.");
  params.addParam<std::vector<MaterialPropertyName> >("hi_names", "Switching Function Materials that provide h(eta_i)");
  return params;
}

AsymmetricCrossTermBarrierFunctionMaterial::AsymmetricCrossTermBarrierFunctionMaterial(const InputParameters & parameters) :
    CrossTermBarrierFunctionBase(parameters),
    _h(_num_eta),
    _dh(_num_eta),
    _d2h(_num_eta)
{
  // switching functions
  const std::vector<MaterialPropertyName> & hi_names = getParam<std::vector<MaterialPropertyName> >("hi_names");
  if (hi_names.size() != _num_eta)
    mooseError("The number of coupled etas must be equal to the number of hi_names in AsymmetricCrossTermBarrierFunctionMaterial " << name());

  for (unsigned int i = 0; i < _num_eta; ++i)
  {
    _h[i] = &getMaterialProperty<Real>(hi_names[i]);
    _dh[i] = &getMaterialPropertyDerivative<Real>(hi_names[i], _eta_names[i]);
    _d2h[i] = &getMaterialPropertyDerivative<Real>(hi_names[i], _eta_names[i], _eta_names[i]);
  }
}

void
AsymmetricCrossTermBarrierFunctionMaterial::computeQpProperties()
{
  // Initialize properties to zero before accumulating
  CrossTermBarrierFunctionBase::computeQpProperties();

  // Sum the components of our W_ij matrix to get constant used in our g function
  for (unsigned int i = 0; i < _num_eta; ++i)
    for (unsigned int j = i + 1; j < _num_eta; ++j)
    {
      const Real ni = (*_eta[i])[_qp];
      const Real nj = (*_eta[j])[_qp];

      const Real Wij = _W_ij[_num_eta * i + j];
      const Real Wji = _W_ij[_num_eta * j + i];

      switch (_g_order)
      {
        case 0: // SIMPLE
          _prop_g[_qp] += 16.0 * (Wij * (*_h[i])[_qp] + Wji * (*_h[j])[_qp]) * (ni * ni * nj * nj);
          // first derivatives
          (*_prop_dg[i])[_qp] += 16.0 * (  (Wij * (*_h[i])[_qp] + Wji * (*_h[j])[_qp]) * (2 * ni * nj * nj)
                                         + (Wij * (*_dh[i])[_qp]) * (ni * ni * nj * nj));
          (*_prop_dg[j])[_qp] += 16.0 * (  (Wij * (*_h[i])[_qp] + Wji * (*_h[j])[_qp]) * (2 * ni * ni * nj)
                                         + (Wji * (*_dh[j])[_qp]) * (ni * ni * nj * nj));
          // second derivatives (diagonal)
          (*_prop_d2g[i][i])[_qp] += 16.0 * (  (Wij * (*_h[i])[_qp] + Wji * (*_h[j])[_qp]) * (2 * nj * nj)
                                             + 2 * (Wij * (*_dh[i])[_qp]) * (2 * ni * nj * nj)
                                             + (Wij * (*_d2h[i])[_qp]) * (ni * ni * nj * nj));
          (*_prop_d2g[j][j])[_qp] += 16.0 * (  (Wij * (*_h[i])[_qp] + Wji * (*_h[j])[_qp]) * (2 * ni * ni)
                                             + 2 * (Wji * (*_dh[j])[_qp]) * (2 * ni * ni * nj)
                                             + (Wji * (*_d2h[j])[_qp]) * (ni * ni * nj * nj));
          // second derivatives (off-diagonal)
          (*_prop_d2g[i][j])[_qp] = 16.0 * (  (Wij * (*_h[i])[_qp] + Wji * (*_h[j])[_qp]) * (4 * ni * nj)
                                             + (Wji * (*_dh[j])[_qp]) * (2 * ni * nj * nj)
                                             + (Wij * (*_dh[i])[_qp]) * (2 * ni * ni * nj));
          break;

        case 1: // LOW
          _prop_g[_qp] += 4.0 * (Wij * (*_h[i])[_qp] + Wji * (*_h[j])[_qp]) * (ni * nj);
          // first derivatives
          (*_prop_dg[i])[_qp] += 4.0 * (  (Wij * (*_h[i])[_qp] + Wji * (*_h[j])[_qp]) * nj
                                         + (Wij * (*_dh[i])[_qp]) * (ni * nj));
          (*_prop_dg[j])[_qp] += 4.0 * (  (Wij * (*_h[i])[_qp] + Wji * (*_h[j])[_qp]) * ni
                                         + (Wji * (*_dh[j])[_qp]) * (ni * nj));
          // second derivatives (diagonal)
          (*_prop_d2g[i][i])[_qp] += 4.0 * (  2 * (Wij * (*_dh[i])[_qp]) * nj
                                            + (Wij * (*_d2h[i])[_qp]) * ni * nj);
          (*_prop_d2g[j][j])[_qp] += 4.0 * (  2 * (Wji * (*_dh[j])[_qp]) * ni
                                            + (Wji * (*_d2h[j])[_qp]) * ni * nj);
          // second derivatives (off-diagonal)
          (*_prop_d2g[i][j])[_qp] = 4.0 * (  (Wij * (*_h[i])[_qp] + Wji * (*_h[j])[_qp])
                                            + (Wji * (*_dh[j])[_qp]) * nj
                                            + (Wij * (*_dh[i])[_qp]) * ni);
          break;

        default:
          mooseError("Internal error");
      }
    }
}
<commit_msg>Add aliases for switching function and derivatives (#6584)<commit_after>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*          All contents are licensed under LGPL V2.1           */
/*             See LICENSE for full restrictions                */
/****************************************************************/
#include "AsymmetricCrossTermBarrierFunctionMaterial.h"

template<>
InputParameters validParams<AsymmetricCrossTermBarrierFunctionMaterial>()
{
  InputParameters params = validParams<CrossTermBarrierFunctionBase>();
  params.addClassDescription("Free energy contribution asymmetric across interfaces between arbitrary pairs of phases.");
  params.addParam<std::vector<MaterialPropertyName> >("hi_names", "Switching Function Materials that provide h(eta_i)");
  return params;
}

AsymmetricCrossTermBarrierFunctionMaterial::AsymmetricCrossTermBarrierFunctionMaterial(const InputParameters & parameters) :
    CrossTermBarrierFunctionBase(parameters),
    _h(_num_eta),
    _dh(_num_eta),
    _d2h(_num_eta)
{
  // switching functions
  const std::vector<MaterialPropertyName> & hi_names = getParam<std::vector<MaterialPropertyName> >("hi_names");
  if (hi_names.size() != _num_eta)
    mooseError("The number of coupled etas must be equal to the number of hi_names in AsymmetricCrossTermBarrierFunctionMaterial " << name());

  for (unsigned int i = 0; i < _num_eta; ++i)
  {
    _h[i] = &getMaterialProperty<Real>(hi_names[i]);
    _dh[i] = &getMaterialPropertyDerivative<Real>(hi_names[i], _eta_names[i]);
    _d2h[i] = &getMaterialPropertyDerivative<Real>(hi_names[i], _eta_names[i], _eta_names[i]);
  }
}

void
AsymmetricCrossTermBarrierFunctionMaterial::computeQpProperties()
{
  // Initialize properties to zero before accumulating
  CrossTermBarrierFunctionBase::computeQpProperties();

  // Sum the components of our W_ij matrix to get constant used in our g function
  for (unsigned int i = 0; i < _num_eta; ++i)
    for (unsigned int j = i + 1; j < _num_eta; ++j)
    {
      // readable aliases
      const Real ni = (*_eta[i])[_qp];
      const Real nj = (*_eta[j])[_qp];

      const Real Wij = _W_ij[_num_eta * i + j];
      const Real Wji = _W_ij[_num_eta * j + i];

      const Real hi = (*_h[i])[_qp];
      const Real hj = (*_h[j])[_qp];
      const Real dhi = (*_dh[i])[_qp];
      const Real dhj = (*_dh[j])[_qp];
      const Real d2hi = (*_d2h[i])[_qp];
      const Real d2hj = (*_d2h[j])[_qp];

      // raw barrier term and derivatives
      Real B, dBi, dBj, d2Bii, d2Bjj, d2Bij;
      switch (_g_order)
      {
        case 0: // SIMPLE
          B = 16.0 * ni * ni * nj * nj;
          dBi = 16.0 * 2.0 * ni * nj * nj;
          dBj = 16.0 * 2.0 * ni * ni * nj;
          d2Bii = 16.0 * 2.0 * nj * nj;
          d2Bjj = 16.0 * 2.0 * ni * ni;
          d2Bij = 16.0 * 4.0 * ni * nj;
          break;

        case 1: // LOW
          B = 4.0 * ni * nj;
          dBi = 4.0 * nj;
          dBj = 4.0 * ni;
          d2Bii = 0.0;
          d2Bjj = 0.0;
          d2Bij = 4.0;
          break;

        default:
          mooseError("Internal error");
      }

      _prop_g[_qp] += (Wij * hi + Wji * hj) * B;
      // first derivatives
      (*_prop_dg[i])[_qp] += (Wij * hi + Wji * hj) * dBi + (Wij * dhi) * B;
      (*_prop_dg[j])[_qp] += (Wij * hi + Wji * hj) * dBj + (Wji * dhj) * B;
      // second derivatives (diagonal)
      (*_prop_d2g[i][i])[_qp] += (Wij * hi + Wji * hj) * d2Bii + 2 * (Wij * dhi) * dBi + (Wij * d2hi) * B;
      (*_prop_d2g[j][j])[_qp] += (Wij * hi + Wji * hj) * d2Bjj + 2 * (Wji * dhj) * dBj + (Wji * d2hj) * B;
      // second derivatives (off-diagonal)
      (*_prop_d2g[i][j])[_qp] = (Wij * hi + Wji * hj) * (d2Bij) + (Wji * dhj) * dBi + (Wij * dhi) * dBj;
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.

#include "browser/url_request_context_getter.h"

#include <algorithm>

#include "browser/network_delegate.h"

#include "base/command_line.h"
#include "base/strings/string_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/worker_pool.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_store_factory.h"
#include "content/public/common/content_switches.h"
#include "net/base/host_mapping_rules.h"
#include "net/cert/cert_verifier.h"
#include "net/cookies/cookie_monster.h"
#include "net/dns/mapped_host_resolver.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_server_properties_impl.h"
#include "net/proxy/dhcp_proxy_script_fetcher_factory.h"
#include "net/proxy/proxy_config_service.h"
#include "net/proxy/proxy_script_fetcher_impl.h"
#include "net/proxy/proxy_service.h"
#include "net/proxy/proxy_service_v8.h"
#include "net/ssl/channel_id_service.h"
#include "net/ssl/default_channel_id_store.h"
#include "net/ssl/ssl_config_service_defaults.h"
#include "net/url_request/data_protocol_handler.h"
#include "net/url_request/file_protocol_handler.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_storage.h"
#include "net/url_request/url_request_intercepting_job_factory.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "url/url_constants.h"
#include "storage/browser/quota/special_storage_policy.h"

using content::BrowserThread;

namespace brightray {

namespace {

// Comma-separated list of rules that control how hostnames are mapped.
//
// For example:
//    "MAP * 127.0.0.1" --> Forces all hostnames to be mapped to 127.0.0.1
//    "MAP *.google.com proxy" --> Forces all google.com subdomains to be
//                                 resolved to "proxy".
//    "MAP test.com [::1]:77 --> Forces "test.com" to resolve to IPv6 loopback.
//                               Will also force the port of the resulting
//                               socket address to be 77.
//    "MAP * baz, EXCLUDE www.google.com" --> Remaps everything to "baz",
//                                            except for "www.google.com".
//
// These mappings apply to the endpoint host in a net::URLRequest (the TCP
// connect and host resolver in a direct connection, and the CONNECT in an http
// proxy connection, and the endpoint host in a SOCKS proxy connection).
const char kHostRules[] = "host-rules";

// Don't use a proxy server, always make direct connections. Overrides any
// other proxy server flags that are passed.
const char kNoProxyServer[] = "no-proxy-server";

// Uses a specified proxy server, overrides system settings. This switch only
// affects HTTP and HTTPS requests.
const char kProxyServer[] = "proxy-server";

}  // namespace

net::URLRequestJobFactory* URLRequestContextGetter::Delegate::CreateURLRequestJobFactory(
    content::ProtocolHandlerMap* protocol_handlers,
    content::URLRequestInterceptorScopedVector* protocol_interceptors) {
  scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(new net::URLRequestJobFactoryImpl);

  for (auto it = protocol_handlers->begin(); it != protocol_handlers->end(); ++it)
    job_factory->SetProtocolHandler(it->first, it->second.release());
  protocol_handlers->clear();

  job_factory->SetProtocolHandler(url::kDataScheme, new net::DataProtocolHandler);
  job_factory->SetProtocolHandler(url::kFileScheme, new net::FileProtocolHandler(
      BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior(
          base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));

  // Set up interceptors in the reverse order.
  scoped_ptr<net::URLRequestJobFactory> top_job_factory =
      job_factory.PassAs<net::URLRequestJobFactory>();
  content::URLRequestInterceptorScopedVector::reverse_iterator i;
  for (i = protocol_interceptors->rbegin(); i != protocol_interceptors->rend(); ++i)
    top_job_factory.reset(new net::URLRequestInterceptingJobFactory(
        top_job_factory.Pass(), make_scoped_ptr(*i)));
  protocol_interceptors->weak_clear();

  return top_job_factory.release();
}

net::HttpCache::BackendFactory*
URLRequestContextGetter::Delegate::CreateHttpCacheBackendFactory(const base::FilePath& base_path) {
  base::FilePath cache_path = base_path.Append(FILE_PATH_LITERAL("Cache"));
  return new net::HttpCache::DefaultBackend(
      net::DISK_CACHE,
      net::CACHE_BACKEND_DEFAULT,
      cache_path,
      0,
      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE));
}

URLRequestContextGetter::URLRequestContextGetter(
    Delegate* delegate,
    const base::FilePath& base_path,
    base::MessageLoop* io_loop,
    base::MessageLoop* file_loop,
    content::ProtocolHandlerMap* protocol_handlers,
    content::URLRequestInterceptorScopedVector protocol_interceptors)
    : delegate_(delegate),
      base_path_(base_path),
      io_loop_(io_loop),
      file_loop_(file_loop),
      protocol_interceptors_(protocol_interceptors.Pass()) {
  // Must first be created on the UI thread.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  std::swap(protocol_handlers_, *protocol_handlers);

  // We must create the proxy config service on the UI loop on Linux because it
  // must synchronously run on the glib message loop. This will be passed to
  // the URLRequestContextStorage on the IO thread in GetURLRequestContext().
  proxy_config_service_.reset(net::ProxyService::CreateSystemProxyConfigService(
      io_loop_->message_loop_proxy(), file_loop_->message_loop_proxy()));
}

URLRequestContextGetter::~URLRequestContextGetter() {
}

net::HostResolver* URLRequestContextGetter::host_resolver() {
  return url_request_context_->host_resolver();
}

net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  if (!url_request_context_.get()) {
    url_request_context_.reset(new net::URLRequestContext);
    network_delegate_.reset(delegate_->CreateNetworkDelegate());
    url_request_context_->set_network_delegate(network_delegate_.get());

    storage_.reset(new net::URLRequestContextStorage(url_request_context_.get()));
    auto cookie_config = content::CookieStoreConfig(
        base_path_.Append(FILE_PATH_LITERAL("Cookies")),
        content::CookieStoreConfig::EPHEMERAL_SESSION_COOKIES,
        NULL, NULL);
    storage_->set_cookie_store(content::CreateCookieStore(cookie_config));
    storage_->set_channel_id_service(new net::ChannelIDService(
        new net::DefaultChannelIDStore(NULL),
        base::WorkerPool::GetTaskRunner(true)));
    storage_->set_http_user_agent_settings(new net::StaticHttpUserAgentSettings(
        "en-us,en", base::EmptyString()));

    scoped_ptr<net::HostResolver> host_resolver(net::HostResolver::CreateDefaultResolver(NULL));

    // --host-resolver-rules
    if (command_line.HasSwitch(switches::kHostResolverRules)) {
      scoped_ptr<net::MappedHostResolver> remapped_resolver(
          new net::MappedHostResolver(host_resolver.Pass()));
      remapped_resolver->SetRulesFromString(
          command_line.GetSwitchValueASCII(switches::kHostResolverRules));
      host_resolver = remapped_resolver.PassAs<net::HostResolver>();
    }

    // --proxy-server
    net::DhcpProxyScriptFetcherFactory dhcp_factory;
    if (command_line.HasSwitch(kNoProxyServer))
      storage_->set_proxy_service(net::ProxyService::CreateDirect());
    else if (command_line.HasSwitch(kProxyServer))
      storage_->set_proxy_service(net::ProxyService::CreateFixed(
          command_line.GetSwitchValueASCII(kProxyServer)));
    else
      storage_->set_proxy_service(
          net::CreateProxyServiceUsingV8ProxyResolver(
              proxy_config_service_.release(),
              new net::ProxyScriptFetcherImpl(url_request_context_.get()),
              dhcp_factory.Create(url_request_context_.get()),
              host_resolver.get(),
              NULL,
              url_request_context_->network_delegate()));

    storage_->set_cert_verifier(net::CertVerifier::CreateDefault());
    storage_->set_transport_security_state(new net::TransportSecurityState);
    storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults);
    storage_->set_http_auth_handler_factory(
        net::HttpAuthHandlerFactory::CreateDefault(host_resolver.get()));
    scoped_ptr<net::HttpServerProperties> server_properties(
        new net::HttpServerPropertiesImpl);
    storage_->set_http_server_properties(server_properties.Pass());

    net::HttpNetworkSession::Params network_session_params;
    network_session_params.cert_verifier = url_request_context_->cert_verifier();
    network_session_params.proxy_service = url_request_context_->proxy_service();
    network_session_params.ssl_config_service = url_request_context_->ssl_config_service();
    network_session_params.network_delegate = url_request_context_->network_delegate();
    network_session_params.http_server_properties = url_request_context_->http_server_properties();
    network_session_params.ignore_certificate_errors = false;
    network_session_params.transport_security_state =
        url_request_context_->transport_security_state();
    network_session_params.channel_id_service =
        url_request_context_->channel_id_service();
    network_session_params.http_auth_handler_factory =
        url_request_context_->http_auth_handler_factory();

    // --host-rules
    if (command_line.HasSwitch(kHostRules)) {
      host_mapping_rules_.reset(new net::HostMappingRules);
      host_mapping_rules_->SetRulesFromString(command_line.GetSwitchValueASCII(kHostRules));
      network_session_params.host_mapping_rules = host_mapping_rules_.get();
    }

    // Give |storage_| ownership at the end in case it's |mapped_host_resolver|.
    storage_->set_host_resolver(host_resolver.Pass());
    network_session_params.host_resolver = url_request_context_->host_resolver();

    net::HttpCache::BackendFactory* backend = delegate_->CreateHttpCacheBackendFactory(base_path_);
    storage_->set_http_transaction_factory(new net::HttpCache(network_session_params, backend));

    storage_->set_job_factory(delegate_->CreateURLRequestJobFactory(
        &protocol_handlers_, &protocol_interceptors_));
  }

  return url_request_context_.get();
}

scoped_refptr<base::SingleThreadTaskRunner> URLRequestContextGetter::GetNetworkTaskRunner() const {
  return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
}

}  // namespace brightray
<commit_msg>Add support for --ignore-certificate-errors<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.

#include "browser/url_request_context_getter.h"

#include <algorithm>

#include "browser/network_delegate.h"

#include "base/command_line.h"
#include "base/strings/string_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/worker_pool.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_store_factory.h"
#include "content/public/common/content_switches.h"
#include "net/base/host_mapping_rules.h"
#include "net/cert/cert_verifier.h"
#include "net/cookies/cookie_monster.h"
#include "net/dns/mapped_host_resolver.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_server_properties_impl.h"
#include "net/proxy/dhcp_proxy_script_fetcher_factory.h"
#include "net/proxy/proxy_config_service.h"
#include "net/proxy/proxy_script_fetcher_impl.h"
#include "net/proxy/proxy_service.h"
#include "net/proxy/proxy_service_v8.h"
#include "net/ssl/channel_id_service.h"
#include "net/ssl/default_channel_id_store.h"
#include "net/ssl/ssl_config_service_defaults.h"
#include "net/url_request/data_protocol_handler.h"
#include "net/url_request/file_protocol_handler.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_storage.h"
#include "net/url_request/url_request_intercepting_job_factory.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "url/url_constants.h"
#include "storage/browser/quota/special_storage_policy.h"

using content::BrowserThread;

namespace brightray {

namespace {

// Comma-separated list of rules that control how hostnames are mapped.
//
// For example:
//    "MAP * 127.0.0.1" --> Forces all hostnames to be mapped to 127.0.0.1
//    "MAP *.google.com proxy" --> Forces all google.com subdomains to be
//                                 resolved to "proxy".
//    "MAP test.com [::1]:77 --> Forces "test.com" to resolve to IPv6 loopback.
//                               Will also force the port of the resulting
//                               socket address to be 77.
//    "MAP * baz, EXCLUDE www.google.com" --> Remaps everything to "baz",
//                                            except for "www.google.com".
//
// These mappings apply to the endpoint host in a net::URLRequest (the TCP
// connect and host resolver in a direct connection, and the CONNECT in an http
// proxy connection, and the endpoint host in a SOCKS proxy connection).
const char kHostRules[] = "host-rules";

// Don't use a proxy server, always make direct connections. Overrides any
// other proxy server flags that are passed.
const char kNoProxyServer[] = "no-proxy-server";

// Uses a specified proxy server, overrides system settings. This switch only
// affects HTTP and HTTPS requests.
const char kProxyServer[] = "proxy-server";

}  // namespace

net::URLRequestJobFactory* URLRequestContextGetter::Delegate::CreateURLRequestJobFactory(
    content::ProtocolHandlerMap* protocol_handlers,
    content::URLRequestInterceptorScopedVector* protocol_interceptors) {
  scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(new net::URLRequestJobFactoryImpl);

  for (auto it = protocol_handlers->begin(); it != protocol_handlers->end(); ++it)
    job_factory->SetProtocolHandler(it->first, it->second.release());
  protocol_handlers->clear();

  job_factory->SetProtocolHandler(url::kDataScheme, new net::DataProtocolHandler);
  job_factory->SetProtocolHandler(url::kFileScheme, new net::FileProtocolHandler(
      BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior(
          base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));

  // Set up interceptors in the reverse order.
  scoped_ptr<net::URLRequestJobFactory> top_job_factory =
      job_factory.PassAs<net::URLRequestJobFactory>();
  content::URLRequestInterceptorScopedVector::reverse_iterator i;
  for (i = protocol_interceptors->rbegin(); i != protocol_interceptors->rend(); ++i)
    top_job_factory.reset(new net::URLRequestInterceptingJobFactory(
        top_job_factory.Pass(), make_scoped_ptr(*i)));
  protocol_interceptors->weak_clear();

  return top_job_factory.release();
}

net::HttpCache::BackendFactory*
URLRequestContextGetter::Delegate::CreateHttpCacheBackendFactory(const base::FilePath& base_path) {
  base::FilePath cache_path = base_path.Append(FILE_PATH_LITERAL("Cache"));
  return new net::HttpCache::DefaultBackend(
      net::DISK_CACHE,
      net::CACHE_BACKEND_DEFAULT,
      cache_path,
      0,
      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE));
}

URLRequestContextGetter::URLRequestContextGetter(
    Delegate* delegate,
    const base::FilePath& base_path,
    base::MessageLoop* io_loop,
    base::MessageLoop* file_loop,
    content::ProtocolHandlerMap* protocol_handlers,
    content::URLRequestInterceptorScopedVector protocol_interceptors)
    : delegate_(delegate),
      base_path_(base_path),
      io_loop_(io_loop),
      file_loop_(file_loop),
      protocol_interceptors_(protocol_interceptors.Pass()) {
  // Must first be created on the UI thread.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  std::swap(protocol_handlers_, *protocol_handlers);

  // We must create the proxy config service on the UI loop on Linux because it
  // must synchronously run on the glib message loop. This will be passed to
  // the URLRequestContextStorage on the IO thread in GetURLRequestContext().
  proxy_config_service_.reset(net::ProxyService::CreateSystemProxyConfigService(
      io_loop_->message_loop_proxy(), file_loop_->message_loop_proxy()));
}

URLRequestContextGetter::~URLRequestContextGetter() {
}

net::HostResolver* URLRequestContextGetter::host_resolver() {
  return url_request_context_->host_resolver();
}

net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  if (!url_request_context_.get()) {
    url_request_context_.reset(new net::URLRequestContext);
    network_delegate_.reset(delegate_->CreateNetworkDelegate());
    url_request_context_->set_network_delegate(network_delegate_.get());

    storage_.reset(new net::URLRequestContextStorage(url_request_context_.get()));
    auto cookie_config = content::CookieStoreConfig(
        base_path_.Append(FILE_PATH_LITERAL("Cookies")),
        content::CookieStoreConfig::EPHEMERAL_SESSION_COOKIES,
        NULL, NULL);
    storage_->set_cookie_store(content::CreateCookieStore(cookie_config));
    storage_->set_channel_id_service(new net::ChannelIDService(
        new net::DefaultChannelIDStore(NULL),
        base::WorkerPool::GetTaskRunner(true)));
    storage_->set_http_user_agent_settings(new net::StaticHttpUserAgentSettings(
        "en-us,en", base::EmptyString()));

    scoped_ptr<net::HostResolver> host_resolver(net::HostResolver::CreateDefaultResolver(NULL));

    // --host-resolver-rules
    if (command_line.HasSwitch(switches::kHostResolverRules)) {
      scoped_ptr<net::MappedHostResolver> remapped_resolver(
          new net::MappedHostResolver(host_resolver.Pass()));
      remapped_resolver->SetRulesFromString(
          command_line.GetSwitchValueASCII(switches::kHostResolverRules));
      host_resolver = remapped_resolver.PassAs<net::HostResolver>();
    }

    // --proxy-server
    net::DhcpProxyScriptFetcherFactory dhcp_factory;
    if (command_line.HasSwitch(kNoProxyServer))
      storage_->set_proxy_service(net::ProxyService::CreateDirect());
    else if (command_line.HasSwitch(kProxyServer))
      storage_->set_proxy_service(net::ProxyService::CreateFixed(
          command_line.GetSwitchValueASCII(kProxyServer)));
    else
      storage_->set_proxy_service(
          net::CreateProxyServiceUsingV8ProxyResolver(
              proxy_config_service_.release(),
              new net::ProxyScriptFetcherImpl(url_request_context_.get()),
              dhcp_factory.Create(url_request_context_.get()),
              host_resolver.get(),
              NULL,
              url_request_context_->network_delegate()));

    storage_->set_cert_verifier(net::CertVerifier::CreateDefault());
    storage_->set_transport_security_state(new net::TransportSecurityState);
    storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults);
    storage_->set_http_auth_handler_factory(
        net::HttpAuthHandlerFactory::CreateDefault(host_resolver.get()));
    scoped_ptr<net::HttpServerProperties> server_properties(
        new net::HttpServerPropertiesImpl);
    storage_->set_http_server_properties(server_properties.Pass());

    net::HttpNetworkSession::Params network_session_params;
    network_session_params.cert_verifier = url_request_context_->cert_verifier();
    network_session_params.proxy_service = url_request_context_->proxy_service();
    network_session_params.ssl_config_service = url_request_context_->ssl_config_service();
    network_session_params.network_delegate = url_request_context_->network_delegate();
    network_session_params.http_server_properties = url_request_context_->http_server_properties();
    network_session_params.ignore_certificate_errors = false;
    network_session_params.transport_security_state =
        url_request_context_->transport_security_state();
    network_session_params.channel_id_service =
        url_request_context_->channel_id_service();
    network_session_params.http_auth_handler_factory =
        url_request_context_->http_auth_handler_factory();

    // --ignore-certificate-errors
    if (command_line.HasSwitch(switches::kIgnoreCertificateErrors))
      network_session_params.ignore_certificate_errors = true;

    // --host-rules
    if (command_line.HasSwitch(kHostRules)) {
      host_mapping_rules_.reset(new net::HostMappingRules);
      host_mapping_rules_->SetRulesFromString(command_line.GetSwitchValueASCII(kHostRules));
      network_session_params.host_mapping_rules = host_mapping_rules_.get();
    }

    // Give |storage_| ownership at the end in case it's |mapped_host_resolver|.
    storage_->set_host_resolver(host_resolver.Pass());
    network_session_params.host_resolver = url_request_context_->host_resolver();

    net::HttpCache::BackendFactory* backend = delegate_->CreateHttpCacheBackendFactory(base_path_);
    storage_->set_http_transaction_factory(new net::HttpCache(network_session_params, backend));

    storage_->set_job_factory(delegate_->CreateURLRequestJobFactory(
        &protocol_handlers_, &protocol_interceptors_));
  }

  return url_request_context_.get();
}

scoped_refptr<base::SingleThreadTaskRunner> URLRequestContextGetter::GetNetworkTaskRunner() const {
  return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
}

}  // namespace brightray
<|endoftext|>


<commit_before>/* Rapicorn
 * Copyright (C) 2005 Tim Janik
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * A copy of the GNU Lesser General Public License should ship along
 * with this library; if not, see http://www.gnu.org/copyleft/.
 */
#ifndef __RAPICORN_ENUMDEFS_HH__
#define __RAPICORN_ENUMDEFS_HH__

#include <rcore/utilities.hh>

namespace Rapicorn {

/* --- enum/flags type descriptions --- */
struct EnumClass {
  struct Value {
    const int64             value;
    const char       *const value_name;
    const uint              name_length;
  };
  virtual            ~EnumClass         () {}
  virtual void        list_values       (uint &n_values, const Value* &values) const = 0;
  virtual const char* enum_name         () const = 0;
  virtual bool        flag_combinable   () const = 0;
  virtual int64       constrain         (int64 value) const = 0;
  bool                match_partial     (const char *value_name1, const char *partial_value_name) const;
  bool                match             (const char *value_name1, const char *value_name2) const;
  const Value*        find_first        (int64 value) const;
  const Value*        find_first        (const String &value_name) const;
  int64               parse             (const char *value_string, String *error = NULL) const;
  String              string            (int64 value) const;
};
template<typename EnumType> EnumType inline enum_type_constrain (EnumType value) { return value; }
template<typename EType>
struct EnumType : public virtual EnumClass {
  typedef EType Type;
  virtual void        list_values       (uint &c_n_values, const Value* &c_values) const { c_n_values = n_values, c_values = values; }
  virtual const char* enum_name         () const { return ename; }
  virtual bool        flag_combinable   () const { return false; }
  virtual int64       constrain         (int64 value) const { return enum_type_constrain<EType> (EType (value)); }
private:
  static const uint         n_values;
  static const Value *const values;
  static const char        *ename;
};
template<typename EType>
struct FlagsType : public virtual EnumClass {
  typedef EType Type;
  virtual void        list_values       (uint &c_n_values, const Value* &c_values) const { c_n_values = n_values, c_values = values; }
  virtual const char* enum_name         () const { return ename; }
  virtual bool        flag_combinable   () const { return true; }
  virtual int64       constrain         (int64 value) const { return enum_type_constrain<EType> (EType (value)); }
private:
  static const uint         n_values;
  static const Value *const values;
  static const char        *ename;
};

/* --- enums --- */
typedef enum {
  ADJUSTMENT_SOURCE_NONE = 0,
  ADJUSTMENT_SOURCE_ANCESTRY_HORIZONTAL,
  ADJUSTMENT_SOURCE_ANCESTRY_VERTICAL,
  ADJUSTMENT_SOURCE_ANCESTRY_VALUE
} AdjustmentSourceType;
typedef EnumType<AdjustmentSourceType> EnumTypeAdjustmentSourceType;

typedef enum {
  ALIGN_LEFT = 1,
  ALIGN_CENTER,
  ALIGN_RIGHT,
} AlignType;
typedef EnumType<AlignType> EnumTypeAlignType;

/**
 * AnchorType specifies an anchoring point for graphical elements.
 */
typedef enum {
  ANCHOR_NONE,
  ANCHOR_CENTER,
  ANCHOR_EAST,
  ANCHOR_NORTH_EAST,
  ANCHOR_NORTH,
  ANCHOR_NORTH_WEST,
  ANCHOR_WEST,
  ANCHOR_SOUTH_WEST,
  ANCHOR_SOUTH,
  ANCHOR_SOUTH_EAST,
} AnchorType;
typedef EnumType<AnchorType> EnumTypeAnchorType;

typedef enum {
  CLICK_ON_PRESS        = 1,
  CLICK_ON_RELEASE,
  CLICK_SLOW_REPEAT,
  CLICK_FAST_REPEAT,
  CLICK_KEY_REPEAT,
} ClickType;
typedef EnumType<ClickType> EnumTypeClickType;

typedef enum {
  COLOR_NONE,
  COLOR_FOREGROUND,
  COLOR_BACKGROUND,
  COLOR_BACKGROUND_EVEN,
  COLOR_BACKGROUND_ODD,
  COLOR_DARK,
  COLOR_DARK_SHADOW,
  COLOR_DARK_GLINT,
  COLOR_LIGHT,
  COLOR_LIGHT_SHADOW,
  COLOR_LIGHT_GLINT,
  COLOR_FOCUS,
  COLOR_BLACK,
  COLOR_WHITE,
  COLOR_RED,
  COLOR_YELLOW,
  COLOR_GREEN,
  COLOR_CYAN,
  COLOR_BLUE,
  COLOR_MAGENTA,
} ColorType;
typedef EnumType<ColorType> EnumTypeColorType;

typedef enum {
  COLOR_INHERIT,        ///< Inherit color from parent component
  COLOR_NORMAL,         ///< Normal color specification
  COLOR_SELECTED,       ///< Color used for selected areas
  COLOR_BASE,           ///< Color used for text or scroll fields
} ColorSchemeType;
typedef EnumType<ColorSchemeType> EnumTypeColorSchemeType;

typedef enum {
  DIR_NONE,
  DIR_RIGHT,
  DIR_UP,
  DIR_LEFT,
  DIR_DOWN,
} DirType;              ///< Enum type for direction indication
typedef EnumType<DirType> EnumTypeDirType;

typedef enum {
  ELLIPSIZE_START = 1,
  ELLIPSIZE_MIDDLE,
  ELLIPSIZE_END
} EllipsizeType;
typedef EnumType<EllipsizeType> EnumTypeEllipsizeType;

typedef enum {
  FOCUS_NEXT    = 1,
  FOCUS_PREV,
  FOCUS_RIGHT,
  FOCUS_UP,
  FOCUS_LEFT,
  FOCUS_DOWN
} FocusDirType;         ///< Enum type for focus movements
typedef EnumType<FocusDirType> EnumTypeFocusDirType;

typedef enum {
  FRAME_NONE,
  FRAME_BACKGROUND,
  FRAME_IN,
  FRAME_OUT,
  FRAME_ETCHED_IN,
  FRAME_ETCHED_OUT,
  FRAME_FOCUS,
  FRAME_ALERT_FOCUS,
} FrameType;
typedef EnumType<FrameType> EnumTypeFrameType;

typedef enum {
  LIGHTING_NONE,
  LIGHTING_UPPER_LEFT,
  LIGHTING_UPPER_RIGHT,
  LIGHTING_LOWER_LEFT,
  LIGHTING_LOWER_RIGHT,
  LIGHTING_CENTER,
  LIGHTING_DIFFUSE,
  LIGHTING_DARK_UPPER_LEFT   = 0x80 | LIGHTING_UPPER_LEFT,
  LIGHTING_DARK_UPPER_RIGHT  = 0x80 | LIGHTING_UPPER_RIGHT,
  LIGHTING_DARK_LOWER_LEFT   = 0x80 | LIGHTING_LOWER_LEFT,
  LIGHTING_DARK_LOWER_RIGHT  = 0x80 | LIGHTING_LOWER_RIGHT,
  LIGHTING_DARK_CENTER       = 0x80 | LIGHTING_CENTER,
  LIGHTING_DARK_DIFFUSE      = 0x80 | LIGHTING_DIFFUSE,
} LightingType;
static const LightingType LIGHTING_DARK_FLAG = LightingType (0x80);
typedef EnumType<LightingType> EnumTypeLightingType;
inline LightingType  operator&  (LightingType  s1, LightingType s2) { return LightingType (s1 & (uint64) s2); }
inline LightingType& operator&= (LightingType &s1, LightingType s2) { s1 = s1 & s2; return s1; }
inline LightingType  operator|  (LightingType  s1, LightingType s2) { return LightingType (s1 | (uint64) s2); }
inline LightingType& operator|= (LightingType &s1, LightingType s2) { s1 = s1 | s2; return s1; }

typedef enum {
  SELECTION_NONE,       ///< No selection possible
  SELECTION_BROWSE,     ///< Browse by always forcing a single selected item
  SELECTION_SINGLE,     ///< Allow selection toggling of a single item
  SELECTION_INTERVAL,   ///< Allow selection of multiple consecutive items
  SELECTION_MULTIPLE,   ///< Allow arbitrary combinations of selected items
} SelectionMode;
typedef EnumType<SelectionMode> EnumTypeSelectionMode;

typedef enum {
  SIZE_POLICY_NORMAL            = 0,
  SIZE_POLICY_WIDTH_FROM_HEIGHT,
  SIZE_POLICY_HEIGHT_FROM_WIDTH,
} SizePolicyType;
typedef EnumType<SizePolicyType> EnumTypeSizePolicyType;

typedef enum {
  STATE_INSENSITIVE     = 1 << 0,
  STATE_PRELIGHT        = 1 << 1,
  STATE_IMPRESSED       = 1 << 2,
  STATE_FOCUS           = 1 << 3,
  STATE_DEFAULT         = 1 << 4,
} StateType;
static const StateType STATE_NORMAL = StateType (0);
static const StateType STATE_MASK = StateType (0x1f);
typedef FlagsType<StateType> FlagsTypeStateType;
inline StateType  operator&  (StateType  s1, StateType s2) { return StateType (s1 & (uint64) s2); }
inline StateType& operator&= (StateType &s1, StateType s2) { s1 = s1 & s2; return s1; }
inline StateType  operator|  (StateType  s1, StateType s2) { return StateType (s1 | (uint64) s2); }
inline StateType& operator|= (StateType &s1, StateType s2) { s1 = s1 | s2; return s1; }

typedef enum {
  TEXT_MODE_WRAPPED = 1,
  TEXT_MODE_ELLIPSIZED,
  TEXT_MODE_SINGLE_LINE,
} TextMode;
typedef EnumType<TextMode> EnumTypeTextMode;

typedef enum {
  /* main window types */
  WINDOW_TYPE_NORMAL  = 0,      ///< Normal window
  WINDOW_TYPE_DESKTOP,          ///< Desktop background
  WINDOW_TYPE_DOCK,             ///< Dock or panel
  WINDOW_TYPE_TOOLBAR,          ///< Torn-off toolbar
  WINDOW_TYPE_MENU,             ///< Torn-off menu
  WINDOW_TYPE_UTILITY,          ///< Palette or toolbox
  WINDOW_TYPE_SPLASH,           ///< Startup/splash screen
  WINDOW_TYPE_DIALOG,           ///< Dialog window, usually transient
  WINDOW_TYPE_DROPDOWN_MENU,    ///< Menu, opened from menubar
  WINDOW_TYPE_POPUP_MENU,       ///< Menu, opened as context menu
  WINDOW_TYPE_TOOLTIP,          ///< Transient context info window
  WINDOW_TYPE_NOTIFICATION,     ///< Transient info window (e.g. info bubble)
  WINDOW_TYPE_COMBO,            ///< Combo box menu or list window
  WINDOW_TYPE_DND,              ///< Window for dragged during DND operations
} WindowType;
typedef EnumType<WindowType> EnumTypeWindowType;

} // Rapicorn

#endif  /* __RAPICORN_ENUMDEFS_HH__ */
<commit_msg>RCORE: provide dummy ctors, demanded by g++-4.6<commit_after>/* Rapicorn
 * Copyright (C) 2005 Tim Janik
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * A copy of the GNU Lesser General Public License should ship along
 * with this library; if not, see http://www.gnu.org/copyleft/.
 */
#ifndef __RAPICORN_ENUMDEFS_HH__
#define __RAPICORN_ENUMDEFS_HH__

#include <rcore/utilities.hh>

namespace Rapicorn {

/* --- enum/flags type descriptions --- */
struct EnumClass {
  struct Value {
    const int64             value;
    const char       *const value_name;
    const uint              name_length;
  };
  virtual            ~EnumClass         () {}
  virtual void        list_values       (uint &n_values, const Value* &values) const = 0;
  virtual const char* enum_name         () const = 0;
  virtual bool        flag_combinable   () const = 0;
  virtual int64       constrain         (int64 value) const = 0;
  bool                match_partial     (const char *value_name1, const char *partial_value_name) const;
  bool                match             (const char *value_name1, const char *value_name2) const;
  const Value*        find_first        (int64 value) const;
  const Value*        find_first        (const String &value_name) const;
  int64               parse             (const char *value_string, String *error = NULL) const;
  String              string            (int64 value) const;
};
template<typename EnumType> EnumType inline enum_type_constrain (EnumType value) { return value; }
template<typename EType>
struct EnumType : public virtual EnumClass {
  typedef EType Type;
  virtual void        list_values       (uint &c_n_values, const Value* &c_values) const { c_n_values = n_values, c_values = values; }
  virtual const char* enum_name         () const { return ename; }
  virtual bool        flag_combinable   () const { return false; }
  virtual int64       constrain         (int64 value) const { return enum_type_constrain<EType> (EType (value)); }
  inline              EnumType          () {}
private:
  static const uint         n_values;
  static const Value *const values;
  static const char        *ename;
};
template<typename EType>
struct FlagsType : public virtual EnumClass {
  typedef EType Type;
  virtual void        list_values       (uint &c_n_values, const Value* &c_values) const { c_n_values = n_values, c_values = values; }
  virtual const char* enum_name         () const { return ename; }
  virtual bool        flag_combinable   () const { return true; }
  virtual int64       constrain         (int64 value) const { return enum_type_constrain<EType> (EType (value)); }
  inline              FlagsType         () {}
private:
  static const uint         n_values;
  static const Value *const values;
  static const char        *ename;
};

/* --- enums --- */
typedef enum {
  ADJUSTMENT_SOURCE_NONE = 0,
  ADJUSTMENT_SOURCE_ANCESTRY_HORIZONTAL,
  ADJUSTMENT_SOURCE_ANCESTRY_VERTICAL,
  ADJUSTMENT_SOURCE_ANCESTRY_VALUE
} AdjustmentSourceType;
typedef EnumType<AdjustmentSourceType> EnumTypeAdjustmentSourceType;

typedef enum {
  ALIGN_LEFT = 1,
  ALIGN_CENTER,
  ALIGN_RIGHT,
} AlignType;
typedef EnumType<AlignType> EnumTypeAlignType;

/**
 * AnchorType specifies an anchoring point for graphical elements.
 */
typedef enum {
  ANCHOR_NONE,
  ANCHOR_CENTER,
  ANCHOR_EAST,
  ANCHOR_NORTH_EAST,
  ANCHOR_NORTH,
  ANCHOR_NORTH_WEST,
  ANCHOR_WEST,
  ANCHOR_SOUTH_WEST,
  ANCHOR_SOUTH,
  ANCHOR_SOUTH_EAST,
} AnchorType;
typedef EnumType<AnchorType> EnumTypeAnchorType;

typedef enum {
  CLICK_ON_PRESS        = 1,
  CLICK_ON_RELEASE,
  CLICK_SLOW_REPEAT,
  CLICK_FAST_REPEAT,
  CLICK_KEY_REPEAT,
} ClickType;
typedef EnumType<ClickType> EnumTypeClickType;

typedef enum {
  COLOR_NONE,
  COLOR_FOREGROUND,
  COLOR_BACKGROUND,
  COLOR_BACKGROUND_EVEN,
  COLOR_BACKGROUND_ODD,
  COLOR_DARK,
  COLOR_DARK_SHADOW,
  COLOR_DARK_GLINT,
  COLOR_LIGHT,
  COLOR_LIGHT_SHADOW,
  COLOR_LIGHT_GLINT,
  COLOR_FOCUS,
  COLOR_BLACK,
  COLOR_WHITE,
  COLOR_RED,
  COLOR_YELLOW,
  COLOR_GREEN,
  COLOR_CYAN,
  COLOR_BLUE,
  COLOR_MAGENTA,
} ColorType;
typedef EnumType<ColorType> EnumTypeColorType;

typedef enum {
  COLOR_INHERIT,        ///< Inherit color from parent component
  COLOR_NORMAL,         ///< Normal color specification
  COLOR_SELECTED,       ///< Color used for selected areas
  COLOR_BASE,           ///< Color used for text or scroll fields
} ColorSchemeType;
typedef EnumType<ColorSchemeType> EnumTypeColorSchemeType;

typedef enum {
  DIR_NONE,
  DIR_RIGHT,
  DIR_UP,
  DIR_LEFT,
  DIR_DOWN,
} DirType;              ///< Enum type for direction indication
typedef EnumType<DirType> EnumTypeDirType;

typedef enum {
  ELLIPSIZE_START = 1,
  ELLIPSIZE_MIDDLE,
  ELLIPSIZE_END
} EllipsizeType;
typedef EnumType<EllipsizeType> EnumTypeEllipsizeType;

typedef enum {
  FOCUS_NEXT    = 1,
  FOCUS_PREV,
  FOCUS_RIGHT,
  FOCUS_UP,
  FOCUS_LEFT,
  FOCUS_DOWN
} FocusDirType;         ///< Enum type for focus movements
typedef EnumType<FocusDirType> EnumTypeFocusDirType;

typedef enum {
  FRAME_NONE,
  FRAME_BACKGROUND,
  FRAME_IN,
  FRAME_OUT,
  FRAME_ETCHED_IN,
  FRAME_ETCHED_OUT,
  FRAME_FOCUS,
  FRAME_ALERT_FOCUS,
} FrameType;
typedef EnumType<FrameType> EnumTypeFrameType;

typedef enum {
  LIGHTING_NONE,
  LIGHTING_UPPER_LEFT,
  LIGHTING_UPPER_RIGHT,
  LIGHTING_LOWER_LEFT,
  LIGHTING_LOWER_RIGHT,
  LIGHTING_CENTER,
  LIGHTING_DIFFUSE,
  LIGHTING_DARK_UPPER_LEFT   = 0x80 | LIGHTING_UPPER_LEFT,
  LIGHTING_DARK_UPPER_RIGHT  = 0x80 | LIGHTING_UPPER_RIGHT,
  LIGHTING_DARK_LOWER_LEFT   = 0x80 | LIGHTING_LOWER_LEFT,
  LIGHTING_DARK_LOWER_RIGHT  = 0x80 | LIGHTING_LOWER_RIGHT,
  LIGHTING_DARK_CENTER       = 0x80 | LIGHTING_CENTER,
  LIGHTING_DARK_DIFFUSE      = 0x80 | LIGHTING_DIFFUSE,
} LightingType;
static const LightingType LIGHTING_DARK_FLAG = LightingType (0x80);
typedef EnumType<LightingType> EnumTypeLightingType;
inline LightingType  operator&  (LightingType  s1, LightingType s2) { return LightingType (s1 & (uint64) s2); }
inline LightingType& operator&= (LightingType &s1, LightingType s2) { s1 = s1 & s2; return s1; }
inline LightingType  operator|  (LightingType  s1, LightingType s2) { return LightingType (s1 | (uint64) s2); }
inline LightingType& operator|= (LightingType &s1, LightingType s2) { s1 = s1 | s2; return s1; }

typedef enum {
  SELECTION_NONE,       ///< No selection possible
  SELECTION_BROWSE,     ///< Browse by always forcing a single selected item
  SELECTION_SINGLE,     ///< Allow selection toggling of a single item
  SELECTION_INTERVAL,   ///< Allow selection of multiple consecutive items
  SELECTION_MULTIPLE,   ///< Allow arbitrary combinations of selected items
} SelectionMode;
typedef EnumType<SelectionMode> EnumTypeSelectionMode;

typedef enum {
  SIZE_POLICY_NORMAL            = 0,
  SIZE_POLICY_WIDTH_FROM_HEIGHT,
  SIZE_POLICY_HEIGHT_FROM_WIDTH,
} SizePolicyType;
typedef EnumType<SizePolicyType> EnumTypeSizePolicyType;

typedef enum {
  STATE_INSENSITIVE     = 1 << 0,
  STATE_PRELIGHT        = 1 << 1,
  STATE_IMPRESSED       = 1 << 2,
  STATE_FOCUS           = 1 << 3,
  STATE_DEFAULT         = 1 << 4,
} StateType;
static const StateType STATE_NORMAL = StateType (0);
static const StateType STATE_MASK = StateType (0x1f);
typedef FlagsType<StateType> FlagsTypeStateType;
inline StateType  operator&  (StateType  s1, StateType s2) { return StateType (s1 & (uint64) s2); }
inline StateType& operator&= (StateType &s1, StateType s2) { s1 = s1 & s2; return s1; }
inline StateType  operator|  (StateType  s1, StateType s2) { return StateType (s1 | (uint64) s2); }
inline StateType& operator|= (StateType &s1, StateType s2) { s1 = s1 | s2; return s1; }

typedef enum {
  TEXT_MODE_WRAPPED = 1,
  TEXT_MODE_ELLIPSIZED,
  TEXT_MODE_SINGLE_LINE,
} TextMode;
typedef EnumType<TextMode> EnumTypeTextMode;

typedef enum {
  /* main window types */
  WINDOW_TYPE_NORMAL  = 0,      ///< Normal window
  WINDOW_TYPE_DESKTOP,          ///< Desktop background
  WINDOW_TYPE_DOCK,             ///< Dock or panel
  WINDOW_TYPE_TOOLBAR,          ///< Torn-off toolbar
  WINDOW_TYPE_MENU,             ///< Torn-off menu
  WINDOW_TYPE_UTILITY,          ///< Palette or toolbox
  WINDOW_TYPE_SPLASH,           ///< Startup/splash screen
  WINDOW_TYPE_DIALOG,           ///< Dialog window, usually transient
  WINDOW_TYPE_DROPDOWN_MENU,    ///< Menu, opened from menubar
  WINDOW_TYPE_POPUP_MENU,       ///< Menu, opened as context menu
  WINDOW_TYPE_TOOLTIP,          ///< Transient context info window
  WINDOW_TYPE_NOTIFICATION,     ///< Transient info window (e.g. info bubble)
  WINDOW_TYPE_COMBO,            ///< Combo box menu or list window
  WINDOW_TYPE_DND,              ///< Window for dragged during DND operations
} WindowType;
typedef EnumType<WindowType> EnumTypeWindowType;

} // Rapicorn

#endif  /* __RAPICORN_ENUMDEFS_HH__ */
<|endoftext|>


<commit_before>#include <iostream>
#include <math.h>

void find_missing(int array[], int n){
  //takes O(2^n)time and takes the  memory of two of the arrays
  int size = pow(2,n);
  bool found[size];
  for (int x=0;x<size;x++)found[x]=0;
  for (int x=0;x<size-2;x++)found[array[x]]=1;
  for (int x=0;x<size;x++) if(!found[x])std::cout<<x<<std::endl;
}

int main(){
  int v[]={0,1,3,4,5,6};
  find_missing( v,3);
  return 0;
}
<commit_msg>I don 't know what I did but it's a change so it must be good.<commit_after>#include <iostream>
#include <math.h>

void find_missing(int array[], int n){
	//takes O(2^n)time and takes the  memory of two of the arrays
	int size = pow(2,n);
	bool found[size];
	for (int x=0;x<size;x++)found[x]=0;
	for (int x=0;x<size-2;x++)found[array[x]]=1;
	for (int x=0;x<size;x++) if(!found[x])std::cout<<x<<std::endl;
}

int main(){
	int v[]={0,1,3,4,5,6};
	find_missing( v,3);
	return 0;
}
<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 *
 * Copyright © 2018 Ruben Van Boxem
 *
 * 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 "test.h++"

#include <core/string.h++>

#include <boost/spirit/home/x3.hpp>

namespace skui::test
{
  using skui::test::check;
  using skui::core::string;

  template<typename Rule>
  void check_rule_success(const Rule& rule,
                          const string& input,
                          const typename Rule::attribute_type& expected_value)
  {
    using boost::spirit::x3::phrase_parse;
    using boost::spirit::x3::space;

    typename Rule::attribute_type result;
    auto first = input.begin();
    auto last = input.end();
    bool success = phrase_parse(first, last,
                                rule,
                                space,
                                result);

    const string rule_name = rule.name;
    check(success, "Rule " + rule_name + " parsed input succesfully; " + input);
    check(first == last, "Rule " + rule_name + " matched complete input: " + input);
    check(result == expected_value, "Rule " + rule_name + " matched expected result for input: " + input);
  }

  template<typename Rule>
  void check_rule_failure(const Rule& rule,
                          const string& input)
  {
    using boost::spirit::x3::phrase_parse;
    using boost::spirit::x3::space;

    typename Rule::attribute_type result;
    auto first = input.begin();
    auto last = input.end();
    bool success = phrase_parse(first, last,
                                rule,
                                space,
                                result);

    const string rule_name = rule.name;
    bool failure = !success || first != last;
    check(failure, "Rule " + rule_name + " parsed input unsuccesfully");
  }
}
<commit_msg>Add debug output to check_rule helpers.<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright © 2018 Ruben Van Boxem
 *
 * 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 "test.h++"

#include <core/debug.h++>
#include <core/string.h++>

#include <boost/spirit/home/x3.hpp>

namespace skui::test
{
  using skui::test::check;
  using skui::core::string;

  template<typename Rule>
  void check_rule_success(const Rule& rule,
                          const string& input,
                          const typename Rule::attribute_type& expected_value)
  {
    using boost::spirit::x3::phrase_parse;
    using boost::spirit::x3::space;

    typename Rule::attribute_type result;
    auto first = input.begin();
    auto last = input.end();
    bool success = phrase_parse(first, last,
                                rule,
                                space,
                                result);

    const string rule_name = rule.name;
    check(success, "Rule " + rule_name + " parsed input succesfully; " + input);
    check(first == last, "Rule " + rule_name + " matched complete input: " + input);
    check(result == expected_value, "Rule " + rule_name + " matched expected result for input: " + input);
    if constexpr(std::is_same_v<typename Rule::attribute_type, unsigned char>)
      core::debug_print("result: ", +result, '\n');
    else
      core::debug_print("result: ", result, '\n');
  }

  template<typename Rule>
  void check_rule_failure(const Rule& rule,
                          const string& input)
  {
    using boost::spirit::x3::phrase_parse;
    using boost::spirit::x3::space;

    typename Rule::attribute_type result;
    auto first = input.begin();
    auto last = input.end();
    bool success = phrase_parse(first, last,
                                rule,
                                space,
                                result);

    const string rule_name = rule.name;
    bool failure = !success || first != last;
    check(failure, "Rule " + rule_name + " parsed input unsuccesfully: " + input);
    if constexpr(std::is_same_v<typename Rule::attribute_type, unsigned char>)
      core::debug_print("result: ", +result, '\n');
    else
      core::debug_print("result: ", result, '\n');
  }
}
<|endoftext|>


<commit_before>#include "backup_debug.h"
// Call all the trace and warn code (for coverage)
int test_main (int argc __attribute__((__unused__)), const char *argv[] __attribute__((__unused__))) {
    HotBackup::CopyTrace("hello", "there");
    return 0;
}
<commit_msg>Refs #6699.  Some coverage in backup_debug.cc<commit_after>#include "backup_debug.h"
#include "backup.h"
// Call all the trace and warn code (for coverage)
int test_main (int argc __attribute__((__unused__)), const char *argv[] __attribute__((__unused__))) {
    HotBackup::CopyTrace("hello", "there");
    HotBackup::CopyWarn("hello", "there");
    HotBackup::CopyError("hello", "there");

    HotBackup::CaptureTrace("hello", "there");
    HotBackup::CaptureTrace("hello", 3);
    HotBackup::CaptureWarn("hello", "there");
    HotBackup::CaptureError("hello", "there");
    HotBackup::CaptureError("hello", 3);

    HotBackup::InterposeTrace("hello", "there");
    HotBackup::InterposeTrace("hello", 3);
    HotBackup::InterposeWarn("hello", "there");
    HotBackup::InterposeError("hello", "there");

    HotBackup::should_pause(HotBackup::MANAGER_IN_PREPARE);
    HotBackup::should_pause(HotBackup::MANAGER_IN_DISABLE);
    HotBackup::should_pause(-1);

    return 0;
}
<|endoftext|>


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

#include <precomp.h>
#include "pm_aldef.hxx"

// NOT FULLY DEFINED SERVICES
#include <cosv/template/tpltools.hxx>
#include <ary/cpp/c_disply.hxx>
#include <ary/cpp/c_define.hxx>
#include <ary/cpp/c_macro.hxx>
#include <ary/loc/l_rogate.hxx>
#include <ary/loc/loc_file.hxx>
#include "hd_docu.hxx"
#include "html_kit.hxx"
#include "navibar.hxx"
#include "opageenv.hxx"
#include "pagemake.hxx"
#include "strconst.hxx"

using namespace csi;
using csi::html::HorizontalLine;
using csi::html::Link;
using csi::html::Label;
using csi::html::AlignAttr;

PageMaker_AllDefs::PageMaker_AllDefs( PageDisplay & io_rPage )
    :   SpecializedPageMaker(io_rPage),
        pDocuDisplay( new Docu_Display(io_rPage.Env()) ),
        pNavi(0)
{
}

PageMaker_AllDefs::~PageMaker_AllDefs()
{
}

void
PageMaker_AllDefs::MakePage()
{
    pNavi = new NavigationBar( Env(), NavigationBar::LOC_AllDefs );
    Write_NavBar();

    Write_TopArea();

    Write_DefinesList();
    Write_MacrosList();

    pNavi->Write_SubRows();
}

void
PageMaker_AllDefs::Write_NavBar()
{
    pNavi->MakeSubRow( "" );
    pNavi->AddItem( "Defines", "defines", true );
    pNavi->AddItem( "Macros", "macros", true );
    pNavi->Write( CurOut() );
    CurOut() << new HorizontalLine;
}

void
PageMaker_AllDefs::Write_TopArea()
{
    adcdisp::PageTitle_Std fTitle;
    fTitle( CurOut(), "Defines and ", "Macros" );

    CurOut() << new HorizontalLine;
}

void
PageMaker_AllDefs::Write_DocuArea()
{
    // Not needed.
}

void
PageMaker_AllDefs::Write_DefinesList()
{
    CurOut()
        << new html::LineBreak
        << new html::LineBreak
        >> *new xml::AnElement("div")
            << new html::ClassAttr("define")
            >> *new html::Label("defines")
                >> *new html::Headline(3)
                    << "Defines";

    List_Ids aAllDefines;
    uintt nCount = Env().Gate().RoDefines().Get_AllDefines(aAllDefines);

    if (nCount > 0)
    {
        csv::call_for_each( aAllDefines,
                            this,
                            &PageMaker_AllDefs::Write_Define );
    }
    else
    {
        CurOut() << "None.";
    }

    CurOut() << new HorizontalLine;
}

void
PageMaker_AllDefs::Write_MacrosList()

{
    CurOut()
        << new html::LineBreak
        << new html::LineBreak
        >> *new xml::AnElement("div")
            << new html::ClassAttr("define")
            >> *new html::Label("macros")
                >> *new html::Headline(3)
                    << "Macros";

    List_Ids aAllMacros;
    uintt nCount = Env().Gate().RoDefines().Get_AllMacros(aAllMacros);

    if (nCount > 0)
    {
        csv::call_for_each(  aAllMacros,
                             this,
                             &PageMaker_AllDefs::Write_Macro );
    }
    else
    {
        CurOut() << "None.";
    }

    CurOut() << new HorizontalLine;
}

void
PageMaker_AllDefs::Write_Define( const ary::Rid & i_nId )
{
    const ary::cpp::Define *
        pDef = Env().Gate().RoDefines().Find_Define(i_nId);
    if (pDef == 0)
        return;

    CurOut() << new html::HorizontalLine;

    adcdisp::ExplanationList aDocu( CurOut(), true );
    aDocu.AddEntry();

    aDocu.Term()
        >> *new html::Label( pDef->DefinedName() )
            << " ";
    aDocu.Term()
        << pDef->DefinedName();

    Write_DefsDocu( aDocu.Def(), *pDef );
}

void
PageMaker_AllDefs::Write_Macro( const ary::Rid & i_nId )
{
    const ary::cpp::Macro *
        pDef = Env().Gate().RoDefines().Find_Macro(i_nId);
    if (pDef == 0)
        return;

    CurOut() << new html::HorizontalLine;

    adcdisp::ExplanationList aDocu( CurOut(), true );
    aDocu.AddEntry();

    aDocu.Term()
        >> *new html::Label( pDef->DefinedName() )
            << " ";
    aDocu.Term()
        << pDef->DefinedName()
        << "(";
    WriteOut_TokenList( aDocu.Term(), pDef->Params(), ", " );
    aDocu.Term()
        << ")";

    Write_DefsDocu( aDocu.Def(), *pDef );
}

void
PageMaker_AllDefs::Write_DefsDocu( csi::xml::Element &              o_rOut,
                                   const ary::cpp::CppDefinition &  i_rTextReplacement )
{
    if ( i_rTextReplacement.DefinitionText().size() > 0 )
    {
        EraseLeadingSpace( *const_cast< udmstri* >(
                                &(*i_rTextReplacement.DefinitionText().begin())
                         ) );
    }

    adcdisp::ExplanationTable rList( o_rOut );

    rList.AddEntry( "Defined As" );
    WriteOut_TokenList( rList.Def(), i_rTextReplacement.DefinitionText(), " " );

    ary::loc::SourceCodeFile *
        pFile = Env().Gate().RoLocations().Find_File( i_rTextReplacement.Location() );
    if (pFile != 0 )
    {
        rList.AddEntry( "In File" );
        rList.Def() << pFile->Name();
    }

    ShowDocu_On( o_rOut, *pDocuDisplay, i_rTextReplacement );
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.8); FILE MERGED 2005/09/05 13:10:48 rt 1.2.8.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pm_aldef.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 17:33:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <precomp.h>
#include "pm_aldef.hxx"

// NOT FULLY DEFINED SERVICES
#include <cosv/template/tpltools.hxx>
#include <ary/cpp/c_disply.hxx>
#include <ary/cpp/c_define.hxx>
#include <ary/cpp/c_macro.hxx>
#include <ary/loc/l_rogate.hxx>
#include <ary/loc/loc_file.hxx>
#include "hd_docu.hxx"
#include "html_kit.hxx"
#include "navibar.hxx"
#include "opageenv.hxx"
#include "pagemake.hxx"
#include "strconst.hxx"

using namespace csi;
using csi::html::HorizontalLine;
using csi::html::Link;
using csi::html::Label;
using csi::html::AlignAttr;

PageMaker_AllDefs::PageMaker_AllDefs( PageDisplay & io_rPage )
    :   SpecializedPageMaker(io_rPage),
        pDocuDisplay( new Docu_Display(io_rPage.Env()) ),
        pNavi(0)
{
}

PageMaker_AllDefs::~PageMaker_AllDefs()
{
}

void
PageMaker_AllDefs::MakePage()
{
    pNavi = new NavigationBar( Env(), NavigationBar::LOC_AllDefs );
    Write_NavBar();

    Write_TopArea();

    Write_DefinesList();
    Write_MacrosList();

    pNavi->Write_SubRows();
}

void
PageMaker_AllDefs::Write_NavBar()
{
    pNavi->MakeSubRow( "" );
    pNavi->AddItem( "Defines", "defines", true );
    pNavi->AddItem( "Macros", "macros", true );
    pNavi->Write( CurOut() );
    CurOut() << new HorizontalLine;
}

void
PageMaker_AllDefs::Write_TopArea()
{
    adcdisp::PageTitle_Std fTitle;
    fTitle( CurOut(), "Defines and ", "Macros" );

    CurOut() << new HorizontalLine;
}

void
PageMaker_AllDefs::Write_DocuArea()
{
    // Not needed.
}

void
PageMaker_AllDefs::Write_DefinesList()
{
    CurOut()
        << new html::LineBreak
        << new html::LineBreak
        >> *new xml::AnElement("div")
            << new html::ClassAttr("define")
            >> *new html::Label("defines")
                >> *new html::Headline(3)
                    << "Defines";

    List_Ids aAllDefines;
    uintt nCount = Env().Gate().RoDefines().Get_AllDefines(aAllDefines);

    if (nCount > 0)
    {
        csv::call_for_each( aAllDefines,
                            this,
                            &PageMaker_AllDefs::Write_Define );
    }
    else
    {
        CurOut() << "None.";
    }

    CurOut() << new HorizontalLine;
}

void
PageMaker_AllDefs::Write_MacrosList()

{
    CurOut()
        << new html::LineBreak
        << new html::LineBreak
        >> *new xml::AnElement("div")
            << new html::ClassAttr("define")
            >> *new html::Label("macros")
                >> *new html::Headline(3)
                    << "Macros";

    List_Ids aAllMacros;
    uintt nCount = Env().Gate().RoDefines().Get_AllMacros(aAllMacros);

    if (nCount > 0)
    {
        csv::call_for_each(  aAllMacros,
                             this,
                             &PageMaker_AllDefs::Write_Macro );
    }
    else
    {
        CurOut() << "None.";
    }

    CurOut() << new HorizontalLine;
}

void
PageMaker_AllDefs::Write_Define( const ary::Rid & i_nId )
{
    const ary::cpp::Define *
        pDef = Env().Gate().RoDefines().Find_Define(i_nId);
    if (pDef == 0)
        return;

    CurOut() << new html::HorizontalLine;

    adcdisp::ExplanationList aDocu( CurOut(), true );
    aDocu.AddEntry();

    aDocu.Term()
        >> *new html::Label( pDef->DefinedName() )
            << " ";
    aDocu.Term()
        << pDef->DefinedName();

    Write_DefsDocu( aDocu.Def(), *pDef );
}

void
PageMaker_AllDefs::Write_Macro( const ary::Rid & i_nId )
{
    const ary::cpp::Macro *
        pDef = Env().Gate().RoDefines().Find_Macro(i_nId);
    if (pDef == 0)
        return;

    CurOut() << new html::HorizontalLine;

    adcdisp::ExplanationList aDocu( CurOut(), true );
    aDocu.AddEntry();

    aDocu.Term()
        >> *new html::Label( pDef->DefinedName() )
            << " ";
    aDocu.Term()
        << pDef->DefinedName()
        << "(";
    WriteOut_TokenList( aDocu.Term(), pDef->Params(), ", " );
    aDocu.Term()
        << ")";

    Write_DefsDocu( aDocu.Def(), *pDef );
}

void
PageMaker_AllDefs::Write_DefsDocu( csi::xml::Element &              o_rOut,
                                   const ary::cpp::CppDefinition &  i_rTextReplacement )
{
    if ( i_rTextReplacement.DefinitionText().size() > 0 )
    {
        EraseLeadingSpace( *const_cast< udmstri* >(
                                &(*i_rTextReplacement.DefinitionText().begin())
                         ) );
    }

    adcdisp::ExplanationTable rList( o_rOut );

    rList.AddEntry( "Defined As" );
    WriteOut_TokenList( rList.Def(), i_rTextReplacement.DefinitionText(), " " );

    ary::loc::SourceCodeFile *
        pFile = Env().Gate().RoLocations().Find_File( i_rTextReplacement.Location() );
    if (pFile != 0 )
    {
        rList.AddEntry( "In File" );
        rList.Def() << pFile->Name();
    }

    ShowDocu_On( o_rOut, *pDocuDisplay, i_rTextReplacement );
}

<|endoftext|>


<commit_before>#include "gtest/gtest.h"
#define AUTOMATIC_CONVERSIONS
#include <FileMgr.h>
#include <file/file.h>
#include <MemoryMgr.h>
#include <WindowMgr.h>

using namespace Executor;

QDGlobals qd;
#include <quickdraw/cquick.h>
#include <vdriver/vdriver.h>
#include <ResourceMgr.h>

class MockVDriver : public VideoDriver
{
    virtual void setColors(int first_color, int num_colors,
                               const struct ColorSpec *color_array) override
    {

    }

    virtual bool setMode(int width, int height, int bpp,
                                bool grayscale_p) override
    {
        width_ = 512;
        height_ = 342;
        rowBytes_ = 64;
        framebuffer_ = new uint8_t[64*342];
        bpp_ = 1;
        return true;
    }
};

class ExecutorTestEnvironment : public testing::Environment
{
    char *thingOnStack;
    fs::path tempDir;
public:
    ExecutorTestEnvironment(char* thingOnStack) : thingOnStack(thingOnStack) {}

    virtual void SetUp() override
    {
        tempDir = fs::current_path() / fs::unique_path("temptest-%%%%-%%%%-%%%%-%%%%");

        Executor::InitMemory(thingOnStack);
        Executor::ROMlib_fileinit();

        fs::create_directory(tempDir);

        if(auto fsspec = nativePathToFSSpec(tempDir))
        {
            WDPBRec wdpb;

            wdpb.ioVRefNum = fsspec->vRefNum;
            wdpb.ioWDDirID = fsspec->parID;
            wdpb.ioWDProcID = FOURCC('X', 'c', 't', 'r');
            wdpb.ioNamePtr = fsspec->name;
            PBOpenWD(&wdpb, false);
            SetVol(nullptr, wdpb.ioVRefNum);
        }

        vdriver = new MockVDriver();
        initialize_68k_emulator(nullptr, false, (uint32_t *)SYN68K_TO_US(0), 0);

        LM(ResErrProc) = 0;
        InitResources();
        ROMlib_InitGDevices();
        LM(TheZone) = LM(ApplZone);

        ROMlib_color_init();

        InitGraf((Ptr)&qd.thePort);
    }

    virtual void TearDown() override
    {
        if(!tempDir.empty())
            fs::remove_all(tempDir);
    }
};

TEST(MemoryMgr, NewClearGetSizeDispose)
{
    Ptr p = NewPtrClear(42);

    ASSERT_NE(nullptr, p);
    ASSERT_EQ(0, *p);

    ASSERT_EQ(42, GetPtrSize(p));

    DisposePtr(p);
}

int main(int argc, char **argv)
{
    testing::InitGoogleTest(&argc, argv);

    char thingOnStack;
    testing::AddGlobalTestEnvironment(new ExecutorTestEnvironment(&thingOnStack));

    int result = RUN_ALL_TESTS();
    return result;
}
<commit_msg>tests: initialize more of executor (needed for list mgr tests)<commit_after>#include "gtest/gtest.h"
#define AUTOMATIC_CONVERSIONS
#include <FileMgr.h>
#include <file/file.h>
#include <MemoryMgr.h>
#include <WindowMgr.h>
#include <MenuMgr.h>
#include <FontMgr.h>

using namespace Executor;

QDGlobals qd;
#include <quickdraw/cquick.h>
#include <vdriver/vdriver.h>
#include <ResourceMgr.h>

class MockVDriver : public VideoDriver
{
    virtual void setColors(int first_color, int num_colors,
                               const struct ColorSpec *color_array) override
    {

    }

    virtual bool setMode(int width, int height, int bpp,
                                bool grayscale_p) override
    {
        width_ = 512;
        height_ = 342;
        rowBytes_ = 64;
        framebuffer_ = new uint8_t[64*342];
        bpp_ = 1;
        return true;
    }
};

class ExecutorTestEnvironment : public testing::Environment
{
    char *thingOnStack;
    fs::path tempDir;
public:
    ExecutorTestEnvironment(char* thingOnStack) : thingOnStack(thingOnStack) {}

    virtual void SetUp() override
    {
        tempDir = fs::current_path() / fs::unique_path("temptest-%%%%-%%%%-%%%%-%%%%");

        Executor::InitMemory(thingOnStack);
        Executor::ROMlib_fileinit();

        fs::create_directory(tempDir);

        if(auto fsspec = nativePathToFSSpec(tempDir))
        {
            WDPBRec wdpb;

            wdpb.ioVRefNum = fsspec->vRefNum;
            wdpb.ioWDDirID = fsspec->parID;
            wdpb.ioWDProcID = FOURCC('X', 'c', 't', 'r');
            wdpb.ioNamePtr = fsspec->name;
            PBOpenWD(&wdpb, false);
            SetVol(nullptr, wdpb.ioVRefNum);
        }

        vdriver = new MockVDriver();
        initialize_68k_emulator(nullptr, false, (uint32_t *)SYN68K_TO_US(0), 0);
        traps::init(false);

        LM(ResErrProc) = 0;
        InitResources();
        ROMlib_InitGDevices();
        LM(TheZone) = LM(ApplZone);

        ROMlib_color_init();
        LM(WindowList) = nullptr;
        LM(MenuList) = nullptr;
        LM(MBDFHndl) = nullptr;
        LM(MBSaveLoc) = nullptr;
        EM_A5 = EM_A7 = ptr_to_longint(LM(MemTop)-4);
        InitGraf((Ptr)&qd.thePort);
        InitFonts();
        InitWindows();
        InitMenus();
    }

    virtual void TearDown() override
    {
        if(!tempDir.empty())
            fs::remove_all(tempDir);
    }
};

TEST(MemoryMgr, NewClearGetSizeDispose)
{
    Ptr p = NewPtrClear(42);

    ASSERT_NE(nullptr, p);
    ASSERT_EQ(0, *p);

    ASSERT_EQ(42, GetPtrSize(p));

    DisposePtr(p);
}

int main(int argc, char **argv)
{
    testing::InitGoogleTest(&argc, argv);

    char thingOnStack;
    testing::AddGlobalTestEnvironment(new ExecutorTestEnvironment(&thingOnStack));

    int result = RUN_ALL_TESTS();
    return result;
}
<|endoftext|>