<commit_before>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2016 - 2017)
//   Rene Milk       (2016 - 2017)
//   Tobias Leibner  (2016)

#ifndef DUNE_GDT_HYPERBOLIC_PROBLEMS_MOMENTMODELS_KINETICTRANSPORTEQUATION_HH
#define DUNE_GDT_HYPERBOLIC_PROBLEMS_MOMENTMODELS_KINETICTRANSPORTEQUATION_HH

#include <dune/xt/functions/affine.hh>
#include <dune/xt/functions/checkerboard.hh>
#include <dune/xt/functions/lambda/global-function.hh>
#include <dune/xt/functions/lambda/global-flux-function.hh>

#include "../kineticequation.hh"

namespace Dune {
namespace GDT {
namespace Hyperbolic {
namespace Problems {

template <class BasisfunctionImp, class GridLayerImp, class U_, size_t quadratureDim = BasisfunctionImp::dimDomain>
class KineticTransportEquation : public KineticEquationImplementation<BasisfunctionImp, GridLayerImp, U_>,
                                 public XT::Common::ParametricInterface
{
  typedef KineticTransportEquation ThisType;
  typedef KineticEquationImplementation<BasisfunctionImp, GridLayerImp, U_> BaseType;

public:
  static const bool linear = true;
  using typename BaseType::BasisfunctionType;
  using typename BaseType::GridLayerType;
  using typename BaseType::DomainFieldType;
  using typename BaseType::StateType;
  using typename BaseType::RangeFieldType;
  using typename BaseType::DomainType;
  using typename BaseType::RangeType;
  using typename BaseType::MatrixType;
  using BaseType::dimDomain;
  using BaseType::dimRange;

  using typename BaseType::FluxType;
  using typename BaseType::RhsType;
  using typename BaseType::InitialValueType;
  using typename BaseType::BoundaryValueType;
  using typename BaseType::ActualFluxType;
  using typename BaseType::ActualRhsType;
  using typename BaseType::ActualInitialValueType;
  using typename BaseType::ActualBoundaryValueType;
  using typename BaseType::RhsAffineFunctionType;

  typedef Dune::QuadratureRule<DomainFieldType, quadratureDim> QuadratureType;

  using BaseType::default_grid_cfg;
  using BaseType::default_boundary_cfg;

  static QuadratureType default_quadrature(const XT::Common::Configuration& grid_cfg = default_grid_cfg())
  {
    std::vector<int> num_quad_cells = grid_cfg.get("num_quad_cells", std::vector<int>{2, 2, 2});
    int quad_order = grid_cfg.get("quad_order", 20);
    // quadrature that consists of a Gauss-Legendre quadrature on each cell of the velocity grid
    QuadratureType quadrature;
    Dune::FieldVector<double, quadratureDim> lower_left(-1);
    Dune::FieldVector<double, quadratureDim> upper_right(1);
    std::array<int, quadratureDim> s;
    for (size_t ii = 0; ii < quadratureDim; ++ii)
      s[ii] = num_quad_cells[ii];
    typedef typename Dune::YaspGrid<quadratureDim, Dune::EquidistantOffsetCoordinates<double, quadratureDim>> GridType;
    GridType velocity_grid(lower_left, upper_right, s);
    const auto velocity_grid_view = velocity_grid.leafGridView();
    for (const auto& entity : elements(velocity_grid_view)) {
      const auto local_quadrature = Dune::QuadratureRules<DomainFieldType, quadratureDim>::rule(
          entity.type(), quad_order, Dune::QuadratureType::GaussLegendre);
      for (const auto& quad_point : local_quadrature) {
        quadrature.push_back(Dune::QuadraturePoint<DomainFieldType, quadratureDim>(
            entity.geometry().global(quad_point.position()),
            quad_point.weight() * entity.geometry().integrationElement(quad_point.position())));
      }
    }
    return quadrature;
  }

  KineticTransportEquation(const BasisfunctionType& basis_functions,
                           const GridLayerType& grid_layer,
                           const QuadratureType quadrature = QuadratureType(),
                           DynamicVector<size_t> num_segments = {1, 1, 1},
                           const XT::Common::Configuration& grid_cfg = default_grid_cfg(),
                           const XT::Common::Configuration& boundary_cfg = default_boundary_cfg(),
                           const RangeFieldType psi_vac = 5e-9,
                           const XT::Common::ParameterType& parameter_type = XT::Common::ParameterType())
    : BaseType(basis_functions, grid_layer)
    , num_segments_(num_segments)
    , grid_cfg_(grid_cfg)
    , boundary_cfg_(boundary_cfg)
    , psi_vac_(psi_vac)
    , quadrature_(quadrature)
    , parameter_type_(parameter_type)
  {
    num_segments_.resize(dimDomain);
    if (quadrature_.empty())
      quadrature_ = default_quadrature(grid_cfg);
    if (parameter_type_.empty())
      parameter_type_ = XT::Common::ParameterType({std::make_pair("sigma_a", get_num_regions(num_segments)),
                                                   std::make_pair("sigma_s", get_num_regions(num_segments)),
                                                   std::make_pair("Q", get_num_regions(num_segments)),
                                                   std::make_pair("CFL", 1),
                                                   std::make_pair("t_end", 1)});
  }

  virtual ~KineticTransportEquation()
  {
  }

  virtual bool is_parametric() const override
  {
    return true;
  }

  virtual const XT::Common::ParameterType& parameter_type() const override
  {
    return parameter_type_;
  }

  virtual XT::Common::Parameter parameters() const = 0;

  using XT::Common::ParametricInterface::parse_parameter;

  // flux matrix A = B M^{-1} with B_{ij} = <v h_i h_j>
  virtual FluxType* create_flux() const override
  {
    // calculate B row-wise by solving M^{T} A^T = B^T column-wise
    auto A = basis_functions_.mass_matrix_with_v();
    auto M_T = basis_functions_.mass_matrix();
    transpose_in_place(M_T);
    // solve
    DynamicVector<RangeFieldType> tmp_row(M_T.N(), 0.);
    for (size_t dd = 0; dd < dimDomain; ++dd) {
      for (size_t ii = 0; ii < M_T.N(); ++ii) {
        M_T.solve(tmp_row, A[dd][ii]);
        A[dd][ii] = tmp_row;
      }
    }
    return new ActualFluxType(A, typename ActualFluxType::RangeType(0));
  }

  // RHS is (sigma_s/vol*G - sigma_t * I)u + Q<b>,
  // where sigma_t = sigma_s + sigma_a, G = <b><b>^T M^{-1} = <b>*c^T and
  // vol = <1> is the volume of the integration domain.
  virtual RhsType* create_rhs() const override
  {
    const auto param = parse_parameter(parameters());
    const size_t num_regions = get_num_regions(num_segments_);
    auto sigma_a = param.get("sigma_a");
    auto sigma_s = param.get("sigma_s");
    auto Q = param.get("Q");
    assert(sigma_a.size() == sigma_s.size() && sigma_a.size() == Q.size() && sigma_a.size() == num_regions);
    const DomainType lower_left = XT::Common::from_string<DomainType>(grid_cfg_["lower_left"]);
    const DomainType upper_right = XT::Common::from_string<DomainType>(grid_cfg_["upper_right"]);
    auto sigma_t = sigma_a;
    for (size_t ii = 0; ii < num_regions; ++ii)
      sigma_t[ii] += sigma_s[ii];
    const RangeType basis_integrated = basis_functions_.integrated();
    std::cout << "basis_integrated = " << XT::Common::to_string(basis_integrated, 15) << std::endl;
    // calculate c = M^{-T} <b>
    auto M_T = basis_functions_.mass_matrix();
    // calculate c = M^{-T} <b>
    transpose_in_place(M_T);
    RangeType c(0.);
    M_T.solve(c, basis_integrated);
    MatrixType I(dimRange, dimRange, 0.);
    for (size_t rr = 0; rr < dimRange; ++rr)
      I[rr][rr] = 1;
    MatrixType G(dimRange, dimRange, 0.);
    for (size_t rr = 0; rr < dimRange; ++rr)
      for (size_t cc = 0; cc < dimRange; ++cc)
        G[rr][cc] = basis_integrated[rr] * c[cc];
    const auto vol = unit_ball_volume();

    std::vector<RhsAffineFunctionType> affine_functions;
    for (size_t ii = 0; ii < num_regions; ++ii) {
      MatrixType G_scaled = G;
      G_scaled *= sigma_s[ii] / vol;
      MatrixType I_scaled = I;
      I_scaled *= sigma_t[ii];
      MatrixType A = G_scaled;
      A -= I_scaled;
      RangeType b = basis_integrated;
      b *= Q[ii];
      affine_functions.emplace_back(A, b, true, "rhs");
    } // ii
    return new ActualRhsType(lower_left, upper_right, num_segments_, affine_functions);
  } // ... create_rhs(...)

  // Initial value of the kinetic equation is a constant vacuum concentration psi_vac.
  // Thus, the initial value of the n-th moment is basis_integrated * psi_vac.
  virtual InitialValueType* create_initial_values() const override
  {
    const DomainType lower_left = XT::Common::from_string<DomainType>(grid_cfg_["lower_left"]);
    const DomainType upper_right = XT::Common::from_string<DomainType>(grid_cfg_["upper_right"]);
    RangeType value = basis_functions_.integrated();
    value *= psi_vac_;
    std::vector<typename ActualInitialValueType::LocalizableFunctionType> initial_vals;
    const size_t num_regions = get_num_regions(num_segments_);
    for (size_t ii = 0; ii < num_regions; ++ii)
      initial_vals.emplace_back([=](const DomainType&, const XT::Common::Parameter&) { return value; }, 0);
    return new ActualInitialValueType(lower_left, upper_right, num_segments_, initial_vals, "initial_values");
  } // ... create_initial_values()

  // Use a constant vacuum concentration basis_integrated * psi_vac as boundary value
  virtual BoundaryValueType* create_boundary_values() const override
  {
    RangeType value = basis_functions_.integrated();
    value *= psi_vac_;
    return new ActualBoundaryValueType([=](const DomainType&, const XT::Common::Parameter&) { return value; }, 0);
  } // ... create_boundary_values()

  virtual RangeFieldType CFL() const override
  {
    return parameters().get("CFL")[0];
  }

  virtual RangeFieldType t_end() const override
  {
    return parameters().get("t_end")[0];
  }

  virtual XT::Common::Configuration grid_config() const override
  {
    return grid_cfg_;
  }

  virtual XT::Common::Configuration boundary_config() const override
  {
    return boundary_cfg_;
  }

  static std::string static_id()
  {
    return "kinetictransportequation";
  }

  virtual const QuadratureType& quadrature() const
  {
    return quadrature_;
  }

protected:
  static size_t get_num_regions(const DynamicVector<size_t>& num_segments)
  {
    return std::accumulate(num_segments.begin(), num_segments.end(), 1, [](auto a, auto b) { return a * b; });
  }

  static RangeFieldType unit_ball_volume()
  {
    if (BasisfunctionType::dimDomain == 1)
      return 2;
    else if (BasisfunctionType::dimDomain == 2)
      return 2 * M_PI;
    else if (BasisfunctionType::dimDomain == 3)
      return 4 * M_PI;
    else {
      DUNE_THROW(NotImplemented, "");
      return 0;
    }
  }

  template <class MatrixType>
  void transpose_in_place(MatrixType& M) const
  {
    for (size_t rr = 0; rr < dimRange; ++rr)
      for (size_t cc = 0; cc < rr; ++cc) {
        auto tmp_val = M[cc][rr];
        M[cc][rr] = M[rr][cc];
        M[rr][cc] = tmp_val;
      }
  }

  using BaseType::basis_functions_;
  DynamicVector<size_t> num_segments_;
  const XT::Common::Configuration grid_cfg_;
  const XT::Common::Configuration boundary_cfg_;
  const RangeFieldType psi_vac_;
  QuadratureType quadrature_;
  XT::Common::ParameterType parameter_type_;
}; // class KineticTransportEquation<...>

} // namespace Problems
} // namespace Hyperbolic
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_HYPERBOLIC_PROBLEMS_MOMENTMODELS_KINETICTRANSPORTEQUATION_HH
<commit_msg>[test.hyperbolic...kinetictransportequation] fix parameter_type<commit_after>// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2016 - 2017)
//   Rene Milk       (2016 - 2017)
//   Tobias Leibner  (2016)

#ifndef DUNE_GDT_HYPERBOLIC_PROBLEMS_MOMENTMODELS_KINETICTRANSPORTEQUATION_HH
#define DUNE_GDT_HYPERBOLIC_PROBLEMS_MOMENTMODELS_KINETICTRANSPORTEQUATION_HH

#include <dune/xt/functions/affine.hh>
#include <dune/xt/functions/checkerboard.hh>
#include <dune/xt/functions/lambda/global-function.hh>
#include <dune/xt/functions/lambda/global-flux-function.hh>

#include "../kineticequation.hh"

namespace Dune {
namespace GDT {
namespace Hyperbolic {
namespace Problems {

template <class BasisfunctionImp, class GridLayerImp, class U_, size_t quadratureDim = BasisfunctionImp::dimDomain>
class KineticTransportEquation : public KineticEquationImplementation<BasisfunctionImp, GridLayerImp, U_>,
                                 public XT::Common::ParametricInterface
{
  typedef KineticTransportEquation ThisType;
  typedef KineticEquationImplementation<BasisfunctionImp, GridLayerImp, U_> BaseType;

public:
  static const bool linear = true;
  using typename BaseType::BasisfunctionType;
  using typename BaseType::GridLayerType;
  using typename BaseType::DomainFieldType;
  using typename BaseType::StateType;
  using typename BaseType::RangeFieldType;
  using typename BaseType::DomainType;
  using typename BaseType::RangeType;
  using typename BaseType::MatrixType;
  using BaseType::dimDomain;
  using BaseType::dimRange;

  using typename BaseType::FluxType;
  using typename BaseType::RhsType;
  using typename BaseType::InitialValueType;
  using typename BaseType::BoundaryValueType;
  using typename BaseType::ActualFluxType;
  using typename BaseType::ActualRhsType;
  using typename BaseType::ActualInitialValueType;
  using typename BaseType::ActualBoundaryValueType;
  using typename BaseType::RhsAffineFunctionType;

  typedef Dune::QuadratureRule<DomainFieldType, quadratureDim> QuadratureType;

  using BaseType::default_grid_cfg;
  using BaseType::default_boundary_cfg;

  static QuadratureType default_quadrature(const XT::Common::Configuration& grid_cfg = default_grid_cfg())
  {
    std::vector<int> num_quad_cells = grid_cfg.get("num_quad_cells", std::vector<int>{2, 2, 2});
    int quad_order = grid_cfg.get("quad_order", 20);
    // quadrature that consists of a Gauss-Legendre quadrature on each cell of the velocity grid
    QuadratureType quadrature;
    Dune::FieldVector<double, quadratureDim> lower_left(-1);
    Dune::FieldVector<double, quadratureDim> upper_right(1);
    std::array<int, quadratureDim> s;
    for (size_t ii = 0; ii < quadratureDim; ++ii)
      s[ii] = num_quad_cells[ii];
    typedef typename Dune::YaspGrid<quadratureDim, Dune::EquidistantOffsetCoordinates<double, quadratureDim>> GridType;
    GridType velocity_grid(lower_left, upper_right, s);
    const auto velocity_grid_view = velocity_grid.leafGridView();
    for (const auto& entity : elements(velocity_grid_view)) {
      const auto local_quadrature = Dune::QuadratureRules<DomainFieldType, quadratureDim>::rule(
          entity.type(), quad_order, Dune::QuadratureType::GaussLegendre);
      for (const auto& quad_point : local_quadrature) {
        quadrature.push_back(Dune::QuadraturePoint<DomainFieldType, quadratureDim>(
            entity.geometry().global(quad_point.position()),
            quad_point.weight() * entity.geometry().integrationElement(quad_point.position())));
      }
    }
    return quadrature;
  }

  KineticTransportEquation(const BasisfunctionType& basis_functions,
                           const GridLayerType& grid_layer,
                           const QuadratureType quadrature = QuadratureType(),
                           DynamicVector<size_t> num_segments = {1, 1, 1},
                           const XT::Common::Configuration& grid_cfg = default_grid_cfg(),
                           const XT::Common::Configuration& boundary_cfg = default_boundary_cfg(),
                           const RangeFieldType psi_vac = 5e-9,
                           const XT::Common::ParameterType& parameter_type = XT::Common::ParameterType())
    : BaseType(basis_functions, grid_layer)
    , num_segments_(num_segments)
    , grid_cfg_(grid_cfg)
    , boundary_cfg_(boundary_cfg)
    , psi_vac_(psi_vac)
    , quadrature_(quadrature)
    , parameter_type_(parameter_type)
  {
    num_segments_.resize(dimDomain);
    if (quadrature_.empty())
      quadrature_ = default_quadrature(grid_cfg);
    if (parameter_type_.empty())
      parameter_type_ = XT::Common::ParameterType({std::make_pair("sigma_a", get_num_regions(num_segments_)),
                                                   std::make_pair("sigma_s", get_num_regions(num_segments_)),
                                                   std::make_pair("Q", get_num_regions(num_segments_)),
                                                   std::make_pair("CFL", 1),
                                                   std::make_pair("t_end", 1)});
  }

  virtual ~KineticTransportEquation()
  {
  }

  virtual bool is_parametric() const override
  {
    return true;
  }

  virtual const XT::Common::ParameterType& parameter_type() const override
  {
    return parameter_type_;
  }

  virtual XT::Common::Parameter parameters() const = 0;

  using XT::Common::ParametricInterface::parse_parameter;

  // flux matrix A = B M^{-1} with B_{ij} = <v h_i h_j>
  virtual FluxType* create_flux() const override
  {
    // calculate B row-wise by solving M^{T} A^T = B^T column-wise
    auto A = basis_functions_.mass_matrix_with_v();
    auto M_T = basis_functions_.mass_matrix();
    transpose_in_place(M_T);
    // solve
    DynamicVector<RangeFieldType> tmp_row(M_T.N(), 0.);
    for (size_t dd = 0; dd < dimDomain; ++dd) {
      for (size_t ii = 0; ii < M_T.N(); ++ii) {
        M_T.solve(tmp_row, A[dd][ii]);
        A[dd][ii] = tmp_row;
      }
    }
    return new ActualFluxType(A, typename ActualFluxType::RangeType(0));
  }

  // RHS is (sigma_s/vol*G - sigma_t * I)u + Q<b>,
  // where sigma_t = sigma_s + sigma_a, G = <b><b>^T M^{-1} = <b>*c^T and
  // vol = <1> is the volume of the integration domain.
  virtual RhsType* create_rhs() const override
  {
    const auto param = parse_parameter(parameters());
    const size_t num_regions = get_num_regions(num_segments_);
    auto sigma_a = param.get("sigma_a");
    auto sigma_s = param.get("sigma_s");
    auto Q = param.get("Q");
    assert(sigma_a.size() == sigma_s.size() && sigma_a.size() == Q.size() && sigma_a.size() == num_regions);
    const DomainType lower_left = XT::Common::from_string<DomainType>(grid_cfg_["lower_left"]);
    const DomainType upper_right = XT::Common::from_string<DomainType>(grid_cfg_["upper_right"]);
    auto sigma_t = sigma_a;
    for (size_t ii = 0; ii < num_regions; ++ii)
      sigma_t[ii] += sigma_s[ii];
    const RangeType basis_integrated = basis_functions_.integrated();
    std::cout << "basis_integrated = " << XT::Common::to_string(basis_integrated, 15) << std::endl;
    // calculate c = M^{-T} <b>
    auto M_T = basis_functions_.mass_matrix();
    // calculate c = M^{-T} <b>
    transpose_in_place(M_T);
    RangeType c(0.);
    M_T.solve(c, basis_integrated);
    MatrixType I(dimRange, dimRange, 0.);
    for (size_t rr = 0; rr < dimRange; ++rr)
      I[rr][rr] = 1;
    MatrixType G(dimRange, dimRange, 0.);
    for (size_t rr = 0; rr < dimRange; ++rr)
      for (size_t cc = 0; cc < dimRange; ++cc)
        G[rr][cc] = basis_integrated[rr] * c[cc];
    const auto vol = unit_ball_volume();

    std::vector<RhsAffineFunctionType> affine_functions;
    for (size_t ii = 0; ii < num_regions; ++ii) {
      MatrixType G_scaled = G;
      G_scaled *= sigma_s[ii] / vol;
      MatrixType I_scaled = I;
      I_scaled *= sigma_t[ii];
      MatrixType A = G_scaled;
      A -= I_scaled;
      RangeType b = basis_integrated;
      b *= Q[ii];
      affine_functions.emplace_back(A, b, true, "rhs");
    } // ii
    return new ActualRhsType(lower_left, upper_right, num_segments_, affine_functions);
  } // ... create_rhs(...)

  // Initial value of the kinetic equation is a constant vacuum concentration psi_vac.
  // Thus, the initial value of the n-th moment is basis_integrated * psi_vac.
  virtual InitialValueType* create_initial_values() const override
  {
    const DomainType lower_left = XT::Common::from_string<DomainType>(grid_cfg_["lower_left"]);
    const DomainType upper_right = XT::Common::from_string<DomainType>(grid_cfg_["upper_right"]);
    RangeType value = basis_functions_.integrated();
    value *= psi_vac_;
    std::vector<typename ActualInitialValueType::LocalizableFunctionType> initial_vals;
    const size_t num_regions = get_num_regions(num_segments_);
    for (size_t ii = 0; ii < num_regions; ++ii)
      initial_vals.emplace_back([=](const DomainType&, const XT::Common::Parameter&) { return value; }, 0);
    return new ActualInitialValueType(lower_left, upper_right, num_segments_, initial_vals, "initial_values");
  } // ... create_initial_values()

  // Use a constant vacuum concentration basis_integrated * psi_vac as boundary value
  virtual BoundaryValueType* create_boundary_values() const override
  {
    RangeType value = basis_functions_.integrated();
    value *= psi_vac_;
    return new ActualBoundaryValueType([=](const DomainType&, const XT::Common::Parameter&) { return value; }, 0);
  } // ... create_boundary_values()

  virtual RangeFieldType CFL() const override
  {
    return parameters().get("CFL")[0];
  }

  virtual RangeFieldType t_end() const override
  {
    return parameters().get("t_end")[0];
  }

  virtual XT::Common::Configuration grid_config() const override
  {
    return grid_cfg_;
  }

  virtual XT::Common::Configuration boundary_config() const override
  {
    return boundary_cfg_;
  }

  static std::string static_id()
  {
    return "kinetictransportequation";
  }

  virtual const QuadratureType& quadrature() const
  {
    return quadrature_;
  }

protected:
  static size_t get_num_regions(const DynamicVector<size_t>& num_segments)
  {
    return std::accumulate(num_segments.begin(), num_segments.end(), 1, [](auto a, auto b) { return a * b; });
  }

  static RangeFieldType unit_ball_volume()
  {
    if (BasisfunctionType::dimDomain == 1)
      return 2;
    else if (BasisfunctionType::dimDomain == 2)
      return 2 * M_PI;
    else if (BasisfunctionType::dimDomain == 3)
      return 4 * M_PI;
    else {
      DUNE_THROW(NotImplemented, "");
      return 0;
    }
  }

  template <class MatrixType>
  void transpose_in_place(MatrixType& M) const
  {
    for (size_t rr = 0; rr < dimRange; ++rr)
      for (size_t cc = 0; cc < rr; ++cc) {
        auto tmp_val = M[cc][rr];
        M[cc][rr] = M[rr][cc];
        M[rr][cc] = tmp_val;
      }
  }

  using BaseType::basis_functions_;
  DynamicVector<size_t> num_segments_;
  const XT::Common::Configuration grid_cfg_;
  const XT::Common::Configuration boundary_cfg_;
  const RangeFieldType psi_vac_;
  QuadratureType quadrature_;
  XT::Common::ParameterType parameter_type_;
}; // class KineticTransportEquation<...>

} // namespace Problems
} // namespace Hyperbolic
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_HYPERBOLIC_PROBLEMS_MOMENTMODELS_KINETICTRANSPORTEQUATION_HH
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

/*
 * Copyright 2014 Cloudius Systems
 *
 * Modified by Cloudius Systems
 */

#ifndef CQL3_CFNAME_HH
#define CQL3_CFNAME_HH

#include <experimental/optional>

namespace cql3 {

class cf_name {
private:
    std::experimental::optional<sstring> _ks_name;
    sstring _cf_name;

public:
    void set_keyspace(sstring ks, bool keep_case) {
        if (!keep_case) {
            std::transform(ks.begin(), ks.end(), ks.begin(), ::tolower);
        }
        _ks_name = std::experimental::make_optional(ks);
    }

