<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_PROLONGATIONS_L2_GLOBAL_HH
#define DUNE_GDT_PROLONGATIONS_L2_GLOBAL_HH

#include <dune/gdt/exceptions.hh>
#include <dune/gdt/discretefunction/reinterpret.hh>
#include <dune/gdt/projections/l2-global.hh>

namespace Dune {
namespace GDT {

template <class GridViewImp, class SourceImp, class RangeImp>
class L2GlobalProlongationLocalizableOperator
    : Stuff::Common::ConstStorageProvider<ReinterpretDiscreteFunction<SourceImp>>,
      public L2GlobalProjectionLocalizableOperator<GridViewImp, ReinterpretDiscreteFunction<SourceImp>, RangeImp>
{
  static_assert(is_const_discrete_function<SourceImp>::value, "");
  static_assert(is_discrete_function<RangeImp>::value, "");
  typedef Stuff::Common::ConstStorageProvider<ReinterpretDiscreteFunction<SourceImp>> SourceStorage;
  typedef L2GlobalProjectionLocalizableOperator<GridViewImp, ReinterpretDiscreteFunction<SourceImp>, RangeImp>
      BaseOperatorType;

public:
  typedef SourceImp SourceType;
  using typename BaseOperatorType::GridViewType;
  using typename BaseOperatorType::RangeType;

  L2GlobalProlongationLocalizableOperator(const size_t over_integrate, GridViewType grd_vw, const SourceType& src,
                                          RangeType& rng)
    : SourceStorage(new ReinterpretDiscreteFunction<SourceImp>(src))
    , BaseOperatorType(over_integrate, grd_vw, SourceStorage::access(), rng)
  {
  }

  L2GlobalProlongationLocalizableOperator(GridViewType grd_vw, const SourceType& src, RangeType& rng)
    : L2GlobalProlongationLocalizableOperator(0, grd_vw, src, rng)
  {
  }

  ///! Calls L2GlobalProjectionLocalizableOperator::apply and gives a meaningful error message.
  void apply()
  {
    try {
      BaseOperatorType::apply();
    } catch (Stuff::Exceptions::reinterpretation_error& ee) {
      DUNE_THROW(Exceptions::prolongation_error,
                 "This prolongation (using a global L2 projection) failed, because the source could not be "
                     << "reinterpreted on the given grid view!\n"
                     << "This was the original error:\n\n"
                     << ee.what());
    }
  } // ... apply(...)
}; // class L2GlobalProlongationLocalizableOperator

template <class GridViewType, class SourceSpaceType, class SourceVectorType, class RangeSpaceType,
          class RangeVectorType>
typename std::enable_if<Stuff::Grid::is_grid_layer<GridViewType>::value && is_space<SourceSpaceType>::value
                            && Stuff::LA::is_vector<SourceVectorType>::value && is_space<RangeSpaceType>::value
                            && Stuff::LA::is_vector<RangeVectorType>::value,
                        std::unique_ptr<L2GlobalProlongationLocalizableOperator<GridViewType,
                                                                                ConstDiscreteFunction<SourceSpaceType,
                                                                                SourceVectorType>,
                                                                                DiscreteFunction<RangeSpaceType,
                                                                                RangeVectorType>>>>::
    type
    make_global_l2_prolongation_localizable_operator(
        const GridViewType& grid_view, const ConstDiscreteFunction<SourceSpaceType, SourceVectorType>& source,
        DiscreteFunction<RangeSpaceType, RangeVectorType>& range, const size_t over_integrate = 0)
{
  return DSC::
      make_unique<L2GlobalProlongationLocalizableOperator<GridViewType,
                                                          ConstDiscreteFunction<SourceSpaceType, SourceVectorType>,
                                                          DiscreteFunction<RangeSpaceType, RangeVectorType>>>(
          over_integrate, grid_view, source, range);
} // ... make_global_l2_prolongation_localizable_operator(...)

template <class SourceSpaceType, class SourceVectorType, class RangeSpaceType, class RangeVectorType>
typename std::enable_if<is_space<SourceSpaceType>::value && Stuff::LA::is_vector<SourceVectorType>::value
                            && is_space<RangeSpaceType>::value && Stuff::LA::is_vector<RangeVectorType>::value,
                        std::unique_ptr<L2GlobalProlongationLocalizableOperator<
                            typename RangeSpaceType::GridViewType,
                            ConstDiscreteFunction<SourceSpaceType, SourceVectorType>,
                            DiscreteFunction<RangeSpaceType, RangeVectorType>>>>::type
make_global_l2_prolongation_localizable_operator(const ConstDiscreteFunction<SourceSpaceType, SourceVectorType>& source,
                                                 DiscreteFunction<RangeSpaceType, RangeVectorType>& range,
                                                 const size_t over_integrate = 0)
{
  return DSC::make_unique<L2GlobalProlongationLocalizableOperator<
      typename RangeSpaceType::GridViewType,
      ConstDiscreteFunction<SourceSpaceType, SourceVectorType>,
      DiscreteFunction<RangeSpaceType, RangeVectorType>>>(over_integrate, range.space().grid_view(), source, range);
} // ... make_global_l2_prolongation_localizable_operator(...)

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PROLONGATIONS_L2_GLOBAL_HH
<commit_msg>[prolongations.l2-global] add L2GlobalProlongationOperator<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_PROLONGATIONS_L2_GLOBAL_HH
#define DUNE_GDT_PROLONGATIONS_L2_GLOBAL_HH

#include <dune/gdt/exceptions.hh>
#include <dune/gdt/discretefunction/reinterpret.hh>
#include <dune/gdt/projections/l2-global.hh>

namespace Dune {
namespace GDT {

// forward
template <class GridViewImp, class FieldImp = double>
class L2GlobalProlongationOperator;

namespace internal {

template <class GridViewImp, class FieldImp>
class L2GlobalProlongationOperatorTraits
{
public:
  typedef L2GlobalProlongationOperator<GridViewImp, FieldImp> derived_type;
  typedef FieldImp FieldType;
};

} // namespace internal

template <class GridViewImp, class SourceImp, class RangeImp>
class L2GlobalProlongationLocalizableOperator
    : Stuff::Common::ConstStorageProvider<ReinterpretDiscreteFunction<SourceImp>>,
      public L2GlobalProjectionLocalizableOperator<GridViewImp, ReinterpretDiscreteFunction<SourceImp>, RangeImp>
{
  static_assert(is_const_discrete_function<SourceImp>::value, "");
  static_assert(is_discrete_function<RangeImp>::value, "");
  typedef Stuff::Common::ConstStorageProvider<ReinterpretDiscreteFunction<SourceImp>> SourceStorage;
  typedef L2GlobalProjectionLocalizableOperator<GridViewImp, ReinterpretDiscreteFunction<SourceImp>, RangeImp>
      BaseOperatorType;

public:
  typedef SourceImp SourceType;
  using typename BaseOperatorType::GridViewType;
  using typename BaseOperatorType::RangeType;

  L2GlobalProlongationLocalizableOperator(const size_t over_integrate, GridViewType grd_vw, const SourceType& src,
                                          RangeType& rng)
    : SourceStorage(new ReinterpretDiscreteFunction<SourceImp>(src))
    , BaseOperatorType(over_integrate, grd_vw, SourceStorage::access(), rng)
  {
  }

  L2GlobalProlongationLocalizableOperator(GridViewType grd_vw, const SourceType& src, RangeType& rng)
    : L2GlobalProlongationLocalizableOperator(0, grd_vw, src, rng)
  {
  }

  ///! Calls L2GlobalProjectionLocalizableOperator::apply and gives a meaningful error message.
  void apply()
  {
    try {
      BaseOperatorType::apply();
    } catch (Stuff::Exceptions::reinterpretation_error& ee) {
      DUNE_THROW(Exceptions::prolongation_error,
                 "This prolongation (using a global L2 projection) failed, because the source could not be "
                     << "reinterpreted on the given grid view!\n"
                     << "This was the original error:\n\n"
                     << ee.what());
    }
  } // ... apply(...)
}; // class L2GlobalProlongationLocalizableOperator

template <class GridViewType, class SourceSpaceType, class SourceVectorType, class RangeSpaceType,
          class RangeVectorType>
typename std::enable_if<Stuff::Grid::is_grid_layer<GridViewType>::value && is_space<SourceSpaceType>::value
                            && Stuff::LA::is_vector<SourceVectorType>::value && is_space<RangeSpaceType>::value
                            && Stuff::LA::is_vector<RangeVectorType>::value,
                        std::unique_ptr<L2GlobalProlongationLocalizableOperator<GridViewType,
                                                                                ConstDiscreteFunction<SourceSpaceType,
                                                                                SourceVectorType>,
                                                                                DiscreteFunction<RangeSpaceType,
                                                                                RangeVectorType>>>>::
    type
    make_global_l2_prolongation_localizable_operator(
        const GridViewType& grid_view, const ConstDiscreteFunction<SourceSpaceType, SourceVectorType>& source,
        DiscreteFunction<RangeSpaceType, RangeVectorType>& range, const size_t over_integrate = 0)
{
  return DSC::
      make_unique<L2GlobalProlongationLocalizableOperator<GridViewType,
                                                          ConstDiscreteFunction<SourceSpaceType, SourceVectorType>,
                                                          DiscreteFunction<RangeSpaceType, RangeVectorType>>>(
          over_integrate, grid_view, source, range);
} // ... make_global_l2_prolongation_localizable_operator(...)

template <class SourceSpaceType, class SourceVectorType, class RangeSpaceType, class RangeVectorType>
typename std::enable_if<is_space<SourceSpaceType>::value && Stuff::LA::is_vector<SourceVectorType>::value
                            && is_space<RangeSpaceType>::value && Stuff::LA::is_vector<RangeVectorType>::value,
                        std::unique_ptr<L2GlobalProlongationLocalizableOperator<
                            typename RangeSpaceType::GridViewType,
                            ConstDiscreteFunction<SourceSpaceType, SourceVectorType>,
                            DiscreteFunction<RangeSpaceType, RangeVectorType>>>>::type
make_global_l2_prolongation_localizable_operator(const ConstDiscreteFunction<SourceSpaceType, SourceVectorType>& source,
                                                 DiscreteFunction<RangeSpaceType, RangeVectorType>& range,
                                                 const size_t over_integrate = 0)
{
  return DSC::make_unique<L2GlobalProlongationLocalizableOperator<
      typename RangeSpaceType::GridViewType,
      ConstDiscreteFunction<SourceSpaceType, SourceVectorType>,
      DiscreteFunction<RangeSpaceType, RangeVectorType>>>(over_integrate, range.space().grid_view(), source, range);
} // ... make_global_l2_prolongation_localizable_operator(...)

template <class GridViewImp, class FieldImp>
class L2GlobalProlongationOperator
    : public OperatorInterface<internal::L2GlobalProlongationOperatorTraits<GridViewImp, FieldImp>>
{
  typedef OperatorInterface<internal::L2GlobalProlongationOperatorTraits<GridViewImp, FieldImp>> BaseType;

public:
  typedef internal::L2GlobalProlongationOperatorTraits<GridViewImp, FieldImp> Traits;
  typedef GridViewImp GridViewType;
  using typename BaseType::FieldType;

private:
  typedef typename Stuff::Grid::Entity<GridViewType>::Type E;
  typedef typename GridViewType::ctype D;
  static const size_t d = GridViewType::dimension;

public:
  L2GlobalProlongationOperator(const size_t over_integrate, GridViewType grid_view)
    : grid_view_(grid_view)
    , over_integrate_(over_integrate)
  {
  }

  L2GlobalProlongationOperator(GridViewType grid_view)
    : grid_view_(grid_view)
    , over_integrate_(0)
  {
  }

  template <class SS, class SV, class RS, class RV>
  void apply(const ConstDiscreteFunction<SS, SV>& source, DiscreteFunction<RS, RV>& range) const
  {
    L2GlobalProlongationLocalizableOperator<GridViewType, ConstDiscreteFunction<SS, SV>, DiscreteFunction<RS, RV>> op(
        over_integrate_, grid_view_, source, range);
    op.apply();
  }

  template <class RangeType, class SourceType>
  FieldType apply2(const RangeType& /*range*/, const SourceType& /*source*/) const
  {
    DUNE_THROW(NotImplemented, "Go ahead if you think this makes sense!");
  }

  template <class RangeType, class SourceType>
  void apply_inverse(const RangeType& /*range*/, SourceType& /*source*/,
                     const Stuff::Common::Configuration& /*opts*/) const
  {
    DUNE_THROW(NotImplemented, "Go ahead if you think this makes sense!");
  }

  std::vector<std::string> invert_options() const
  {
    DUNE_THROW(NotImplemented, "Go ahead if you think this makes sense!");
  }

  Stuff::Common::Configuration invert_options(const std::string& /*type*/) const
  {
    DUNE_THROW(NotImplemented, "Go ahead if you think this makes sense!");
  }

private:
  GridViewType grid_view_;
  const size_t over_integrate_;
}; // class L2GlobalProlongationOperator

template <class GridViewType>
typename std::enable_if<Stuff::Grid::is_grid_layer<GridViewType>::value,
                        std::unique_ptr<L2GlobalProlongationOperator<GridViewType>>>::type
make_global_l2_prolongation_operator(const GridViewType& grid_view, const size_t over_integrate = 0)
{
  return DSC::make_unique<L2GlobalProlongationOperator<GridViewType>>(over_integrate, grid_view);
}

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PROLONGATIONS_L2_GLOBAL_HH
<|endoftext|>


<commit_before>#include <config.h>

#include <dune/common/exceptions.hh>
#include <dune/common/timer.hh>
#include <dune/multiscale/msfem/coarse_rhs_functional.hh>
#include <dune/multiscale/common/traits.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/functions/norm.hh>
#include <dune/stuff/common/parameter/configcontainer.hh>

#include <dune/gdt/spaces/continuouslagrange.hh>
#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/operators/elliptic-cg.hh>
#include <dune/gdt/functionals/l2.hh>
#include <dune/gdt/spaces/constraints.hh>
#include <dune/gdt/assembler/system.hh>
#include <dune/gdt/operators/projections.hh>

#include <limits>
#include <sstream>
#include <string>

#include "fem_solver.hh"

namespace Dune {
namespace Multiscale {

Elliptic_FEM_Solver::Elliptic_FEM_Solver(const CommonTraits::GdtSpaceType &space)
  : space_(space) {}

void Elliptic_FEM_Solver::apply(const CommonTraits::DiffusionType& diffusion,
                                const CommonTraits::SourceType& force,
                                CommonTraits::DiscreteFunctionType &solution) const {
  DSC_LOG_DEBUG_0 << "Solving linear problem with standard FEM" << std::endl;

  DSC_PROFILER.startTiming("fem.apply");

  typedef CommonTraits::GridViewType GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  const auto& boundary_info = Problem::getModelData()->boundaryInfo();
  const auto& neumann = Problem::getNeumannData();
  const auto& dirichlet = Problem::getDirichletData();

  const auto& space = space_;

  // container
  CommonTraits::LinearOperatorType system_matrix(space.mapper().size(), space.mapper().size(),
                                                 CommonTraits::EllipticOperatorType::pattern(space));
  CommonTraits::GdtVectorType rhs_vector(space.mapper().size());
  auto& solution_vector = solution.vector();
  // left hand side (elliptic operator)
  CommonTraits::EllipticOperatorType elliptic_operator(diffusion, system_matrix, space);
  // right hand side
  GDT::Functionals::L2Volume< CommonTraits::SourceType, CommonTraits::GdtVectorType, CommonTraits::GdtSpaceType > force_functional(force, rhs_vector, space);
  GDT::Functionals::L2Face< CommonTraits::NeumannDataType, CommonTraits::GdtVectorType, CommonTraits::GdtSpaceType >
      neumann_functional(*neumann, rhs_vector, space);
  // dirichlet boundary values
  CommonTraits::DiscreteFunctionType dirichlet_projection(space);
  GDT::Operators::DirichletProjectionLocalizable< GridViewType, CommonTraits::DirichletDataType, CommonTraits::DiscreteFunctionType >
      dirichlet_projection_operator(*(space.grid_view()),
                                    boundary_info,
                                    *dirichlet,
                                    dirichlet_projection);
  DSC_PROFILER.startTiming("fem.assemble");
  // now assemble everything in one grid walk
  GDT::SystemAssembler< CommonTraits::GdtSpaceType > system_assembler(space);
  system_assembler.add(elliptic_operator);
  system_assembler.add(force_functional);
  system_assembler.add(neumann_functional, new GDT::ApplyOn::NeumannIntersections< GridViewType >(boundary_info));
  system_assembler.add(dirichlet_projection_operator,
                       new GDT::ApplyOn::BoundaryEntities< GridViewType >());
  system_assembler.assemble();
  DSC_PROFILER.stopTiming("fem.assemble");

  DSC_PROFILER.startTiming("fem.constraints");
  // substract the operators action on the dirichlet values, since we assemble in H^1 but solve in H^1_0
  CommonTraits::GdtVectorType tmp(space.mapper().size());
  system_matrix.mv(dirichlet_projection.vector(), tmp);
  rhs_vector -= tmp;
  // apply the dirichlet zero constraints to restrict the system to H^1_0
  GDT::Constraints::Dirichlet < typename GridViewType::Intersection, CommonTraits::RangeFieldType >
      dirichlet_constraints(boundary_info, space.mapper().maxNumDofs(), space.mapper().maxNumDofs());
  system_assembler.add(dirichlet_constraints, system_matrix/*, new GDT::ApplyOn::BoundaryEntities< GridViewType >()*/);
  system_assembler.add(dirichlet_constraints, rhs_vector/*, new GDT::ApplyOn::BoundaryEntities< GridViewType >()*/);
  system_assembler.assemble();
  DSC_PROFILER.stopTiming("fem.constraints");

  // solve the system
  DSC_PROFILER.startTiming("fem.solve");
  const Stuff::LA::Solver< CommonTraits::LinearOperatorType, typename CommonTraits::GdtSpaceType::CommunicatorType >
      linear_solver(system_matrix, space.communicator());
  auto linear_solver_options = linear_solver.options("bicgstab.amg.ilu0");
  linear_solver_options.set("max_iter",                 "5000", true);
  linear_solver_options.set("precision",                "1e-8", true);
  linear_solver_options.set("post_check_solves_system", "0",    true);
  linear_solver_options.set("preconditioner.anisotropy_dim", GRIDDIM, true);
  linear_solver_options.set("preconditioner.isotropy_dim", GRIDDIM, true);
  linear_solver.apply(rhs_vector, solution_vector, linear_solver_options);
  // add the dirichlet shift to obtain the solution in H^1
  DSC_PROFILER.stopTiming("fem.solve");

  solution_vector += dirichlet_projection.vector();

  DSC_PROFILER.stopTiming("fem.apply");
}

} // namespace Multiscale
}
<commit_msg>[femSolver] set all solver options locally, change smoother relaxation<commit_after>#include <config.h>

#include <dune/common/exceptions.hh>
#include <dune/common/timer.hh>
#include <dune/multiscale/msfem/coarse_rhs_functional.hh>
#include <dune/multiscale/common/traits.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/functions/norm.hh>
#include <dune/stuff/common/parameter/configcontainer.hh>

#include <dune/gdt/spaces/continuouslagrange.hh>
#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/operators/elliptic-cg.hh>
#include <dune/gdt/functionals/l2.hh>
#include <dune/gdt/spaces/constraints.hh>
#include <dune/gdt/assembler/system.hh>
#include <dune/gdt/operators/projections.hh>

#include <limits>
#include <sstream>
#include <string>

#include "fem_solver.hh"

namespace Dune {
namespace Multiscale {

Elliptic_FEM_Solver::Elliptic_FEM_Solver(const CommonTraits::GdtSpaceType &space)
  : space_(space) {}

void Elliptic_FEM_Solver::apply(const CommonTraits::DiffusionType& diffusion,
                                const CommonTraits::SourceType& force,
                                CommonTraits::DiscreteFunctionType &solution) const {
  DSC_LOG_DEBUG_0 << "Solving linear problem with standard FEM" << std::endl;

  DSC_PROFILER.startTiming("fem.apply");

  typedef CommonTraits::GridViewType GridViewType;
  typedef typename GridViewType::Intersection IntersectionType;

  const auto& boundary_info = Problem::getModelData()->boundaryInfo();
  const auto& neumann = Problem::getNeumannData();
  const auto& dirichlet = Problem::getDirichletData();

  const auto& space = space_;

  // container
  CommonTraits::LinearOperatorType system_matrix(space.mapper().size(), space.mapper().size(),
                                                 CommonTraits::EllipticOperatorType::pattern(space));
  CommonTraits::GdtVectorType rhs_vector(space.mapper().size());
  auto& solution_vector = solution.vector();
  // left hand side (elliptic operator)
  CommonTraits::EllipticOperatorType elliptic_operator(diffusion, system_matrix, space);
  // right hand side
  GDT::Functionals::L2Volume< CommonTraits::SourceType, CommonTraits::GdtVectorType, CommonTraits::GdtSpaceType > force_functional(force, rhs_vector, space);
  GDT::Functionals::L2Face< CommonTraits::NeumannDataType, CommonTraits::GdtVectorType, CommonTraits::GdtSpaceType >
      neumann_functional(*neumann, rhs_vector, space);
  // dirichlet boundary values
  CommonTraits::DiscreteFunctionType dirichlet_projection(space);
  GDT::Operators::DirichletProjectionLocalizable< GridViewType, CommonTraits::DirichletDataType, CommonTraits::DiscreteFunctionType >
      dirichlet_projection_operator(*(space.grid_view()),
                                    boundary_info,
                                    *dirichlet,
                                    dirichlet_projection);
  DSC_PROFILER.startTiming("fem.assemble");
  // now assemble everything in one grid walk
  GDT::SystemAssembler< CommonTraits::GdtSpaceType > system_assembler(space);
  system_assembler.add(elliptic_operator);
  system_assembler.add(force_functional);
  system_assembler.add(neumann_functional, new GDT::ApplyOn::NeumannIntersections< GridViewType >(boundary_info));
  system_assembler.add(dirichlet_projection_operator,
                       new GDT::ApplyOn::BoundaryEntities< GridViewType >());
  system_assembler.assemble();
  DSC_PROFILER.stopTiming("fem.assemble");

  DSC_PROFILER.startTiming("fem.constraints");
  // substract the operators action on the dirichlet values, since we assemble in H^1 but solve in H^1_0
  CommonTraits::GdtVectorType tmp(space.mapper().size());
  system_matrix.mv(dirichlet_projection.vector(), tmp);
  rhs_vector -= tmp;
  // apply the dirichlet zero constraints to restrict the system to H^1_0
  GDT::Constraints::Dirichlet < typename GridViewType::Intersection, CommonTraits::RangeFieldType >
      dirichlet_constraints(boundary_info, space.mapper().maxNumDofs(), space.mapper().maxNumDofs());
  system_assembler.add(dirichlet_constraints, system_matrix/*, new GDT::ApplyOn::BoundaryEntities< GridViewType >()*/);
  system_assembler.add(dirichlet_constraints, rhs_vector/*, new GDT::ApplyOn::BoundaryEntities< GridViewType >()*/);
  system_assembler.assemble();
  DSC_PROFILER.stopTiming("fem.constraints");

  // solve the system
  DSC_PROFILER.startTiming("fem.solve");
  const Stuff::LA::Solver< CommonTraits::LinearOperatorType, typename CommonTraits::GdtSpaceType::CommunicatorType >
      linear_solver(system_matrix, space.communicator());
  auto linear_solver_options = linear_solver.options("bicgstab.amg.ilu0");
  linear_solver_options.set("max_iter",                 "5000", true);
  linear_solver_options.set("precision",                "1e-8", true);
  linear_solver_options.set("post_check_solves_system", "0",    true);
  linear_solver_options.set("preconditioner.anisotropy_dim", GRIDDIM, true);
  linear_solver_options.set("preconditioner.isotropy_dim", GRIDDIM, true);
  linear_solver_options.set("smoother.iterations", "1", true);
  linear_solver_options.set("smoother.relaxation_factor", "0.5", true);
  linear_solver_options.set("criterion.max_level", "100", true);
  linear_solver_options.set("criterion.coarse_target", "1000", true);
  linear_solver_options.set("criterion.min_coarse_rate", "1.2", true);
  linear_solver_options.set("criterion.prolong_damp", "1.6", true);
  linear_solver_options.set("criterion.anisotropy_dim", GRIDDIM, true);
  linear_solver_options.set("criterion.verbose", "1", true);
  linear_solver_options.set("smoother.verbose", "1", true);

  linear_solver.apply(rhs_vector, solution_vector, linear_solver_options);
  // add the dirichlet shift to obtain the solution in H^1
  DSC_PROFILER.stopTiming("fem.solve");

  solution_vector += dirichlet_projection.vector();

  DSC_PROFILER.stopTiming("fem.apply");
}

} // namespace Multiscale
}
<|endoftext|>


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

using namespace tiramisu;

#define mixf(x, y, a) (cast(p_float32, x) * (expr((float) 1) - cast(p_float32, a)) + cast(p_float32, y) * cast(p_float32, a))
#define cast(TYPE, EXPRESSION) (tiramisu::expr(tiramisu::o_cast, TYPE, EXPRESSION))
#define floor(EXPRESSION) (tiramisu::expr(o_floor, EXPRESSION))
#define clamp(EXPRESSION, MIN_VAL, MAX_VAL) (tiramisu::expr(tiramisu::o_max, tiramisu::expr(tiramisu::o_min, EXPRESSION, MAX_VAL), MIN_VAL))

int main(int argc, char* argv[]) {

    // Name of the function that we want to generate.
    tiramisu::init("warp_affine_tiramisu");

    // Declare an input that holds the sizes of input arrays.
    input SIZES("SIZES", {var("S", 0, 2)}, p_int32);

    constant N0("N0", SIZES(0));
    constant N1("N1", SIZES(1));

    var x("x", 0, N1), y("y", 0, N0);
    input in("in", {y, x}, p_uint8);

    expr a00 = expr((float) 0.1);
    expr a01 = expr((float) 0.1);
    expr a10 = expr((float) 0.1);
    expr a11 = expr((float) 0.1);
    expr b00 = expr((float) 0.1);
    expr b10 = expr((float) 0.1);

    // Translating this algorithm as close as possible
    expr o_r = a11*cast(p_float32, y) + a10*cast(p_float32, x) + b00;
    expr o_c = a01*(cast(p_float32, y)) + a00*cast(p_float32, x) + b10;

    expr r = o_r - floor(o_r);
    expr c = o_c - floor(o_c);

    expr coord_00_r = cast(p_int32, floor(o_r));
    expr coord_00_c = cast(p_int32, floor(o_c));
    expr coord_01_r = cast(p_int32, coord_00_r);
    expr coord_01_c = cast(p_int32, coord_00_c + expr((int) 1));
    expr coord_10_r = cast(p_int32, coord_00_r + expr((int) 1));
    expr coord_10_c = cast(p_int32, coord_00_c);
    expr coord_11_r = cast(p_int32, coord_00_r + expr((int) 1));
    expr coord_11_c = cast(p_int32, coord_00_c + expr((int) 1));

    coord_00_r = clamp(coord_00_r, 0, cast(p_int32, N0));
    coord_00_c = clamp(coord_00_c, 0, cast(p_int32, N1));
    coord_01_r = clamp(coord_01_r, 0, cast(p_int32, N0));
    coord_01_c = clamp(coord_01_c, 0, cast(p_int32, N1));
    coord_10_r = clamp(coord_10_r, 0, cast(p_int32, N0));
    coord_10_c = clamp(coord_10_c, 0, cast(p_int32, N1));
    coord_11_r = clamp(coord_11_r, 0, cast(p_int32, N0));
    coord_11_c = clamp(coord_11_c, 0, cast(p_int32, N1));

    expr A00 = in(coord_00_c, coord_00_r);
    expr A10 = in(coord_10_c, coord_10_r);
    expr A01 = in(coord_01_c, coord_01_r);
    expr A11 = in(coord_11_c, coord_11_r);

    expr e = cast(p_float32, mixf(mixf(A00, A10, r), mixf(A01, A11, r), c));

    computation affine({y, x}, e);

    affine.parallelize(y);
//    affine.vectorize(x, 8);

    buffer  b_input("b_input",  {N0, N1}, p_uint8, a_input);
    buffer b_SIZES("b_SIZES", {2}, p_int32, a_input);
    buffer b_affine("b_affine", {N0, N1}, p_float32, a_output);
    in.store_in(&b_input);
    SIZES.store_in(&b_SIZES);
    affine.store_in(&b_affine);

    tiramisu::codegen({&b_SIZES, &b_input, &b_affine}, "build/generated_fct_warp_affine.o");

    return 0;
}
<commit_msg>Fix warp_affine_tiramisu<commit_after>#include "tiramisu/tiramisu.h"

using namespace tiramisu;

#define mixf(x, y, a) (cast(p_float32, x) * (expr((float) 1) - cast(p_float32, a)) + cast(p_float32, y) * cast(p_float32, a))

int main(int argc, char* argv[]) {

    // Name of the function that we want to generate.
    tiramisu::init("warp_affine_tiramisu");

    // Declare an input that holds the sizes of input arrays.
    input SIZES("SIZES", {var("S", 0, 2)}, p_int32);

    constant N0("N0", SIZES(0));
    constant N1("N1", SIZES(1));

    var x("x", 0, N1), y("y", 0, N0);
    input in("in", {y, x}, p_uint8);

    expr a00 = expr((float) 0.1);
    expr a01 = expr((float) 0.1);
    expr a10 = expr((float) 0.1);
    expr a11 = expr((float) 0.1);
    expr b00 = expr((float) 0.1);
    expr b10 = expr((float) 0.1);

    // Translating this algorithm as close as possible
    expr o_r = a11*cast(p_float32, y) + a10*cast(p_float32, x) + b00;
    expr o_c = a01*cast(p_float32, y) + a00*cast(p_float32, x) + b10;

    expr r = o_r - floor(o_r);
    expr c = o_c - floor(o_c);

    expr coord_00_r = cast(p_int32, floor(o_r));
    expr coord_00_c = cast(p_int32, floor(o_c));
    expr coord_01_r = cast(p_int32, coord_00_r);
    expr coord_01_c = cast(p_int32, coord_00_c + 1);
    expr coord_10_r = cast(p_int32, coord_00_r + 1);
    expr coord_10_c = cast(p_int32, coord_00_c);
    expr coord_11_r = cast(p_int32, coord_00_r + 1);
    expr coord_11_c = cast(p_int32, coord_00_c + 1);

    coord_00_r = clamp(coord_00_r, 0, N0);
    coord_00_c = clamp(coord_00_c, 0, N1);
    coord_01_r = clamp(coord_01_r, 0, N0);
    coord_01_c = clamp(coord_01_c, 0, N1);
    coord_10_r = clamp(coord_10_r, 0, N0);
    coord_10_c = clamp(coord_10_c, 0, N1);
    coord_11_r = clamp(coord_11_r, 0, N0);
    coord_11_c = clamp(coord_11_c, 0, N1);

    expr A00 = in(coord_00_c, coord_00_r);
    expr A10 = in(coord_10_c, coord_10_r);
    expr A01 = in(coord_01_c, coord_01_r);
    expr A11 = in(coord_11_c, coord_11_r);

    expr e = cast(p_float32, mixf(mixf(A00, A10, r), mixf(A01, A11, r), c));

    computation affine({y, x}, e);

    affine.parallelize(y);
    affine.vectorize(x, 8);

    buffer  b_input("b_input",  {N0, N1}, p_uint8, a_input);
    buffer b_SIZES("b_SIZES", {2}, p_int32, a_input);
    buffer b_affine("b_affine", {N0, N1}, p_float32, a_output);
    in.store_in(&b_input);
    SIZES.store_in(&b_SIZES);
    affine.store_in(&b_affine);

    tiramisu::codegen({&b_SIZES, &b_input, &b_affine}, "build/generated_fct_warp_affine.o");

    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************/
/*  menu_button.cpp                                                      */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "menu_button.h"

#include "core/os/keyboard.h"
#include "scene/main/window.h"

void MenuButton::_unhandled_key_input(Ref<InputEvent> p_event) {
	if (disable_shortcuts) {
		return;
	}

	if (p_event->is_pressed() && !p_event->is_echo() && (Object::cast_to<InputEventKey>(p_event.ptr()) || Object::cast_to<InputEventJoypadButton>(p_event.ptr()) || Object::cast_to<InputEventAction>(*p_event))) {
		if (!get_parent() || !is_visible_in_tree() || is_disabled()) {
			return;
		}

		//bool global_only = (get_viewport()->get_modal_stack_top() && !get_viewport()->get_modal_stack_top()->is_a_parent_of(this));
		//if (popup->activate_item_by_event(p_event, global_only))
		//	accept_event();
		if (popup->activate_item_by_event(p_event, false)) {
			accept_event();
		}
	}
}

void MenuButton::pressed() {
	{
		Window *w = Object::cast_to<Window>(get_viewport());
		if (w && !w->is_embedding_subwindows()) {
			print_line("windowpos: " + w->get_position());
		}
	}
	Size2 size = get_size();

	Point2 gp = get_screen_position();

	print_line("screenpos: " + gp);
	gp.y += get_size().y;

	popup->set_position(gp);

	popup->set_size(Size2(size.width, 0));
	popup->set_parent_rect(Rect2(Point2(gp - popup->get_position()), get_size()));
	popup->take_mouse_focus();
	popup->popup();
}

void MenuButton::_gui_input(Ref<InputEvent> p_event) {
	BaseButton::_gui_input(p_event);
}

PopupMenu *MenuButton::get_popup() const {
	return popup;
}

void MenuButton::_set_items(const Array &p_items) {
	popup->set("items", p_items);
}

Array MenuButton::_get_items() const {
	return popup->get("items");
}

void MenuButton::set_switch_on_hover(bool p_enabled) {
	switch_on_hover = p_enabled;
}

bool MenuButton::is_switch_on_hover() {
	return switch_on_hover;
}

void MenuButton::_notification(int p_what) {
	if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
		if (!is_visible_in_tree()) {
			popup->hide();
		}
	}
}

void MenuButton::_bind_methods() {
	ClassDB::bind_method(D_METHOD("get_popup"), &MenuButton::get_popup);
	ClassDB::bind_method(D_METHOD("_unhandled_key_input"), &MenuButton::_unhandled_key_input);
	ClassDB::bind_method(D_METHOD("_set_items"), &MenuButton::_set_items);
	ClassDB::bind_method(D_METHOD("_get_items"), &MenuButton::_get_items);
	ClassDB::bind_method(D_METHOD("set_switch_on_hover", "enable"), &MenuButton::set_switch_on_hover);
	ClassDB::bind_method(D_METHOD("is_switch_on_hover"), &MenuButton::is_switch_on_hover);
	ClassDB::bind_method(D_METHOD("set_disable_shortcuts", "disabled"), &MenuButton::set_disable_shortcuts);

	ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "items", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_items", "_get_items");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "switch_on_hover"), "set_switch_on_hover", "is_switch_on_hover");

	ADD_SIGNAL(MethodInfo("about_to_popup"));
}

void MenuButton::set_disable_shortcuts(bool p_disabled) {
	disable_shortcuts = p_disabled;
}

MenuButton::MenuButton() {
	switch_on_hover = false;
	set_flat(true);
	set_toggle_mode(true);
	set_disable_shortcuts(false);
	set_process_unhandled_key_input(true);
	set_action_mode(ACTION_MODE_BUTTON_PRESS);

	popup = memnew(PopupMenu);
	popup->hide();
	add_child(popup);
	popup->connect("about_to_popup", callable_mp((BaseButton *)this, &BaseButton::set_pressed), varray(true)); // For when switching from another MenuButton.
	popup->connect("popup_hide", callable_mp((BaseButton *)this, &BaseButton::set_pressed), varray(false));
}

MenuButton::~MenuButton() {
}
<commit_msg>Remove printing of windowpos/screenpos in MenuButton<commit_after>/*************************************************************************/
/*  menu_button.cpp                                                      */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "menu_button.h"

#include "core/os/keyboard.h"
#include "scene/main/window.h"

void MenuButton::_unhandled_key_input(Ref<InputEvent> p_event) {
	if (disable_shortcuts) {
		return;
	}

	if (p_event->is_pressed() && !p_event->is_echo() && (Object::cast_to<InputEventKey>(p_event.ptr()) || Object::cast_to<InputEventJoypadButton>(p_event.ptr()) || Object::cast_to<InputEventAction>(*p_event))) {
		if (!get_parent() || !is_visible_in_tree() || is_disabled()) {
			return;
		}

		//bool global_only = (get_viewport()->get_modal_stack_top() && !get_viewport()->get_modal_stack_top()->is_a_parent_of(this));
		//if (popup->activate_item_by_event(p_event, global_only))
		//	accept_event();
		if (popup->activate_item_by_event(p_event, false)) {
			accept_event();
		}
	}
}

void MenuButton::pressed() {
	Size2 size = get_size();

	Point2 gp = get_screen_position();
	gp.y += get_size().y;

	popup->set_position(gp);

	popup->set_size(Size2(size.width, 0));
	popup->set_parent_rect(Rect2(Point2(gp - popup->get_position()), get_size()));
	popup->take_mouse_focus();
	popup->popup();
}

void MenuButton::_gui_input(Ref<InputEvent> p_event) {
	BaseButton::_gui_input(p_event);
}

PopupMenu *MenuButton::get_popup() const {
	return popup;
}

void MenuButton::_set_items(const Array &p_items) {
	popup->set("items", p_items);
}

Array MenuButton::_get_items() const {
	return popup->get("items");
}

void MenuButton::set_switch_on_hover(bool p_enabled) {
	switch_on_hover = p_enabled;
}

bool MenuButton::is_switch_on_hover() {
	return switch_on_hover;
}

void MenuButton::_notification(int p_what) {
	if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
		if (!is_visible_in_tree()) {
			popup->hide();
		}
	}
}

void MenuButton::_bind_methods() {
	ClassDB::bind_method(D_METHOD("get_popup"), &MenuButton::get_popup);
	ClassDB::bind_method(D_METHOD("_unhandled_key_input"), &MenuButton::_unhandled_key_input);
	ClassDB::bind_method(D_METHOD("_set_items"), &MenuButton::_set_items);
	ClassDB::bind_method(D_METHOD("_get_items"), &MenuButton::_get_items);
	ClassDB::bind_method(D_METHOD("set_switch_on_hover", "enable"), &MenuButton::set_switch_on_hover);
	ClassDB::bind_method(D_METHOD("is_switch_on_hover"), &MenuButton::is_switch_on_hover);
	ClassDB::bind_method(D_METHOD("set_disable_shortcuts", "disabled"), &MenuButton::set_disable_shortcuts);

	ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "items", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_items", "_get_items");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "switch_on_hover"), "set_switch_on_hover", "is_switch_on_hover");

	ADD_SIGNAL(MethodInfo("about_to_popup"));
}

void MenuButton::set_disable_shortcuts(bool p_disabled) {
	disable_shortcuts = p_disabled;
}

MenuButton::MenuButton() {
	switch_on_hover = false;
	set_flat(true);
	set_toggle_mode(true);
	set_disable_shortcuts(false);
	set_process_unhandled_key_input(true);
	set_action_mode(ACTION_MODE_BUTTON_PRESS);

	popup = memnew(PopupMenu);
	popup->hide();
	add_child(popup);
	popup->connect("about_to_popup", callable_mp((BaseButton *)this, &BaseButton::set_pressed), varray(true)); // For when switching from another MenuButton.
	popup->connect("popup_hide", callable_mp((BaseButton *)this, &BaseButton::set_pressed), varray(false));
}

MenuButton::~MenuButton() {
}
<|endoftext|>


<commit_before>// This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org/>

#include "span_analyzer_view.h"

#include "span_analyzer_app.h"

#include "edit_pane.h"
#include "results_pane.h"

IMPLEMENT_DYNAMIC_CLASS(SpanAnalyzerView, wxView)

SpanAnalyzerView::SpanAnalyzerView() {
}

SpanAnalyzerView::~SpanAnalyzerView() {
}

bool SpanAnalyzerView::OnCreate(wxDocument *doc, long flags) {
  if (!wxView::OnCreate(doc, flags)) {
    return false;
  }

  // gets main application frame
  wxFrame* frame = ((wxFrame *)wxGetApp().GetTopWindow());

  // notify application of new view
  SetFrame(frame);
  Activate(true);

  // tells aui manager to manage this frame
  manager_.SetManagedWindow(frame);

  // creates AUI windows and adds to manager
  wxAuiPaneInfo info;

  info = wxAuiPaneInfo();
  info.Name("Results");
  info.CenterPane();
  pane_results_ = new ResultsPane(frame, this);
  manager_.AddPane(pane_results_, info);

  info = wxAuiPaneInfo();
  info.Name("Edit");
  info.Floatable(true);
  info.Left();
  info.Caption("Edit");
  info.CloseButton(false);
  pane_edit_ = new EditPane(frame, this);
  manager_.AddPane(pane_edit_, info);

  manager_.Update();

  return true;
}

void SpanAnalyzerView::OnDraw(wxDC *dc) {
}

void SpanAnalyzerView::OnUpdate(wxView* sender, wxObject* hint) {
  // passes to base class first
  wxView::OnUpdate(sender, hint);

  // don't need to distinguish sender - all frames are grouped under one view
  pane_edit_->Update(hint);
  pane_results_->Update(hint);
}

bool SpanAnalyzerView::OnClose(bool WXUNUSED(deleteWindow)) {
  if (!GetDocument()->Close()) {
    return false;
  }

  // detaches frames and un-init manager
  manager_.DetachPane(pane_edit_);
  manager_.DetachPane(pane_results_);
  manager_.UnInit();

  // destroys frames
  pane_edit_->Destroy();
  pane_results_->Destroy();

  // resets frame to document-less state
  SpanAnalyzerFrame* frame = wxGetApp().frame();
  frame->Refresh();
  frame->SetTitle("SpanAnalyzer");

  return true;
}

EditPane* SpanAnalyzerView::pane_edit() {
  return pane_edit_;
}

ResultsPane* SpanAnalyzerView::pane_results() {
  return pane_results_;
}

wxString SpanAnalyzerView::GetPerspective() {
  return manager_.SavePerspective();
}<commit_msg>Missed this file in AUI perspective commit. Needed to load/save AUI perspective.<commit_after>// This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org/>

#include "span_analyzer_view.h"

#include "span_analyzer_app.h"

#include "edit_pane.h"
#include "results_pane.h"

IMPLEMENT_DYNAMIC_CLASS(SpanAnalyzerView, wxView)

SpanAnalyzerView::SpanAnalyzerView() {
}

SpanAnalyzerView::~SpanAnalyzerView() {
}

bool SpanAnalyzerView::OnCreate(wxDocument *doc, long flags) {
  if (!wxView::OnCreate(doc, flags)) {
    return false;
  }

  // gets main application frame
  wxFrame* frame = ((wxFrame *)wxGetApp().GetTopWindow());

  // notify application of new view
  SetFrame(frame);
  Activate(true);

  // tells aui manager to manage this frame
  manager_.SetManagedWindow(frame);

  // creates AUI windows and adds to manager
  wxAuiPaneInfo info;

  info = wxAuiPaneInfo();
  info.Name("Results");
  info.CenterPane();
  pane_results_ = new ResultsPane(frame, this);
  manager_.AddPane(pane_results_, info);

  info = wxAuiPaneInfo();
  info.Name("Edit");
  info.Floatable(true);
  info.Left();
  info.Caption("Edit");
  info.CloseButton(false);
  pane_edit_ = new EditPane(frame, this);
  manager_.AddPane(pane_edit_, info);

  // loads perspective and updates
  std::string perspective = wxGetApp().config()->perspective;
  if (perspective == "") {
    manager_.Update();
  } else {
    manager_.LoadPerspective(wxGetApp().config()->perspective);
  }

  return true;
}

void SpanAnalyzerView::OnDraw(wxDC *dc) {
}

void SpanAnalyzerView::OnUpdate(wxView* sender, wxObject* hint) {
  // passes to base class first
  wxView::OnUpdate(sender, hint);

  // don't need to distinguish sender - all frames are grouped under one view
  pane_edit_->Update(hint);
  pane_results_->Update(hint);
}

bool SpanAnalyzerView::OnClose(bool WXUNUSED(deleteWindow)) {
  if (!GetDocument()->Close()) {
    return false;
  }

  // saves AUI perspective
  wxGetApp().config()->perspective = manager_.SavePerspective();

  // detaches frames and un-init manager
  manager_.DetachPane(pane_edit_);
  manager_.DetachPane(pane_results_);
  manager_.UnInit();

  // destroys frames
  pane_edit_->Destroy();
  pane_results_->Destroy();

  // resets frame to document-less state
  SpanAnalyzerFrame* frame = wxGetApp().frame();
  frame->Refresh();
  frame->SetTitle("SpanAnalyzer");

  return true;
}

EditPane* SpanAnalyzerView::pane_edit() {
  return pane_edit_;
}

ResultsPane* SpanAnalyzerView::pane_results() {
  return pane_results_;
}

wxString SpanAnalyzerView::GetPerspective() {
  return manager_.SavePerspective();
}<|endoftext|>


<commit_before>// ping_pong.cpp

#define N 100

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <limits.h>
#include <mpi.h>
using namespace std;

