text:
#include <deal.II/grid/tria.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/dofs/dof_accessor.h>
#include <deal.II/fe/fe_q.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/fe/fe_values.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/function.h>
#include <deal.II/numerics/vector_tools.h>
#include <deal.II/numerics/matrix_tools.h>
#include <deal.II/lac/vector.h>
#include <deal.II/lac/full_matrix.h>
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/dynamic_sparsity_pattern.h>
#include <deal.II/lac/affine_constraints.h>
#include <deal.II/lac/solver_cg.h>
#include <deal.II/lac/precondition.h>
#include <deal.II/numerics/data_out.h>

#include <deal.II/lac/petsc_sparse_matrix.h>
#include <deal.II/lac/petsc_vector.h>
#include <deal.II/lac/petsc_solver.h>
#include <deal.II/lac/petsc_precondition.h>

#include <deal.II/base/utilities.h>

#include <deal.II/lac/slepc_solver.h>

#include <deal.II/base/timer.h>
#include <deal.II/base/conditional_ostream.h>
#include <deal.II/base/index_set.h>

#include <deal.II/lac/sparsity_tools.h>

#include <deal.II/distributed/tria.h>
#include <deal.II/distributed/grid_refinement.h>

#include <fstream>
#include <iostream>
#include <math.h>
#include <random>
#include <mpi.h>

using namespace dealii;
class ParallelKL
{
public:
  ParallelKL();
  void run();
private:
  void make_grid();
  void setup_system();
  void assemble_system();
  void solve();
  void create_random_field();
  void stats_for_random_field();
  void output_results() const;
  void output_results_parallel();

  MPI_Comm mpi_communicator;

  parallel::distributed::Triangulation<2> triangulation;

  FE_Q<2>          fe;
  DoFHandler<2>    dof_handler;

  IndexSet         locally_owned_dofs;
  IndexSet         locally_relevant_dofs;

  AffineConstraints<double> constraints;

  SparsityPattern      sparsity_pattern;

  PETScWrappers::MPI::SparseMatrix system_mass_matrix;
  PETScWrappers::MPI::SparseMatrix system_stiffness_matrix;

  PETScWrappers::MPI::Vector randomfield_vector;

  std::vector<double> eigenvalues;
  std::vector<PETScWrappers::MPI::Vector> eigenvectors;

  std::vector<double> normalized_gaussian;
  std::default_random_engine generator;
  std::normal_distribution<double> distribution;

  unsigned int this_mpi_process, n_mpi_processes;

  ConditionalOStream pcout;
  TimerOutput        computing_timer;
};

ParallelKL::ParallelKL()
  : mpi_communicator(MPI_COMM_WORLD)
  , triangulation(mpi_communicator,
                  typename Triangulation<2>::MeshSmoothing(
                  Triangulation<2>::smoothing_on_refinement |
                  Triangulation<2>::smoothing_on_coarsening))
  , fe(1)
  , dof_handler(triangulation)
  , this_mpi_process(Utilities::MPI::this_mpi_process(mpi_communicator))
  , n_mpi_processes(Utilities::MPI::n_mpi_processes(mpi_communicator))
  , pcout(std::cout,
        (Utilities::MPI::this_mpi_process(mpi_communicator) == 0))
  , computing_timer(mpi_communicator,
                    pcout,
                    TimerOutput::summary,
                    TimerOutput::wall_times)
{}

void ParallelKL::make_grid()
{
  GridGenerator::hyper_cube(triangulation, -1, 1);
  triangulation.refine_global(5);

  //parallel console output
  pcout << "Number of active cells: " << triangulation.n_active_cells()
        << std::endl;
}

void ParallelKL::setup_system()
{
  TimerOutput::Scope t(computing_timer, "setup");

  dof_handler.distribute_dofs(fe);
  pcout << "Number of degrees of freedom: " << dof_handler.n_dofs()
            << std::endl;

  locally_owned_dofs = dof_handler.locally_owned_dofs();
  DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs);

  DynamicSparsityPattern dsp(locally_relevant_dofs);
  DoFTools::make_sparsity_pattern(dof_handler, dsp);

  SparsityTools::distribute_sparsity_pattern(dsp,
                                             locally_owned_dofs,
                                             mpi_communicator,
                                             locally_relevant_dofs);

  system_stiffness_matrix.reinit(locally_owned_dofs,
                                 locally_owned_dofs,
                                 dsp,
                                 mpi_communicator);

  system_mass_matrix.reinit(locally_owned_dofs,
                            locally_owned_dofs,
                            dsp,
                            mpi_communicator);

  randomfield_vector.reinit(locally_owned_dofs, mpi_communicator);

  constraints.clear();
  constraints.reinit(locally_relevant_dofs);
  constraints.close();
}

void ParallelKL::assemble_system()
{
  TimerOutput::Scope t(computing_timer, "assembly");

  system_stiffness_matrix = 0.;
  system_mass_matrix = 0.;

  QGauss<2> quadrature_formula(fe.degree + 1);

  FEValues<2> fe_values(fe,
                        quadrature_formula,
                        update_values | update_gradients | update_JxW_values | update_quadrature_points);

  const unsigned int dofs_per_cell = fe.dofs_per_cell;

  FullMatrix<double> cell_mass_matrix(dofs_per_cell, dofs_per_cell);
  FullMatrix<double> cell_stiffness_matrix(dofs_per_cell, dofs_per_cell);

  std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);

  for (const auto &cell : dof_handler.active_cell_iterators())
    { if (cell->is_locally_owned())
       {
          fe_values.reinit(cell);
          cell_mass_matrix = 0.;
          cell_stiffness_matrix = 0.;

          for (const unsigned int q_index : fe_values.quadrature_point_indices())
            {
              Point<2> quad_pointq = fe_values.quadrature_point(q_index);
              for (const unsigned int i : fe_values.dof_indices())
                for (const unsigned int j : fe_values.dof_indices())
                  cell_mass_matrix(i, j) +=
                    (fe_values.shape_value(i, q_index) * // grad phi_i(x_q)
                    fe_values.shape_value(j, q_index) * // grad phi_j(x_q)
                    fe_values.JxW(q_index));           // dx

              for (const unsigned int l_index : fe_values.quadrature_point_indices())
                {
                  Point<2> quad_pointl = fe_values.quadrature_point(l_index);
                  const double point_distance = quad_pointl.distance(quad_pointq);

                  for (const unsigned int i : fe_values.dof_indices())
                    for (const unsigned int j : fe_values.dof_indices())
                        cell_stiffness_matrix(i, j) +=
                        (exp(-0.5*point_distance/(0.05*0.05))*          // R(x,x')
                        fe_values.shape_value(i, q_index) * // grad phi_i(x_q)
                        fe_values.shape_value(j, l_index) * // grad phi_j(x_l)
                        fe_values.JxW(q_index)*fe_values.JxW(l_index));           // dx
                }
            }
          cell->get_dof_indices(local_dof_indices);

          constraints.distribute_local_to_global(cell_stiffness_matrix,
                                         local_dof_indices,
                                         system_stiffness_matrix);

          constraints.distribute_local_to_global(cell_mass_matrix,
                                         local_dof_indices,
                                         system_mass_matrix);
       }
    }

system_mass_matrix.compress(VectorOperation::add);
system_stiffness_matrix.compress(VectorOperation::add);

//system_mass_matrix.print(std::cout);
//system_stiffness_matrix.print(std::cout);
}

void ParallelKL::solve()
{
  const unsigned int num_eigenpairs_requested = 100;

  eigenvalues.resize(num_eigenpairs_requested);
  eigenvectors.resize(num_eigenpairs_requested);

  normalized_gaussian.resize(num_eigenpairs_requested);

  for (unsigned int i = 0; i < num_eigenpairs_requested; ++i)
    eigenvectors[i].reinit(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);

  SolverControl eigen_solver_control (10000, 1e-10);

  SLEPcWrappers::SolverKrylovSchur eigensolver(eigen_solver_control, mpi_communicator);

  eigensolver.set_which_eigenpairs(EPS_LARGEST_REAL);

  eigensolver.set_problem_type(EPS_GHEP);

  pcout << "Beginning Eigensolve..." << std::endl;
  eigensolver.solve(system_stiffness_matrix,
                    system_mass_matrix,
                    eigenvalues,
                    eigenvectors,
                    num_eigenpairs_requested);

  for (unsigned int i = 0; i < num_eigenpairs_requested; i++)
  {
    double temporary_sample = 0.0;

    if (this_mpi_process == 0)
      temporary_sample = distribution(generator);

    double temporary_sum = 0.0;

    MPI_Allreduce (&temporary_sample, &temporary_sum, 1, MPI_DOUBLE, MPI_SUM, mpi_communicator);

    normalized_gaussian[i] = temporary_sum;

  }
}

void ParallelKL::create_random_field()
{
  randomfield_vector = 0.0;

  PETScWrappers::MPI::Vector tmp_locally_owned_vector(locally_owned_dofs, mpi_communicator);

  for (unsigned int i = 0; i < eigenvalues.size(); i++)
    {
      const double multiplier = sqrt(eigenvalues[i])*normalized_gaussian[i];
      tmp_locally_owned_vector = eigenvectors[i];
      randomfield_vector.add(multiplier, tmp_locally_owned_vector);
    }
}

void ParallelKL::stats_for_random_field()
{
  PETScWrappers::MPI::Vector relevent_randomfield_vector(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);
  relevent_randomfield_vector = randomfield_vector;

  QGauss<2> quadrature_formula(fe.degree + 1);

  FEValues<2> fe_values(fe,
                        quadrature_formula,
                        update_values | update_JxW_values);

  double vol_on_current_processor = 0.;
  double random_field_volume_integral_on_current_processor = 0.;

  std::vector<double> local_dof_values(fe.dofs_per_cell);
  std::vector<double> current_function_values(quadrature_formula.size());

  const FEValuesExtractors::Scalar r_field(0);

  for (const auto &cell : dof_handler.active_cell_iterators())
  { if (cell->is_locally_owned())
       {
          fe_values.reinit(cell);
          cell->get_dof_values(relevent_randomfield_vector, local_dof_values.begin(), local_dof_values.end());
          fe_values[r_field].get_function_values_from_local_dof_values(local_dof_values, current_function_values);

          for (const unsigned int q_index : fe_values.quadrature_point_indices())
            {
              vol_on_current_processor  += fe_values.JxW(q_index);
              random_field_volume_integral_on_current_processor += current_function_values[q_index]*fe_values.JxW(q_index);
            }
       }
  }

  double total_random_field_volume_integral = 0.0;
  double total_volume = 0.0;

  MPI_Allreduce (&random_field_volume_integral_on_current_processor, &total_random_field_volume_integral, 1, MPI_DOUBLE, MPI_SUM, mpi_communicator);
  MPI_Allreduce (&vol_on_current_processor, &total_volume, 1, MPI_DOUBLE, MPI_SUM, mpi_communicator);

  double volume_average_of_random_field = total_random_field_volume_integral/total_volume;

  pcout << "Volume Average of Random Field = " << volume_average_of_random_field << std::endl;
  pcout << "Total Volume = " << total_volume << std::endl;

}

void ParallelKL::output_results() const
{
  DataOut<2> data_out;
  data_out.attach_dof_handler(dof_handler);
  /*
  Vector<float> subdomain(triangulation.n_active_cells());
  for (unsigned int i = 0; i < subdomain.size(); ++i)
      subdomain(i) = triangulation.locally_owned_subdomain();
  data_out.add_data_vector(subdomain, "subdomain");
*/
  for (unsigned int i = 0; i < eigenvalues.size(); i++)
  {
    //std::cout << eigenvectors[i] << "\n" << std::endl;
    std::string tmpname = "solution";
    tmpname += Utilities::int_to_string(i, 3);
    //std::cout << "Eigen_val = " << eigenvalues[i] << " " << "Normalized_gaussian = " << normalized_gaussian[i] << "\n"  << std::endl;
    data_out.add_data_vector(eigenvectors[i], tmpname);
  }

  data_out.build_patches();
  std::ofstream output("solution.vtk");
  data_out.write_vtk(output);
}