    void set_column_family(sstring cf, bool keep_case) {
        _cf_name = cf;
        if (!keep_case) {
            std::transform(_cf_name.begin(), _cf_name.end(), _cf_name.begin(), ::tolower);
        }
    }
    bool has_keyspace() const {
        return _ks_name ? true : false;
    }

    sstring get_keyspace() const {
        return *_ks_name;
    }

    sstring get_column_family() const {
        return _cf_name;
    }

    friend std::ostream& operator<<(std::ostream& os, const cf_name& n);
};

std::ostream&
operator<<(std::ostream& os, const cf_name& n) {
    if (n.has_keyspace()) {
        os << n.get_keyspace() << ".";
    }
    os << n.get_column_family();
    return os;
}

}

#endif
<commit_msg>cql3: Make cf_name operator<< inline to avoid multiple copies<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

/*
 * Copyright 2014 Cloudius Systems
 *
 * Modified by Cloudius Systems
 */

#ifndef CQL3_CFNAME_HH
#define CQL3_CFNAME_HH

#include <experimental/optional>

namespace cql3 {

class cf_name {
private:
    std::experimental::optional<sstring> _ks_name;
    sstring _cf_name;

public:
    void set_keyspace(sstring ks, bool keep_case) {
        if (!keep_case) {
            std::transform(ks.begin(), ks.end(), ks.begin(), ::tolower);
        }
        _ks_name = std::experimental::make_optional(ks);
    }

