text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_TOOLBOX_TRIGONOMETRIC_FUNCTIONS_SCALAR_REM_PIO2_MEDIUM_HPP_INCLUDED
#define NT2_TOOLBOX_TRIGONOMETRIC_FUNCTIONS_SCALAR_REM_PIO2_MEDIUM_HPP_INCLUDED
#include <nt2/toolbox/trigonometric/functions/rem_pio2_medium.hpp>
#include <nt2/toolbox/trigonometric/constants.hpp>
#include <nt2/include/functions/scalar/round.hpp>
#include <nt2/include/functions/scalar/fast_toint.hpp>
#include <nt2/sdk/meta/as_integer.hpp>
#include <boost/fusion/tuple.hpp>

namespace nt2 { namespace ext
{
  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::rem_pio2_medium_, tag::cpu_,
                             (A0),
                             (scalar_ < floating_<A0> > )
                             )
  {
    typedef boost::fusion::tuple<A0,A0,nt2::int32_t>           result_type;

    inline result_type operator()(A0 const& a0) const
    {
      result_type res;
      boost::fusion::at_c<2>(res) =
      nt2::rem_pio2_medium(a0,
                           boost::fusion::at_c<0>(res),
                           boost::fusion::at_c<1>(res)
                          );
      return res;
    }
  };

  /////////////////////////////////////////////////////////////////////////////
  // reference based Implementation when real
  /////////////////////////////////////////////////////////////////////////////
  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::rem_pio2_medium_, tag::cpu_,
                             (A0),
                             (scalar_ < floating_<A0> > )
                             (scalar_ < floating_<A0> > )
                             (scalar_ < floating_<A0> > )
                             )
  {
    typedef typename meta::as_integer<A0>::type result_type;
    inline result_type operator()(A0 const& t, A0 & xr, A0& xc) const
    {
      const A0 fn = nt2::round(t*Invpio_2<A0>());
      A0 r  = t-fn*Pio2_1<A0>();
      A0 w  = fn*Pio2_1t<A0>();
      A0 t2 = r;
      w  = fn*Pio2_2<A0>();
      r  = t2-w;
      w  = fn*Pio2_2t<A0>()-((t2-r)-w);
      t2 = r;
      w  = fn*Pio2_3<A0>();
      r  = t2-w;
      w  = fn*Pio2_3t<A0>()-((t2-r)-w);
      xr = r-w;
      xc = (r-xr)-w;
      return  fast_toint(fn)&3;
    }
  };
} }
#endif


text:
#include <iostream>

#include "compiler.hpp"
#include "logger_setup.hpp"

#include <boost/log/trivial.hpp>

using namespace std;

int main(int ac, char* av[]){
    boost::log::trivial::severity_level log_level = boost::log::trivial::info;
    logger_setup(log_level);

    //TODO: Does not produce the same results because op->retire never free any tiles.
    //That is because serialization of tile->input_of does not work correctly so setting op->retired = True does not change the op in input_of.
    //Fix this first before using this code.

    Compiler* compiler;
    {
        // create and open an archive for input
        std::ifstream ifs("../experiments/tmp/schedule1.dat");
        if (ifs.fail()){
            cout << "Input file could not be opened." << endl;
        }

        boost::archive::text_iarchive ia(ifs);
        // read class state from archive
        ia >> compiler;
        // archive and stream closed when destructors are called
    }

    cout << compiler->sram_round_trip << endl;
    cout << compiler->pp_latency_offset << endl;

    compiler->run_cycle_model();

    cout << "no_cycles: " << compiler->no_cycles << endl;

    return 0;
}

ext: cpp

max_stars_repo_name: yuezuegu/sosa-compiler

max_issues_repo_name: yuezuegu/sosa-compiler

max_forks_repo_name: yuezuegu/sosa-compiler


text:
#include "catch.hpp"

#include "libirc/atom.h"

#include "libirc/periodic_table.h"

#include <iostream>
#include <stdexcept>

#ifdef HAVE_ARMA
#include <armadillo>
using arma::vec3;
#elif HAVE_EIGEN3
#include <Eigen/Dense>
using vec3 = Eigen::Vector3d;
#else
#error
#endif

using namespace irc;

TEST_CASE("Test atom and periodic table lookup functions", "[atom]") {

  using namespace atom;

  SECTION("invalid atom") {
    CHECK_THROWS_AS(Atom<vec3>{AtomicNumber{0}}, std::logic_error);
  }

  SECTION("atom from atomic number") {
    for (std::size_t i{1}; i < periodic_table::pt_size; i++) {
      REQUIRE(periodic_table::valid_atomic_number(i));

      const auto a = Atom<vec3>{i};

      REQUIRE(symbol(a.atomic_number) == periodic_table::symbols[i]);
      REQUIRE(symbol(i) == periodic_table::symbols[i]);

      REQUIRE(mass(a.atomic_number) == Approx(periodic_table::masses[i]));
      REQUIRE(mass(i) == Approx(periodic_table::masses[i]));

      REQUIRE(covalent_radius(a.atomic_number) ==
              Approx(periodic_table::covalent_radii[i]));
      REQUIRE(covalent_radius(i) == Approx(periodic_table::covalent_radii[i]));

      REQUIRE(vdw_radius(a.atomic_number) ==
              Approx(periodic_table::vdw_radii[i]));
      REQUIRE(vdw_radius(i) == Approx(periodic_table::vdw_radii[i]));

      if (i == 1) {
        REQUIRE(is_H(a.atomic_number));
        REQUIRE(is_H(i));
      } else if (i == 7 or i == 8 or i == 9 or i == 15 or i == 16 or i == 17) {
        REQUIRE(is_NOFPSCl(a.atomic_number));
        REQUIRE(is_NOFPSCl(i));
      }
    }
  }

  SECTION("atom from atomic symbol") {
    for (std::size_t i{1}; i < periodic_table::pt_size; i++) {

      REQUIRE(periodic_table::valid_atomic_number(i));

      const auto a = Atom<vec3>{periodic_table::symbols[i]};

      CHECK(symbol(a.atomic_number) == periodic_table::symbols[i]);
      CHECK(symbol(AtomicNumber(periodic_table::symbols[i])) ==
            periodic_table::symbols[i]);

      CHECK(mass(a.atomic_number) == Approx(periodic_table::masses[i]));
      CHECK(mass(AtomicNumber(periodic_table::symbols[i])) ==
            Approx(periodic_table::masses[i]));

      CHECK(covalent_radius(a.atomic_number) ==
            Approx(periodic_table::covalent_radii[i]));
      CHECK(covalent_radius(AtomicNumber(periodic_table::symbols[i])) ==
            Approx(periodic_table::covalent_radii[i]));

      CHECK(vdw_radius(a.atomic_number) ==
            Approx(periodic_table::vdw_radii[i]));
      CHECK(vdw_radius(AtomicNumber(periodic_table::symbols[i])) ==
            Approx(periodic_table::vdw_radii[i]));

      // Atom in H-bond
      if (i == 1) {
        CHECK(is_H(a.atomic_number));
      } else if (i == 7 or i == 8 or i == 9 or i == 15 or i == 16 or i == 17) {
        CHECK(is_NOFPSCl(a.atomic_number));
      }
    }
  }
}

max_stars_repo_name: francesco-bosia/irc

max_issues_repo_name: francesco-bosia/irc

max_forks_repo_name: francesco-bosia/irc


text:
#ifndef PHASER_TYPES
#define PHASER_TYPES

#include <vector>

#include <boost/smart_ptr.hpp>
#include <scitbx/vec3.h>
#include <scitbx/mat3.h>
#include <scitbx/array_family/shared.h>
#include <scitbx/array_family/misc_functions.h>

namespace phaser { namespace af = scitbx::af; }
namespace phaser { namespace fn = scitbx::fn; }
typedef double floatType;

namespace phaser {

    typedef std::vector<std::vector<std::vector<std::vector<std::vector<std::vector<floatType> > > > > > float6D;
    typedef std::vector<std::vector<std::vector<std::vector<std::vector<floatType> > > > > float5D;
    typedef std::vector<std::vector<std::vector<std::vector<floatType> > > > float4D;
    typedef std::vector<std::vector<std::vector<floatType> > > float3D;
    typedef std::vector<std::vector<floatType> > float2D;
    typedef std::vector<floatType> float1D;

    typedef std::complex<floatType> cmplxType;
    typedef std::vector<std::vector<std::vector<std::vector<cmplxType> > > > cmplx4D;
    typedef std::vector<std::vector<std::vector<cmplxType> > > cmplx3D;
    typedef std::vector<std::vector<cmplxType> > cmplx2D;
    typedef std::vector<cmplxType> cmplx1D;

    typedef std::vector<std::vector<std::vector<std::vector<bool> > > > bool4D;
    typedef std::vector<std::vector<std::vector<bool> > > bool3D;
    typedef std::vector<std::vector<bool> > bool2D;
    typedef std::vector<bool> bool1D;

    typedef std::vector<std::vector<std::vector<std::vector<unsigned> > > > unsigned4D;
    typedef std::vector<std::vector<std::vector<unsigned> > > unsigned3D;
    typedef std::vector<std::vector<unsigned> > unsigned2D;
    typedef std::vector<unsigned> unsigned1D;

    typedef std::vector<std::vector<std::vector<std::vector<std::string> > > > string4D;
    typedef std::vector<std::vector<std::vector<std::string> > > string3D;
    typedef std::vector<std::vector<std::string> > string2D;
    typedef std::vector<std::string> string1D;

    typedef std::vector<std::vector<std::vector<std::vector<int> > > > int4D;
    typedef std::vector<std::vector<std::vector<int> > > int3D;
    typedef std::vector<std::vector<int> > int2D;
    typedef std::vector<int> int1D;

    typedef scitbx::vec3<floatType> dvect3;
    typedef scitbx::mat3<floatType> dmat33;
    typedef scitbx::vec3<int> ivect3;
    typedef scitbx::mat3<int> imat33;

    typedef double dFloatType;
    typedef std::vector<std::vector<std::vector<std::vector<dFloatType> > > > dFloat4D;
    typedef std::vector<std::vector<std::vector<dFloatType> > > dFloat3D;
    typedef std::vector<std::vector<dFloatType> > dFloat2D;
    typedef std::vector<dFloatType> dFloat1D;

    typedef std::complex<double> dCmplxType;
    typedef std::vector<std::vector<std::vector<std::vector<dCmplxType> > > > dCmplx4D;
    typedef std::vector<std::vector<std::vector<dCmplxType> > > dCmplx3D;
    typedef std::vector<std::vector<dCmplxType> > dCmplx2D;
    typedef std::vector<dCmplxType> dCmplx1D;

}

#endif

ext: hh

max_stars_repo_name: maciejwlodek/blend

max_issues_repo_name: maciejwlodek/blend

max_forks_repo_name: maciejwlodek/blend