	double cal_pi(int);

int main(int argc, char *argv[])
{

	MPI_Init(&argc, &argv);

	// get world size
	int world_size;
	MPI_Comm_size(MPI_COMM_WORLD, &world_size);
	// get my rank
	int world_rank;
	MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);

	int t1 = (double)MPI_Wtime();
	int i, j, t;

	double global_pi;
	double my_pi;

	// root-only array
	double *data = NULL;
	if (world_rank == 0) {
		data = new double[world_size];
	}

	/************************************************************/
	/*					 run core function                      */
	/************************************************************/

	my_pi = cal_pi(N);

	// collect results
	MPI_Gather(&my_pi, 1, MPI_DOUBLE,
		data, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);

	int t2 = (double)MPI_Wtime();
	if (world_rank == 0) {
		// calculate mean
		for (int i = 0; i < world_size; i++) {
			global_pi += data[i];
		}
		global_pi = 4.0 * global_pi / world_size;
		// output result
		cout << "pi = " << global_pi << endl;
		cout << "Time elasped: " << t2 - t1 << endl;
	} // end of if

	MPI_Finalize();
	return 0;
}

double cal_pi(int M) {
	int count = 0;
	double x, y, r, result;
	for (int i = 0; i < M; i++) {
		x = 1.0 * rand(time(NULL)) / INT_MAX;
		y = 1.0 * rand(time(NULL)) / INT_MAX;
		r = sqrt( pow(x,2) + pow(y,2) );
		if (r < 1) {
			count++;
		}
	}
	result = 1.0 * count / M;
	return result;
}
<commit_msg>use srand()<commit_after>// ping_pong.cpp

#define N 100

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <limits.h>
#include <mpi.h>
using namespace std;