    void set_column_family(sstring cf, bool keep_case) {
        _cf_name = cf;
        if (!keep_case) {
            std::transform(_cf_name.begin(), _cf_name.end(), _cf_name.begin(), ::tolower);
        }
    }
    bool has_keyspace() const {
        return _ks_name ? true : false;
    }

    sstring get_keyspace() const {
        return *_ks_name;
    }

    sstring get_column_family() const {
        return _cf_name;
    }

    friend std::ostream& operator<<(std::ostream& os, const cf_name& n);
};

inline
std::ostream&
operator<<(std::ostream& os, const cf_name& n) {
    if (n.has_keyspace()) {
        os << n.get_keyspace() << ".";
    }
    os << n.get_column_family();
    return os;
}

}

#endif
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008, 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "fileutils.h"
#include "infoxmlbackend.h"

class InfoXmlBackendUnitTest : public QObject
{
    Q_OBJECT
    InfoXmlBackend *backend;

private slots:
    void initTestCase();
    void listKeys();
    void listPlugins();
    void listKeysForPlugin();
};

void InfoXmlBackendUnitTest::initTestCase()
{
    utilSetEnv("CONTEXT_PROVIDERS", LOCAL_DIR);
    utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null");
    backend = new InfoXmlBackend();
}

void InfoXmlBackendUnitTest::listKeys()
{
    QStringList keys = backend->listKeys();
    QVERIFY(keys.contains("Battery.ChargePercentage"));
    QVERIFY(keys.contains("Battery.LowBattery"));
    QVERIFY(keys.contains("Key.With.Attribute"));
    QVERIFY(keys.contains("Key.With.bool"));
    QVERIFY(keys.contains("Key.With.int32"));
    QVERIFY(keys.contains("Key.With.string"));
    QVERIFY(keys.contains("Key.With.double"));
    QVERIFY(keys.contains("Key.With.complex"));
    QVERIFY(keys.contains("Battery.Charging"));
    QVERIFY(keys.contains("Battery.ChargePercentage"));
}

void InfoXmlBackendUnitTest::listPlugins()
{
    QStringList plugins = backend->listPlugins();
    QCOMPARE(plugins.count(), 1);
    QVERIFY(plugins.contains("contextkit-dbus"));
}

void InfoXmlBackendUnitTest::listKeysForPlugin()
{
    QStringList keys = backend->listKeysForPlugin("contextkit-dbus");
    QVERIFY(keys.contains("Battery.ChargePercentage"));
    QVERIFY(keys.contains("Battery.LowBattery"));
    QVERIFY(keys.contains("Key.With.Attribute"));
    QVERIFY(keys.contains("Key.With.bool"));
    QVERIFY(keys.contains("Key.With.int32"));
    QVERIFY(keys.contains("Key.With.string"));
    QVERIFY(keys.contains("Key.With.double"));
    QVERIFY(keys.contains("Key.With.complex"));
    QVERIFY(keys.contains("Battery.Charging"));
    QVERIFY(keys.contains("Battery.ChargePercentage"));
}

#include "infoxmlbackendunittest.moc"
QTEST_MAIN(InfoXmlBackendUnitTest);
<commit_msg>typeForKey.<commit_after>/*
 * Copyright (C) 2008, 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "fileutils.h"
#include "infoxmlbackend.h"

class InfoXmlBackendUnitTest : public QObject
{
    Q_OBJECT
    InfoXmlBackend *backend;

private slots:
    void initTestCase();
    void listKeys();
    void listPlugins();
    void listKeysForPlugin();
    void typeForKey();
};

void InfoXmlBackendUnitTest::initTestCase()
{
    utilSetEnv("CONTEXT_PROVIDERS", LOCAL_DIR);
    utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null");
    backend = new InfoXmlBackend();
}

void InfoXmlBackendUnitTest::listKeys()
{
    QStringList keys = backend->listKeys();
    QVERIFY(keys.contains("Battery.ChargePercentage"));
    QVERIFY(keys.contains("Battery.LowBattery"));
    QVERIFY(keys.contains("Key.With.Attribute"));
    QVERIFY(keys.contains("Key.With.bool"));
    QVERIFY(keys.contains("Key.With.int32"));
    QVERIFY(keys.contains("Key.With.string"));
    QVERIFY(keys.contains("Key.With.double"));
    QVERIFY(keys.contains("Key.With.complex"));
    QVERIFY(keys.contains("Battery.Charging"));
    QVERIFY(keys.contains("Battery.ChargePercentage"));
}

void InfoXmlBackendUnitTest::listPlugins()
{
    QStringList plugins = backend->listPlugins();
    QCOMPARE(plugins.count(), 1);
    QVERIFY(plugins.contains("contextkit-dbus"));
}

void InfoXmlBackendUnitTest::listKeysForPlugin()
{
    QStringList keys = backend->listKeysForPlugin("contextkit-dbus");
    QVERIFY(keys.contains("Battery.ChargePercentage"));
    QVERIFY(keys.contains("Battery.LowBattery"));
    QVERIFY(keys.contains("Key.With.Attribute"));
    QVERIFY(keys.contains("Key.With.bool"));
    QVERIFY(keys.contains("Key.With.int32"));
    QVERIFY(keys.contains("Key.With.string"));
    QVERIFY(keys.contains("Key.With.double"));
    QVERIFY(keys.contains("Key.With.complex"));
    QVERIFY(keys.contains("Battery.Charging"));
}

void InfoXmlBackendUnitTest::typeForKey()
{
    QCOMPARE(backend->typeForKey("Battery.ChargePercentage"), QString());
    QCOMPARE(backend->typeForKey("Key.With.Attribute"), QString("TRUTH"));
    QCOMPARE(backend->typeForKey("Battery.LowBattery"), QString("TRUTH"));
    QCOMPARE(backend->typeForKey("Key.With.bool"), QString("TRUTH"));
    QCOMPARE(backend->typeForKey("Key.With.int32"), QString("INT"));
    QCOMPARE(backend->typeForKey("Key.With.string"), QString("STRING"));
    QCOMPARE(backend->typeForKey("Key.With.double"), QString("DOUBLE"));
    QCOMPARE(backend->typeForKey("Key.With.complex"), QString());
    QCOMPARE(backend->typeForKey("Battery.Charging"), QString("TRUTH"));
}

#include "infoxmlbackendunittest.moc"
QTEST_MAIN(InfoXmlBackendUnitTest);
<|endoftext|>


<commit_before>/*
 * Copyright 2003,2004 The Apache Software Foundation.
 *
 * 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.
 */

/*
 * $Log$
 * Revision 1.13  2004/09/08 13:56:08  peiyongz
 * Apache License Version 2.0
 *
 * Revision 1.12  2004/01/29 11:46:30  cargilld
 * Code cleanup changes to get rid of various compiler diagnostic messages.
 *
 * Revision 1.11  2003/12/24 17:42:02  knoaman
 * Misc. PSVI updates
 *
 * Revision 1.10  2003/12/19 15:09:47  knoaman
 * PSVI: process 'final' information
 *
 * Revision 1.9  2003/12/15 17:23:48  cargilld
 * psvi updates; cleanup revisits and bug fixes
 *
 * Revision 1.8  2003/11/27 16:42:00  neilg
 * fixes for segfaults and infinite loops in schema component model implementation; thanks to David Cargill
 *
 * Revision 1.7  2003/11/25 18:08:31  knoaman
 * Misc. PSVI updates. Thanks to David Cargill.
 *
 * Revision 1.6  2003/11/21 17:19:30  knoaman
 * PSVI update.
 *
 * Revision 1.5  2003/11/14 22:47:53  neilg
 * fix bogus log message from previous commit...
 *
 * Revision 1.4  2003/11/14 22:33:30  neilg
 * Second phase of schema component model implementation.
 * Implement XSModel, XSNamespaceItem, and the plumbing necessary
 * to connect them to the other components.
 * Thanks to David Cargill.
 *
 * Revision 1.3  2003/11/10 21:56:54  neilg
 * make internal code use the new, stateless, method of traversing attribute lists
 *
 * Revision 1.2  2003/11/06 15:30:04  neilg
 * first part of PSVI/schema component model implementation, thanks to David Cargill.  This covers setting the PSVIHandler on parser objects, as well as implementing XSNotation, XSSimpleTypeDefinition, XSIDCDefinition, and most of XSWildcard, XSComplexTypeDefinition, XSElementDeclaration, XSAttributeDeclaration and XSAttributeUse.
 *
 * Revision 1.1  2003/09/16 14:33:36  neilg
 * PSVI/schema component model classes, with Makefile/configuration changes necessary to build them
 *
 */

#include <xercesc/framework/psvi/XSComplexTypeDefinition.hpp>
#include <xercesc/framework/psvi/XSWildcard.hpp>
#include <xercesc/framework/psvi/XSSimpleTypeDefinition.hpp>
#include <xercesc/framework/psvi/XSAttributeUse.hpp>
#include <xercesc/framework/psvi/XSModel.hpp>
#include <xercesc/framework/psvi/XSAnnotation.hpp>
#include <xercesc/framework/psvi/XSParticle.hpp>
#include <xercesc/validators/schema/ComplexTypeInfo.hpp>
#include <xercesc/validators/schema/SchemaElementDecl.hpp>
#include <xercesc/validators/schema/SchemaAttDefList.hpp>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  XSComplexTypeDefinition: Constructors and Destructor
// ---------------------------------------------------------------------------
XSComplexTypeDefinition::XSComplexTypeDefinition
(
    ComplexTypeInfo* const          complexTypeInfo
    , XSWildcard* const             xsWildcard
    , XSSimpleTypeDefinition* const xsSimpleType
    , XSAttributeUseList* const     xsAttList
    , XSTypeDefinition* const       xsBaseType
    , XSParticle* const             xsParticle
    , XSAnnotation* const           headAnnot
    , XSModel* const                xsModel
    , MemoryManager* const          manager
)
    : XSTypeDefinition(COMPLEX_TYPE, xsBaseType, xsModel, manager)
    , fComplexTypeInfo(complexTypeInfo)
    , fXSWildcard(xsWildcard)
    , fXSAttributeUseList(xsAttList)
    , fXSSimpleTypeDefinition(xsSimpleType)
    , fXSAnnotationList(0)
    , fParticle(xsParticle)
    , fProhibitedSubstitution(0)
{
    int blockset = fComplexTypeInfo->getBlockSet();
    if (blockset)
    {
        if (blockset & SchemaSymbols::XSD_EXTENSION)
            fProhibitedSubstitution |= XSConstants::DERIVATION_EXTENSION;

        if (blockset & SchemaSymbols::XSD_RESTRICTION)
            fProhibitedSubstitution |= XSConstants::DERIVATION_RESTRICTION;
    }

    int finalSet = fComplexTypeInfo->getFinalSet();
    if (finalSet)
    {
        if (finalSet & SchemaSymbols::XSD_EXTENSION)
            fFinal |= XSConstants::DERIVATION_EXTENSION;

        if (finalSet & SchemaSymbols::XSD_RESTRICTION)
            fFinal |= XSConstants::DERIVATION_RESTRICTION;
    }

    if (headAnnot)
    {
        fXSAnnotationList = new (manager) RefVectorOf<XSAnnotation>(1, false, manager);
        XSAnnotation* annot = headAnnot;

        do
        {
            fXSAnnotationList->addElement(annot);
            annot = annot->getNext();
        } while (annot);
    }
}

XSComplexTypeDefinition::~XSComplexTypeDefinition()
{
    // don't delete fXSWildcard - deleted by XSModel
    // don't delete fXSSimpleTypeDefinition - deleted by XSModel
    if (fXSAttributeUseList)
        delete fXSAttributeUseList;

    if (fXSAnnotationList)
        delete fXSAnnotationList;

    if (fParticle)
        delete fParticle;
}

// ---------------------------------------------------------------------------
//  XSComplexTypeDefinition: access methods
// ---------------------------------------------------------------------------
XSConstants::DERIVATION_TYPE XSComplexTypeDefinition::getDerivationMethod() const
{
    if(fComplexTypeInfo->getDerivedBy() == SchemaSymbols::XSD_EXTENSION)
        return XSConstants::DERIVATION_EXTENSION;
    return XSConstants::DERIVATION_RESTRICTION;
}

bool XSComplexTypeDefinition::getAbstract() const
{
    return fComplexTypeInfo->getAbstract();
}

XSComplexTypeDefinition::CONTENT_TYPE XSComplexTypeDefinition::getContentType() const
{
    switch(fComplexTypeInfo->getContentType()) {
        case SchemaElementDecl::Simple:
            return CONTENTTYPE_SIMPLE;
        case SchemaElementDecl::Empty:
            return CONTENTTYPE_EMPTY;
        case SchemaElementDecl::Children:
            return CONTENTTYPE_ELEMENT;
        default:
            //case SchemaElementDecl::Mixed_Complex:
            //case SchemaElementDecl::Mixed_Simple:
            //case SchemaElementDecl::Any:
            return CONTENTTYPE_MIXED;
    }
}

bool XSComplexTypeDefinition::isProhibitedSubstitution(XSConstants::DERIVATION_TYPE toTest)
{
    if (fProhibitedSubstitution & toTest)
        return true;

    return false;
}

XSAnnotationList *XSComplexTypeDefinition::getAnnotations()
{
    return fXSAnnotationList;
}

// ---------------------------------------------------------------------------
//  XSComplexTypeDefinition: virtual methods
// ---------------------------------------------------------------------------
const XMLCh *XSComplexTypeDefinition::getName()
{
    return fComplexTypeInfo->getTypeLocalName();
}

const XMLCh *XSComplexTypeDefinition::getNamespace()
{
    return fComplexTypeInfo->getTypeUri();
}

XSNamespaceItem *XSComplexTypeDefinition::getNamespaceItem()
{
    return fXSModel->getNamespaceItem(getNamespace());
}

bool XSComplexTypeDefinition::getAnonymous() const
{
    return fComplexTypeInfo->getAnonymous();
}

XSTypeDefinition *XSComplexTypeDefinition::getBaseType()
{
    return fBaseType;
}

bool XSComplexTypeDefinition::derivedFromType(const XSTypeDefinition * const ancestorType)
{
    if (!ancestorType)
        return false;

    XSTypeDefinition* type = this;

    while (type && (type != ancestorType))
    {
        type = type->getBaseType();
    }

    return (type == ancestorType);
}

XERCES_CPP_NAMESPACE_END
<commit_msg>Fix for jira bug 1234.  Infinite loop in XSComplexTypeDefinition::derviedFromType.<commit_after>/*
 * Copyright 2003,2004 The Apache Software Foundation.
 *
 * 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.
 */

/*
 * $Log$
 * Revision 1.14  2004/10/15 11:15:44  cargilld
 * Fix for jira bug 1234.  Infinite loop in XSComplexTypeDefinition::derviedFromType.
 *
 * Revision 1.13  2004/09/08 13:56:08  peiyongz
 * Apache License Version 2.0
 *
 * Revision 1.12  2004/01/29 11:46:30  cargilld
 * Code cleanup changes to get rid of various compiler diagnostic messages.
 *
 * Revision 1.11  2003/12/24 17:42:02  knoaman
 * Misc. PSVI updates
 *
 * Revision 1.10  2003/12/19 15:09:47  knoaman
 * PSVI: process 'final' information
 *
 * Revision 1.9  2003/12/15 17:23:48  cargilld
 * psvi updates; cleanup revisits and bug fixes
 *
 * Revision 1.8  2003/11/27 16:42:00  neilg
 * fixes for segfaults and infinite loops in schema component model implementation; thanks to David Cargill
 *
 * Revision 1.7  2003/11/25 18:08:31  knoaman
 * Misc. PSVI updates. Thanks to David Cargill.
 *
 * Revision 1.6  2003/11/21 17:19:30  knoaman
 * PSVI update.
 *
 * Revision 1.5  2003/11/14 22:47:53  neilg
 * fix bogus log message from previous commit...
 *
 * Revision 1.4  2003/11/14 22:33:30  neilg
 * Second phase of schema component model implementation.
 * Implement XSModel, XSNamespaceItem, and the plumbing necessary
 * to connect them to the other components.
 * Thanks to David Cargill.
 *
 * Revision 1.3  2003/11/10 21:56:54  neilg
 * make internal code use the new, stateless, method of traversing attribute lists
 *
 * Revision 1.2  2003/11/06 15:30:04  neilg
 * first part of PSVI/schema component model implementation, thanks to David Cargill.  This covers setting the PSVIHandler on parser objects, as well as implementing XSNotation, XSSimpleTypeDefinition, XSIDCDefinition, and most of XSWildcard, XSComplexTypeDefinition, XSElementDeclaration, XSAttributeDeclaration and XSAttributeUse.
 *
 * Revision 1.1  2003/09/16 14:33:36  neilg
 * PSVI/schema component model classes, with Makefile/configuration changes necessary to build them
 *
 */

#include <xercesc/framework/psvi/XSComplexTypeDefinition.hpp>
#include <xercesc/framework/psvi/XSWildcard.hpp>
#include <xercesc/framework/psvi/XSSimpleTypeDefinition.hpp>
#include <xercesc/framework/psvi/XSAttributeUse.hpp>
#include <xercesc/framework/psvi/XSModel.hpp>
#include <xercesc/framework/psvi/XSAnnotation.hpp>
#include <xercesc/framework/psvi/XSParticle.hpp>
#include <xercesc/validators/schema/ComplexTypeInfo.hpp>
#include <xercesc/validators/schema/SchemaElementDecl.hpp>
#include <xercesc/validators/schema/SchemaAttDefList.hpp>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  XSComplexTypeDefinition: Constructors and Destructor
// ---------------------------------------------------------------------------
XSComplexTypeDefinition::XSComplexTypeDefinition
(
    ComplexTypeInfo* const          complexTypeInfo
    , XSWildcard* const             xsWildcard
    , XSSimpleTypeDefinition* const xsSimpleType
    , XSAttributeUseList* const     xsAttList
    , XSTypeDefinition* const       xsBaseType
    , XSParticle* const             xsParticle
    , XSAnnotation* const           headAnnot
    , XSModel* const                xsModel
    , MemoryManager* const          manager
)
    : XSTypeDefinition(COMPLEX_TYPE, xsBaseType, xsModel, manager)
    , fComplexTypeInfo(complexTypeInfo)
    , fXSWildcard(xsWildcard)
    , fXSAttributeUseList(xsAttList)
    , fXSSimpleTypeDefinition(xsSimpleType)
    , fXSAnnotationList(0)
    , fParticle(xsParticle)
    , fProhibitedSubstitution(0)
{
    int blockset = fComplexTypeInfo->getBlockSet();
    if (blockset)
    {
        if (blockset & SchemaSymbols::XSD_EXTENSION)
            fProhibitedSubstitution |= XSConstants::DERIVATION_EXTENSION;

        if (blockset & SchemaSymbols::XSD_RESTRICTION)
            fProhibitedSubstitution |= XSConstants::DERIVATION_RESTRICTION;
    }

    int finalSet = fComplexTypeInfo->getFinalSet();
    if (finalSet)
    {
        if (finalSet & SchemaSymbols::XSD_EXTENSION)
            fFinal |= XSConstants::DERIVATION_EXTENSION;

        if (finalSet & SchemaSymbols::XSD_RESTRICTION)
            fFinal |= XSConstants::DERIVATION_RESTRICTION;
    }

    if (headAnnot)
    {
        fXSAnnotationList = new (manager) RefVectorOf<XSAnnotation>(1, false, manager);
        XSAnnotation* annot = headAnnot;

        do
        {
            fXSAnnotationList->addElement(annot);
            annot = annot->getNext();
        } while (annot);
    }
}

XSComplexTypeDefinition::~XSComplexTypeDefinition()
{
    // don't delete fXSWildcard - deleted by XSModel
    // don't delete fXSSimpleTypeDefinition - deleted by XSModel
    if (fXSAttributeUseList)
        delete fXSAttributeUseList;

    if (fXSAnnotationList)
        delete fXSAnnotationList;

    if (fParticle)
        delete fParticle;
}

// ---------------------------------------------------------------------------
//  XSComplexTypeDefinition: access methods
// ---------------------------------------------------------------------------
XSConstants::DERIVATION_TYPE XSComplexTypeDefinition::getDerivationMethod() const
{
    if(fComplexTypeInfo->getDerivedBy() == SchemaSymbols::XSD_EXTENSION)
        return XSConstants::DERIVATION_EXTENSION;
    return XSConstants::DERIVATION_RESTRICTION;
}

bool XSComplexTypeDefinition::getAbstract() const
{
    return fComplexTypeInfo->getAbstract();
}

XSComplexTypeDefinition::CONTENT_TYPE XSComplexTypeDefinition::getContentType() const
{
    switch(fComplexTypeInfo->getContentType()) {
        case SchemaElementDecl::Simple:
            return CONTENTTYPE_SIMPLE;
        case SchemaElementDecl::Empty:
            return CONTENTTYPE_EMPTY;
        case SchemaElementDecl::Children:
            return CONTENTTYPE_ELEMENT;
        default:
            //case SchemaElementDecl::Mixed_Complex:
            //case SchemaElementDecl::Mixed_Simple:
            //case SchemaElementDecl::Any:
            return CONTENTTYPE_MIXED;
    }
}

bool XSComplexTypeDefinition::isProhibitedSubstitution(XSConstants::DERIVATION_TYPE toTest)
{
    if (fProhibitedSubstitution & toTest)
        return true;

    return false;
}

XSAnnotationList *XSComplexTypeDefinition::getAnnotations()
{
    return fXSAnnotationList;
}

// ---------------------------------------------------------------------------
//  XSComplexTypeDefinition: virtual methods
// ---------------------------------------------------------------------------
const XMLCh *XSComplexTypeDefinition::getName()
{
    return fComplexTypeInfo->getTypeLocalName();
}

const XMLCh *XSComplexTypeDefinition::getNamespace()
{
    return fComplexTypeInfo->getTypeUri();
}

XSNamespaceItem *XSComplexTypeDefinition::getNamespaceItem()
{
    return fXSModel->getNamespaceItem(getNamespace());
}

bool XSComplexTypeDefinition::getAnonymous() const
{
    return fComplexTypeInfo->getAnonymous();
}

XSTypeDefinition *XSComplexTypeDefinition::getBaseType()
{
    return fBaseType;
}

bool XSComplexTypeDefinition::derivedFromType(const XSTypeDefinition * const ancestorType)
{
    if (!ancestorType)
        return false;

    XSTypeDefinition* type = this;
    XSTypeDefinition* lastType = 0;  // anytype has a basetype of anytype so will have infinite loop...

    while (type && (type != ancestorType) && (type != lastType))
    {
        lastType = type;
        type = type->getBaseType();
    }

    return (type == ancestorType);
}

XERCES_CPP_NAMESPACE_END
<|endoftext|>


<commit_before>// g++ main.cpp -o main -lzmq ./libcryptopp.a -std=c++11

#include <zmq.hpp>
#include <string>
#include <iostream>
#include <unistd.h>
#include <vector>
#include <sstream>
#include <bitset>
#include "cryptopp/osrng.h"
#include "cryptopp/integer.h"
#include "cryptopp/nbtheory.h"
#include "cryptopp/dh.h"
#include "cryptopp/secblock.h"
#include "cryptopp/rsa.h"
#include "cryptopp/queue.h"
#include "cryptopp/pem.h"
#include "cryptopp/files.h"

// For our JSON support
#include "json.hpp"

using json = nlohmann::json;
using CryptoPP::AutoSeededRandomPool;
using CryptoPP::Integer;
using CryptoPP::ModularExponentiation;
using CryptoPP::DH;
using CryptoPP::SecByteBlock;
using CryptoPP::RSA;

using std::cout;
using std::stringstream;
using std::string;

struct RSAPair
{
  string str_prv;
  string str_pub;

public:
  RSAPair(int key_size)
  {
    CryptoPP::InvertibleRSAFunction rsa;
    AutoSeededRandomPool rnd;

    rsa.GenerateRandomWithKeySize(rnd, key_size);
    RSA::PrivateKey priv(rsa);
    RSA::PublicKey pub(rsa);

    CryptoPP::StringSink fs(str_prv);
    CryptoPP::PEM_Save(fs, priv);

    CryptoPP::StringSink fs2(str_pub);
    CryptoPP::PEM_Save(fs2, pub);

    // Remove trailing newline character
    if (str_pub[str_pub.length() - 1] == '\n') {
      str_pub.erase(str_pub.length() - 1);
    }
    if (str_prv[str_prv.length() - 1] == '\n') {
      str_prv.erase(str_prv.length() - 1);
    }
  }

