<commit_before>#ifndef STAN_MATH_PRIM_FUN_LUB_CONSTRAIN_HPP
#define STAN_MATH_PRIM_FUN_LUB_CONSTRAIN_HPP

#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/add.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/elt_multiply.hpp>
#include <stan/math/prim/fun/inv_logit.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/log1p.hpp>
#include <stan/math/prim/fun/multiply.hpp>
#include <stan/math/prim/fun/subtract.hpp>
#include <stan/math/prim/fun/sum.hpp>
#include <cmath>

namespace stan {
namespace math {

/**
 * Return the lower- and upper-bounded scalar derived by
 * transforming the specified free scalar given the specified
 * lower and upper bounds.
 *
 *
The transform is the transformed and scaled inverse logit,
 *
 *
\f$f(x) = L + (U - L) \mbox{logit}^{-1}(x)\f$
 *
 * @tparam T Type of scalar.
 * @tparam L Type of lower bound.
 * @tparam U Type of upper bound.
 * @param[in] x Free scalar to transform.
 * @param[in] lb Lower bound.
 * @param[in] ub Upper bound.
 * @return Lower- and upper-bounded scalar derived from transforming
 *   the free scalar.
 * @throw std::domain_error if ub <= lb
 */
template <typename T, typename L, typename U>
inline auto lub_constrain(T&& x, L&& lb, U&& ub) {
    check_less("lub_constrain", "lb", value_of(lb_ref), value_of(ub_ref));
    check_finite("lub_constrain", "lb", value_of(lb_ref));
    check_finite("lub_constrain", "ub", value_of(ub_ref));
    return add(elt_multiply(subtract(ub_ref, lb_ref), inv_logit(x_ref)),
               lb_ref);
}

/**
 * Return the lower- and upper-bounded scalar derived by
 * transforming the specified free scalar given the specified
 * lower and upper bounds and increment the specified log
 * density with the log absolute Jacobian determinant.
 *
 *
The transform is as defined in
 * lub_constrain(T, double, double).  The log absolute
 * Jacobian determinant is given by
 *
 *
\f$\log \left| \frac{d}{dx} \left(
 *                L + (U-L) \mbox{logit}^{-1}(x) \right)
 *            \right|\f$
 *
 *
\f$ {} = \log |
 *         (U-L)
 *         \, (\mbox{logit}^{-1}(x))
 *         \, (1 - \mbox{logit}^{-1}(x)) |\f$
 *
 *
\f$ {} = \log (U - L) + \log (\mbox{logit}^{-1}(x))
 *                          + \log (1 - \mbox{logit}^{-1}(x))\f$
 *
 * @tparam T Type of scalar.
 * @tparam L Type of lower bound.
 * @tparam U Type of upper bound.
 * @param[in] x Free scalar to transform.
 * @param[in] lb Lower bound.
 * @param[in] ub Upper bound.
 * @param[in,out] lp Log probability scalar reference.
 * @return Lower- and upper-bounded scalar derived from transforming
 *   the free scalar.
 * @throw std::domain_error if ub <= lb
 */
template <typename T, typename L, typename U>
inline auto lub_constrain(T&& x, L&& lb, U&& ub, return_type_t<T, L, U>& lp) {
  auto&& x_ref = to_ref(std::forward<T>(x));
  auto&& lb_ref = to_ref(std::forward<L>(lb));
  auto&& ub_ref = to_ref(std::forward(ub));

  check_less("lub_constrain", "lb", value_of(lb_ref), value_of(ub_ref));
  check_finite("lub_constrain", "lb", value_of(lb_ref));
  check_finite("lub_constrain", "ub", value_of(ub_ref));

  auto diff = eval(subtract(std::forward<decltype(ub_ref)>(ub_ref), lb_ref));

  lp += sum(
      add(log(diff), subtract(-abs(x_ref), multiply(static_cast<double>(2),
                                                    log1p_exp(-abs(x_ref))))));

  return add(elt_multiply(diff, inv_logit(x_ref)), lb_ref);
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_PRIM_FUN_LUB_CONSTRAIN_HPP
#define STAN_MATH_PRIM_FUN_LUB_CONSTRAIN_HPP

#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/add.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/elt_multiply.hpp>
#include <stan/math/prim/fun/inv_logit.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/log1p.hpp>
#include <stan/math/prim/fun/multiply.hpp>
#include <stan/math/prim/fun/subtract.hpp>
#include <stan/math/prim/fun/sum.hpp>
#include <cmath>

namespace stan {
namespace math {

/**
 * Return the lower- and upper-bounded scalar derived by
 * transforming the specified free scalar given the specified
 * lower and upper bounds.
 *
 *
The transform is the transformed and scaled inverse logit,
 *
 *
\f$f(x) = L + (U - L) \mbox{logit}^{-1}(x)\f$
 *
 * @tparam T Type of scalar.
 * @tparam L Type of lower bound.
 * @tparam U Type of upper bound.
 * @param[in] x Free scalar to transform.
 * @param[in] lb Lower bound.
 * @param[in] ub Upper bound.
 * @return Lower- and upper-bounded scalar derived from transforming
 *   the free scalar.
 * @throw std::domain_error if ub <= lb
 */
template <typename T, typename L, typename U>
inline auto lub_constrain(T&& x, L&& lb, U&& ub) {
  check_less("lub_constrain", "lb", value_of(lb_ref), value_of(ub_ref));
  check_finite("lub_constrain", "lb", value_of(lb_ref));
  check_finite("lub_constrain", "ub", value_of(ub_ref));
  return add(elt_multiply(subtract(ub_ref, lb_ref), inv_logit(x_ref)), lb_ref);
}

/**
 * Return the lower- and upper-bounded scalar derived by
 * transforming the specified free scalar given the specified
 * lower and upper bounds and increment the specified log
 * density with the log absolute Jacobian determinant.
 *
 *
The transform is as defined in
 * lub_constrain(T, double, double).  The log absolute
 * Jacobian determinant is given by
 *
 *
\f$\log \left| \frac{d}{dx} \left(
 *                L + (U-L) \mbox{logit}^{-1}(x) \right)
 *            \right|\f$
 *
 *
\f$ {} = \log |
 *         (U-L)
 *         \, (\mbox{logit}^{-1}(x))
 *         \, (1 - \mbox{logit}^{-1}(x)) |\f$
 *
 *
\f$ {} = \log (U - L) + \log (\mbox{logit}^{-1}(x))
 *                          + \log (1 - \mbox{logit}^{-1}(x))\f$
 *
 * @tparam T Type of scalar.
 * @tparam L Type of lower bound.
 * @tparam U Type of upper bound.
 * @param[in] x Free scalar to transform.
 * @param[in] lb Lower bound.
 * @param[in] ub Upper bound.
 * @param[in,out] lp Log probability scalar reference.
 * @return Lower- and upper-bounded scalar derived from transforming
 *   the free scalar.
 * @throw std::domain_error if ub <= lb
 */
template <typename T, typename L, typename U>
inline auto lub_constrain(T&& x, L&& lb, U&& ub, return_type_t<T, L, U>& lp) {
  auto&& x_ref = to_ref(std::forward<T>(x));
  auto&& lb_ref = to_ref(std::forward<L>(lb));
  auto&& ub_ref = to_ref(std::forward(ub));

  check_less("lub_constrain", "lb", value_of(lb_ref), value_of(ub_ref));
  check_finite("lub_constrain", "lb", value_of(lb_ref));
  check_finite("lub_constrain", "ub", value_of(ub_ref));

  auto diff = eval(subtract(std::forward<decltype(ub_ref)>(ub_ref), lb_ref));

  lp += sum(
      add(log(diff), subtract(-abs(x_ref), multiply(static_cast<double>(2),
                                                    log1p_exp(-abs(x_ref))))));

  return add(elt_multiply(diff, inv_logit(x_ref)), lb_ref);
}

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


<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_TO_MATRIX_HPP
#define STAN_MATH_PRIM_MAT_FUN_TO_MATRIX_HPP

#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <Eigen/Dense>
#include <vector>

namespace stan {
  namespace math {
    /**
     * Returns a matrix with dynamic dimensions constructed from
     * an Eigen matrix which is either
     * a row vector, column vector, or matrix.
     * The runtime dimensions will be the same as the input.
     *
     * @tparam T type of the scalar
     * @tparam R number of rows
     * @tparam C number of columns
     * @param x matrix
     * @return the matrix representation of the input
     */
    template <typename T, int R, int C>
    inline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const Eigen::Matrix<T, R, C>& x) {
      return x;
    }

    /**
     * Returns a matrix representation of a standard vector of Eigen
     * row vectors with the same dimensions and indexing order.
     *
     * @tparam T type of the scalar
     * @param x Eigen vector of vectors of scalar values
     * @return the matrix representation of the input
     */
    template <typename T>
    inline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const
              std::vector<Eigen::Matrix<T, 1, Eigen::Dynamic> >& x) {
      size_t rows = x.size();
      if (rows != 0) {
        size_t cols = x[0].size();
        Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
          result(rows, cols);
        for (size_t i=0, ij=0; i < cols; i++)
          for (size_t j=0; j < rows; j++, ij++)
            result(ij) = x[j][i];
        return result;
      } else {
        return Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> (0, 0);
      }
    }

    /**
     * Returns a matrix representation of the standard vector of
     * standard vectors with the same dimensions and indexing order.
     *
     * @tparam T type of the scalar
     * @param x vector of vectors of scalar values
     * @return the matrix representation of the input
     */
    template <typename T>
    inline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const std::vector< std::vector<T> >& x) {
      size_t rows = x.size();
      if (rows != 0) {
        size_t cols = x[0].size();
        Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
          result(rows, cols);
        for (size_t i=0, ij=0; i < cols; i++)
          for (size_t j=0; j < rows; j++, ij++)
            result(ij) = x[j][i];
        return result;
      } else {
        return Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> (0, 0);
      }
    }

    /**
     * Returns a matrix representation of a standard vector of
     * standard vectors of integers with the same dimensions and
     * indexing order.
     *
     * @param x vector of vectors of integer values
     * @return the matrix representation of the input,
     * ints promoted to doubles
     */
    inline Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const std::vector< std::vector<int> >& x) {
      size_t rows = x.size();
      if (rows != 0) {
        size_t cols = x[0].size();
        Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
          result(rows, cols);
        for (size_t i=0, ij=0; i < cols; i++)
          for (size_t j=0; j < rows; j++, ij++)
            result(ij) = x[j][i];
        return result;
      } else {
        return Eigen::Matrix<double, Eigen::Dynamic,
                             Eigen::Dynamic> (0, 0);
      }
    }

    /**
     * Returns a matrix representation of the vector in column-major
     * order with the specified number of rows and columns.
     *
     * @tparam T type of the scalar
     * @param x matrix
     * @param m rows
     * @param n columns
     * @return Reshaped inputted matrix
     * @throw std::invalid_argument if the sizes
     * do not match
     */
    template <typename T, int R, int C>
    inline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const Eigen::Matrix<T, R, C>& x, int m, int n) {
      static const char* fun = "to_matrix(matrix)";
      check_size_match(fun, "rows * columns", m * n, "vector size",
                       x.size());
      Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> y = x;
      y.resize(m, n);
      return y;
    }

