<commit_before>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#include <hpp/core/config-projector.hh>

#include <limits>

#include <boost/bind.hpp>

#include <hpp/util/debug.hh>
#include <hpp/util/timer.hh>

#include <pinocchio/multibody/liegroup/liegroup.hpp>
#include <pinocchio/multibody/model.hpp>

#include <hpp/pinocchio/configuration.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/extra-config-space.hh>
#include <hpp/pinocchio/joint.hh>
#include <hpp/pinocchio/liegroup.hh>

#include <hpp/constraints/differentiable-function.hh>
#include <hpp/constraints/solver/by-substitution.hh>

#include <hpp/core/constraint-set.hh>
// #include <hpp/constraints/explicit.hh>
// #include <hpp/constraints/implicit.hh>

namespace hpp {
  namespace core {
    using constraints::solver::BySubstitution;

    namespace {

      bool saturate (const DevicePtr_t& robot, vectorIn_t q, vectorOut_t qSat,
                     Eigen::VectorXi& sat)
      {
        bool ret = false;
        const se3::Model& model = robot->model();

        for (std::size_t i = 1; i < model.joints.size(); ++i) {
          const size_type nq = model.joints[i].nq();
          const size_type nv = model.joints[i].nv();
          const size_type idx_q = model.joints[i].idx_q();
          const size_type idx_v = model.joints[i].idx_v();
          for (size_type j = 0; j < nq; ++j) {
            const size_type iq = idx_q + j;
            const size_type iv = idx_v + std::min(j,nv-1);
            if        (q[iq] >= model.upperPositionLimit[iq]) {
              qSat [iq] = model.upperPositionLimit[iq];
              sat[iv] =  1;
              ret = true;
            } else if (q[iq] <= model.lowerPositionLimit[iq]) {
              qSat [iq] = model.lowerPositionLimit[iq];
              sat[iv] = -1;
              ret = true;
            } else {
              qSat [iq] = q [iq];
              sat[iv] =  0;
            }
          }
        }

        const hpp::pinocchio::ExtraConfigSpace& ecs = robot->extraConfigSpace();
        const size_type& d = ecs.dimension();

        for (size_type k = 0; k < d; ++k) {
          const size_type iq = model.nq + k;
          const size_type iv = model.nv + k;
          if        (q[iq] >= ecs.upper(k)) {
            sat[iv] =  1;
            qSat [iq] = ecs.upper(k);
            ret = true;
          } else if (q[iq] <= ecs.lower(k)) {
            qSat [iq] = ecs.lower(k);
            sat[iv] = -1;
            ret = true;
          } else {
            qSat [iq] = q [iq];
            sat[iv] =  0;
          }
        }
        return ret;
      }
    }

    ConfigProjector::LineSearchType ConfigProjector::defaultLineSearch_ = ConfigProjector::FixedSequence;

    void ConfigProjector::defaultLineSearch (LineSearchType ls)
    {
      defaultLineSearch_ = ls;
    }

    HPP_DEFINE_REASON_FAILURE (REASON_MAX_ITER, "Max Iterations reached");
    HPP_DEFINE_REASON_FAILURE (REASON_ERROR_INCREASED, "Error increased");
    HPP_DEFINE_REASON_FAILURE (REASON_INFEASIBLE, "Problem infeasible");

    ConfigProjectorPtr_t ConfigProjector::create (const DevicePtr_t& robot,
						  const std::string& name,
						  value_type errorThreshold,
						  size_type maxIterations)
    {
      ConfigProjector* ptr = new ConfigProjector (robot, name, errorThreshold,
						  maxIterations);
      ConfigProjectorPtr_t shPtr (ptr);
      ptr->init (shPtr);
      return shPtr;
    }

    ConfigProjectorPtr_t
    ConfigProjector::createCopy (const ConfigProjectorPtr_t cp)
    {
      ConfigProjector* ptr = new ConfigProjector (*cp);
      ConfigProjectorPtr_t shPtr (ptr);
      ptr->init (shPtr);
      return shPtr;
    }

    ConfigProjector::ConfigProjector (const DevicePtr_t& robot,
				      const std::string& name,
				      value_type _errorThreshold,
				      size_type _maxIterations) :
      Constraint (name), robot_ (robot),
      lineSearchType_ (defaultLineSearch_),
      solver_ (new BySubstitution (robot->configSpace()->vectorSpacesMerged())),
      weak_ (),
      statistics_ ("ConfigProjector " + name)
    {
      errorThreshold (_errorThreshold);
      maxIterations  (_maxIterations);
      lastIsOptional (false);
      solver_->saturation(boost::bind(saturate, robot_, _1, _2, _3));
    }

    ConfigProjector::ConfigProjector (const ConfigProjector& cp) :
      Constraint (cp), robot_ (cp.robot_),
      lineSearchType_ (cp.lineSearchType_),
      solver_ (new BySubstitution(*cp.solver_)),
      weak_ (),
      statistics_ (cp.statistics_)
    {
    }

    ConfigProjector::~ConfigProjector ()
    {
      delete solver_;
    }

    ConstraintPtr_t ConfigProjector::copy () const
    {
      return createCopy (weak_.lock ());
    }

    bool ConfigProjector::contains
    (const constraints::ImplicitPtr_t& numericalConstraint) const
    {
      return solver_->contains (numericalConstraint);
    }

    bool ConfigProjector::add (const constraints::ImplicitPtr_t& nm,
			       const segments_t& passiveDofs,
			       const std::size_t priority)
    {
      return solver_->add (nm, passiveDofs, priority);
    }

    void ConfigProjector::computeValueAndJacobian
    (ConfigurationIn_t configuration, vectorOut_t value,
     matrixOut_t reducedJacobian)
    {
      Configuration_t q (configuration);
      // q_{out} = f (q_{in})
      solver_->explicitConstraintSet().solve(q);
      solver_->computeValue<true>(q);
      solver_->updateJacobian(q); // includes the jacobian of the explicit system
      solver_->getValue(value);
      solver_->getReducedJacobian(reducedJacobian);
    }

    /// Convert vector of non locked degrees of freedom to vector of
    /// all degrees of freedom
    void ConfigProjector::uncompressVector (vectorIn_t small,
					    vectorOut_t normal) const
    {
      solver_->explicitConstraintSet ().notOutDers ().transpose ().lview
        (normal) = small;
    }

    void ConfigProjector::compressVector (vectorIn_t normal,
					  vectorOut_t small) const
    {
      small = solver_->explicitConstraintSet ().notOutDers ().transpose ().rview
        (normal);
    }

    void ConfigProjector::compressMatrix (matrixIn_t normal,
					  matrixOut_t small, bool rows) const
    {
      if (rows) {
        typedef Eigen::MatrixBlockView<matrixIn_t, Eigen::Dynamic, Eigen::Dynamic, false, false> View;
        const Eigen::ColBlockIndices& cols =
          solver_->explicitConstraintSet().notOutDers();
        small = View (normal, cols.nbIndices(), cols.indices(), cols.nbIndices(), cols.indices());
      } else {
        small = solver_->explicitConstraintSet().notOutDers().rview(normal);
      }
    }

    void ConfigProjector::uncompressMatrix (matrixIn_t small,
					    matrixOut_t normal, bool rows) const
    {
      if (rows) {
        typedef Eigen::MatrixBlockView<matrixOut_t, Eigen::Dynamic, Eigen::Dynamic, false, false> View;
        const Eigen::ColBlockIndices& cols =
          solver_->explicitConstraintSet().notOutDers();
        View (normal, cols.nbIndices(), cols.indices(), cols.nbIndices(), cols.indices()) = small;
      } else {
        solver_->explicitConstraintSet().notOutDers().lview(normal) = small;
      }
    }

    bool ConfigProjector::impl_compute (ConfigurationOut_t configuration)
    {
      // If configuration satisfies the constraint, do not modify it
      if (isSatisfied (configuration)) return true;
      if (!(robot_->computationFlag() & pinocchio::JACOBIAN))
        throw std::runtime_error("In ConfigProjector::apply: can't project a configuration if JACOBIAN computation flag is not enabled.");
      BySubstitution::Status status = (BySubstitution::Status)
        solverSolve (configuration);
      switch (status) {
        case BySubstitution::ERROR_INCREASED:
          statistics_.addFailure (REASON_ERROR_INCREASED);
          return false;
          break;
        case BySubstitution::MAX_ITERATION_REACHED:
          statistics_.addFailure (REASON_MAX_ITER);
          return false;
          break;
        case BySubstitution::INFEASIBLE:
          statistics_.addFailure (REASON_INFEASIBLE);
          return false;
          break;
        case BySubstitution::SUCCESS:
          statistics_.addSuccess();
          return true;
          break;
      }
      return false;
    }

    bool ConfigProjector::oneStep (ConfigurationOut_t configuration,
        vectorOut_t dq, const value_type&)
    {
      bool ret = solverOneStep (configuration);
      dq = solver_->lastStep ();
      return ret;
    }

    bool ConfigProjector::optimize (ConfigurationOut_t configuration,
        std::size_t maxIter)
    {
      if (!lastIsOptional()) return true;
      if (!isSatisfied (configuration)) return false;
      const size_type maxIterSave = maxIterations();
      if (maxIter != 0) maxIterations(maxIter);
      hppDout (info, "before optimization: " << configuration.transpose ());
      lastIsOptional(false);
      BySubstitution::Status status = (BySubstitution::Status)
        solverSolve (configuration);
      lastIsOptional(true);
      maxIterations(maxIterSave);
      hppDout (info, "After optimization: " << configuration.transpose ());
      if (status == BySubstitution::SUCCESS)
        return true;
      else {
	hppDout (info, "Optimization failed.");
        return false;
      }
    }

    void ConfigProjector::projectVectorOnKernel (ConfigurationIn_t from,
						 vectorIn_t velocity,
						 vectorOut_t result)
    {
      solver_->projectVectorOnKernel(from, velocity, result);
    }

    void ConfigProjector::projectOnKernel (ConfigurationIn_t from,
					   ConfigurationIn_t to,
					   ConfigurationOut_t result)
    {
      solver_->projectOnKernel (from, to, result);
    }

    void ConfigProjector::addToConstraintSet
    (const ConstraintSetPtr_t& constraintSet)
    {
      if (constraintSet->configProjector ()) {
       std::ostringstream oss
         ("Constraint set cannot store more than one config-projector");
       oss << std::endl << *constraintSet;
       throw std::runtime_error (oss.str ());
      }
      // The constraint is added at the end of the set.
      Constraint::addToConstraintSet (constraintSet);
      constraintSet->removeFirstElement ();
      constraintSet->configProjectorIt_ = constraintSet->constraints_.end () - 1;
      constraintSet->trivialOrNotConfigProjectorIt_ =
	constraintSet->configProjectorIt_;
    }