  std::vector<string> encrypt(std::vector<string> msgs)
  {
    AutoSeededRandomPool rnd;
    CryptoPP::InvertibleRSAFunction rsa;

    RSA::PrivateKey priv (rsa);
    RSA::PublicKey pub(rsa);

    CryptoPP::StringSink fs(str_prv);
    CryptoPP::PEM_Load(fs, priv);

    CryptoPP::StringSink fs2(str_pub);
    CryptoPP::PEM_Load(fs2, pub);

    CryptoPP::RSAES_OAEP_SHA_Encryptor encryptor(pub);
    std::vector<string> cipher_list;

    for (int i = 0; i < msgs.size(); i ++) {
      string cipher;
      CryptoPP::StringSource ss1(msgs[i], true,
        new CryptoPP::PK_EncryptorFilter(rnd, encryptor,
          new CryptoPP::StringSink(cipher)
        )
      );
      cipher_list.push_back(cipher);
    }

    return cipher_list;
  }
};

// g^{priv} == pub mod G
void create_key_pair(AutoSeededRandomPool &rnd, DH &dh, Integer &priv, Integer &pub)
{
  SecByteBlock block_priv(dh.PrivateKeyLength());
  SecByteBlock block_pub(dh.PublicKeyLength());

  dh.GenerateKeyPair(rnd, block_priv, block_pub);
  priv.Decode(block_priv, dh.PrivateKeyLength());
  pub.Decode(block_pub, dh.PublicKeyLength());

  return;
}

// convert Integer object to string (in hex format!)
string integer_to_string(Integer num)
{
  stringstream ss;
  ss << std::hex << num;

  string s = ss.str();

  // std::hex prints the number in HEX but it appends 'h'
  // at the end of the string
  if (s[s.length() - 1] == 'h')
  {
    s.erase(s.begin() + s.length() - 1);
  }

  return s;
}

class DataTxn
{
  std::vector<string> str_g_r_i;
  std::vector<string> str_r_i;
  string str_G;
  string str_g;
  string str_a;
  string str_g_a;
  string str_r;
  string str_g_r;
  string str_secret;
  int K;

public:
  // Create a data txn with given info.
  DataTxn(int bit_size, int K, string hashed_identity)
   : K(K)
  {
    AutoSeededRandomPool rnd;
    DH dh;

    // Generates safe prime G and its generator g.
    // "Safe prime" for DH structure is the prime p that is in form
    // 2q + 1 where q is an another prime.
    dh.AccessGroupParameters().GenerateRandomWithKeySize(rnd, bit_size);

    // Get G and g
    const Integer &G = dh.GetGroupParameters().GetModulus();
    const Integer &g = dh.GetGroupParameters().GetGenerator();

    // Key pairs for DH communication with Request TXN
    Integer g_a, a;
    create_key_pair(rnd, dh, a, g_a);

    // For encrypting secret key
    Integer r, g_r;
    create_key_pair(rnd, dh, r, g_r);

    // Create secret secret = g^r + hashed_identity
    Integer secret = g_r + Integer(hashed_identity.c_str());

    // Create 'tryouts' for ZKP
    for (int i = 0; i < K; i++)
    {
      Integer zkp_r, zkp_g_r;
      create_key_pair(rnd, dh, zkp_r, zkp_g_r);

      str_r_i.push_back(integer_to_string(zkp_r));
      str_g_r_i.push_back(integer_to_string(zkp_g_r));
    }

    str_G = integer_to_string(G);
    str_g = integer_to_string(g);
    str_r = integer_to_string(r);
    str_g_r = integer_to_string(g_r);
    str_a = integer_to_string(a);
    str_g_a = integer_to_string(g_a);
    str_secret = integer_to_string(secret);
  }