    /**
     * Returns a matrix representation of the vector in column-major
     * order with the specified number of rows and columns.
     *
     * @tparam T type of the scalar
     * @param x vector of values
     * @param m rows
     * @param n columns
     * @return the matrix representation of the input
     * @throw std::invalid_argument
     * if the sizes do not match
     */
    template <typename T>
    inline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const std::vector<T>& x, int m, int n) {
      static const char* fun = "to_matrix(array)";
      check_size_match(fun, "rows * columns", m * n, "vector size",
                       x.size());
      return Eigen::Map<const
                        Eigen::Matrix<T, Eigen::Dynamic,
                                      Eigen::Dynamic> >(&x[0], m, n);
    }

    /**
     * Returns a matrix representation of the vector in column-major
     * order with the specified number of rows and columns.
     *
     * @param x vector of values
     * @param m rows
     * @param n columns
     * @return the matrix representation of the input
     * @throw std::invalid_argument
     * if the sizes do not match
     */
    inline Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const std::vector<int>& x, int m, int n) {
      static const char* fun = "to_matrix(array)";
      int size = x.size();
      check_size_match(fun, "rows * columns", m * n,
                       "vector size", size);
      Eigen::Matrix<double,
                    Eigen::Dynamic, Eigen::Dynamic> result(m, n);
      double* datap = result.data();
      for (int i=0; i < size; i++)
        datap[i] = x[i];
      return result;
    }

    /**
     * Returns a matrix representation of the vector in column-major
     * order with the specified number of rows and columns.
     *
     * @tparam T type of the scalar
     * @param x matrix
     * @param m rows
     * @param n columns
     * @param cm column-major indicator:
     * if 1, output matrix is transversed in column-major order,
     * if 0, output matrix is transversed in row-major order,
     * otherwise function throws std::invalid_argument
     * @return Reshaped inputted matrix
     * @throw std::invalid_argument
     * if the sizes do not match
     */
    template <typename T, int R, int C>
    inline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const Eigen::Matrix<T, R, C>& x, int m, int n, int cm) {
      if (cm == 1)
        return to_matrix(x, m, n);
      else if (cm == 0) {
        check_size_match("to_matrix", "rows * columns", m * n,
                         "matrix size", x.size());
        Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
          result(m, n);
        for (size_t i=0, ij=0; i < m; i++)
          for (size_t j=0; j < n; j++, ij++)
            result(i, j) = x(ij);
        return result;
      }
      else {
        invalid_argument("to_matrix", "cm", cm,
                         "column-major indicator",
                         "must equal 0 or 1");
        return Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> (0, 0);
      }
    }

    /**
     * Returns a matrix representation of the vector in column-major
     * order with the specified number of rows and columns.
     *
     * @tparam T type of the scalar
     * @param x vector of values
     * @param m rows
     * @param n columns
     * @param cm column-major indicator:
     * if 1, output matrix is transversed in column-major order,
     * if 0, output matrix is transversed in row-major order,
     * otherwise function throws std::invalid_argument
     * @return the matrix representation of the input
     * @throw std::invalid_argument
     * if the sizes do not match
     */
    template <typename T>
    inline
    Eigen::Matrix<typename
      boost::math::tools::promote_args<T, double>::type,
      Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const std::vector<T>& x, int m, int n, int cm) {
      if (cm == 1)
        return to_matrix(x, m, n);
      else if (cm == 0) {
        check_size_match("to_matrix", "rows * columns", m * n,
                         "matrix size", x.size());
        Eigen::Matrix<typename
          boost::math::tools::promote_args<T, double>::type,
          Eigen::Dynamic, Eigen::Dynamic>
          result(m, n);
        for (size_t i=0, ij=0; i < m; i++)
          for (size_t j=0; j < n; j++, ij++)
            result(i, j) = x[ij];
        return result;
      }
      else {
        invalid_argument("to_matrix", "cm", cm,
                         "column-major indicator",
                         "must equal 0 or 1");
        return Eigen::Matrix<typename
                boost::math::tools::promote_args<T, double>::type,
                Eigen::Dynamic, Eigen::Dynamic> (0, 0);
      }
    }

  }
}
#endif
<commit_msg>trailing spaces and cpplint<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_TO_MATRIX_HPP
#define STAN_MATH_PRIM_MAT_FUN_TO_MATRIX_HPP

#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <Eigen/Dense>
#include <vector>

namespace stan {
  namespace math {
    /**
     * Returns a matrix with dynamic dimensions constructed from
     * an Eigen matrix which is either
     * a row vector, column vector, or matrix.
     * The runtime dimensions will be the same as the input.
     *
     * @tparam T type of the scalar
     * @tparam R number of rows
     * @tparam C number of columns
     * @param x matrix
     * @return the matrix representation of the input
     */
    template <typename T, int R, int C>
    inline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const Eigen::Matrix<T, R, C>& x) {
      return x;
    }

    /**
     * Returns a matrix representation of a standard vector of Eigen
     * row vectors with the same dimensions and indexing order.
     *
     * @tparam T type of the scalar
     * @param x Eigen vector of vectors of scalar values
     * @return the matrix representation of the input
     */
    template <typename T>
    inline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const
              std::vector<Eigen::Matrix<T, 1, Eigen::Dynamic> >& x) {
      size_t rows = x.size();
      if (rows != 0) {
        size_t cols = x[0].size();
        Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
          result(rows, cols);
        for (size_t i=0, ij=0; i < cols; i++)
          for (size_t j=0; j < rows; j++, ij++)
            result(ij) = x[j][i];
        return result;
      } else {
        return Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> (0, 0);
      }
    }

    /**
     * Returns a matrix representation of the standard vector of
     * standard vectors with the same dimensions and indexing order.
     *
     * @tparam T type of the scalar
     * @param x vector of vectors of scalar values
     * @return the matrix representation of the input
     */
    template <typename T>
    inline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const std::vector< std::vector<T> >& x) {
      size_t rows = x.size();
      if (rows != 0) {
        size_t cols = x[0].size();
        Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
          result(rows, cols);
        for (size_t i=0, ij=0; i < cols; i++)
          for (size_t j=0; j < rows; j++, ij++)
            result(ij) = x[j][i];
        return result;
      } else {
        return Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> (0, 0);
      }
    }

    /**
     * Returns a matrix representation of a standard vector of
     * standard vectors of integers with the same dimensions and
     * indexing order.
     *
     * @param x vector of vectors of integer values
     * @return the matrix representation of the input,
     * ints promoted to doubles
     */
    inline Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const std::vector< std::vector<int> >& x) {
      size_t rows = x.size();
      if (rows != 0) {
        size_t cols = x[0].size();
        Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
          result(rows, cols);
        for (size_t i=0, ij=0; i < cols; i++)
          for (size_t j=0; j < rows; j++, ij++)
            result(ij) = x[j][i];
        return result;
      } else {
        return Eigen::Matrix<double, Eigen::Dynamic,
                             Eigen::Dynamic> (0, 0);
      }
    }

    /**
     * Returns a matrix representation of the vector in column-major
     * order with the specified number of rows and columns.
     *
     * @tparam T type of the scalar
     * @param x matrix
     * @param m rows
     * @param n columns
     * @return Reshaped inputted matrix
     * @throw std::invalid_argument if the sizes
     * do not match
     */
    template <typename T, int R, int C>
    inline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const Eigen::Matrix<T, R, C>& x, int m, int n) {
      static const char* fun = "to_matrix(matrix)";
      check_size_match(fun, "rows * columns", m * n, "vector size",
                       x.size());
      Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> y = x;
      y.resize(m, n);
      return y;
    }

    /**
     * Returns a matrix representation of the vector in column-major
     * order with the specified number of rows and columns.
     *
     * @tparam T type of the scalar
     * @param x vector of values
     * @param m rows
     * @param n columns
     * @return the matrix representation of the input
     * @throw std::invalid_argument
     * if the sizes do not match
     */
    template <typename T>
    inline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const std::vector<T>& x, int m, int n) {
      static const char* fun = "to_matrix(array)";
      check_size_match(fun, "rows * columns", m * n, "vector size",
                       x.size());
      return Eigen::Map<const
                        Eigen::Matrix<T, Eigen::Dynamic,
                                      Eigen::Dynamic> >(&x[0], m, n);
    }

    /**
     * Returns a matrix representation of the vector in column-major
     * order with the specified number of rows and columns.
     *
     * @param x vector of values
     * @param m rows
     * @param n columns
     * @return the matrix representation of the input
     * @throw std::invalid_argument
     * if the sizes do not match
     */
    inline Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const std::vector<int>& x, int m, int n) {
      static const char* fun = "to_matrix(array)";
      int size = x.size();
      check_size_match(fun, "rows * columns", m * n,
                       "vector size", size);
      Eigen::Matrix<double,
                    Eigen::Dynamic, Eigen::Dynamic> result(m, n);
      double* datap = result.data();
      for (int i=0; i < size; i++)
        datap[i] = x[i];
      return result;
    }

    /**
     * Returns a matrix representation of the vector in column-major
     * order with the specified number of rows and columns.
     *
     * @tparam T type of the scalar
     * @param x matrix
     * @param m rows
     * @param n columns
     * @param cm column-major indicator:
     * if 1, output matrix is transversed in column-major order,
     * if 0, output matrix is transversed in row-major order,
     * otherwise function throws std::invalid_argument
     * @return Reshaped inputted matrix
     * @throw std::invalid_argument
     * if the sizes do not match
     */
    template <typename T, int R, int C>
    inline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const Eigen::Matrix<T, R, C>& x, int m, int n, int cm) {
      if (cm == 1) {
        return to_matrix(x, m, n);
      } else if (cm == 0) {
        check_size_match("to_matrix", "rows * columns", m * n,
                         "matrix size", x.size());
        Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
          result(m, n);
        for (size_t i=0, ij=0; i < m; i++)
          for (size_t j=0; j < n; j++, ij++)
            result(i, j) = x(ij);
        return result;
      } else {
        invalid_argument("to_matrix", "cm", cm,
                         "column-major indicator",
                         "must equal 0 or 1");
        return Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> (0, 0);
      }
    }

    /**
     * Returns a matrix representation of the vector in column-major
     * order with the specified number of rows and columns.
     *
     * @tparam T type of the scalar
     * @param x vector of values
     * @param m rows
     * @param n columns
     * @param cm column-major indicator:
     * if 1, output matrix is transversed in column-major order,
     * if 0, output matrix is transversed in row-major order,
     * otherwise function throws std::invalid_argument
     * @return the matrix representation of the input
     * @throw std::invalid_argument
     * if the sizes do not match
     */
    template <typename T>
    inline
    Eigen::Matrix<typename
      boost::math::tools::promote_args<T, double>::type,
      Eigen::Dynamic, Eigen::Dynamic>
    to_matrix(const std::vector<T>& x, int m, int n, int cm) {
      if (cm == 1) {
        return to_matrix(x, m, n);
      } else if (cm == 0) {
        check_size_match("to_matrix", "rows * columns", m * n,
                         "matrix size", x.size());
        Eigen::Matrix<typename
          boost::math::tools::promote_args<T, double>::type,
          Eigen::Dynamic, Eigen::Dynamic>
          result(m, n);
        for (size_t i=0, ij=0; i < m; i++)
          for (size_t j=0; j < n; j++, ij++)
            result(i, j) = x[ij];
        return result;
      } else {
        invalid_argument("to_matrix", "cm", cm,
                         "column-major indicator",
                         "must equal 0 or 1");
        return Eigen::Matrix<typename
                boost::math::tools::promote_args<T, double>::type,
                Eigen::Dynamic, Eigen::Dynamic> (0, 0);
      }
    }

  }
}
#endif
<|endoftext|>