text:
/*

Copyright (c) 2005-2020, University of Oxford.
All rights reserved.

University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.

This file is part of Chaste.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 * Neither the name of the University of Oxford nor the names of its
   contributors may be used to endorse or promote products derived from this
   software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef _BOUNDARYCONDITIONSCONTAINER_HPP_
#define _BOUNDARYCONDITIONSCONTAINER_HPP_

#include <map>
#include "ChasteSerialization.hpp"
#include <boost/serialization/split_member.hpp>
#include <boost/serialization/map.hpp>

#include "AbstractBoundaryConditionsContainer.hpp"
#include "AbstractBoundaryCondition.hpp"
#include "AbstractTetrahedralMesh.hpp"
#include "BoundaryElement.hpp"
#include "Node.hpp"
#include "LinearSystem.hpp"
#include "PetscException.hpp"
#include "ChastePoint.hpp"
#include "ConstBoundaryCondition.hpp"
#include "DistributedVectorFactory.hpp"

/**
 * Boundary Conditions Container.
 *
 * This class contains a list of nodes on the Dirichlet boundary and associated Dirichlet
 * boundary conditions, and a list of surface elements on the Neumann boundary and associated
 * Neumann boundary conditions.
 *
 * \todo #1321
 * Various operations are currently very inefficient - there is certainly scope for
 * optimisation here!
 */
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
class BoundaryConditionsContainer : public AbstractBoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>
{
public:

    /** Type of a read-only iterator over Neumann boundary conditions. */
    typedef typename std::map< const BoundaryElement<ELEMENT_DIM-1, SPACE_DIM>*, const AbstractBoundaryCondition<SPACE_DIM>* >::const_iterator
        NeumannMapIterator;

    /** Base class type. */
    typedef AbstractBoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM> BaseClassType;

private:

    std::map< const BoundaryElement<ELEMENT_DIM-1, SPACE_DIM> *, const AbstractBoundaryCondition<SPACE_DIM>* >*
        mpNeumannMap[PROBLEM_DIM]; /**< List (map) of Neumann boundary conditions. */

    /** Nodes to be identified when periodic boundary conditions are applied */
    std::map< const Node<SPACE_DIM> *, const Node<SPACE_DIM> * >*  mpPeriodicBcMap[PROBLEM_DIM];

    /**
     * Neumann boundary condition iterator.
     */
    NeumannMapIterator mLastNeumannCondition[PROBLEM_DIM];

    /**
     * Array storing whether there are any Neumann boundary conditions for each unknown.
     */
    bool mAnyNonZeroNeumannConditionsForUnknown[PROBLEM_DIM];

    /** A zero boundary condition, used for other unknowns in ApplyNeumannBoundaryCondition */
    ConstBoundaryCondition<SPACE_DIM>* mpZeroBoundaryCondition;

    /** Whether the contents of this container were originally loaded from an archive. */
    bool mLoadedFromArchive;

public:

    /**
     * Constructor calls base constuctor and allocates memory for the Neumann boundary
     * conditions lists.
     *
     * @param deleteConditions whether to delete BCs in destructor (defaults to true)
     */
    BoundaryConditionsContainer(bool deleteConditions=true);

    /**
     * Note that the destructor will delete memory for each boundary condition object, as
     * well as for the internal bookkeeping of this class.
     */
    ~BoundaryConditionsContainer();

    /**
     * Add a Dirichlet boundary condition specifying two parameters, a pointer to a node,
     * and a pointer to a boundary condition object associated with that node.
     *
     * The destructor for the BoundaryConditionsContainer will destroy the boundary
     * conditions objects.
     *
     * @param pBoundaryNode Pointer to a node on the boundary.
     * @param pBoundaryCondition Pointer to the Dirichlet boundary condition at that node.
     * @param indexOfUnknown defaults to 0
     * @param checkIfBoundaryNode defaults to true
     */
    void AddDirichletBoundaryCondition(const Node<SPACE_DIM>* pBoundaryNode,
                                       const AbstractBoundaryCondition<SPACE_DIM>* pBoundaryCondition,
                                       unsigned indexOfUnknown = 0,
                                       bool checkIfBoundaryNode = true);

    /**
     * Add a Neumann boundary condition specifying two parameters, a pointer to a
     * surface element, and a pointer to a boundary condition object associated with
     * that element.
     *
     * The destructor for the BoundaryConditionsContainer will destroy the boundary
     * conditions objects.
     *
     * Note that the value of a Neumann boundary condition should specify
     * D * grad(u).n, not just grad(u).n.
     *
     * Take care if using non-zero Neumann boundary conditions in 1d. If applied at
     * the left hand end you need to multiply the value by -1 to get the right answer.
     *
     * @param pBoundaryElement Pointer to an element on the boundary
     * @param pBoundaryCondition Pointer to the Neumann boundary condition on that element
     * @param indexOfUnknown defaults to 0
     */
    void AddNeumannBoundaryCondition(const BoundaryElement<ELEMENT_DIM-1, SPACE_DIM>* pBoundaryElement,
                                     const AbstractBoundaryCondition<SPACE_DIM>* pBoundaryCondition,
                                     unsigned indexOfUnknown = 0);

    /**
     *  Add a periodic boundary condition: provide two nodes to be identified when solving
     *  @param pNode1 node 1
     *  @param pNode2 node 2
     *
     *  This method identifies the nodes for all unknowns, so doesn't have to be called for each unknown.
     */
    void AddPeriodicBoundaryCondition(const Node<SPACE_DIM>* pNode1,
                                      const Node<SPACE_DIM>* pNode2);

    /**
     * This function defines zero Dirichlet boundary conditions on every boundary node
     * of the mesh.
     *
     * @param pMesh Pointer to a mesh object, from which we extract the boundary
     * @param indexOfUnknown defaults to 0
     */
    void DefineZeroDirichletOnMeshBoundary(AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>* pMesh,
                                           unsigned indexOfUnknown = 0);

    /**
     * This function defines constant Dirichlet boundary conditions on every boundary node
     * of the mesh.
     *
     * @param pMesh Pointer to a mesh object, from which we extract the boundary
     * @param value the value of the constant Dirichlet boundary condition
     * @param indexOfUnknown defaults to 0
     */
    void DefineConstantDirichletOnMeshBoundary(AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>* pMesh,
                                               double value,
                                               unsigned indexOfUnknown = 0);

    /**
     * This function defines zero Neumann boundary conditions on every boundary element
     * of the mesh.
     *
     * @param pMesh Pointer to a mesh object, from which we extract the boundary
     * @param indexOfUnknown defaults to 0
     */
    void DefineZeroNeumannOnMeshBoundary(AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>* pMesh,
                                         unsigned indexOfUnknown = 0);

    /**
     *  Alter the given linear system to satisfy Dirichlet boundary conditions.
     *
     *  If the number of unknowns is greater than one, it is assumed the solution vector is
     *  of the form (in the case of two unknowns u and v, and N nodes):
     *  solnvec = (U_1, V_1, U_2, V_2, ...., U_N, V_N)
     *
     *  @param rLinearSystem Linear system on which to apply boundary conditions
     *
     *  @param applyToMatrix This optional parameter can be set as false to
     *  ensure that the matrix of the linear system is not updated. To
     *  be used when the matrix does not change between time steps.
     *  @param applyToRhsVector Similarly, whether to apply the changes to the RHS vector (b in Ax=b).
     */
    void ApplyDirichletToLinearProblem(LinearSystem& rLinearSystem,
                                       bool applyToMatrix = true,
                                       bool applyToRhsVector = true);

    /**
     *  Alter the given linear system to satisfy periodic boundary conditions.
     *
     *  For one of the two nodes that have been identified, the row corresponding to the
     *  unknown which has periodic BCs, for one of the nodes, ie replaced with
     *  [0 0 0 ... -1 0 0 .. 0 1 0 .. 0]
     *  where the 1 is the diagonal entry and the -1 on the column corresponding to that
     *  unknown and the other node.
     *
     *  The entry in the RHS vector is zeroed.
     *
     *  @param rLinearSystem Linear system on which to apply boundary conditions
     *
     *  @param applyToMatrix This optional parameter can be set as false to
     *  ensure that the matrix of the linear system is not updated. To
     *  be used when the matrix does not change between time steps.
     *  @param applyToRhsVector Similarly, whether to apply the changes to the RHS vector (b in Ax=b).
     *
     */
    void ApplyPeriodicBcsToLinearProblem(LinearSystem& rLinearSystem,
                                         bool applyToMatrix = true,
                                         bool applyToRhsVector = true);

    /**
     * Alter the residual vector for a nonlinear system to satisfy
     * Dirichlet boundary conditions.
     *
     * If the number of unknowns is greater than one, it is assumed the solution vector is
     * of the form (in the case of two unknowns u and v, and N nodes):
     * solnvec = (U_1, V_1, U_2, V_2, ...., U_N, V_N)
     *
     * @param currentSolution
     * @param residual
     * @param rFactory  the factory to use to create DistributedVector objects
     */
    void ApplyDirichletToNonlinearResidual(const Vec currentSolution, Vec residual,
                                           DistributedVectorFactory& rFactory);

    /**
     * Alter the Jacobian matrix vector for a nonlinear system to satisfy
     * Dirichlet boundary conditions.
     *
     * If the number of unknowns is greater than one, it is assumed the solution vector is
     * of the form (in the case of two unknowns u and v, and N nodes):
     * solnvec = (U_1, V_1, U_2, V_2, ...., U_N, V_N)
     *
     * @param jacobian
     */
    void ApplyDirichletToNonlinearJacobian(Mat jacobian);

    /**
     * Check that we have boundary conditions defined everywhere on mesh boundary.
     *
     * We iterate over all surface elements, and check either that they have an
     * associated Neumann condition, or that each node in the element has an
     * associated Dirichlet condition.
     *
     * @param pMesh Pointer to the mesh to check for validity.
     * @return true iff all boundaries have boundary conditions defined.
     */
    bool Validate(AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>* pMesh);

    /**
     * @return value of Neumann boundary condition at a specified point in a given surface element
     *
     * It is up to the user to ensure that the point x is contained in the surface element.
     *
     * @param pSurfaceElement pointer to a boundary element
     * @param rX a point
     * @param indexOfUnknown defaults to 0
     */
    double GetNeumannBCValue(const BoundaryElement<ELEMENT_DIM-1,SPACE_DIM>* pSurfaceElement,
                             const ChastePoint<SPACE_DIM>& rX,
                             unsigned indexOfUnknown = 0);

    /**
     * @return true if there is a Neumann boundary condition defined on the given element.
     *
     * \todo #1321
     * This is a horrendously inefficient fix. Perhaps have flag in element object?
     *
     * @param pSurfaceElement pointer to a boundary element
     * @param indexOfUnknown defaults to 0
     */
    bool HasNeumannBoundaryCondition(const BoundaryElement<ELEMENT_DIM-1,SPACE_DIM>* pSurfaceElement,
                                     unsigned indexOfUnknown = 0);

    /**
     * @return whether there are any non-zero Neumann boundary conditions
     */
    bool AnyNonZeroNeumannConditions();

    /**
     * @return iterator pointing to the first Neumann boundary condition
     */
    NeumannMapIterator BeginNeumann();

    /**
     * @return iterator pointing to one past the last Neumann boundary condition
     */
    NeumannMapIterator EndNeumann();

    /**
     * Load a collection of boundary conditions from an archive.
     *
     * @note We assume this collection is empty prior to being called.  If it is not, any boundary
     * conditions already present may get replaced by conditions loaded from the archive, which may
     * lead to a memory leak.
     *
     * This method only loads data if #mLoadedFromArchive is false, to allow for multiple pointers
     * to the same container to be handled correctly.  It sets #mLoadedFromArchive when done.
     *
     * @param archive  the archive to load from
     * @param pMesh  the mesh to use to resolve Node and BoundaryElement indices
     */
    template <class Archive>
    void LoadFromArchive(Archive & archive, AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>* pMesh)
    {
        if (mLoadedFromArchive)
        {
            return;
        }

        MergeFromArchive(archive, pMesh);
    }