  string serialize_data(string token)
  {
    cout << "Finding RSA pairs ... " << std::endl;
    RSAPair pair(2048);

    json j = {
        {"G", str_G},
        {"g", str_g},
        {"r", str_r},
        {"g_r", str_g_r},
        {"a", str_a},
        {"g_a", str_g_a},
        {"secret", str_secret},
        {"g_r_i", str_g_r_i},
        {"r_i", str_r_i},
        {"pub_key", pair.str_pub},
        {"prv_key", pair.str_prv},
        {"K", K},
        {"token", token}};

    cout << j << std::endl;
    // Return the serialized JSON object
    return j.dump();
  }

  // If it is supplied with RSA private key,
  string serialize_data(string token, string prv_key)
  {

  }
};

class RequestTxn
{
  Integer integer_with_hex(string hex)
  {
    // Insert '0x' at front
    hex.insert(0, "0x");

    return Integer(hex.c_str());
  }

  string str_b;
  string str_g_b;
  string str_g_g_ab_p_r;
  string req_str;

public:
  RequestTxn(string data_txn_json_str, string hashed_request_identity)
  {
    auto data_txn_json = json::parse(data_txn_json_str);

    Integer G = integer_with_hex(data_txn_json["txn_payload"]["G"]);
    Integer g = integer_with_hex(data_txn_json["txn_payload"]["g"]);
    Integer g_a = integer_with_hex(data_txn_json["txn_payload"]["g_a"]);
    Integer secret = integer_with_hex(data_txn_json["txn_payload"]["secret"]);
    int K = data_txn_json["txn_payload"]["K"];

    // Initialize DH structure with G and g of data_txn
    DH dh_req;
    dh_req.AccessGroupParameters().Initialize(G, g);

    // Generate b and g^b for request txn
    AutoSeededRandomPool rng;
    Integer b, g_b;
    create_key_pair(rng, dh_req, b, g_b);

    // Calculate the shared secret g^ab
    SecByteBlock shared (dh_req.AgreedValueLength());
    SecByteBlock sec_b (dh_req.PrivateKeyLength()), sec_g_a(dh_req.PublicKeyLength());

    b.Encode(sec_b, dh_req.PrivateKeyLength());
    g_a.Encode(sec_g_a, dh_req.PublicKeyLength());

    dh_req.Agree(shared, sec_b, sec_g_a);

    Integer g_ab;
    g_ab.Decode(shared, dh_req.AgreedValueLength());

    Integer identity_hash = integer_with_hex(hashed_request_identity);
    Integer g_g_ab_p_r = ModularExponentiation(g, g_ab, G) * (secret - identity_hash);

    string req_str = "";

    for (int i = 0; i < K; i ++) {
      Integer req (rng, 1);
      if (req == 1) {
        req_str.push_back('1');
      }
      else {
        req_str.push_back('0');
      }
    }

    str_b = integer_to_string(b);
    str_g_b = integer_to_string(g_b);
    str_g_g_ab_p_r = integer_to_string(g_g_ab_p_r);
  }