<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <iostream>
#include <fstream>
#include <string>
// MPL
#include <boost/mpl/push_back.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/type_traits/is_same.hpp>
// StdAir
#include <stdair/STDAIR_Service.hpp>
#include <stdair/STDAIR_Types.hpp>
#include <stdair/bom/BomList.hpp>
#include <stdair/bom/BomSource.hpp>
#include <stdair/factory/FacBomContent.hpp>
#include <stdair/service/Logger.hpp>
#include <test/stdair/StdairTestLib.hpp>

/**
 * Namespace gathering classes and structures for test purposes
 */
namespace stdair_test {

  /** BookingClass */
  struct BookingClass {
    std::string _classCode;
    /** Constructor. */
    BookingClass (const std::string& iClassCode)
      : _classCode (iClassCode) {
    }

    /** Display .*/
    std::string toString() const {
      std::ostringstream oStr;
      oStr << _classCode;
      return oStr.str();
    }
  };

  /** Cabin */
  struct Cabin {
    BookingClass _bookingClass;
    Cabin (const BookingClass& iBkgClass)
      : _bookingClass (iBkgClass) {
    }

    /** Display .*/
    std::string toString() const {
      std::ostringstream oStr;
      oStr << _bookingClass._classCode;
      return oStr.str();
    }

    /** Child type. */
    typedef BookingClass child;
  };
}

// //////////////////////////////////////////////////////////////////////
void StdairTestLib::testMPLStructure() {

  // Output log File
  const std::string lLogFilename ("testMPLStructure.log");

  // Set the log parameters
  std::ofstream logOutputFile;

  // Open and clean the log outputfile
  logOutputFile.open (lLogFilename.c_str());
  logOutputFile.clear();

  // Initialise the stdair BOM
  const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
  stdair::STDAIR_Service stdairService (lLogParams);

  // DEBUG
  STDAIR_LOG_DEBUG ("StdAir service initialised");

  typedef boost::mpl::vector<stdair_test::BookingClass> MPL_BookingClass;
  typedef boost::mpl::push_back<MPL_BookingClass,
                                stdair_test::Cabin>::type types;

  const stdair_test::BookingClass lA ("A");
  const stdair_test::Cabin lCabin (lA);

  // lCabin::type
  if (boost::is_same<stdair_test::BookingClass,
                     stdair_test::Cabin::child>::value) {
    STDAIR_LOG_DEBUG ("The type of the child of a Cabin is a BookingClass");

  } else {
    STDAIR_LOG_DEBUG ("The type of " << lCabin.toString()
                              << " is unknown");
  }

  if (boost::is_same<boost::mpl::at_c<types, 1>::type,
                     stdair_test::Cabin>::value) {
    STDAIR_LOG_DEBUG ("The 2nd type is STDAIR::Cabin");

  } else {
    STDAIR_LOG_ERROR ("Problem!");
  }

BOOST_MPL_ASSERT ((boost::is_same<boost::mpl::at_c<types, 1>::type,
                                  stdair_test::Cabin>));
}

// //////////////////////////////////////////////////////////////////////
void StdairTestLib::testServiceInitialisation() {

  // Output log File
  const std::string lLogFilename ("testServiceInitialisation.log");

  // Set the log parameters
  std::ofstream logOutputFile;

  // Open and clean the log outputfile
  logOutputFile.open (lLogFilename.c_str());
  logOutputFile.clear();

  // Initialise the stdair BOM
  const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
  stdair::STDAIR_Service stdairService (lLogParams);

  // DEBUG
  STDAIR_LOG_DEBUG ("StdAir service initialised");
}