void ParallelKL::output_results_parallel()
{
    TimerOutput::Scope t(computing_timer, "output parallel");

    PETScWrappers::MPI::Vector relevent_randomfield_vector(locally_owned_dofs, locally_relevant_dofs, mpi_communicator);
    relevent_randomfield_vector = randomfield_vector;

    DataOut<2> data_out;

    // ############################################################
    // #######                   OUTPUT                     #######
    // ############################################################

    data_out.add_data_vector(dof_handler, relevent_randomfield_vector,
                               "RandomField");

  /*
    for (unsigned int i = 0; i < eigenvalues.size(); i++)
      {
        std::string tmpname = "solution";
        tmpname += Utilities::int_to_string(i, 3);
        data_out.add_data_vector(eigenvectors[i], tmpname);
      }
      */

    std::vector<Vector<double>> buckling_eigenmodes_out;

    buckling_eigenmodes_out.resize(eigenvalues.size());
    for (unsigned int i = 0; i < eigenvalues.size(); ++i)
      {
        buckling_eigenmodes_out[i].reinit(dof_handler.n_dofs(), 0.0);
        buckling_eigenmodes_out[i] = eigenvectors[i];
        const std::string buckling_mode_string = std::string("EigenVector") + Utilities::int_to_string(i, 2);

        data_out.add_data_vector(dof_handler, buckling_eigenmodes_out[i],
                                 buckling_mode_string);
      }

    // ############################################################
    // #######                 WRITE VTU FILE               #######
    // ############################################################
    data_out.build_patches ();
    const std::string filename = "Solution." +
                                  Utilities::int_to_string (this_mpi_process, 2) + ".vtu";

    std::ofstream output (filename.c_str());
    data_out.write_vtu (output);
    output.close();

    // ############################################################
    // #######                 WRITE PVTU FILE              #######
    // ############################################################
    if (this_mpi_process == 0)
    {
      std::vector<std::string> filenames;
      for (unsigned int i=0; i < n_mpi_processes; ++i)
        filenames.push_back ("Solution." +
                                  Utilities::int_to_string (i, 2) + ".vtu");

      std::ofstream master_output ("Solution.pvtu");

      data_out.write_pvtu_record (master_output, filenames);
    }
}

void ParallelKL::run()
{
  pcout << "Running with " << "PETSc" << " on " << Utilities::MPI::n_mpi_processes(mpi_communicator)
          << " MPI rank(s)..." << std::endl;

  make_grid();

  setup_system();

  pcout << "   Number of active cells:       "
        << triangulation.n_global_active_cells() << std::endl
        << "   Number of degrees of freedom: " << dof_handler.n_dofs()
        << std::endl;

  assemble_system();
  solve();
  create_random_field();
  stats_for_random_field();

  if (Utilities::MPI::n_mpi_processes(mpi_communicator) <= 32)
    {
      TimerOutput::Scope t(computing_timer, "output");
      //output_results();
      output_results_parallel();

    }
}

int main(int argc, char* argv[])
{
  Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);

  deallog.depth_console(0);

  ParallelKL klexpansion_2d;
  klexpansion_2d.run();
  return 0;
}


text:
#include <faabric/util/files.h>
#include <faabric/util/logging.h>
#include <wamr/WAMRWasmModule.h>

#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
#include <stdexcept>

#include <aot_export.h>
#include <wasm_export.h>

namespace wasm {
std::vector<uint8_t> wamrCodegen(std::vector<uint8_t>& wasmBytes, bool isSgx)
{
    // Make sure WAMR is initialised
    WAMRWasmModule::initialiseWAMRGlobally();

    if (!faabric::util::isWasm(wasmBytes)) {
        throw std::runtime_error("File is not a wasm binary");
    }

    // Load the module
    char errorBuffer[128];
    wasm_module_t wasmModule = wasm_runtime_load(
      wasmBytes.data(), wasmBytes.size(), errorBuffer, sizeof(errorBuffer));

    if (wasmModule == nullptr) {
        SPDLOG_ERROR("Failed to import module: {}", errorBuffer);
        throw std::runtime_error("Failed to load module");
    }

    aot_comp_data_t compileData = aot_create_comp_data(wasmModule);
    if (compileData == nullptr) {
        SPDLOG_ERROR("Failed to generat AOT data: {}", aot_get_last_error());
        throw std::runtime_error("Failed to generate AOT data");
    }

    AOTCompOption option = { 0 };
    option.opt_level = 3;
    option.size_level = 3;
    option.output_format = AOT_FORMAT_FILE;
    option.bounds_checks = 2;

    if (isSgx) {
        option.size_level = 1;
        option.is_sgx_platform = true;
    }

    aot_comp_context_t compileContext =
      aot_create_comp_context(compileData, &option);

    if (compileContext == nullptr) {
        SPDLOG_ERROR("Failed to generat AOT context: {}", aot_get_last_error());
        throw std::runtime_error("Failed to generate AOT context");
    }

    bool compileSuccess = aot_compile_wasm(compileContext);
    if (!compileSuccess) {
        SPDLOG_ERROR("Failed to run codegen on wasm: {}", aot_get_last_error());
        throw std::runtime_error("Failed to run codegen");
    }

    // TODO - avoid using a temp file here
    // Note - WAMR doesn't let us generate an array of bytes, so we have to
    // write to a temp file, then load the bytes again
    boost::filesystem::path temp = boost::filesystem::unique_path();
    bool aotSuccess =
      aot_emit_aot_file(compileContext, compileData, temp.c_str());
    if (!aotSuccess) {
        SPDLOG_ERROR("Failed to write AOT file to {}", temp.string());
        throw std::runtime_error("Failed to emit AOT file");
    }

    // Read object bytes back in
    std::vector<uint8_t> objBytes =
      faabric::util::readFileToBytes(temp.c_str());

    // Delete the file
    boost::filesystem::remove(temp.c_str());

    return objBytes;
}
}

ext: cpp

max_stars_repo_name: faasm/faasm

max_issues_repo_name: faasm/faasm

max_forks_repo_name: faasm/faasm


text:
// Copyright Oleg Maximenko 2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://github.com/svgpp/svgpp for library home page.

#pragma once

#include <svgpp/definitions.hpp>
#include <svgpp/parser/detail/common.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

namespace svgpp
{

namespace qi = boost::spirit::qi;

template <
  class PropertySource,
  class Iterator,
  class ICCColorFactory,
  class Number = typename ICCColorFactory::component_type
>
class icc_color_grammar:
  public qi::grammar<Iterator, typename ICCColorFactory::icc_color_type(ICCColorFactory const &), qi::locals<typename ICCColorFactory::builder_type> >
{
  typedef icc_color_grammar<PropertySource, Iterator, ICCColorFactory, Number> this_type;
public:
  icc_color_grammar()
    : this_type::grammar(rule_)
  {
    namespace phx = boost::phoenix;
    using detail::character_encoding_namespace::char_;

    rule_
        = detail::no_case_if_css(PropertySource())[ qi::lit("icc-color(") ]
          >> qi::raw[ +(!char_(",() \r\n\t") >> char_) ]  // [^,()#x20#x9#xD#xA]  any char except ",", "(", ")" or wsp
                [phx::bind(&icc_color_grammar::call_set_profile_name, qi::_r1, qi::_a, qi::_1)]
          >> + (
                comma_wsp_
                >> number_ [phx::bind(&icc_color_grammar::call_append_component_value, qi::_r1, qi::_a, qi::_1)]
               )
          >> qi::lit(")")
                [qi::_val = phx::bind(&icc_color_grammar::call_create_icc_color, qi::_r1, qi::_a)];
  }

private:
  typename this_type::start_type rule_;
  detail::comma_wsp_rule_no_skip<Iterator> comma_wsp_;
  qi::real_parser<Number, detail::number_policies<Number, PropertySource> > number_;

  static void call_set_profile_name(ICCColorFactory const & color_factory,
    typename ICCColorFactory::builder_type & builder, boost::iterator_range<Iterator> const & profile_name)
  {
    color_factory.set_profile_name(builder, profile_name);
  }

  static void call_append_component_value(ICCColorFactory const & color_factory,
    typename ICCColorFactory::builder_type & builder, Number value)
  {
    color_factory.append_component_value(builder, value);
  }

  static typename ICCColorFactory::icc_color_type
    call_create_icc_color(ICCColorFactory const & color_factory, typename ICCColorFactory::builder_type & builder)
  {
    return color_factory.create_icc_color(builder);
  }
};

}

ext: hpp

max_stars_repo_name: RichardCory/svgpp


text:
/* Copyright 2003-2013 Joaquin M Lopez Munoz.
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 *
 * See http://www.boost.org/libs/multi_index for library home page.
 */

#ifndef BOOST_MULTI_INDEX_KEY_EXTRACTORS_HPP
#define BOOST_MULTI_INDEX_KEY_EXTRACTORS_HPP

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/multi_index/composite_key.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/global_fun.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/mem_fun.hpp>

#endif


text:
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\
|  Phycas: Python software for phylogenetic analysis						  |
|  Copyright (C) 2010 Mark T. Holder, Paul O. Lewis and David L. Swofford	  |
|																			  |
|  This program is free software; you can redistribute it and/or modify		  |
|  it under the terms of the GNU General Public License as published by		  |
|  the Free Software Foundation; either version 2 of the License, or		  |
|  (at your option) any later version.										  |
|																			  |
|  This program is distributed in the hope that it will be useful,			  |
|  but WITHOUT ANY WARRANTY; without even the implied warranty of			  |
|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the			  |
|  GNU General Public License for more details.								  |
|																			  |
|  You should have received a copy of the GNU General Public License along	  |
|  with this program; if not, write to the Free Software Foundation, Inc.,	  |
|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.				  |
\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

#if ! defined(CHAR_SUPER_MATRIX_HPP)
#define CHAR_SUPER_MATRIX_HPP

#include <boost/shared_ptr.hpp>
#include "ncl/nxspublicblocks.h"
#include "nxs_file_path.hpp"
#include "ncl/nxscxxdiscretematrix.h"

class PhycasNexusReader;
namespace phycas
{
class CharSuperMatrix
	{
	public:
		CharSuperMatrix(){}
		CharSuperMatrix(std::vector<NxsCXXDiscreteMatrix *> mats) : allSubmatrices(mats) {}

		unsigned GetNumMatrices() const {return allSubmatrices.size();}
		unsigned getNTax() const {return allSubmatrices[0]->getNTax();}
		unsigned getNChar() const {return allSubmatrices[0]->getNChar();}
		NxsCXXDiscreteMatrix * GetMatrix(unsigned i) const { return allSubmatrices.at(i);}

	public:

		std::vector<NxsCXXDiscreteMatrix *> allSubmatrices;
	};

}	// namespace phycas

phycas::CharSuperMatrix * GetLastDiscreteMatrix(PhycasNexusReader & nexusReader, bool convertGapsToMissing);
phycas::CharSuperMatrix * createNativeDiscreteMatrix(PhycasNexusReader & nexusReader, NxsTaxaBlock * taxaBlockPtr, unsigned int charBlockIndex, bool convertGapsToMissing);

#endif

max_stars_repo_name: plewis/phycas

max_issues_repo_name: plewis/phycas

max_forks_repo_name: plewis/phycas


text:
// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
//               2008 Dresden University of Technology and the Trustees of Indiana University.
//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library2
//
// See also license.mtl.txt in the distribution.

#ifndef ITL_CYCLIC_ITERATION_INCLUDE
#define ITL_CYCLIC_ITERATION_INCLUDE

#include <iostream>
#include <boost/numeric/itl/iteration/basic_iteration.hpp>

namespace itl {

  /// Class for iteration control that cyclically prints residual
  /** Many methods are inherited from \ref basic_iteration **/
  template <class Real, class OStream = std::ostream>
  class cyclic_iteration : public basic_iteration<Real>
  {
      typedef basic_iteration<Real> super;
      typedef cyclic_iteration self;

      void print_resid()
      {
	  if (!this->my_quite && this->i % cycle == 0)
	      if (multi_print || this->i != last_print) { // Avoid multiple print-outs in same iteration
		  out << "iteration " << this->i << ": resid " << this->resid()
#                   ifdef MTL_VERBOSE_ITERATION
		      << " / " << this->norm_r0() << " = " << this->resid() / this->norm_r0() << " (rel. error)"
#                   endif
		      << std::endl;
		  last_print= this->i;
	      }
      }

    public:

      /// Constructor
      template <class Vector>
      cyclic_iteration(const Vector& r0, int max_iter_, Real tol_, Real atol_ = Real(0), int cycle_ = 100,
		       OStream& out = std::cout)
	: super(r0, max_iter_, tol_, atol_), cycle(cycle_), last_print(-1), multi_print(false), out(out)
      {}

      /// Constructor
      cyclic_iteration(Real r0, int max_iter_, Real tol_, Real atol_ = Real(0), int cycle_ = 100,
		       OStream& out = std::cout)
	: super(r0, max_iter_, tol_, atol_), cycle(cycle_), last_print(-1), multi_print(false), out(out)
      {}

      bool finished() { return super::finished(); }
      // using super::finished;