  string serialize_data(string token)
  {
    json j = {
      {"g_b", str_g_b},
      {"g_g_ab_p_r", str_g_g_ab_p_r},
      {"req", req_str},
      {"b", str_b},
      {"token", token}
    };

    cout << j << std::endl;
    return j.dump();
  }
};

class AnswerTxn
{

  Integer integer_with_hex(string hex)
  {
    // Insert '0x' at front
    hex.insert(0, "0x");

    return Integer(hex.c_str());
  }

  std::vector<string> response;

  public:

  AnswerTxn(string data_txn_str, string request_txn_str, string secret) {
    auto data_txn_json = json::parse(data_txn_str);
    auto request_txn_json = json::parse(request_txn_str);
    auto secret_json = json::parse(secret);

    Integer a = integer_with_hex(secret_json["a"]);
    Integer G = integer_with_hex(data_txn_json["txn_payload"]["G"]);
    Integer g = integer_with_hex(data_txn_json["txn_payload"]["g"]);

    Integer g_b = integer_with_hex(request_txn_json["txn_payload"]["g_b"]);
    Integer g_ab = ModularExponentiation(g_b, a, G);

    string request = request_txn_json["txn_payload"]["req"];
    std::vector<string> r_i_list = secret_json["r_i"];
    Integer r = integer_with_hex(secret_json["r"]);

    for (int i = 0; i < request.length(); i ++) {
      if (request[i] == '0') {
        response.push_back(r_i_list[i]);
      }
      else if (request[i] == '1') {
        Integer r_i_num = integer_with_hex(r_i_list[i]);
        Integer resp = r_i_num + r + g_ab;
        response.push_back(integer_to_string(resp));
      }
    }
  }

  string serialize_data(string token) {
    json j = {
      {"response", response},
      {"token", token}
    };

    cout << j << std::endl;
    return j.dump();
  }
};

int main()
{
  //  Prepare our context and socket
  zmq::context_t context(1);
  zmq::socket_t socket(context, ZMQ_REP);
  socket.bind("tcp://*:5555");

  cout << "---------- TXN Calculator is started ---------------" << std::endl;

  while (true)
  {
    zmq::message_t request;

    //  Wait for next request from client
    socket.recv(&request);

    std::cout << "Request :: " << (char *)request.data() << std::endl;
    auto json_data = json::parse(string((char *)request.data()));
    string serial = "";

    // Request for generating DATA TXN
    if (json_data["type"] == 0) {
      //  Do some 'work'
      DataTxn txn(1024, 10, json_data["identity"]);

      cout << "Generating Key pairs..." << std::endl;
      serial = txn.serialize_data(json_data["token"]);
    }
    // Request for generating REQUEST TXN
    else if (json_data["type"] == 1) {
      RequestTxn txn(json_data["data_txn"], json_data["identity"]);
      serial = txn.serialize_data(json_data["token"]);
    }
    else if (json_data["type"] == 2) {
      AnswerTxn txn(json_data["data_txn"], json_data["req_txn"], json_data["secret"]);
      serial = txn.serialize_data(json_data["token"]);
    }

    //  Send reply back to client
    zmq::message_t reply(serial.length() + 1);
    memcpy((void *)reply.data(), serial.c_str(), serial.length() + 1);
    socket.send(reply);
    cout << "Data is sent!" << std::endl;
  }
  return 0;
}
<commit_msg>Created a way to user to create an additional data_txn<commit_after>// g++ main.cpp -o main -lzmq ./libcryptopp.a -std=c++11

#include <zmq.hpp>
#include <string>
#include <iostream>
#include <unistd.h>
#include <vector>
#include <sstream>
#include <bitset>
#include "cryptopp/osrng.h"
#include "cryptopp/integer.h"
#include "cryptopp/nbtheory.h"
#include "cryptopp/dh.h"
#include "cryptopp/secblock.h"
#include "cryptopp/rsa.h"
#include "cryptopp/queue.h"
#include "cryptopp/pem.h"
#include "cryptopp/files.h"

// For our JSON support
#include "json.hpp"

using json = nlohmann::json;
using CryptoPP::AutoSeededRandomPool;
using CryptoPP::Integer;
using CryptoPP::ModularExponentiation;
using CryptoPP::DH;
using CryptoPP::SecByteBlock;
using CryptoPP::RSA;

using std::cout;
using std::stringstream;
using std::string;

struct RSAPair
{
    string str_prv;
    string str_pub;