// //////////////////////////////////////////////////////////////////////
void StdairTestLib::testBomStructureInstantiation() {

  // Test create objects.

  // Output log File
  std::string lLogFilename ("testBomStructureInstantiation.log");

  // Set the log parameters
  std::ofstream logOutputFile;
  // open and clean the log outputfile
  logOutputFile.open (lLogFilename.c_str());
  logOutputFile.clear();

  const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
  stdair::STDAIR_Service stdairService (lLogParams);

  // DEBUG
  STDAIR_LOG_DEBUG ("StdAir service initialised");

  // Step 0.0: initialisation
  // Create the root of the Bom tree (i.e., a BomRoot object)
  stdair::BomRoot& lBomRoot =
    stdair::FacBomContent::instance().create<stdair::BomRoot>();

  // Step 0.1: Inventory level
  // Create an Inventory (BA)
  const stdair::AirlineCode_T lAirlineCode ("BA");
  stdair::InventoryKey_T lInventoryKey (lAirlineCode);

  stdair::Inventory& lInventory =
    stdair::FacBomContent::instance().create<stdair::Inventory>(lInventoryKey);
  stdair::FacBomContent::linkWithParent (lInventory, lBomRoot);

  // Display the inventory
  STDAIR_LOG_DEBUG ("Inventory: " << lInventory.toString());

  // Step 0.2: Flight-date level
  // Create a FlightDate (BA15/10-JUN-2010)
  const stdair::FlightNumber_T lFlightNumber = 15;
  const stdair::Date_T lDate (2010, 6, 10);
  stdair::FlightDateKey_T lFlightDateKey (lFlightNumber, lDate);

  stdair::FlightDate& lFlightDate = stdair::FacBomContent::
    instance().create<stdair::FlightDate> (lFlightDateKey);
  stdair::FacBomContent::linkWithParent (lFlightDate, lInventory);

  // Display the flight-date
  STDAIR_LOG_DEBUG ("FlightDate: " << lFlightDate.toString());

  // Step 0.3: Segment-date level
  // Create a first SegmentDate (LHR-SYD)
  const stdair::AirportCode_T lLHR ("LHR");
  const stdair::AirportCode_T lSYD ("SYD");
  stdair::SegmentDateKey_T lSegmentDateKey (lLHR, lSYD);

  stdair::SegmentDate& lLHRSYDSegment =
    stdair::FacBomContent::
    instance().create<stdair::SegmentDate> (lSegmentDateKey);
  stdair::FacBomContent::linkWithParent (lLHRSYDSegment, lFlightDate);

  // Display the segment-date
  STDAIR_LOG_DEBUG ("SegmentDate: " << lLHRSYDSegment.toString());

  // Create a second SegmentDate (LHR-BKK)
  const stdair::AirportCode_T lBKK ("BKK");
  lSegmentDateKey = stdair::SegmentDateKey_T (lLHR, lBKK);

  stdair::SegmentDate& lLHRBKKSegment =
    stdair::FacBomContent::
    instance().create<stdair::SegmentDate> (lSegmentDateKey);
  stdair::FacBomContent::linkWithParent (lLHRBKKSegment, lFlightDate);

  // Display the segment-date
  STDAIR_LOG_DEBUG ("SegmentDate: " << lLHRBKKSegment.toString());

  // Create a third SegmentDate (BKK-SYD)
  lSegmentDateKey = stdair::SegmentDateKey_T (lBKK, lSYD);

  stdair::SegmentDate& lBKKSYDSegment =
    stdair::FacBomContent::
    instance().create<stdair::SegmentDate> (lSegmentDateKey);
  stdair::FacBomContent::linkWithParent (lBKKSYDSegment, lFlightDate);

  // Display the segment-date
  STDAIR_LOG_DEBUG ("SegmentDate: " << lBKKSYDSegment.toString());

  // Step 0.4: Leg-date level
  // Create a first LegDate (LHR)
  stdair::LegDateKey_T lLegDateKey (lLHR);

  stdair::LegDate& lLHRLeg =
    stdair::FacBomContent::instance().create<stdair::LegDate> (lLegDateKey);
  stdair::FacBomContent::linkWithParent<stdair::LegDate>(lLHRLeg, lFlightDate);

  // Display the leg-date
  STDAIR_LOG_DEBUG ("LegDate: " << lLHRLeg.toString());

  // Create a second LegDate (BKK)
  lLegDateKey = stdair::LegDateKey_T (lBKK);

  stdair::LegDate& lBKKLeg =
    stdair::FacBomContent::instance().create<stdair::LegDate> (lLegDateKey);
  stdair::FacBomContent::linkWithParent (lBKKLeg, lFlightDate);

  // Display the leg-date
  STDAIR_LOG_DEBUG ("LegDate: " << lBKKLeg.toString());

  // Step 0.5: segment-cabin level
  // Create a SegmentCabin (Y) of the Segment LHR-BKK;
  const stdair::CabinCode_T lY ("Y");
  stdair::SegmentCabinKey_T lYSegmentCabinKey (lY);

  stdair::SegmentCabin& lLHRBKKSegmentYCabin =
    stdair::FacBomContent::
    instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
  stdair::FacBomContent::
    linkWithParent (lLHRBKKSegmentYCabin, lLHRBKKSegment);

  // Display the segment-cabin
  STDAIR_LOG_DEBUG ("SegmentCabin: " << lLHRBKKSegmentYCabin.toString());

  // Create a SegmentCabin (Y) of the Segment BKK-SYD;
  stdair::SegmentCabin& lBKKSYDSegmentYCabin =
    stdair::FacBomContent::
    instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
  stdair::FacBomContent::
    linkWithParent (lBKKSYDSegmentYCabin, lBKKSYDSegment);

  // Display the segment-cabin
  STDAIR_LOG_DEBUG ("SegmentCabin: " << lBKKSYDSegmentYCabin.toString());

  // Create a SegmentCabin (Y) of the Segment LHR-SYD;
  stdair::SegmentCabin& lLHRSYDSegmentYCabin =
    stdair::FacBomContent::
    instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
  stdair::FacBomContent::
    linkWithParent (lLHRSYDSegmentYCabin, lLHRSYDSegment);

  // Display the segment-cabin
  STDAIR_LOG_DEBUG ("SegmentCabin: " << lLHRSYDSegmentYCabin.toString());

  // Step 0.6: leg-cabin level
  // Create a LegCabin (Y) of the Leg LHR-BKK;
  stdair::LegCabinKey_T lYLegCabinKey (lY);

  stdair::LegCabin& lLHRLegYCabin =
    stdair::FacBomContent::instance().create<stdair::LegCabin> (lYLegCabinKey);
  stdair::FacBomContent::linkWithParent (lLHRLegYCabin, lLHRLeg);

  // Display the leg-cabin
  STDAIR_LOG_DEBUG ("LegCabin: " << lLHRLegYCabin.toString());

  // Create a LegCabin (Y) of the Leg BKK-SYD;
  stdair::LegCabin& lBKKLegYCabin =
    stdair::FacBomContent::instance().create<stdair::LegCabin> (lYLegCabinKey);
  stdair::FacBomContent::linkWithParent (lBKKLegYCabin, lBKKLeg);

  // Display the leg-cabin
  STDAIR_LOG_DEBUG ("LegCabin: " << lBKKLegYCabin.toString());

  // Step 0.7: booking class level
  // Create a BookingClass (Q) of the Segment LHR-BKK, cabin Y;
  const stdair::ClassCode_T lQ ("Q");
  stdair::BookingClassKey_T lQBookingClassKey (lQ);

  stdair::BookingClass& lLHRBKKSegmentYCabinQClass =
    stdair::FacBomContent::
    instance().create<stdair::BookingClass> (lQBookingClassKey);
  stdair::FacBomContent::
    linkWithParent (lLHRBKKSegmentYCabinQClass, lLHRBKKSegmentYCabin);

  // Display the booking class
  STDAIR_LOG_DEBUG ("BookingClass: "
                    << lLHRBKKSegmentYCabinQClass.toString());

  // Browse the BomRoot and display the created objects.
  STDAIR_LOG_DEBUG ("Browse the BomRoot");

  const stdair::InventoryList_T& lInventoryList = lBomRoot.getInventoryList();
  for (stdair::InventoryList_T::iterator itInv = lInventoryList.begin();
       itInv != lInventoryList.end(); ++itInv) {
    const stdair::Inventory& lCurrentInventory = *itInv;
    STDAIR_LOG_DEBUG ("Inventory: " << lCurrentInventory.toString());

    const stdair::FlightDateMap_T& lFlightDateMap =
      lCurrentInventory.getFlightDateMap ();
    for (stdair::FlightDateMap_T::iterator itFlightDate =
           lFlightDateMap.begin();
         itFlightDate != lFlightDateMap.end(); ++itFlightDate) {
      const stdair::FlightDate* lCurrentFlightDate = itFlightDate->second;
      STDAIR_LOG_DEBUG ("FlightDate: " << lCurrentFlightDate->describeKey());
    }
  }

  // Close the Log outputFile
  logOutputFile.close();
}

// //////////////////////////////////////////////////////////////////////
bool StdairTestLib::testErrorCase() {
  return false;
}
<commit_msg>[dev] Adapted to the new stdair.<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <iostream>
#include <fstream>
#include <string>
// MPL
#include <boost/mpl/push_back.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/type_traits/is_same.hpp>
// StdAir
#include <stdair/STDAIR_Service.hpp>
#include <stdair/STDAIR_Types.hpp>
#include <stdair/service/Logger.hpp>
#include <test/stdair/StdairTestLib.hpp>

/**
 * Namespace gathering classes and structures for test purposes
 */
namespace stdair_test {

  /** BookingClass */
  struct BookingClass {
    std::string _classCode;
    /** Constructor. */
    BookingClass (const std::string& iClassCode)
      : _classCode (iClassCode) {
    }

    /** Display .*/
    std::string toString() const {
      std::ostringstream oStr;
      oStr << _classCode;
      return oStr.str();
    }
  };

  /** Cabin */
  struct Cabin {
    BookingClass _bookingClass;
    Cabin (const BookingClass& iBkgClass)
      : _bookingClass (iBkgClass) {
    }

    /** Display .*/
    std::string toString() const {
      std::ostringstream oStr;
      oStr << _bookingClass._classCode;
      return oStr.str();
    }

    /** Child type. */
    typedef BookingClass child;
  };
}

// //////////////////////////////////////////////////////////////////////
void StdairTestLib::testMPLStructure() {

  // Output log File
  const std::string lLogFilename ("testMPLStructure.log");

  // Set the log parameters
  std::ofstream logOutputFile;

  // Open and clean the log outputfile
  logOutputFile.open (lLogFilename.c_str());
  logOutputFile.clear();

  // Initialise the stdair BOM
  const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
  stdair::STDAIR_Service stdairService (lLogParams);

  // DEBUG
  STDAIR_LOG_DEBUG ("StdAir service initialised");

  typedef boost::mpl::vector<stdair_test::BookingClass> MPL_BookingClass;
  typedef boost::mpl::push_back<MPL_BookingClass,
                                stdair_test::Cabin>::type types;

  const stdair_test::BookingClass lA ("A");
  const stdair_test::Cabin lCabin (lA);

  // lCabin::type
  if (boost::is_same<stdair_test::BookingClass,
                     stdair_test::Cabin::child>::value) {
    STDAIR_LOG_DEBUG ("The type of the child of a Cabin is a BookingClass");

  } else {
    STDAIR_LOG_DEBUG ("The type of " << lCabin.toString()
                              << " is unknown");
  }

  if (boost::is_same<boost::mpl::at_c<types, 1>::type,
                     stdair_test::Cabin>::value) {
    STDAIR_LOG_DEBUG ("The 2nd type is STDAIR::Cabin");

  } else {
    STDAIR_LOG_ERROR ("Problem!");
  }

BOOST_MPL_ASSERT ((boost::is_same<boost::mpl::at_c<types, 1>::type,
                                  stdair_test::Cabin>));
}

// //////////////////////////////////////////////////////////////////////
void StdairTestLib::testServiceInitialisation() {

  // Output log File
  const std::string lLogFilename ("testServiceInitialisation.log");

  // Set the log parameters
  std::ofstream logOutputFile;

  // Open and clean the log outputfile
  logOutputFile.open (lLogFilename.c_str());
  logOutputFile.clear();

  // Initialise the stdair BOM
  const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
  stdair::STDAIR_Service stdairService (lLogParams);

  // DEBUG
  STDAIR_LOG_DEBUG ("StdAir service initialised");
}