    /**
     * Load extra boundary conditions from an archive to add to this collection.
     *
     * Multiple pointers to the same container need to be handled by the caller - we assume there
     * will be conditions to load.  Sets #mLoadedFromArchive when done.
     *
     * @param archive  the archive to load from
     * @param pMesh  the mesh to use to resolve Node and BoundaryElement indices
     */
    template <class Archive>
    void MergeFromArchive(Archive & archive, AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>* pMesh);

private:

    /** Needed for serialization. */
    friend class boost::serialization::access;

    /**
     * Save this container and its contents.
     *
     * @param archive
     * @param version
     */
    template<class Archive>
    void save(Archive & archive, const unsigned int version) const;

    /**
     * Load this container, but not its content.
     *
     * Objects loading a boundary conditions container should call LoadFromArchive
     * on the new object immediately after loading it from the archive.
     *
     * Note that boundary conditions should be saved to the ProcessSpecificArchive,
     * since if a DistributedTetrahedralMesh is used each process will only know a
     * portion of the mesh, and hence a portion of the boundary conditions.
     *
     * Extra care needs to be taken when migrating to ensure that boundary conditions
     * are loaded appropriately.  See BidomainProblem::LoadExtraArchiveForBidomain
     * and AbstractCardiacProblem::LoadExtraArchive for examples.
     *
     * @param archive
     * @param version
     */
    template<class Archive>
    void load(Archive & archive, const unsigned int version)
    {
    }

    BOOST_SERIALIZATION_SPLIT_MEMBER()
};

template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
template<class Archive>
void BoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::save(
        Archive & archive, const unsigned int version) const
{
    typedef typename std::map<unsigned, const AbstractBoundaryCondition<SPACE_DIM> *> archive_map_type;

    // Save Dirichlet conditions
    for (unsigned index_of_unknown=0; index_of_unknown<PROBLEM_DIM; index_of_unknown++)
    {
        archive_map_type bc_map;
        typename BaseClassType::DirichletIteratorType it = this->mpDirichletMap[index_of_unknown]->begin();
        while (it != this->mpDirichletMap[index_of_unknown]->end() )
        {
            unsigned node_index = it->first->GetIndex();
            const AbstractBoundaryCondition<SPACE_DIM> * p_cond = it->second;
            bc_map[node_index] = p_cond;

            it++;
        }
        archive & bc_map;
    }

    // Save Neumann conditions
    for (unsigned index_of_unknown=0; index_of_unknown<PROBLEM_DIM; index_of_unknown++)
    {
        archive_map_type bc_map;
        for (NeumannMapIterator it = mpNeumannMap[index_of_unknown]->begin();
             it != mpNeumannMap[index_of_unknown]->end();
             ++it)
        {
            unsigned elem_index = it->first->GetIndex();
            const AbstractBoundaryCondition<SPACE_DIM>* p_cond = it->second;
            bc_map[elem_index] = p_cond;
        }
        archive & bc_map;
    }
}

template<unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
template<class Archive>
void BoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::MergeFromArchive(
        Archive & archive, AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>* pMesh)
{
    mLoadedFromArchive = true;

    typedef typename std::map<unsigned, AbstractBoundaryCondition<SPACE_DIM>*> archive_map_type;

    // Keep track of conditions that might need deleting
    std::set<const AbstractBoundaryCondition<SPACE_DIM>*> maybe_unused_bcs;
    std::set<const AbstractBoundaryCondition<SPACE_DIM>*> used_bcs;

    // Load Dirichlet conditions
    for (unsigned index_of_unknown=0; index_of_unknown<PROBLEM_DIM; index_of_unknown++)
    {
        archive_map_type bc_map;
        archive & bc_map;
        for (typename archive_map_type::iterator it = bc_map.begin();
             it != bc_map.end();
             ++it)
        {
            unsigned node_index = it->first;
            this->mHasDirichletBCs=true;  //We know that a Dirichlet is being added, even if not by this process
            Node<SPACE_DIM>* p_node;
            try
            {
                p_node = pMesh->GetNodeFromPrePermutationIndex(node_index);
            }
            catch (Exception&)
            {
                // It's a distributed mesh and we don't own this node - skip to the next BC
                maybe_unused_bcs.insert(it->second);
                continue;
            }
            AddDirichletBoundaryCondition(p_node, it->second, index_of_unknown, false);
            used_bcs.insert(it->second);
        }
    }
    this->mCheckedAndCommunicatedIfDirichletBcs=true; // Whether the Dirichlet BCC was empty or not, all processes know the status.

    // Load Neumann conditions
    for (unsigned index_of_unknown=0; index_of_unknown<PROBLEM_DIM; index_of_unknown++)
    {
        archive_map_type bc_map;
        archive & bc_map;
        for (typename archive_map_type::iterator it = bc_map.begin();
             it != bc_map.end();
             ++it)
        {
            unsigned boundary_element_index = it->first;
            BoundaryElement<ELEMENT_DIM-1, SPACE_DIM>* p_boundary_element;
            try
            {
                p_boundary_element = pMesh->GetBoundaryElement(boundary_element_index);
            }
            catch (Exception&)
            {
                // It's a distributed mesh and we don't own this element - skip to the next BC
                maybe_unused_bcs.insert(it->second);
                continue;
            }
            AddNeumannBoundaryCondition(p_boundary_element, it->second, index_of_unknown);
            used_bcs.insert(it->second);
        }
    }

    // Free any unused BCs
    for (typename std::set<const AbstractBoundaryCondition<SPACE_DIM>*>::iterator it=maybe_unused_bcs.begin();
         it != maybe_unused_bcs.end();
         ++it)
    {
        typename std::set<const AbstractBoundaryCondition<SPACE_DIM>*>::iterator used = used_bcs.find(*it);
        if (used == used_bcs.end())
        {
            delete (*it);
        }
    }
}

#endif //_BOUNDARYCONDITIONSCONTAINER_HPP_

ext: hpp

max_stars_repo_name: SoftMatterMechanics/ApicalStressFibers

max_issues_repo_name: SoftMatterMechanics/ApicalStressFibers

max_forks_repo_name: SoftMatterMechanics/ApicalStressFibers


text:
/*  Sirikata
 *  asyncCraqGet.hpp
 *
 *  Copyright (c) 2010, Behram Mistree
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are
 *  met:
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *  * Neither the name of Sirikata nor the names of its contributors may
 *    be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sirikata/core/util/Platform.hpp>
#include <sirikata/core/network/Asio.hpp>
#include <boost/asio.hpp>
#include <map>
#include <vector>
#include <queue>
#include "../asyncCraqUtil.hpp"
#include "../asyncCraqScheduler.hpp"

#include <sirikata/space/SpaceContext.hpp>
#include <sirikata/core/network/IOStrandImpl.hpp>
#include <sirikata/space/OSegLookupTraceToken.hpp>

#ifndef __ASYNC_CRAQ_GET_CLASS_H__
#define __ASYNC_CRAQ_GET_CLASS_H__

namespace Sirikata
{

class AsyncConnectionGet;
class CraqObjectSegmentation;

class AsyncCraqGet : public AsyncCraqScheduler
  {
  private:

    struct QueueValue
    {
      CraqDataSetGet* cdQuery;
      OSegLookupTraceToken* traceToken;
    };

  public:
    AsyncCraqGet(SpaceContext* con, Network::IOStrand* strand_this_runs_on, Network::IOStrand* strand_to_post_results_to, CraqObjectSegmentation* parent_oseg_called);
    ~AsyncCraqGet();

    int runReQuery();
    void initialize(std::vector<CraqInitializeArgs>);

    virtual void erroredGetValue(CraqOperationResult* cor);
    virtual void erroredSetValue(CraqOperationResult* cor);

    void get(const CraqDataSetGet& cdGet, OSegLookupTraceToken* traceToken);

    int queueSize();
    int numStillProcessing();
    int getRespCount();
    virtual void stop();

  private:

    void straightPoll();
    std::vector<CraqInitializeArgs> mIpAddPort;
    std::vector<AsyncConnectionGet*> mConnections;
    std::vector<Network::IOStrand*> mConnectionsStrands;

    std::queue<QueueValue*>mQueue;

    void reInitializeNode(int s);
    void readyStateChanged(int s);
    bool checkConnections(int s);
    void pushQueue(QueueValue*qv);
    std::vector<int> mReadyConnections;

    SpaceContext* ctx;
    Network::IOStrand* mStrand;        //strand that the asyncCraqGet is running on.
    Network::IOStrand* mResultsStrand; //strand that we post our results to.
    CraqObjectSegmentation* mOSeg;

  };

}//end namespace

#endif

max_stars_repo_name: sirikata/sirikata

max_issues_repo_name: pathorn/sirikata

max_forks_repo_name: pathorn/sirikata


text:
#include <string>
#include <boost/filesystem.hpp>
#include "config.hpp"

NAMESPACE_BEGIN(monoco)

namespace fs = boost::filesystem;

class aof_writer
{
public:
	aof_writer();
}
NAMESPACE_END(monoco)

max_stars_repo_name: Damenly/monoco

max_issues_repo_name: Damenly/Monoco

max_forks_repo_name: Damenly/Monoco


text:
#pragma once

#include "generator/regions/country_specifier.hpp"
#include "generator/regions/level_region.hpp"
#include "generator/regions/node.hpp"
#include "generator/regions/region.hpp"

#include <functional>
#include <map>
#include <memory>
#include <string>
#include <vector>

#include <boost/optional.hpp>

namespace generator
{
namespace regions
{
// This class is needed to build a hierarchy of regions. We can have several nodes for a region
// with the same name, represented by a multi-polygon (several polygons).
class RegionsBuilder
{
public:
  using Regions = std::vector<Region>;
  using StringsList = std::vector<std::string>;
  using CountryFn = std::function<void(std::string const &, Node::PtrList const &)>;

  explicit RegionsBuilder(Regions && regions, PlacePointsMap && placePointsMap,
                          size_t threadsCount = 1);

  Regions const & GetCountriesOuters() const;
  StringsList GetCountryInternationalNames() const;
  void ForEachCountry(CountryFn fn);

  static void InsertIntoSubtree(Node::Ptr & subtree, LevelRegion && region,
                                CountrySpecifier const & countrySpecifier);
  // Return: 0 - no relation, 1 - |l| contains |r|, -1 - |r| contains |l|.
  static int CompareAffiliation(LevelRegion const & l, LevelRegion const & r,
                                CountrySpecifier const & countrySpecifier);
  static bool IsAreaLessRely(Region const & l, Region const & r);

private:
  static constexpr double kAreaRelativeErrorPercent = 0.1;

  void MoveLabelPlacePoints(PlacePointsMap & placePointsMap, Regions & regions);
  Regions FormRegionsInAreaOrder(Regions && regions);
  Regions ExtractCountriesOuters(Regions & regions);
  Node::PtrList BuildCountry(std::string const & countryName) const;
  boost::optional<std::string> FindCountryIsoCode(Regions const & outers) const;
  Node::PtrList BuildCountryRegionTrees(Regions const & outers,
                                        boost::optional<std::string> const & isoCode,
                                        CountrySpecifier const & countrySpecifier) const;
  Node::Ptr BuildCountryRegionTree(Region const & outer,
                                   boost::optional<std::string> const & isoCode,
                                   CountrySpecifier const & countrySpecifier) const;
  std::vector<Node::Ptr> MakeCountryNodesInAreaOrder(
      Region const & countryOuter, Regions const & regionsInAreaOrder,
      boost::optional<std::string> const & isoCode,
      CountrySpecifier const & countrySpecifier) const;
  Node::Ptr ChooseParent(std::vector<Node::Ptr> const & nodesInAreaOrder,
                         std::vector<Node::Ptr>::const_reverse_iterator forItem,
                         CountrySpecifier const & countrySpecifier) const;
  std::vector<Node::Ptr>::const_reverse_iterator FindAreaLowerBoundRely(
      std::vector<Node::Ptr> const & nodesInAreaOrder,
      std::vector<Node::Ptr>::const_reverse_iterator forItem) const;
  static void InsertIntoSubtree(Node::Ptr & subtree, Node::Ptr && newNode,
                                CountrySpecifier const & countrySpecifier);

  Regions m_countriesOuters;
  Regions m_regionsInAreaOrder;
  PlacePointsMap m_placePointsMap;
  size_t m_threadsCount;
};
}  // namespace regions
}  // namespace generator

max_stars_repo_name: LaGrunge/omim

max_issues_repo_name: LaGrunge/omim

max_forks_repo_name: LaGrunge/omim


text:
/*
 * @CopyRight:
 * FISCO-BCOS 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 3 of the License, or
 * (at your option) any later version.
 *
 * FISCO-BCOS 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 FISCO-BCOS.  If not, see <http://www.gnu.org/licenses/>
 * (c) 2016-2018 fisco-dev contributors.
 */