      /// Override termination control with logging version
      template <typename T>
      bool finished(const T& r)
      {
	  bool ret= super::finished(r);
	  print_resid();
	  return ret;
      }

      inline self& operator++() { ++this->i; return *this; }  ///< Increment counter
      inline self& operator+=(int n) { this->i+= n; return *this; } ///< Increment counter by n

      operator int() const { return error_code(); } ///< Conversion to int returns \ref error_code

      /// Whether the residual is printed multiple times in iteration
      bool is_multi_print() const { return multi_print; }

      /// Set whether the residual is printed multiple times in iteration
      void set_multi_print(bool m) { multi_print= m; }

      /// Set the cycle, i.e. how often is logged
      void set_cycle(int new_cycle) { cycle= new_cycle; }

      /// Error code with final resume
      int error_code() const
      {
	  if (!this->my_suppress)
	      out << "finished! error code = " << this->error << '\n'
		  << this->iterations() << " iterations\n"
		  << this->resid() << " is actual final residual. \n"
		  << this->relresid() << " is actual relative tolerance achieved. \n"
		  << "Relative tol: " << this->rtol_ << "  Absolute tol: " << this->atol_ << '\n'
		  << "Convergence:  " << pow(this->relresid(), 1.0 / double(this->iterations())) << std::endl;
	  return this->error;
      }
    protected:
      int        cycle, last_print;
      bool       multi_print;
      OStream&   out;
  };

} // namespace itl

#endif // ITL_CYCLIC_ITERATION_INCLUDE


text:
#include "libs/ml_models/svm_types.h"
#include <boost/assign.hpp>
#include <map>

namespace mlmodels
{
namespace svm
{
type_t str2type(const std::string& from)
{
    static const std::map<std::string, type_t> mapper =
        boost::assign::map_list_of("c_svc", C_SVC)
            ("nu_svc", NU_SVC)
            ("one_class", ONE_CLASS)
            ("eps_svr", EPS_SVR)
            ("nu_svr", NU_SVR);
    auto i = mapper.find(from);
    if (i == std::end(mapper)) {
        throw std::runtime_error{"invalid configuration for SVM " + from};
    }
    return i->second;
}

kernel_type str2kernel(const std::string& from)
{
    static const std::map<std::string, kernel_type> mapper =
        boost::assign::map_list_of("custom", CUSTOM)
            ("linear", LINEAR)
            ("poly",POLY)
            ("rbf", RBF)
            ("sigmoid", SIGMOID)
            ("chi2", CHI2)
            ("inter", INTER);
    auto i = mapper.find(from);
    if (i == std::end(mapper)) {
        throw std::runtime_error{"invalid configuration for SVM " + from};
    }
    return i->second;
}
std::string to_string(kernel_type k)
{
    using namespace std::string_literals;
    switch (k) {
        case CUSTOM:
            return "custom"s;
        case LINEAR:
            return "linear"s;
        case POLY:
            return "poly"s;
        case RBF:    // default
            return "rbf"s;
        case SIGMOID:
            return "sigmoid"s;
        case CHI2:
            return "chi2"s;
        case INTER:
            return "inter"s;
    }
}

std::string to_string(type_t t)
{
    using namespace std::string_literals;
    switch (t) {
        case C_SVC:  // classifier
            return "c_svc"s;
        case NU_SVC:
            return "nu_svc"s;
        case ONE_CLASS:
            return "one_class"s;
        case EPS_SVR:
            return "eps_svr"s;
        case NU_SVR:  // regression
            return "nu_svr"s;
    }
}

}   // end of namespace svm
}   // end of namespace mlmodels


text:
// Autogenerated from KST: please remove this line if doing any edits by hand!

#include <boost/test/unit_test.hpp>
#include "imports_abs.h"
#include "vlq_base128_le.h"
#include <iostream>
#include <fstream>
#include <vector>

BOOST_AUTO_TEST_CASE(test_imports_abs) {
    std::ifstream ifs("src/fixed_struct.bin", std::ifstream::binary);
    kaitai::kstream ks(&ifs);
    imports_abs_t* r = new imports_abs_t(&ks);

    BOOST_CHECK_EQUAL(r->len()->value(), 80);
    BOOST_CHECK_EQUAL(r->body().length(), 80);

    delete r;
}


text:
#pragma once

#include <cstdint>
#include <string>
#include <vector>
#include <optional>
#include <functional>
#include <boost/fusion/include/adapt_struct.hpp>
#include <pre/json/from_json.hpp>

#include <xxhr/xxhr.hpp>

#include <gh/auth.hxx>

namespace gh::git_data {

  struct object_t {
    std::string type;
    std::string sha;
    std::string url;
  };

  struct ref_t {
    std::string ref;
    std::string url;
    object_t object;
  };

  using refs = std::vector<ref_t>;
}

BOOST_FUSION_ADAPT_STRUCT(gh::git_data::object_t, type, sha, url);
BOOST_FUSION_ADAPT_STRUCT(gh::git_data::ref_t, ref, url, object);

namespace gh {

  using namespace std::string_literals;

  //! filter references based on their types
  enum class filter_refs {
    //! tags and branches mixed
    ALL,
    //! Only tags
    TAGS,
    //! Only branches
    HEADS
  };

  /**
   * \brief gets the refs that a repo contains (tags and branch heads)
   * \param auth credentials
   * \param owner
   * \param repository
   * \param filter Whether to list all refs or only tags or branch heads
   * \param result_handler taking a gh::git_data::refs collection.
   */
  inline void get_refs(std::string owner, std::string repository,
    filter_refs filter,
    std::function<void(git_data::refs&&)>&& result_handler,
    std::optional<auth> auth = std::nullopt,
    const std::string& api_endpoint = "https://api.github.com"s ) {

    using namespace xxhr;
    auto url = api_endpoint + "/repos/"s + owner + "/" + repository + "/git/refs/";

    if (filter == filter_refs::TAGS) {
      url += "tags";
    } else if (filter == filter_refs::HEADS) {
      url += "heads";
    }

    auto response_handler = [&](auto&& resp) {
      if ( (!resp.error) && (resp.status_code == 200) ) {
        result_handler(pre::json::from_json<git_data::refs>(resp.text));
      } else {
        throw std::runtime_error( "err : "s + std::string(resp.error) + "status: "s
            + std::to_string(resp.status_code) + " accessing : "s + url );
      }
    };

    if (auth) {
      GET(url, Authentication{auth->user, auth->pass},
        on_response = response_handler
      );
    } else {
      GET(url, on_response = response_handler);
    }
  }

  /**
   * \brief get the ref (tag or branch)
   * \param auth credentials
   * \param owner
   * \param repository
   * \param ref Name of the ref, either "heads/<branch>" or "tags/<tag>"
   * \param result_handler taking a gh::git_data::refs collection.
   */
  inline void get_ref(std::string owner, std::string repository,
    const std::string& ref,
    std::function<void(git_data::ref_t&&)>&& result_handler,
    std::optional<auth> auth = std::nullopt,
    const std::string& api_endpoint = "https://api.github.com"s ) {

    using namespace xxhr;
    auto url = api_endpoint + "/repos/"s + owner + "/" + repository
      + "/git/refs/" + ref;

    auto response_handler = [&](auto&& resp) {
      if ( (!resp.error) && (resp.status_code == 200) ) {
        result_handler(pre::json::from_json<git_data::ref_t>(resp.text));
      } else {
        throw std::runtime_error( "err : "s + std::string(resp.error) + "status: "s
            + std::to_string(resp.status_code) + " accessing : "s + url );
      }
    };

    if (auth) {
      GET(url, Authentication{auth->user, auth->pass},
        on_response = response_handler);
    } else {
      GET(url, on_response = response_handler);
    }

  }

}

ext: hxx

max_stars_repo_name: nxxm/gh

max_issues_repo_name: nxxm/gh

max_forks_repo_name: nxxm/gh