	double cal_pi(int);

int main(int argc, char *argv[])
{
	srand(time(NULL));
	MPI_Init(&argc, &argv);

	// get world size
	int world_size;
	MPI_Comm_size(MPI_COMM_WORLD, &world_size);
	// get my rank
	int world_rank;
	MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);

	int t1 = (double)MPI_Wtime();
	int i, j, t;

	double global_pi;
	double my_pi;

	// root-only array
	double *data = NULL;
	if (world_rank == 0) {
		data = new double[world_size];
	}

	/************************************************************/
	/*					 run core function                      */
	/************************************************************/

	my_pi = cal_pi(N);

	// collect results
	MPI_Gather(&my_pi, 1, MPI_DOUBLE,
		data, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);

	int t2 = (double)MPI_Wtime();
	if (world_rank == 0) {
		// calculate mean
		for (int i = 0; i < world_size; i++) {
			global_pi += data[i];
		}
		global_pi = 4.0 * global_pi / world_size;
		// output result
		cout << "pi = " << global_pi << endl;
		cout << "Time elasped: " << t2 - t1 << endl;
	} // end of if

	MPI_Finalize();
	return 0;
}

double cal_pi(int M) {
	int count = 0;
	double x, y, r, result;
	for (int i = 0; i < M; i++) {
		x = 1.0 * rand() / INT_MAX;
		y = 1.0 * rand() / INT_MAX;
		r = sqrt( pow(x,2) + pow(y,2) );
		if (r < 1) {
			count++;
		}
	}
	result = 1.0 * count / M;
	return result;
}
<|endoftext|>


<commit_before>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE libstorage

#include <boost/test/unit_test.hpp>

#include "storage/Utils/AppUtil.h"

using namespace storage;

BOOST_AUTO_TEST_CASE(test_regex_escape1)
{
    BOOST_CHECK_EQUAL(regex_escape("test", regex::extended), "test");
    BOOST_CHECK_EQUAL(regex_escape("test []", regex::extended), "test \\[]");
}

/*
 * Check that for single char strings 1. the regex compilation with
 * the escaped string works and that 2. the string only matches itself.
 */
BOOST_AUTO_TEST_CASE(test_regex_escape2)
{
    vector<string> v;

    for (unsigned char c1 = 1; c1 < 255; ++c1)
        v.push_back(string(1, c1));

    for (const string& s1 : v)
    {
	regex rx1;

	BOOST_CHECK_NO_THROW(rx1.assign(regex_escape(s1, regex::extended), regex::extended));

	for (const string& s2 : v)
	    BOOST_CHECK_EQUAL(regex_match(s2, rx1), s1 == s2);
    }
}
<commit_msg>- extended unit test (bsc#1135341)<commit_after>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE libstorage

#include <boost/test/unit_test.hpp>

#include "storage/Utils/AppUtil.h"

using namespace storage;

BOOST_AUTO_TEST_CASE(test_regex_escape1)
{
    BOOST_CHECK_EQUAL(regex_escape("test", regex::extended), "test");
    BOOST_CHECK_EQUAL(regex_escape("test []", regex::extended), "test \\[]");
}

/*
 * Check that for single char strings 1. the regex compilation with
 * the escaped string works and that 2. the string only matches
 * itself. The checks are also done when the escaped string is places
 * inside rounded brackets.
 */
BOOST_AUTO_TEST_CASE(test_regex_escape2)
{
    vector<string> v;

    for (unsigned char c1 = 1; c1 < 255; ++c1)
        v.push_back(string(1, c1));

    for (const string& s1 : v)
    {
	string es1 = regex_escape(s1, regex::extended);

	regex rx;

	BOOST_CHECK_NO_THROW(rx.assign(es1, regex::extended));

	for (const string& s2 : v)
	    BOOST_CHECK_EQUAL(regex_match(s2, rx), s1 == s2);

	BOOST_CHECK_NO_THROW(rx.assign("(" + es1 + ")", regex::extended));

	for (const string& s2 : v)
	    BOOST_CHECK_EQUAL(regex_match(s2, rx), s1 == s2);
    }
}
<|endoftext|>


<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
**    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
**      disclaimer.
**    * 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.
**    * Neither the name of the ETH Zurich 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 HOLDER 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 "CScript.h"

#include "ModelBase/src/nodes/Node.h"
#include "ModelBase/src/util/SymbolMatcher.h"

#include "OOModel/src/declarations/Class.h"
#include "OOModel/src/declarations/Method.h"

#include "../queries/QueryExecutor.h"
#include "../queries/CompositeQuery.h"
#include "../queries/AstNameFilter.h"
#include "../queries/SubstractOperator.h"
#include "../queries/AstQuery.h"
#include "../queries/NodePropertyAdder.h"
#include "../queries/UnionOperator.h"
#include "../queries/ScriptQuery.h"
#include "../queries/AddASTPropertiesAsTuples.h"

#include "../parsing/QueryBuilder.h"

namespace InformationScripting {

CScript::CScript() : Command{"script"} {}

bool CScript::canInterpret(Visualization::Item* source, Visualization::Item*, const QStringList& commandTokens,
									const std::unique_ptr<Visualization::Cursor>&)
{
	return commandTokens.size() > 1 && commandTokens.first() == "script" && source->findAncestorWithNode();
}

Interaction::CommandResult* CScript::execute(Visualization::Item* source, Visualization::Item*,
															const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>&)
{
	using namespace boost;

	auto node = source->findAncestorWithNode()->node();
	Q_ASSERT(node);

	QStringList args = commandTokens.mid(1);
	if (!args.size()) new Interaction::CommandResult();

	QString command = args[0];
	args = args.mid(1);

	if (command != "fallback")
	{
		args.prepend(command);
		auto q = QueryBuilder::instance().buildQueryFrom(args.join(""), node);
		QueryExecutor queryExecutor(q);
		queryExecutor.execute();
	}
	else
	{
		QString command = args[0];
		args = args.mid(1);

		if (command == "script")
		{
			if (args.size() > 1)
			{
				// $"classes g" | "script test"$
				auto classesQuery = new AstQuery(AstQuery::QueryType::Classes, node, {"g"});
				// TODO we could be more fancy in script file name detection, e.g. if .py is already entered don't append it.
				auto scriptQuery = new ScriptQuery(QString("../InformationScripting/test/scripts/%1.py").arg(args[0]));
				auto compositeQuery = new CompositeQuery();
				compositeQuery->connectQuery(classesQuery, scriptQuery);
				compositeQuery->connectToOutput(scriptQuery);
				QueryExecutor queryExecutor(compositeQuery);
				queryExecutor.execute();
			}
		}
		else if (command == "methods")
		{
			// "methods"
			auto query = new AstQuery(AstQuery::QueryType::Methods, node, args);
			QueryExecutor queryExecutor(query);
			queryExecutor.execute();
		}
		else if (command == "bases")
		{
			// "bases"
			auto query = new AstQuery(AstQuery::QueryType::BaseClasses, node, args);
			QueryExecutor queryExecutor(query);
			queryExecutor.execute();
		}
		else if (command == "pipe")
		{
			// $"methods" | "toClass"$
			auto methodQuery = new AstQuery(AstQuery::QueryType::Methods, node, args);
			auto toBaseQuery = new AstQuery(AstQuery::QueryType::ToClass, node, args);
			auto compositeQuery = new CompositeQuery();
			compositeQuery->connectQuery(methodQuery, toBaseQuery);
			compositeQuery->connectToOutput(toBaseQuery);
			QueryExecutor queryExecutor(compositeQuery);
			queryExecutor.execute();
		}
		else if (command == "query21")
		{
			// Find all classes for which the name contains X and which have a method named Y
			// 5 queries seems like a lot for this :S

			// $"classes g" | "filter *Matcher*" | "methods of" | "filter matches" | "toClass"$
			auto classesQuery = new AstQuery(AstQuery::QueryType::Classes, node, {"g"});
			auto filterQuery = new AstNameFilter(Model::SymbolMatcher(new QRegExp("\\w*Matcher\\w*")));
			auto methodsOfQuery = new AstQuery(AstQuery::QueryType::Methods, node, {"of"});
			auto methodsFilter = new AstNameFilter(Model::SymbolMatcher("matches"));
			auto toBaseQuery = new AstQuery(AstQuery::QueryType::ToClass, node, args);
			auto compositeQuery = new CompositeQuery();
			compositeQuery->connectQuery(classesQuery, filterQuery);
			compositeQuery->connectQuery(filterQuery, methodsOfQuery);
			compositeQuery->connectQuery(methodsOfQuery, methodsFilter);
			compositeQuery->connectQuery(methodsFilter, toBaseQuery);
			compositeQuery->connectToOutput(toBaseQuery);
			QueryExecutor queryExecutor(compositeQuery);
			queryExecutor.execute();
		}
		else if (command == "callgraph")
		{
			// "callgraph"
			auto query = new AstQuery(AstQuery::QueryType::CallGraph, node, args);
			auto compositeQuery = new CompositeQuery();
			compositeQuery->connectToOutput(query);
			QueryExecutor queryExecutor(compositeQuery);
			queryExecutor.execute();
		}
		else if (command == "query19")
		{
			// Find all methods that are not called transitively from the TARGET method.

			// $"methods g" - {$"callgraph" | "addASTProperties"$}$
			// or:
			// ${"methods g", $"callgraph" | "addASTProperties"$}-$
			auto allMethodsQuery = new AstQuery(AstQuery::QueryType::Methods, node, {"g"});
			auto callGraphQuery = new AstQuery(AstQuery::QueryType::CallGraph, node, args);
			auto astAdder = new AddASTPropertiesAsTuples();
			auto complement = new SubstractOperator();
			auto compositeQuery = new CompositeQuery();
			compositeQuery->connectQuery(callGraphQuery, astAdder);
			compositeQuery->connectQuery(allMethodsQuery, complement);
			compositeQuery->connectQuery(astAdder, 0, complement, 1);
			compositeQuery->connectToOutput(complement);
			QueryExecutor queryExecutor(compositeQuery);
			queryExecutor.execute();
		}
		else if (command == "color")
		{
			// $"methods" | {$"filter *quotes*" | "color = blue"$, $"filter *brackets*" | "color = green"$} U$
			auto colorQuotes = new NodePropertyAdder("color", QString("blue"));
			auto colorBrackets = new NodePropertyAdder("color", QString("green"));

			auto quotesFilter = new AstNameFilter(Model::SymbolMatcher(new QRegExp("\\w*quotes\\w*")));
			auto bracketsFilter = new AstNameFilter(Model::SymbolMatcher(new QRegExp("\\w*brackets\\w*")));

			auto quotes = new CompositeQuery();
			quotes->connectInput(0, quotesFilter);
			quotes->connectQuery(quotesFilter, colorQuotes);
			quotes->connectToOutput(colorQuotes);

			auto brackets = new CompositeQuery();
			brackets->connectInput(0, bracketsFilter);
			brackets->connectQuery(bracketsFilter, colorBrackets);
			brackets->connectToOutput(colorBrackets);

			auto methods = new AstQuery(AstQuery::QueryType::Methods, node, {});
			auto unionOp = new UnionOperator();

			auto composite = new CompositeQuery();

			composite->connectQuery(methods, quotes);
			composite->connectQuery(methods, brackets);

			composite->connectQuery(quotes, unionOp);
			composite->connectQuery(brackets, 0, unionOp, 1);

			composite->connectToOutput(unionOp);

			QueryExecutor queryExecutor(composite);
			queryExecutor.execute();
		}
	}
	return new Interaction::CommandResult();
}

} /* namespace InformationScripting */
<commit_msg>Use QueryRegistry in CScript instead of direct constructor<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
**    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
**      disclaimer.
**    * 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.
**    * Neither the name of the ETH Zurich 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 HOLDER 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 "CScript.h"

#include "ModelBase/src/nodes/Node.h"
#include "ModelBase/src/util/SymbolMatcher.h"

#include "OOModel/src/declarations/Class.h"
#include "OOModel/src/declarations/Method.h"

#include "../queries/QueryExecutor.h"
#include "../queries/CompositeQuery.h"
#include "../queries/SubstractOperator.h"
#include "../queries/NodePropertyAdder.h"
#include "../queries/UnionOperator.h"
#include "../queries/AddASTPropertiesAsTuples.h"
#include "../queries/QueryRegistry.h"
#include "../parsing/QueryBuilder.h"

namespace InformationScripting {

CScript::CScript() : Command{"script"} {}

bool CScript::canInterpret(Visualization::Item* source, Visualization::Item*, const QStringList& commandTokens,
									const std::unique_ptr<Visualization::Cursor>&)
{
	return commandTokens.size() > 1 && commandTokens.first() == "script" && source->findAncestorWithNode();
}

Interaction::CommandResult* CScript::execute(Visualization::Item* source, Visualization::Item*,
															const QStringList& commandTokens, const std::unique_ptr<Visualization::Cursor>&)
{
	using namespace boost;

	auto node = source->findAncestorWithNode()->node();
	Q_ASSERT(node);

	QStringList args = commandTokens.mid(1);
	if (!args.size()) new Interaction::CommandResult();

	QString command = args[0];
	args = args.mid(1);

	if (command != "fallback")
	{
		args.prepend(command);
		auto q = QueryBuilder::instance().buildQueryFrom(args.join(""), node);
		QueryExecutor queryExecutor(q);
		queryExecutor.execute();
	}
	else
	{
		QString command = args[0];
		args = args.mid(1);

		if (command == "script")
		{
			if (args.size() > 1)
			{
				// $"classes g" | "script test"$
				auto classesQuery = QueryRegistry::instance().buildQuery("classes", node, {"-s=g"});
				// TODO we could be more fancy in script file name detection, e.g. if .py is already entered don't append it.
				auto scriptQuery = QueryRegistry::instance().buildQuery(args.takeFirst(), node, args);
				auto compositeQuery = new CompositeQuery();
				compositeQuery->connectQuery(classesQuery, scriptQuery);
				compositeQuery->connectToOutput(scriptQuery);
				QueryExecutor queryExecutor(compositeQuery);
				queryExecutor.execute();
			}
		}
		else if (command == "methods")
		{
			// "methods"
			auto query = QueryRegistry::instance().buildQuery("methods", node, args);
			QueryExecutor queryExecutor(query);
			queryExecutor.execute();
		}
		else if (command == "bases")
		{
			// "bases"
			auto query = QueryRegistry::instance().buildQuery("bases", node, args);
			QueryExecutor queryExecutor(query);
			queryExecutor.execute();
		}
		else if (command == "pipe")
		{
			// $"methods" | "toClass"$
			auto methodQuery = QueryRegistry::instance().buildQuery("methods", node, args);
			auto toBaseQuery = QueryRegistry::instance().buildQuery("toClass", node, args);
			auto compositeQuery = new CompositeQuery();
			compositeQuery->connectQuery(methodQuery, toBaseQuery);
			compositeQuery->connectToOutput(toBaseQuery);
			QueryExecutor queryExecutor(compositeQuery);
			queryExecutor.execute();
		}
		else if (command == "query21")
		{
			// Find all classes for which the name contains X and which have a method named Y
			// 5 queries seems like a lot for this :S

			// $"classes -s=g" | "filter *Matcher*" | "methods -s=of" | "filter matches" | "toClass"$
			auto classesQuery = QueryRegistry::instance().buildQuery("classes", node, {"-s=g"});
			auto filterQuery = QueryRegistry::instance().buildQuery("filter", node, {"*Matcher*"});
			auto methodsOfQuery = QueryRegistry::instance().buildQuery("methods", node, {"-s=of"});
			auto methodsFilter = QueryRegistry::instance().buildQuery("filter", node, {"matches"});
			auto toBaseQuery = QueryRegistry::instance().buildQuery("toClass", node, args);
			auto compositeQuery = new CompositeQuery();
			compositeQuery->connectQuery(classesQuery, filterQuery);
			compositeQuery->connectQuery(filterQuery, methodsOfQuery);
			compositeQuery->connectQuery(methodsOfQuery, methodsFilter);
			compositeQuery->connectQuery(methodsFilter, toBaseQuery);
			compositeQuery->connectToOutput(toBaseQuery);
			QueryExecutor queryExecutor(compositeQuery);
			queryExecutor.execute();
		}
		else if (command == "callgraph")
		{
			// "callgraph"
			auto query = QueryRegistry::instance().buildQuery("callgraph", node, args);
			auto compositeQuery = new CompositeQuery();
			compositeQuery->connectToOutput(query);
			QueryExecutor queryExecutor(compositeQuery);
			queryExecutor.execute();
		}
		else if (command == "query19")
		{
			// Find all methods that are not called transitively from the TARGET method.

			// $"methods -s=g" - {$"callgraph" | "addASTProperties"$}$
			// or:
			// ${"methods -s=g", $"callgraph" | "addASTProperties"$}-$
			auto allMethodsQuery = QueryRegistry::instance().buildQuery("methods", node, {"-s=g"});
			auto callGraphQuery = QueryRegistry::instance().buildQuery("callgraph", node, args);
			auto astAdder = new AddASTPropertiesAsTuples();
			auto complement = new SubstractOperator();
			auto compositeQuery = new CompositeQuery();
			compositeQuery->connectQuery(callGraphQuery, astAdder);
			compositeQuery->connectQuery(allMethodsQuery, complement);
			compositeQuery->connectQuery(astAdder, 0, complement, 1);
			compositeQuery->connectToOutput(complement);
			QueryExecutor queryExecutor(compositeQuery);
			queryExecutor.execute();
		}
		else if (command == "color")
		{
			// $"methods" | {$"filter *quotes*" | "color = blue"$, $"filter *brackets*" | "color = green"$} U$
			auto colorQuotes = new NodePropertyAdder("color", QString("blue"));
			auto colorBrackets = new NodePropertyAdder("color", QString("green"));

			auto quotesFilter = QueryRegistry::instance().buildQuery("filter", node, {"*quotes*"});
			auto bracketsFilter = QueryRegistry::instance().buildQuery("filter", node, {"*brackets*"});

			auto quotes = new CompositeQuery();
			quotes->connectInput(0, quotesFilter);
			quotes->connectQuery(quotesFilter, colorQuotes);
			quotes->connectToOutput(colorQuotes);

			auto brackets = new CompositeQuery();
			brackets->connectInput(0, bracketsFilter);
			brackets->connectQuery(bracketsFilter, colorBrackets);
			brackets->connectToOutput(colorBrackets);

			auto methods = QueryRegistry::instance().buildQuery("methods", node, {});
			auto unionOp = new UnionOperator();

			auto composite = new CompositeQuery();

			composite->connectQuery(methods, quotes);
			composite->connectQuery(methods, brackets);

			composite->connectQuery(quotes, unionOp);
			composite->connectQuery(brackets, 0, unionOp, 1);

			composite->connectToOutput(unionOp);

			QueryExecutor queryExecutor(composite);
			queryExecutor.execute();
		}
	}
	return new Interaction::CommandResult();
}

} /* namespace InformationScripting */
<|endoftext|>


<commit_before>/*
 * Copyright 2008-2010 Google Inc.
 *
 * 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 "esnpapi.h"
#include "proxyImpl.h"

#include <any.h>
#include <reflect.h>
#include <org/w3c/dom.h>

using namespace org::w3c::dom;

void initializeSvgMetaData()
{
    registerMetaData(smil::ElementTimeControl::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, smil::ElementTimeControl_Bridge<Any, invoke> >::createInstance));
    registerMetaData(smil::TimeEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, smil::TimeEvent_Bridge<Any, invoke> >::createInstance));
    registerMetaData(svg::GetSVGDocument::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, svg::GetSVGDocument_Bridge<Any, invoke> >::createInstance));
    registerMetaData(svg::SVGZoomEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, svg::SVGZoomEvent_Bridge<Any, invoke> >::createInstance));

    initializeSvgMetaDataA_G();
    initializeSvgMetaDataH_N();
    initializeSvgMetaDataO_U();
    initializeSvgMetaDataV_Z();
}
<commit_msg>(initializeSvgMetaData) : Register "XMLDocument".<commit_after>/*
 * Copyright 2008-2010 Google Inc.
 *
 * 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 "esnpapi.h"
#include "proxyImpl.h"

#include <any.h>
#include <reflect.h>
#include <org/w3c/dom.h>

using namespace org::w3c::dom;

void initializeSvgMetaData()
{
    registerMetaData(smil::ElementTimeControl::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, smil::ElementTimeControl_Bridge<Any, invoke> >::createInstance));
    registerMetaData(smil::TimeEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, smil::TimeEvent_Bridge<Any, invoke> >::createInstance));
    registerMetaData(svg::GetSVGDocument::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, svg::GetSVGDocument_Bridge<Any, invoke> >::createInstance));
    registerMetaData(svg::SVGZoomEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, svg::SVGZoomEvent_Bridge<Any, invoke> >::createInstance));

    initializeSvgMetaDataA_G();
    initializeSvgMetaDataH_N();
    initializeSvgMetaDataO_U();
    initializeSvgMetaDataV_Z();

    registerMetaData(Document::getMetaData(),
                     reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, Document_Bridge<Any, invoke> >::createInstance),
                     "XMLDocument");
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstring>
#include <iostream>
#include <sstream>

#include <netinet/in.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <vector>
#include <algorithm>
#include <list>
#include <map>

#include <netdb.h>
#include <cstdlib>

#include "segment.h"
#include "message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "execute_success_message.h"
#include "execute_failure_message.h"
#include "execute_request_message.h"
#include "register_success_message.h"
#include "register_failure_message.h"
#include "register_request_message.h"
#include "terminate_message.h"

#include "rpc.h"
#include "constants.h"
#include "network.h"
#include "helper_function.h"

using namespace std;

// Global variables for client
bool connectedToBinder = false;
int binderSocket = 0;

// Global variables for server
struct addrinfo* servinfo;
static map<procedure_signature, skeleton, ps_compare> proc_skele_dict;
string serverIdentifier;
unsigned int port = 0;
int welcomeSocket = 0;

void mapPrint(){
  cout << "proc_skele_dict size: "<<proc_skele_dict.size() << endl;

  cout << "Map Print: ";

  for(map<procedure_signature, skeleton>::iterator it = proc_skele_dict.begin();
   it != proc_skele_dict.end(); ++it){

    cout << it->first.name << endl;
  }

  cout << endl;
}

// See interface (header file).
int rpcInit(){
	cout << "Running rpcInit..." << endl;

	// Creates a connection socket to be used for accepting connections
	// from clients
	welcomeSocket = createSocket();
	setUpToListen(welcomeSocket);
	serverIdentifier = getHostAddress();
	port = getSocketPort(welcomeSocket);
	cout << "SERVER IDENTIFIER: " << serverIdentifier << endl;
	cout << "PORT: " << port << endl;

	// Opens a connection to the binder
	binderSocket = createSocket();
	string binderAddress = getBinderAddress();
	unsigned int binderPort = getBinderPort();
	setUpToConnect(binderSocket, binderAddress, binderPort);
  connectedToBinder = true;
  cout << "binderSocket: " << binderSocket << endl;

  return 0;
}

int sendExecute(int sock, string name, int* argTypes, void**args){

  ExecuteRequestMessage exeReqMsg = ExecuteRequestMessage(name, argTypes, args);
  Segment exeReqSeg = Segment(exeReqMsg.getLength(), MSG_TYPE_EXECUTE_REQUEST, &exeReqMsg);
  int status =  exeReqSeg.send(sock);

  int returnVal;

	string retName;
	int* retArgTypes;
	void** retArgs;

  if(status == 0){
    Segment * segment = 0;
    status = Segment::receive(sock, segment);

    if(segment->getType() == MSG_TYPE_EXECUTE_SUCCESS) {

			Message * cast = segment->getMessage();
	 		ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(cast);

			retName = esm->getName();
			retArgTypes = esm->getArgTypes();
			retArgs = esm->getArgs();

			if(retName == name){
				//extractArgumentsMessage(replyMessageP, argTypes, args, argTypesLength, false);
				returnVal = 0;
			}else{
				returnVal = 99;
			}

    }else if(segment->getType() ==  MSG_TYPE_EXECUTE_FAILURE){
  		Message * cast = segment->getMessage();
			ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast);
    	returnVal = efm->getReasonCode();
    }

  }else{ //Something bad happened
  	returnVal = 99;
  }

  return returnVal;
}

// See interface (header file).
int rpcCall(char *name, int *argTypes, void **args) {
  cout << "Flag0" << endl;

	string serverAddress;
	unsigned int serverPort;
	int status;

	if(!connectedToBinder){
		binderSocket = createSocket();
		string binderAddress = getBinderAddress();
		unsigned int binderPort = getBinderPort();
		status = setUpToConnect(binderSocket, binderAddress, binderPort);
	  connectedToBinder = true;
	}
	//do something with returnVal

  cout << "Flag1" << endl;

  LocRequestMessage locReqMsg = LocRequestMessage(name, argTypes);
  Segment locReqSeg = Segment(locReqMsg.getLength(), MSG_TYPE_LOC_REQUEST, &locReqMsg);
  int binder_status = locReqSeg.send(binderSocket);
  cout << "Flag1.5" << endl;

	//maybe error check with binder_status
  //TODO: SEGMENT FAULT IF NOT IN THIS FOR LOOP
	/**Server stuff **/
	if(binder_status >= 0){
	  cout << "Flag2" << endl;
    Segment * parsedSegment = 0;
    cout << "Flag2.1" << endl;
    int tempStatus = 0;
    cout << "Flag2.2" << endl;
    tempStatus = Segment::receive(binderSocket, parsedSegment);
    cout << "Flag2.5" << endl;

		if(parsedSegment->getType() == MSG_TYPE_LOC_SUCCESS) { //'LOC_REQUEST'
  		cout << "Got success" << endl;
      Message * cast = parsedSegment->getMessage();
  		LocSuccessMessage * lcm = dynamic_cast<LocSuccessMessage*>(cast);
	  	serverAddress = lcm->getServerIdentifier();
	  	serverPort = lcm->getPort();
	  }else if(parsedSegment->getType() == MSG_TYPE_LOC_FAILURE) {
			//something bad happens
	  	return 1;
	  }
	}

  int serverSocket = createSocket();
	int status = setUpToConnect(serverSocket, serverAddress, serverPort);
	status = sendExecute(serverSocket, string(name), argTypes, args);

	return status;
}