/** @file BinLogHandler.h
 *  @author chaychen
 *  @date 20190802
 */

#include "BinLogHandler.h"

#include <json/json.h>
#include <libdevcore/Exceptions.h>
#include <libdevcore/FixedHash.h>
#include <libethcore/Exceptions.h>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/crc.hpp>
#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

using namespace dev;
using namespace dev::storage;

BinLogHandler::BinLogHandler(const std::string& path)
{
    setBinLogStoragePath(path);
}

BinLogHandler::~BinLogHandler()
{
    close(m_fd);
}

void BinLogHandler::setBinLogStoragePath(const std::string& path)
{
    // called during chain initialization
    m_path = path + "/";
    // If the directory exists, the function does nothing
    fs::create_directories(m_path);
    BINLOG_HANDLER_LOG(INFO) << LOG_DESC("set binLog storage path") << LOG_KV("path", m_path);

    checkBinLogSize();
}

bool BinLogHandler::writeBlocktoBinLog(int64_t num, const std::vector<TableData::Ptr>& datas)
{
    if (boost::filesystem::space(m_path).available < m_binarylogSize)
    {
        BINLOG_HANDLER_LOG(ERROR) << LOG_DESC("Disk space is insufficient.");
        raise(SIGTERM);
        BOOST_THROW_EXCEPTION(dev::eth::NotEnoughAvailableSpace());
    }

    bytes buffer;
    auto start = utcTimeUs();
    encodeBlock(num, datas, buffer);
    auto end1 = utcTimeUs();
    if (m_writtenBytesLength == 0 || m_writtenBytesLength + buffer.size() > m_binarylogSize)
    {  // check if need to create a new file, in the case of first write or capacity limitation
        if (m_writtenBytesLength > 0)
        {  // close the file which has been opened
            close(m_fd);
        }

        BINLOG_HANDLER_LOG(INFO) << LOG_DESC("try to open new binary file!")
                                 << LOG_KV("file written length", m_writtenBytesLength)
                                 << LOG_KV("buffer size", buffer.size());
        // open binary file and write version
        if (!initNewBinaryFile(num))
        {
            return false;
        }
    }
    // write block buffer, include block length, block buffer and CRC32
    if (write(m_fd, (char*)&buffer[0], buffer.size()) == -1)
    {
        BINLOG_HANDLER_LOG(ERROR) << LOG_DESC("write binary file fail!");
        return false;
    }
    m_writtenBytesLength += buffer.size();
    auto end2 = utcTimeUs();
    BINLOG_HANDLER_LOG(INFO) << LOG_DESC("write block to binlog end")
                             << LOG_KV("encode + CRC32 cost", end1 - start)
                             << LOG_KV("write cost", end2 - end1)
                             << LOG_KV("binlog written size", m_writtenBytesLength);

    return true;
}

int64_t BinLogHandler::getLastBlockNum()
{
    fs::path path(m_path);
    if (!fs::is_directory(path))
    {
        return -1;
    }

    typedef std::vector<fs::path> vec;
    vec v;
    // get binlog list
    std::copy(fs::directory_iterator(path), fs::directory_iterator(), back_inserter(v));
    if (v.size() == 0)
    {
        return -1;
    }
    // descending sort
    std::sort(v.begin(), v.end(), [](fs::path const& a, fs::path const& b) {
        return std::stoll(a.filename().string()) >= std::stoll(b.filename().string());
    });

    // read First binlog
    uint32_t blockLen = 0;
    uint64_t blockNum = 0;
    vec::const_iterator it = v.begin();
    try
    {
        if (getFirstBlockNumInBinLog(it->string()) != std::stoll(it->filename().string()))
        {
            BOOST_THROW_EXCEPTION(
                dev::StorageError() << errinfo_comment(
                    "the first block num in binlog is not equal to file name! file name:" +
                    it->filename().string()));
        }
    }
    catch (std::exception& e)
    {
        BOOST_THROW_EXCEPTION(
            dev::StorageError() << errinfo_comment(boost::diagnostic_information(e)));
    }

    BinLogContext binlog(it->string());
    if (!binlog.file.is_open() || !getBinLogContext(binlog))
    {
        return -1;
    }

    while (binlog.offset < binlog.length)
    {
        if (!readFile(binlog.file, &blockLen, sizeof(uint32_t)))
        {
            BINLOG_HANDLER_LOG(ERROR) << LOG_DESC("read binLog error!");
            return -1;
        }
        blockLen = ntohl(blockLen);
        if (binlog.offset + sizeof(uint32_t) + blockLen > binlog.length)
        {
            break;
        }
        if (!readFile(binlog.file, &blockNum, sizeof(uint64_t)))
        {
            BINLOG_HANDLER_LOG(ERROR) << LOG_DESC("read binLog error!");
            break;
        }
        blockNum = NTOHLL(blockNum);
        BINLOG_HANDLER_LOG(DEBUG) << LOG_DESC("get last block num") << LOG_KV("num", blockNum)
                                  << LOG_KV("offset", binlog.offset) << LOG_KV("length", blockLen);
        binlog.offset += (sizeof(uint32_t) + blockLen);
        binlog.file.seekg(binlog.offset, std::ios::beg);
    }

    BINLOG_HANDLER_LOG(INFO) << LOG_DESC("get last block num") << LOG_KV("num", blockNum);
    return blockNum;
}

std::shared_ptr<BlockDataMap> BinLogHandler::getMissingBlocksFromBinLog(
    int64_t startNum, int64_t endNum)
{
    BINLOG_HANDLER_LOG(INFO) << LOG_DESC("get missing blocks")
                             << LOG_KV("start block num", startNum)
                             << LOG_KV("start block num", endNum);
    std::shared_ptr<BlockDataMap> binLogData = std::make_shared<BlockDataMap>();
    if (startNum >= endNum)
    {
        return binLogData;
    }
    fs::path path(m_path);
    if (fs::is_directory(path))
    {
        try
        {
            typedef std::vector<fs::path> vec;
            vec v;
            // descending sort, read from first
            std::copy(fs::directory_iterator(path), fs::directory_iterator(), back_inserter(v));
            if (v.size() > 0)
            {
                std::sort(v.begin(), v.end(), [](fs::path const& a, fs::path const& b) {
                    return std::stoll(a.filename().string()) >= std::stoll(b.filename().string());
                });
                for (vec::const_iterator it(v.begin()), it_end(v.end()); it != it_end; ++it)
                {
                    BINLOG_HANDLER_LOG(INFO)
                        << LOG_DESC("binlog log path") << LOG_KV("path", it->string());
                    int64_t num = getFirstBlockNumInBinLog(it->string());
                    if (num != std::stoll(it->filename().string()))
                    {
                        BOOST_THROW_EXCEPTION(dev::StorageError() << errinfo_comment(
                                                  "the first block num in binlog is not equal to "
                                                  "file name! file name:" +
                                                  it->filename().string()));
                    }
                    if (endNum < num)
                    {
                        continue;
                    }
                    readBinLog(it->string(), startNum, endNum, *binLogData);
                    if (startNum >= std::stoll(it->filename().string()))
                    {
                        break;
                    }
                }
            }
        }
        catch (std::exception& e)
        {
            BOOST_THROW_EXCEPTION(
                dev::StorageError() << errinfo_comment(boost::diagnostic_information(e)));
        }
    }

    return binLogData;
}

bool BinLogHandler::initNewBinaryFile(int64_t num)
{
    std::string filePath = m_path + std::to_string(num) + ".binlog";
    m_fd = open(filePath.c_str(), O_CREAT | O_WRONLY, 0644);
    if (m_fd == -1)
    {
        BINLOG_HANDLER_LOG(ERROR) << LOG_DESC("open binary file fail!");
        return false;
    }
    BINLOG_HANDLER_LOG(INFO) << LOG_DESC("open binary file success!")
                             << LOG_KV("file path", filePath) << LOG_KV("fd", m_fd);

    // write version
    uint32_t version = htonl(BINLOG_VERSION);
    if (write(m_fd, (char*)&version, sizeof(uint32_t)) == -1)
    {
        BINLOG_HANDLER_LOG(ERROR) << LOG_DESC("write binary file fail!");
        return false;
    }
    m_writtenBytesLength = sizeof(uint32_t);

    return true;
}

void BinLogHandler::writeUINT32(bytes& buffer, uint32_t ui)
{
    uint32_t ui_tmp = htonl(ui);
    buffer.insert(buffer.end(), (byte*)&ui_tmp, (byte*)&ui_tmp + 4);
}

void BinLogHandler::writeUINT64(bytes& buffer, uint64_t ui)
{
    uint64_t ui_tmp = HTONLL(ui);
    buffer.insert(buffer.end(), (byte*)&ui_tmp, (byte*)&ui_tmp + 8);
}

void BinLogHandler::writeString(bytes& buffer, const std::string& str)
{
    writeUINT32(buffer, str.length());
    buffer.insert(buffer.end(), str.begin(), str.end());
}

uint32_t BinLogHandler::readUINT32(const bytes& buffer, uint32_t& offset)
{
    uint32_t ui = ntohl(*((uint32_t*)&buffer[offset]));
    offset += 4;
    return ui;
}

uint64_t BinLogHandler::readUINT64(const bytes& buffer, uint32_t& offset)
{
    uint64_t ui = NTOHLL(*((uint64_t*)&buffer[offset]));
    offset += 8;
    return ui;
}

void BinLogHandler::readString(const bytes& buffer, std::string& str, uint32_t& offset)
{
    uint32_t strLen = readUINT32(buffer, offset);
    std::string s((char*)&buffer[offset], strLen);
    str = s;
    offset += strLen;
}