text:
///////////////////////////////////////////////////////////////////
//  Copyright Eduardo Quintana 2021
//  Copyright Janek Kozicki 2021
//  Copyright Christopher Kormanyos 2021
//  Distributed under the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt
//  or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_MATH_FFT_REAL_ALGORITHMS_HPP
  #define BOOST_MATH_FFT_REAL_ALGORITHMS_HPP

  #include <algorithm>
  #include <numeric>
  #include <cmath>

  #include <boost/math/fft/simple_complex.hpp>

  namespace boost { namespace math {  namespace fft {

  namespace detail {

  template<class T>
  inline void real_dft_2(
    const T* in,
    T* out, int)
  {
    T o1 = in[0]+in[1], o2 = in[0]-in[1] ;
    out[0] = o1;
    out[1] = o2;
  }

  template<class RealType>
  RealType complex_root_of_unity_real(long n,long p=1)
  /*
    Computes cos(-2 pi p/n)
  */
  {
    p = modulo(p,n);

    if(p==0)
      return RealType(1);

    long g = gcd(p,n);
    n/=g;
    p/=g;
    switch(n)
    {
      case 1:
        return RealType(1);
      case 2:
        return p==0 ? RealType(1) : RealType(-1);
      case 4:
        return p==0 ? RealType(1) :
               p==1 ? RealType(0) :
               p==2 ? RealType(-1) :
                      RealType(0) ;
    }
    using std::cos;
    RealType phase = -2*p*boost::math::constants::pi<RealType>()/n;
    return RealType(cos(phase));
  }
  template<class RealType>
  RealType complex_root_of_unity_imag(long n,long p=1)
  /*
    Computes sin(-2 pi p/n)
  */
  {
    p = modulo(p,n);

    if(p==0)
      return RealType(0);

    long g = gcd(p,n);
    n/=g;
    p/=g;
    switch(n)
    {
      case 1:
        return RealType(0);
      case 2:
        return p==0 ? RealType(0) : RealType(0);
      case 4:
        return p==0 ? RealType(0) :
               p==1 ? RealType(-1) :
               p==2 ? RealType(0) :
                      RealType(1) ;
    }
    using std::sin;
    RealType phase = -2*p*boost::math::constants::pi<RealType>()/n;
    return RealType(sin(phase));
  }

  template <class T>
  void real_dft_power2(const T *in_first, const T *in_last, T* out, int/*sign*/)
  {
    /*
      Cooley-Tukey mapping, in-place Decimation in Time
    */
    const long ptrdiff = static_cast<long>(std::distance(in_first,in_last));
    if(ptrdiff <=0 )
      return;
    const long n = lower_bound_power2(ptrdiff);

    if(in_first!=out)
      std::copy(in_first,in_last,out);

    if (n == 1)
        return;

    // Gold-Rader bit-reversal algorithm.
    for(int i=0,j=0;i<n-1;++i)
    {
      if(i<j)
        std::swap(out[i],out[j]);
      for(int k=n>>1;!( (j^=k)&k );k>>=1);
    }

    for (int len = 2, prev_len = 1; len <= n; len <<= 1,prev_len<<=1)
    {
      for (int i = 0; i < n; i += len)
      {
        {
          // j=0;
          T* u = out + i, *v = out + i + prev_len;
          T Bu = *u, Bv = *v;
          *u = Bu + Bv;
          *v = Bu - Bv;
        }
        for(int j=1;j < prev_len/2;++j)
        {
          T cos{ complex_root_of_unity_real<T>(len,j) },
            sin{ complex_root_of_unity_imag<T>(len,j) };

          T *ux = out + i + j,
            *uy = out + i + len - j;

          T *vx = out + i + prev_len - j,
            *vy = out + i + prev_len + j;

          T prev_ux = *ux,
            prev_uy = *uy;

          T prev_vx = *vx,
            prev_vy = *vy;

          *ux = prev_ux + cos * prev_vy + sin * prev_uy;
          *uy = prev_vx + cos * prev_uy - sin * prev_vy;
          *vx = prev_ux - cos * prev_vy - sin * prev_uy;
          *vy =-prev_vx + cos * prev_uy - sin * prev_vy;
        }
        //if(prev_len>=2)
        //{
        //  const int j = prev_len/2;
        //  T* u = out + i + j, *v = out + i + j + prev_len;
        //  T Bu = *u, Bv = *v;
        //  *u = Bu;
        //  *v = Bv;
        //}
      }
    }
  }
  template <class T>
  void real_inverse_dft_power2(const T *in_first, const T *in_last, T* out, int /*sign*/)
  {
    /*
      Cooley-Tukey mapping, in-place Decimation in Time
      Reverse flow graph of the real_dft_power2
    */
    const long ptrdiff = static_cast<long>(std::distance(in_first,in_last));
    if(ptrdiff <=0 )
      return;
    const long n = lower_bound_power2(ptrdiff);

    if(in_first!=out)
      std::copy(in_first,in_last,out);

    if (n == 1)
        return;

    for (int len = n, prev_len = len/2; len >= 2; len >>= 1,prev_len>>=1)
    {
      for (int i = 0; i < n; i += len)
      {
        {
          // j=0;
          T* u = out + i, *v = out + i + prev_len;
          T Bu = *u, Bv = *v;
          *u = Bu + Bv;
          *v = Bu - Bv;
        }
        for(int j=1;j < prev_len/2;++j)
        {
          T cos{ complex_root_of_unity_real<T>(len,-j) },
            sin{ complex_root_of_unity_imag<T>(len,-j) };

          T *ux = out + i + j,
            *uy = out + i + len - j;

          T *vx = out + i + prev_len - j,
            *vy = out + i + prev_len + j;

          T prev_ux = *ux,
            prev_uy = *uy;

          T prev_vx = *vx,
            prev_vy = *vy;

          T sum_x = prev_ux + prev_vx,
            dif_x = prev_ux - prev_vx,
            sum_y = prev_uy + prev_vy,
            dif_y = prev_uy - prev_vy;

          *ux = sum_x;
          *vx = dif_y;
          *uy = cos * sum_y - sin*dif_x;
          *vy = cos * dif_x + sin*sum_y;
        }
        if(prev_len>=2)
        {
          const int j = prev_len/2;
          T* u = out + i + j, *v = out + i + j + prev_len;
          T Bu = *u, Bv = *v;
          *u = Bu + Bu;
          *v = Bv + Bv;
        }
      }
    }

    // Gold-Rader bit-reversal algorithm.
    for(int i=0,j=0;i<n-1;++i)
    {
      if(i<j)
        std::swap(out[i],out[j]);
      for(int k=n>>1;!( (j^=k)&k );k>>=1);
    }
  }

  template<class T>
  void real_dft_prime_bruteForce_outofplace(
    const T* in_first,
    const T* in_last,
    T* out, int sign)
  /*
    assumptions:
    - allocated memory in out is enough to hold distance(in_first,in_last) element,
    - out!=in
  */
  {
    const long N = static_cast<long>(std::distance(in_first,in_last));
    if(N<=0)
      return;

    out[0] = std::accumulate(in_first+1,in_last,in_first[0]);

    for(long i=1,j=N-1;i<j;++i,--j)
    {
      T sum_x{in_first[0]},sum_y = 0;
      for(long l=1;l<N; ++l)
      {
        sum_x += in_first[l] * complex_root_of_unity_real<T>(N,i*l*sign);
        sum_y += in_first[l] * complex_root_of_unity_imag<T>(N,i*l*sign);
      }
      // if(i<j) // i==j never happens for odd sizes
      out[j] = -sum_y;
      out[i] = sum_x;
    }
  }

  template<class T,class Allocator_t>
  void real_dft_prime_bruteForce_inplace(
    T* in_first,
    T* in_last,
    int sign,
    const Allocator_t& alloc)
  {
    std::vector<T,Allocator_t> work_space(in_first,in_last,alloc);
    real_dft_prime_bruteForce_outofplace(in_first,in_last,work_space.data(),sign);
    std::copy(work_space.begin(),work_space.end(),in_first);
  }
  template<class T, class Allocator_t>
  void real_dft_prime_bruteForce(
    const T* in_first,
    const T* in_last,
    T* out,
    int sign,
    const Allocator_t& alloc)
  {
    if(in_first==out)
      real_dft_prime_bruteForce_inplace(out,out+std::distance(in_first,in_last),sign,alloc);
    else
      real_dft_prime_bruteForce_outofplace(in_first,in_last,out,sign);
  }

  template<class T>
  void real_inverse_dft_prime_bruteForce_outofplace(
    const T* in_first,
    const T* in_last,
    T* out, int sign)
  /*
    assumptions:
    - allocated memory in out is enough to hold distance(in_first,in_last) element,
    - out!=in
  */
  {
    const long N = static_cast<long>(std::distance(in_first,in_last));
    if(N<=0)
      return;

    {
      T sum_x{0.};
      for(long i=1,j=N-1;i<j;++i,--j)
      {
        sum_x += in_first[i];
      }
      // if(i<j) // i==j never happens for odd sizes
      out[0] = ( 2*sum_x + in_first[0]);
    }
    for(long l=1;l<N; ++l)
    {
      T sum_x{0.},sum_y{0.};
      for(long i=1,j=N-1;i<j;++i,--j)
      {
        sum_x += in_first[i] * complex_root_of_unity_real<T>(N,i*l*sign);
        sum_y += in_first[j] * complex_root_of_unity_imag<T>(N,i*l*sign);
      }
      // if(i<j) // i==j never happens for odd sizes
      out[l] = (2*sum_x - 2*sum_y + in_first[0]);
    }
  }

  template<class T,class Allocator_t>
  void real_inverse_dft_prime_bruteForce_inplace(
    T* in_first,
    T* in_last,
    int sign,
    const Allocator_t& alloc)
  {
    std::vector<T,Allocator_t> work_space(in_first,in_last,alloc);
    real_inverse_dft_prime_bruteForce_outofplace(in_first,in_last,work_space.data(),sign);
    std::copy(work_space.begin(),work_space.end(),in_first);
  }
  template<class T, class Allocator_t>
  void real_inverse_dft_prime_bruteForce(
    const T* in_first,
    const T* in_last,
    T* out,
    int sign,
    const Allocator_t& alloc)
  {
    if(in_first==out)
      real_inverse_dft_prime_bruteForce_inplace(out,out+std::distance(in_first,in_last),sign,alloc);
    else
      real_inverse_dft_prime_bruteForce_outofplace(in_first,in_last,out,sign);
  }

  template <class T, class allocator_t>
  void real_dft_composite_outofplace(
            const T *in_first,
            const T *in_last,
            T* out,
            int /*sign*/,
            const allocator_t& alloc)
  {
    /*
      Cooley-Tukey mapping, intrinsically out-of-place, Decimation in Time
      composite sizes.
    */
    using allocator_type = allocator_t;
    using ComplexType = simple_complex<T>;
    using ComplexAllocator = typename std::allocator_traits<allocator_type>::template rebind_alloc<ComplexType>;

    const long n = static_cast<long>(std::distance(in_first,in_last));
    if(n <=0 )
      return;

    if (n == 1)
    {
        out[0]=in_first[0];
        return;
    }
    std::array<int,32> prime_factors;
    const int nfactors = prime_factorization(n,prime_factors.begin());

    // reorder input
    for (long i = 0; i < n; ++i)
    {
        long j = 0, k = i;
        for (int ip=0;ip<nfactors;++ip)
        {
            int p = prime_factors[ip];
            j = j * p + k % p;
            k /= p;
        }
        out[j] = in_first[i];
    }

    std::reverse(prime_factors.begin(), prime_factors.begin()+nfactors);

    //auto show = [&] (const T* beg, const T* end)
    //{
    //  for(;beg!=end;++beg)
    //  {
    //    std::cout << *beg << ", ";
    //  }
    //  std::cout << "\n";
    //};

    // butterfly pattern
    long len = 1;
    for (int ip=0;ip<nfactors;++ip)
    {
      int p = prime_factors[ip];
      long len_old = len;
      len *= p;

      std::vector<ComplexType,ComplexAllocator> tmp(p,ComplexType(),alloc);
      //std::cout << "pass " << ip << "\n";
      for (long i = 0; i < n; i += len)
      {
        //std::cout << "    i = " << i << "\n";
        for(long k=0;2*k<=len_old;++k)
        {
          if(k==0)
          {
            tmp[0] = ComplexType{out[i],0.};
            for(long j=1;j<p;++j)
              tmp[j] = ComplexType{out[i + j*len_old],0.};
          }else if(2*k == len_old)
          {
            tmp[0] = ComplexType{out[i + k ],0.};
            for(long j=1;j<p;++j)
              tmp[j] = ComplexType{out[i + j*len_old +k ],0.}
                * complex_root_of_unity<ComplexType>(len,k*j);
          }else
          {
            tmp[0] = ComplexType{out[i + k ],-out[i+len_old-k]};
            for(long j=1;j<p;++j)
              tmp[j] = ComplexType{out[i + j*len_old +k ],-out[i+j*len_old + len_old-k]}
                * complex_root_of_unity<ComplexType>(len,k*j);
          }
          if(p==2)
          {
            complex_dft_2(tmp.data(),tmp.data(),1);
          }
          else
          {
            complex_dft_prime_rader<ComplexType,ComplexAllocator>(tmp.data(),tmp.data()+p,tmp.data(),1,alloc);
          }
          for(long j=0;j<p;++j)
          {
            int posx = j*len_old + k, posy = len - k - j*len_old;

            if(posx==0)
            {
              out[i+posx] = tmp[j].real();
            }else if(posx>posy)
            {
              out[i+posx] = tmp[j].imag();
              out[i+posy] = tmp[j].real();
            }else
            {
              out[i+posy] = -tmp[j].imag();
              out[i+posx] = tmp[j].real();
            }
          }
        }
        //show(out+i,out+i+len);
      }
    }
  }

  template<class T,class Allocator_t>
  void real_dft_composite_inplace(
          T* in_first,
          T* in_last,
          int sign,
          const Allocator_t& alloc)
  {
    std::vector<T,Allocator_t> work_space(in_first,in_last,alloc);
    real_dft_composite_outofplace(in_first,in_last,work_space.data(),sign,alloc);
    std::copy(work_space.begin(),work_space.end(),in_first);
  }
  template<class T, class Allocator_t>
  void real_dft_composite(
          const T* in_first,
          const T* in_last,
          T* out,
          int sign,
          const Allocator_t& alloc)
  {
    if(in_first==out)
      real_dft_composite_inplace(out,out+std::distance(in_first,in_last),sign,alloc);
    else
      real_dft_composite_outofplace(in_first,in_last,out,sign,alloc);
  }

  template <class T, class allocator_t>
  void real_inverse_dft_composite_outofplace(
            const T *in_first,
            const T *in_last,
            T* out,
            int /*sign*/,
            const allocator_t& alloc)
  {
    /*
      Cooley-Tukey mapping, intrinsically out-of-place, Decimation in Time
      composite sizes.
      Reverse graph.
    */
    using allocator_type = allocator_t;
    using ComplexType = simple_complex<T>;
    using ComplexAllocator = typename std::allocator_traits<allocator_type>::template rebind_alloc<ComplexType>;

    const long n = static_cast<long>(std::distance(in_first,in_last));
    if(n <=0 )
      return;

    std::copy(in_first,in_last,out);
    if (n == 1)
        return;

    std::array<int,32> prime_factors;
    const int nfactors = prime_factorization(n,prime_factors.begin());

    // butterfly pattern
    for (long ip=0,len=n,prev_len = len;ip<nfactors;++ip,len = prev_len)
    {
      int p = prime_factors[ip];
      prev_len = len/p;

      std::vector<ComplexType,ComplexAllocator> tmp(p,ComplexType(),alloc);
      for (long i = 0; i < n; i += len)
      {
        for(long k=0;2*k<=prev_len;++k)
        {
          for(long j=0;j<p;++j)
          {
            int posx = j*prev_len + k, posy = len - k - j*prev_len;

            if(posx==0 || posx==posy)
            {
              tmp[j] = ComplexType {out[i+posx],0.};
            }else if(posx>posy)
            {
              tmp[j] = ComplexType{out[i+posy],out[i+posx]};
            }else // if(posx<posy)
            {
              tmp[j] = ComplexType{out[i+posx],-out[i+posy]};
            }
          }
          if(p==2)
          {
            complex_dft_2(tmp.data(),tmp.data(),-1);
          }
          else
          {
            complex_dft_prime_rader<ComplexType,ComplexAllocator>(tmp.data(),tmp.data()+p,tmp.data(),-1,alloc);
          }

          if(k==0)
          {
            out[i] = tmp[0].real();
            for(long j=1;j<p;++j)
              out[i + j*prev_len] = tmp[j].real();
          }else if(2*k == prev_len)
          {
            out[i + k ] = tmp[0].real();
            for(long j=1;j<p;++j)
              out[i + j*prev_len +k ] = (tmp[j]* complex_root_of_unity<ComplexType>(len,-k*j) ). real();
          }else
          {
            out[i+k]          =  tmp[0].real();
            out[i+prev_len-k] = -tmp[0].imag();
            for(long j=1;j<p;++j)
            {
              ComplexType cplx = tmp[j] * complex_root_of_unity<ComplexType>(len,-k*j);
              out[i + j*prev_len +k ]        = cplx.real();
              out[i+j*prev_len + prev_len-k] = -cplx.imag();
            }
          }
        }
      }
    }

    std::vector<T,allocator_type> tmp(out,out+n);
    // reorder
    for (long i = 0; i < n; ++i)
    {
        long j = 0, k = i;
        for (int ip=0;ip<nfactors;++ip)
        {
            int p = prime_factors[ip];
            j = j * p + k % p;
            k /= p;
        }
        out[i] = tmp[j];
    }
  }

  template<class T,class Allocator_t>
  void real_inverse_dft_composite_inplace(
          T* in_first,
          T* in_last,
          int sign,
          const Allocator_t& alloc)
  {
    std::vector<T,Allocator_t> work_space(in_first,in_last,alloc);
    real_inverse_dft_composite_outofplace(in_first,in_last,work_space.data(),sign,alloc);
    std::copy(work_space.begin(),work_space.end(),in_first);
  }
  template<class T, class Allocator_t>
  void real_inverse_dft_composite(
          const T* in_first,
          const T* in_last,
          T* out,
          int sign,
          const Allocator_t& alloc)
  {
    if(in_first==out)
      real_inverse_dft_composite_inplace(out,out+std::distance(in_first,in_last),sign,alloc);
    else
      real_inverse_dft_composite_outofplace(in_first,in_last,out,sign,alloc);
  }

  } // namespace detail

  } } } // namespace boost::math::fft