  //TODO:
  // CREATE SERVER
  // CONNECT TO BINDER

int rpcRegister(char * name, int *argTypes, skeleton f){

  RegisterRequestMessage regReqMsg = RegisterRequestMessage(serverIdentifier, port, name, argTypes);
  cout << "rpcRegister name: " << name << endl;
  cout << "rpcRegister serverIdentifier: " << serverIdentifier << endl;
  cout << "rpcRegister port: " << port << endl;

  /*
  We should get seg.send to give us some feed back maybe
  int status = regReqMsg->send(binderSocket);
  */

  Segment regReqSeg = Segment(regReqMsg.getLength(), MSG_TYPE_REGISTER_REQUEST, &regReqMsg);
  int status = regReqSeg.send(binderSocket);
  cout << "rpcRegister Status: " << status << endl;

  if(status >= 0){
    //Success
    Segment *parsedSegment = 0;
    int result = 0;
    result = Segment::receive(binderSocket, parsedSegment);

    if(parsedSegment->getType() == MSG_TYPE_REGISTER_SUCCESS){

      cout << "MSG_TYPE_REGISTER_SUCCESS" << endl;

      Message * cast = parsedSegment->getMessage();
      //Error Checking maybe
      RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast);

      struct procedure_signature k(string(name), argTypes);

      proc_skele_dict[k] = f;

      //cout << "k: " << k.name << endl;
      mapPrint();

    }else if(parsedSegment->getType() == MSG_TYPE_REGISTER_FAILURE){
      return 0;
    }

  }else if( status < 0){
    //Error
    return -99;
  }