// //////////////////////////////////////////////////////////////////////
void StdairTestLib::testBomStructureInstantiation() {

  // Test create objects.

  // Output log File
  std::string lLogFilename ("testBomStructureInstantiation.log");

  // Set the log parameters
  std::ofstream logOutputFile;
  // open and clean the log outputfile
  logOutputFile.open (lLogFilename.c_str());
  logOutputFile.clear();

  const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
  stdair::STDAIR_Service stdairService (lLogParams);

  // DEBUG
  STDAIR_LOG_DEBUG ("StdAir service initialised");

  // Close the Log outputFile
  logOutputFile.close();
}

// //////////////////////////////////////////////////////////////////////
bool StdairTestLib::testErrorCase() {
  return false;
}
<|endoftext|>


<commit_before>#include "storage/diff_scheme/diff_manager.hpp"
#include "storage/diff_scheme/diff_scheme_checker.hpp"

#include "platform/platform.hpp"

#include "coding/internal/file_data.hpp"

#include "base/assert.hpp"
#include "base/cancellable.hpp"

#include <algorithm>

#include "3party/Alohalytics/src/alohalytics.h"

namespace
{
bool IsDiffsAvailable(storage::diffs::NameDiffInfoMap const & diffs)
{
  return std::any_of(diffs.cbegin(), diffs.cend(),
                     [](auto const & d) { return d.second.m_isApplied == false; });
}
}  // namespace

namespace storage
{
namespace diffs
{
void Manager::Load(LocalMapsInfo && info)
{
  LocalMapsInfo localMapsInfo = info;
  {
    std::lock_guard<std::mutex> lock(m_mutex);
    m_localMapsInfo = std::move(info);
  }

  m_workerThread.Push([this, localMapsInfo] {
    NameDiffInfoMap diffs = Checker::Check(localMapsInfo);

    std::lock_guard<std::mutex> lock(m_mutex);

    m_diffs = std::move(diffs);
    if (m_diffs.empty())
    {
      m_status = Status::NotAvailable;

      alohalytics::Stats::Instance().LogEvent("Downloader_DiffScheme_OnStart_fallback");
    }
    else
    {
      m_status = Status::Available;
    }

    auto & observers = m_observers;
    auto status = m_status;
    GetPlatform().RunTask(Platform::Thread::Gui, [observers, status]() mutable {
      observers.ForEach(&Observer::OnDiffStatusReceived, status);
    });
  });
}

void Manager::ApplyDiff(ApplyDiffParams && p, base::Cancellable const & cancellable,
                        Manager::OnDiffApplicationFinished const & task)
{
  using namespace generator::mwm_diff;

  m_workerThread.Push([this, p, &cancellable, task] {
    CHECK(p.m_diffFile, ());
    CHECK(p.m_oldMwmFile, ());

    auto & diffReadyPath = p.m_diffReadyPath;
    auto & diffFile = p.m_diffFile;
    auto const diffPath = diffFile->GetPath(MapOptions::Diff);
    auto result = DiffApplicationResult::Failed;

    diffFile->SyncWithDisk();

    auto const isOnDisk = diffFile->OnDisk(MapOptions::Diff);
    auto const isFilePrepared = isOnDisk || base::RenameFileX(diffReadyPath, diffPath);

    if (isFilePrepared)
    {
      // Sync with disk after renaming.
      if (!isOnDisk)
        diffFile->SyncWithDisk();

      string const oldMwmPath = p.m_oldMwmFile->GetPath(MapOptions::Map);
      string const newMwmPath = diffFile->GetPath(MapOptions::Map);
      string const diffApplyingInProgressPath = newMwmPath + DIFF_APPLYING_FILE_EXTENSION;

      result = generator::mwm_diff::ApplyDiff(oldMwmPath, diffApplyingInProgressPath, diffPath,
                                              cancellable);
      if (result == DiffApplicationResult::Ok &&
          !base::RenameFileX(diffApplyingInProgressPath, newMwmPath))
      {
        result = DiffApplicationResult::Failed;
      }

      base::DeleteFileX(diffApplyingInProgressPath);

      if (result != DiffApplicationResult::Ok)
        Platform::RemoveFileIfExists(newMwmPath);
    }

    switch (result)
    {
    case DiffApplicationResult::Ok:
    {
      diffFile->DeleteFromDisk(MapOptions::Diff);
      break;
    }
    case DiffApplicationResult::Cancelled:
      // The diff file will be deleted by storage.
      // Another way would be to leave it on disk but all consequences
      // of interacting with storage are much harder to be taken into account that way.
      break;
    case DiffApplicationResult::Failed:
    {
      diffFile->DeleteFromDisk(MapOptions::Diff);
      alohalytics::Stats::Instance().LogEvent(
          "Downloader_DiffScheme_error",
          {{"type", "patching"},
           {"error", isFilePrepared ? "Cannot apply diff" : "Cannot prepare file"}});

      std::lock_guard<std::mutex> lock(m_mutex);
      m_status = Status::NotAvailable;
      break;
    }
    }

    task(result);
  });
}

Status Manager::GetStatus() const
{
  std::lock_guard<std::mutex> lock(m_mutex);
  return m_status;
}

bool Manager::SizeFor(storage::CountryId const & countryId, uint64_t & size) const
{
  std::lock_guard<std::mutex> lock(m_mutex);
  if (m_status != Status::Available)
    return false;

  auto const it = m_diffs.find(countryId);
  if (it == m_diffs.cend())
    return false;

  size = it->second.m_size;
  return true;
}

bool Manager::SizeToDownloadFor(storage::CountryId const & countryId, uint64_t & size) const
{
  return WithNotAppliedDiff(countryId, [&size](DiffInfo const & info) { size = info.m_size; });
}

bool Manager::VersionFor(storage::CountryId const & countryId, uint64_t & v) const
{
  return WithNotAppliedDiff(countryId, [&v](DiffInfo const & info) { v = info.m_version; });
}

bool Manager::HasDiffFor(storage::CountryId const & countryId) const
{
  return WithNotAppliedDiff(countryId, [](DiffInfo const &) {});
}

void Manager::MarkAsApplied(storage::CountryId const & countryId)
{
  std::lock_guard<std::mutex> lock(m_mutex);
  auto const it = m_diffs.find(countryId);
  if (it == m_diffs.end())
    return;

  it->second.m_isApplied = true;

  if (!IsDiffsAvailable(m_diffs))
    m_status = Status::NotAvailable;
}

void Manager::RemoveDiffForCountry(storage::CountryId const & countryId)
{
  std::lock_guard<std::mutex> lock(m_mutex);
  m_diffs.erase(countryId);

  if (m_diffs.empty() || !IsDiffsAvailable(m_diffs))
    m_status = Status::NotAvailable;
}

void Manager::AbortDiffScheme()
{
  std::lock_guard<std::mutex> lock(m_mutex);
  m_status = Status::NotAvailable;
  m_diffs.clear();
}

bool Manager::IsPossibleToAutoupdate() const
{
  std::lock_guard<std::mutex> lock(m_mutex);

  if (m_status != Status::Available)
    return false;

  for (auto const & nameVersion : m_localMapsInfo.m_localMaps)
  {
    auto const it = m_diffs.find(nameVersion.first);
    if (it == m_diffs.end() || it->second.m_isApplied)
      return false;
  }
  return true;
}
}  // namespace diffs
}  // namespace storage
<commit_msg>[storage][android] review fixes<commit_after>#include "storage/diff_scheme/diff_manager.hpp"
#include "storage/diff_scheme/diff_scheme_checker.hpp"

#include "platform/platform.hpp"

#include "coding/internal/file_data.hpp"

#include "base/assert.hpp"
#include "base/cancellable.hpp"

#include <algorithm>

#include "3party/Alohalytics/src/alohalytics.h"

namespace
{
bool IsDiffsAvailable(storage::diffs::NameDiffInfoMap const & diffs)
{
  return std::any_of(diffs.cbegin(), diffs.cend(),
                     [](auto const & d) { return d.second.m_isApplied == false; });
}
}  // namespace