void BinLogHandler::encodeEntries(
    const std::vector<std::string>& vecField, Entries::Ptr entries, bytes& buffer)
{
    writeUINT32(buffer, entries->size());
    for (size_t idx = 0; idx < entries->size(); idx++)
    {
        auto entry = entries->get(idx);
        writeUINT64(buffer, entry->getID());
        uint8_t status = entry->getStatus();
        /*BINLOG_HANDLER_LOG(TRACE) << LOG_DESC("entry info") << LOG_KV("idx", idx)
                                  << LOG_KV("id", entry->getID())
                                  << LOG_KV("status", (uint32_t)status);*/
        buffer.insert(buffer.end(), (byte*)&status, (byte*)&status + 1);
        int flagSize = (vecField.size() - 3) / 8 + 1;  // exclude STATUS,NUM_FIELD,ID_FIELD
        uint8_t* usedFlag = new uint8_t[flagSize];     // bit-based used to represent a field
        memset(usedFlag, 0, sizeof(uint8_t) * flagSize);
        int KeyIdx = 0;  // field index
        for (const auto& key : vecField)
        {
            if (key == STATUS || key == NUM_FIELD || key == ID_FIELD)
            {
                continue;
            }
            if (entry->find(key) != entry->end())
            {
                // "KeyIdx / 8" get the index in array, "7 - KeyIdx % 8" get the bit index in byte
                // "A += std::pow(2, B)" set the Bth digit of A to 1, count backwards
                usedFlag[KeyIdx / 8] |= (1 << (7 - KeyIdx % 8));
            }
            KeyIdx++;
        }
        buffer.insert(buffer.end(), (byte*)usedFlag, (byte*)usedFlag + flagSize);
        delete[] usedFlag;

        for (const auto& key : vecField)
        {
            if (key == STATUS || key == NUM_FIELD || key == ID_FIELD)
            {
                continue;
            }
            auto fieldIt = entry->find(key);
            if (fieldIt != entry->end())
            {
                writeString(buffer, fieldIt->second);
                // BINLOG_HANDLER_LOG(TRACE) << LOG_KV("k", key) << LOG_KV("v", fieldIt->second);
            }
        }
    }
}

void BinLogHandler::encodeTable(TableData::Ptr table, bytes& buffer)
{
    // table info: name and fields
    TableInfo::Ptr info = table->info;
    uint8_t tableNameLen = info->name.length();
    buffer.insert(buffer.end(), (byte*)&tableNameLen, (byte*)&tableNameLen + 1);
    buffer.insert(buffer.end(), info->name.begin(), info->name.end());
    std::vector<std::string> vecField;  // record a list of column names used in encodeEntries
    std::stringstream ss;               // used to output column names
    ss << info->key;
    vecField.push_back(info->key);
    for (size_t j = 0; j < info->fields.size(); j++)
    {
        if (info->fields[j] != info->key)
        {
            ss << "," << info->fields[j];
            vecField.push_back(info->fields[j]);
        }
    }
    writeString(buffer, ss.str());
    // BINLOG_HANDLER_LOG(TRACE) << "table name:" << info->name << ",fields(include key):" <<
    // ss.str(); table data : dirty entries and new entries
    encodeEntries(vecField, table->dirtyEntries, buffer);
    encodeEntries(vecField, table->newEntries, buffer);
}

void BinLogHandler::encodeBlock(
    int64_t num, const std::vector<TableData::Ptr>& datas, bytes& buffer)
{
    auto start = utcTimeUs();
    // block heigth
    writeUINT64(buffer, num);

    // block data
    writeUINT32(buffer, datas.size());
    for (size_t i = 0; i < datas.size(); i++)
    {
        encodeTable(datas[i], buffer);
    }
    auto end1 = utcTimeUs();
    // CRC32
    boost::crc_32_type result;
    result.process_block((char*)&buffer[0], (char*)&buffer[0] + buffer.size());
    uint32_t crc32 = result.checksum();
    writeUINT32(buffer, crc32);

    // insert length
    uint32_t length = htonl(buffer.size());
    buffer.insert(buffer.begin(), (byte*)&length, (byte*)&length + 4);
    auto end2 = utcTimeUs();
    BINLOG_HANDLER_LOG(INFO) << LOG_DESC("encode block end") << LOG_KV("num", num)
                             << LOG_KV("block binary data length", buffer.size())
                             << LOG_KV("CRC32", crc32) << LOG_KV("encode cost", end1 - start)
                             << LOG_KV("CRC32 cost", end2 - end1);
}

uint32_t BinLogHandler::decodeEntries(const bytes& buffer, uint32_t& offset,
    const std::vector<std::string>& vecField, Entries::Ptr entries, bool force)
{
    uint32_t preOffset = offset;
    uint32_t entryCount = readUINT32(buffer, offset);
    for (uint32_t idx = 0; idx < entryCount; idx++)
    {
        Entry::Ptr entry = std::make_shared<Entry>();
        uint64_t id = readUINT64(buffer, offset);
        entry->setID(id);
        uint8_t status = *((uint8_t*)&buffer[offset]);
        offset++;
        entry->setStatus(status);
        /*BINLOG_HANDLER_LOG(TRACE) << LOG_DESC("entry info") << LOG_KV("idx in entries", idx)
                                  << LOG_KV("_id_", entry->getID())
                                  << LOG_KV("_status_", (uint32_t)entry->getStatus());*/
        int flagSize = (vecField.size() - 3) / 8 + 1;  // exclude STATUS,NUM_FIELD,ID_FIELD
        uint8_t* usedFlag = new uint8_t[flagSize];     // bit-based used to represent a field
        int fieldIdx = 0;                              // field index
        for (int i = 0; i < flagSize; i++)
        {
            usedFlag[i] = *((uint8_t*)&buffer[offset]);
            /* BINLOG_HANDLER_LOG(TRACE) << LOG_DESC("usedFlag") << LOG_KV("idx", i)
                                      << LOG_KV("value", (uint32_t)usedFlag[i]); */
            offset++;
        }
        for (const auto& key : vecField)
        {
            if (key == STATUS || key == NUM_FIELD || key == ID_FIELD)
            {
                continue;
            }
            // "fieldIdx / 8" get the index in array, "7 - fieldIdx % 8" get the bit index in byte
            // "A >> B & 1" check if the Bth digit of A is 1, count backwards
            if ((usedFlag[fieldIdx / 8] >> (7 - fieldIdx % 8)) & 1)
            {
                std::string value;
                readString(buffer, value, offset);
                entry->setField(key, value);
                // BINLOG_HANDLER_LOG(TRACE) << LOG_KV("k", key) << LOG_KV("v", value);
            }
            fieldIdx++;
        }
        if (force)
        {
            entry->setForce(true);
        }
        entries->addEntry(entry);
        delete[] usedFlag;
    }
    return offset - preOffset;
}

uint32_t BinLogHandler::decodeTable(const bytes& buffer, uint32_t& offset, TableData::Ptr data)
{
    uint32_t preOffset = offset;
    // table name
    uint8_t tableNameLen = *((uint8_t*)&buffer[offset]);
    offset++;
    std::string s((char*)&buffer[offset], tableNameLen);
    data->info->name = s;
    offset += tableNameLen;
    // table key and fields
    std::string fields;
    readString(buffer, fields, offset);
    std::vector<std::string> vecField;
    boost::split(vecField, fields, boost::is_any_of(","), boost::token_compress_on);
    data->info->key = vecField[0];
    data->info->fields.insert(
        data->info->fields.end(), vecField.begin() + 1, vecField.begin() + vecField.size());
    return offset - preOffset;
}

DecodeBlockResult BinLogHandler::decodeBlock(const bytes& buffer, int64_t startNum, int64_t endNum,
    int64_t& binLogNum, std::vector<TableData::Ptr>& datas)
{
    uint32_t offset = 0;
    binLogNum = readUINT64(buffer, offset);
    if (binLogNum <= startNum)
    {
        BINLOG_HANDLER_LOG(DEBUG) << LOG_DESC("decode block, less than specified range!")
                                  << LOG_KV("num", binLogNum);
        return DecodeBlockResult::LessThanSpecifiedRange;
    }
    if (binLogNum > endNum)
    {
        BINLOG_HANDLER_LOG(DEBUG) << LOG_DESC("decode block, greater than specified range!")
                                  << LOG_KV("num", binLogNum);
        return DecodeBlockResult::GreaterThanSpecifiedRange;
    }
    uint32_t dataSize = readUINT32(buffer, offset);
    for (uint32_t i = 0; i < dataSize; i++)
    {
        TableData::Ptr data = std::make_shared<TableData>();
        decodeTable(buffer, offset, data);

        // entries
        std::vector<std::string> vecField;
        vecField.push_back(data->info->key);
        for (const auto& field : data->info->fields)
        {
            vecField.push_back(field);
        }
        bool force =
            (data->info->name == SYS_BLOCK_2_NONCES || data->info->name == SYS_HASH_2_BLOCK);
        decodeEntries(buffer, offset, vecField, data->dirtyEntries, force);
        decodeEntries(buffer, offset, vecField, data->newEntries, force);
        datas.push_back(data);
    }

    if (buffer.size() == offset + 4)
    {  // The remaining 4 bytes is CRC32
        return DecodeBlockResult::Success;
    }
    else
    {
        BINLOG_HANDLER_LOG(ERROR) << LOG_DESC("decode block, block data size error!");
        return DecodeBlockResult::BlockDataLengthError;
    }
}

bool BinLogHandler::getBinLogContext(BinLogContext& binlog)
{
    // get length
    binlog.file.seekg(0, std::ios_base::end);
    binlog.length = (uint32_t)binlog.file.tellg();
    if (binlog.length < sizeof(BINLOG_VERSION))
    {
        BINLOG_HANDLER_LOG(ERROR) << LOG_DESC("read binLog error!")
                                  << LOG_KV("length", binlog.length);
        return false;
    }
    binlog.file.seekg(0);
    // get version
    uint32_t size =
        binlog.file.read(reinterpret_cast<char*>(&binlog.version), sizeof(uint32_t)).gcount();
    if (size != sizeof(uint32_t))
    {
        BINLOG_HANDLER_LOG(ERROR) << LOG_DESC("read binLog error!");
        return false;
    }
    binlog.version = ntohl(binlog.version);
    binlog.offset += sizeof(uint32_t);
    return true;
}

bool BinLogHandler::getBlockData(
    BinLogContext& binlog, int64_t startNum, int64_t endNum, BlockDataMap& blocksData)
{
    while (binlog.offset < binlog.length)
    {
        // get block data length
        uint32_t blockLen = 0;
        uint32_t size =
            binlog.file.read(reinterpret_cast<char*>(&blockLen), sizeof(uint32_t)).gcount();
        if (size != sizeof(uint32_t))
        {
            BINLOG_HANDLER_LOG(ERROR) << LOG_DESC("read binLog error!");
            return false;
        }
        blockLen = ntohl(blockLen);
        BINLOG_HANDLER_LOG(DEBUG) << LOG_DESC("decode block")
                                  << LOG_KV("block index", binlog.offset)
                                  << LOG_KV("block data length", blockLen);
        binlog.offset += sizeof(uint32_t);
        if (binlog.offset + blockLen > binlog.length)
        {
            BINLOG_HANDLER_LOG(ERROR) << LOG_DESC("readBinLog, block data length error!");
            return false;
        }

        // get block buffer, include CRC32
        bytes buffer;
        buffer.resize(blockLen);
        size = binlog.file.read(reinterpret_cast<char*>(buffer.data()), buffer.size()).gcount();
        if (size != buffer.size())
        {
            BINLOG_HANDLER_LOG(ERROR) << LOG_DESC("readBinLog, read error!");
            return false;
        }
        binlog.offset += blockLen;
        int64_t num;
        std::vector<TableData::Ptr> datas;
        DecodeBlockResult decodeRet = decodeBlock(buffer, startNum, endNum, num, datas);
        if (DecodeBlockResult::Success == decodeRet)
        {
            blocksData[num] = datas;
        }
        else if (DecodeBlockResult::GreaterThanSpecifiedRange == decodeRet)
        {
            break;
        }
        else if (DecodeBlockResult::BlockDataLengthError == decodeRet)
        {
            return false;
        }
    }
    return true;
}