  return 1;
}

int rpcExecute(void){
	cout << "Running rpcExecute..." << endl;
  //Create connection socket ot be used for accepting clients
  vector<int> myConnections;
  vector<int> myToRemove;

  fd_set readfds;
  int n;
  int status;

  while(true){
    //CONNECTIONS VECTOR
    FD_ZERO(&readfds);
    FD_SET(welcomeSocket, &readfds);

    n = welcomeSocket;

    for (vector<int>::iterator it = myConnections.begin();it != myConnections.end(); ++it) {
      int connection = *it;
      FD_SET(connection, &readfds);
       if (connection > n){
        n = connection;
      }
    }

    n = n+1;

    status = select(n, &readfds, NULL, NULL, NULL);

    if (status == -1) {
      cerr << "ERROR: select failed." << endl;
    } else {

      if (FD_ISSET(welcomeSocket, &readfds)) {
				int connectionSocket = acceptConnection(welcomeSocket);
        if (connectionSocket < 0) {
          cerr << "ERROR: while accepting connection" << endl;
          continue;
        }

        myConnections.push_back(connectionSocket);

      } else {

        for (vector<int>::iterator it = myConnections.begin(); it != myConnections.end(); ++it) {
          int tempConnection = *it;
          if (FD_ISSET(tempConnection, &readfds)) {

            int reasonCode = 0;
            Segment * segment = 0;
            status = Segment::receive(tempConnection, segment);

            if(segment->getType() == MSG_TYPE_EXECUTE_REQUEST){
              Message * cast = segment->getMessage();
              ExecuteRequestMessage * eqm = dynamic_cast<ExecuteRequestMessage*>(cast);

              procedure_signature * ps = new procedure_signature(eqm->getName(), eqm->getArgTypes());
              skeleton skel = proc_skele_dict[*ps];

              int result = skel(eqm->getArgTypes(), eqm->getArgs());

              if(result == 0 ){
                ExecuteSuccessMessage exeSuccessMsg = ExecuteSuccessMessage(eqm->getName(), eqm->getArgTypes(), eqm->getArgs());
                Segment exeSuccessSeg = Segment(exeSuccessMsg.getLength(), MSG_TYPE_EXECUTE_SUCCESS, &exeSuccessMsg);
                status = exeSuccessSeg.send(tempConnection);

              }else{
                ExecuteFailureMessage exeFailMsg = ExecuteFailureMessage(reasonCode);
                Segment exeFailSeg = Segment(exeFailMsg.getLength(), MSG_TYPE_EXECUTE_FAILURE, &exeFailMsg);
                status = exeFailSeg.send(tempConnection);
              }
            }

            if (status == 0) {
              // client has closed the connection
              myToRemove.push_back(tempConnection);
              return status;
            }

          }
        }
      }

      for (vector<int>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) {
        myConnections.erase(remove(myConnections.begin(), myConnections.end(), *it), myConnections.end());
        close(*it);
      }
      myToRemove.clear();
    }
  }

  freeaddrinfo(servinfo);
  return 0;
}