    std::ostream& ConfigProjector::print (std::ostream& os) const
    {
      return os << "Config projector: " << name () << ", contains "
        << *solver_ << decindent;
    }

    bool ConfigProjector::isSatisfied (ConfigurationIn_t config)
    {
      return solver_->isSatisfied (config);
    }

    bool ConfigProjector::isSatisfied (ConfigurationIn_t config,
				       vector_t& error)
    {
      error.resize (solver_->dimension() +
                    solver_->explicitConstraintSet().outDers().nbIndices());
      return solver_->isSatisfied (config, error);
    }

    vector_t ConfigProjector::rightHandSideFromConfig (ConfigurationIn_t config)
    {
      return solver_->rightHandSideFromConfig (config);
    }

    void ConfigProjector::rightHandSideFromConfig (
        const constraints::ImplicitPtr_t& nm,
        ConfigurationIn_t config)
    {
      if (!solver_->rightHandSideFromConfig (nm, config)) {
        throw std::runtime_error ("Function was not found in the solver.");
      }
    }

    void ConfigProjector::rightHandSide (const vector_t& small)
    {
      solver_->rightHandSide (small);
    }

    void ConfigProjector::rightHandSide (
        const constraints::ImplicitPtr_t& nm,
        vectorIn_t rhs)
    {
      if (!solver_->rightHandSide (nm, rhs)) {
        throw std::runtime_error ("Function was not found in the solver. This is probably because it is an explicit function and rhs is not supported for this type of function.");
      }
    }

    vector_t ConfigProjector::rightHandSide () const
    {
      return solver_->rightHandSide();
    }

    inline bool ConfigProjector::solverOneStep (ConfigurationOut_t config) const
    {
      switch (lineSearchType_) {
        case Backtracking  : {
                               constraints::solver::lineSearch::Backtracking ls;
                               return solver_->oneStep(config, ls);
                             }
        case ErrorNormBased: {
                               constraints::solver::lineSearch::ErrorNormBased ls;
                               return solver_->oneStep(config, ls);
                             }
        case FixedSequence : {
                               constraints::solver::lineSearch::FixedSequence ls;
                               return solver_->oneStep(config, ls);
                             }
        case Constant : {
                          constraints::solver::lineSearch::Constant ls;
                          return solver_->oneStep(config, ls);
                        }
      }
      return false;
    }

    inline int ConfigProjector::solverSolve (
        ConfigurationOut_t config) const
    {
      typedef constraints::solver::lineSearch::Backtracking Backtracking_t;
      typedef constraints::solver::lineSearch::ErrorNormBased ErrorNormBased_t;
      typedef constraints::solver::lineSearch::FixedSequence FixedSequence_t;
      typedef constraints::solver::lineSearch::Constant Constant_t;

      switch (lineSearchType_) {
        case Backtracking  : {
                               Backtracking_t ls;
                               return solver_->solve(config, ls);
                             }
        case ErrorNormBased: {
                               ErrorNormBased_t ls;
                               return solver_->solve(config, ls);
                             }
        case FixedSequence : {
                               FixedSequence_t ls;
                               return solver_->solve(config, ls);
                             }
        case Constant : {
                          Constant_t ls;
                          return solver_->solve(config, ls);
                        }
      }
      throw std::runtime_error ("Unknow line search type");
      return BySubstitution::MAX_ITERATION_REACHED;
    }

    void ConfigProjector::lastIsOptional (bool optional)
    {
      solver_->lastIsOptional(optional);
    }

    bool ConfigProjector::lastIsOptional () const
    {
      return solver_->lastIsOptional();
    }

    size_type ConfigProjector::numberFreeVariables () const
    {
      return solver_->numberFreeVariables ();
    }

    size_type ConfigProjector::numberNonLockedDof () const
    {
      return numberFreeVariables ();
    }

    size_type ConfigProjector::dimension () const
    {
      return solver_->reducedDimension();
    }

    void ConfigProjector::maxIterations (size_type iterations)
    {
      solver_->maxIterations(iterations);
    }

    size_type ConfigProjector::maxIterations () const
    {
      return solver_->maxIterations();
    }

    void ConfigProjector::errorThreshold (const value_type& threshold)
    {
      solver_->errorThreshold(threshold);
      solver_->inequalityThreshold(threshold);
    }

    value_type ConfigProjector::errorThreshold () const
    {
      return solver_->errorThreshold();
    }

    value_type ConfigProjector::residualError() const
    {
      return solver_->residualError();
    }

    const value_type& ConfigProjector::sigma() const
    {
      return solver_->sigma();
    }
  } // namespace core
} // namespace hpp
<commit_msg>Fix ConfigProjector::optimize<commit_after>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#include <hpp/core/config-projector.hh>

#include <limits>

#include <boost/bind.hpp>

#include <hpp/util/debug.hh>
#include <hpp/util/timer.hh>

#include <pinocchio/multibody/liegroup/liegroup.hpp>
#include <pinocchio/multibody/model.hpp>

#include <hpp/pinocchio/configuration.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/extra-config-space.hh>
#include <hpp/pinocchio/joint.hh>
#include <hpp/pinocchio/liegroup.hh>

#include <hpp/constraints/differentiable-function.hh>
#include <hpp/constraints/solver/by-substitution.hh>

#include <hpp/core/constraint-set.hh>
// #include <hpp/constraints/explicit.hh>
// #include <hpp/constraints/implicit.hh>

namespace hpp {
  namespace core {
    using constraints::solver::BySubstitution;
    typedef constraints::solver::lineSearch::Backtracking Backtracking_t;
    typedef constraints::solver::lineSearch::ErrorNormBased ErrorNormBased_t;
    typedef constraints::solver::lineSearch::FixedSequence FixedSequence_t;
    typedef constraints::solver::lineSearch::Constant Constant_t;

    namespace {

      bool saturate (const DevicePtr_t& robot, vectorIn_t q, vectorOut_t qSat,
                     Eigen::VectorXi& sat)
      {
        bool ret = false;
        const se3::Model& model = robot->model();

        for (std::size_t i = 1; i < model.joints.size(); ++i) {
          const size_type nq = model.joints[i].nq();
          const size_type nv = model.joints[i].nv();
          const size_type idx_q = model.joints[i].idx_q();
          const size_type idx_v = model.joints[i].idx_v();
          for (size_type j = 0; j < nq; ++j) {
            const size_type iq = idx_q + j;
            const size_type iv = idx_v + std::min(j,nv-1);
            if        (q[iq] >= model.upperPositionLimit[iq]) {
              qSat [iq] = model.upperPositionLimit[iq];
              sat[iv] =  1;
              ret = true;
            } else if (q[iq] <= model.lowerPositionLimit[iq]) {
              qSat [iq] = model.lowerPositionLimit[iq];
              sat[iv] = -1;
              ret = true;
            } else {
              qSat [iq] = q [iq];
              sat[iv] =  0;
            }
          }
        }

        const hpp::pinocchio::ExtraConfigSpace& ecs = robot->extraConfigSpace();
        const size_type& d = ecs.dimension();

        for (size_type k = 0; k < d; ++k) {
          const size_type iq = model.nq + k;
          const size_type iv = model.nv + k;
          if        (q[iq] >= ecs.upper(k)) {
            sat[iv] =  1;
            qSat [iq] = ecs.upper(k);
            ret = true;
          } else if (q[iq] <= ecs.lower(k)) {
            qSat [iq] = ecs.lower(k);
            sat[iv] = -1;
            ret = true;
          } else {
            qSat [iq] = q [iq];
            sat[iv] =  0;
          }
        }
        return ret;
      }
    }

    ConfigProjector::LineSearchType ConfigProjector::defaultLineSearch_ = ConfigProjector::FixedSequence;

    void ConfigProjector::defaultLineSearch (LineSearchType ls)
    {
      defaultLineSearch_ = ls;
    }

    HPP_DEFINE_REASON_FAILURE (REASON_MAX_ITER, "Max Iterations reached");
    HPP_DEFINE_REASON_FAILURE (REASON_ERROR_INCREASED, "Error increased");
    HPP_DEFINE_REASON_FAILURE (REASON_INFEASIBLE, "Problem infeasible");

    ConfigProjectorPtr_t ConfigProjector::create (const DevicePtr_t& robot,
						  const std::string& name,
						  value_type errorThreshold,
						  size_type maxIterations)
    {
      ConfigProjector* ptr = new ConfigProjector (robot, name, errorThreshold,
						  maxIterations);
      ConfigProjectorPtr_t shPtr (ptr);
      ptr->init (shPtr);
      return shPtr;
    }

    ConfigProjectorPtr_t
    ConfigProjector::createCopy (const ConfigProjectorPtr_t cp)
    {
      ConfigProjector* ptr = new ConfigProjector (*cp);
      ConfigProjectorPtr_t shPtr (ptr);
      ptr->init (shPtr);
      return shPtr;
    }

    ConfigProjector::ConfigProjector (const DevicePtr_t& robot,
				      const std::string& name,
				      value_type _errorThreshold,
				      size_type _maxIterations) :
      Constraint (name), robot_ (robot),
      lineSearchType_ (defaultLineSearch_),
      solver_ (new BySubstitution (robot->configSpace()->vectorSpacesMerged())),
      weak_ (),
      statistics_ ("ConfigProjector " + name)
    {
      errorThreshold (_errorThreshold);
      maxIterations  (_maxIterations);
      lastIsOptional (false);
      solver_->saturation(boost::bind(saturate, robot_, _1, _2, _3));
    }

    ConfigProjector::ConfigProjector (const ConfigProjector& cp) :
      Constraint (cp), robot_ (cp.robot_),
      lineSearchType_ (cp.lineSearchType_),
      solver_ (new BySubstitution(*cp.solver_)),
      weak_ (),
      statistics_ (cp.statistics_)
    {
    }

    ConfigProjector::~ConfigProjector ()
    {
      delete solver_;
    }

    ConstraintPtr_t ConfigProjector::copy () const
    {
      return createCopy (weak_.lock ());
    }

    bool ConfigProjector::contains
    (const constraints::ImplicitPtr_t& numericalConstraint) const
    {
      return solver_->contains (numericalConstraint);
    }

    bool ConfigProjector::add (const constraints::ImplicitPtr_t& nm,
			       const segments_t& passiveDofs,
			       const std::size_t priority)
    {
      return solver_->add (nm, passiveDofs, priority);
    }