bool BinLogHandler::readBinLog(
    const std::string& filePath, int64_t startNum, int64_t endNum, BlockDataMap& blocksData)
{
    BinLogContext binlog(filePath);
    if (!binlog.file.is_open() || !getBinLogContext(binlog))
    {
        return false;
    }
    BINLOG_HANDLER_LOG(INFO) << LOG_DESC("readBinLog start") << LOG_KV("file length", binlog.length)
                             << LOG_KV("version", binlog.version)
                             << LOG_KV("offset", binlog.offset);
    bool ret = false;
    if (binlog.version == BINLOG_VERSION)
    {
        ret = getBlockData(binlog, startNum, endNum, blocksData);
    }
    return ret;
}

int64_t BinLogHandler::getFirstBlockNumInBinLog(const std::string& filePath)
{
    BinLogContext binlog(filePath);
    if (!binlog.file.is_open() || !getBinLogContext(binlog))
    {
        return -1;
    }
    uint32_t blockLen = 0;
    uint64_t blockNum = 0;
    if (binlog.file.read(reinterpret_cast<char*>(&blockLen), sizeof(uint32_t)).gcount() !=
            sizeof(uint32_t) ||
        binlog.file.read(reinterpret_cast<char*>(&blockNum), sizeof(uint64_t)).gcount() !=
            sizeof(uint64_t))
    {
        BINLOG_HANDLER_LOG(ERROR) << LOG_DESC("read binLog error!");
        return -1;
    }
    blockNum = NTOHLL(blockNum);
    return blockNum;
}

bool BinLogHandler::readFile(std::ifstream& file, void* buffer, uint32_t size)
{
    return (file.read(reinterpret_cast<char*>(buffer), size).gcount() == size);
}

void BinLogHandler::checkBinLogSize()
{
    // removes files of unusual length that have not been written to the block data since they were
    // created
    fs::path p(m_path);
    std::vector<fs::path> vec;
    fs::directory_iterator end;
    for (fs::directory_iterator it(p); it != end; it++)
    {
        if (fs::file_size(*it) <= sizeof(BINLOG_VERSION))
        {
            fs::path ep(fs::current_path().string() + "/" + it->path().string());
            BINLOG_HANDLER_LOG(INFO)
                << LOG_DESC("remove unusual binlogs") << LOG_KV("path", ep.string());
            vec.push_back(ep);
        }
    }
    for (auto v : vec)
    {
        fs::remove(v);
    }
}

max_stars_repo_name: imtypist/FISCO-BCOS

max_issues_repo_name: imtypist/FISCO-BCOS

max_forks_repo_name: imtypist/FISCO-BCOS


text:
#define BOOST_TEST_MODULE SolutionTest

#include "solution.hpp"

#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(SolutionSuite)

BOOST_AUTO_TEST_CASE(PlainTest1)
{
    vector<vector<int>> matrix{
        {1,2,3},
        {4,5,6},
        {7,8,9}
    };
    Solution().rotate(matrix);

    vector<vector<int>> expected{
        {7,4,1},
        {8,5,2},
        {9,6,3}
    };
    BOOST_CHECK_EQUAL(matrix.size(), expected.size());
    for (int i = 0; i < matrix.size(); i++)
        BOOST_CHECK_EQUAL_COLLECTIONS(matrix[i].begin(), matrix[i].end(), expected[i].begin(), expected[i].end());
}