int rpcCacheCall() {
	return 0;
}

int rpcTerminate() {
	cout << "Running rpcTerminate..." << endl;
	TerminateMessage messageToBinder = TerminateMessage();
	Segment segmentToBinder =
	  Segment(messageToBinder.getLength(), MSG_TYPE_TERMINATE, &messageToBinder);
	segmentToBinder.send(binderSocket);
	return 0;
}
<commit_msg>changes<commit_after>#include <cstdio>
#include <cstring>
#include <iostream>
#include <sstream>

#include <netinet/in.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <vector>
#include <algorithm>
#include <list>
#include <map>

#include <netdb.h>
#include <cstdlib>

#include "segment.h"
#include "message.h"
#include "loc_success_message.h"
#include "loc_failure_message.h"
#include "loc_request_message.h"
#include "execute_success_message.h"
#include "execute_failure_message.h"
#include "execute_request_message.h"
#include "register_success_message.h"
#include "register_failure_message.h"
#include "register_request_message.h"
#include "terminate_message.h"

#include "rpc.h"
#include "constants.h"
#include "network.h"
#include "helper_function.h"

using namespace std;

// Global variables for client
bool connectedToBinder = false;
int binderSocket = 0;

// Global variables for server
struct addrinfo* servinfo;
static map<procedure_signature, skeleton, ps_compare> proc_skele_dict;
string serverIdentifier;
unsigned int port = 0;
int welcomeSocket = 0;