    void ConfigProjector::computeValueAndJacobian
    (ConfigurationIn_t configuration, vectorOut_t value,
     matrixOut_t reducedJacobian)
    {
      Configuration_t q (configuration);
      // q_{out} = f (q_{in})
      solver_->explicitConstraintSet().solve(q);
      solver_->computeValue<true>(q);
      solver_->updateJacobian(q); // includes the jacobian of the explicit system
      solver_->getValue(value);
      solver_->getReducedJacobian(reducedJacobian);
    }

    /// Convert vector of non locked degrees of freedom to vector of
    /// all degrees of freedom
    void ConfigProjector::uncompressVector (vectorIn_t small,
					    vectorOut_t normal) const
    {
      solver_->explicitConstraintSet ().notOutDers ().transpose ().lview
        (normal) = small;
    }

    void ConfigProjector::compressVector (vectorIn_t normal,
					  vectorOut_t small) const
    {
      small = solver_->explicitConstraintSet ().notOutDers ().transpose ().rview
        (normal);
    }

    void ConfigProjector::compressMatrix (matrixIn_t normal,
					  matrixOut_t small, bool rows) const
    {
      if (rows) {
        typedef Eigen::MatrixBlockView<matrixIn_t, Eigen::Dynamic, Eigen::Dynamic, false, false> View;
        const Eigen::ColBlockIndices& cols =
          solver_->explicitConstraintSet().notOutDers();
        small = View (normal, cols.nbIndices(), cols.indices(), cols.nbIndices(), cols.indices());
      } else {
        small = solver_->explicitConstraintSet().notOutDers().rview(normal);
      }
    }

    void ConfigProjector::uncompressMatrix (matrixIn_t small,
					    matrixOut_t normal, bool rows) const
    {
      if (rows) {
        typedef Eigen::MatrixBlockView<matrixOut_t, Eigen::Dynamic, Eigen::Dynamic, false, false> View;
        const Eigen::ColBlockIndices& cols =
          solver_->explicitConstraintSet().notOutDers();
        View (normal, cols.nbIndices(), cols.indices(), cols.nbIndices(), cols.indices()) = small;
      } else {
        solver_->explicitConstraintSet().notOutDers().lview(normal) = small;
      }
    }

    bool ConfigProjector::impl_compute (ConfigurationOut_t configuration)
    {
      // If configuration satisfies the constraint, do not modify it
      if (isSatisfied (configuration)) return true;
      if (!(robot_->computationFlag() & pinocchio::JACOBIAN))
        throw std::runtime_error("In ConfigProjector::apply: can't project a configuration if JACOBIAN computation flag is not enabled.");
      BySubstitution::Status status = (BySubstitution::Status)
        solverSolve (configuration);
      switch (status) {
        case BySubstitution::ERROR_INCREASED:
          statistics_.addFailure (REASON_ERROR_INCREASED);
          return false;
          break;
        case BySubstitution::MAX_ITERATION_REACHED:
          statistics_.addFailure (REASON_MAX_ITER);
          return false;
          break;
        case BySubstitution::INFEASIBLE:
          statistics_.addFailure (REASON_INFEASIBLE);
          return false;
          break;
        case BySubstitution::SUCCESS:
          statistics_.addSuccess();
          return true;
          break;
      }
      return false;
    }

    bool ConfigProjector::oneStep (ConfigurationOut_t configuration,
        vectorOut_t dq, const value_type&)
    {
      bool ret = solverOneStep (configuration);
      dq = solver_->lastStep ();
      return ret;
    }

    bool ConfigProjector::optimize (ConfigurationOut_t configuration,
        std::size_t maxIter)
    {
      if (!lastIsOptional()) return true;
      if (!isSatisfied (configuration)) return false;
      const size_type maxIterSave = maxIterations();
      if (maxIter != 0) maxIterations(maxIter);
      hppDout (info, "before optimization: " << configuration.transpose ());
      BySubstitution::Status status;
      switch (lineSearchType_) {
        case Backtracking  : {
                               Backtracking_t ls;
                               status = solver_->solve(configuration, true, ls);
                               break;
                             }
        case ErrorNormBased: {
                               ErrorNormBased_t ls;
                               status = solver_->solve(configuration, true, ls);
                               break;
                             }
        case FixedSequence : {
                               FixedSequence_t ls;
                               status = solver_->solve(configuration, true, ls);
                               break;
                             }
        case Constant      : {
                               Constant_t ls;
                               status = solver_->solve(configuration, true, ls);
                               break;
                             }
      }
      maxIterations(maxIterSave);
      hppDout (info, "After optimization: " << configuration.transpose ());
      if (status == BySubstitution::SUCCESS)
        return true;
      else if (status == BySubstitution::INFEASIBLE && isSatisfied (configuration))
        return true;
      else {
        hppDout (info, "Optimization failed.");
        return false;
      }
    }

    void ConfigProjector::projectVectorOnKernel (ConfigurationIn_t from,
						 vectorIn_t velocity,
						 vectorOut_t result)
    {
      solver_->projectVectorOnKernel(from, velocity, result);
    }

    void ConfigProjector::projectOnKernel (ConfigurationIn_t from,
					   ConfigurationIn_t to,
					   ConfigurationOut_t result)
    {
      solver_->projectOnKernel (from, to, result);
    }

    void ConfigProjector::addToConstraintSet
    (const ConstraintSetPtr_t& constraintSet)
    {
      if (constraintSet->configProjector ()) {
       std::ostringstream oss
         ("Constraint set cannot store more than one config-projector");
       oss << std::endl << *constraintSet;
       throw std::runtime_error (oss.str ());
      }
      // The constraint is added at the end of the set.
      Constraint::addToConstraintSet (constraintSet);
      constraintSet->removeFirstElement ();
      constraintSet->configProjectorIt_ = constraintSet->constraints_.end () - 1;
      constraintSet->trivialOrNotConfigProjectorIt_ =
	constraintSet->configProjectorIt_;
    }

    std::ostream& ConfigProjector::print (std::ostream& os) const
    {
      return os << "Config projector: " << name () << ", contains "
        << *solver_ << decindent;
    }

    bool ConfigProjector::isSatisfied (ConfigurationIn_t config)
    {
      return solver_->isSatisfied (config);
    }

    bool ConfigProjector::isSatisfied (ConfigurationIn_t config,
				       vector_t& error)
    {
      error.resize (solver_->dimension() +
                    solver_->explicitConstraintSet().outDers().nbIndices());
      return solver_->isSatisfied (config, error);
    }

    vector_t ConfigProjector::rightHandSideFromConfig (ConfigurationIn_t config)
    {
      return solver_->rightHandSideFromConfig (config);
    }

    void ConfigProjector::rightHandSideFromConfig (
        const constraints::ImplicitPtr_t& nm,
        ConfigurationIn_t config)
    {
      if (!solver_->rightHandSideFromConfig (nm, config)) {
        throw std::runtime_error ("Function was not found in the solver.");
      }
    }

    void ConfigProjector::rightHandSide (const vector_t& small)
    {
      solver_->rightHandSide (small);
    }

    void ConfigProjector::rightHandSide (
        const constraints::ImplicitPtr_t& nm,
        vectorIn_t rhs)
    {
      if (!solver_->rightHandSide (nm, rhs)) {
        throw std::runtime_error ("Function was not found in the solver. This is probably because it is an explicit function and rhs is not supported for this type of function.");
      }
    }

    vector_t ConfigProjector::rightHandSide () const
    {
      return solver_->rightHandSide();
    }

    inline bool ConfigProjector::solverOneStep (ConfigurationOut_t config) const
    {
      switch (lineSearchType_) {
        case Backtracking  : {
                               Backtracking_t ls;
                               return solver_->oneStep(config, ls);
                             }
        case ErrorNormBased: {
                               ErrorNormBased_t ls;
                               return solver_->oneStep(config, ls);
                             }
        case FixedSequence : {
                               FixedSequence_t ls;
                               return solver_->oneStep(config, ls);
                             }
        case Constant : {
                          Constant_t ls;
                          return solver_->oneStep(config, ls);
                        }
      }
      return false;
    }

    inline int ConfigProjector::solverSolve (
        ConfigurationOut_t config) const
    {
      switch (lineSearchType_) {
        case Backtracking  : {
                               Backtracking_t ls;
                               return solver_->solve(config, ls);
                             }
        case ErrorNormBased: {
                               ErrorNormBased_t ls;
                               return solver_->solve(config, ls);
                             }
        case FixedSequence : {
                               FixedSequence_t ls;
                               return solver_->solve(config, ls);
                             }
        case Constant : {
                          Constant_t ls;
                          return solver_->solve(config, ls);
                        }
      }
      throw std::runtime_error ("Unknow line search type");
      return BySubstitution::MAX_ITERATION_REACHED;
    }

    void ConfigProjector::lastIsOptional (bool optional)
    {
      solver_->lastIsOptional(optional);
    }

    bool ConfigProjector::lastIsOptional () const
    {
      return solver_->lastIsOptional();
    }

    size_type ConfigProjector::numberFreeVariables () const
    {
      return solver_->numberFreeVariables ();
    }

    size_type ConfigProjector::numberNonLockedDof () const
    {
      return numberFreeVariables ();
    }

    size_type ConfigProjector::dimension () const
    {
      return solver_->reducedDimension();
    }

    void ConfigProjector::maxIterations (size_type iterations)
    {
      solver_->maxIterations(iterations);
    }

    size_type ConfigProjector::maxIterations () const
    {
      return solver_->maxIterations();
    }

    void ConfigProjector::errorThreshold (const value_type& threshold)
    {
      solver_->errorThreshold(threshold);
      solver_->inequalityThreshold(threshold);
    }

    value_type ConfigProjector::errorThreshold () const
    {
      return solver_->errorThreshold();
    }

    value_type ConfigProjector::residualError() const
    {
      return solver_->residualError();
    }

    const value_type& ConfigProjector::sigma() const
    {
      return solver_->sigma();
    }
  } // namespace core
} // namespace hpp
<|endoftext|>


<commit_before>#include "Settings.hpp"
#include "File.hpp"
#include <cstring>
#include <fstream>

void loadSettingsFromFile(std::vector<std::string> &args_, std::string settFile_)
{
    std::ifstream in(settFile_);
    if (!in.is_open())
    {
        throw (std::string("SSettings:loadSettingsFromFile: can't open settings file \"") + settFile_ + std::string("\""));
    }
    else
    {
        std::string bufRead;
        do
        {
            bufRead = readLine(in);
            args_.push_back(bufRead);
        } while (in.eof() == false);

    }
}