    public:
    RSAPair(int key_size)
    {
        CryptoPP::InvertibleRSAFunction rsa;
        AutoSeededRandomPool rnd;

        rsa.GenerateRandomWithKeySize(rnd, key_size);
        RSA::PrivateKey priv(rsa);
        RSA::PublicKey pub(rsa);

        CryptoPP::StringSink fs(str_prv);
        CryptoPP::PEM_Save(fs, priv);

        CryptoPP::StringSink fs2(str_pub);
        CryptoPP::PEM_Save(fs2, pub);

        // Remove trailing newline character
        if (str_pub[str_pub.length() - 1] == '\n') {
            str_pub.erase(str_pub.length() - 1);
        }
        if (str_prv[str_prv.length() - 1] == '\n') {
            str_prv.erase(str_prv.length() - 1);
        }
    }

    std::vector<string> encrypt(std::vector<string> msgs)
    {
        AutoSeededRandomPool rnd;
        CryptoPP::InvertibleRSAFunction rsa;

        RSA::PrivateKey priv (rsa);
        RSA::PublicKey pub(rsa);

        CryptoPP::StringSink fs(str_prv);
        CryptoPP::PEM_Load(fs, priv);

        CryptoPP::StringSink fs2(str_pub);
        CryptoPP::PEM_Load(fs2, pub);

        CryptoPP::RSAES_OAEP_SHA_Encryptor encryptor(pub);
        std::vector<string> cipher_list;

        for (int i = 0; i < msgs.size(); i ++) {
            string cipher;
            CryptoPP::StringSource ss1(msgs[i], true,
                    new CryptoPP::PK_EncryptorFilter(rnd, encryptor,
                        new CryptoPP::StringSink(cipher)
                        )
                    );
            cipher_list.push_back(cipher);
        }

        return cipher_list;
    }
};

// g^{priv} == pub mod G
void create_key_pair(AutoSeededRandomPool &rnd, DH &dh, Integer &priv, Integer &pub)
{
    SecByteBlock block_priv(dh.PrivateKeyLength());
    SecByteBlock block_pub(dh.PublicKeyLength());

    dh.GenerateKeyPair(rnd, block_priv, block_pub);
    priv.Decode(block_priv, dh.PrivateKeyLength());
    pub.Decode(block_pub, dh.PublicKeyLength());

    return;
}

// convert Integer object to string (in hex format!)
string integer_to_string(Integer num)
{
    stringstream ss;
    ss << std::hex << num;

    string s = ss.str();

    // std::hex prints the number in HEX but it appends 'h'
    // at the end of the string
    if (s[s.length() - 1] == 'h')
    {
        s.erase(s.begin() + s.length() - 1);
    }

    return s;
}

class DataTxn
{
    std::vector<string> str_g_r_i;
    std::vector<string> str_r_i;
    string str_G;
    string str_g;
    string str_a;
    string str_g_a;
    string str_r;
    string str_g_r;
    string str_secret;
    int K;

    public:
    // Create a data txn with given info.
    DataTxn(int bit_size, int K, string hashed_identity)
        : K(K)
    {
        AutoSeededRandomPool rnd;
        DH dh;

        // Generates safe prime G and its generator g.
        // "Safe prime" for DH structure is the prime p that is in form
        // 2q + 1 where q is an another prime.
        dh.AccessGroupParameters().GenerateRandomWithKeySize(rnd, bit_size);

        // Get G and g
        const Integer &G = dh.GetGroupParameters().GetModulus();
        const Integer &g = dh.GetGroupParameters().GetGenerator();

        // Key pairs for DH communication with Request TXN
        Integer g_a, a;
        create_key_pair(rnd, dh, a, g_a);

        // For encrypting secret key
        Integer r, g_r;
        create_key_pair(rnd, dh, r, g_r);

        // Create secret secret = g^r + hashed_identity
        Integer secret = g_r + Integer(hashed_identity.c_str());

        // Create 'tryouts' for ZKP
        for (int i = 0; i < K; i++)
        {
            Integer zkp_r, zkp_g_r;
            create_key_pair(rnd, dh, zkp_r, zkp_g_r);

            str_r_i.push_back(integer_to_string(zkp_r));
            str_g_r_i.push_back(integer_to_string(zkp_g_r));
        }

        str_G = integer_to_string(G);
        str_g = integer_to_string(g);
        str_r = integer_to_string(r);
        str_g_r = integer_to_string(g_r);
        str_a = integer_to_string(a);
        str_g_a = integer_to_string(g_a);
        str_secret = integer_to_string(secret);
    }

    string serialize_data(string token)
    {
        cout << "Finding RSA pairs ... " << std::endl;
        RSAPair pair(2048);

        json j = {
            {"G", str_G},
            {"g", str_g},
            {"r", str_r},
            {"g_r", str_g_r},
            {"a", str_a},
            {"g_a", str_g_a},
            {"secret", str_secret},
            {"g_r_i", str_g_r_i},
            {"r_i", str_r_i},
            {"pub_key", pair.str_pub},
            {"prv_key", pair.str_prv},
            {"K", K},
            {"token", token}};

        cout << j << std::endl;
        // Return the serialized JSON object
        return j.dump();
    }

    // If it is supplied with RSA private key,
    string serialize_data_without_rsa_key(string token)
    {
        json j = {
            {"G", str_G},
            {"g", str_g},
            {"r", str_r},
            {"g_r", str_g_r},
            {"a", str_a},
            {"g_a", str_g_a},
            {"secret", str_secret},
            {"g_r_i", str_g_r_i},
            {"r_i", str_r_i},
            {"K", K},
            {"token", token}};

        cout << j << std::endl;
        // Return the serialized JSON object
        return j.dump();
    }
};

class RequestTxn
{
    Integer integer_with_hex(string hex)
    {
        // Insert '0x' at front
        hex.insert(0, "0x");

        return Integer(hex.c_str());
    }

    string str_b;
    string str_g_b;
    string str_g_g_ab_p_r;
    string req_str;

    public:
    RequestTxn(string data_txn_json_str, string hashed_request_identity)
    {
        auto data_txn_json = json::parse(data_txn_json_str);

        Integer G = integer_with_hex(data_txn_json["txn_payload"]["G"]);
        Integer g = integer_with_hex(data_txn_json["txn_payload"]["g"]);
        Integer g_a = integer_with_hex(data_txn_json["txn_payload"]["g_a"]);
        Integer secret = integer_with_hex(data_txn_json["txn_payload"]["secret"]);
        int K = data_txn_json["txn_payload"]["K"];

        // Initialize DH structure with G and g of data_txn
        DH dh_req;
        dh_req.AccessGroupParameters().Initialize(G, g);

        // Generate b and g^b for request txn
        AutoSeededRandomPool rng;
        Integer b, g_b;
        create_key_pair(rng, dh_req, b, g_b);

        // Calculate the shared secret g^ab
        SecByteBlock shared (dh_req.AgreedValueLength());
        SecByteBlock sec_b (dh_req.PrivateKeyLength()), sec_g_a(dh_req.PublicKeyLength());

        b.Encode(sec_b, dh_req.PrivateKeyLength());
        g_a.Encode(sec_g_a, dh_req.PublicKeyLength());

        dh_req.Agree(shared, sec_b, sec_g_a);

        Integer g_ab;
        g_ab.Decode(shared, dh_req.AgreedValueLength());

        Integer identity_hash = integer_with_hex(hashed_request_identity);
        Integer g_g_ab_p_r = ModularExponentiation(g, g_ab, G) * (secret - identity_hash);

        string req_str = "";

        for (int i = 0; i < K; i ++) {
            Integer req (rng, 1);
            if (req == 1) {
                req_str.push_back('1');
            }
            else {
                req_str.push_back('0');
            }
        }

        str_b = integer_to_string(b);
        str_g_b = integer_to_string(g_b);
        str_g_g_ab_p_r = integer_to_string(g_g_ab_p_r);
    }

    string serialize_data(string token)
    {
        json j = {
            {"g_b", str_g_b},
            {"g_g_ab_p_r", str_g_g_ab_p_r},
            {"req", req_str},
            {"b", str_b},
            {"token", token}
        };

        cout << j << std::endl;
        return j.dump();
    }
};

class AnswerTxn
{

    Integer integer_with_hex(string hex)
    {
        // Insert '0x' at front
        hex.insert(0, "0x");

        return Integer(hex.c_str());
    }

    std::vector<string> response;

    public:

    AnswerTxn(string data_txn_str, string request_txn_str, string secret) {
        auto data_txn_json = json::parse(data_txn_str);
        auto request_txn_json = json::parse(request_txn_str);
        auto secret_json = json::parse(secret);

        Integer a = integer_with_hex(secret_json["a"]);
        Integer G = integer_with_hex(data_txn_json["txn_payload"]["G"]);
        Integer g = integer_with_hex(data_txn_json["txn_payload"]["g"]);

        Integer g_b = integer_with_hex(request_txn_json["txn_payload"]["g_b"]);
        Integer g_ab = ModularExponentiation(g_b, a, G);

        string request = request_txn_json["txn_payload"]["req"];
        std::vector<string> r_i_list = secret_json["r_i"];
        Integer r = integer_with_hex(secret_json["r"]);

        for (int i = 0; i < request.size(); i ++) {
            if (request[i] == '0') {
                response.push_back(r_i_list[i]);
            }
            else if (request[i] == '1') {
                Integer r_i_num = integer_with_hex(r_i_list[i]);
                Integer resp = r_i_num + r + g_ab;
                response.push_back(integer_to_string(resp));
            }
        }
    }