void mapPrint(){
  cout << "proc_skele_dict size: "<<proc_skele_dict.size() << endl;

  cout << "Map Print: ";

  for(map<procedure_signature, skeleton>::iterator it = proc_skele_dict.begin();
   it != proc_skele_dict.end(); ++it){

    cout << it->first.name << endl;
  }

  cout << endl;
}

// See interface (header file).
int rpcInit(){
	cout << "Running rpcInit..." << endl;

	// Creates a connection socket to be used for accepting connections
	// from clients
	welcomeSocket = createSocket();
	setUpToListen(welcomeSocket);
	serverIdentifier = getHostAddress();
	port = getSocketPort(welcomeSocket);
	cout << "SERVER IDENTIFIER: " << serverIdentifier << endl;
	cout << "PORT: " << port << endl;

	// Opens a connection to the binder
	binderSocket = createSocket();
	string binderAddress = getBinderAddress();
	unsigned int binderPort = getBinderPort();
	setUpToConnect(binderSocket, binderAddress, binderPort);
  connectedToBinder = true;
  cout << "binderSocket: " << binderSocket << endl;

  return 0;
}

int sendExecute(int sock, string name, int* argTypes, void**args){

  ExecuteRequestMessage exeReqMsg = ExecuteRequestMessage(name, argTypes, args);
  Segment exeReqSeg = Segment(exeReqMsg.getLength(), MSG_TYPE_EXECUTE_REQUEST, &exeReqMsg);
  int status =  exeReqSeg.send(sock);

  int returnVal;

	string retName;
	int* retArgTypes;
	void** retArgs;

  if(status == 0){
    Segment * segment = 0;
    status = Segment::receive(sock, segment);

    if(segment->getType() == MSG_TYPE_EXECUTE_SUCCESS) {

			Message * cast = segment->getMessage();
	 		ExecuteSuccessMessage * esm = dynamic_cast<ExecuteSuccessMessage*>(cast);

			retName = esm->getName();
			retArgTypes = esm->getArgTypes();
			retArgs = esm->getArgs();

			if(retName == name){
				//extractArgumentsMessage(replyMessageP, argTypes, args, argTypesLength, false);
				returnVal = 0;
			}else{
				returnVal = 99;
			}

    }else if(segment->getType() ==  MSG_TYPE_EXECUTE_FAILURE){
  		Message * cast = segment->getMessage();
			ExecuteFailureMessage * efm = dynamic_cast<ExecuteFailureMessage*>(cast);
    	returnVal = efm->getReasonCode();
    }

  }else{ //Something bad happened
  	returnVal = 99;
  }

  return returnVal;
}

// See interface (header file).
int rpcCall(char *name, int *argTypes, void **args) {
  cout << "Flag0" << endl;

	string serverAddress;
	unsigned int serverPort;
	int status;

	if(!connectedToBinder){
		binderSocket = createSocket();
		string binderAddress = getBinderAddress();
		unsigned int binderPort = getBinderPort();
		status = setUpToConnect(binderSocket, binderAddress, binderPort);
	  connectedToBinder = true;
	}
	//do something with returnVal

  cout << "Flag1" << endl;

  LocRequestMessage locReqMsg = LocRequestMessage(name, argTypes);
  Segment locReqSeg = Segment(locReqMsg.getLength(), MSG_TYPE_LOC_REQUEST, &locReqMsg);
  int binder_status = locReqSeg.send(binderSocket);
  cout << "Flag1.5" << endl;

	//maybe error check with binder_status
  //TODO: SEGMENT FAULT IF NOT IN THIS FOR LOOP
	/**Server stuff **/
	if(binder_status >= 0){
	  cout << "Flag2" << endl;
    Segment * parsedSegment = 0;
    cout << "Flag2.1" << endl;
    int tempStatus = 0;
    cout << "Flag2.2" << endl;
    tempStatus = Segment::receive(binderSocket, parsedSegment);
    cout << "Flag2.5" << endl;

		if(parsedSegment->getType() == MSG_TYPE_LOC_SUCCESS) { //'LOC_REQUEST'
  		cout << "Got success" << endl;
      Message * cast = parsedSegment->getMessage();
  		LocSuccessMessage * lcm = dynamic_cast<LocSuccessMessage*>(cast);
	  	serverAddress = lcm->getServerIdentifier();
	  	serverPort = lcm->getPort();
	  }else if(parsedSegment->getType() == MSG_TYPE_LOC_FAILURE) {
			//something bad happens
	  	return 1;
	  }
	}

  int serverSocket = createSocket();
	int status1 = setUpToConnect(serverSocket, serverAddress, serverPort);
	status1 = sendExecute(serverSocket, string(name), argTypes, args);

	return status1;
}

  //TODO:
  // CREATE SERVER
  // CONNECT TO BINDER