void SSettings::update(std::vector<std::string> &args_)
{
    for (unsigned int i = 0; i < args_.size(); i++)
    {
        if (args_[i][0] != '-')
        {
            this->taskName = args_[i];
            this->solutionName = args_[i];
        }
        else if (args_[i] == "-tera")
            this->terminateAsk = true;
        else if (args_[i] == "-was")
            this->waStop = true;
        else if (args_[i] == "-tles")
            this->tleStop = true;
        else if (args_[i] == "-errs")
            this->errStop = true;
        else if (args_[i] == "-ncs")
        {
            this->noClearStop = true;
            this->waStop = true;
        }
        else if (args_[i] == "-nocolor")
        {
            this->isColorOutputEnabled = false;
            this->okMessage = "OK";
            this->waMessage = "WA";
            this->errorMessage = "ERR";
            this->tleMessage = "TLE";

            this->color_attention = "";
            this->color_reset = "";
            this->color_ok_green = "";
            this->color_wa_red = "";

            this->string_Main_pathd = "Main path:";
            this->string_Solutiond = "Solution:";
            this->string_Patternd = "Pattern:";
            this->string_Test_folderd = "Test subfolder:";

            this->terminationAskMessage = std::string(" #  ") + waMessage + std::string("/") + errorMessage + std::string("/") + tleMessage + std::string(" existed.") + std::string("  #  ") + std::string("Do you want to stop checking?(y or n):");
        }
        else if (args_[i] ==  "-cmpf")
        {
            if (i + 1 < args_.size())
                this->cmpFunction = args_[i + 1];
            else
                throw "SSettings::update: No compare function name provided in next string";
            i += 1;
        }
        else if (args_[i] ==  "-cmpa")
        {
            if (i + 1 < args_.size())
                this->cmpOptions = args_[i + 1];
            else
                throw "SSettings::update: No compare function arguments provided in next string";
            i += 1;
        }
        else if (args_[i] ==  "-oa")
        {
            this->checkOrder = ECheckOrder::ALPHABETICAL;
        }
        else if (args_[i] ==  "-srpref")
        {

            if (i + 1 < args_.size())
                this->solutionRunPrefix = args_[i + 1];
            else
                throw "SSettings::update: No run prefix provided in next string";
            i += 1;
        }
        else if (args_[i] ==  "-grpref")
        {

            if (i + 1 < args_.size())
                this->generatorRunPrefix = args_[i + 1];
            else
                throw "SSettings::update: No run prefix provided in next string";
            i += 1;
        }
        else if (args_[i] ==  "-gena")
        {

            if (i + 1 < args_.size())
                this->generatorOptions = args_[i + 1];
            else
                throw "SSettings::update: No generator arguments provided in next string";
            i += 1;
        }
        else if (args_[i] == "-gseed")
        {
            if (i + 1 < args_.size())
                this->generatorSeed = std::stoi(args_[i + 1]);
            else
                throw "SSettings::update: No generator seed provided in next string";
            i += 1;
        }
        else if (args_[i] == "-gseedt")
        {
            srand(time(0));
            this->generatorSeed = rand();
        }
        else if (args_[i] ==  "-prpref")
        {

            if (i + 1 < args_.size())
                this->patternRunPrefix = args_[i + 1];
            else
                throw "SSettings::update: No run prefix provided in next string";
            i += 1;
        }
        else if (args_[i] ==  "-tf")
        {
            if (i + 1 < args_.size())
                this->testSubFolder = args_[i + 1];
            else
                throw "SSettings::update: No folder name provided in next string";
            i += 1;
        }
        else if (args_[i] == "-sf")
        {
            if (i + 1 < args_.size())
                this->solutionSubFolder = args_[i + 1];
            else
                throw "SSettings::update: No folder name provided in next string";
            i += 1;
        }
        else if (args_[i] == "-sn")
        {
            if (i + 1 < args_.size())
                this->solutionName = args_[i + 1];
            else
                throw "SSettings::update: No solution name provided in next string";
            i += 1;
        }
        else if (args_[i] == "-meml")
        {
	    throw "Unsupported operation";	//!!!!!!!!!!!
            if (i + 1 < args_.size())
                this->limits.virtualMemory = args_[i + 1];
            else
                throw "SSettings::update: No virtual mememory limit provided in next string";
            i += 1;
        }
        else if (args_[i] == "-stal")
        {
            if (i + 1 < args_.size())
                this->limits.stackMemory = args_[i + 1];
            else
                throw "SSettings::update: No stack memory limit provided in next string";
            i += 1;
        }
		else if (args_[i] == "-savwa")
		{
			this->waSave = true;
		}
        else if (args_[i] == "-time")
        {
            if (i + 1 < args_.size())
                this->limits.time = args_[i + 1];
            else
                throw "SSettings::update: No time limit provided in next string";
            i += 1;
        }
        else if (args_[i] == "-tn")
        {
            if (i + 1 < args_.size())
                this->testName = args_[i + 1];
            else
                throw "SSettings::update: No test name provided in next string";
            i += 1;
        }
        else if (args_[i] == "-gen")
        {
            if (i + 1 < args_.size())
                this->generatorName = args_[i + 1];
            else
                throw "SSettings::update: No generator name provided in next string";
            if (i + 2 < args_.size())
                this->generatorNumOfCalls = std::stoi(args_[i + 2]);
            else
                throw "SSettings::update: No generator number of calls provided in next string";
            i += 2;
            this->checkType = ECheckType::GENERATE;
        }
        else if (args_[i] == "-pat")
        {
            if (i + 1 < args_.size())
                this->pattern = args_[i + 1];
            else
                throw "SSettings::update: No pattern program name provided in next string";
            i += 1;
        }
        else if (args_[i] == "-tsf")
        {
            if (i + 1 < args_.size())
            {
                this->taskSuperFolder = args_[i + 1];
            }
            else
                throw "SSettings::update: No task folder provided in next string";
            i += 1;
        }
        else if (args_[i] == "-cmd")
        {
            if (i + 1 < args_.size())
            {
                if (this->taskName.size() > 0)
                    loadSettingsFromFile(args_, createFullPath(*this) + args_[i + 1]);
                else
                    loadSettingsFromFile(args_, args_[i + 1]);
            }
            else
                throw "SSettings::update: No command file provided in next string";
            i += 1;
        }
        else
        {
            throw (std::string("SSettings::update: No arg called \"") + args_[i] + std::string("\" exists"));
            continue;
        }

    }
    if (this->taskName.size() == 0)
        throw "SSettings: No solution name provided";
    this->limits.refresh();
}

std::string createFullPath(const SSettings &settings_)
{
    std::string result = settings_.taskSuperFolder;
    result += settings_.taskName;
    result += "/";
    //result += settings_.testSubFolder;
    return result;
}
<commit_msg>-cmd fix<commit_after>#include "Settings.hpp"
#include "File.hpp"
#include <cstring>
#include <fstream>
#include <iostream>

void loadSettingsFromFile(std::vector<std::string> &args_, std::string settFile_)
{
    std::ifstream in(settFile_);
    if (!in.is_open())
    {
        throw (std::string("SSettings:loadSettingsFromFile: can't open settings file \"") + settFile_ + std::string("\""));
    }
    else
    {
        std::string bufRead;
        do
        {
            bufRead = readLine(in);
            if (bufRead.size() == 0)
                continue;
            args_.push_back(bufRead);
        } while (in.eof() == false);

    }
}

void SSettings::update(std::vector<std::string> &args_)
{
    for (unsigned int i = 0; i < args_.size(); i++)
    {
        if (args_[i][0] != '-')
        {
            this->taskName = args_[i];
            this->solutionName = args_[i];
        }
        else if (args_[i] == "-tera")
            this->terminateAsk = true;
        else if (args_[i] == "-was")
            this->waStop = true;
        else if (args_[i] == "-tles")
            this->tleStop = true;
        else if (args_[i] == "-errs")
            this->errStop = true;
        else if (args_[i] == "-ncs")
        {
            this->noClearStop = true;
            this->waStop = true;
        }
        else if (args_[i] == "-nocolor")
        {
            this->isColorOutputEnabled = false;
            this->okMessage = "OK";
            this->waMessage = "WA";
            this->errorMessage = "ERR";
            this->tleMessage = "TLE";

            this->color_attention = "";
            this->color_reset = "";
            this->color_ok_green = "";
            this->color_wa_red = "";

            this->string_Main_pathd = "Main path:";
            this->string_Solutiond = "Solution:";
            this->string_Patternd = "Pattern:";
            this->string_Test_folderd = "Test subfolder:";

            this->terminationAskMessage = std::string(" #  ") + waMessage + std::string("/") + errorMessage + std::string("/") + tleMessage + std::string(" existed.") + std::string("  #  ") + std::string("Do you want to stop checking?(y or n):");
        }
        else if (args_[i] ==  "-cmpf")
        {
            if (i + 1 < args_.size())
                this->cmpFunction = args_[i + 1];
            else
                throw "SSettings::update: No compare function name provided in next string";
            i += 1;
        }
        else if (args_[i] ==  "-cmpa")
        {
            if (i + 1 < args_.size())
                this->cmpOptions = args_[i + 1];
            else
                throw "SSettings::update: No compare function arguments provided in next string";
            i += 1;
        }
        else if (args_[i] ==  "-oa")
        {
            this->checkOrder = ECheckOrder::ALPHABETICAL;
        }
        else if (args_[i] ==  "-srpref")
        {

            if (i + 1 < args_.size())
                this->solutionRunPrefix = args_[i + 1];
            else
                throw "SSettings::update: No run prefix provided in next string";
            i += 1;
        }
        else if (args_[i] ==  "-grpref")
        {

            if (i + 1 < args_.size())
                this->generatorRunPrefix = args_[i + 1];
            else
                throw "SSettings::update: No run prefix provided in next string";
            i += 1;
        }
        else if (args_[i] ==  "-gena")
        {

            if (i + 1 < args_.size())
                this->generatorOptions = args_[i + 1];
            else
                throw "SSettings::update: No generator arguments provided in next string";
            i += 1;
        }
        else if (args_[i] == "-gseed")
        {
            if (i + 1 < args_.size())
                this->generatorSeed = std::stoi(args_[i + 1]);
            else
                throw "SSettings::update: No generator seed provided in next string";
            i += 1;
        }
        else if (args_[i] == "-gseedt")
        {
            srand(time(0));
            this->generatorSeed = rand();
        }
        else if (args_[i] ==  "-prpref")
        {

            if (i + 1 < args_.size())
                this->patternRunPrefix = args_[i + 1];
            else
                throw "SSettings::update: No run prefix provided in next string";
            i += 1;
        }
        else if (args_[i] ==  "-tf")
        {
            if (i + 1 < args_.size())
                this->testSubFolder = args_[i + 1];
            else
                throw "SSettings::update: No folder name provided in next string";
            i += 1;
        }
        else if (args_[i] == "-sf")
        {
            if (i + 1 < args_.size())
                this->solutionSubFolder = args_[i + 1];
            else
                throw "SSettings::update: No folder name provided in next string";
            i += 1;
        }
        else if (args_[i] == "-sn")
        {
            if (i + 1 < args_.size())
                this->solutionName = args_[i + 1];
            else
                throw "SSettings::update: No solution name provided in next string";
            i += 1;
        }
        else if (args_[i] == "-meml")
        {
	    throw "Unsupported operation";	//!!!!!!!!!!!
            if (i + 1 < args_.size())
                this->limits.virtualMemory = args_[i + 1];
            else
                throw "SSettings::update: No virtual mememory limit provided in next string";
            i += 1;
        }
        else if (args_[i] == "-stal")
        {
            if (i + 1 < args_.size())
                this->limits.stackMemory = args_[i + 1];
            else
                throw "SSettings::update: No stack memory limit provided in next string";
            i += 1;
        }
		else if (args_[i] == "-savwa")
		{
			this->waSave = true;
		}
        else if (args_[i] == "-time")
        {
            if (i + 1 < args_.size())
                this->limits.time = args_[i + 1];
            else
                throw "SSettings::update: No time limit provided in next string";
            i += 1;
        }
        else if (args_[i] == "-tn")
        {
            if (i + 1 < args_.size())
                this->testName = args_[i + 1];
            else
                throw "SSettings::update: No test name provided in next string";
            i += 1;
        }
        else if (args_[i] == "-gen")
        {
            if (i + 1 < args_.size())
                this->generatorName = args_[i + 1];
            else
                throw "SSettings::update: No generator name provided in next string";
            if (i + 2 < args_.size())
                this->generatorNumOfCalls = std::stoi(args_[i + 2]);
            else
                throw "SSettings::update: No generator number of calls provided in next string";
            i += 2;
            this->checkType = ECheckType::GENERATE;
        }
        else if (args_[i] == "-pat")
        {
            if (i + 1 < args_.size())
                this->pattern = args_[i + 1];
            else
                throw "SSettings::update: No pattern program name provided in next string";
            i += 1;
        }
        else if (args_[i] == "-tsf")
        {
            if (i + 1 < args_.size())
            {
                this->taskSuperFolder = args_[i + 1];
            }
            else
                throw "SSettings::update: No task folder provided in next string";
            i += 1;
        }
        else if (args_[i] == "-cmd")
        {
            if (i + 1 < args_.size())
            {
                if (this->taskName.size() > 0)
                    loadSettingsFromFile(args_, createFullPath(*this) + args_[i + 1]);
                else
                    loadSettingsFromFile(args_, args_[i + 1]);
            }
            else
                throw "SSettings::update: No command file provided in next string";
            i += 1;
        }
        else
        {
            throw (std::string("SSettings::update: No arg called \"") + args_[i] + std::string("\" exists"));
            continue;
        }

    }
    if (this->taskName.size() == 0)
        throw "SSettings: No solution name provided";
    this->limits.refresh();
}