#endif // BOOST_MATH_FFT_REAL_ALGORITHMS_HPP


text:
//
// Created by tao on 7/11/21.
//

#include "altimeter_converter.h"

#include <rosbag/bag.h>
#include <irp_sen_msgs/altimeter.h>
#include <boost/filesystem.hpp>

namespace kaist2bag {

AltimeterConverter::AltimeterConverter(const std::string &dataset_dir, const std::string &save_dir,
                                       const std::string &topic)
                                       : Converter(dataset_dir, save_dir), topic_(topic) {
    bag_name_ = FilterSlash(topic_) + ".bag";
}

int AltimeterConverter::Convert() {
    CheckAndCreateSaveDir();

    boost::filesystem::path bag_file = boost::filesystem::path(save_dir_) / bag_name_;
    rosbag::Bag bag(bag_file.string(), rosbag::bagmode::Write);
    ROS_INFO("saving %s", bag_file.c_str());

    const std::string data_file = dataset_dir_ + "/" + default_data_file;
    FILE* fp = fopen(data_file.c_str(), "r");
    irp_sen_msgs::altimeter altimeter_data;
    int64_t stamp;
    double altimeter_value;
    while (fscanf(fp, "%ld,%lf\n", &stamp, &altimeter_value) == 2) {
        altimeter_data.header.stamp.fromNSec(stamp);
        altimeter_data.header.frame_id = "altimeter";
        altimeter_data.data = altimeter_value;

        bag.write(topic_, altimeter_data.header.stamp, altimeter_data);
    }
    bag.close();
    fclose(fp);
    ROS_INFO("done saving %s", bag_file.c_str());

    return 0;
}

} // namespace kaist2bag


text:
/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

 * -------------------------------------------------------------------------- */

/**
 * @file testBTree.cpp
 * @date Feb 3, 2010
 * @author Chris Beall
 * @author Frank Dellaert
 */

#include <boost/shared_ptr.hpp>
#include <boost/foreach.hpp>
#include <boost/assign/std/list.hpp> // for +=
using namespace boost::assign;

#include <CppUnitLite/TestHarness.h>
#include <gtsam_unstable/base/BTree.h>

using namespace std;
using namespace gtsam;

typedef pair<size_t, size_t> Range;
typedef BTree<string, Range> RangeTree;
typedef BTree<string, int> IntTree;

static std::stringstream ss;
static string x1("x1"), x2("x2"), x3("x3"), x4("x4"), x5("x5");
typedef pair<string, int> KeyInt;
KeyInt p1(x1, 1), p2(x2, 2), p3(x3, 3), p4(x4, 4), p5(x5, 5);

/* ************************************************************************* */
int f(const string& key, const Range& range) {
  return range.first;
}

void g(const string& key, int i) {
  ss << (string) key;
}

int add(const string& k, int v, int a) {
  return v + a;
}

/* ************************************************************************* */
TEST( BTree, add )
{
  RangeTree tree;
  CHECK(tree.empty())
  LONGS_EQUAL(0,tree.height())

  // check the height of tree after adding an element
  RangeTree tree1 = tree.add(x1, Range(1, 1));
  LONGS_EQUAL(1,tree1.height())
  LONGS_EQUAL(1,tree1.size())
  CHECK(tree1.find(x1) == Range(1,1))

  RangeTree tree2 = tree1.add(x5, Range(5, 2));
  RangeTree tree3 = tree2.add(x3, Range(3, 3));
  LONGS_EQUAL(3,tree3.size())
  CHECK(tree3.find(x5) == Range(5,2))
  CHECK(tree3.find(x3) == Range(3,3))

  RangeTree tree4 = tree3.add(x2, Range(2, 4));
  RangeTree tree5 = tree4.add(x4, Range(4, 5));
  LONGS_EQUAL(5,tree5.size())
  CHECK(tree5.find(x4) == Range(4,5))

  // Test functional nature: tree5 and tree6 have different values for x4
  RangeTree tree6 = tree5.add(x4, Range(6, 6));
  CHECK(tree5.find(x4) == Range(4,5))
  CHECK(tree6.find(x4) == Range(6,6))

  // test assignment
  RangeTree c5 = tree5;
  LONGS_EQUAL(5,c5.size())
  CHECK(c5.find(x4) == Range(4,5))

  // test map
  // After (map f tree5) tree contains (x1,1), (x2,2), etc...
  IntTree mapped = tree5.map<int> (f);
  LONGS_EQUAL(2,mapped.find(x2));
  LONGS_EQUAL(4,mapped.find(x4));
}

/* ************************************************************************* */
TEST( BTree, equality )
{
  IntTree tree1 = IntTree().add(p1).add(p2).add(p3).add(p4).add(p5);
  CHECK(tree1==tree1)
  CHECK(tree1.same(tree1))

  IntTree tree2 = IntTree().add(p1).add(p2).add(p3).add(p4).add(p5);
  CHECK(tree2==tree1)
  CHECK(!tree2.same(tree1))

  IntTree tree3 = IntTree().add(p1).add(p2).add(p3).add(p4);
  CHECK(tree3!=tree1)
  CHECK(tree3!=tree2)
  CHECK(!tree3.same(tree1))
  CHECK(!tree3.same(tree2))

  IntTree tree4 = tree3.add(p5);
  CHECK(tree4==tree1)
  CHECK(!tree4.same(tree1))

  IntTree tree5 = tree1;
  CHECK(tree5==tree1)
  CHECK(tree5==tree2)
  CHECK(tree5.same(tree1))
  CHECK(!tree5.same(tree2))
}

/* ************************************************************************* */
TEST( BTree, iterating )
{
  IntTree tree = IntTree().add(p1).add(p2).add(p3).add(p4).add(p5);

  // test iter
  tree.iter(g);
  CHECK(ss.str() == string("x1x2x3x4x5"));

  // test fold
  LONGS_EQUAL(25,tree.fold<int>(add,10))

  // test iterator
  BTree<string, int>::const_iterator it = tree.begin(), it2 = tree.begin();
  CHECK(it==it2)
  CHECK(*it == p1)
  CHECK(it->first == x1)
  CHECK(it->second == 1)
  CHECK(*(++it) == p2)
  CHECK(it!=it2)
  CHECK(it==(++it2))
  CHECK(*(++it) == p3)
  CHECK(*(it++) == p3)
  // post-increment, not so efficient
  CHECK(*it == p4)
  CHECK(*(++it) == p5)
  CHECK((++it)==tree.end())

  // acid iterator test: BOOST_FOREACH
  int sum = 0;
  BOOST_FOREACH(const KeyInt& p, tree)
sum  += p.second;
  LONGS_EQUAL(15,sum)

  // STL iterator test
  list<KeyInt> expected, actual;
  expected += p1,p2,p3,p4,p5;
  copy (tree.begin(),tree.end(),back_inserter(actual));
  CHECK(actual==expected)
}

/* ************************************************************************* */
TEST( BTree, remove )
{
  IntTree tree5 = IntTree().add(p1).add(p2).add(p3).add(p4).add(p5);
  LONGS_EQUAL(5,tree5.size())
  CHECK(tree5.mem(x3))
  IntTree tree4 = tree5.remove(x3);
  LONGS_EQUAL(4,tree4.size())
  CHECK(!tree4.mem(x3))
}

/* ************************************************************************* */
TEST( BTree, stress )
{
  RangeTree tree;
  list<RangeTree::value_type> expected;
  int N = 128;
  for (int i = 1; i <= N; i++) {
    string key('a', i);
    Range value(i - 1, i);
    tree = tree.add(key, value);
    LONGS_EQUAL(i,tree.size())
    CHECK(tree.find(key) == value)
    expected += make_pair(key, value);
  }

  // Check height is log(N)
  LONGS_EQUAL(8,tree.height())

  // stress test iterator
  list<RangeTree::value_type> actual;
  copy(tree.begin(), tree.end(), back_inserter(actual));
  CHECK(actual==expected)

  // deconstruct the tree
  for (int i = N; i >= N; i--) {
    string key('a', i);
    tree = tree.remove(key);
    LONGS_EQUAL(i-1,tree.size())
    CHECK(!tree.mem(key))
  }
}

/* ************************************************************************* */
int main() {
  TestResult tr;
  return TestRegistry::runAllTests(tr);
}
/* ************************************************************************* */


text:
// Copyright (c) 2013-2018 LG Electronics, 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.
//
// SPDX-License-Identifier: Apache-2.0

#include "AppPackage.h"
#include "base/Logging.h"
#include "base/Utils.h"

#include <fstream>
#include <sstream>
#include <stdlib.h>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

#define FILENAME_CONTROL "control.tar.gz"
#define FILENAME_DATA    "data.tar.gz"
#define FILENAME_DEBIAN  "debian-binary"

std::string AppPackage::Control::getPackage() const
{
    return m_package;
}

std::string AppPackage::Control::getVersion() const
{
    return m_version;
}

std::string AppPackage::Control::getArchitecture() const
{
    return m_architecture;
}

uint64_t AppPackage::Control::getInstalledSize() const
{
    return m_installedSize;
}

bool AppPackage::extract(std::string targetFile,
    int targetItem,
    std::string targetPath,
    std::function<void (bool)> onExtract)
{
    gchar* argv[16] = {0};
    GError* gerr = NULL;
    GSpawnFlags flags = (GSpawnFlags)(G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD);

    GPid childPid;
    gboolean result;
    int index = 0;

    argv[index++] = (gchar *) "ar";
    argv[index++] = (gchar *) "x";
    argv[index++] = (gchar *) targetFile.c_str();
    if (targetItem & CONTROL)
        argv[index++] = (gchar *) FILENAME_CONTROL;
    if (targetItem & DATA)
        argv[index++] = (gchar *) FILENAME_DATA;
    if (targetItem & DEBIAN)
        argv[index++] = (gchar *) FILENAME_DEBIAN;
    argv[index] = NULL;

    if (targetItem & CONTROL)
        Utils::remove_file(targetPath + "/" + FILENAME_CONTROL);
    if (targetItem & DATA)
        Utils::remove_file(targetPath + "/" + FILENAME_DATA);
    if (targetItem & DEBIAN)
        Utils::remove_file(targetPath + "/" + FILENAME_DEBIAN);

    m_targetItemList.clear();
    m_canceled = false;

    result = g_spawn_async(targetPath.c_str(),
                           argv,
                           NULL,
                           flags,
                           NULL,
                           NULL,
                           &childPid,
                           &gerr);

    if (result)
    {
        g_child_watch_add(childPid, cbExtractComplete, this);

        m_targetFile = targetFile;
        m_targetPath = targetPath;
        m_funcExtracted = onExtract;
        if (targetItem & CONTROL)
            m_targetItemList.push_back(FILENAME_CONTROL);
        if (targetItem & DATA)
            m_targetItemList.push_back(FILENAME_DATA);

        return true;
    }

    if (gerr)
    {
        LOG_ERROR(MSGID_APPUNPACK_IPK_FAIL,2,
            PMLOGKS(FILENAME, targetFile.c_str()),
            PMLOGKS(LOGKEY_ERRTEXT,gerr->message),"Failed to unpack file");
        g_error_free(gerr);
    }

    return false;
}

