<commit_before>#ifndef STAN_MATH_REV_FUN_HMM_MARGINAL_LPDF_HPP
#define STAN_MATH_REV_FUN_HMM_MARGINAL_LPDF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/row.hpp>
#include <stan/math/prim/fun/col.hpp>
#include <stan/math/prim/fun/transpose.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/core.hpp>
#include <stan/math/fwd/fun/exp.hpp>
#include <stan/math/fwd/fun/log.hpp>
#include <vector>
#include <iostream>

namespace stan {
namespace math {

/**
 * For a Hidden Markov Model with observation y, hidden state x,
 * and parameters theta, return the log marginal density, log
 * p(y | theta). In this setting, the hidden states are discrete
 * and take values over the finite space {1, ..., K}.
 * The marginal lpdf is obtained via a forward pass, and
 * the derivative is calculated with an adjoint method,
 * see (Betancourt, Margossian, & Leos-Barajas, 2020).
 *
 * @tparam T_omega type of the log likelihood matrix
 * @tparam T_Gamma type of the transition matrix
 * @tparam T_rho type of the initial guess vector
 *
 * @param[in] log_omega log matrix of observational densities.
 *              The (i, j)th entry corresponds to the
 *              density of the ith observation, y_i,
 *              given x_i = j.
 * @param[in] Gamma transition density between hidden states.
 *              The (i, j)th entry is the probability that x_n = j,
 *              given x_{n - 1} = i. The rows of Gamma are simplexes.
 * @param[in] rho initial state
 * @throw `std::domain_error` if Gamma is not square.
 * @throw `std::invalid_argument` if the size of rho is not
 * the number of rows of Gamma.
 * @throw `std::domain_error` if rho is not a simplex.
 * @throw `std::domain_error` if the rows of Gamma are
 * not a simplex.
 * @return log marginal density.
 */
template <typename T_omega, typename T_Gamma, typename T_rho>
inline return_type_t<T_omega, T_Gamma, T_rho> hmm_marginal_lpdf(
    const Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>& log_omegas,
    const Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>& Gamma,
    const Eigen::Matrix<T_rho, Eigen::Dynamic, 1>& rho) {

  using T_partials_return = partials_return_t<T_omega, T_Gamma, T_rho>;
  using T_partial_type
      = real_return_t<partials_type_t<T_omega>, partials_type_t<T_Gamma>,
                      partials_type_t<T_rho> >;

  int n_states = log_omegas.rows();
  int n_transitions = log_omegas.cols() - 1;

  check_square("hmm_marginal_lpdf", "Gamma", Gamma);
  check_consistent_size("hmm_marginal_lpdf", "Gamma", row(Gamma, 1), n_states);
  check_consistent_size("hmm_marginal_lpdf", "rho", rho, n_states);
  check_simplex("hmm_marginal_lpdf", "rho", rho);
  for (int i = 0; i < Gamma.rows(); ++i) {
    check_simplex("hmm_marginal_lpdf", "Gamma[i, ]", row(Gamma, i + 1));
  }

  operands_and_partials<Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>,
                        Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>,
                        Eigen::Matrix<T_rho, Eigen::Dynamic, 1> >
      ops_partials(log_omegas, Gamma, rho);

  Eigen::Matrix<T_partials_return, Eigen::Dynamic, Eigen::Dynamic> alphas(
      n_states, n_transitions + 1);
  Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> alpha_log_norms(n_transitions
                                                                   + 1);
  Eigen::Matrix<T_partials_return, Eigen::Dynamic, Eigen::Dynamic>
      omegas;
  auto Gamma_val = value_of(Gamma);

  // Eigen::MatrixXd alphas(n_states, n_transitions + 1);
  // Eigen::VectorXd alpha_log_norms(n_transitions + 1);
  // Eigen::MatrixXd omegas;
  // Eigen::MatrixXd Gamma_val = value_of(Gamma);
  /**
   * For a Hidden Markov Model with observation y, hidden state x,
   * and parameters theta, return the log marginal density, log
   * p(y | theta). In this setting, the hidden states are discrete
   * and take values over the finite space {1, ..., K}.
   * The marginal lpdf is obtained via a forward pass.
   * The [in, out] argument are saved so that we can use them when
   * calculating the derivatives.
   *
   * @param[in] log_omega log matrix of observational densities.
   *              The (i, j)th entry corresponds to the
   *              density of the ith observation, y_i,
   *              given x_i = j.qq
   * @param[in] Gamma transition density between hidden states.
   *              The (i, j)th entry is the probability that x_n = j,
   *              given x_{n - 1} = i. The rows of Gamma are simplexes.
   * @param[in] rho initial state
   * @param[in, out] alphas unnormalized partial marginal density.
   *                   The jth column is the joint density over all
   *                   observations y and the hidden state j.
   * @param[in, out] alpha_log_norms max coefficient for column of alpha,
   *                   to be used to normalize alphas.
   * @param[in, out] omegas term-wise exponential of omegas.
   * @return log marginal density.
   */
  {
    auto log_omegas_m = value_of(log_omegas).eval();
    auto rho_val = value_of(rho).eval();
    omegas = log_omegas_m.array().exp();
    int n_states = log_omegas_m.rows();
    int n_transitions = log_omegas_m.cols() - 1;

    alphas.col(0) = omegas.col(0).cwiseProduct(rho_val);

    auto norm = alphas.col(0).maxCoeff();
    alphas.col(0) /= norm;
    alpha_log_norms(0) = log(norm);

    for (int n = 0; n < n_transitions; ++n) {
      alphas.col(n + 1)
          = omegas.col(n + 1).cwiseProduct(Gamma_val.transpose() * alphas.col(n));

      auto norm = alphas.col(n + 1).maxCoeff();
      alphas.col(n + 1) /= norm;
      alpha_log_norms(n + 1) = log(norm) + alpha_log_norms(n);
    }
  }
  T_partials_return log_marginal_density = log(alphas.col(n_transitions).sum()) + alpha_log_norms(n_transitions);

  // Variables required for all three Jacobian-adjoint products.
  auto norm_norm = alpha_log_norms(n_transitions);
  auto unnormed_marginal = alphas.col(n_transitions).sum();

  std::vector<Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> > kappa(
      n_transitions);
  Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> kappa_log_norms(
      n_transitions);
  std::vector<T_partials_return> grad_corr(n_transitions);

  // std::vector<Eigen::VectorXd> kappa(n_transitions);
  // Eigen::VectorXd kappa_log_norms(n_transitions);
  // std::vector<double> grad_corr(n_transitions);

  if (n_transitions > 0) {
    kappa[n_transitions - 1] = Eigen::VectorXd::Ones(n_states);
    kappa_log_norms(n_transitions - 1) = 0;
    grad_corr[n_transitions - 1]
        = exp(alpha_log_norms(n_transitions - 1) - norm_norm);
    // = std::exp(alpha_log_norms(n_transitions - 1) - norm_norm);
  }

  for (int n = n_transitions - 2; n >= 0; --n) {
    kappa[n] = Gamma_val * (omegas.col(n + 2).cwiseProduct(kappa[n + 1]));

    auto norm = kappa[n].maxCoeff();
    // double norm = kappa[n].maxCoeff();
    kappa[n] /= norm;
    kappa_log_norms(n) = log(norm) + kappa_log_norms(n + 1);
    grad_corr[n] = exp(alpha_log_norms(n) + kappa_log_norms(n) - norm_norm);
    // kappa_log_norms(n) = std::log(norm) + kappa_log_norms(n + 1);
    // grad_corr[n]
    //     = std::exp(alpha_log_norms(n) + kappa_log_norms(n) - norm_norm);
  }

  if (!is_constant_all<T_Gamma>::value) {
    Eigen::Matrix<T_partials_return, Eigen::Dynamic, Eigen::Dynamic> Gamma_jacad
        = Eigen::MatrixXd::Zero(n_states, n_states);
    // Eigen::MatrixXd Gamma_jacad = Eigen::MatrixXd::Zero(n_states, n_states);

    for (int n = n_transitions - 1; n >= 0; --n) {
      Gamma_jacad += (grad_corr[n] * kappa[n].cwiseProduct(omegas.col(n + 1))
                      * alphas.col(n).transpose())
                         .transpose();
    }

    Gamma_jacad /= unnormed_marginal;
    ops_partials.edge2_.partials_ = Gamma_jacad;
  }

  bool sensitivities_for_omega_or_rho
      = (!is_constant_all<T_omega>::value) || (!is_constant_all<T_rho>::value);

  // boundary terms
  if (sensitivities_for_omega_or_rho) {
    // Eigen::MatrixXd log_omega_jacad
    Eigen::Matrix<T_partials_return, Eigen::Dynamic, Eigen::Dynamic>
        log_omega_jacad = Eigen::MatrixXd::Zero(n_states, n_transitions + 1);

    if (!is_constant_all<T_omega>::value) {
      for (int n = n_transitions - 1; n >= 0; --n)
        log_omega_jacad.col(n + 1)
            = grad_corr[n]
              * kappa[n].cwiseProduct(Gamma_val.transpose() * alphas.col(n));
    }

    // Boundary terms
    if (n_transitions == 0) {
      if (!is_constant_all<T_omega>::value) {
        log_omega_jacad.col(0) = omegas.col(0).cwiseProduct(value_of(rho))
                                 / exp(value_of(log_marginal_density));
        ops_partials.edge1_.partials_ = log_omega_jacad;
      }

      if (!is_constant_all<T_rho>::value) {
        ops_partials.edge3_.partials_
            = omegas.col(0) / exp(value_of(log_marginal_density));
      }
    } else {
      auto grad_corr_boundary = exp(kappa_log_norms(0) - norm_norm);
      Eigen::Matrix<T_partial_type, Eigen::Dynamic, 1> C
          = Gamma_val * omegas.col(1).cwiseProduct(kappa[0]);
      // double grad_corr_boundary = std::exp(kappa_log_norms(0) - norm_norm);
      // Eigen::VectorXd C = Gamma_val * omegas.col(1).cwiseProduct(kappa[0]);

      if (!is_constant_all<T_omega>::value) {
        log_omega_jacad.col(0)
            = grad_corr_boundary * C.cwiseProduct(value_of(rho));
        ops_partials.edge1_.partials_
            = log_omega_jacad.cwiseProduct(omegas / unnormed_marginal);
      }

      if (!is_constant_all<T_rho>::value) {
        ops_partials.edge3_.partials_ = grad_corr_boundary
                                        * C.cwiseProduct(omegas.col(0))
                                        / unnormed_marginal;
      }
    }
  }

  return ops_partials.build(log_marginal_density);
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>use partial_type instead of full return type<commit_after>#ifndef STAN_MATH_REV_FUN_HMM_MARGINAL_LPDF_HPP
#define STAN_MATH_REV_FUN_HMM_MARGINAL_LPDF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/row.hpp>
#include <stan/math/prim/fun/col.hpp>
#include <stan/math/prim/fun/transpose.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/core.hpp>
#include <stan/math/fwd/fun/exp.hpp>
#include <stan/math/fwd/fun/log.hpp>
#include <vector>
#include <iostream>

namespace stan {
namespace math {

/**
 * For a Hidden Markov Model with observation y, hidden state x,
 * and parameters theta, return the log marginal density, log
 * p(y | theta). In this setting, the hidden states are discrete
 * and take values over the finite space {1, ..., K}.
 * The marginal lpdf is obtained via a forward pass, and
 * the derivative is calculated with an adjoint method,
 * see (Betancourt, Margossian, & Leos-Barajas, 2020).
 *
 * @tparam T_omega type of the log likelihood matrix
 * @tparam T_Gamma type of the transition matrix
 * @tparam T_rho type of the initial guess vector
 *
 * @param[in] log_omega log matrix of observational densities.
 *              The (i, j)th entry corresponds to the
 *              density of the ith observation, y_i,
 *              given x_i = j.
 * @param[in] Gamma transition density between hidden states.
 *              The (i, j)th entry is the probability that x_n = j,
 *              given x_{n - 1} = i. The rows of Gamma are simplexes.
 * @param[in] rho initial state
 * @throw `std::domain_error` if Gamma is not square.
 * @throw `std::invalid_argument` if the size of rho is not
 * the number of rows of Gamma.
 * @throw `std::domain_error` if rho is not a simplex.
 * @throw `std::domain_error` if the rows of Gamma are
 * not a simplex.
 * @return log marginal density.
 */
template <typename T_omega, typename T_Gamma, typename T_rho>
inline return_type_t<T_omega, T_Gamma, T_rho> hmm_marginal_lpdf(
    const Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>& log_omegas,
    const Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>& Gamma,
    const Eigen::Matrix<T_rho, Eigen::Dynamic, 1>& rho) {
  using T_partials_return = partials_return_t<T_omega, T_Gamma, T_rho>;
  using T_partial_type
      = return_type_t<partials_type_t<T_omega>, partials_type_t<T_Gamma>,
                      partials_type_t<T_rho> >;
  using eig_matrix_partial
      = Eigen::Matrix<T_partial_type, Eigen::Dynamic, Eigen::Dynamic>;
  using eig_vector_partial = Eigen::Matrix<T_partial_type, Eigen::Dynamic, 1>;
  int n_states = log_omegas.rows();
  int n_transitions = log_omegas.cols() - 1;

  check_square("hmm_marginal_lpdf", "Gamma", Gamma);
  check_consistent_size("hmm_marginal_lpdf", "Gamma", row(Gamma, 1), n_states);
  check_consistent_size("hmm_marginal_lpdf", "rho", rho, n_states);
  check_simplex("hmm_marginal_lpdf", "rho", rho);
  for (int i = 0; i < Gamma.rows(); ++i) {
    check_simplex("hmm_marginal_lpdf", "Gamma[i, ]", row(Gamma, i + 1));
  }

  operands_and_partials<Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>,
                        Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>,
                        Eigen::Matrix<T_rho, Eigen::Dynamic, 1> >
      ops_partials(log_omegas, Gamma, rho);

  eig_matrix_partial alphas(n_states, n_transitions + 1);
  eig_vector_partial alpha_log_norms(n_transitions + 1);
  eig_matrix_partial omegas;
  auto Gamma_val = value_of(Gamma).eval();

  /**
   * For a Hidden Markov Model with observation y, hidden state x,
   * and parameters theta, return the log marginal density, log
   * p(y | theta). In this setting, the hidden states are discrete
   * and take values over the finite space {1, ..., K}.
   * The marginal lpdf is obtained via a forward pass.
   * The [in, out] argument are saved so that we can use them when
   * calculating the derivatives.
   *
   * @param[in] log_omega log matrix of observational densities.
   *              The (i, j)th entry corresponds to the
   *              density of the ith observation, y_i,
   *              given x_i = j.qq
   * @param[in] Gamma transition density between hidden states.
   *              The (i, j)th entry is the probability that x_n = j,
   *              given x_{n - 1} = i. The rows of Gamma are simplexes.
   * @param[in] rho initial state
   * @param[in, out] alphas unnormalized partial marginal density.
   *                   The jth column is the joint density over all
   *                   observations y and the hidden state j.
   * @param[in, out] alpha_log_norms max coefficient for column of alpha,
   *                   to be used to normalize alphas.
   * @param[in, out] omegas term-wise exponential of omegas.
   * @return log marginal density.
   */
  {
    const auto log_omegas_val = value_of(log_omegas).eval();
    const auto rho_val = value_of(rho).eval();
    omegas = log_omegas_val.array().exp();
    const int n_states = log_omegas_val.rows();
    const int n_transitions = log_omegas_val.cols() - 1;

    alphas.col(0) = omegas.col(0).cwiseProduct(rho_val);

    const auto norm = alphas.col(0).maxCoeff();
    alphas.col(0) /= norm;
    alpha_log_norms(0) = log(norm);

    for (int n = 0; n < n_transitions; ++n) {
      alphas.col(n + 1) = omegas.col(n + 1).cwiseProduct(Gamma_val.transpose()
                                                         * alphas.col(n));

      const auto col_norm = alphas.col(n + 1).maxCoeff();
      alphas.col(n + 1) /= col_norm;
      alpha_log_norms(n + 1) = log(col_norm) + alpha_log_norms(n);
    }
  }
  const T_partial_type log_marginal_density
      = log(alphas.col(n_transitions).sum()) + alpha_log_norms(n_transitions);

  // Variables required for all three Jacobian-adjoint products.
  const auto norm_norm = alpha_log_norms(n_transitions);
  const auto unnormed_marginal = alphas.col(n_transitions).sum();

  std::vector<eig_vector_partial> kappa(n_transitions, eig_vector_partial::Ones(n_states));
  eig_vector_partial kappa_log_norms = eig_vector_partial::Zero(n_transitions);
  std::vector<T_partial_type> grad_corr(n_transitions);

  if (n_transitions > 0) {
    grad_corr[n_transitions - 1]
        = exp(alpha_log_norms(n_transitions - 1) - norm_norm);
  }

  for (int n = n_transitions - 2; n >= 0; --n) {
    kappa[n] = Gamma_val * (omegas.col(n + 2).cwiseProduct(kappa[n + 1]));

    const auto norm = kappa[n].maxCoeff();
    kappa[n] /= norm;
    kappa_log_norms[n] = log(norm) + kappa_log_norms[n + 1];
    grad_corr[n] = exp(alpha_log_norms[n] + kappa_log_norms[n] - norm_norm);
  }

  if (!is_constant_all<T_Gamma>::value) {
    eig_matrix_partial Gamma_jacad
        = eig_matrix_partial::Zero(n_states, n_states);

    for (int n = n_transitions - 1; n >= 0; --n) {
      Gamma_jacad += (grad_corr[n] * kappa[n].cwiseProduct(omegas.col(n + 1))
                      * alphas.col(n).transpose())
                         .transpose();
    }

    Gamma_jacad /= unnormed_marginal;
    ops_partials.edge2_.partials_ = Gamma_jacad;
  }

  const bool sensitivities_for_omega_or_rho
      = (!is_constant_all<T_omega>::value) || (!is_constant_all<T_rho>::value);

  // boundary terms
  if (sensitivities_for_omega_or_rho) {
    eig_matrix_partial log_omega_jacad
        = eig_matrix_partial::Zero(n_states, n_transitions + 1);

    if (!is_constant_all<T_omega>::value) {
      for (int n = n_transitions - 1; n >= 0; --n)
        log_omega_jacad.col(n + 1)
            = grad_corr[n]
              * kappa[n].cwiseProduct(Gamma_val.transpose() * alphas.col(n));
    }

    // Boundary terms
    if (n_transitions == 0) {
      if (!is_constant_all<T_omega>::value) {
        log_omega_jacad.col(0) = omegas.col(0).cwiseProduct(value_of(rho))
                                 / exp(value_of(log_marginal_density));
        ops_partials.edge1_.partials_ = log_omega_jacad;
      }

      if (!is_constant_all<T_rho>::value) {
        ops_partials.edge3_.partials_
            = omegas.col(0) / exp(value_of(log_marginal_density));
      }
    } else {
      const auto grad_corr_boundary = exp(kappa_log_norms(0) - norm_norm);
      eig_vector_partial C = Gamma_val * omegas.col(1).cwiseProduct(kappa[0]);

      if (!is_constant_all<T_omega>::value) {
        log_omega_jacad.col(0)
            = grad_corr_boundary * C.cwiseProduct(value_of(rho));
        ops_partials.edge1_.partials_
            = log_omega_jacad.cwiseProduct(omegas / unnormed_marginal);
      }

      if (!is_constant_all<T_rho>::value) {
        ops_partials.edge3_.partials_ = grad_corr_boundary
                                        * C.cwiseProduct(omegas.col(0))
                                        / unnormed_marginal;
      }
    }
  }

  return ops_partials.build(log_marginal_density);
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>/* This file is part of the UniSet project
 * Copyright (c) 2009 Free Software Foundation, Inc.
 * Copyright (c) 2009 Ivan Donchevskiy
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
// --------------------------------------------------------------------------
/*! \file
 *  \author Ivan Donchevskiy
 *  \date   $Date: 2009/07/15 15:55:00 $
 *  \version $Id: Jrn.h,v 1.0 2009/07/15 15:55:00vpashka Exp $
 */
// --------------------------------------------------------------------------

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "Storages.h"

TableStorage::TableStorage(const char* name, int inf_sz, int sz, int seek)
{
	file = fopen(name, "r+");
	inf_size=inf_sz;
	int l=-1,r=size,mid;
	size=sz/(sizeof(TableStorageElem)+inf_size);
	TableStorageElem *t = (TableStorageElem*)malloc(sizeof(TableStorageElem)+inf_size);
	if(file==NULL)
	{
		file = fopen(name,"w");
		for(int i=0;i<size;i++) fwrite(t,(sizeof(TableStorageElem)+inf_size),1,file);
		fclose(file);
		file = fopen(name,"r+");
		seekpos=0;
		head=-1;
	}
	else
	{
		seekpos=seek;
		fseek(file,seekpos,0);
		fread(t,(sizeof(TableStorageElem)+inf_size),1,file);
		if(t->status==0)
		{
			head=-1;
		}
		else if((t->status==1)||(t->status==6))
		{
			head=0;
		}
		else if((t->status==2)||(t->status==3))
		{
			while((t->status!=1)&&(t->status!=6)&&(r - l > 1))
			{
				mid = (l+r)/2;
				fseek(file,seekpos+mid*(sizeof(TableStorageElem)+inf_size),0);
				fread(t,(sizeof(TableStorageElem)+inf_size),1,file);
				if((t->status==2)||(t->status==3))
					l = mid;
				else if((t->status==4)||(t->status==5))
					r = mid;
				else
				{
					r=mid;
					break;
				}
			}
			if(r<size)
				head=r;
			else head=size-1;
		}
		else
		{
			while((t->status!=1)&&(t->status!=6)&&(r - l > 1))
			{
				mid = (l+r)/2;
				fseek(file,seekpos+mid*(sizeof(TableStorageElem)+inf_size),0);
				fread(t,(sizeof(TableStorageElem)+inf_size),1,file);
				if((t->status==2)||(t->status==3))
					r = mid;
				else if((t->status==4)||(t->status==5))
					l = mid;
				else
				{
					r=mid;
					break;
				}
			}
			if(r<size)
				head=r;
			else head=size-1;
		}
	}
}

TableStorage::~TableStorage()
{
	fclose(file);
}

int TableStorage::AddRow(char* key, char* value)
{
	TableStorageElem *tbl = (TableStorageElem*)malloc(sizeof(TableStorageElem)+inf_size);
	int i,k,j,st;
	if(file!=NULL)
	{
		if(head==-1)
		{
			fseek(file,seekpos,0);
			tbl->status=1;
			strcpy(tbl->key,key);
			for(k=0;k<inf_size;k++)
				*((char*)(tbl)+sizeof(TableStorageElem)+k)=*(value+k);
			fwrite(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
			head=0;
			return 0;
		}
		fseek(file,seekpos+head*(sizeof(TableStorageElem)+inf_size),0);
		j=head;
		for(i=0;i<size;i++)
		{
			fread(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
			if(tbl->status==0) break;
			if(!strcmp(tbl->key,key)&&((tbl->status==2)||(tbl->status==4)||(tbl->status==1)))
			{
				for(k=0;k<inf_size;k++)
					*((char*)(tbl)+sizeof(TableStorageElem)+k)=*(value+k);
				fseek(file,seekpos+i*(sizeof(TableStorageElem)+inf_size),0);
				fwrite(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
				return 0;
			}
			j++;
			if(j>=size)
			{
				j=0;
				fseek(file,seekpos,0);
			}
		}
		fseek(file,seekpos+j*(sizeof(TableStorageElem)+inf_size),0);
		if(j==head)
		{
			if((tbl->status==2)||(tbl->status==3)) st=2;
			else st=4;

			if(j==0)
				if(st==2) st=4;
				else st=2;

			tbl->status=st;
			strcpy(tbl->key,key);
			for(k=0;k<inf_size;k++)
				*((char*)(tbl)+sizeof(TableStorageElem)+k)=*(value+k);
			fwrite(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
			j++;
			if(j>=size)
			{
				j=0;
				fseek(file,seekpos,0);
			}

			fread(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
			if((tbl->status==3)||(tbl->status==5)) tbl->status=6;
			else tbl->status=1;
			fseek(file,seekpos+j*(sizeof(TableStorageElem)+inf_size),0);
			fwrite(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
			head++;
			if(head>=size) head=0;
			return 0;
		}

		/*for(i=0;i<size;i++)
		{
			fread(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
			if(tbl->key[0]==0)
			{
				strcpy(tbl->key,key);
				for(k=0;k<inf_size;k++)
					*((char*)(tbl)+sizeof(TableStorageElem)+k)=*(value+k);
				fseek(file,seekpos+i*(sizeof(TableStorageElem)+inf_size),0);
				fwrite(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
				return 0;
			}
		}*/
	}
	return 1;
}

int TableStorage::DelRow(char* key)
{
	TableStorageElem *tbl = (TableStorageElem*)malloc(sizeof(TableStorageElem)+inf_size);
	int i,j;
	if(file!=NULL)
	{
		fseek(file,seekpos+head*(sizeof(TableStorageElem)+inf_size),0);
		j=head;
		for(i=0;i<size;i++)
		{
			fread(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
			if(!strcmp(tbl->key,key)&&((tbl->status==2)||(tbl->status==4)||(tbl->status==1)))
			{
				//tbl->key[0]=0;
				if(tbl->status==1) tbl->status=6;
				else if(tbl->status==2) tbl->status=3;
				else tbl->status=5;
				fseek(file,seekpos+j*(sizeof(TableStorageElem)+inf_size),0);
				fwrite(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
				return 0;
			}
			j++;
			if(j>=size)
			{
				j=0;
				fseek(file,seekpos,0);
			}
		}
	}
	return 1;
}

char* TableStorage::FindKeyValue(char* key, char* val)
{
	TableStorageElem *tbl = (TableStorageElem*)malloc(sizeof(TableStorageElem)+inf_size);
	int i,k;
	if(file!=NULL)
	{
		fseek(file,seekpos,0);
		for(i=0;i<size;i++)
		{
			fread(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
			if(!strcmp(tbl->key,key)&&((tbl->status==2)||(tbl->status==4)||(tbl->status==1)))
			{
				for(k=0;k<inf_size;k++)
					*(val+k)=*((char*)(tbl)+sizeof(TableStorageElem)+k);
				return val;
			}
		}
	}
	return 0;
}

<commit_msg>TableStorage: fix warning<commit_after>/* This file is part of the UniSet project
 * Copyright (c) 2009 Free Software Foundation, Inc.
 * Copyright (c) 2009 Ivan Donchevskiy
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
// --------------------------------------------------------------------------
/*! \file
 *  \author Ivan Donchevskiy
 *  \date   $Date: 2009/07/15 15:55:00 $
 *  \version $Id: Jrn.h,v 1.0 2009/07/15 15:55:00vpashka Exp $
 */
// --------------------------------------------------------------------------

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "Storages.h"

TableStorage::TableStorage(const char* name, int inf_sz, int sz, int seek)
{
	file = fopen(name, "r+");
	inf_size=inf_sz;
	int l=-1,r=size,mid;
	size=sz/(sizeof(TableStorageElem)+inf_size);
	TableStorageElem *t = (TableStorageElem*)malloc(sizeof(TableStorageElem)+inf_size);
	if(file==NULL)
	{
		file = fopen(name,"w");
		for(int i=0;i<size;i++) fwrite(t,(sizeof(TableStorageElem)+inf_size),1,file);
		fclose(file);
		file = fopen(name,"r+");
		seekpos=0;
		head=-1;
	}
	else
	{
		seekpos=seek;
		fseek(file,seekpos,0);
		fread(t,(sizeof(TableStorageElem)+inf_size),1,file);
		if(t->status==0)
		{
			head=-1;
		}
		else if((t->status==1)||(t->status==6))
		{
			head=0;
		}
		else if((t->status==2)||(t->status==3))
		{
			while((t->status!=1)&&(t->status!=6)&&(r - l > 1))
			{
				mid = (l+r)/2;
				fseek(file,seekpos+mid*(sizeof(TableStorageElem)+inf_size),0);
				fread(t,(sizeof(TableStorageElem)+inf_size),1,file);
				if((t->status==2)||(t->status==3))
					l = mid;
				else if((t->status==4)||(t->status==5))
					r = mid;
				else
				{
					r=mid;
					break;
				}
			}
			if(r<size)
				head=r;
			else head=size-1;
		}
		else
		{
			while((t->status!=1)&&(t->status!=6)&&(r - l > 1))
			{
				mid = (l+r)/2;
				fseek(file,seekpos+mid*(sizeof(TableStorageElem)+inf_size),0);
				fread(t,(sizeof(TableStorageElem)+inf_size),1,file);
				if((t->status==2)||(t->status==3))
					r = mid;
				else if((t->status==4)||(t->status==5))
					l = mid;
				else
				{
					r=mid;
					break;
				}
			}
			if(r<size)
				head=r;
			else head=size-1;
		}
	}
}

TableStorage::~TableStorage()
{
	fclose(file);
}

int TableStorage::AddRow(char* key, char* value)
{
	TableStorageElem *tbl = (TableStorageElem*)malloc(sizeof(TableStorageElem)+inf_size);
	int i,k,j;
	if(file!=NULL)
	{
		if(head==-1)
		{
			fseek(file,seekpos,0);
			tbl->status=1;
			strcpy(tbl->key,key);
			for(k=0;k<inf_size;k++)
				*((char*)(tbl)+sizeof(TableStorageElem)+k)=*(value+k);
			fwrite(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
			head=0;
			return 0;
		}
		fseek(file,seekpos+head*(sizeof(TableStorageElem)+inf_size),0);
		j=head;
		for(i=0;i<size;i++)
		{
			fread(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
			if(tbl->status==0) break;
			if(!strcmp(tbl->key,key)&&((tbl->status==2)||(tbl->status==4)||(tbl->status==1)))
			{
				for(k=0;k<inf_size;k++)
					*((char*)(tbl)+sizeof(TableStorageElem)+k)=*(value+k);
				fseek(file,seekpos+i*(sizeof(TableStorageElem)+inf_size),0);
				fwrite(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
				return 0;
			}
			j++;
			if(j>=size)
			{
				j=0;
				fseek(file,seekpos,0);
			}
		}
		fseek(file,seekpos+j*(sizeof(TableStorageElem)+inf_size),0);
		if(j==head)
		{
			if((tbl->status==2)||(tbl->status==3))
				tbl->status=2;
			else
				tbl->status=4;

			if(j==0)
			{
				if(tbl->status==2)
					tbl->status=4;
				else
					tbl->status=2;
			}

			strcpy(tbl->key,key);
			for(k=0;k<inf_size;k++)
				*((char*)(tbl)+sizeof(TableStorageElem)+k)=*(value+k);
			fwrite(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
			j++;
			if(j>=size)
			{
				j=0;
				fseek(file,seekpos,0);
			}

			fread(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
			if((tbl->status==3)||(tbl->status==5)) tbl->status=6;
			else tbl->status=1;
			fseek(file,seekpos+j*(sizeof(TableStorageElem)+inf_size),0);
			fwrite(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
			head++;
			if(head>=size) head=0;
			return 0;
		}

		/*for(i=0;i<size;i++)
		{
			fread(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
			if(tbl->key[0]==0)
			{
				strcpy(tbl->key,key);
				for(k=0;k<inf_size;k++)
					*((char*)(tbl)+sizeof(TableStorageElem)+k)=*(value+k);
				fseek(file,seekpos+i*(sizeof(TableStorageElem)+inf_size),0);
				fwrite(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
				return 0;
			}
		}*/
	}
	return 1;
}

int TableStorage::DelRow(char* key)
{
	TableStorageElem *tbl = (TableStorageElem*)malloc(sizeof(TableStorageElem)+inf_size);
	int i,j;
	if(file!=NULL)
	{
		fseek(file,seekpos+head*(sizeof(TableStorageElem)+inf_size),0);
		j=head;
		for(i=0;i<size;i++)
		{
			fread(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
			if(!strcmp(tbl->key,key)&&((tbl->status==2)||(tbl->status==4)||(tbl->status==1)))
			{
				//tbl->key[0]=0;
				if(tbl->status==1) tbl->status=6;
				else if(tbl->status==2) tbl->status=3;
				else tbl->status=5;
				fseek(file,seekpos+j*(sizeof(TableStorageElem)+inf_size),0);
				fwrite(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
				return 0;
			}
			j++;
			if(j>=size)
			{
				j=0;
				fseek(file,seekpos,0);
			}
		}
	}
	return 1;
}

char* TableStorage::FindKeyValue(char* key, char* val)
{
	TableStorageElem *tbl = (TableStorageElem*)malloc(sizeof(TableStorageElem)+inf_size);
	int i,k;
	if(file!=NULL)
	{
		fseek(file,seekpos,0);
		for(i=0;i<size;i++)
		{
			fread(tbl,(sizeof(TableStorageElem)+inf_size),1,file);
			if(!strcmp(tbl->key,key)&&((tbl->status==2)||(tbl->status==4)||(tbl->status==1)))
			{
				for(k=0;k<inf_size;k++)
					*(val+k)=*((char*)(tbl)+sizeof(TableStorageElem)+k);
				return val;
			}
		}
	}
	return 0;
}

<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2002 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/>.
 */
#if !defined(XALAN_KEYDECLARATION_HEADER_GUARD)
#define XALAN_KEYDECLARATION_HEADER_GUARD

// Base include file.  Must be first.
#include "XSLTDefinitions.hpp"

XALAN_CPP_NAMESPACE_BEGIN

class XPath;

/**
 * Holds the attribute declarations for the "xsl:key" element.
 */
class KeyDeclaration
{
public:

	/**
	 * Construct an object containing attributes of an "xsl:key" element
	 *
	 * @param qname        name of element
	 * @param matchPattern XPath for "match" attribute
	 * @paramuse           XPath for "use" attribute
	 */
	KeyDeclaration(
			const XalanQName&	qname,
			const XPath&		matchPattern,
			const XPath&		use) :
		m_qname(&qname),
		m_match(&matchPattern),
		m_use(&use)
	{
	}

	explicit
	KeyDeclaration() :
		m_qname(0),
		m_match(0),
		m_use(0)
	{
	}

	KeyDeclaration(const KeyDeclaration&	theSource) :
		m_qname(theSource.m_qname),
		m_match(theSource.m_match),
		m_use(theSource.m_use)
	{
	}

	~KeyDeclaration()
	{
	}

	/**
	 * Retrieves name of element
	 *
	 * @return name string
	 */
	const XalanQName*
	getQName() const
	{
		return m_qname;
	}

	/**
	 * Retrieves "use" XPath
	 *
	 * @return XPath for "use" attribute
	 */
	const XPath*
	getUse() const
	{
		return m_use;
	}

	/**
	 * Retrieves "match" XPath
	 *
	 * @return XPath for "match" attribute
	 */
	const XPath*
	getMatchPattern() const
	{
		return m_match;
	}

private:

	const XalanQName*	m_qname;

	const XPath*		m_match;

	const XPath*		m_use;
};

XALAN_CPP_NAMESPACE_END

#endif	// XALAN_KEYDECLARATION_HEADER_GUARD
<commit_msg>Added information from Locator.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2002 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/>.
 */
#if !defined(XALAN_KEYDECLARATION_HEADER_GUARD)
#define XALAN_KEYDECLARATION_HEADER_GUARD

// Base include file.  Must be first.
#include "XSLTDefinitions.hpp"

XALAN_CPP_NAMESPACE_BEGIN

#include <PlatformSupport/XalanLocator.hpp>

class XPath;

/**
 * Holds the attribute declarations for the "xsl:key" element.
 */
class KeyDeclaration
{
public:

	/**
	 * Construct an object containing attributes of an "xsl:key" element
	 *
	 * @param qname name of element
	 * @param matchPattern XPath for "match" attribute
	 * @param use XPath for "use" attribute
	 */
	KeyDeclaration(
			const XalanQName&			qname,
			const XPath&				matchPattern,
			const XPath&				use,
			const XalanDOMString&		uri,
			XalanLocator::size_type		lineNumber,
			XalanLocator::size_type		columnNumber) :
		m_qname(&qname),
		m_match(&matchPattern),
		m_use(&use),
		m_uri(&uri),
		m_lineNumber(lineNumber),
		m_columnNumber(columnNumber)
	{
	}

	explicit
	KeyDeclaration() :
		m_qname(0),
		m_match(0),
		m_use(0),
		m_uri(0),
		m_lineNumber(0),
		m_columnNumber(0)
	{
	}

	KeyDeclaration(const KeyDeclaration&	theSource) :
		m_qname(theSource.m_qname),
		m_match(theSource.m_match),
		m_use(theSource.m_use)
	{
	}

	~KeyDeclaration()
	{
	}

	/**
	 * Retrieves name of element
	 *
	 * @return name string
	 */
	const XalanQName*
	getQName() const
	{
		return m_qname;
	}

	/**
	 * Retrieves "use" XPath
	 *
	 * @return XPath for "use" attribute
	 */
	const XPath*
	getUse() const
	{
		return m_use;
	}

	/**
	 * Retrieves "match" XPath
	 *
	 * @return XPath for "match" attribute
	 */
	const XPath*
	getMatchPattern() const
	{
		return m_match;
	}

	/**
	 * Retrieves the URI.
	 *
	 * @return A pointer to a URI string.
	 */
	const XalanDOMString*
	getURI() const
	{
		return m_uri;
	}

	/**
	 * Retrieves the line number where the xsl:key element occurred.
	 *
	 * @return The line number
	 */
	XalanLocator::size_type
	getLineNumber() const
	{
		return m_lineNumber;
	}

	/**
	 * Retrieves the column number where the xsl:key element occurred.
	 *
	 * @return The column number
	 */
	XalanLocator::size_type
	getColumnNumber() const
	{
		return m_columnNumber;
	}

private:

	const XalanQName*			m_qname;

	const XPath*				m_match;

	const XPath*				m_use;

	const XalanDOMString*		m_uri;

	XalanLocator::size_type		m_lineNumber;

	XalanLocator::size_type		m_columnNumber;
};

XALAN_CPP_NAMESPACE_END

#endif	// XALAN_KEYDECLARATION_HEADER_GUARD
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 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/>.
 */
#if !defined(XALAN_STYLESHEETROOT_HEADER_GUARD)
#define XALAN_STYLESHEETROOT_HEADER_GUARD

// Base include file.  Must be first.
#include "XSLTDefinitions.hpp"

#include "Stylesheet.hpp"

#include <XalanDOM/XalanDOMString.hpp>

#include <PlatformSupport/FormatterListener.hpp>

class StylesheetConstructionContext;
class XMLURL;
class XSLTResultTarget;

/**
 * This acts as the stylesheet root of the stylesheet
 * tree, and holds values that are shared by all
 * stylesheets in the tree.
 */
class XALAN_XSLT_EXPORT StylesheetRoot : public Stylesheet
{
public:

	/**
	 * Construct a Stylesheet from a Document.
	 *
	 * @param baseIdentifier document identifier
	 * @param constructionContext context for construction of object
	 */
	StylesheetRoot(
        const XalanDOMString&			baseIdentifier,
		StylesheetConstructionContext&	constructionContext);

	virtual
	~StylesheetRoot();

	/**
	 * Transform the source tree to the output in the given result tree target.
	 *
	 * @param inputSource  The input source tree
	 * @param outputTarget The output source tree
	 * @param constructionContext context for construction of object
	 */
	void
	process(
			XalanNode*						sourceTree,
			XSLTResultTarget&				outputTarget,
			StylesheetExecutionContext&		executionContext) const;

	/**
	 * Have the stylesheet create the appropriate FormatterListener,
	 * based on the XSLTResultTarget provided.  setupFormatterListener
	 * also calls setFormatterListener() on the execution context
	 * instance.  setupFormatterListener() is done automatically by
	 * process(), but this is provided as an escape, to allow for
	 * changing the FormatterListener on-the-fly.
	 *
	 * @param outputTarget The output source tree
	 * @param constructionContext context for construction of object
	 * @return a pointer to the new FormatterListener instance.
	 */
	FormatterListener*
	setupFormatterListener(
			XSLTResultTarget&				outputTarget,
			StylesheetExecutionContext&		executionContext) const;

	/**
	 * Return the output method that was specified in the stylesheet.
	 * The returned value is one of FormatterLister::eFormat values.
	 *
	 * @return value of output method
	 */
	FormatterListener::eFormat
	getOutputMethod() const
	{
		return m_outputMethod;
	}

	bool
	isOutputMethodSet() const
	{
		return getOutputMethod() == FormatterListener::OUTPUT_METHOD_NONE ? false : true;
	}

	/**
	 * Get the output version string that was specified in the
	 * xsl:output element
	 *
	 * @return output version string
	 */
	XalanDOMString
	getOutputVersion() const
	{
		return m_version;
	}

	/**
	 * Determine if output indenting was specified in the
	 * xsl:output element
	 *
	 * @return true to indent
	 */
	bool
	getOutputIndent() const
	{
		return m_indentResult;
	}

	/**
	 * Get the output encoding string that was specified in the
	 * xsl:output element
	 *
	 * @return encoding string
	 */
	XalanDOMString
	getOutputEncoding() const
	{
		return m_encoding;
	}

	/**
	 * Get the java output encoding string that was specified in the
	 * xsl:output element
	 *
	 * @return encoding string
	 */
	XalanDOMString
	getJavaOutputEncoding() const;

	/**
	 * Get the media-type string that was specified in the
	 * xsl:output element
	 *
	 * @return media type string
	 */
	XalanDOMString
	getOutputMediaType() const
	{
		return m_mediatype;
	}

	/**
	 * Get the doctype-system-id string that was specified in the
	 * xsl:output element
	 *
	 * @return document type string
	 */
	XalanDOMString
	getOutputDoctypeSystem() const
	{
		return m_doctypeSystem;
	}

	/**
	 * Get the doctype-public-id string that was specified in the
	 * xsl:output element
	 *
	 * @return document type public id string
	 */
	XalanDOMString
	getOutputDoctypePublic() const
	{
		return m_doctypePublic;
	}

	/**
	 * Determine whether to output XML declarations.
	 *
	 * @return true to output declarations
	 */
	bool
	getOmitOutputXMLDecl() const
	{
		return m_omitxmlDecl;
	}

	/**
	 * Get the standalone string that was specified in the
	 * xsl:output element.(either "yes" or "no")
	 *
	 * @return standalone string
	 */
	XalanDOMString
	getOutputStandalone() const
	{
		return m_standalone;
	}

	/**
	 * Get the template representing the default rule for text.
	 *
	 * @return pointer to template rule for text
	 */
	ElemTemplate*
	getDefaultTextRule() const
	{
		return m_defaultTextRule;
	}

	/**
	 * Get the template representing the default rule.
	 *
	 * @return pointer to default template rule
	 */
	ElemTemplate*
	getDefaultRule() const
	{
		return m_defaultRule;
	}

	/**
	 * Get the template representing the default root rule.
	 *
	 * @return pointer to default root template rule
	 */
	ElemTemplate*
	getDefaultRootRule() const
	{
		return m_defaultRootRule;
	}

	/**
	 * Process the "xsl:output" element.
	 *
	 * @param name                name of element
	 * @param atts                attribute list for element
	 * @param constructionContext context for construction of object
	 */
	void
	processOutputSpec(
			const XalanDOMChar*				name,
			const AttributeList&			atts,
			StylesheetConstructionContext&	constructionContext);

	/**
	 * Create the default rule if needed.
	 *
	 * @param constructionContext context for construction of object
	 */
	void
	initDefaultRule(StylesheetConstructionContext&	constructionContext);

	/**
	 * The version tells the version of XML to be used for outputting the result tree,
	 * as specified in xsl:output.
	 */
	XalanDOMString m_version;

	/**
	 * indent-result is by default no, which means an XSL processor must not
	 * change the whitespace on output.
	 */
	bool m_indentResult;

	/**
	 * The encoding attribute specifies the preferred encoding to use
	 * for outputting the result tree.
	 */
	XalanDOMString m_encoding;

	/**
	 * The media-type attribute is applicable for the xml output method.
	 * The default value for the media-type attribute is text/xml.
	 */
	XalanDOMString m_mediatype;

	/**
	 * If the doctype-system-id attribute is specified, the xml output method should
	 * output a document type declaration immediately before the first element.
	 * The name following <!DOCTYPE should be the name of the first element.
	 */
	XalanDOMString m_doctypeSystem;

	/**
	 * If doctype-public-id attribute is also specified, then the xml output
	 * method should output PUBLIC followed by the public identifier and then
	 * the system identifier; otherwise, it should output SYSTEM followed by
	 * the system identifier. The internal subset should be empty. The
	 * doctype-public-id attribute should be ignored unless the doctype-system-id
	 * attribute is specified.
	 */
	XalanDOMString m_doctypePublic;

	/**
	 * Tells whether or not to output an XML declaration.
	 */
	bool m_omitxmlDecl;

	/**
	 * Tells what the xmldecl should specify for the standalone value.
     */
	XalanDOMString m_standalone;

	/**
	 * Retrieve the stack of imported stylesheets.
	 *
	 * @return stack of URIs for stylesheets
	 */
	URLStackType&
	getImportStack()
	{
		return m_importStack;
	}

	/**
	 * Retrieve the stack of imported stylesheets.
	 *
	 * @return const stack of URIs for stylesheets
	 */
	const URLStackType&
	getImportStack() const
	{
		return m_importStack;
	}

	/**
	 * Change the value of the flag for indenting results.
	 *
	 * @param bIndent true to indent results
	 */
	void
	setIndentResult(bool bIndent)
	{
		m_indentResult = bIndent;
	}

	/**
	 * Change the value of the output method, one of the
	 * FormatterListener::eFormat values.
	 *
	 * @param meth new method number
	 */
	void
	setOutputMethod(FormatterListener::eFormat	meth)
	{
		m_outputMethod = meth;
	}

	/**
	 * Retrieve list of CDATA section elements.
	 *
	 * @return vector of elements
	 */
	const QNameVectorType&
	getCDATASectionElems() const
	{
		return m_cdataSectionElems;
	}

	/**
	 * Given a valid element key, return the corresponding node list.
	 *
	 * @param doc			   source document
	 * @param name			   name of the key, which must match the 'name'
	 *						   attribute on xsl:key
	 * @param ref			   value that must match the value found by the
	 *						   'match' attribute on xsl:key
	 * @param resolver		   resolver for namespace resolution
	 * @param nodelist         A node list to contain the nodes found
	 * @param executionContext current execution context
	 */
	void
	getNodeSetByKey(
			XalanNode*						doc,
			const XalanDOMString&			name,
			const XalanDOMString&			ref,
			const PrefixResolver&			resolver,
			MutableNodeRefList&				nodelist,
			StylesheetExecutionContext&		executionContext,
			KeyTablesTableType&				theKeysTable) const;

private:

	/**
	 * The URL that belongs to the result namespace.
	 * @serial
	 */
	XalanDOMString	m_resultNameSpaceURL;

	/**
	 * The output method as specified in xsl:output.
	 */
	FormatterListener::eFormat	m_outputMethod;

	/**
	 * List of qnames that specifies elements that should be formatted
	 * as CDATA.
	 */
	QNameVectorType		m_cdataSectionElems;

	/**
	 * A stack of who's importing who is needed in order to support
	 * "It is an error if a stylesheet directly or indirectly imports
	 * itself. Apart from this, the case where a stylesheet with a
	 * particular URI is imported in multiple places is not treated
	 * specially."
	 */
	URLStackType m_importStack;

	/**
	 * The default template to use for text nodes if we don't find
	 * anything else.  This is initialized in initDefaultRule().
	 * @serial
	 */
	ElemTemplate* m_defaultTextRule;

	/**
	 * The default template to use if we don't find anything
	 * else.  This is initialized in initDefaultRule().
	 * @serial
	 */
	ElemTemplate* m_defaultRule;

	/**
	 * The default template to use for the root if we don't find
	 * anything else.  This is initialized in initDefaultRule().
	 * We kind of need this because the defaultRule isn't good
	 * enough because it doesn't supply a document context.
	 * For now, I default the root document element to "HTML".
	 * Don't know if this is really a good idea or not.
	 * I suspect it is not.
	 * @serial
	 */
	ElemTemplate* m_defaultRootRule;

};

#endif	// XALAN_STYLESHEETROOT_HEADER_GUARD
<commit_msg>Cleanup...<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 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/>.
 */
#if !defined(XALAN_STYLESHEETROOT_HEADER_GUARD)
#define XALAN_STYLESHEETROOT_HEADER_GUARD

// Base include file.  Must be first.
#include "XSLTDefinitions.hpp"

#include "Stylesheet.hpp"

#include <XalanDOM/XalanDOMString.hpp>

#include <PlatformSupport/FormatterListener.hpp>

class StylesheetConstructionContext;
class XMLURL;
class XSLTResultTarget;

/**
 * This acts as the stylesheet root of the stylesheet
 * tree, and holds values that are shared by all
 * stylesheets in the tree.
 */
class XALAN_XSLT_EXPORT StylesheetRoot : public Stylesheet
{
public:

	/**
	 * Construct a Stylesheet from a Document.
	 *
	 * @param baseIdentifier document identifier
	 * @param constructionContext context for construction of object
	 */
	StylesheetRoot(
        const XalanDOMString&			baseIdentifier,
		StylesheetConstructionContext&	constructionContext);

	virtual
	~StylesheetRoot();

	/**
	 * Transform the source tree to the output in the given result tree target.
	 *
	 * @param inputSource  The input source tree
	 * @param outputTarget The output source tree
	 * @param constructionContext context for construction of object
	 */
	void
	process(
			XalanNode*						sourceTree,
			XSLTResultTarget&				outputTarget,
			StylesheetExecutionContext&		executionContext) const;

	/**
	 * Have the stylesheet create the appropriate FormatterListener,
	 * based on the XSLTResultTarget provided.  setupFormatterListener
	 * also calls setFormatterListener() on the execution context
	 * instance.  setupFormatterListener() is done automatically by
	 * process(), but this is provided as an escape, to allow for
	 * changing the FormatterListener on-the-fly.
	 *
	 * @param outputTarget The output source tree
	 * @param constructionContext context for construction of object
	 * @return a pointer to the new FormatterListener instance.
	 */
	FormatterListener*
	setupFormatterListener(
			XSLTResultTarget&				outputTarget,
			StylesheetExecutionContext&		executionContext) const;

	/**
	 * Return the output method that was specified in the stylesheet.
	 * The returned value is one of FormatterLister::eFormat values.
	 *
	 * @return value of output method
	 */
	FormatterListener::eFormat
	getOutputMethod() const
	{
		return m_outputMethod;
	}

	bool
	isOutputMethodSet() const
	{
		return getOutputMethod() == FormatterListener::OUTPUT_METHOD_NONE ? false : true;
	}

	/**
	 * Get the output version string that was specified in the
	 * xsl:output element
	 *
	 * @return output version string
	 */
	XalanDOMString
	getOutputVersion() const
	{
		return m_version;
	}

	/**
	 * Determine if output indenting was specified in the
	 * xsl:output element
	 *
	 * @return true to indent
	 */
	bool
	getOutputIndent() const
	{
		return m_indentResult;
	}

	/**
	 * Get the output encoding string that was specified in the
	 * xsl:output element
	 *
	 * @return encoding string
	 */
	XalanDOMString
	getOutputEncoding() const
	{
		return m_encoding;
	}

	/**
	 * Get the java output encoding string that was specified in the
	 * xsl:output element
	 *
	 * @return encoding string
	 */
	XalanDOMString
	getJavaOutputEncoding() const;

	/**
	 * Get the media-type string that was specified in the
	 * xsl:output element
	 *
	 * @return media type string
	 */
	XalanDOMString
	getOutputMediaType() const
	{
		return m_mediatype;
	}

	/**
	 * Get the doctype-system-id string that was specified in the
	 * xsl:output element
	 *
	 * @return document type string
	 */
	XalanDOMString
	getOutputDoctypeSystem() const
	{
		return m_doctypeSystem;
	}

	/**
	 * Get the doctype-public-id string that was specified in the
	 * xsl:output element
	 *
	 * @return document type public id string
	 */
	XalanDOMString
	getOutputDoctypePublic() const
	{
		return m_doctypePublic;
	}

	/**
	 * Determine whether to output XML declarations.
	 *
	 * @return true to output declarations
	 */
	bool
	getOmitOutputXMLDecl() const
	{
		return m_omitxmlDecl;
	}

	/**
	 * Get the standalone string that was specified in the
	 * xsl:output element.(either "yes" or "no")
	 *
	 * @return standalone string
	 */
	XalanDOMString
	getOutputStandalone() const
	{
		return m_standalone;
	}

	/**
	 * Get the template representing the default rule for text.
	 *
	 * @return pointer to template rule for text
	 */
	ElemTemplate*
	getDefaultTextRule() const
	{
		return m_defaultTextRule;
	}

	/**
	 * Get the template representing the default rule.
	 *
	 * @return pointer to default template rule
	 */
	ElemTemplate*
	getDefaultRule() const
	{
		return m_defaultRule;
	}

	/**
	 * Get the template representing the default root rule.
	 *
	 * @return pointer to default root template rule
	 */
	ElemTemplate*
	getDefaultRootRule() const
	{
		return m_defaultRootRule;
	}

	/**
	 * Process the "xsl:output" element.
	 *
	 * @param name                name of element
	 * @param atts                attribute list for element
	 * @param constructionContext context for construction of object
	 */
	void
	processOutputSpec(
			const XalanDOMChar*				name,
			const AttributeList&			atts,
			StylesheetConstructionContext&	constructionContext);

	/**
	 * Create the default rule if needed.
	 *
	 * @param constructionContext context for construction of object
	 */
	void
	initDefaultRule(StylesheetConstructionContext&	constructionContext);

	/**
	 * The version tells the version of XML to be used for outputting the result tree,
	 * as specified in xsl:output.
	 */
	XalanDOMString	m_version;

	/**
	 * indent-result is by default no, which means an XSL processor must not
	 * change the whitespace on output.
	 */
	bool			m_indentResult;

	/**
	 * The encoding attribute specifies the preferred encoding to use
	 * for outputting the result tree.
	 */
	XalanDOMString	m_encoding;

	/**
	 * The media-type attribute is applicable for the xml output method.
	 * The default value for the media-type attribute is text/xml.
	 */
	XalanDOMString	m_mediatype;

	/**
	 * If the doctype-system-id attribute is specified, the xml output method should
	 * output a document type declaration immediately before the first element.
	 * The name following <!DOCTYPE should be the name of the first element.
	 */
	XalanDOMString	m_doctypeSystem;

	/**
	 * If doctype-public-id attribute is also specified, then the xml output
	 * method should output PUBLIC followed by the public identifier and then
	 * the system identifier; otherwise, it should output SYSTEM followed by
	 * the system identifier. The internal subset should be empty. The
	 * doctype-public-id attribute should be ignored unless the doctype-system-id
	 * attribute is specified.
	 */
	XalanDOMString	m_doctypePublic;

	/**
	 * Tells whether or not to output an XML declaration.
	 */
	bool			m_omitxmlDecl;

	/**
	 * Tells what the xmldecl should specify for the standalone value.
     */
	XalanDOMString	m_standalone;

	/**
	 * Retrieve the stack of imported stylesheets.
	 *
	 * @return stack of URIs for stylesheets
	 */
	URLStackType&
	getImportStack()
	{
		return m_importStack;
	}

	/**
	 * Retrieve the stack of imported stylesheets.
	 *
	 * @return const stack of URIs for stylesheets
	 */
	const URLStackType&
	getImportStack() const
	{
		return m_importStack;
	}

	/**
	 * Change the value of the flag for indenting results.
	 *
	 * @param bIndent true to indent results
	 */
	void
	setIndentResult(bool bIndent)
	{
		m_indentResult = bIndent;
	}

	/**
	 * Change the value of the output method, one of the
	 * FormatterListener::eFormat values.
	 *
	 * @param meth new method number
	 */
	void
	setOutputMethod(FormatterListener::eFormat	meth)
	{
		m_outputMethod = meth;
	}

	/**
	 * Retrieve list of CDATA section elements.
	 *
	 * @return vector of elements
	 */
	const QNameVectorType&
	getCDATASectionElems() const
	{
		return m_cdataSectionElems;
	}

	/**
	 * Given a valid element key, return the corresponding node list.
	 *
	 * @param doc			   source document
	 * @param name			   name of the key, which must match the 'name'
	 *						   attribute on xsl:key
	 * @param ref			   value that must match the value found by the
	 *						   'match' attribute on xsl:key
	 * @param resolver		   resolver for namespace resolution
	 * @param nodelist         A node list to contain the nodes found
	 * @param executionContext current execution context
	 */
	void
	getNodeSetByKey(
			XalanNode*						doc,
			const XalanDOMString&			name,
			const XalanDOMString&			ref,
			const PrefixResolver&			resolver,
			MutableNodeRefList&				nodelist,
			StylesheetExecutionContext&		executionContext,
			KeyTablesTableType&				theKeysTable) const;

private:

	/**
	 * The URL that belongs to the result namespace.
	 * @serial
	 */
	XalanDOMString	m_resultNameSpaceURL;

	/**
	 * The output method as specified in xsl:output.
	 */
	FormatterListener::eFormat	m_outputMethod;

	/**
	 * List of qnames that specifies elements that should be formatted
	 * as CDATA.
	 */
	QNameVectorType		m_cdataSectionElems;

	/**
	 * A stack of who's importing whom is needed in order to detect
	 * a recursive include or import, which is an error.
	 */
	URLStackType	m_importStack;

	/**
	 * The default template to use for text nodes if we don't find
	 * anything else.  This is initialized in initDefaultRule().
	 */
	ElemTemplate*	m_defaultTextRule;

	/**
	 * The default template to use if we don't find anything
	 * else.  This is initialized in initDefaultRule().
	 */
	ElemTemplate*	m_defaultRule;

	/**
	 * The default template to use for the root if we don't find
	 * anything else.  This is initialized in initDefaultRule().
	 */
	ElemTemplate*	m_defaultRootRule;

};

#endif	// XALAN_STYLESHEETROOT_HEADER_GUARD
<|endoftext|>


<commit_before>#include "Stack.h"
#include <catch.hpp>
using namespace std;
SCENARIO("Stack count", "[count]"){
	bool mark=false;
	stack<int> st;
	if ((st.count()==0))
	{
		mark=true;
	}
	st.push(1);
	if ((st.count()==1))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack push", "[push]"){
	bool mark=false;
	stack<int> st;
	st.push(1);
	if ((st.count()==1)&&(st.top()==1))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack pop", "[pop]"){
	bool mark=false;
	stack<int> st;
	st.push(123);
	st.pop();
	if (st.count()==0)
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack top", "[top]"){
	bool mark=false;
	stack<int> st;
	st.push(11);
	st.push(22);
	int v=st.top();
	if (v==22)
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Assign", "[assign]"){
	bool mark=false;
	stack<int> st;
	st.push(10);
	stack<int> st_;
	st_=st;
	std::cout << "st_.count_=" << st_.count() << std::endl;
	std::cout << "st_.top=" << st_.top() << std::endl;
	if ((st_.count()==1) && (st_.top()==10))
	{
		mark=true;
	}
	REQUIRE(mark);
}
/*
SCENARIO("Copy","[copy]"){
	bool mark=false;
	stack<int> st;
	st.push(10);
	stack<int> st_=st;
	std::cout << "st_.count_=" << st_.count() << std::endl;
	std::cout << "st_.top=" << st_.top() << std::endl;
	if ((st_.count()==1) && (st_.top()==10))
	{
		mark=true;
	}
	REQUIRE(mark);
}*/

SCENARIO("Empty","[empty]"){
	bool mark=false;
	bool mark_empty,mark_full;
	stack<int> st;
	mark_empty=st.empty();
	st.push(10);
	mark_full=st.empty();
	if ((mark_empty==true) && (mark_full==false))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("threads","[TH]"){
	stack<int> st;
	st.push(1);
	st.push(2);
	st.push(3);
	std::thread t1([&st](){
		st.push(4);
		st.push(5);
	});
	std::thread t2([&st](){
		st.pop();
		st.pop();
	});
	t1.join();
	t2.join();
	REQUIRE(st.count()==3);
}
<commit_msg>Update init.cpp<commit_after>#include "Stack.h"
#include <catch.hpp>
using namespace std;
SCENARIO("Stack count", "[count]"){
	bool mark=false;
	stack<int> st;
	if ((st.count()==0))
	{
		mark=true;
	}
	st.push(1);
	if ((st.count()==1))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack push", "[push]"){
	bool mark=false;
	stack<int> st;
	st.push(1);
	if ((st.count()==1)&&(st.top()==1))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack pop", "[pop]"){
	bool mark=false;
	stack<int> st;
	st.push(123);
	st.pop();
	if (st.count()==0)
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Stack top", "[top]"){
	bool mark=false;
	stack<int> st;
	st.push(11);
	st.push(22);
	int v=st.top();
	if (v==22)
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Assign", "[assign]"){
	bool mark=false;
	stack<int> st;
	st.push(10);
	stack<int> st_;
	st_=st;
	std::cout << "st_.count_=" << st_.count() << std::endl;
	std::cout << "st_.top=" << st_.top() << std::endl;
	if ((st_.count()==1) && (st_.top()==10))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Copy","[copy]"){
	bool mark=false;
	stack<int> st;
	st.push(10);
	stack<int> st_=st;
	std::cout << "st_.count_=" << st_.count() << std::endl;
	std::cout << "st_.top=" << st_.top() << std::endl;
	if ((st_.count()==1) && (st_.top()==10))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("Empty","[empty]"){
	bool mark=false;
	bool mark_empty,mark_full;
	stack<int> st;
	mark_empty=st.empty();
	st.push(10);
	mark_full=st.empty();
	if ((mark_empty==true) && (mark_full==false))
	{
		mark=true;
	}
	REQUIRE(mark);
}

SCENARIO("threads","[TH]"){
	stack<int> st;
	st.push(1);
	st.push(2);
	st.push(3);
	std::thread t1([&st](){
		st.push(4);
		st.push(5);
	});
	std::thread t2([&st](){
		st.pop();
		st.pop();
	});
	t1.join();
	t2.join();
	REQUIRE(st.count()==3);
}
<|endoftext|>


<commit_before>#include <BinaryTree.hpp>
#include <catch.hpp>

SCENARIO ("init", "[init]")
{
  BinaryTree<int> obj;
  REQUIRE(obj.root_() == nullptr);
}

SCENARIO("insert", "[insert]")
{
  BinaryTree<int> obj;
  obj.insert_node(3);
  REQUIRE(obj.find_node(3, obj.root_())->data == 3);
}

SCENARIO("find_node", "[find_node]")
{
  BinaryTree<int> obj;
  obj.insert_node(2);
  REQUIRE(obj.find_node(2, obj.root_()) != nullptr);
  REQUIRE(obj.find_node(2, obj.root_())->data == 2);
}

SCENARIO("get root", "[get root]")
{
  BinaryTree<int> obj;
  obj.insert_node(4);
  REQUIRE(obj.root_() != 0);
}

SCENARIO ("reading", "[init]")
{
   BinaryTree<int> obj;
   obj.reading("file2.txt");
   REQUIRE(obj.search_result(1) == 1);
}
<commit_msg>Update init.cpp<commit_after>#include <BinaryTree.hpp>
#include <catch.hpp>

SCENARIO ("init", "[init]")
{
  BinaryTree<int> obj;
  REQUIRE(obj.root_() == nullptr);
}

SCENARIO("insert", "[insert]")
{
  BinaryTree<int> obj;
  obj.insert_node(3);
  REQUIRE(obj.find_node(3, obj.root_())->data == 3);
}

SCENARIO("find_node", "[find_node]")
{
  BinaryTree<int> obj;
  obj.insert_node(2);
  REQUIRE(obj.find_node(2, obj.root_()) != nullptr);
  REQUIRE(obj.find_node(2, obj.root_())->data == 2);
}

SCENARIO("get root", "[get root]")
{
  BinaryTree<int> obj;
  obj.insert_node(4);
  REQUIRE(obj.root_() != 0);
}
<|endoftext|>


<commit_before>#include <matrix.hpp>
#include <catch.hpp>

SCENARIO("matrix init without parametrs", "[init wp]") {
	Matrix matrix;
	REQUIRE(matrix.rows() == 4);
	REQUIRE(matrix.columns() == 4);

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == 0);
		}
	}
}

SCENARIO("matrix init with parametrs", "[init withp]") {
	Matrix matrix(6,6);
	REQUIRE(matrix.rows() == 6);
	REQUIRE(matrix.columns() == 6);

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == 0);
		}
	}
}

SCENARIO("matrix init copy", "[init copy]") {
	Matrix matrix(6,6);
	Matrix matrix1(matrix);
	REQUIRE(matrix1.rows() == matrix.rows());
	REQUIRE(matrix1.columns() == matrix.columns());

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j));
		}
	}
}

SCENARIO("matrix fill", "[fill]") {
	Matrix matrix(2,2);
	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();
	matrix.fill("test1.txt");
	REQUIRE(matrix.Element(0,0) == 1);
	REQUIRE(matrix.Element(0,1) == 2);
	REQUIRE(matrix.Element(1,0) == 3);
	REQUIRE(matrix.Element(1,1) == 4);
}

SCENARIO("matrix sum", "[sum]") {
	Matrix matrix(2,2);
	Matrix matrix1(2,2);
	Matrix sum(2,2);

	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();

	matrix.fill("test1.txt");
	matrix1.fill("test1.txt");
	ofstream sumfile("sumfile.txt");
	sumfile << "2 4 6 8";
	sum.fill("sumfile.txt");
	sumfile.close();
	REQUIRE(sum == matrix + matrix1);
}

<commit_msg>Update init.cpp<commit_after>#include <matrix.hpp>
#include <catch.hpp>

SCENARIO("matrix init without parametrs", "[init wp]") {
	Matrix matrix;
	REQUIRE(matrix.rows() == 4);
	REQUIRE(matrix.columns() == 4);

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == 0);
		}
	}
}

SCENARIO("matrix init with parametrs", "[init withp]") {
	Matrix matrix(6,6);
	REQUIRE(matrix.rows() == 6);
	REQUIRE(matrix.columns() == 6);

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == 0);
		}
	}
}

SCENARIO("matrix init copy", "[init copy]") {
	Matrix matrix(6,6);
	Matrix matrix1(matrix);
	REQUIRE(matrix1.rows() == matrix.rows());
	REQUIRE(matrix1.columns() == matrix.columns());

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j));
		}
	}
}

SCENARIO("matrix fill", "[fill]") {
	Matrix matrix(2,2);
	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();
	matrix.fill("test1.txt");
	REQUIRE(matrix.Element(0,0) == 1);
	REQUIRE(matrix.Element(0,1) == 2);
	REQUIRE(matrix.Element(1,0) == 3);
	REQUIRE(matrix.Element(1,1) == 4);
}

SCENARIO("matrix sum", "[sum]") {
	Matrix matrix(2,2);
	Matrix matrix1(2,2);
	Matrix sum(2,2);

	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();

	matrix.fill("test1.txt");
	matrix1.fill("test1.txt");
	ofstream sumfile("sumfile.txt");
	sumfile << "2 4 6 8";
	sum.fill("sumfile.txt");
	sumfile.close();
	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(sum.Element(i,j) == matrix.Element(i,j) + matrix1.Element(i,j));
		}
	}
}

<|endoftext|>


<commit_before>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include "shape.hpp"
#include "box.hpp"
#include "sphere.hpp"
#include <glm/vec3.hpp>

TEST_CASE("test box", "[test box]")
{
	Color black{0.0,0.0,0.0};
	Box box1;
	glm::vec3 v1{0.0,0.0,0.0};
	glm::vec3 v2{1.0,1.0,1.0};
	REQUIRE(box1.min() == v1);
	REQUIRE(box1.max() == v2);
	REQUIRE(box1.volume() == 1.0);
	REQUIRE(box1.area() == 6.0);
	REQUIRE(box1.name() == "noname");
	REQUIRE(box1.color() == black);

	glm::vec3 v3{-1.0,-1.0,-1.0};
	glm::vec3 v4{1.0,1.0,1.0};
	Box box2{v3,v4};
	REQUIRE(box2.min() == v3);
	REQUIRE(box2.max() == v4);
	REQUIRE(box2.volume() == 8.0);
	REQUIRE(box2.area() == 24.0);
	REQUIRE(box2.name() == "noname");
	REQUIRE(box2.color() == black);

	Color red{1.0,0.0,0.0};
	Box box3{"red box", red, v3,v4};
	REQUIRE(box3.min() == v3);
	REQUIRE(box3.max() == v4);
	REQUIRE(box3.volume() == 8.0);
	REQUIRE(box3.area() == 24.0);
	REQUIRE(box3.name() == "red box");
	REQUIRE(box3.color() == red);
}

TEST_CASE("test sphere", "[test sphere]")
{
	Color black{0.0,0.0,0.0};
	Sphere sphere1;
	glm::vec3 v1{0.0,0.0,0.0};
	glm::vec3 v2{1.0,1.0,1.0};
	REQUIRE(sphere1.mid() == v1);
	REQUIRE(sphere1.volume() == Approx(0.5236));
	REQUIRE(sphere1.area() == Approx(3.14159));
	REQUIRE(sphere1.name() == "noname");
	REQUIRE(sphere1.color() == black);

	Sphere sphere2{v2, 1.0};
	REQUIRE(sphere2.mid() == v2);
	REQUIRE(sphere2.volume() == Approx(4.18879));
	REQUIRE(sphere2.area() == Approx(12.56637));
	REQUIRE(sphere2.name() == "noname");
	REQUIRE(sphere2.color() == black);

	Color green{0.0,1.0,0.0};
	Sphere sphere3{"green sphere", green, v2, 1.0};
	REQUIRE(sphere3.mid() == v2);
	REQUIRE(sphere3.volume() == Approx(4.18879));
	REQUIRE(sphere3.area() == Approx(12.56637));
	REQUIRE(sphere3.name() == "green sphere");
	REQUIRE(sphere3.color() == green);
}

int main(int argc, char *argv[])
{
  return Catch::Session().run(argc, argv);
}
<commit_msg>Print stuff included<commit_after>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include "shape.hpp"
#include "box.hpp"
#include "sphere.hpp"
#include <glm/vec3.hpp>

TEST_CASE("test box", "[test box]")
{
	Color black{0.0,0.0,0.0};
	Box box1;
	glm::vec3 v1{0.0,0.0,0.0};
	glm::vec3 v2{1.0,1.0,1.0};
	REQUIRE(box1.min() == v1);
	REQUIRE(box1.max() == v2);
	REQUIRE(box1.volume() == 1.0);
	REQUIRE(box1.area() == 6.0);
	REQUIRE(box1.name() == "noname");
	REQUIRE(box1.color() == black);

	glm::vec3 v3{-1.0,-1.0,-1.0};
	glm::vec3 v4{1.0,1.0,1.0};
	Box box2{v3,v4};
	REQUIRE(box2.min() == v3);
	REQUIRE(box2.max() == v4);
	REQUIRE(box2.volume() == 8.0);
	REQUIRE(box2.area() == 24.0);
	REQUIRE(box2.name() == "noname");
	REQUIRE(box2.color() == black);

	Color red{1.0,0.0,0.0};
	Box box3{"red box", red, v3,v4};
	REQUIRE(box3.min() == v3);
	REQUIRE(box3.max() == v4);
	REQUIRE(box3.volume() == 8.0);
	REQUIRE(box3.area() == 24.0);
	REQUIRE(box3.name() == "red box");
	REQUIRE(box3.color() == red);
	std::cout << box3;
}

TEST_CASE("test sphere", "[test sphere]")
{
	Color black{0.0,0.0,0.0};
	Sphere sphere1;
	glm::vec3 v1{0.0,0.0,0.0};
	glm::vec3 v2{1.0,1.0,1.0};
	REQUIRE(sphere1.mid() == v1);
	REQUIRE(sphere1.volume() == Approx(0.5236));
	REQUIRE(sphere1.area() == Approx(3.14159));
	REQUIRE(sphere1.name() == "noname");
	REQUIRE(sphere1.color() == black);

	Sphere sphere2{v2, 1.0};
	REQUIRE(sphere2.mid() == v2);
	REQUIRE(sphere2.volume() == Approx(4.18879));
	REQUIRE(sphere2.area() == Approx(12.56637));
	REQUIRE(sphere2.name() == "noname");
	REQUIRE(sphere2.color() == black);

	Color green{0.0,1.0,0.0};
	Sphere sphere3{"green sphere", green, v2, 1.0};
	REQUIRE(sphere3.mid() == v2);
	REQUIRE(sphere3.volume() == Approx(4.18879));
	REQUIRE(sphere3.area() == Approx(12.56637));
	REQUIRE(sphere3.name() == "green sphere");
	REQUIRE(sphere3.color() == green);
	std::cout << sphere3;
}

int main(int argc, char *argv[])
{
  return Catch::Session().run(argc, argv);
}
<|endoftext|>


<commit_before>/* /tests/main.cpp
 *
 * A test entrypoint which enables the use of the tap listener.
 *
 * See /LICENCE.md for Copyright information */

#define GTEST_TAP_PRINT_TO_STDOUT
#define GTEST_TAP_13_DIAGNOSTIC

#include <memory>  // IWYU pragma: keep
#include <string>  // IWYU pragma: keep
#include <tuple>  // IWYU pragma: keep
#include <vector>  // IWYU pragma: keep

#include <gtest/gtest.h>
#include <boost/program_options.hpp>   // IWYU pragma: keep
#include <boost/program_options/errors.hpp>               // for program_opt...
#include <boost/program_options/options_description.hpp>  // for options_des...
#include <boost/program_options/variables_map.hpp>        // for variables_map

#include <gtest-tap-listener-mocha/tap.h>

namespace po = boost::program_options;

namespace
{
    char const *PROGRAM_NAME = "test";

    std::tuple <int, std::vector <char const *>>
    GetUnrecognizedStrv (po::parsed_options const &parsed)
    {
        auto unrecognised = po::collect_unrecognized (parsed.options,
                                                      po::include_positional);

        std::vector <char const *> unrecognisedStrv;
        unrecognisedStrv.reserve (unrecognised.size () + 1);
        unrecognisedStrv.push_back (PROGRAM_NAME);

        for (auto &str : unrecognised)
        {
            unrecognisedStrv.push_back (str.c_str ());
        }

        int unrecognisedStrvLen = unrecognisedStrv.size ();

        return std::make_tuple (unrecognisedStrvLen, unrecognisedStrv);
    }
}

int main (int argc, char **argv)
{
    po::options_description desc ("CPP-Subprocess Tests Entrypoint");
    desc.add_options () ("reporter",
                         po::value <std::string> ()->default_value ("default"),
                         "Test reporter to use");

    po::variables_map program_variables;
    auto parsed = po::command_line_parser (argc, argv).options (desc)
                                                      .allow_unregistered ()
                                                      .run ();

    po::store (po::parse_command_line (argc, argv, desc), program_variables);
    po::notify (program_variables);

    std::unique_ptr <::testing::TestEventListener> listener;

    if (program_variables.count ("reporter"))
    {
        if (program_variables["reporter"].as <std::string> () ==
            std::string ("tap"))
        {
            listener.reset (new ::tap::mocha::TapListener ());
        }
    }

    std::vector <const char *> unrecognisedStrv;
    int unrecognisedStrvLen;

    std::tie (unrecognisedStrvLen,
              unrecognisedStrv) = GetUnrecognizedStrv (parsed);

    ::testing::InitGoogleTest (&argc, argv);

    auto &listeners = ::testing::UnitTest::GetInstance ()->listeners ();

    if (listener)
    {
        delete listeners.Release (listeners.default_result_printer ());
        listeners.Append (listener.release ());
    }

    return RUN_ALL_TESTS ();
}<commit_msg>main: Linter errors<commit_after>/* /tests/main.cpp
 *
 * A test entry-point which enables the use of the tap listener.
 *
 * See /LICENCE.md for Copyright information */

#define GTEST_TAP_PRINT_TO_STDOUT
#define GTEST_TAP_13_DIAGNOSTIC

#include <memory>  // IWYU pragma: keep
#include <string>  // IWYU pragma: keep
#include <tuple>  // IWYU pragma: keep
#include <vector>  // IWYU pragma: keep

#include <gtest/gtest.h>
#include <boost/program_options.hpp>   // IWYU pragma: keep
#include <boost/program_options/errors.hpp>               // for program_opt...
#include <boost/program_options/options_description.hpp>  // for options_des...
#include <boost/program_options/variables_map.hpp>        // for variables_map

#include <gtest-tap-listener-mocha/tap.h>

namespace po = boost::program_options;

namespace
{
    char const *PROGRAM_NAME = "test";

    std::tuple <int, std::vector <char const *>>
    GetUnrecognizedStrv (po::parsed_options const &parsed)
    {
        auto unrecognised = po::collect_unrecognized (parsed.options,
                                                      po::include_positional);

        std::vector <char const *> unrecognisedStrv;
        unrecognisedStrv.reserve (unrecognised.size () + 1);
        unrecognisedStrv.push_back (PROGRAM_NAME);

        for (auto &str : unrecognised)
        {
            unrecognisedStrv.push_back (str.c_str ());
        }

        int unrecognisedStrvLen = unrecognisedStrv.size ();

        return std::make_tuple (unrecognisedStrvLen, unrecognisedStrv);
    }
}

int main (int argc, char **argv)
{
    po::options_description desc ("CPP-Subprocess Tests Entrypoint");
    desc.add_options () ("reporter",
                         po::value <std::string> ()->default_value ("default"),
                         "Test reporter to use");

    po::variables_map program_variables;
    auto parsed = po::command_line_parser (argc, argv).options (desc)
                                                      .allow_unregistered ()
                                                      .run ();

    po::store (po::parse_command_line (argc, argv, desc), program_variables);
    po::notify (program_variables);

    std::unique_ptr <::testing::TestEventListener> listener;

    if (program_variables.count ("reporter"))
    {
        if (program_variables["reporter"].as <std::string> () ==
            std::string ("tap"))
        {
            listener.reset (new ::tap::mocha::TapListener ());
        }
    }

    std::vector <const char *> unrecognisedStrv;
    int unrecognisedStrvLen;

    std::tie (unrecognisedStrvLen,
              unrecognisedStrv) = GetUnrecognizedStrv (parsed);

    ::testing::InitGoogleTest (&argc, argv);

    auto &listeners = ::testing::UnitTest::GetInstance ()->listeners ();

    if (listener)
    {
        delete listeners.Release (listeners.default_result_printer ());
        listeners.Append (listener.release ());
    }

    return RUN_ALL_TESTS ();
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <ios>

// template <class charT, class traits> class basic_ios

// operator unspecified-bool-type() const;

#include <ios>
#include <type_traits>
#include <cassert>

int main()
{
    std::ios ios(0);
    assert(static_cast<bool>(ios) == !ios.fail());
    ios.setstate(std::ios::failbit);
    assert(static_cast<bool>(ios) == !ios.fail());
    static_assert((!std::is_convertible<std::ios, void*>::value), "");
    static_assert((!std::is_convertible<std::ios, int>::value), "");
    static_assert((!std::is_convertible<std::ios const&, int>::value), "");
#if TEST_STD_VER >= 11
    static_assert((!std::is_convertible<std::ios, bool>::value), "");
#endif
}
<commit_msg>Add missing include in test.<commit_after>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <ios>

// template <class charT, class traits> class basic_ios

// operator unspecified-bool-type() const;

#include <ios>
#include <type_traits>
#include <cassert>

#include "test_macros.h"

int main()
{
    std::ios ios(0);
    assert(static_cast<bool>(ios) == !ios.fail());
    ios.setstate(std::ios::failbit);
    assert(static_cast<bool>(ios) == !ios.fail());
    static_assert((!std::is_convertible<std::ios, void*>::value), "");
    static_assert((!std::is_convertible<std::ios, int>::value), "");
    static_assert((!std::is_convertible<std::ios const&, int>::value), "");
#if TEST_STD_VER >= 11
    static_assert((!std::is_convertible<std::ios, bool>::value), "");
#endif
}
<|endoftext|>