std::string createFullPath(const SSettings &settings_)
{
    std::string result = settings_.taskSuperFolder;
    result += settings_.taskName;
    result += "/";
    //result += settings_.testSubFolder;
    return result;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Quick Controls module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "plugin_p.h"
#include "qtaction_p.h"
#include "qtexclusivegroup_p.h"
#include "qtmenu_p.h"
#include "qtmenubar_p.h"
#include "qtmenuitemcontainer_p.h"
#include "qpagestatus.h"

#include <qimage.h>
#include <qqml.h>
#include <qqmlengine.h>
#include <qqmlextensionplugin.h>
#include <qquickimageprovider.h>
#include <qquickwindow.h>

QT_BEGIN_NAMESPACE

// Load icons from desktop theme
class DesktopIconProvider : public QQuickImageProvider
{
public:
    DesktopIconProvider()
        : QQuickImageProvider(QQuickImageProvider::Pixmap)
    {
    }

    QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize)
    {
        Q_UNUSED(requestedSize);
        Q_UNUSED(size);
        int pos = id.lastIndexOf('/');
        QString iconName = id.right(id.length() - pos);
        int width = requestedSize.width();
        return QIcon::fromTheme(iconName).pixmap(width);
    }
};

void StylePlugin::registerTypes(const char *uri)
{
    qmlRegisterType<QtAction>(uri, 1, 0, "Action");
    qmlRegisterType<QtExclusiveGroup>(uri, 1, 0, "ExclusiveGroup");
    qmlRegisterType<QtMenu>(uri, 1, 0, "MenuPrivate");
    qmlRegisterType<QtMenuBar>(uri, 1, 0, "MenuBarPrivate");
    qmlRegisterType<QtMenuItem>(uri, 1, 0, "MenuItem");
    qmlRegisterType<QtMenuItemContainer>(uri, 1, 0, "MenuItemContainer");
    qmlRegisterType<QtMenuSeparator>(uri, 1, 0, "MenuSeparator");
    qmlRegisterUncreatableType<QtMenuBase>(uri, 1, 0, "MenuBase",
                                           QLatin1String("Do not create objects of type MenuBase"));

    qmlRegisterUncreatableType<QPageStatus>(uri, 1, 0, "PageStatus", QLatin1String("Do not create objects of type PageStatus"));
}

void StylePlugin::initializeEngine(QQmlEngine *engine, const char *uri)
{
    Q_UNUSED(uri);
    engine->addImageProvider("desktoptheme", new DesktopIconProvider);
}

QT_END_NAMESPACE
<commit_msg>Remove unnecessary type registration<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Quick Controls module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "plugin_p.h"
#include "qtaction_p.h"
#include "qtexclusivegroup_p.h"
#include "qtmenu_p.h"
#include "qtmenubar_p.h"
#include "qpagestatus.h"

#include <qimage.h>
#include <qqml.h>
#include <qqmlengine.h>
#include <qqmlextensionplugin.h>
#include <qquickimageprovider.h>
#include <qquickwindow.h>

QT_BEGIN_NAMESPACE

// Load icons from desktop theme
class DesktopIconProvider : public QQuickImageProvider
{
public:
    DesktopIconProvider()
        : QQuickImageProvider(QQuickImageProvider::Pixmap)
    {
    }

    QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize)
    {
        Q_UNUSED(requestedSize);
        Q_UNUSED(size);
        int pos = id.lastIndexOf('/');
        QString iconName = id.right(id.length() - pos);
        int width = requestedSize.width();
        return QIcon::fromTheme(iconName).pixmap(width);
    }
};

void StylePlugin::registerTypes(const char *uri)
{
    qmlRegisterType<QtAction>(uri, 1, 0, "Action");
    qmlRegisterType<QtExclusiveGroup>(uri, 1, 0, "ExclusiveGroup");
    qmlRegisterType<QtMenu>(uri, 1, 0, "MenuPrivate");
    qmlRegisterType<QtMenuBar>(uri, 1, 0, "MenuBarPrivate");
    qmlRegisterType<QtMenuItem>(uri, 1, 0, "MenuItem");
    qmlRegisterType<QtMenuSeparator>(uri, 1, 0, "MenuSeparator");
    qmlRegisterUncreatableType<QtMenuBase>(uri, 1, 0, "MenuBase",
                                           QLatin1String("Do not create objects of type MenuBase"));

    qmlRegisterUncreatableType<QPageStatus>(uri, 1, 0, "PageStatus", QLatin1String("Do not create objects of type PageStatus"));
}

void StylePlugin::initializeEngine(QQmlEngine *engine, const char *uri)
{
    Q_UNUSED(uri);
    engine->addImageProvider("desktoptheme", new DesktopIconProvider);
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before><commit_msg>fix arrows to full stops (syntax errors)<commit_after><|endoftext|>


<commit_before>#include <list>
#include <algorithm>
#include "rtmidi/RtMidi.h"
#include "core.hpp"
#include "MidiIO.hpp"

/*
 * MIDIToCVInterface converts midi note on/off events, velocity , channel aftertouch, pitch wheel and mod weel to
 * CV
 */
struct MIDICCToCVInterface : MidiIO, Module {
	enum ParamIds {
		NUM_PARAMS
	};
	enum InputIds {
		NUM_INPUTS
	};
	enum OutputIds {
		NUM_OUTPUTS = 16
	};

	int cc[NUM_OUTPUTS];
	int ccNum[NUM_OUTPUTS];
	int ccSync[NUM_OUTPUTS];
	bool ccSyncFirst[NUM_OUTPUTS];
	bool ccNumInited[NUM_OUTPUTS];
	bool onFocus[NUM_OUTPUTS];
	float lights[NUM_OUTPUTS];

	MIDICCToCVInterface() : MidiIO(), Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS) {
		for (int i = 0; i < NUM_OUTPUTS; i++) {
			cc[i] = 0;
			ccNum[i] = i;
			ccSync[i] = 0;
			ccSyncFirst[i] = true;
			onFocus[i] = false;
		}
	}

	~MIDICCToCVInterface() {

	}

	void step();

	void processMidi(std::vector<unsigned char> msg);

	void resetMidi();

	json_t *toJson() {
		json_t *rootJ = json_object();
		addBaseJson(rootJ);
		for (int i = 0; i < NUM_OUTPUTS; i++) {
			json_object_set_new(rootJ, ("ccNum" + std::to_string(i)).c_str(), json_integer(ccNum[i]));
			if (outputs[i].active) {
				json_object_set_new(rootJ, ("ccVal" + std::to_string(i)).c_str(), json_integer(cc[i]));
			}
		}
		return rootJ;
	}

	void fromJson(json_t *rootJ) {
		baseFromJson(rootJ);
		for (int i = 0; i < NUM_OUTPUTS; i++) {
			json_t *ccNumJ = json_object_get(rootJ, ("ccNum" + std::to_string(i)).c_str());
			if (ccNumJ) {
				ccNum[i] = json_integer_value(ccNumJ);
				ccNumInited[i] = true;
			}

			json_t *ccValJ = json_object_get(rootJ, ("ccVal" + std::to_string(i)).c_str());
			if (ccValJ) {
				cc[i] = json_integer_value(ccValJ);
			}

		}
	}

	void reset() {
		resetMidi();
	}

};

void MIDICCToCVInterface::step() {
	if (isPortOpen()) {
		std::vector<unsigned char> message;

		// midiIn->getMessage returns empty vector if there are no messages in the queue
		getMessage(&message);
		while (message.size() > 0) {
			processMidi(message);
			getMessage(&message);
		}
	}

	for (int i = 0; i < NUM_OUTPUTS; i++) {

		lights[i] = ccSync[i] / 127.0;

		outputs[i].value = cc[i] / 127.0 * 10.0;
	}
}

void MIDICCToCVInterface::resetMidi() {
	for (int i = 0; i < NUM_OUTPUTS; i++) {
		cc[i] = 0;
		ccSync[i] = 0;
		ccSyncFirst[i] = true;
	}
};