bool AppPackage::extractOneItem()
{
    if (m_targetItemList.empty())
    {
        m_funcExtracted(true);
        return true;
    }

    std::string targetFile = m_targetItemList.front();
    m_targetItemList.pop_front();

    gchar* argv[16] = {0};
    GError* gerr = NULL;
    GSpawnFlags flags = (GSpawnFlags)(G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD);

    GPid childPid;
    gboolean result;
    int index = 0;

    argv[index++] = (gchar *) "tar";
    argv[index++] = (gchar *) "xzf";
    argv[index++] = (gchar *) targetFile.c_str();
    argv[index] = NULL;

    result = g_spawn_async(m_targetPath.c_str(),
                           argv,
                           NULL,
                           flags,
                           NULL,
                           NULL,
                           &childPid,
                           &gerr);

    if (result)
    {
        g_child_watch_add(childPid, cbExtractComplete, this);
        return true;
    }

    if (gerr)
    {
        LOG_ERROR(MSGID_APPUNPACK_TAR_FAIL,2,
            PMLOGKS(FILENAME, targetFile.c_str()),
            PMLOGKS(LOGKEY_ERRTEXT,gerr->message),"Failed to unzip file");
        g_error_free(gerr);
    }

    return false;
}

bool AppPackage::parseControl(std::string controlFilePath, AppPackage::Control &control)
{
    std::ifstream file(controlFilePath.c_str());
    std::string line;
    std::string field, value;

    if (file.good())
    {
        while(std::getline(file, line))
        {
            std::istringstream lineStream(line);

            if (!std::getline(lineStream, field, ':'))
                continue;
            if (!std::getline(lineStream, value))
                continue;

            boost::trim(value);
            if (field == "Package") control.m_package = value;
            else if (field == "Version") control.m_version = value;
            else if (field == "Architecture") control.m_architecture = value;
            else if (field == "Installed-Size") control.m_installedSize = boost::lexical_cast<uint64_t>(value);
        }

        file.close();
        return true;
    }

    return false;
}

void AppPackage::saveInstalledSizeToControlFile(std::string controlFilePath, uint64_t unpackFileSize)
{
    std::ofstream file(controlFilePath.c_str(), std::ios::app);

    if (file.good())
        file << "Installed-Size: " << unpackFileSize << std::endl;

    file.close();
}

void AppPackage::cbExtractComplete(GPid pid, gint status, gpointer user_data)
{
    AppPackage *package = reinterpret_cast<AppPackage*>(user_data);
    if (!package)
        return;

    if (!WIFEXITED(status) || (WEXITSTATUS(status) != 0) || package->isCanceled())
    {
        package->m_funcExtracted(false);
        return;
    }

    if (!package->extractOneItem())
        package->m_funcExtracted(false);
}

void AppPackage::cancel()
{
    m_canceled = true;
}

bool AppPackage::isCanceled() const
{
    return m_canceled;
}


text:
#define BOOST_TEST_MODULE pichi vo_egress test

#include "utils.hpp"
#include "vo.hpp"
#include <boost/mpl/set.hpp>
#include <boost/test/unit_test.hpp>
#include <pichi/common/literals.hpp>
#include <pichi/vo/egress.hpp>
#include <pichi/vo/keys.hpp>
#include <pichi/vo/parse.hpp>
#include <pichi/vo/to_json.hpp>

#ifdef _MSC_VER
#ifdef OPTIONAL
#undef OPTIONAL
#endif OPTIONAL
#endif  // _MSC_VER

using namespace std;
using namespace rapidjson;
namespace mpl = boost::mpl;