namespace storage
{
namespace diffs
{
void Manager::Load(LocalMapsInfo && info)
{
  LocalMapsInfo localMapsInfo = info;
  {
    std::lock_guard<std::mutex> lock(m_mutex);
    m_localMapsInfo = std::move(info);
  }

  m_workerThread.Push([this, localMapsInfo] {
    NameDiffInfoMap diffs = Checker::Check(localMapsInfo);

    std::lock_guard<std::mutex> lock(m_mutex);

    m_diffs = std::move(diffs);
    if (m_diffs.empty())
    {
      m_status = Status::NotAvailable;

      alohalytics::Stats::Instance().LogEvent("Downloader_DiffScheme_OnStart_fallback");
    }
    else
    {
      m_status = Status::Available;
    }

    auto & observers = m_observers;
    auto status = m_status;
    GetPlatform().RunTask(Platform::Thread::Gui, [observers, status]() mutable {
      observers.ForEach(&Observer::OnDiffStatusReceived, status);
    });
  });
}

void Manager::ApplyDiff(ApplyDiffParams && p, base::Cancellable const & cancellable,
                        Manager::OnDiffApplicationFinished const & task)
{
  using namespace generator::mwm_diff;

  m_workerThread.Push([this, p, &cancellable, task] {
    CHECK(p.m_diffFile, ());
    CHECK(p.m_oldMwmFile, ());

    auto & diffReadyPath = p.m_diffReadyPath;
    auto & diffFile = p.m_diffFile;
    auto const diffPath = diffFile->GetPath(MapOptions::Diff);
    auto result = DiffApplicationResult::Failed;

    diffFile->SyncWithDisk();

    auto const isOnDisk = diffFile->OnDisk(MapOptions::Diff);
    auto const isFilePrepared = isOnDisk || base::RenameFileX(diffReadyPath, diffPath);

    if (isFilePrepared)
    {
      // Sync with disk after renaming.
      if (!isOnDisk)
        diffFile->SyncWithDisk();

      string const oldMwmPath = p.m_oldMwmFile->GetPath(MapOptions::Map);
      string const newMwmPath = diffFile->GetPath(MapOptions::Map);
      string const diffApplyingInProgressPath = newMwmPath + DIFF_APPLYING_FILE_EXTENSION;

      result = generator::mwm_diff::ApplyDiff(oldMwmPath, diffApplyingInProgressPath, diffPath,
                                              cancellable);
      if (result == DiffApplicationResult::Ok &&
          !base::RenameFileX(diffApplyingInProgressPath, newMwmPath))
      {
        result = DiffApplicationResult::Failed;
      }

      base::DeleteFileX(diffApplyingInProgressPath);

      if (result != DiffApplicationResult::Ok)
        Platform::RemoveFileIfExists(newMwmPath);
    }

    switch (result)
    {
    case DiffApplicationResult::Ok:
    {
      diffFile->DeleteFromDisk(MapOptions::Diff);
      break;
    }
    case DiffApplicationResult::Cancelled:
      // The diff file will be deleted by storage.
      // Another way would be to leave it on disk but all consequences
      // of interacting with storage are much harder to be taken into account that way.
      break;
    case DiffApplicationResult::Failed:
    {
      diffFile->DeleteFromDisk(MapOptions::Diff);
      alohalytics::Stats::Instance().LogEvent(
          "Downloader_DiffScheme_error",
          {{"type", "patching"},
           {"error", isFilePrepared ? "Cannot apply diff" : "Cannot prepare file"}});

      std::lock_guard<std::mutex> lock(m_mutex);
      m_status = Status::NotAvailable;
      break;
    }
    }

    task(result);
  });
}

Status Manager::GetStatus() const
{
  std::lock_guard<std::mutex> lock(m_mutex);
  return m_status;
}

bool Manager::SizeFor(storage::CountryId const & countryId, uint64_t & size) const
{
  std::lock_guard<std::mutex> lock(m_mutex);
  if (m_status != Status::Available)
    return false;

  auto const it = m_diffs.find(countryId);
  if (it == m_diffs.cend())
    return false;

  size = it->second.m_size;
  return true;
}

bool Manager::SizeToDownloadFor(storage::CountryId const & countryId, uint64_t & size) const
{
  return WithNotAppliedDiff(countryId, [&size](DiffInfo const & info) { size = info.m_size; });
}

bool Manager::VersionFor(storage::CountryId const & countryId, uint64_t & v) const
{
  return WithNotAppliedDiff(countryId, [&v](DiffInfo const & info) { v = info.m_version; });
}

bool Manager::HasDiffFor(storage::CountryId const & countryId) const
{
  return WithNotAppliedDiff(countryId, [](DiffInfo const &) {});
}

void Manager::MarkAsApplied(storage::CountryId const & countryId)
{
  std::lock_guard<std::mutex> lock(m_mutex);
  auto it = m_diffs.find(countryId);
  if (it == m_diffs.end())
    return;

  it->second.m_isApplied = true;

  if (!IsDiffsAvailable(m_diffs))
    m_status = Status::NotAvailable;
}

void Manager::RemoveDiffForCountry(storage::CountryId const & countryId)
{
  std::lock_guard<std::mutex> lock(m_mutex);
  m_diffs.erase(countryId);

  if (m_diffs.empty() || !IsDiffsAvailable(m_diffs))
    m_status = Status::NotAvailable;
}

void Manager::AbortDiffScheme()
{
  std::lock_guard<std::mutex> lock(m_mutex);
  m_status = Status::NotAvailable;
  m_diffs.clear();
}

bool Manager::IsPossibleToAutoupdate() const
{
  std::lock_guard<std::mutex> lock(m_mutex);

  if (m_status != Status::Available)
    return false;

  for (auto const & nameVersion : m_localMapsInfo.m_localMaps)
  {
    auto const it = m_diffs.find(nameVersion.first);
    if (it == m_diffs.cend() || it->second.m_isApplied)
      return false;
  }
  return true;
}
}  // namespace diffs
}  // namespace storage
<|endoftext|>