void MIDICCToCVInterface::processMidi(std::vector<unsigned char> msg) {
	int channel = msg[0] & 0xf;
	int status = (msg[0] >> 4) & 0xf;
	int data1 = msg[1];
	int data2 = msg[2];

	//fprintf(stderr, "channel %d status %d data1 %d data2 %d\n", channel, status, data1,data2);

	// Filter channels
	if (this->channel >= 0 && this->channel != channel)
		return;

	if (status == 0xb) {
		for (int i = 0; i < NUM_OUTPUTS; i++) {
			if (onFocus[i]) {
				ccSync[i] = true;
				ccSyncFirst[i] = true;
				ccNum[i] = data1;
			}

			if (data1 == ccNum[i]) {
				if (ccSyncFirst[i]) {
					ccSyncFirst[i] = false;

					if (data2 < cc[i] + 2 && data2 > cc[i] - 2) {
						ccSync[i] = 0;
					} else {
						ccSync[i] = absi(data2 - cc[i]);
					}
				}

				if (ccSync[i] == 0) {
					cc[i] = data2;
				} else {
					ccSync[i] = absi(data2 - cc[i]);
				}
			}
		}
	}
}

struct CCTextField : TextField {
	void onTextChange();

	void draw(NVGcontext *vg);

	void onMouseDownOpaque(int button);

	void onMouseUpOpaque(int button);

	void onMouseLeave();

	int num;

	MIDICCToCVInterface *module;
};

void CCTextField::draw(NVGcontext *vg) {
	/* This is necessary, since the save
	 * file is loaded after constructing the widget*/
	if (module->ccNumInited[num]) {
		module->ccNumInited[num] = false;
		text = std::to_string(module->ccNum[num]);
	}

	if (module->onFocus[num]) {
		text = std::to_string(module->ccNum[num]);
	}

	TextField::draw(vg);
}

void CCTextField::onMouseUpOpaque(int button) {
	if (button == 1) {
		module->onFocus[num] = false;
	}

}

void CCTextField::onMouseDownOpaque(int button) {
	if (button == 1) {
		module->onFocus[num] = true;
	}
}

void CCTextField::onMouseLeave() {
	module->onFocus[num] = false;
}

void CCTextField::onTextChange() {
	int *ccNum = &module->ccNum[num];
	if (text.size() > 0) {
		try {
			*ccNum = std::stoi(text);
			// Only allow valid cc numbers
			if (*ccNum < 0 || *ccNum > 127 || text.size() > 3) {
				text = "";
				begin = end = 0;
				*ccNum = -1;
				return;
			}

			if (!module->ccNumInited[num] && *ccNum != std::stoi(text)) {
				module->ccSync[num] = 0;
				module->ccSyncFirst[num] = true;
			}

		} catch (...) {
			text = "";
			begin = end = 0;
			*ccNum = -1;
		}
	};
}

MIDICCToCVWidget::MIDICCToCVWidget() {
	MIDICCToCVInterface *module = new MIDICCToCVInterface();
	setModule(module);
	box.size = Vec(16 * 15, 380);

	{
		Panel *panel = new LightPanel();
		panel->box.size = box.size;
		addChild(panel);
	}

	float margin = 5;
	float labelHeight = 15;
	float yPos = margin;

	addChild(createScrew<ScrewSilver>(Vec(15, 0)));
	addChild(createScrew<ScrewSilver>(Vec(box.size.x - 30, 0)));
	addChild(createScrew<ScrewSilver>(Vec(15, 365)));
	addChild(createScrew<ScrewSilver>(Vec(box.size.x - 30, 365)));
	{
		Label *label = new Label();
		label->box.pos = Vec(box.size.x - margin - 11 * 15, margin);
		label->text = "MIDI CC to CV";
		addChild(label);
		yPos = labelHeight * 2;
	}

	{
		Label *label = new Label();
		label->box.pos = Vec(margin, yPos);
		label->text = "MIDI Interface";
		addChild(label);

		MidiChoice *midiChoice = new MidiChoice();
		midiChoice->midiModule = dynamic_cast<MidiIO *>(module);
		midiChoice->box.pos = Vec((box.size.x - 10) / 2 + margin, yPos);
		midiChoice->box.size.x = (box.size.x / 2.0) - margin;
		addChild(midiChoice);
		yPos += midiChoice->box.size.y + margin;
	}

	{
		Label *label = new Label();
		label->box.pos = Vec(margin, yPos);
		label->text = "Channel";
		addChild(label);

		ChannelChoice *channelChoice = new ChannelChoice();
		channelChoice->midiModule = dynamic_cast<MidiIO *>(module);
		channelChoice->box.pos = Vec((box.size.x - 10) / 2 + margin, yPos);
		channelChoice->box.size.x = (box.size.x / 2.0) - margin;
		addChild(channelChoice);
		yPos += channelChoice->box.size.y + margin * 3;
	}

	for (int i = 0; i < MIDICCToCVInterface::NUM_OUTPUTS; i++) {
		CCTextField *ccNumChoice = new CCTextField();
		ccNumChoice->module = module;
		ccNumChoice->num = i;
		ccNumChoice->text = std::to_string(module->ccNum[i]);
		ccNumChoice->box.pos = Vec(11 + (i % 4) * (63), yPos);
		ccNumChoice->box.size.x = 29;

		addChild(ccNumChoice);

		yPos += labelHeight + margin;
		addOutput(createOutput<PJ3410Port>(Vec((i % 4) * (63) + 10, yPos + 5), module, i));
		addChild(createValueLight<SmallLight<RedValueLight>>(Vec((i % 4) * (63) + 32, yPos + 5),
															 &module->lights[i]));

		if ((i + 1) % 4 == 0) {
			yPos += 47 + margin;
		} else {
			yPos -= labelHeight + margin;
		}
	}
}

void MIDICCToCVWidget::step() {

	ModuleWidget::step();
}
<commit_msg>Fix sync if ccNum is changed by modifying the text<commit_after>#include <list>
#include <algorithm>
#include "rtmidi/RtMidi.h"
#include "core.hpp"
#include "MidiIO.hpp"

/*
 * MIDIToCVInterface converts midi note on/off events, velocity , channel aftertouch, pitch wheel and mod weel to
 * CV
 */
struct MIDICCToCVInterface : MidiIO, Module {
	enum ParamIds {
		NUM_PARAMS
	};
	enum InputIds {
		NUM_INPUTS
	};
	enum OutputIds {
		NUM_OUTPUTS = 16
	};

	int cc[NUM_OUTPUTS];
	int ccNum[NUM_OUTPUTS];
	int ccSync[NUM_OUTPUTS];
	bool ccSyncFirst[NUM_OUTPUTS];
	bool ccNumInited[NUM_OUTPUTS];
	bool onFocus[NUM_OUTPUTS];
	float lights[NUM_OUTPUTS];

	MIDICCToCVInterface() : MidiIO(), Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS) {
		for (int i = 0; i < NUM_OUTPUTS; i++) {
			cc[i] = 0;
			ccNum[i] = i;
			ccSync[i] = 0;
			ccSyncFirst[i] = true;
			onFocus[i] = false;
		}
	}

	~MIDICCToCVInterface() {

	}

	void step();

	void processMidi(std::vector<unsigned char> msg);

	void resetMidi();

	json_t *toJson() {
		json_t *rootJ = json_object();
		addBaseJson(rootJ);
		for (int i = 0; i < NUM_OUTPUTS; i++) {
			json_object_set_new(rootJ, ("ccNum" + std::to_string(i)).c_str(), json_integer(ccNum[i]));
			if (outputs[i].active) {
				json_object_set_new(rootJ, ("ccVal" + std::to_string(i)).c_str(), json_integer(cc[i]));
			}
		}
		return rootJ;
	}

	void fromJson(json_t *rootJ) {
		baseFromJson(rootJ);
		for (int i = 0; i < NUM_OUTPUTS; i++) {
			json_t *ccNumJ = json_object_get(rootJ, ("ccNum" + std::to_string(i)).c_str());
			if (ccNumJ) {
				ccNum[i] = json_integer_value(ccNumJ);
				ccNumInited[i] = true;
			}

			json_t *ccValJ = json_object_get(rootJ, ("ccVal" + std::to_string(i)).c_str());
			if (ccValJ) {
				cc[i] = json_integer_value(ccValJ);
			}

		}
	}

	void reset() {
		resetMidi();
	}

};

void MIDICCToCVInterface::step() {
	if (isPortOpen()) {
		std::vector<unsigned char> message;

		// midiIn->getMessage returns empty vector if there are no messages in the queue
		getMessage(&message);
		while (message.size() > 0) {
			processMidi(message);
			getMessage(&message);
		}
	}

	for (int i = 0; i < NUM_OUTPUTS; i++) {

		lights[i] = ccSync[i] / 127.0;

		outputs[i].value = cc[i] / 127.0 * 10.0;
	}
}

void MIDICCToCVInterface::resetMidi() {
	for (int i = 0; i < NUM_OUTPUTS; i++) {
		cc[i] = 0;
		ccSync[i] = 0;
		ccSyncFirst[i] = true;
	}
};

void MIDICCToCVInterface::processMidi(std::vector<unsigned char> msg) {
	int channel = msg[0] & 0xf;
	int status = (msg[0] >> 4) & 0xf;
	int data1 = msg[1];
	int data2 = msg[2];

	//fprintf(stderr, "channel %d status %d data1 %d data2 %d\n", channel, status, data1,data2);

	// Filter channels
	if (this->channel >= 0 && this->channel != channel)
		return;

	if (status == 0xb) {
		for (int i = 0; i < NUM_OUTPUTS; i++) {
			if (onFocus[i]) {
				ccSync[i] = true;
				ccSyncFirst[i] = true;
				ccNum[i] = data1;
			}

			if (data1 == ccNum[i]) {
				if (ccSyncFirst[i]) {
					ccSyncFirst[i] = false;

					if (data2 < cc[i] + 2 && data2 > cc[i] - 2) {
						ccSync[i] = 0;
					} else {
						ccSync[i] = absi(data2 - cc[i]);
					}
				}

				if (ccSync[i] == 0) {
					cc[i] = data2;
				} else {
					ccSync[i] = absi(data2 - cc[i]);
				}
			}
		}
	}
}

struct CCTextField : TextField {
	void onTextChange();

	void draw(NVGcontext *vg);

	void onMouseDownOpaque(int button);

	void onMouseUpOpaque(int button);

	void onMouseLeave();

	int num;

	MIDICCToCVInterface *module;
};