int rpcRegister(char * name, int *argTypes, skeleton f){

  RegisterRequestMessage regReqMsg = RegisterRequestMessage(serverIdentifier, port, name, argTypes);
  cout << "rpcRegister name: " << name << endl;
  cout << "rpcRegister serverIdentifier: " << serverIdentifier << endl;
  cout << "rpcRegister port: " << port << endl;

  /*
  We should get seg.send to give us some feed back maybe
  int status = regReqMsg->send(binderSocket);
  */

  Segment regReqSeg = Segment(regReqMsg.getLength(), MSG_TYPE_REGISTER_REQUEST, &regReqMsg);
  int status = regReqSeg.send(binderSocket);
  cout << "rpcRegister Status: " << status << endl;

  if(status >= 0){
    //Success
    Segment *parsedSegment = 0;
    int result = 0;
    result = Segment::receive(binderSocket, parsedSegment);

    if(parsedSegment->getType() == MSG_TYPE_REGISTER_SUCCESS){

      cout << "MSG_TYPE_REGISTER_SUCCESS" << endl;

      Message * cast = parsedSegment->getMessage();
      //Error Checking maybe
      RegisterSuccessMessage * rsm = dynamic_cast<RegisterSuccessMessage*>(cast);

      struct procedure_signature k(string(name), argTypes);

      proc_skele_dict[k] = f;

      //cout << "k: " << k.name << endl;
      mapPrint();

    }else if(parsedSegment->getType() == MSG_TYPE_REGISTER_FAILURE){
      return 0;
    }

  }else if( status < 0){
    //Error
    return -99;
  }

  return 1;
}

int rpcExecute(void){
	cout << "Running rpcExecute..." << endl;
  //Create connection socket ot be used for accepting clients
  vector<int> myConnections;
  vector<int> myToRemove;

  fd_set readfds;
  int n;
  int status;

  while(true){
    //CONNECTIONS VECTOR
    FD_ZERO(&readfds);
    FD_SET(welcomeSocket, &readfds);

    n = welcomeSocket;

    for (vector<int>::iterator it = myConnections.begin();it != myConnections.end(); ++it) {
      int connection = *it;
      FD_SET(connection, &readfds);
       if (connection > n){
        n = connection;
      }
    }

    n = n+1;

    status = select(n, &readfds, NULL, NULL, NULL);

    if (status == -1) {
      cerr << "ERROR: select failed." << endl;
    } else {

      if (FD_ISSET(welcomeSocket, &readfds)) {
				int connectionSocket = acceptConnection(welcomeSocket);
        if (connectionSocket < 0) {
          cerr << "ERROR: while accepting connection" << endl;
          continue;
        }

        myConnections.push_back(connectionSocket);

      } else {

        for (vector<int>::iterator it = myConnections.begin(); it != myConnections.end(); ++it) {
          int tempConnection = *it;
          if (FD_ISSET(tempConnection, &readfds)) {

            int reasonCode = 0;
            Segment * segment = 0;
            status = Segment::receive(tempConnection, segment);

            if(segment->getType() == MSG_TYPE_EXECUTE_REQUEST){
              Message * cast = segment->getMessage();
              ExecuteRequestMessage * eqm = dynamic_cast<ExecuteRequestMessage*>(cast);

              procedure_signature * ps = new procedure_signature(eqm->getName(), eqm->getArgTypes());
              skeleton skel = proc_skele_dict[*ps];

              int result = skel(eqm->getArgTypes(), eqm->getArgs());

              if(result == 0 ){
                ExecuteSuccessMessage exeSuccessMsg = ExecuteSuccessMessage(eqm->getName(), eqm->getArgTypes(), eqm->getArgs());
                Segment exeSuccessSeg = Segment(exeSuccessMsg.getLength(), MSG_TYPE_EXECUTE_SUCCESS, &exeSuccessMsg);
                status = exeSuccessSeg.send(tempConnection);

              }else{
                ExecuteFailureMessage exeFailMsg = ExecuteFailureMessage(reasonCode);
                Segment exeFailSeg = Segment(exeFailMsg.getLength(), MSG_TYPE_EXECUTE_FAILURE, &exeFailMsg);
                status = exeFailSeg.send(tempConnection);
              }
            }

            if (status == 0) {
              // client has closed the connection
              myToRemove.push_back(tempConnection);
              return status;
            }

          }
        }
      }

      for (vector<int>::iterator it = myToRemove.begin(); it != myToRemove.end(); ++it) {
        myConnections.erase(remove(myConnections.begin(), myConnections.end(), *it), myConnections.end());
        close(*it);
      }
      myToRemove.clear();
    }
  }

  freeaddrinfo(servinfo);
  return 0;
}

int rpcCacheCall() {
	return 0;
}

int rpcTerminate() {
	cout << "Running rpcTerminate..." << endl;
	TerminateMessage messageToBinder = TerminateMessage();
	Segment segmentToBinder =
	  Segment(messageToBinder.getLength(), MSG_TYPE_TERMINATE, &messageToBinder);
	segmentToBinder.send(binderSocket);
	return 0;
}
<|endoftext|>


<commit_before><commit_msg>Also use sparse block size to align sparse extents<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *                                                                       *
 * Open Dynamics Engine, Copyright (C) 2001 Russell L. Smith.            *
 *                                                                       *
 * This library is free software; you can redistribute it and/or         *
 * modify it under the terms of the GNU Lesser General Public            *
 * License as published by the Free Software Foundation; either          *
 * version 2.1 of the License, or (at your option) any later version.    *
 *                                                                       *
 * This library is distributed in the hope that it will be useful,       *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      *
 * Lesser General Public License for more details.                       *
 *                                                                       *
 * You should have received a copy of the GNU Lesser General Public      *
 * License along with this library (see the file LICENSE.TXT); if not,   *
 * write to the Free Software Foundation, Inc., 59 Temple Place,         *
 * Suite 330, Boston, MA 02111-1307 USA.                                 *
 *                                                                       *
 *************************************************************************/

#include <string.h>
#include <errno.h>
#include "stack.h"
#include "ode/error.h"

//****************************************************************************

#ifndef WIN32

#include <unistd.h>
#include <sys/mman.h>

void dStack::init (int max_size)
{
  if (sizeof(long int) != sizeof(char*)) dDebug (0,"internal");
  if (max_size <= 0) dDebug (0,"Stack::init() given size <= 0");
  base = (char*) mmap (0,max_size, PROT_READ | PROT_WRITE,
		       MAP_PRIVATE | MAP_ANON,0,0);
  if (int(base) == -1) dError (0,"Stack::init(), mmap() failed, "
    "max_size=%d (%s)",max_size,strerror(errno));
  size = max_size;
  pointer = base;
  frame = 0;
}

void dStack::destroy()
{
  munmap (base,size);
  base = 0;
  size = 0;
  pointer = 0;
  frame = 0;
}

#endif

//****************************************************************************

#ifdef WIN32

#include "windows.h"

void dStack::init (int max_size)
{
  if (sizeof(LPVOID) != sizeof(char*)) dDebug (0,"internal");
  if (max_size <= 0) dDebug (0,"Stack::init() given size <= 0");
  base = (char*) VirtualAlloc (NULL,max_size,MEM_RESERVE,PAGE_READWRITE);
  if (base == 0) dError (0,"Stack::init(), VirtualAlloc() failed, "
    "max_size=%d",max_size);
  size = max_size;
  pointer = base;
  frame = 0;
  committed = 0;

  // get page size
  SYSTEM_INFO info;
  GetSystemInfo (&info);
  pagesize = info.dwPageSize;
}

void dStack::destroy()
{
  VirtualFree (base,0,MEM_RELEASE);
  base = 0;
  size = 0;
  pointer = 0;
  frame = 0;
}

#endif
<commit_msg>support systems like solaris (?) that dont have anonymous mmaps<commit_after>/*************************************************************************
 *                                                                       *
 * Open Dynamics Engine, Copyright (C) 2001 Russell L. Smith.            *
 *                                                                       *
 * This library is free software; you can redistribute it and/or         *
 * modify it under the terms of the GNU Lesser General Public            *
 * License as published by the Free Software Foundation; either          *
 * version 2.1 of the License, or (at your option) any later version.    *
 *                                                                       *
 * This library is distributed in the hope that it will be useful,       *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      *
 * Lesser General Public License for more details.                       *
 *                                                                       *
 * You should have received a copy of the GNU Lesser General Public      *
 * License along with this library (see the file LICENSE.TXT); if not,   *
 * write to the Free Software Foundation, Inc., 59 Temple Place,         *
 * Suite 330, Boston, MA 02111-1307 USA.                                 *
 *                                                                       *
 *************************************************************************/

#include <string.h>
#include <errno.h>
#include "stack.h"
#include "ode/error.h"
#include "ode/config.h"

//****************************************************************************
// unix version that uses mmap(). some systems have anonymous mmaps and some
// need to mmap /dev/zero.

#ifndef WIN32

#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

void dStack::init (int max_size)
{
  if (sizeof(long int) != sizeof(char*)) dDebug (0,"internal");
  if (max_size <= 0) dDebug (0,"Stack::init() given size <= 0");

#ifndef MMAP_ANONYMOUS
  static int dev_zero_fd = -1;	// cached file descriptor for /dev/zero
  if (dev_zero_fd < 0) dev_zero_fd = open ("/dev/zero", O_RDWR);
  if (dev_zero_fd < 0) dError (0,"can't open /dev/zero (%s)",strerror(errno));
  base = (char*) mmap (0,max_size, PROT_READ | PROT_WRITE, MAP_PRIVATE,
		       dev_zero_fd,0);
#else
  base = (char*) mmap (0,max_size, PROT_READ | PROT_WRITE,
		       MAP_PRIVATE | MAP_ANON,0,0);
#endif

  if (int(base) == -1) dError (0,"Stack::init(), mmap() failed, "
    "max_size=%d (%s)",max_size,strerror(errno));
  size = max_size;
  pointer = base;
  frame = 0;
}

void dStack::destroy()
{
  munmap (base,size);
  base = 0;
  size = 0;
  pointer = 0;
  frame = 0;
}

#endif

//****************************************************************************

#ifdef WIN32

#include "windows.h"

void dStack::init (int max_size)
{
  if (sizeof(LPVOID) != sizeof(char*)) dDebug (0,"internal");
  if (max_size <= 0) dDebug (0,"Stack::init() given size <= 0");
  base = (char*) VirtualAlloc (NULL,max_size,MEM_RESERVE,PAGE_READWRITE);
  if (base == 0) dError (0,"Stack::init(), VirtualAlloc() failed, "
    "max_size=%d",max_size);
  size = max_size;
  pointer = base;
  frame = 0;
  committed = 0;

  // get page size
  SYSTEM_INFO info;
  GetSystemInfo (&info);
  pagesize = info.dwPageSize;
}

void dStack::destroy()
{
  VirtualFree (base,0,MEM_RELEASE);
  base = 0;
  size = 0;
  pointer = 0;
  frame = 0;
}

#endif
<|endoftext|>