    string serialize_data(string token) {
        json j = {
            {"response", response},
            {"token", token}
        };

        cout << j << std::endl;
        return j.dump();
    }
};

int main()
{
    //  Prepare our context and socket
    zmq::context_t context(1);
    zmq::socket_t socket(context, ZMQ_REP);
    socket.bind("tcp://*:5555");

    cout << "---------- TXN Calculator is started ---------------" << std::endl;

    while (true)
    {
        zmq::message_t request;

        //  Wait for next request from client
        socket.recv(&request);

        std::cout << "Request :: " << (char *)request.data() << std::endl;
        auto json_data = json::parse(string((char *)request.data()));
        string serial = "";

        // Request for generating DATA TXN
        if (json_data["type"] == 0) {
            //  Do some 'work'
            DataTxn txn(1024, 10, json_data["identity"]);
            cout << "Generating Key pairs..." << std::endl;

            // If 'with_key' flag is enabled, then you must supply the
            // newly generated rsa key.
            if (json_data["with_key"] == 1) {
                serial = txn.serialize_data(json_data["token"]);
            }
            else {
                serial = txn.serialize_data_without_rsa_key(json_data["token"]);
            }
        }
        // Request for generating REQUEST TXN
        else if (json_data["type"] == 1) {
            RequestTxn txn(json_data["data_txn"], json_data["identity"]);
            serial = txn.serialize_data(json_data["token"]);
        }
        else if (json_data["type"] == 2) {
            AnswerTxn txn(json_data["data_txn"], json_data["req_txn"], json_data["secret"]);
            serial = txn.serialize_data(json_data["token"]);
        }

        //  Send reply back to client
        zmq::message_t reply(serial.length() + 1);
        memcpy((void *)reply.data(), serial.c_str(), serial.length() + 1);
        socket.send(reply);
        cout << "Data is sent!" << std::endl;
    }
    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "Widget.h"

#include "IntRect.h"
#include "ScrollView.h"

#include <wtf/Assertions.h>

namespace WebCore {

void Widget::init()
{
    m_parent = 0;
    m_widget = 0;
    m_selfVisible = false;
    m_parentVisible = false;
    m_containingWindow = 0;
}

void Widget::setParent(ScrollView* view)
{
    ASSERT(!view || !m_parent);
    if (!view || !view->isVisible())
        setParentVisible(false);
    m_parent = view;
    if (view && view->isVisible())
        setParentVisible(true);
}

ScrollView* Widget::root() const
{
    const Widget* top = this;
    while (top->parent())
        top = top->parent();
    if (top->isFrameView())
        return const_cast<ScrollView*>(static_cast<const ScrollView*>(top));
    return 0;
}

#if !PLATFORM(MAC)

IntRect Widget::convertToContainingWindow(const IntRect& rect) const
{
    IntRect convertedRect = rect;
    convertedRect.setLocation(convertToContainingWindow(convertedRect.location()));
    return convertedRect;
}

IntPoint Widget::convertToContainingWindow(const IntPoint& point) const
{
    IntPoint windowPoint = point;
    for (const ScrollView *parentScrollView = parent(), *childWidget = this;
         parentScrollView;
         childWidget = parentScrollView, parentScrollView = parentScrollView->parent())
        windowPoint = parentScrollView->convertChildToSelf(childWidget, windowPoint);
    return windowPoint;
}

IntPoint Widget::convertFromContainingWindow(const IntPoint& point) const
{
    IntPoint widgetPoint = point;
    for (const ScrollView *parentScrollView = parent(), *childWidget = this;
         parentScrollView;
         childWidget = parentScrollView, parentScrollView = parentScrollView->parent())
        widgetPoint = parentScrollView->convertSelfToChild(childWidget, widgetPoint);
    return widgetPoint;
}

void Widget::releasePlatformWidget()
{
}

void Widget::retainPlatformWidget()
{
}
#endif

}
<commit_msg>Fix Qt/Win/Gtk bustage.<commit_after>/*
 * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "Widget.h"

#include "IntRect.h"
#include "ScrollView.h"

#include <wtf/Assertions.h>

namespace WebCore {

void Widget::init()
{
    m_parent = 0;
    m_widget = 0;
    m_selfVisible = false;
    m_parentVisible = false;
    m_containingWindow = 0;
}

void Widget::setParent(ScrollView* view)
{
    ASSERT(!view || !m_parent);
    if (!view || !view->isVisible())
        setParentVisible(false);
    m_parent = view;
    if (view && view->isVisible())
        setParentVisible(true);
}

ScrollView* Widget::root() const
{
    const Widget* top = this;
    while (top->parent())
        top = top->parent();
    if (top->isFrameView())
        return const_cast<ScrollView*>(static_cast<const ScrollView*>(top));
    return 0;
}

#if !PLATFORM(MAC)

IntRect Widget::convertToContainingWindow(const IntRect& rect) const
{
    IntRect convertedRect = rect;
    convertedRect.setLocation(convertToContainingWindow(convertedRect.location()));
    return convertedRect;
}

IntPoint Widget::convertToContainingWindow(const IntPoint& point) const
{
    IntPoint windowPoint = point;
    const Widget* childWidget = this;
    for (const ScrollView* parentScrollView = parent();
         parentScrollView;
         childWidget = parentScrollView, parentScrollView = parentScrollView->parent())
        windowPoint = parentScrollView->convertChildToSelf(childWidget, windowPoint);
    return windowPoint;
}

IntPoint Widget::convertFromContainingWindow(const IntPoint& point) const
{
    IntPoint widgetPoint = point;
    const Widget* childWidget = this;
    for (const ScrollView* parentScrollView = parent();
         parentScrollView;
         childWidget = parentScrollView, parentScrollView = parentScrollView->parent())
        widgetPoint = parentScrollView->convertSelfToChild(childWidget, widgetPoint);
    return widgetPoint;
}

void Widget::releasePlatformWidget()
{
}

void Widget::retainPlatformWidget()
{
}
#endif

}
<|endoftext|>


<commit_before><commit_msg>gfe-relnote: (n/a) Always handle MSG_TOO_BIG when sending buffered packets. Protected by existing --gfe2_reloadable_flag_quic_treat_queued_packets_as_sent.<commit_after><|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "NotificationWidget.h"
#include "NaaliUI.h"
#include "Framework.h"
#include "Renderer.h"

namespace RexLogic
{
    NotificationWidget::NotificationWidget(RexLogicModule *rex_logic, QWidget *parent) :
        rex_logic_(rex_logic),
        framework_(rex_logic->GetFramework()),
        QGraphicsView(parent)
    {
        scene_ = framework_->Ui()->GraphicsScene();
        setScene(scene_);

        time_line_ = new QTimeLine(3000, this);

        frame_pic_ = new QFrame;
        scene_->addWidget(frame_pic_);
        frame_pic_->setFixedSize(100, 100);
        frame_pic_->hide();

        start_ = "QFrame {background-color: transparent;"
                         "border-image: url(./data/ui/images/notificationwidget/";
        end_ = ")}";
    }

    void NotificationWidget::SetupScene()
    {
        float width = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock()->GetWindowWidth();
        float height = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock()->GetWindowHeight();
        frame_pic_->move(width - frame_pic_->width() - 10, 40);

        QString style_sheet_ = start_ + picture_name_ + end_;

        frame_pic_->show();
        frame_pic_->setStyleSheet(style_sheet_);
        frame_pic_->setWindowOpacity(1.0);

        time_line_->setFrameRange(0, 100);
        connect(time_line_, SIGNAL(frameChanged(int)), this, SLOT(updateStep(int)));
        time_line_->start();

    }

    void NotificationWidget::updateStep(int i)
    {
      frame_pic_->setWindowOpacity((100-i)/100.0);
    }

    void NotificationWidget::FocusOnObject()
    {
        picture_name_ = "camera_focus.png" ;
        SetupScene();
    }

    bool NotificationWidget::HandleInputEvent(event_id_t event_id, IEventData* data)
    {
        if (event_id == InputEvents::CAMERA_TRIPOD)
        {
            picture_name_ = "tripod_camera.png" ;
            SetupScene();
        }
        else if (event_id == InputEvents::INPUTSTATE_FREECAMERA)
        {
            picture_name_ = "free_camera.png" ;
            SetupScene();
        }
        else if (event_id == InputEvents::INPUTSTATE_THIRDPERSON)
        {
            picture_name_ = "third_person.png";
            SetupScene();
        }
        else if (event_id == InputEvents::INPUTSTATE_FOCUSONOBJECT)
        {
            picture_name_ = "camera_focus_grey.png";
            SetupScene();
        }
        return false;
    }
}

<commit_msg>Fixing casesensitive error - #include NaaliUi.h<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "NotificationWidget.h"
#include "NaaliUi.h"
#include "Framework.h"
#include "Renderer.h"

namespace RexLogic
{
    NotificationWidget::NotificationWidget(RexLogicModule *rex_logic, QWidget *parent) :
        rex_logic_(rex_logic),
        framework_(rex_logic->GetFramework()),
        QGraphicsView(parent)
    {
        scene_ = framework_->Ui()->GraphicsScene();
        setScene(scene_);

        time_line_ = new QTimeLine(3000, this);

        frame_pic_ = new QFrame;
        scene_->addWidget(frame_pic_);
        frame_pic_->setFixedSize(100, 100);
        frame_pic_->hide();

        start_ = "QFrame {background-color: transparent;"
                         "border-image: url(./data/ui/images/notificationwidget/";
        end_ = ")}";
    }

    void NotificationWidget::SetupScene()
    {
        float width = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock()->GetWindowWidth();
        float height = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>(Foundation::Service::ST_Renderer).lock()->GetWindowHeight();
        frame_pic_->move(width - frame_pic_->width() - 10, 40);

        QString style_sheet_ = start_ + picture_name_ + end_;

        frame_pic_->show();
        frame_pic_->setStyleSheet(style_sheet_);
        frame_pic_->setWindowOpacity(1.0);

        time_line_->setFrameRange(0, 100);
        connect(time_line_, SIGNAL(frameChanged(int)), this, SLOT(updateStep(int)));
        time_line_->start();

    }

    void NotificationWidget::updateStep(int i)
    {
      frame_pic_->setWindowOpacity((100-i)/100.0);
    }

    void NotificationWidget::FocusOnObject()
    {
        picture_name_ = "camera_focus.png" ;
        SetupScene();
    }

    bool NotificationWidget::HandleInputEvent(event_id_t event_id, IEventData* data)
    {
        if (event_id == InputEvents::CAMERA_TRIPOD)
        {
            picture_name_ = "tripod_camera.png" ;
            SetupScene();
        }
        else if (event_id == InputEvents::INPUTSTATE_FREECAMERA)
        {
            picture_name_ = "free_camera.png" ;
            SetupScene();
        }
        else if (event_id == InputEvents::INPUTSTATE_THIRDPERSON)
        {
            picture_name_ = "third_person.png";
            SetupScene();
        }
        else if (event_id == InputEvents::INPUTSTATE_FOCUSONOBJECT)
        {
            picture_name_ = "camera_focus_grey.png";
            SetupScene();
        }
        return false;
    }
}

<|endoftext|>