namespace pichi::unit_test {

BOOST_AUTO_TEST_SUITE(VO_EGRESS)

using namespace pichi::vo;

enum class Present { MANDATORY, OPTIONAL, UNUSED };

template <AdapterType type> struct AdapterTrait {
};

template <> struct AdapterTrait<AdapterType::DIRECT> {
  static const auto type_ = AdapterType::DIRECT;
  static const auto server_ = Present::UNUSED;
  static const auto credential_ = Present::UNUSED;
  static const auto option_ = Present::UNUSED;
  static const auto tls_ = Present::UNUSED;
  static const auto websocket_ = Present::UNUSED;
};

template <> struct AdapterTrait<AdapterType::HTTP> {
  static const auto type_ = AdapterType::HTTP;
  static const auto server_ = Present::MANDATORY;
  static const auto credential_ = Present::OPTIONAL;
  static const auto option_ = Present::UNUSED;
  static const auto tls_ = Present::OPTIONAL;
  static const auto websocket_ = Present::UNUSED;
  using Credential = UpEgressCredential;
};

template <> struct AdapterTrait<AdapterType::SOCKS5> {
  static const auto type_ = AdapterType::SOCKS5;
  static const auto server_ = Present::MANDATORY;
  static const auto credential_ = Present::OPTIONAL;
  static const auto option_ = Present::UNUSED;
  static const auto tls_ = Present::OPTIONAL;
  static const auto websocket_ = Present::UNUSED;
  using Credential = UpEgressCredential;
};

template <> struct AdapterTrait<AdapterType::REJECT> {
  static const auto type_ = AdapterType::REJECT;
  static const auto server_ = Present::UNUSED;
  static const auto credential_ = Present::UNUSED;
  static const auto option_ = Present::MANDATORY;
  static const auto tls_ = Present::UNUSED;
  static const auto websocket_ = Present::UNUSED;
  using Option = RejectOption;
};

template <> struct AdapterTrait<AdapterType::SS> {
  static const auto type_ = AdapterType::SS;
  static const auto server_ = Present::MANDATORY;
  static const auto credential_ = Present::UNUSED;
  static const auto option_ = Present::MANDATORY;
  static const auto tls_ = Present::UNUSED;
  static const auto websocket_ = Present::UNUSED;
  using Option = ShadowsocksOption;
};

template <> struct AdapterTrait<AdapterType::TROJAN> {
  static const auto type_ = AdapterType::TROJAN;
  static const auto server_ = Present::MANDATORY;
  static const auto credential_ = Present::MANDATORY;
  static const auto option_ = Present::UNUSED;
  static const auto tls_ = Present::MANDATORY;
  static const auto websocket_ = Present::OPTIONAL;
  using Credential = TrojanEgressCredential;
};

template <> struct AdapterTrait<AdapterType::VMESS> {
  static const auto type_ = AdapterType::VMESS;
  static const auto server_ = Present::MANDATORY;
  static const auto credential_ = Present::MANDATORY;
  static const auto option_ = Present::UNUSED;
  static const auto tls_ = Present::OPTIONAL;
  static const auto websocket_ = Present::OPTIONAL;
  using Credential = VMessEgressCredential;
};

using AllAdapterTraits =
    mpl::set<AdapterTrait<AdapterType::DIRECT>, AdapterTrait<AdapterType::HTTP>,
             AdapterTrait<AdapterType::SOCKS5>, AdapterTrait<AdapterType::REJECT>,
             AdapterTrait<AdapterType::SS>, AdapterTrait<AdapterType::TROJAN>,
             AdapterTrait<AdapterType::VMESS>>;

template <AdapterType type> Value defaultEgressJson()
{
  using Trait = AdapterTrait<type>;
  auto egress = Value{kObjectType};
  egress.AddMember(egress::TYPE, toJson(type, alloc), alloc);

  if constexpr (Trait::server_ == Present::MANDATORY)
    egress.AddMember(egress::SERVER, toJson(DEFAULT_ENDPOINT, alloc), alloc);
  if constexpr (Trait::credential_ == Present::MANDATORY)
    egress.AddMember(egress::CREDENTIAL, defaultCredentialJson<typename Trait::Credential>(),
                     alloc);
  if constexpr (Trait::option_ == Present::MANDATORY)
    egress.AddMember(egress::OPTION, defaultOptionJson<typename Trait::Option>(), alloc);
  if constexpr (Trait::tls_ == Present::MANDATORY)
    egress.AddMember(egress::TLS, defaultOptionJson<TlsEgressOption>(), alloc);
  if constexpr (Trait::websocket_ == Present::MANDATORY)
    egress.AddMember(egress::WEBSOCKET, defaultOptionJson<WebsocketOption>(), alloc);
  return egress;
}

template <AdapterType type> Egress defaultEgress()
{
  using Trait = AdapterTrait<type>;
  auto egress = Egress{};
  egress.type_ = type;
  if constexpr (Trait::server_ == Present::MANDATORY) egress.server_ = DEFAULT_ENDPOINT;
  if constexpr (Trait::credential_ == Present::MANDATORY)
    egress.credential_ = defaultCredential<typename Trait::Credential>();
  if constexpr (Trait::option_ == Present::MANDATORY)
    egress.opt_ = defaultOption<typename Trait::Option>();
  if constexpr (Trait::tls_ == Present::MANDATORY) egress.tls_ = defaultOption<TlsEgressOption>();
  if constexpr (Trait::websocket_ == Present::MANDATORY)
    egress.websocket_ = defaultOption<WebsocketOption>();
  return egress;
}

template <AdapterType type, typename Key> void verifyMandatoryField(Key&& key)
{
  auto json = defaultEgressJson<type>();
  json.RemoveMember(key);
  BOOST_CHECK_EXCEPTION(parse<Egress>(json), Exception, verifyException<PichiError::BAD_JSON>);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(parse_Default_Ones, Trait, AllAdapterTraits)
{
  BOOST_CHECK(defaultEgress<Trait::type_>() == parse<Egress>(defaultEgressJson<Trait::type_>()));
}

BOOST_AUTO_TEST_CASE(parse_Invalid_Json_Type)
{
  for (auto t : {kNumberType, kNullType, kStringType, kTrueType, kFalseType, kArrayType}) {
    BOOST_CHECK_EXCEPTION(parse<Egress>(Value{t}), Exception,
                          verifyException<PichiError::BAD_JSON>);
  }
}

BOOST_AUTO_TEST_CASE_TEMPLATE(parse_Type_Is_Mandatory, Trait, AllAdapterTraits)
{
  auto noType = defaultEgressJson<Trait::type_>();
  noType.RemoveMember(egress::TYPE);
  BOOST_CHECK_EXCEPTION(parse<Egress>(noType), Exception, verifyException<PichiError::BAD_JSON>);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(parse_Invalid_Types, Trait, AllAdapterTraits)
{
  auto invalid = defaultEgressJson<Trait::type_>();
  invalid[egress::TYPE] = toJson(AdapterType::TUNNEL, alloc);
  BOOST_CHECK_EXCEPTION(parse<Egress>(invalid), Exception, verifyException<PichiError::BAD_JSON>);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(parse_Mandatory_Fields, Trait, AllAdapterTraits)
{
  if constexpr (Trait::server_ == Present::MANDATORY)
    verifyMandatoryField<Trait::type_>(egress::SERVER);
  if constexpr (Trait::credential_ == Present::MANDATORY)
    verifyMandatoryField<Trait::type_>(egress::CREDENTIAL);
  if constexpr (Trait::option_ == Present::MANDATORY)
    verifyMandatoryField<Trait::type_>(egress::OPTION);
  if constexpr (Trait::tls_ == Present::MANDATORY) verifyMandatoryField<Trait::type_>(egress::TLS);
  if constexpr (Trait::websocket_ == Present::MANDATORY)
    verifyMandatoryField<Trait::type_>(egress::WEBSOCKET);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(parse_Optional_Fields, Trait, AllAdapterTraits)
{
  if constexpr (Trait::credential_ == Present::OPTIONAL) {
    using Credential = typename Trait::Credential;
    auto egress = defaultEgress<Trait::type_>();
    egress.credential_ = defaultCredential<Credential>();
    BOOST_CHECK(parse<Egress>(defaultEgressJson<Trait::type_>().AddMember(
                    egress::CREDENTIAL, defaultCredentialJson<Credential>(), alloc)) == egress);
  }
  if constexpr (Trait::option_ == Present::OPTIONAL) {
    using Option = typename Trait::Option;
    auto egress = defaultEgress<Trait::type_>();
    egress.opt_ = defaultOption<Option>();
    BOOST_CHECK(parse<Egress>(defaultEgressJson<Trait::type_>().AddMember(
                    egress::OPTION, defaultOptionJson<Option>(), alloc)) == egress);
  }
  if constexpr (Trait::tls_ == Present::OPTIONAL) {
    auto egress = defaultEgress<Trait::type_>();
    egress.tls_ = defaultOption<TlsEgressOption>();
    BOOST_CHECK(parse<Egress>(defaultEgressJson<Trait::type_>().AddMember(
                    egress::TLS, defaultOptionJson<TlsEgressOption>(), alloc)) == egress);
  }
  if constexpr (Trait::websocket_ == Present::OPTIONAL) {
    auto egress = defaultEgress<Trait::type_>();
    egress.websocket_ = defaultOption<WebsocketOption>();
    BOOST_CHECK(parse<Egress>(defaultEgressJson<Trait::type_>().AddMember(
                    egress::WEBSOCKET, defaultOptionJson<WebsocketOption>(), alloc)) == egress);
  }
}

BOOST_AUTO_TEST_CASE_TEMPLATE(parse_Unused_Fields, Trait, AllAdapterTraits)
{
  auto json = defaultEgressJson<Trait::type_>();
  if constexpr (Trait::server_ == Present::UNUSED)
    json.AddMember(egress::SERVER, toJson(DEFAULT_ENDPOINT, alloc), alloc);
  if constexpr (Trait::credential_ == Present::UNUSED)
    json.AddMember(egress::CREDENTIAL, Value{kObjectType}, alloc);
  if constexpr (Trait::option_ == Present::UNUSED)
    json.AddMember(egress::OPTION, Value{kObjectType}, alloc);
  if constexpr (Trait::tls_ == Present::UNUSED)
    json.AddMember(egress::TLS, defaultOptionJson<TlsEgressOption>(), alloc);
  if constexpr (Trait::websocket_ == Present::UNUSED)
    json.AddMember(egress::WEBSOCKET, defaultOptionJson<WebsocketOption>(), alloc);
  BOOST_CHECK(parse<Egress>(json) == defaultEgress<Trait::type_>());
}

BOOST_AUTO_TEST_CASE_TEMPLATE(toJson_Default_Ones, Trait, AllAdapterTraits)
{
  BOOST_CHECK(defaultEgressJson<Trait::type_>() == toJson(defaultEgress<Trait::type_>(), alloc));
}

BOOST_AUTO_TEST_CASE(toJson_Invalid_Adapter_Type)
{
  auto egress = Egress{};
  egress.type_ = AdapterType::TUNNEL;
  BOOST_CHECK_EXCEPTION(toJson(egress, alloc), Exception, verifyException<PichiError::MISC>);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(toJson_Mandatory_Fields, Trait, AllAdapterTraits)
{
  if constexpr (Trait::server_ == Present::MANDATORY) {
    auto egress = defaultEgress<Trait::type_>();
    egress.server_.reset();
    BOOST_CHECK_EXCEPTION(toJson(egress, alloc), Exception, verifyException<PichiError::MISC>);
  }
  if constexpr (Trait::credential_ == Present::MANDATORY) {
    auto egress = defaultEgress<Trait::type_>();
    egress.credential_.reset();
    BOOST_CHECK_EXCEPTION(toJson(egress, alloc), Exception, verifyException<PichiError::MISC>);
  }
  if constexpr (Trait::option_ == Present::MANDATORY) {
    auto egress = defaultEgress<Trait::type_>();
    egress.opt_.reset();
    BOOST_CHECK_EXCEPTION(toJson(egress, alloc), Exception, verifyException<PichiError::MISC>);
  }
  if constexpr (Trait::tls_ == Present::MANDATORY) {
    auto egress = defaultEgress<Trait::type_>();
    egress.tls_.reset();
    BOOST_CHECK_EXCEPTION(toJson(egress, alloc), Exception, verifyException<PichiError::MISC>);
  }
  if constexpr (Trait::websocket_ == Present::MANDATORY) {
    auto egress = defaultEgress<Trait::type_>();
    egress.websocket_.reset();
    BOOST_CHECK_EXCEPTION(toJson(egress, alloc), Exception, verifyException<PichiError::MISC>);
  }
}

BOOST_AUTO_TEST_CASE_TEMPLATE(toJson_Optional_Fields, Trait, AllAdapterTraits)
{
  auto egress = defaultEgress<Trait::type_>();
  auto json = defaultEgressJson<Trait::type_>();

  if constexpr (Trait::credential_ == Present::OPTIONAL) {
    egress.credential_ = defaultCredential<typename Trait::Credential>();
    json.AddMember(egress::CREDENTIAL, defaultCredentialJson<typename Trait::Credential>(), alloc);
  }
  if constexpr (Trait::option_ == Present::OPTIONAL) {
    egress.opt_ = defaultOption<typename Trait::Option>();
    json.AddMember(egress::OPTION, defaultOptionJson<typename Trait::Option>(), alloc);
  }
  if constexpr (Trait::tls_ == Present::OPTIONAL) {
    egress.tls_ = defaultOption<TlsEgressOption>();
    json.AddMember(egress::TLS, defaultOptionJson<TlsEgressOption>(), alloc);
  }
  if constexpr (Trait::websocket_ == Present::OPTIONAL) {
    egress.websocket_ = defaultOption<WebsocketOption>();
    json.AddMember(egress::WEBSOCKET, defaultOptionJson<WebsocketOption>(), alloc);
  }

  BOOST_CHECK(toJson(egress, alloc) == json);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(toJson_Unused_Fields, Trait, AllAdapterTraits)
{
  auto egress = defaultEgress<Trait::type_>();
  if constexpr (Trait::server_ == Present::UNUSED) egress.server_ = DEFAULT_ENDPOINT;
  if constexpr (Trait::credential_ == Present::UNUSED)
    egress.credential_ = defaultCredential<UpEgressCredential>();
  if constexpr (Trait::option_ == Present::UNUSED) egress.opt_ = defaultOption<RejectOption>();
  if constexpr (Trait::tls_ == Present::UNUSED) egress.tls_ = defaultOption<TlsEgressOption>();
  if constexpr (Trait::websocket_ == Present::UNUSED)
    egress.websocket_ = defaultOption<WebsocketOption>();
  BOOST_CHECK(toJson(egress, alloc) == defaultEgressJson<Trait::type_>());
}

BOOST_AUTO_TEST_SUITE_END()

}  // namespace pichi::unit_test

max_stars_repo_name: imuzi/pichi

max_issues_repo_name: imuzi/pichi

max_forks_repo_name: imuzi/pichi


text:
#include <iostream>

#include <boost/algorithm/string.hpp>

#include <fc/io/json.hpp>

#include <graphene/utilities/key_conversion.hpp>

#include <steemit/protocol/types.hpp>
#include <steemit/protocol/authority.hpp>

#include <steemit/chain/shared_authority.hpp>

#include <boost/interprocess/sync/named_mutex.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>

using boost::multi_index_container;
using namespace boost::multi_index;
namespace bip=boost::interprocess;

/* shared_string is a string type placeable in shared memory,
 *  * courtesy of Boost.Interprocess.
 *   */

typedef bip::basic_string<
        char, std::char_traits<char>,
        bip::allocator<char, bip::managed_mapped_file::segment_manager>
> shared_string;

typedef bip::allocator<shared_string, bip::managed_mapped_file::segment_manager> basic_string_allocator;

namespace fc {
    void to_variant(const shared_string &s, fc::variant &vo) {
        vo = std::string(s.c_str());
    }

    void from_variant(const fc::variant &var, shared_string &vo) {
        vo = var.as_string().c_str();
    }

    /*
    template<typename... T >
    void to_variant( const bip::deque< T... >& t, fc::variant& v ) {
      std::vector<variant> vars(t.size());
      for( size_t i = 0; i < t.size(); ++i ) {
         vars[i] = t[i];
      }
      v = std::move(vars);
    }

    template<typename T, typename... A>
    void from_variant( const fc::variant& v, bip::deque< T, A... >& d ) {
      const variants& vars = v.get_array();
      d.clear();
      d.resize( vars.size() );
      for( uint32_t i = 0; i < vars.size(); ++i ) {
         from_variant( vars[i], d[i] );
      }
    }
    */
}

/* Book record. All its members can be placed in shared memory,
 *  * hence the structure itself can too.
 *   */

struct book {
    typedef bip::allocator<book, bip::managed_mapped_file::segment_manager> allocator_type;

    template<typename Constructor, typename Allocator>
    book(Constructor &&c, const Allocator &al)
            :name(al), author(al), pages(0), prize(0),
             auth(bip::allocator<steemit::chain::shared_authority, bip::managed_mapped_file::segment_manager>(al.get_segment_manager())),
             deq(basic_string_allocator(al.get_segment_manager())) {
        c(*this);
    }

    shared_string name;
    shared_string author;
    int32_t pages;
    int32_t prize;
    steemit::chain::shared_authority auth;
    bip::deque<shared_string, basic_string_allocator> deq;

    book(const shared_string::allocator_type &al) :
            name(al), author(al), pages(0), prize(0),
            auth(bip::allocator<steemit::chain::shared_authority, bip::managed_mapped_file::segment_manager>(al.get_segment_manager())),
            deq(basic_string_allocator(al.get_segment_manager())) {
    }

};

typedef multi_index_container<
        book,
        indexed_by<
                ordered_non_unique<BOOST_MULTI_INDEX_MEMBER(book, shared_string, author)>,
                ordered_non_unique<BOOST_MULTI_INDEX_MEMBER(book, shared_string, name)>,
                ordered_non_unique<BOOST_MULTI_INDEX_MEMBER(book, int32_t, prize)>
        >,
        bip::allocator<book, bip::managed_mapped_file::segment_manager>
> book_container;

FC_REFLECT(book, (name)(author)(pages)(prize)(deq)(auth))

struct astr {
    fc::fixed_string<> str;
    fc::fixed_string<> str1;
    fc::fixed_string<> str2;
};
FC_REFLECT(astr, (str)(str1)(str2));
struct bstr {
    std::string str;
    std::string str1;
    std::string str2;
};
FC_REFLECT(bstr, (str)(str1)(str2));

int main(int argc, char **argv, char **envp) {
    try {

        bip::managed_mapped_file seg(bip::open_or_create, "./book_container.db",
                1024 * 100);
        bip::named_mutex mutex(bip::open_or_create, "./book_container.db");

        /*
        book b( book::allocator_type( seg.get_segment_manager() ) );
        b.name = "test name";
        b.author = "test author";
        b.deq.push_back( shared_string( "hello world", basic_string_allocator( seg.get_segment_manager() )  ) );
        idump((b));
        */
        book_container *pbc = seg.find_or_construct<book_container>("book container")(book_container::ctor_args_list(),
                book_container::allocator_type(seg.get_segment_manager()));

        for (const auto &item : *pbc) {
            idump((item));
        }

        //b.pages = pbc->size();
        //b.auth = steemit::chain::authority( 1, "dan", pbc->size() );
        pbc->emplace([&](book &b) {
            b.name = "emplace name";
            b.pages = pbc->size();
        }, book::allocator_type(seg.get_segment_manager()));

        bip::deque < book,
                book::allocator_type > *deq =
                        seg.find_or_construct < bip::deque < book,
                book::allocator_type > >
                ("book deque")(book_container::allocator_type(seg.get_segment_manager()));
        idump((deq->size()));

        // book c( b ); //book::allocator_type( seg.get_segment_manager() ) );
        // deq->push_back( b );

    } catch (const std::exception &e) {
        edump((std::string(e.what())));
    }
    return 0;
}

max_stars_repo_name: sergeyrizan/botchain-bot

max_issues_repo_name: sergeyrizan/botchain-bot

max_forks_repo_name: sergeyrizan/botchain-bot


text:
//
//  RaceText.cpp
//  SilverSprints
//
//  Created by Charlie Whitney on 10/13/14.
//
//

#include "ui/RaceText.h"
#include <boost/algorithm/string.hpp>
#include <sstream>

using namespace gfx;
using namespace ci;
using namespace ci::app;
using namespace std;

RaceText::RaceText( const ci::Color &color ){
    mColor = color;
}

std::string RaceText::toDec( const float &num, const int &decPlaces ) {
    std::ostringstream buffer;
    buffer << fixed << setprecision( decPlaces ) << num;
    return buffer.str();
}

void RaceText::draw( gfx::PlayerData *data, const ci::vec2 &offset )
{
    gl::pushMatrices();{
        gl::translate( offset );

        int w = 7;

        gl::color( mColor );
        // PLAYER NUMBER ---------

        // COLORED GRID ----------
        gl::translate( 150, 0);
        if( !data->didFinishRace() ){
            gl::drawSolidRect( Rectf(0,       0,      1670,   w) );   // T
            gl::drawSolidRect( Rectf(0,       0,      w,      68) );  // L
            gl::drawSolidRect( Rectf(1670-w,  0,      1670,   68) );  // R
            gl::drawSolidRect( Rectf(0,       68-w,   1670,   68) );  // B
            gl::drawSolidRect( Rectf(1462-w,  w,      1462, 68-w) );  // MID
        }else{
            gl::drawSolidRect( Rectf(0,       0,      1670,   68) );  // BG
            gl::color( Color::black() );
            gl::drawSolidRect( Rectf(1462-w,  w,      1462, 68-w) );  // MID
        }

        // TEXT ------------------
        gl::color( Color::white() );

        // NAME
        boost::to_upper(data->player_name);
        Model::instance().texFont->drawString(data->player_name, vec2(20, 44), Model::instance().getTfDrawOpts());

        // SPEED
        if( Model::instance().getUsesKph()){
            if(getElapsedSeconds() - mLastSpeedUpdate > Model::instance().speedUpdateInterval){
                mLastSpeed = data->getKph();
                mLastSpeedUpdate = getElapsedSeconds();
            }

			std::string tx = toDec(mLastSpeed, 1) + " KPH";
			vec2 strSize = Model::instance().texFont->measureString(tx) / Model::instance().getFontScale();
//            Model::instance().texFont->drawString(tx, vec2(1580 - strSize.x, 44), Model::instance().getTfDrawOpts() );
            Model::instance().texFont->drawString(tx, vec2(1430 - strSize.x, 44), Model::instance().getTfDrawOpts() );
        }else{
            if(getElapsedSeconds() - mLastSpeedUpdate > Model::instance().speedUpdateInterval){
                mLastSpeed = data->getMph();
                mLastSpeedUpdate = getElapsedSeconds();
            }

			std::string tx = toDec(mLastSpeed, 1) + " MPH";
			vec2 strSize = Model::instance().texFont->measureString(tx) / Model::instance().getFontScale();
			Model::instance().texFont->drawString(tx, vec2(1430 - strSize.x, 44), Model::instance().getTfDrawOpts() );
        }

        // DISTANCE AND TIME
        if( Model::instance().getCurrentRaceType() == Model::RACE_TYPE::RACE_TYPE_TIME ){
            if(Model::instance().getUsesKph()){
                Model::instance().texFont->drawString(toDec(data->getDistanceMeters(), 2) + "m", vec2(1485,44),
					Model::instance().getTfDrawOpts());
            }else{
                Model::instance().texFont->drawString(toDec(data->getDistanceFeet(), 2) + "ft", vec2(1485,44),
					Model::instance().getTfDrawOpts());
            }
        }
        else if(Model::instance().getCurrentRaceType() == Model::RACE_TYPE::RACE_TYPE_DISTANCE){
            if( data->didFinishRace() ){
                Model::instance().texFont->drawString(sb::utils::millisToTimestamp( data->finishTimeMillis ), vec2(1485,44),
					Model::instance().getTfDrawOpts());
            }else{
                Model::instance().texFont->drawString(sb::utils::millisToTimestamp( Model::instance().elapsedRaceTimeMillis ), vec2(1485,44),
					Model::instance().getTfDrawOpts());
            }
        }

    }gl::popMatrices();
}

max_stars_repo_name: nfinitedesign/SilverSprint

max_issues_repo_name: nfinitedesign/SilverSprint

max_forks_repo_name: nfinitedesign/SilverSprint


text:
#ifndef __LLPM_MODULE_HPP__
#define __LLPM_MODULE_HPP__

#include <llpm/design.hpp>
#include <llpm/ports.hpp>
#include <llpm/block.hpp>
#include <llpm/connection.hpp>
#include <libraries/core/comm_intr.hpp>
#include <libraries/core/interface.hpp>
#include <util/cache.hpp>

#include <llvm/IR/Module.h>
#include <llvm/Transforms/Utils/ValueMapper.h>
#include <boost/foreach.hpp>

namespace llpm {

class Design;

class Module : public Block {
protected:
    Design& _design;

    llvm::ValueToValueMapTy VMap;
    llvm::Module* _swModule;

    // A type which represents this module in the S/W version of this
    // module
    llvm::StructType* _swType;
    // A type which represents this module's S/W interface. Typically
    // opaque
    llvm::StructType* _ifaceType;

    llvm::Function* cloneFunc(llvm::Function* F, std::string name);
    llvm::Function* createCallStub(Interface*);
    llvm::Function* createPortStub(Port*);

    std::map<std::string, llvm::Function*> _interfaceStubs;
    std::map<Port*, llvm::Function*> _portStubs;

    // Unit testing functions
    std::set<llvm::Function*> _tests;
    std::map<std::string, llvm::Function*> _swVersion;

public:
    Module(Design& design, std::string name) :
        _design(design),
        _swModule(NULL)
    {
        this->name(name);
    }
    virtual ~Module() { }

    DEF_GET_NP(design);
    llvm::Module* swModule() {
        return _swModule;
    }
    virtual void swModule(llvm::Module* mod);
    void createSWModule(llvm::Module*);
    DEF_GET_NP(swType);
    DEF_GET_NP(ifaceType);

    llvm::Function* swVersion(std::string name) {
        auto f = _swVersion.find(name);
        if (f != _swVersion.end())
            return f->second;
        return NULL;
    }
    std::set<llvm::Function*> tests() {
        return _tests;
    }
    llvm::Function* interfaceStub(std::string name) {
        auto f = _interfaceStubs.find(name);
        if (f == _interfaceStubs.end())
            return NULL;
        return f->second;
    }
    const std::map<std::string, llvm::Function*>& interfaceStubs() {
        return _interfaceStubs;
    }

    virtual bool hasState() const = 0;
    virtual bool isPure() const {
        return !hasState();
    }

    // For opaque modules, this may return NULL
    virtual ConnectionDB* conns() {
        return NULL;
    }
    virtual const ConnectionDB* conns() const {
        return NULL;
    }

    // Return the current change count -- useful for tracking if
    // changes have been made to a module
    virtual uint64_t changeCounter() = 0;

    virtual void blocks(std::vector<Block*>&) const = 0;
    virtual void submodules(std::vector<Module*>&) const = 0;
    virtual void submodules(std::vector<Block*>& vec) const = 0;

    virtual unsigned internalRefine(
        int depth = -1,
        Refinery::StopCondition* sc = NULL) = 0;

    virtual bool refined(Refinery::StopCondition* sc) {
        std::vector<Block*> crude;
        this->blocks(crude);
        return sc->refined(crude);
    }
    virtual void validityCheck() const = 0;

    virtual OutputPort* getDriver(const InputPort*) const {
        return nullptr;
    }
    virtual InputPort* getSink(const OutputPort*) const {
        return nullptr;
    }
    void internalDrivers(std::vector<OutputPort*>&) const;

    virtual bool hasCycle() const = 0;
};

/**
 * Each input and output ports owned by ContainerModule refers to the
 * external ports of the module. Their internal counterparts need to
 * below belong to something, but if they also belong to the
 * ContainerModule, then it'll look like they're external to the
 * module rather than internal since port->owner()->module() will
 * return the module which contains the ContainerModule rather than
 * returning the module itself.
 *
 * To get around this issue, we create a DummyBlock to each container
 * input and output and use the block's appropriate port as the
 * internal driver/sink. It's a bit of a hack, but it works.
 */
class DummyBlock: public Identity {
    Port* _modPort;
public:
    DummyBlock(llvm::Type* t, Port* modPort) :
        Identity(t),
        _modPort(modPort) { }

    DummyBlock(Port* modPort) :
        Identity(modPort->type()),
        _modPort(modPort) { }

    DEF_GET_NP(modPort);
};

/**
 * A module which a third party can edit
 */
class MutableModule: public Module {
public:
    MutableModule(Design& design, std::string name) :
        Module(design, name) { }

    virtual ConnectionDB* conns() = 0;
    virtual const ConnectionDB* conns() const = 0;

    virtual uint64_t changeCounter() {
        return conns()->changeCounter();
    }

    virtual bool hasState() const {
        std::set<Block*> blocks;
        conns()->findAllBlocks(blocks);
        for(Block* b: blocks) {
            if (b->hasState())
                return true;
        }

        return false;
    }

    virtual void blocks(std::vector<Block*>& vec) const {
        std::set<Block*> blocks;
        conns()->findAllBlocks(blocks);
        vec.insert(vec.end(), blocks.begin(), blocks.end());
    }

    virtual void blocks(std::set<Block*>& blocks) const {
        conns()->findAllBlocks(blocks);
    }

    virtual unsigned size() const {
        std::set<Block*> b;
        blocks(b);
        return b.size();
    }

    virtual void submodules(std::vector<Block*>& vec) const {
        std::set<Block*> blocks;
        conns()->findAllBlocks(blocks);
        for (Block* b: blocks) {
            Module* m = dynamic_cast<Module*>(b);
            if (m != NULL)
                vec.push_back(m);
        }
    }

    virtual void submodules(std::vector<Module*>& vec) const {
        std::set<Block*> blocks;
        conns()->findAllBlocks(blocks);
        for (Block* b: blocks) {
            Module* m = dynamic_cast<Module*>(b);
            if (m != NULL)
                vec.push_back(m);
        }
    }
};

/**
 * This module simply contains blocks. It is likely to be the most
 * common module class and a good default module base class. Should
 * be sub-classed to define input and output ports.
 */
class ContainerModule : public MutableModule {
protected:
    // The connections between blocks in this module
    ConnectionDB _conns;

    // Each container module input and output port have a pass
    // through block and a mapping to the internal output and input
    // port on the corresponding pass through block.
    std::map<InputPort*, boost::intrusive_ptr<DummyBlock>> _inputMap;
    std::map<OutputPort*, boost::intrusive_ptr<DummyBlock>> _outputMap;
    std::set<Interface*> _ownedInterfaces;
    std::set<Port*>      _ownedPorts;

    InputPort* addInputPort(InputPort* ip, std::string name = "");
    InputPort* createInputPort(llvm::Type* ty, std::string name = "");
    void removeInputPort(InputPort* ip);
    OutputPort* addOutputPort(OutputPort* op, std::string name = "");
    OutputPort* createOutputPort(llvm::Type* ty, std::string name = "");
    void removeOutputPort(OutputPort* ip);
    Interface* addClientInterface(OutputPort* req,
                                  InputPort* resp,
                                  std::string name = "");
    Interface* addServerInterface(InputPort* req,
                                  OutputPort* resp,
                                  std::string name = "");
    void removeInterface(Interface* iface);

    /***
     * Cached data
     */
    Cache<bool> _hasCycle;
    bool _hasCycleCompute() const;

    CacheMap<const OutputPort*, DependenceRule> _deps;
    DependenceRule _findDeps(const OutputPort*) const;

public:
    ContainerModule(Design& design, std::string name) :
        MutableModule(design, name),
        _conns(this),
        _hasCycle(_conns.counterPtr(),
                  boost::bind(&ContainerModule::_hasCycleCompute, this)),
        _deps(_conns.counterPtr(),
              boost::bind(&ContainerModule::_findDeps, this, _1))
    { }

    virtual ~ContainerModule();

    ConnectionDB* conns() {
        return &_conns;
    }
    const ConnectionDB* conns() const {
        return &_conns;
    }

    virtual void validityCheck() const;

    OutputPort* getDriver(const InputPort* ip) const {
        // Strip away const-ness for lookup. Just don't touch it
        auto f = _inputMap.find((InputPort*)ip);
        assert(f != _inputMap.end());
        OutputPort* internalIPDriver = f->second->dout();
        return internalIPDriver;
    }

    InputPort* getSink(const OutputPort* op) const {
        // Strip away const-ness for lookup. Just don't touch it
        auto f = _outputMap.find((OutputPort*)op);
        assert(f != _outputMap.end());
        InputPort* internalOPSink = f->second->din();
        return internalOPSink;
    }

    void connect(InputPort* sink, OutputPort* source) {
        connect(source, sink);
    }
    void connect(OutputPort* source, InputPort* sink) {
        if (source == NULL || sink == NULL)
            throw InvalidArgument("Neither source nor sink can be NULL!");

        Block* sourceB = source->owner();
        Block* sinkB   = sink->owner();

        if (sourceB->module() != NULL && sourceB->module() != this) {
            throw InvalidArgument("Source block is not contained by this module!");
        }

        if (sinkB->module() != NULL && sinkB->module() != this) {
            throw InvalidArgument("Sink block is not contained by this module!");
        }

        _conns.connect(source, sink);
    }

    /**
     * If our outputs are tied, unify them into one join'ed output and
     * add an extraction to each output
     */
    bool unifyOutput();

    virtual bool refine(ConnectionDB& conns) const;
    virtual bool refinable() const {
        return true;
    }

    virtual bool hasCycle() const {
        return this->_hasCycle();
    }

    virtual unsigned internalRefine(int depth = -1,
                                    Refinery::StopCondition* sc = NULL);

    virtual bool outputsSeparate() const;
    virtual DependenceRule deps(const OutputPort* op) const;
};

} // namespace llpm

#endif // __LLPM_MODULE_HPP__

max_stars_repo_name: llpm/llpm

max_issues_repo_name: llpm/llpm

max_forks_repo_name: llpm/llpm