BOOST_AUTO_TEST_CASE(PlainTest2)
{
    vector<vector<int>> matrix{
        { 5, 1, 9,11},
        { 2, 4, 8,10},
        {13, 3, 6, 7},
        {15,14,12,16}
    };
    Solution().rotate(matrix);

    vector<vector<int>> expected{
        {15,13, 2, 5},
        {14, 3, 4, 1},
        {12, 6, 8, 9},
        {16, 7,10,11}
    };
    BOOST_CHECK_EQUAL(matrix.size(), expected.size());
    for (int i = 0; i < matrix.size(); i++)
        BOOST_CHECK_EQUAL_COLLECTIONS(matrix[i].begin(), matrix[i].end(), expected[i].begin(), expected[i].end());
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: johnhany/leetcode

max_issues_repo_name: johnhany/leetcode

max_forks_repo_name: johnhany/leetcode


text:
/*
  * Generated by cppsrc.sh
  * On
  * by Paweu
*/
/*--END OF HEADER BLOCK--*/
#include <cstddef>
#include <string>
#include <memory>
#include <map>
#include <vector>
#include <list>
#include <mutex>
#include <iostream>
#define BOOST_NUMERIC_CONVERSION_DETAIL_CONVERTER_FLC_12NOV2002_HPP
#define BOOST_NUMERIC_CONVERSION_CONVERTER_FLC_12NOV2002_HPP
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>

#include "arguments.h"

struct BaseStringSet {
	virtual ~BaseStringSet() {}
	virtual bool split(const std::string &value) = 0;
protected:
	static bool xsplit(const char *&input, char delim, std::string &first) {
		if (!input || !*input)
			return false;

		auto dd = strchr(input, delim);
		if (!dd) {
			first = input;
			input = nullptr;
		} else {
			first = std::string(input, dd - input);
			input = dd + 1;
		}

		return true;
	}

	static bool vecSplit(const char *input, std::vector<std::string> &vec, char delim) {
		while (input) {
			std::string s;
			if (!xsplit(input, delim, s))
				return false;
			vec.emplace_back(std::move(s));
		}
		return true;
	}

	static bool vec2map(const std::vector<std::string> &vec, std::map<std::string, std::string> &map, char delim) {
		for (auto &it : vec) {
			auto pos = it.find(delim);
			if (pos == std::string::npos) {
				map[it] = "1";
				continue;
			}
			auto name = it.substr(0, pos);
			auto value = it.substr(pos + 1, it.length() - pos - 1);
			map[name] = value;
		}
		return false;
	}

	template<class ...ARGS>
	static bool xsplit(const char *input, char delim, std::string &first, ARGS& ... args) {
		xsplit(input, ':', first);
		return xsplit(input, ':', args...);
	}
};

struct MountInfo : public BaseStringSet {
	std::string m_Path, m_MountPoint;
	virtual bool split(const std::string &value) override {
		xsplit(value.c_str(), ':', m_Path, m_MountPoint);
		if (m_MountPoint.empty())
			m_MountPoint = "/";
		if (m_MountPoint.front() != '/')
			m_MountPoint = std::string("/") + m_MountPoint;
		return true;
	}
	static MountInfo FromString(const std::string &value) {
		MountInfo r;
		r.split(value);
		return r;
	}
};

struct InjectInfo : public BaseStringSet {
	//std::string m_Path, m_MountPoint;
	virtual bool split(const std::string &value) override {
		return false;// xsplit(value.c_str(), m_Path, m_MountPoint);
	}
	static InjectInfo FromString(const std::string &value) {
		InjectInfo r;
		// r.split(value);
		return r;
	}
};

struct ExportInfo : public BaseStringSet {
	//std::string m_Path, m_MountPoint;
	std::string m_Exporter, m_OutFile, m_BasePath, m_Arguemnts;
	std::map<std::string, std::string> GetArgs() const {
		std::vector<std::string> vec;
		std::map<std::string, std::string> map;
		vecSplit(m_Arguemnts.c_str(), vec, ',');
		vec2map(vec, map, '=');
		return map;
	}
	virtual bool split(const std::string &value) override {
		xsplit(value.c_str(), ':', m_Exporter, m_OutFile, m_BasePath, m_Arguemnts);
		if (m_BasePath.empty())
			m_BasePath = "/";
		if (m_BasePath.front() != '/')
			m_BasePath = std::string("/") + m_BasePath;
		return true;
	}
	static ExportInfo FromString(const std::string &value) {
		ExportInfo r;
		r.split(value);
		return r;
	}
};
//-------------------------------------------------------------------------------------------------

namespace po = boost::program_options;
struct Parser::PrivData  {
	po::options_description m_desc;
	po::variables_map m_vm;
	std::list<std::string> m_Lines;

	std::string GetInitScript() {
		std::stringstream ss;
		for (auto &it : m_Lines)
			ss << it << "\n";
		return ss.str();
	}

	void AddLine(std::string line) { m_Lines.emplace_back(std::move(line)); }
	template<class ...ARGS>
	void AddLine(const char *fmt, ARGS ...args) {
		char buf[8192];
		sprintf(buf, fmt, std::forward<ARGS>(args)...);
		AddLine(std::string(buf));
	}

	void AddPrint(const std::string &line) {
		AddLine("print([[%s]])", line.c_str());
	}
	template<class ...ARGS>
	void AddPrint(const char *fmt, ARGS ...args) {
		char buf[8192];
		sprintf(buf, fmt, std::forward<ARGS>(args)...);
		AddLine("print([[%s]])", buf);
	}

	bool GenInitScriptEnv() {
		AddLine("--StarVFS cli init script");
		AddLine("--Generated automatically from commandline");
		AddLine("");
		return true;
	}
	bool ProcessInitialSettings() {
		if (m_vm["remote"].as<bool>()) {
			int port = m_vm["remote-port"].as<int>();
			std::string sport;
			if (port <= 0 || port >= 0xFFFF) {
				port = 0;
				sport = "<default>";
			} else {
				sport = std::to_string(port);
			}

			AddPrint("Starting remote server at port %s", sport.c_str());
			AddLine("RemoteServer = Register:CreateModule('RemoteModule')");
			if(port)
				AddLine("RemoteServer:SetAttribute('Port', '%d')", port);
			AddLine("RemoteServer:Enable()");
			AddLine("");
		}
		if (m_vm["meta-module"].as<bool>()) {
			AddPrint("Loading MetaModule");
			AddLine("Register:CreateModule('MetaModule'):Enable()");
		}
		return true;
	}

	bool ProcessMainPipeline() {
		if (!m_vm["library"].empty()) {
			AddPrint("Loading Lua libs...");
			for (auto &it : m_vm["library"].as<std::vector<std::string>>()) {
				AddPrint("Loading library: %s", it.c_str());
				AddLine("require('%s')", it.c_str());
			}
			AddLine("");
		}

		if (!m_vm["mount"].empty()) {
			AddPrint("Mounting containers...");
			for (auto &it : m_vm["mount"].as<std::vector<std::string>>()) {
				auto info = MountInfo::FromString(it);
				AddPrint("Mounting %s on %s", info.m_Path.c_str(), info.m_MountPoint.c_str());
				AddLine("mount('%s', '%s')", info.m_Path.c_str(), info.m_MountPoint.c_str());
			}
			AddLine("");
		}

		//for (auto &it : e.m_Mounts) {
		//	if (e.m_InitVerbose)
		//		printf("Mounting %s to %s\n", it.m_Path.c_str(), it.m_MountPoint.c_str());
		//	auto ret = svfs.OpenContainer(it.m_Path.c_str(), it.m_MountPoint.c_str(), 0);
		//	if (ret != ::StarVFS::VFSErrorCode::Success) {
		//		printf("Failed to mount container!\n");
		//		return false;
		//	}
		//}

		//inject
		//	if (!vm["inject"].empty())
		//		for (auto &it : vm["inject"].as<std::vector<std::string>>())
		//			m_Env.m_Injects.push_back(InitEnv::InjectInfo::FromString(it));

		if (!m_vm["script"].empty()) {
			AddPrint("Executing scripts...");
			for (auto &it : m_vm["script"].as<std::vector<std::string>>()) {
				bool isfile = boost::filesystem::is_regular_file(it);
				if (isfile)
					AddPrint("Executing file: %s", it.c_str());
				else
					AddPrint("Executing chunk: %s", it.c_str());
				if (isfile) {
					AddLine("dofile([[%s]])", it.c_str());
				} else {
					AddLine("%s", it.c_str());
				}
			}
			AddLine("");
		}

		//export
		if (!m_vm["export"].empty()) {
			AddPrint("Exporting vfs content...");
			AddLine("");
			int idx = 0;
			for (auto &it : m_vm["export"].as<std::vector<std::string>>()) {
				++idx;
				auto info = ExportInfo::FromString(it);
				char valname[32];
				sprintf(valname, "Exporter_%02d", idx);

				AddPrint("Exporting %s to %s using %s with%s arguments %s", info.m_BasePath.c_str(), info.m_OutFile.c_str(), info.m_Exporter.c_str(), info.m_Arguemnts.empty() ? "out" : "", info.m_Arguemnts.c_str());

				AddLine("local %s = Register:CreateExporter([[%s]])", valname, info.m_Exporter.c_str());
				auto map = info.GetArgs();
				for (auto &it : map)
					AddLine("%s:SetAttribute([[%s]], [[%s]])", valname, it.first.c_str(), it.second.c_str());

				AddLine("%s:DoExport([[%s]], [[%s]])", valname, info.m_BasePath.c_str(), info.m_OutFile.c_str());
				AddLine("");
			}
		}
		return true;
	}

	bool ProcessFinalSettings() {
		//	m_Env.m_RunCLI =
		if (m_vm["list-exporters"].as<bool>()) {
			AddLine("print 'List of known exporters:'");
			AddLine("print(table.unpack(Register:GetRegisteredExporters()))");
			AddLine("");
		}
		return true;
	}

	PrivData() : m_desc("Allowed options") {
		m_desc.add_options()
			("help", "produce help message")

			("print-init-script", po::bool_switch(), "Print init script generated from command line and exit")

			("no-cli", po::bool_switch(), "Do not enter CLI")
			("version,v", "Print version information and exit")

			("meta-module", po::bool_switch(), "Load MetaModule at startup")
			("remote", po::bool_switch(), "Start remote server")
			("remote-port", po::value<int>()->default_value(0), "Set port for remote server")

			("library,l", po::value<std::vector<std::string>>(), "Load lua library")
			("mount,m", po::value<std::vector<std::string>>(), "Mount container. format: FILE[:MOUNTPOINT]") //[:TYPE]
																											 //			("inject,i", po::value<std::vector<std::string>>(), "Inject file into vfs. format: SYSPATH:VPATH. Virtual path will be created if not exits") //[:TYPE]
			("script,s", po::value<std::vector<std::string>>(), "Execute scipt before entering CLI. It may be file or chunk of code")
			("export,e", po::value<std::vector<std::string>>(), "Export vfs content. format: EXPORTER:OUTFILE[:BASEPATH[:PARAM=VALUE]]")

			("list-exporters", po::bool_switch(), "List available exporters")

			("no-bash-mode", po::bool_switch(), "disable Bash-like function call")
			;
	}

	bool Run(InitEnv& out, int argc, char **argv) {
		po::store(po::parse_command_line(argc, argv, m_desc), m_vm);
		po::notify(m_vm);

		if (m_vm.count("help")) {
			std::cout << m_desc << "\n";
			std::cout << "Arguments are processed in order:\n";
			std::cout << "[other settings] -> lua libs -> mounts -> injects -> scripts -> exports -> enter cli\n\n";
			exit(0);
		}

		if (m_vm.count("version")) {
			std::cout << "version\n";
			exit(0);
		}

		if (!GenInitScriptEnv())
			return false;
		if (!ProcessInitialSettings())
			return false;
		if (!ProcessMainPipeline())
			return false;
		if (!ProcessFinalSettings())
			return false;

		if (m_vm["print-init-script"].as<bool>()) {
			std::cout << GetInitScript();
			exit(0);
		}

		out.m_RunCLI = !m_vm["no-cli"].as<bool>();
		out.m_BashMode = !m_vm["no-bash-mode"].as<bool>();

		return true;
	}
};

//-------------------------------------------------------------------------------------------------

Parser::Parser() {
}

bool Parser::Run(InitEnv& out, int argc, char **argv) {
	m_InitScriptLines.clear();
	auto data = std::make_unique<PrivData>();
	if (!data->Run(out, argc, argv))
		return false;
	m_InitScriptLines.swap(data->m_Lines);
	return true;
}

std::string Parser::GetInitScript() {
	std::stringstream ss;
	for (auto &it : m_InitScriptLines)
		ss << it << "\n";
	return ss.str();
}

max_stars_repo_name: pgrabas/starVFS

max_issues_repo_name: pgrabas/starVFS

max_forks_repo_name: pgrabas/starVFS


text:
//
// Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include <server/include/basePipeServer/ConnectionHandler.hpp>

#include <SocketProfilingConnection.hpp>
#include <Processes.hpp>

#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test_suite.hpp>

BOOST_AUTO_TEST_SUITE(BasePipeServerTests)

using namespace armnn;
using namespace arm::pipe;

BOOST_AUTO_TEST_CASE(BasePipeServerTest)
{
    // Setup the mock service to bind to the UDS.
    std::string udsNamespace = "gatord_namespace";

    // Try to initialize a listening socket through the ConnectionHandler
    BOOST_CHECK_NO_THROW(ConnectionHandler connectionHandler(udsNamespace, true));

    // The socket should close once we leave the scope of BOOST_CHECK_NO_THROW
    // and socketProfilingConnection should fail to connect
    BOOST_CHECK_THROW(profiling::SocketProfilingConnection socketProfilingConnection,
                      arm::pipe::SocketConnectionException);

    // Try to initialize a listening socket through the ConnectionHandler again
    ConnectionHandler connectionHandler(udsNamespace, true);
    // socketProfilingConnection should connect now
    profiling::SocketProfilingConnection socketProfilingConnection;
    BOOST_TEST(socketProfilingConnection.IsOpen());

    auto basePipeServer = connectionHandler.GetNewBasePipeServer(false);
    // GetNewBasePipeServer will return null if it fails to create a socket
    BOOST_TEST(basePipeServer.get());

    profiling::BufferManager bufferManager;
    profiling::SendCounterPacket sendCounterPacket(bufferManager);

    // Check that we can receive a StreamMetaDataPacket
    sendCounterPacket.SendStreamMetaDataPacket();

    auto packetBuffer = bufferManager.GetReadableBuffer();
    const unsigned char* readBuffer = packetBuffer->GetReadableData();
    unsigned int readBufferSize = packetBuffer->GetSize();

    BOOST_TEST(readBuffer);
    BOOST_TEST(readBufferSize > 0u);

    socketProfilingConnection.WritePacket(readBuffer,readBufferSize);
    bufferManager.MarkRead(packetBuffer);

    BOOST_TEST(basePipeServer.get()->WaitForStreamMetaData());
    BOOST_TEST(basePipeServer.get()->GetStreamMetadataPid() == armnnUtils::Processes::GetCurrentId());
    BOOST_TEST(basePipeServer.get()->GetStreamMetadataMaxDataLen() == MAX_METADATA_PACKET_LENGTH);

    // Now try a simple PeriodicCounterSelectionPacket
    sendCounterPacket.SendPeriodicCounterSelectionPacket(50, {1,2,3,4,5});

    packetBuffer = bufferManager.GetReadableBuffer();
    readBuffer = packetBuffer->GetReadableData();
    readBufferSize = packetBuffer->GetSize();

    BOOST_TEST(readBuffer);
    BOOST_TEST(readBufferSize > 0u);

    socketProfilingConnection.WritePacket(readBuffer,readBufferSize);
    bufferManager.MarkRead(packetBuffer);

    auto packet1 = basePipeServer.get()->WaitForPacket(500);

    BOOST_TEST(!packet1.IsEmpty());
    BOOST_TEST(packet1.GetPacketFamily() == 0);
    BOOST_TEST(packet1.GetPacketId() == 4);
    BOOST_TEST(packet1.GetLength() == 14);

    // Try and send the packet back to the client
    basePipeServer.get()->SendPacket(packet1.GetPacketFamily(),
                                     packet1.GetPacketId(),
                                     packet1.GetData(),
                                     packet1.GetLength());

    auto packet2 = socketProfilingConnection.ReadPacket(500);

    BOOST_TEST(!packet2.IsEmpty());
    BOOST_TEST(packet2.GetPacketFamily() == 0);
    BOOST_TEST(packet2.GetPacketId() == 4);
    BOOST_TEST(packet2.GetLength() == 14);

    socketProfilingConnection.Close();
}

BOOST_AUTO_TEST_SUITE_END()


text:
/*
 * Copyright (C) Alex Nekipelov (alex@nekipelov.net)
 * License: BSD
 */

#include <boost/algorithm/string/replace.hpp>
#include "buildinhelpers.h"

namespace cpptl {

Value include(TemplateEngine &engine, const Value &context, const Value &args)
{
    if( args.size() > 0 )
    {
        const std::string &fileName = args[0].toString();
        Template subTempl = engine.templFile(fileName);
        return subTempl.render( context );
    }
    else
    {
        assert( false );
        return Value();
    }
}

Value rawHtml(const Value &, const Value &html)
{
    if( html.size() == 1 )
    {
        if( html[0].type() == Value::String)
        {
            std::string s = html[0].toString();

            boost::replace_all(s, "&", "&");
            boost::replace_all(s, ">", ">");
            boost::replace_all(s, "<", "<");
            boost::replace_all(s, """, "\"");

            return Value(s, Value::UnsafeStringTag());
        }
        else
        {
            return html[0];
        }
    }
    else
    {
        return Value("");
    }
}

} // namespace cpptl

max_stars_repo_name: nekipelov/cpptl

max_issues_repo_name: nekipelov/cpptl

max_forks_repo_name: nekipelov/cpptl


text:
/*******************************************************************************
 *         Copyright 2003-2012 LASMEA UMR 6602 CNRS/U.B.P
 *         Copyright 2011-2012 LRI    UMR 8623 CNRS/Univ Paris Sud XI
 *
 *          Distributed under the Boost Software License, Version 1.0.
 *                 See accompanying file LICENSE.txt or copy at
 *                     http://www.boost.org/LICENSE_1_0.txt
 ******************************************************************************/
#ifndef NT2_TOOLBOX_INTERPOL_FUNCTIONS_GENERIC_PCHIP_HPP_INCLUDED
#define NT2_TOOLBOX_INTERPOL_FUNCTIONS_GENERIC_PCHIP_HPP_INCLUDED

#include <nt2/toolbox/interpol/functions/pchip.hpp>
#include <nt2/include/functions/ppval.hpp>
#include <nt2/include/functions/is_nge.hpp>
#include <nt2/include/functions/is_nle.hpp>
#include <nt2/include/functions/issorted.hpp>
#include <nt2/include/functions/bsearch.hpp>
#include <nt2/include/functions/diff.hpp>
#include <nt2/include/functions/conj.hpp>
#include <nt2/include/functions/abs.hpp>
#include <nt2/include/functions/globalfind.hpp>
#include <nt2/include/functions/if_else.hpp>
#include <nt2/include/functions/is_gtz.hpp>
#include <nt2/include/functions/fma.hpp>
#include <nt2/include/functions/logical_or.hpp>
#include <nt2/include/functions/zeros.hpp>
#include <nt2/include/functions/oneminus.hpp>
#include <nt2/include/functions/oneplus.hpp>
#include <nt2/include/functions/repnum.hpp>
#include <nt2/include/functions/width.hpp>
#include <nt2/include/functions/average.hpp>
#include <nt2/include/functions/first_index.hpp>
#include <nt2/include/functions/isreal.hpp>
#include <nt2/include/functions/colvect.hpp>
#include <nt2/include/functions/rowvect.hpp>
#include <nt2/include/functions/transpose.hpp>
#include <nt2/include/functions/reshape.hpp>
#include <nt2/include/functions/vertcat.hpp>
#include <nt2/include/functions/multiplies.hpp>
#include <nt2/include/functions/logical_and.hpp>
#include <nt2/include/constants/nan.hpp>
#include <nt2/include/constants/three.hpp>
#include <nt2/core/container/table/table.hpp>
#include <nt2/sdk/meta/as_integer.hpp>
#include <nt2/sdk/simd/logical.hpp>
#include <boost/assert.hpp>

namespace nt2 { namespace ext
{

  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::run_assign_, tag::cpu_
                            , (A0)(A1)(N1)
                            , ((ast_<A0, nt2::container::domain>))
                              ((node_<A1,nt2::tag::pchip_,N1,nt2::container::domain>))
                            )
  {
    typedef typename boost::proto::result_of::child_c<A1&,0>::value_type  child0;
    typedef typename boost::proto::result_of::child_c<A1&,1>::value_type  child1;
    typedef typename boost::proto::result_of::child_c<A1&,2>::value_type  child2;
    typedef typename child0::value_type                               value_type;
    typedef typename meta::as_integer<value_type>::type               index_type;
    typedef table<value_type>                                             vtab_t;
    typedef table<index_type>                                             itab_t;
    typedef A0&                                                      result_type;

    result_type operator()(A0& yi, A1& inputs) const
    {
      yi.resize(inputs.extent());
      const child0 & x   =  boost::proto::child_c<0>(inputs);
      BOOST_ASSERT_MSG(issorted(x, 'a'), "for 'pchip' interpolation x values must be sorted in ascending order");
      const child1 & y   =  boost::proto::child_c<1>(inputs);
      const child2 & xi  =  boost::proto::child_c<2>(inputs);
      bool extrap = false;
      value_type extrapval = Nan<value_type>();
      choices(inputs, extrap, extrapval, N1());
      vtab_t h  =  nt2::diff(x,1,2);
      vtab_t del = nt2::diff(y,1,2)/h;
      pchipslopes(x,y,del, yi);
      ppval <value_type> pp(x,y,yi,h,del);
      yi =pp.eval(xi);
      if (!extrap)
      {
        value_type  b =  value_type(x(begin_));
        value_type  e =  value_type(x(end_));
        yi = nt2::if_else(nt2::logical_or(boost::simd::is_nge(xi, b),
                                          boost::simd::is_nle(xi, e)), extrapval, yi);
      }
      return yi;
    }
  private :
    static void choices(const A1&, bool &,  value_type&, boost::mpl::long_<3> const &)
    { }
    static void choices(const A1& inputs, bool & extrap,  value_type& extrapval, boost::mpl::long_<4> const &)
    {
      typedef typename boost::proto::result_of::child_c<A1&,3>::type             child3;
      typedef typename meta::scalar_of<child3>::type                    cref_param_type;
      typedef typename meta::strip<cref_param_type>::type                    param_type;
      get(inputs, extrap, extrapval, param_type());
    }
    static void get(const A1& inputs, bool & extrap,  value_type&,  const bool &)
    {
      extrap =  boost::proto::child_c<3>(inputs);
    }
    static void get(const A1& inputs, bool &,  value_type& extrapval,  const value_type &)
    {
      extrapval =  boost::proto::child_c<3>(inputs);
    }

    static void pchipslopes(const child0 & x, const child1 & y, const vtab_t &del, A0& d)
    {
      itab_t k;
      size_t n =  length(x);
      if (nt2::numel(x) == 2) {
        d =  nt2::repnum(value_type(del(begin_)), 1, width(y)); // del(begin_) is not of value_type !
      } else {
        d =  nt2::zeros(1, width(y), nt2::meta::as_<value_type>());
        if (/* nt2::isreal(del)*/ true) //to do proper version for real types
        { // is k 1 based or 0,  I hope 1 here ?
          k = nt2::globalfind(nt2::is_gtz(nt2::multiplies(nt2::sign(del(nt2::_(begin_, begin_+n-3))), nt2::sign(del(nt2::_(begin_+1, begin_+n-2))))), nt2::meta::as_<index_type>());
        }
        else
        {
          k = nt2::globalfind(nt2::logical_and(is_eqz(del(nt2::_(begin_, begin_+n-3))), is_eqz(del(nt2::_(begin_+1,begin_+n-2)))), nt2::meta::as_<index_type>());
        }
      }
      itab_t kp1 = oneplus(k);
      itab_t kp2 = oneplus(kp1);
      vtab_t h = nt2::diff(x, 1, 2);
      vtab_t hs = h(1, k)+h(1, kp1);
      vtab_t w1 = (h(1, k)+hs)/(Three<value_type>()*hs);
      vtab_t w2 = (hs+h(1, kp1))/(Three<value_type>()*hs);
      vtab_t dmax = nt2::max(nt2::abs(del(1, k)), nt2::abs(del(1, kp1)));
      vtab_t dmin = nt2::min(nt2::abs(del(1, k)), nt2::abs(del(1, kp1)));
      d(kp1) = dmin/nt2::conj(nt2::multiplies(w1,(del(1, k)/dmax)) + nt2::multiplies(w2, (del(1, kp1)/dmax)));
      //   Slopes at end points.
      //   Set d(0) and d(n-1) via non-centered, shape-preserving three-point formulae.
      d(1) = ((2*h(1)+h(2))*del(1) - h(1)*del(2))/(h(1)+h(2));
      if (/*nt2::isreal(d) && */(nt2::sign(d(nt2::first_index<1>(d))) != nt2::sign(del(1))))
      {
        d(nt2::first_index<2>(d)) = Zero<value_type>();
      }
      else if ((nt2::sign(del(1)) != nt2::sign(del(1))) &&
               (nt2::abs(d(nt2::first_index<1>(d))) > nt2::abs(Three<value_type>()*del(1))))
      {
        d(nt2::first_index<2>(d)) = Three<value_type>()*del(1);
      }
      //      index_type end = n;
      //     NT2_DISPLAY(h);
      d(nt2::last_index<2>(d)) = ((Two<value_type>()*h(n-1)+h(n-2))*del(n-1) - h(n-1)*del(n-2))/(h(n-1)+h(n-2));
      if (/*isreal(d) &&*/ (nt2::sign(d(nt2::last_index<1>(d))) != nt2::sign(del(n-1))))
      {
        d(nt2::last_index<2>(d)) = Zero<value_type>();
      }
      else if ((nt2::sign(del(n-1)) != nt2::sign(del(n-2))) &&
               (nt2::abs(d(nt2::last_index<1>(d))) > nt2::abs(Three<value_type>()*del(n-1))))
      {
        d(nt2::last_index<2>(d)) = 3*del(n-1);
      }
    }
  };
} }

#endif


text:
#include <net/aggregator/WorkerServer.h>
#include <net/aggregator/WorkerRouter.h>
#include <net/aggregator/WorkerHandler.h>

#include <stdexcept>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/ref.hpp>

namespace net{
namespace aggregator{

void WorkerServerThreadPool::init(size_t poolsize)
{
    if (pool_)
        return;
    if (poolsize == 0)
        poolsize = 1;
    pool_.reset(new boost::threadpool::pool(poolsize));
}

void WorkerServerThreadPool::schedule_task(const boost::threadpool::pool::task_type& task)
{
    //if (pool_->active() == 0)
    //{
    //    std::cout << "currently no active in rpc worker server.========= " << std::endl;
    //}
    pool_->schedule(task);
    //if (pool_->pending() > 1)
    //{
    //    std::cout << "some task pending in rpc worker server: " << pool_->pending() << std::endl;
    //}
}

void WorkerServerThreadPool::stop()
{
    if (pool_)
    {
        pool_->clear();
        pool_->wait();
    }
}

WorkerServer::WorkerServer(
    const WorkerRouter& router,
    const std::string& host,
    uint16_t port,
    unsigned int threadNum)
: router_(router)
, srvInfo_(host, port)
, threadNum_(threadNum)
{
    if (threadNum_ < 2)
        threadNum_ = 2;
    worker_pool_.init(threadNum_);
}

WorkerServer::~WorkerServer()
{
    stop();
}

void WorkerServer::start()
{
    if (srvInfo_.host_.empty() || srvInfo_.port_ <= 0)
        throw std::runtime_error("invalid host or port for Worker server!");

    instance.listen(srvInfo_.host_, srvInfo_.port_);
    instance.start(threadNum_/2);
}

void WorkerServer::stop()
{
    if (instance.is_running())
    {
        instance.end();
        instance.join();
    }
    worker_pool_.stop();
}

void WorkerServer::join()
{
    instance.join();
}

void handler_wrapper(WorkerHandlerBase* handler, msgpack::rpc::request& req)
{
    try
    {
        handler->invoke(req);
    }
    catch (const msgpack::type_error& e)
    {
        std::cerr << "[WorkerServer] " << e.what() << std::endl;
        req.error(msgpack::rpc::ARGUMENT_ERROR);
    }
    catch (const std::exception& e)
    {
        std::cerr << "[WorkerServer] " << e.what() << std::endl;
        req.error(std::string(e.what()));
    }
}

void WorkerServer::dispatch(msgpack::rpc::request req)
{
    try
    {
        std::string method;
        req.method().convert(&method);

        WorkerHandlerBase* handler = router_.find(method);
        if (handler)
        {
            //handler->invoke(req);
            worker_pool_.schedule_task(boost::bind(handler_wrapper, handler, req));
        }
        else
        {
            std::cerr << "[WorkerServer] Method not found: " << method << std::endl;
            req.error(msgpack::rpc::NO_METHOD_ERROR);
        }
    }
    catch (const msgpack::type_error& e)
    {
        std::cerr << "[WorkerServer] " << e.what() << std::endl;
        req.error(msgpack::rpc::ARGUMENT_ERROR);
    }
    catch (const std::exception& e)
    {
        std::cerr << "[WorkerServer] " << e.what() << std::endl;
        req.error(std::string(e.what()));
    }
}

}} // end - namespace

max_stars_repo_name: izenecloud/izenelib

max_issues_repo_name: izenecloud/izenelib

max_forks_repo_name: izenecloud/izenelib