void CCTextField::draw(NVGcontext *vg) {
	/* This is necessary, since the save
	 * file is loaded after constructing the widget*/
	if (module->ccNumInited[num]) {
		module->ccNumInited[num] = false;
		text = std::to_string(module->ccNum[num]);
	}

	if (module->onFocus[num]) {
		text = std::to_string(module->ccNum[num]);
	}

	TextField::draw(vg);
}

void CCTextField::onMouseUpOpaque(int button) {
	if (button == 1) {
		module->onFocus[num] = false;
	}

}

void CCTextField::onMouseDownOpaque(int button) {
	if (button == 1) {
		module->onFocus[num] = true;
	}
}

void CCTextField::onMouseLeave() {
	module->onFocus[num] = false;
}

void CCTextField::onTextChange() {
	int *ccNum = &module->ccNum[num];
	if (text.size() > 0) {
		try {
			*ccNum = std::stoi(text);
			// Only allow valid cc numbers
			if (*ccNum < 0 || *ccNum > 127 || text.size() > 3) {
				text = "";
				begin = end = 0;
				*ccNum = -1;
				return;
			}

			if (!module->ccNumInited[num]) {
				module->ccSync[num] = 0;
				module->ccSyncFirst[num] = true;
			}

		} catch (...) {
			text = "";
			begin = end = 0;
			*ccNum = -1;
		}
	};
}

MIDICCToCVWidget::MIDICCToCVWidget() {
	MIDICCToCVInterface *module = new MIDICCToCVInterface();
	setModule(module);
	box.size = Vec(16 * 15, 380);

	{
		Panel *panel = new LightPanel();
		panel->box.size = box.size;
		addChild(panel);
	}

	float margin = 5;
	float labelHeight = 15;
	float yPos = margin;

	addChild(createScrew<ScrewSilver>(Vec(15, 0)));
	addChild(createScrew<ScrewSilver>(Vec(box.size.x - 30, 0)));
	addChild(createScrew<ScrewSilver>(Vec(15, 365)));
	addChild(createScrew<ScrewSilver>(Vec(box.size.x - 30, 365)));
	{
		Label *label = new Label();
		label->box.pos = Vec(box.size.x - margin - 11 * 15, margin);
		label->text = "MIDI CC to CV";
		addChild(label);
		yPos = labelHeight * 2;
	}

	{
		Label *label = new Label();
		label->box.pos = Vec(margin, yPos);
		label->text = "MIDI Interface";
		addChild(label);

		MidiChoice *midiChoice = new MidiChoice();
		midiChoice->midiModule = dynamic_cast<MidiIO *>(module);
		midiChoice->box.pos = Vec((box.size.x - 10) / 2 + margin, yPos);
		midiChoice->box.size.x = (box.size.x / 2.0) - margin;
		addChild(midiChoice);
		yPos += midiChoice->box.size.y + margin;
	}

	{
		Label *label = new Label();
		label->box.pos = Vec(margin, yPos);
		label->text = "Channel";
		addChild(label);

		ChannelChoice *channelChoice = new ChannelChoice();
		channelChoice->midiModule = dynamic_cast<MidiIO *>(module);
		channelChoice->box.pos = Vec((box.size.x - 10) / 2 + margin, yPos);
		channelChoice->box.size.x = (box.size.x / 2.0) - margin;
		addChild(channelChoice);
		yPos += channelChoice->box.size.y + margin * 3;
	}

	for (int i = 0; i < MIDICCToCVInterface::NUM_OUTPUTS; i++) {
		CCTextField *ccNumChoice = new CCTextField();
		ccNumChoice->module = module;
		ccNumChoice->num = i;
		ccNumChoice->text = std::to_string(module->ccNum[i]);
		ccNumChoice->box.pos = Vec(11 + (i % 4) * (63), yPos);
		ccNumChoice->box.size.x = 29;

		addChild(ccNumChoice);

		yPos += labelHeight + margin;
		addOutput(createOutput<PJ3410Port>(Vec((i % 4) * (63) + 10, yPos + 5), module, i));
		addChild(createValueLight<SmallLight<RedValueLight>>(Vec((i % 4) * (63) + 32, yPos + 5),
															 &module->lights[i]));

		if ((i + 1) % 4 == 0) {
			yPos += 47 + margin;
		} else {
			yPos -= labelHeight + margin;
		}
	}
}

void MIDICCToCVWidget::step() {

	ModuleWidget::step();
}
<|endoftext|>


<commit_before><commit_msg>Use double when reading double value :-)<commit_after><|endoftext|>


<commit_before><commit_msg>-Wmisleading-indentation<commit_after><|endoftext|>


<commit_before><commit_msg>Add highbd inv_txfm unit test to support eob logic<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2015 WebAssembly Community Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <types/Void.h>
#include <types/Int32.h>
#include <types/Int64.h>
#include <types/Float32.h>
#include <types/Float64.h>
#include "Variable.h"
#include "types/Type.h"

namespace wasm_module {

    Variable::Variable(const wasm_module::Type *type) {
        setType(type);
    }

    Variable::Variable() : type_(wasm_module::Void::instance()) {
    }

    void Variable::setValue(std::vector<uint8_t> newData) {
        if (newData.size() != type_->size())
            throw InvalidDataSize();
        memcpy(value_, newData.data(), size_);
    }

    uint32_t Variable::uint32() const {
        return Int32::getUnsignedValue(*this);
    }

    int32_t Variable::int32() const {
        return Int32::getValue(*this);
    }

    Variable::Variable(uint32_t value) {
        setType(Int32::instance());
        uint32(value);
    }

    Variable::Variable(int32_t value) {
        setType(Int32::instance());
        int32(value);
    }

    void Variable::setType(const wasm_module::Type* type) {
        type_ = type;
    }

    void Variable::uint32(uint32_t value) {
        Int32::setUnsignedValue(*this, value);
    }

    void Variable::int32(int32_t value) {
        Int32::setValue(*this, value);
    }

    Variable::Variable(int64_t value) {
        setType(Int64::instance());
        Int64::setValue(*this, value);
    }

    Variable::Variable(uint64_t value) {
        setType(Int64::instance());
        Int64::setUnsignedValue(*this, value);
    }

    Variable::Variable(float value) {
        setType(Float32::instance());
        Float32::setValue(*this, value);
    }

    Variable::Variable(double value) {
        setType(Float64::instance());
        Float64::setValue(*this, value);
    }

    Variable Variable::Void() {
        return Variable(Void::instance());
    }

    float Variable::float32() const {
        return Float32::getValue(*this);
    }

    double Variable::float64() const {
        return Float64::getValue(*this);
    }

    void Variable::float32(float value) {
        Float32::setValue(*this, value);
    }

    void Variable::float64(double value) {
        Float64::setValue(*this, value);
    }

    bool Variable::isVoid() const {
        return type_ == Void::instance();
    }