<commit_before>server {
    listen       80;
    server_name  youth.cc;

    charset utf-8;
    root /home/work/dev/app/youth/public;

    access_log  logs/youth.app.access.log  main;

    location / {
        index  index.html index.htm index.php;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }

    # 静态文件代理
    location ~ /static/ {
        rewrite "^/static/(.*)$" /static/$1 break;
    }

    # 不记录 favicon.ico 错误日志
    location ~ (favicon.ico){
        log_not_found off;
        expires 100d;
        access_log off;
        break;
    }

    # 静态文件设置过期时间
    location ~* \.(ico|css|js|gif|jpe?g|png)(\?[0-9]+)?$ {
        expires 100d;
        break;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #location ~ \.php$ {
    # 其他请求一律单一入口处理
    location ~ / {
        rewrite "^(.*)$" /index.php  break;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root/$fastcgi_script_name;
        include        fastcgi_params;
    }
}
<commit_msg>add 参考配置<commit_after>server {
    listen       80;
    server_name  youth.cc;

    charset utf-8;
    root /home/work/dev/app/youth/public;

    access_log  logs/youth.app.access.log  main;

    location / {
        index  index.html index.htm index.php;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }

    # 静态文件代理
    location ~ /static/ {
        rewrite "^/static/(.*)$" /static/$1 break;
    }

    # 不记录 favicon.ico 错误日志
    location ~ (favicon.ico){
        log_not_found off;
        expires 100d;
        access_log off;
        break;
    }

    # 静态文件设置过期时间
    location ~* \.(ico|css|js|gif|jpe?g|png)(\?[0-9]+)?$ {
        expires 100d;
        break;
    }

    location ~ /chart.php {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_param  SCRIPT_FILENAME   /home/work/rd/analyze/chart.php;
        include        fastcgi_params;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #location ~ \.php$ {
    # 其他请求一律单一入口处理
    location ~ / {
        rewrite "^(.*)$" /index.php  break;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root/$fastcgi_script_name;
        include        fastcgi_params;
    }
}
<|endoftext|>


<commit_before>#include "moduleProcessing.h"
#include <vector>

using namespace std;

moduleProcessing::moduleProcessing(){
			E = 0.49f;
			F = 0.45f;
			Fsharp = 0.41f;
			G = 0.37f;
			Gsharp = 0.33f;
			A = 0.29f;
			Asharp = 0.25f;
			B = 0.21f;
			C = 0.17f;
			Csharp = 0.13f;
			D = 0.9f;
			Dsharp = 0.05f;

			boxSize = 0.05f;
			maxDistance = 0.01f;
}

void moduleProcessing::calculateTone(HandsHip *handship){
	Vector4 chordHand = handship->chordHandPosition;
	Vector4 hip = handship->hipPosition;

	float distance = (chordHand.x-hip.x)*(chordHand.x-hip.x) + (chordHand.y-hip.y)*(chordHand.y-hip.y);

	if(distance>E){
		this->tone = 0;
	}else if(distance>F){
		this->tone = 1;
	}else if(distance>Fsharp){
		this->tone = 2;
	}else if(distance>G){
		this->tone = 3;
	}else if(distance>Gsharp){
		this->tone = 4;
	}else if(distance>A){
		this->tone = 5;
	}else if(distance>Asharp){
		this->tone = 6;
	}else if(distance>B){
		this->tone = 7;
	}else if(distance>C){
		this->tone = 8;
	}else if(distance>Csharp){
		this->tone = 9;
	}else if(distance>D){
		this->tone = 10;
	}else if(distance>Dsharp){
		this->tone = 11;
	}
}

void moduleProcessing::calculateVolume(HandsHip *handship){
	Vector4 playingHand = handship->playingHandPosition;

	float distance = (playingHand.x-lastPlayingHand.x)*(playingHand.x-lastPlayingHand.x) + (playingHand.y-lastPlayingHand.y)*(playingHand.y-lastPlayingHand.y);

	if(distance>maxDistance){
		this->volume = 1.0;
	}else{
		this->volume = distance/maxDistance;
	}
	lastPlayingHand = playingHand;
}

float moduleProcessing::distance(HandsHip *handship){
	Vector4 chordHand = handship->chordHandPosition;
	Vector4 hip = handship->hipPosition;

	float distance = (chordHand.x-hip.x)*(chordHand.x-hip.x) + (chordHand.y-hip.y)*(chordHand.y-hip.y);

	return distance;
}

bool moduleProcessing::playedNote(HandsHip *handship){
	Vector4 hip = handship->hipPosition;
	Vector4 playingHand = handship->playingHandPosition;

	float ax = hip.x-boxSize,
		ay = hip.y-boxSize,
		bx = hip.x+boxSize,
		by = hip.y-boxSize,
		dx = hip.x+boxSize,
		dy = hip.y+boxSize;

	float bax = bx - ax,
		bay = by - ay,
		dax = dx - ax,
		day = dy -ay;

	isOnPlayingArea = true;

	if ((playingHand.x - ax) * bax + (playingHand.y - ay) * bay < 0.0) this->isOnPlayingArea = false;
	if ((playingHand.x - bx) * bax + (playingHand.y - by) * bay > 0.0) this->isOnPlayingArea = false;
	if ((playingHand.x - ax) * dax + (playingHand.y - ay) * day < 0.0) this->isOnPlayingArea = false;
	if ((playingHand.x - dx) * dax + (playingHand.y - dy) * day > 0.0) this->isOnPlayingArea = false;

	if(isOnPlayingArea && !notePlayed){
		notePlayed = true;
		return true;
	}

	if(!isOnPlayingArea) notePlayed = false;

	return false;
}<commit_msg>Fixed conflict<commit_after>#include "moduleProcessing.h"
#include <vector>

using namespace std;

moduleProcessing::moduleProcessing(){
			E = 0.49f;
			F = 0.45f;
			Fsharp = 0.41f;
			G = 0.37f;
			Gsharp = 0.33f;
			A = 0.29f;
			Asharp = 0.25f;
			B = 0.21f;
			C = 0.17f;
			Csharp = 0.13f;
			D = 0.9f;
			Dsharp = 0.05f;

			boxSize = 0.05f;
			maxDistance = 0.01f;

}

void moduleProcessing::calculateTone(HandsHip *handship){
	Vector4 chordHand = handship->chordHandPosition;
	Vector4 hip = handship->hipPosition;

	float distance = (chordHand.x-hip.x)*(chordHand.x-hip.x) + (chordHand.y-hip.y)*(chordHand.y-hip.y);

	if(distance>E){
		this->tone = 0;
	}else if(distance>F){
		this->tone = 1;
	}else if(distance>Fsharp){
		this->tone = 2;
	}else if(distance>G){
		this->tone = 3;
	}else if(distance>Gsharp){
		this->tone = 4;
	}else if(distance>A){
		this->tone = 5;
	}else if(distance>Asharp){
		this->tone = 6;
	}else if(distance>B){
		this->tone = 7;
	}else if(distance>C){
		this->tone = 8;
	}else if(distance>Csharp){
		this->tone = 9;
	}else if(distance>D){
		this->tone = 10;
	}else if(distance>Dsharp){
		this->tone = 11;
	}
}

void moduleProcessing::calculateVolume(HandsHip *handship){
	Vector4 playingHand = handship->playingHandPosition;

	float distance = (playingHand.x-lastPlayingHand.x)*(playingHand.x-lastPlayingHand.x) + (playingHand.y-lastPlayingHand.y)*(playingHand.y-lastPlayingHand.y);

	if(distance>maxDistance){
		this->volume = 1.0;
	}else{
		this->volume = distance/maxDistance;
	}
	lastPlayingHand = playingHand;
}

float moduleProcessing::distance(HandsHip *handship){
	Vector4 chordHand = handship->chordHandPosition;
	Vector4 hip = handship->hipPosition;

	float distance = (chordHand.x-hip.x)*(chordHand.x-hip.x) + (chordHand.y-hip.y)*(chordHand.y-hip.y);

	return distance;
}

bool moduleProcessing::playedNote(HandsHip *handship){
	Vector4 hip = handship->hipPosition;
	Vector4 playingHand = handship->playingHandPosition;

	float ax = hip.x-boxSize,
		ay = hip.y-boxSize,
		bx = hip.x+boxSize,
		by = hip.y-boxSize,
		dx = hip.x+boxSize,
		dy = hip.y+boxSize;

	float bax = bx - ax,
		bay = by - ay,
		dax = dx - ax,
		day = dy -ay;

	isOnPlayingArea = true;

	if ((playingHand.x - ax) * bax + (playingHand.y - ay) * bay < 0.0) this->isOnPlayingArea = false;
	if ((playingHand.x - bx) * bax + (playingHand.y - by) * bay > 0.0) this->isOnPlayingArea = false;
	if ((playingHand.x - ax) * dax + (playingHand.y - ay) * day < 0.0) this->isOnPlayingArea = false;
	if ((playingHand.x - dx) * dax + (playingHand.y - dy) * day > 0.0) this->isOnPlayingArea = false;

	if(isOnPlayingArea && !notePlayed){
		notePlayed = true;
		return true;
	}

	if(!isOnPlayingArea) notePlayed = false;

	return false;
}<|endoftext|>


<commit_before>#include "util/ocl_helper.h"
#include "util/x_error.h"
#include <algorithm>
#include <iostream>

using x_engine::ocl_error;

void show_platform_info(const cl::Platform &);
void init_cl_devices(std::priority_queue<std::shared_ptr<device>> &);

std::priority_queue<std::shared_ptr<device>> get_dev_queue() {
  std::priority_queue<std::shared_ptr<device>> q;
  init_cl_devices(q);
  if (q.size() < 1) {
    throw ocl_error("No OpenCL devices were found");
  }
  return q;
}

size_t get_device_count(const cl::Platform &p) {
  std::vector<cl::Device> devices;
  p.getDevices(CL_DEVICE_TYPE_ALL, &devices);
  return devices.size();
}

void init_cl_devices(std::priority_queue<std::shared_ptr<device>> &q) {
  cl_int err;
  cl::Context context;
  std::vector<cl::Platform> platform_list;
  err = cl::Platform::get(
      &platform_list); // TODO make check that returned value isn't error
  if (platform_list.size() < 1 || err != CL_SUCCESS) {
    throw ocl_error("No OpenCL platforms were found");
  }
  // std::for_each(platform_list.begin(), platform_list.end(),
  // show_platform_info);
  auto it =
      std::max_element(platform_list.begin(), platform_list.end(),
                       [](const cl::Platform &p1, const cl::Platform &p2) {
                         return get_device_count(p1) < get_device_count(p2);
                       });
  std::cout << "Use platform" << std::endl;
  show_platform_info(*it);
  cl_context_properties cprops[3] = {CL_CONTEXT_PLATFORM,
                                     (cl_context_properties)(*it)(), 0};
  context = cl::Context(CL_DEVICE_TYPE_ALL, cprops, NULL, NULL, &err);
  std::vector<cl::Device> devices;
  devices = context.getInfo<CL_CONTEXT_DEVICES>();
  // std::distance(platform_list, it);
  for (size_t i = 0; i < devices.size(); ++i) {
    std::shared_ptr<device> d(new device(devices[i], 0, i));
    q.push(d);
    std::cout << "Init device " << d->name << std::endl;
  }
}

void show_platform_info(const cl::Platform &platform) {
  // Get OpenCL platform name and version
  std::cout << "Platform Name: " << platform.getInfo<CL_PLATFORM_NAME>()
            << std::endl;
  std::cout << "Platform Vendor: " << platform.getInfo<CL_PLATFORM_VENDOR>()
            << std::endl;
  std::cout << "Platform Version: " << platform.getInfo<CL_PLATFORM_VERSION>()
            << std::endl;
  std::cout << "Devices: " << get_device_count(platform) << std::endl;
  std::cout << "===============================================" << std::endl;
}<commit_msg>little changes in ocl solver<commit_after>#include "util/ocl_helper.h"
#include "util/x_error.h"
#include <algorithm>
#include <iostream>

using x_engine::ocl_error;

void show_platform_info(const cl::Platform &);
void init_cl_devices(std::priority_queue<std::shared_ptr<device>> &);

std::priority_queue<std::shared_ptr<device>> get_dev_queue() {
  std::priority_queue<std::shared_ptr<device>> q;
  init_cl_devices(q);
  if (q.size() < 1) {
    throw ocl_error("No OpenCL devices were found");
  }
  return q;
}

size_t get_device_count(const cl::Platform &p) {
  std::vector<cl::Device> devices;
  p.getDevices(CL_DEVICE_TYPE_ALL, &devices);
  return devices.size();
}

void init_cl_devices(std::priority_queue<std::shared_ptr<device>> &q) {
  cl_int err;
  std::vector<cl::Platform> platform_list;
  err = cl::Platform::get(
      &platform_list); // TODO make check that returned value isn't error
  if (platform_list.size() < 1 || err != CL_SUCCESS) {
    throw ocl_error("No OpenCL platforms were found");
  }
  // std::for_each(platform_list.begin(), platform_list.end(),
  // show_platform_info);
  auto it =
      std::max_element(platform_list.begin(), platform_list.end(),
                       [](const cl::Platform &p1, const cl::Platform &p2) {
                         return get_device_count(p1) < get_device_count(p2);
                       });
  std::cout << "Use platform" << std::endl;
  show_platform_info(*it);
  std::vector<cl::Device> devices;
  it->getDevices(CL_DEVICE_TYPE_ALL, &devices);
  for (size_t i = 0; i < devices.size(); ++i) {
    std::shared_ptr<device> d(new device(devices[i], 0, i));
    q.push(d);
    std::cout << "Init device " << d->name << std::endl;
  }
}

void show_platform_info(const cl::Platform &platform) {
  // Get OpenCL platform name and version
  std::cout << "Platform Name: " << platform.getInfo<CL_PLATFORM_NAME>()
            << std::endl;
  std::cout << "Platform Vendor: " << platform.getInfo<CL_PLATFORM_VENDOR>()
            << std::endl;
  std::cout << "Platform Version: " << platform.getInfo<CL_PLATFORM_VERSION>()
            << std::endl;
  std::cout << "Devices: " << get_device_count(platform) << std::endl;
  std::cout << "===============================================" << std::endl;
}<|endoftext|>


<commit_before>// Copyright (c) 2011, Christian Rorvik
// Distributed under the Simplified BSD License (See accompanying file LICENSE.txt)

#ifndef CRUNCH_CONCURRENCY_WAITABLE_HPP
#define CRUNCH_CONCURRENCY_WAITABLE_HPP

#include "crunch/base/override.hpp"

#include <utility>

namespace Crunch { namespace Concurrency {

struct Waiter
{
    virtual void Notify() = 0;

    Waiter* next;
};

template<typename F>
struct GenericWaiter : Waiter
{
    GenericWaiter(F const& f) : f(f) {}
    GenericWaiter(F&& f) : f(std::move(f)) {}
    GenericWaiter(GenericWaiter const& rhs) : f(rhs.f) {}
    GenericWaiter& operator = (GenericWaiter const& rhs) { f = rhs.f; return *this; }

    virtual void Notify() CRUNCH_OVERRIDE
    {
        f();
    }

    F f;
};

template<typename F>
GenericWaiter<F> MakeWaiter(F const& f)
{
    return GenericWaiter<F>(f);
}

template<typename F>
GenericWaiter<F> MakeWaiter(F&& f)
{
    return GenericWaiter<F>(std::move(f));
}

struct IWaitable
{
    virtual void AddWaiter(Waiter* waiter) = 0;

    // Must not return until any callbacks on waiter has completed
    virtual void RemoveWaiter(Waiter* waiter) = 0;

    virtual bool IsOrderDependent() const = 0;

    virtual ~IWaitable() { }
};

enum WaitMode
{
    WAIT_MODE_POLL,
    WAIT_MODE_YIELD_PREEMTIVE,
    WAIT_MODE_YIELD_COOPERATIVE
};

void WaitFor(IWaitable& waitable, WaitMode waitMode = WAIT_MODE_YIELD_COOPERATIVE);
void WaitForAll(IWaitable** waitables, std::size_t count, WaitMode waitMode = WAIT_MODE_YIELD_COOPERATIVE);
void WaitForAny(IWaitable** waitables, std::size_t count, WaitMode waitMode = WAIT_MODE_YIELD_COOPERATIVE);

}}

#endif
<commit_msg>crunch_concurrency - Added RemoveWaitFromList utility function<commit_after>// Copyright (c) 2011, Christian Rorvik
// Distributed under the Simplified BSD License (See accompanying file LICENSE.txt)

#ifndef CRUNCH_CONCURRENCY_WAITABLE_HPP
#define CRUNCH_CONCURRENCY_WAITABLE_HPP

#include "crunch/base/override.hpp"

#include <utility>

namespace Crunch { namespace Concurrency {

struct Waiter
{
    virtual void Notify() = 0;

    Waiter* next;
};

/// Remove waiter from list
/// \param head Start of list
/// \param waiter The waiter to remove
/// \return New head
inline Waiter* RemoveWaiterFromList(Waiter* head, Waiter* waiter)
{
    if (head == waiter)
        return head->next;

    Waiter* current = head;
    while (current->next != nullptr)
    {
        if (current->next == waiter)
        {
            current->next = waiter->next;
            break;
        }

        current = current->next;
    }
    return head;
}

template<typename F>
struct GenericWaiter : Waiter
{
    GenericWaiter(F const& f) : f(f) {}
    GenericWaiter(F&& f) : f(std::move(f)) {}
    GenericWaiter(GenericWaiter const& rhs) : f(rhs.f) {}
    GenericWaiter& operator = (GenericWaiter const& rhs) { f = rhs.f; return *this; }

    virtual void Notify() CRUNCH_OVERRIDE
    {
        f();
    }

    F f;
};

template<typename F>
GenericWaiter<F> MakeWaiter(F const& f)
{
    return GenericWaiter<F>(f);
}

template<typename F>
GenericWaiter<F> MakeWaiter(F&& f)
{
    return GenericWaiter<F>(std::move(f));
}

struct IWaitable
{
    virtual void AddWaiter(Waiter* waiter) = 0;

    // Must not return until any callbacks on waiter has completed
    virtual void RemoveWaiter(Waiter* waiter) = 0;

    virtual bool IsOrderDependent() const = 0;

    virtual ~IWaitable() { }
};

enum WaitMode
{
    WAIT_MODE_POLL,
    WAIT_MODE_YIELD_PREEMTIVE,
    WAIT_MODE_YIELD_COOPERATIVE
};

void WaitFor(IWaitable& waitable, WaitMode waitMode = WAIT_MODE_YIELD_COOPERATIVE);
void WaitForAll(IWaitable** waitables, std::size_t count, WaitMode waitMode = WAIT_MODE_YIELD_COOPERATIVE);
void WaitForAny(IWaitable** waitables, std::size_t count, WaitMode waitMode = WAIT_MODE_YIELD_COOPERATIVE);

}}

#endif
<|endoftext|>


<commit_before>#include "../ext/Draw/CDraw3DLine.h"
#include "../ext/Draw/Draw3DLineShaders.h"

using namespace irr;
using namespace video;
using namespace scene;
using namespace ext;
using namespace draw;

CDraw3DLine* CDraw3DLine::create(IVideoDriver* _driver)
{
    return new CDraw3DLine(_driver);
}

CDraw3DLine::CDraw3DLine(IVideoDriver* _driver)
:   m_driver(_driver),
    m_desc(_driver->createGPUMeshDataFormatDesc()),
    m_meshBuffer(new IGPUMeshBuffer())
{
    auto callBack = new Draw3DLineCallBack();
    m_material.MaterialType = (E_MATERIAL_TYPE)
        m_driver->getGPUProgrammingServices()->addHighLevelShaderMaterial(
        Draw3DLineVertexShader,
        nullptr,nullptr,nullptr,
        Draw3DLineFragmentShader,
        2,EMT_SOLID,
        callBack,
        0);
    callBack->drop();

    m_meshBuffer->setPrimitiveType(EPT_LINES);
    m_meshBuffer->setMeshDataAndFormat(m_desc);
    m_meshBuffer->setIndexType(EIT_UNKNOWN);
    m_desc->drop();
}

void CDraw3DLine::draw(
    float fromX, float fromY, float fromZ,
    float toX, float toY, float toZ,
    float r, float g, float b, float a)
{
    S3DLineVertex vertices[2] = {
        {{ fromX, fromY, fromZ }, { r, g, b, a }},
        {{ toX, toY, toZ }, { r, g, b, a }}
    };

    auto upStreamBuff = m_driver->getDefaultUpStreamingBuffer();
    void* lineData[1] = { vertices };

    upStreamBuff->multi_place(2u, (const void* const*)lineData, (uint32_t*)&m_offsets,(uint32_t*)&sizes,(uint32_t*)&alignments);
    if (upStreamBuff->needsManualFlushOrInvalidate())
    {
        auto upStreamMem = upStreamBuff->getBuffer()->getBoundMemory();
        m_driver->flushMappedMemoryRanges({{ upStreamMem,m_offsets[0],sizes[0] }});
    }

    auto buff = upStreamBuff->getBuffer();
    m_desc->mapVertexAttrBuffer(buff,EVAI_ATTR0,ECPA_THREE,ECT_FLOAT,sizeof(S3DLineVertex), offsetof(S3DLineVertex, Position[0]) + m_offsets[0]);
    m_desc->mapVertexAttrBuffer(buff,EVAI_ATTR1,ECPA_FOUR,ECT_FLOAT,sizeof(S3DLineVertex), offsetof(S3DLineVertex, Color[0]) + m_offsets[0]);

    m_driver->setTransform(E4X3TS_WORLD, core::matrix4x3());
    m_driver->setMaterial(m_material);
    m_driver->drawMeshBuffer(m_meshBuffer);

    upStreamBuff->multi_free(2u,(uint32_t*)&m_offsets,(uint32_t*)&sizes,m_driver->placeFence());
}

CDraw3DLine::~CDraw3DLine()
{
    m_desc->drop();
    m_meshBuffer->drop();
}
<commit_msg>Set index count<commit_after>#include "../ext/Draw/CDraw3DLine.h"
#include "../ext/Draw/Draw3DLineShaders.h"

using namespace irr;
using namespace video;
using namespace scene;
using namespace ext;
using namespace draw;

CDraw3DLine* CDraw3DLine::create(IVideoDriver* _driver)
{
    return new CDraw3DLine(_driver);
}

CDraw3DLine::CDraw3DLine(IVideoDriver* _driver)
:   m_driver(_driver),
    m_desc(_driver->createGPUMeshDataFormatDesc()),
    m_meshBuffer(new IGPUMeshBuffer())
{
    auto callBack = new Draw3DLineCallBack();
    m_material.MaterialType = (E_MATERIAL_TYPE)
        m_driver->getGPUProgrammingServices()->addHighLevelShaderMaterial(
        Draw3DLineVertexShader,
        nullptr,nullptr,nullptr,
        Draw3DLineFragmentShader,
        2,EMT_SOLID,
        callBack,
        0);
    callBack->drop();

    m_meshBuffer->setPrimitiveType(EPT_LINES);
    m_meshBuffer->setMeshDataAndFormat(m_desc);
    m_meshBuffer->setIndexType(EIT_UNKNOWN);
    m_meshBuffer->setIndexCount(2);
    m_desc->drop();
}

void CDraw3DLine::draw(
    float fromX, float fromY, float fromZ,
    float toX, float toY, float toZ,
    float r, float g, float b, float a)
{
    S3DLineVertex vertices[2] = {
        {{ fromX, fromY, fromZ }, { r, g, b, a }},
        {{ toX, toY, toZ }, { r, g, b, a }}
    };

    auto upStreamBuff = m_driver->getDefaultUpStreamingBuffer();
    void* lineData[1] = { vertices };

    upStreamBuff->multi_place(2u, (const void* const*)lineData, (uint32_t*)&m_offsets,(uint32_t*)&sizes,(uint32_t*)&alignments);
    if (upStreamBuff->needsManualFlushOrInvalidate())
    {
        auto upStreamMem = upStreamBuff->getBuffer()->getBoundMemory();
        m_driver->flushMappedMemoryRanges({{ upStreamMem,m_offsets[0],sizes[0] }});
    }

    auto buff = upStreamBuff->getBuffer();
    m_desc->mapVertexAttrBuffer(buff,EVAI_ATTR0,ECPA_THREE,ECT_FLOAT,sizeof(S3DLineVertex), offsetof(S3DLineVertex, Position[0]) + m_offsets[0]);
    m_desc->mapVertexAttrBuffer(buff,EVAI_ATTR1,ECPA_FOUR,ECT_FLOAT,sizeof(S3DLineVertex), offsetof(S3DLineVertex, Color[0]) + m_offsets[0]);

    m_driver->setTransform(E4X3TS_WORLD, core::matrix4x3());
    m_driver->setMaterial(m_material);
    m_driver->drawMeshBuffer(m_meshBuffer);

    upStreamBuff->multi_free(2u,(uint32_t*)&m_offsets,(uint32_t*)&sizes,m_driver->placeFence());
}

CDraw3DLine::~CDraw3DLine()
{
    m_desc->drop();
    m_meshBuffer->drop();
}
<|endoftext|>