    std::vector<uint8_t> Variable::data() {
        std::vector<uint8_t> result;
        result.resize(size_);
        memcpy(result.data(), value_, size_);
        return result;
    }
}<commit_msg>Ensured that the data() method of Variable only returns defined values<commit_after>/*
 * Copyright 2015 WebAssembly Community Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <types/Void.h>
#include <types/Int32.h>
#include <types/Int64.h>
#include <types/Float32.h>
#include <types/Float64.h>
#include "Variable.h"
#include "types/Type.h"

namespace wasm_module {

    Variable::Variable(const wasm_module::Type *type) {
        setType(type);
    }

    Variable::Variable() : type_(wasm_module::Void::instance()) {
    }

    void Variable::setValue(std::vector<uint8_t> newData) {
        if (newData.size() != type_->size())
            throw InvalidDataSize();
        memcpy(value_, newData.data(), size_);
    }

    uint32_t Variable::uint32() const {
        return Int32::getUnsignedValue(*this);
    }

    int32_t Variable::int32() const {
        return Int32::getValue(*this);
    }

    Variable::Variable(uint32_t value) {
        setType(Int32::instance());
        uint32(value);
    }

    Variable::Variable(int32_t value) {
        setType(Int32::instance());
        int32(value);
    }

    void Variable::setType(const wasm_module::Type* type) {
        type_ = type;
    }

    void Variable::uint32(uint32_t value) {
        Int32::setUnsignedValue(*this, value);
    }

    void Variable::int32(int32_t value) {
        Int32::setValue(*this, value);
    }

    Variable::Variable(int64_t value) {
        setType(Int64::instance());
        Int64::setValue(*this, value);
    }

    Variable::Variable(uint64_t value) {
        setType(Int64::instance());
        Int64::setUnsignedValue(*this, value);
    }

    Variable::Variable(float value) {
        setType(Float32::instance());
        Float32::setValue(*this, value);
    }

    Variable::Variable(double value) {
        setType(Float64::instance());
        Float64::setValue(*this, value);
    }

    Variable Variable::Void() {
        return Variable(Void::instance());
    }

    float Variable::float32() const {
        return Float32::getValue(*this);
    }

    double Variable::float64() const {
        return Float64::getValue(*this);
    }

    void Variable::float32(float value) {
        Float32::setValue(*this, value);
    }

    void Variable::float64(double value) {
        Float64::setValue(*this, value);
    }

    bool Variable::isVoid() const {
        return type_ == Void::instance();
    }

    std::vector<uint8_t> Variable::data() {
        std::vector<uint8_t> result;
        result.resize(type_->size());
        memcpy(result.data(), value_, type_->size());
        return result;
    }
}<|endoftext|>


<commit_before>//
// ThreadLocal.cpp
//
// $Id$
//
// Library: Foundation
// Package: Threading
// Module:  Thread
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//

#include "Poco/ThreadLocal.h"
#include "Poco/SingletonHolder.h"
#include "Poco/Thread.h"

namespace Poco {

TLSAbstractSlot::TLSAbstractSlot()
{
}

TLSAbstractSlot::~TLSAbstractSlot()
{
}

ThreadLocalStorage::ThreadLocalStorage()
{
}

ThreadLocalStorage::~ThreadLocalStorage()
{
	for (TLSMap::iterator it = _map.begin(); it != _map.end(); ++it)
	{
		delete it->second;
	}
}

TLSAbstractSlot*& ThreadLocalStorage::get(const void* key)
{
	TLSMap::iterator it = _map.find(key);
	if (it == _map.end())
		return _map.insert(TLSMap::value_type(key, 0)).first->second;
	else
		return it->second;
}

ThreadLocalStorage& ThreadLocalStorage::current()
{
	Thread* pThread = Thread::current();
	if (pThread)
	{
		return pThread->tls();
	}
	else
	{
		static SingletonHolder<ThreadLocalStorage> sh;
		return *sh.get();
	}
}

void ThreadLocalStorage::clear()
{
	Thread* pThread = Thread::current();
	if (pThread)
		pThread->clearTLS();
}

} // namespace Poco
<commit_msg>COMP (#5160): use of 'nullptr' instead of 0;<commit_after>//
// ThreadLocal.cpp
//
// $Id$
//
// Library: Foundation
// Package: Threading
// Module:  Thread
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//

#include "Poco/ThreadLocal.h"
#include "Poco/SingletonHolder.h"
#include "Poco/Thread.h"

namespace Poco {

TLSAbstractSlot::TLSAbstractSlot()
{
}

TLSAbstractSlot::~TLSAbstractSlot()
{
}

ThreadLocalStorage::ThreadLocalStorage()
{
}

ThreadLocalStorage::~ThreadLocalStorage()
{
	for (TLSMap::iterator it = _map.begin(); it != _map.end(); ++it)
	{
		delete it->second;
	}
}

TLSAbstractSlot*& ThreadLocalStorage::get(const void* key)
{
	TLSMap::iterator it = _map.find(key);
	if (it == _map.end())
		return _map.insert(TLSMap::value_type(key, nullptr)).first->second;
	else
		return it->second;
}

ThreadLocalStorage& ThreadLocalStorage::current()
{
	Thread* pThread = Thread::current();
	if (pThread)
	{
		return pThread->tls();
	}
	else
	{
		static SingletonHolder<ThreadLocalStorage> sh;
		return *sh.get();
	}
}

void ThreadLocalStorage::clear()
{
	Thread* pThread = Thread::current();
	if (pThread)
		pThread->clearTLS();
}

} // namespace Poco
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2019, Vinitha Ranganeni, Eric Pan
// 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. Neither the name of the copyright holder nor the names of its
//        contributors may be used to endorse or promote products derived from
//        this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 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.
////////////////////////////////////////////////////////////////////////////////

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/chrono.h>
#include <pybind11/eigen.h>
#include <Eigen/Geometry>
#include <chrono>
#include <cozmo_description/cozmo.hpp>
#include "actionspace/ObjectOrientedActionSpace.hpp"

namespace py = pybind11;

namespace libcozmo {
namespace python {

PYBIND11_MODULE(cozmopy, m) {
    // from aikidopy import StateSpace, Interpolated
    py::object StateSpace = py::module::import("aikidopy").attr("StateSpace");
    py::object Interpolated = py::module::import("aikidopy").attr("Interpolated");

    py::class_<libcozmo::Cozmo>(m, "Cozmo")
        .def(py::init<const std::string&>())
        .def("getCozmoSkeleton", &Cozmo::getCozmoSkeleton)
        .def("setForkliftPosition", &Cozmo::setForkliftPosition, py::arg("pos"))
        .def("createState", &Cozmo::createState, py::arg("x"), py::arg("y"), py::arg("th"))
        .def("createInterpolatedTraj", &Cozmo::createInterpolatedTraj, py::arg("waypoints"))
        .def("executeTrajectory", [](
            libcozmo::Cozmo& cozmo,
            const std::chrono::duration<double, std::milli> milliseconds,
            aikido::trajectory::TrajectoryPtr traj) {
            return cozmo.executeTrajectory(
                std::chrono::duration_cast<std::chrono::milliseconds>(milliseconds), traj);
        })
        .def("setState", [](
            libcozmo::Cozmo& cozmo,
            const double& x,
            const double& y,
            const std::vector<double>& quat) {
            Eigen::Quaterniond q(quat[0], quat[1], quat[2], quat[3]);
            cozmo.setState(x, y, q);
        });

        py::class_<libcozmo::Waypoint>(m, "Waypoint")
        .def(py::init([](const double x, const double y, const double th, const double t) {
            libcozmo::Waypoint w = {.x = x, .y = y, .th = th, .t = t};
            return w;
        }));

    py::class_<actionspace::ObjectOrientedActionSpace>(m, "ObjectOrientedActionSpace")
        .def(py::init<const std::vector<double>&,
                      const std::vector<double>&,
                      const Eigen::Vector2d&,
                      const Eigen::Vector2d&,
                      const int&>())
        .def("action_similarity", [](
            const actionspace::ObjectOrientedActionSpace& actionspace,
            const int& action_id1,
            const int& action_id2) {
            double similarity = -1;
            bool successful =
                actionspace.action_similarity(action_id1, action_id2, &similarity);
            return similarity, successful;
        })
        .def("get_action",
            &actionspace::ObjectOrientedActionSpace::get_action,
            py::arg("action_id"))
        .def("is_valid_action_id",
            &actionspace::ObjectOrientedActionSpace::is_valid_action_id,
            py::arg("action_id"))
        .def("get_generic_to_object_oriented_action", [](
            const actionspace::ObjectOrientedActionSpace& actionspace,
            const int& action_id,
            const aikido::statespace::StateSpace::State& _state){
            actionspace::ObjectOrientedActionSpace::CozmoAction action(
                0.0, Eigen::Vector3d(0, 0, 0));
            bool successful = actionspace.get_generic_to_object_oriented_action(
                action_id, _state, &action);
            return action;
        })
        .def("publish_action",
            &actionspace::ObjectOrientedActionSpace::publish_action,
            py::arg("action_id"),
            py::arg("publisher"),
            py::arg("_state"))
        .def("size", &actionspace::ObjectOrientedActionSpace::size);

        py::class_<actionspace::ObjectOrientedActionSpace::Action>(m, "Action")
            .def(py::init<const double&, const double&, const double&, const double&>())
            .def("speed", &actionspace::ObjectOrientedActionSpace::Action::speed)
            .def("aspect_ratio", &actionspace::ObjectOrientedActionSpace::Action::aspect_ratio)
            .def("edge_offset", &actionspace::ObjectOrientedActionSpace::Action::edge_offset)
            .def("heading_offset", &actionspace::ObjectOrientedActionSpace::Action::heading_offset);

        py::class_<actionspace::ObjectOrientedActionSpace::CozmoAction>(m, "CozmoAction")
            .def(py::init<const double&, const Eigen::Vector3d&>())
            .def("speed", &actionspace::ObjectOrientedActionSpace::CozmoAction::speed)
            .def("start_pose", &actionspace::ObjectOrientedActionSpace::CozmoAction::start_pose);
}

}  // namespace python
}  // namespace libcozmo
<commit_msg>removing publish action until build is resolved for action msgs<commit_after>////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2019, Vinitha Ranganeni, Eric Pan
// 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. Neither the name of the copyright holder nor the names of its
//        contributors may be used to endorse or promote products derived from
//        this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 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.
////////////////////////////////////////////////////////////////////////////////

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/chrono.h>
#include <pybind11/eigen.h>
#include <Eigen/Geometry>
#include <chrono>
#include <cozmo_description/cozmo.hpp>
#include "actionspace/ObjectOrientedActionSpace.hpp"

namespace py = pybind11;

namespace libcozmo {
namespace python {

PYBIND11_MODULE(cozmopy, m) {
    // from aikidopy import StateSpace, Interpolated
    py::object StateSpace = py::module::import("aikidopy").attr("StateSpace");
    py::object Interpolated = py::module::import("aikidopy").attr("Interpolated");

    py::class_<libcozmo::Cozmo>(m, "Cozmo")
        .def(py::init<const std::string&>())
        .def("getCozmoSkeleton", &Cozmo::getCozmoSkeleton)
        .def("setForkliftPosition", &Cozmo::setForkliftPosition, py::arg("pos"))
        .def("createState", &Cozmo::createState, py::arg("x"), py::arg("y"), py::arg("th"))
        .def("createInterpolatedTraj", &Cozmo::createInterpolatedTraj, py::arg("waypoints"))
        .def("executeTrajectory", [](
            libcozmo::Cozmo& cozmo,
            const std::chrono::duration<double, std::milli> milliseconds,
            aikido::trajectory::TrajectoryPtr traj) {
            return cozmo.executeTrajectory(
                std::chrono::duration_cast<std::chrono::milliseconds>(milliseconds), traj);
        })
        .def("setState", [](
            libcozmo::Cozmo& cozmo,
            const double& x,
            const double& y,
            const std::vector<double>& quat) {
            Eigen::Quaterniond q(quat[0], quat[1], quat[2], quat[3]);
            cozmo.setState(x, y, q);
        });

        py::class_<libcozmo::Waypoint>(m, "Waypoint")
        .def(py::init([](const double x, const double y, const double th, const double t) {
            libcozmo::Waypoint w = {.x = x, .y = y, .th = th, .t = t};
            return w;
        }));

    py::class_<actionspace::ObjectOrientedActionSpace>(m, "ObjectOrientedActionSpace")
        .def(py::init<const std::vector<double>&,
                      const std::vector<double>&,
                      const Eigen::Vector2d&,
                      const Eigen::Vector2d&,
                      const int&>())
        .def("action_similarity", [](
            const actionspace::ObjectOrientedActionSpace& actionspace,
            const int& action_id1,
            const int& action_id2) {
            double similarity = -1;
            bool successful =
                actionspace.action_similarity(action_id1, action_id2, &similarity);
            return similarity, successful;
        })
        .def("get_action",
            &actionspace::ObjectOrientedActionSpace::get_action,
            py::arg("action_id"))
        .def("is_valid_action_id",
            &actionspace::ObjectOrientedActionSpace::is_valid_action_id,
            py::arg("action_id"))
        .def("get_generic_to_object_oriented_action", [](
            const actionspace::ObjectOrientedActionSpace& actionspace,
            const int& action_id,
            const aikido::statespace::StateSpace::State& _state){
            actionspace::ObjectOrientedActionSpace::CozmoAction action(
                0.0, Eigen::Vector3d(0, 0, 0));
            bool successful = actionspace.get_generic_to_object_oriented_action(
                action_id, _state, &action);
            return action;
        })
        .def("size", &actionspace::ObjectOrientedActionSpace::size);

        py::class_<actionspace::ObjectOrientedActionSpace::Action>(m, "Action")
            .def(py::init<const double&, const double&, const double&, const double&>())
            .def("speed", &actionspace::ObjectOrientedActionSpace::Action::speed)
            .def("aspect_ratio", &actionspace::ObjectOrientedActionSpace::Action::aspect_ratio)
            .def("edge_offset", &actionspace::ObjectOrientedActionSpace::Action::edge_offset)
            .def("heading_offset", &actionspace::ObjectOrientedActionSpace::Action::heading_offset);

        py::class_<actionspace::ObjectOrientedActionSpace::CozmoAction>(m, "CozmoAction")
            .def(py::init<const double&, const Eigen::Vector3d&>())
            .def("speed", &actionspace::ObjectOrientedActionSpace::CozmoAction::speed)
            .def("start_pose", &actionspace::ObjectOrientedActionSpace::CozmoAction::start_pose);
}

}  // namespace python
}  // namespace libcozmo
<|endoftext|>