text:
/******************************************************************************
 * $Id$
 *
 * Project:  libLAS - http://liblas.org - A BSD library for LAS format data.
 * Purpose:  Definition of LASClassification type.
 * Author:   Mateusz Loskot, mateusz@loskot.net
 *
 ******************************************************************************
 * Copyright (c) 2009, Mateusz Loskot
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following
 * conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in
 *       the documentation and/or other materials provided
 *       with the distribution.
 *     * Neither the name of the Martin Isenburg or Iowa Department
 *       of Natural Resources 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.
 ****************************************************************************/

#ifndef LIBLAS_LASCLASSIFICATION_HPP_INCLUDED
#define LIBLAS_LASCLASSIFICATION_HPP_INCLUDED

// boost
#include <boost/cstdint.hpp>
#include <liblas/export.hpp>
// std
#include <cassert>
#include <cstddef>
#include <bitset>
#include <ostream>
#include <sstream>
#include <stdexcept>

// I hate you windows
#ifdef _MSC_VER
#ifdef GetClassName
#undef GetClassName
#endif
#endif

namespace liblas {

/// Class definition to manipulate properties of point record classification.
///
class LAS_DLL Classification
{
public:

    /// Alias on std::bitset<8> used as collection of flags.
    typedef std::bitset<8> bitset_type;

    /// Number of classes in lookup table as defined in ASPRS LAS 1.1+.
    /// For LAS 1.0, this static number may be invalid and
    /// extend up to 255 classes stored in variable-length records.
    /// @note Currently, libLAS does not support classification based on table
    /// stored in variable-length record. Only Standard ASPRS classification
    /// table is supported.
    static boost::uint32_t const class_table_size;

    /// Values of indexes in the set of bit flags.
    enum BitPosition
    {
        eClassBit     = 0, ///< First bit position of 0:4 range.
        eSyntheticBit = 5, ///< Synthetic flag.
        eKeyPointBit  = 6, ///< Key-point flag.
        eWithheldBit  = 7  ///< Withheld flag.
    };

    /// Default initialization constructor.
    /// Initializes all flags of classification as set to 0.
    /// Operation semantic is equivalent to bitset_type::reset().
    Classification() {}

    /// Initializes classification flags using given set of 8 bits.
    /// @param flags [in] - contains 8 bits representing classification flags.
    explicit Classification(bitset_type const& flags)
        : m_flags(flags)
    {}

    /// Initializes classification flags using 8 bits of integral type.
    /// @param flags [in] - contains 8 bits representing classification flags.
    explicit Classification(boost::uint8_t const& flags)
        : m_flags(flags)
    {}

    /// Initializes classification with values of given compounds.
    /// @param cls [in] - index of Standard ASPRS classification as
    /// defined in the lookup table, from 0 to class_table_size - 1.
    /// @param s [in] - If set then this point was created by a technique other than
    /// LIDAR collection such as digitized from a photogrammetric stereo model.
    /// @param k [in] - If set, this point is considered to be a model keypoint and
    /// thus generally should not be withheld in a thinning algorithm.
    /// @param w [in] - If set, this point should not be included in processing.
    Classification(boost::uint32_t cls, bool s, bool k, bool w)
    {
        SetClass(cls);
        SetSynthetic(s);
        SetKeyPoint(k);
        SetWithheld(w);
    }

    /// Copy constructor.
    Classification(Classification const& other)
    {
        m_flags = other.m_flags;
    }

    /// Assignment operator.
    Classification& operator=(Classification const& rhs)
    {
        if (&rhs != this)
        {
            m_flags = rhs.m_flags;
        }
        return *this;
    }

    /// Conversion operator.
    /// Returns classification object as in form of std::bitset<8>.
    operator bitset_type() const
    {
        return bitset_type(m_flags);
    }

    /// Named accessor converting Classification to std::bitset<8>.
    bitset_type GetFlags() const
    {
        return bitset_type(m_flags);
    }

    /// Raturns name of class as defined in LAS 1.1+
    /// Finds class name in lookup table based on class index
    /// as defined in classification object.
    std::string GetClassName() const;

    /// Returns index of ASPRS classification as defined in the lookup table.
    boost::uint8_t GetClass() const;

    /// Updates index of ASPRS classification as defined in the lookup table.
    /// Valid index is in range from 0 to class_table_size - 1.
    /// For LAS 1.0, this static number may be invalid and
    /// extend up to 255 classes stored in variable-length records.
    /// @note Currently, libLAS does not support classification based on table
    /// stored in variable-length record. Only Standard ASPRS classification
    /// table is supported.
    /// @exception Theoretically, may throw std::out_of_range in case index
    /// value is not in range between 0 and class_table_size - 1.
    void SetClass(boost::uint32_t index);

    /// Sets if this point was created by a technique other than LIDAR
    /// collection such as digitized from a photogrammetric stereo model.
    void SetSynthetic(bool flag)
    {
        m_flags[eSyntheticBit] = flag;
    }

    /// Tests if this point was created by a technique other than LIDAR collection.
    bool IsSynthetic() const
    {
        return m_flags[eSyntheticBit];
    }

    /// Sets if this point is considered to be a model keypoint and
    /// thus generally should not be withheld in a thinning algorithm.
    void SetKeyPoint(bool flag)
    {
        m_flags[eKeyPointBit] = flag;
    }

    /// Tests if this point is considered to be a model keypoint.
    bool IsKeyPoint() const
    {
        return m_flags[eKeyPointBit];
    }

    /// SetTests if this point should excluded from processing.
    void SetWithheld(bool flag)
    {
        m_flags[eWithheldBit] = flag;
    }

    /// Tests if this point should excluded from processing.
    bool IsWithheld() const
    {
        return m_flags[eWithheldBit];
    }

    /// Compares this classification object with other one.
    /// Comparison is preformed against set of bit flags stored
    /// in both objects.
    bool equal(Classification const& other) const
    {
        return (other.m_flags == m_flags);
    }

private:

    bitset_type m_flags;

    void check_class_index(boost::uint32_t index) const;
};

/// Equal-to operator implemented in terms of Classification::equal.
inline bool operator==(Classification const& lhs, Classification const& rhs)
{
    return lhs.equal(rhs);
}

/// Not-equal-to operator implemented in terms of Classification::equal.
inline bool operator!=(Classification const& lhs, Classification const& rhs)
{
    return (!(lhs == rhs));
}

/// The output stream operator is based on std::bitset<N>::operator<<.
/// It outputs classification flags in form of string.
/// Effects promised as by
/// @link http://www.open-std.org/Jtc1/sc22/wg21/ Standard for Programming Language C++ @endlink,
/// 23.3.5.2:
/// Each character is determined by the value of its corresponding bit
/// position in *this. Character position N - 1 corresponds to bit position
/// zero. Subsequent decreasing character positions correspond to increasing
/// bit positions. Bit value zero becomes the character 0, bit value one
/// becomes the character 1.
inline std::ostream& operator<<(std::ostream& os, Classification const& cls)
{
    Classification::bitset_type flags(cls);
    return (os << flags);
}

} // namespace liblas

#endif // LIBLAS_LASCLASSIFICATION_HPP_INCLUDED

max_stars_repo_name: sebastic/libLAS

max_issues_repo_name: sebastic/libLAS

max_forks_repo_name: sebastic/libLAS


text:
#ifndef ASLAM_PYTHON_EXPORT_PINHOLE_UNDISTORTER_HPP
#define ASLAM_PYTHON_EXPORT_PINHOLE_UNDISTORTER_HPP

#include <Eigen/Core>
#include <aslam/PinholeUndistorter.hpp>
#include <numpy_eigen/boost_python_headers.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/core/eigen.hpp>

namespace aslam {
namespace cameras {

typedef Eigen::Matrix<boost::uint8_t, Eigen::Dynamic, Eigen::Dynamic> image_t;

template <typename DISTORTION_T, typename MASK_T>
image_t undistortImageNumpyCvmat(const PinholeUndistorter<DISTORTION_T, MASK_T>* instance, const image_t& image_eigen) {
    cv::Mat image_cv, image_cv_undist;
    eigen2cv(image_eigen, image_cv);

    instance->undistortImage(image_cv, image_cv_undist);

    image_t image_eigen_undist(image_cv_undist.rows, image_cv_undist.cols);
    cv2eigen(image_cv_undist, image_eigen_undist);

    return image_eigen_undist;
}

template <typename DISTORTION_T, typename MASK_T>
void exportPinholeUndistorter(const std::string& name) {
    using namespace boost::python;
    typedef MASK_T mask_t;
    typedef DISTORTION_T distortion_t;
    typedef typename PinholeUndistorter<distortion_t, mask_t>::distorted_geometry_t distorted_geometry_t;

    class_<PinholeUndistorter<distortion_t, mask_t>, boost::shared_ptr<PinholeUndistorter<distortion_t, mask_t> > >(
        name.c_str(), init<>())
        .def(init<const sm::PropertyTree&, const sm::PropertyTree&>(
            (name + "(undistorterConfig, cameraConfig)").c_str()))
        .def(init<const sm::PropertyTree&, int, double, double>(
            (name + "(cameraConfig, interpolation, alpha, scale)").c_str()))
        .def(init<boost::shared_ptr<distorted_geometry_t>, int, double, double>(
            (name + "(distortedGeometry, interpolation, alpha, scale)").c_str()))
        .def("init", &PinholeUndistorter<distortion_t, mask_t>::init)
        .def("constructUndistortedFrame", &PinholeUndistorter<distortion_t, mask_t>::constructUndistortedFrame)
        .def("undistortImage", &PinholeUndistorter<distortion_t, mask_t>::undistortImage)
        .def("undistortImage", &undistortImageNumpyCvmat<distortion_t, mask_t>)
        .def("getIdealGeometry", &PinholeUndistorter<distortion_t, mask_t>::idealGeometry);
}

}  // namespace cameras
}  // namespace aslam

#endif /* ASLAM_PYTHON_EXPORT_PINHOLE_UNDISTORTER_HPP */

ext: hpp

max_stars_repo_name: chengfzy/kalibr

max_issues_repo_name: chengfzy/kalibr

max_forks_repo_name: chengfzy/kalibr


text:
/*
 Copyright 2009-2012 Karsten Ahnert
 Copyright 2009-2012 Mario Mulansky

 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)
 */

#include <iostream>
#include <vector>

/* WARNING: Compilation in debug mode might consume enormous memory
   (e.g. ~2GB on gcc 4.4 )
*/

// first increase fusion macro variables (now done by odeint itself)
//#define BOOST_FUSION_INVOKE_MAX_ARITY 15
//#define BOOST_RESULT_OF_NUM_ARGS 15

//[ units_define_basic_quantities

#include <boost/numeric/odeint.hpp>
#include <boost/numeric/odeint/algebra/fusion_algebra.hpp>

#include <boost/units/systems/si/length.hpp>
#include <boost/units/systems/si/time.hpp>
#include <boost/units/systems/si/velocity.hpp>
#include <boost/units/systems/si/acceleration.hpp>
#include <boost/units/systems/si/io.hpp>

#include <boost/fusion/container.hpp>

using namespace std;
using namespace boost::numeric::odeint;
namespace fusion = boost::fusion;
namespace units = boost::units;
namespace si = boost::units::si;

typedef units::quantity< si::time , double > time_type;
typedef units::quantity< si::length , double > length_type;
typedef units::quantity< si::velocity , double > velocity_type;
typedef units::quantity< si::acceleration , double > acceleration_type;
typedef units::quantity< si::frequency , double > frequency_type;

typedef fusion::vector< length_type , velocity_type > state_type;
typedef fusion::vector< velocity_type , acceleration_type > deriv_type;
//]

//[ units_define_ode
struct oscillator
{
    frequency_type m_omega;

    oscillator( const frequency_type &omega = 1.0 * si::hertz ) : m_omega( omega ) { }

    void operator()( const state_type &x , deriv_type &dxdt , time_type t ) const
    {
        fusion::at_c< 0 >( dxdt ) = fusion::at_c< 1 >( x );
        fusion::at_c< 1 >( dxdt ) = - m_omega * m_omega * fusion::at_c< 0 >( x );
    }
};
//]

//[ units_observer
struct streaming_observer
{
    std::ostream& m_out;

    streaming_observer( std::ostream &out ) : m_out( out ) { }

    struct write_element
    {
        std::ostream &m_out;
        write_element( std::ostream &out ) : m_out( out ) { };

        template< class T >
        void operator()( const T &t ) const
        {
            m_out << "\t" << t;
        }
    };

    template< class State , class Time >
    void operator()( const State &x , const Time &t ) const
    {
        m_out << t;
        fusion::for_each( x , write_element( m_out ) );
        m_out << "\n";
    }
};
//]

int main( int argc , char**argv )
{
//    typedef dense_output_runge_kutta
//    <
//        controlled_runge_kutta
//        <
//            runge_kutta_dopri5< state_type , double , deriv_type , time_type , fusion_algebra >
//        >
//    > stepper_type;

    //[ units_define_stepper
    typedef runge_kutta_dopri5< state_type , double , deriv_type , time_type , fusion_algebra > stepper_type;

    state_type x( 1.0 * si::meter , 0.0 * si::meter_per_second );

    integrate_const( make_dense_output( 1.0e-6 , 1.0e-6 , stepper_type() ) , oscillator( 2.0 * si::hertz ) , x , 0.0 * si::second , 100.0 * si::second , 0.1 * si::second , streaming_observer( cout ) );
    //]

    return 0;
}

ext: cpp


text:
/* Copyright John Reid 2007
*/

#include "bio-pch.h"

#include <bio/application.h>
#include <bio/site_data.h>
#include <bio/remo.h>
USING_BIO_NS;

#include <boost/progress.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/operations.hpp>
using namespace boost;
namespace po = boost::program_options;
namespace fs = boost::filesystem;

#include <iostream>
#include <fstream>
using namespace std;

struct ParseReMosApp : Application
{
	std::string text_filename;
	std::string binary_filename;

	ParseReMosApp()
	{
		get_options().add_options()
			("remo,r", po::value(&text_filename)->default_value("remos.txt"), "text remo extraction file")
			("output,o", po::value(&binary_filename)->default_value("remos.bin"), "binary remo extraction file")
			;
	}

	int task()
	{
		ReMoExtraction::ptr_t remo;
		//parse
		cout << "Parsing remo extraction from \"" << text_filename << "\"" << endl;
		{
			boost::progress_timer timer;
			remo = parse_remo_extraction(fs::path(text_filename));
			cout << "Parsed " << remo->sequence_groups.size() << " sequence groups\n";
		}

		fs::path
			remo_extraction_archive(
				binary_filename.c_str()
			);
		cout << "Writing remo extraction to: \"" << remo_extraction_archive._BOOST_FS_NATIVE() << "\"" << endl;
		{
			boost::progress_timer timer;
			remo->serialise(remo_extraction_archive);
		}

		return 0;
	}
};

int
main(int argc, char * argv [])
{
	return ParseReMosApp().main(argc, argv);
}

max_stars_repo_name: JohnReid/biopsy

max_issues_repo_name: JohnReid/biopsy

max_forks_repo_name: JohnReid/biopsy


text:
/**
 * @file   geometry.cpp
 * @author Aron Ahmadia <aron@casiphia.local>
 * @date   Tue Feb 26 15:26:49 2008
 *
 * @brief  Geometry - Implementation of Geometry methods
 *
 *
 */

#include "hyper_sample/utility/geometry.hpp"
#include "utility/error.hpp"

#include <iostream>

#include <cmath>

#include <o2scl/funct.h>
#include <o2scl/gsl_root_brent.h>
#include <gsl/gsl_sf_gamma.h>

#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/math/common_factor.hpp>

namespace smo {

  using namespace boost::numeric::ublas;
  using namespace boost::math;

  PolarAngle Geometry::polarCap(DimCount d, PointCount n)
  {
    switch (n) {
    case 1:
      return pi;
    case 2:
      return pi/2;
    }
    return angleOfCap(d, regionArea(d,n));
  }

  Area Geometry::regionArea(DimCount d, PointCount n)
  {
    return areaOfSphere(d)/n;
  }

  Area Geometry::regionArea(DimCount d, Area polarCapArea, PolarAngle phi1, PolarAngle phi2, PointCount n)
  {
    Area toPartition = areaOfCollar(d,phi1,phi2);
    Area toDivide = toPartition - polarCapArea;
    return toDivide/n;
  }

  PolarAngle Geometry::angleOfCap(DimCount d, Area capArea)
  {
    switch (d) {
      case 1:
	return capArea/2;
      case 2:
	return 2*asin(sqrt(capArea/pi)/2);
      }
    // general case d > 2

    Area sphereArea = areaOfSphere(d);

    if (capArea >= sphereArea) {
      return pi;
    }
    else {
      o2scl::funct_fptr_noerr<AreaOfCapP> f(&Geometry::areaOfCap);
      o2scl::gsl_root_brent<AreaOfCapP,o2scl::funct<AreaOfCapP> > s;
      double x1 = 0;  // lower bound AND returned solution for solve_bkt, see O2 documentation
      AreaOfCapP p;
      p.d = d;
      if (2*capArea > sphereArea) {
	p.capAreaZero = sphereArea - capArea;
	s.solve_bkt(x1,pi,p,f);
	return pi - x1;
      }
      else {
	p.capAreaZero = capArea;
	s.solve_bkt(x1,pi,p,f);
	return x1;
      }
    }
  }

  Area Geometry::areaOfCap(DimCount d, PolarAngle capPhi)
  {
    AreaOfCapP p;
    p.d = d;
    p.capAreaZero = 0;
    return areaOfCap(capPhi, p);
  }

  Area Geometry::areaOfCap(PolarAngle capPhi, AreaOfCapP &p)
  {
    DimCount d = p.d;
    Area capAreaZero = p.capAreaZero;
    double e;
    switch (d) {
    case 1:
      return 2*capPhi - capAreaZero;
    case 2:
      return 4*pi*pow(sin(capPhi/2),2) - capAreaZero;
    case 3:
      if (capPhi < pi/6 || capPhi > pi*5/6) { //Near the poles, use the incomplete Beta function ratio.
	e = static_cast<double>(d);
	return areaOfSphere(d) * gsl_sf_beta_inc(e/2,e/2,pow(sin(capPhi/2),2))
	  - capAreaZero;
      }
      else {
	//In the tropics, use closed solution to integral.
	return (2*capPhi - sin(2*capPhi))*pi;
      }
    }

    e = static_cast<double>(d);
    return areaOfSphere(d) * gsl_sf_beta_inc(e/2,e/2,pow(sin(capPhi/2),2))
      - capAreaZero;
  }

  Area Geometry::areaOfSphere(const DimCount d)
  {
    double e = static_cast<double>(d+1)/2;
    return 2*pow(pi,e)/gsl_sf_gamma(e);
  }

  Area Geometry::areaOfCollar(const DimCount d, const PolarAngle phi1, const PolarAngle phi2)
  {
    if (phi1 >= phi2) {
      throw meshError("The collar angle phi1 is greater than or equal to phi2\n");
    }
    return areaOfCap(d,phi2) - areaOfCap(d,phi1);
  }

  void
  Geometry::bottomCapRegion(const DimCount d, const PolarAngle capPhi, Region &r)
  {
    r.resize(d,2);
    if (d == 1) {
      r(0,0) = 2*pi - capPhi;
      r(0,1) = 2*pi;
    }
    else {
      // r(1:d-1,:) = SphereRegion(d-1);
      Region rSphere(d-1,2);
      sphereRegion(d-1, rSphere);
      subrange(r, 0, d-1, 0 ,2) = rSphere;
      r(d-1,0) = pi-capPhi;
      r(d-1,1) = pi;
    }
  }

  void
  Geometry::topCapRegion(const DimCount d, const PolarAngle capPhi, Region &r)
  {
    r.resize(d,2);
    if (d == 1) {
      r(0,0) = 0;
      r(0,1) = capPhi;
    }
    else {
      // r(1:d-1,:) = SphereRegion(d-1);
      Region rSphere(d-1,2);
      sphereRegion(d-1, rSphere);
      subrange(r, 0, d-1, 0 ,2) = rSphere;
      r(d-1,0) = 0;
      r(d-1,1) = capPhi;
    }
  }

  void
  Geometry::sphereRegion(DimCount d, Region &r)
  {
    r.resize(d,2);
    r(0,0) = 0;
    r(0,1) = 2*pi;

    for (int i=1; i < d; i++) {
      r(i,0) = 0;
      r(i,1) = pi;
    }
    return;
  }

  PolarAngle
  Geometry::circleOffset(const PointCount p1, const PointCount p2)
  {
    double d1 = static_cast<double> (p1);
    double d2 = static_cast<double> (p2);
    double sectorTwistAlign = (1/d2 - 1/d1)/2;
    double maxMinAngleRot = gcd(p1,p2)/(2*d1*d2);
    return sectorTwistAlign + maxMinAngleRot;
  }

  void
  Geometry::toPolar(CartPoints p, SpherePoints &s)
  {
    PointCount n = p.size1();
    DimCount d = p.size2() - 1;
    PolarAngle iSinProd;
    PolarAngle aTanTheta;

    s.resize(n,d);

    for (int i=0; i < n; ++i) {
      iSinProd = 1;
      for (int j=d-1; j > 0; --j) {
	s(i,j) = acos(p(i,j+1)/iSinProd);
	iSinProd *= sin(s(i,j));
      }
      aTanTheta = atan2(p(i,1),p(i,0));
      if (aTanTheta >= 0) {
	s(i,0) = aTanTheta;
      }
      else {
	s(i,0) = aTanTheta + 2*pi;
      }
    }
    return;
  }

  void
  Geometry::toCart(SpherePoints s, CartPoints &p)
  {
    PointCount n = s.size1();
    DimCount d = s.size2() + 1;
    PolarAngle iSinProd;
    //    double radiusSqSum, radius;

    p.resize(n,d);

    for (int i=0; i < n; ++i) {
      iSinProd = 1;
      // radiusSqSum = 0;
      for (int j=d-1; j > 1; --j) {
	p(i,j) = iSinProd*cos(s(i,j-1));
	//	radiusSqSum += pow(p(i,j),2);
	iSinProd *= sin(s(i,j-1));
      }
      p(i,1) = iSinProd*sin(s(i,0));
      p(i,0) = iSinProd*cos(s(i,0));

      /* extra code to verify radius is == 1
      radiusSqSum += pow(p(i,1),2) + pow(p(i,0),2);
      if (radiusSqSum != 1) {
	radius = sqrt(radiusSqSum);
	for (int j=0; j < d; ++j) {
	  p(i,j) = p(i,j)/radius;
	}
      } */
    }

    return;
  }

}

max_stars_repo_name: ahmadia/hypermesh

max_issues_repo_name: ahmadia/hypermesh

max_forks_repo_name: ahmadia/hypermesh


text:
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma
// de Barcelona (UAB).
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.

#include "carla/client/ActorBlueprint.h"

#include <boost/algorithm/string/predicate.hpp>

#ifdef _WIN32
#  include <shlwapi.h>
#else
#  include <fnmatch.h>
#endif // _WIN32

namespace carla {
namespace client {

  static bool MatchWildcards(const std::string &str, const std::string &test) {
#ifdef _WIN32
    return PathMatchSpecA(str.c_str(), test.c_str());
#else
    return 0 == fnmatch(test.c_str(), str.c_str(), 0);
#endif // _WIN32
  }

  bool ActorBlueprint::StartsWith(const std::string &test) const {
    return boost::starts_with(GetTypeId(), test);
  }

  bool ActorBlueprint::MatchWildcards(const std::string &test) const {
    return ::carla::client::MatchWildcards(GetTypeId(), test);
  }

} // namespace client
} // namespace carla

max_stars_repo_name: nsubiron/libcarla

max_issues_repo_name: nsubiron/libcarla

max_forks_repo_name: nsubiron/libcarla


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

#include <iostream>
#include <set>
#include <signal.h>

#include <spdlog/spdlog.h>
#include <boost/program_options.hpp>
#include <fmt/format.h>
#include <systemd/sd-daemon.h>

#include "sr_wrapper/session.hh"
#include "configurator/subscribe.hh"
#include "configurator/configurator.hh"
#include "configurator/config.hh"
#include "config.h"

using std::set;
using std::cout;
namespace po = boost::program_options;

static const set<string> logLevels{"trace", "debug", "info", "warning", "error", "critical", "off"};

static bool doExit = false;

static void siginthandler(int signum) {
  if (doExit) {
    spdlog::warn("Forced exit requested");
    exit(1 + signum);
  }
  doExit = true;
}

int main(int argc, char* argv[]) {
  po::options_description opts("Options");
  string logLevelHelp = fmt::format("The loglevel of the program, possible values are {}", fmt::join(logLevels, ", "));

  opts.add_options()
    ("help,h", "Output a help message")
    ("config,c", po::value<string>()->default_value(PDNSSYSREPOCONFDIR"/pdns-sysrepo.yaml"), "Configuration file to load.")
    ("loglevel,l", po::value<string>()->default_value("info"), logLevelHelp.c_str())
    ("version,v", "Show the version")
    ("log-timestamps", po::value<bool>()->default_value(true), "Add timestamps to the logs");

  po::variables_map vm;
  try {
    po::store(po::parse_command_line(argc, argv, opts), vm);
    po::notify(vm);
  }
  catch (const boost::program_options::error& e) {
    cerr << fmt::format("Unable to parse commandline arguments: {}", e.what()) << endl;
    return 1;
  }

  if (vm.count("help")) {
    cout << opts << endl;
    return 0;
  }

  if (vm.count("version")) {
    cout << VERSION << endl;
    return 0;
  }

  spdlog::set_pattern("%l - %v");
  if (vm.count("log-timestamps")) {
    if (vm["log-timestamps"].as<bool>()) {
      spdlog::set_pattern("%Y-%m-%d %H:%M:%S.%f - %l - %v");
    }
  }

  if (logLevels.count(vm["loglevel"].as<string>()) == 0) {
    spdlog::error("Unknown loglevel {}", vm["loglevel"].as<string>());
    return 1;
  }
  spdlog::set_level(spdlog::level::from_str(vm["loglevel"].as<string>()));
  spdlog::info("Level set to {}", vm["loglevel"].as<string>());

  try {
    auto myConfig = pdns_conf::Config(vm["config"].as<string>());

    spdlog::debug("Starting connection to sysrepo");
    sysrepo::S_Connection conn(new sysrepo::Connection());

    spdlog::debug("Starting session");
    auto sess = sr::Session(conn);

    try {
      /* This is passed to both the ServerConfigCB and the ZoneCB.
         As the have the same reference, the ServerConfigCB can update the pdns_api::ApiClient with the
         correct config, allowing both the ZoneCB and the ServerConfigCB to work with the API
      */
      auto apiClient = make_shared<pdns_api::ApiClient>();

      spdlog::debug("Registering config change callbacks");
      sysrepo::S_Session sSess(make_shared<sysrepo::Session>(sess));
      auto s = sysrepo::Subscribe(sSess);
      auto cb = pdns_conf::getServerConfigCB(myConfig.getPdnsConfigFilename(), myConfig.getServiceName(), apiClient);
      s.module_change_subscribe("pdns-server", cb, nullptr, nullptr, 0, SR_SUBSCR_ENABLED);

      auto zoneSubscribe = sysrepo::Subscribe(sSess);
      spdlog::debug("done, registring operational zone CB");
      auto zoneCB = pdns_conf::getZoneCB(apiClient);
      zoneSubscribe.oper_get_items_subscribe("pdns-server", "/pdns-server:zones-state", zoneCB);

      spdlog::trace("callbacks registered, registring signal handlers");

      signal(SIGINT, siginthandler);
      signal(SIGSTOP, siginthandler);
      spdlog::trace("signalhandlers registered, notifying systemd we're ready");

      sd_notify(0, "READY=1");
      spdlog::info("Startup complete");

      while (!doExit) {
        sleep(500);
      }

      spdlog::info("Exit requested");
      sd_notify(0, "STOPPING=1");
    }
    catch (const sysrepo::sysrepo_exception& e) {
      auto errs = sess.get_error();
      for (size_t i = 0; i < errs->error_cnt(); i++) {
        spdlog::error("Had an error from session: {}", errs->message(i));
      }
      throw;
    }
  }
  catch (const std::exception& e) {
    spdlog::error("Fatal error: {}", e.what());
    return 1;
  }
  return 0;
}

ext: cc

max_stars_repo_name: pieterlexis/pdns-sysrepo

max_issues_repo_name: pieterlexis/pdns-sysrepo

max_forks_repo_name: pieterlexis/pdns-sysrepo


text:
/**
 * @file    main.cpp
 * @author  Sebastian Maisch <sebastian.maisch@googlemail.com>
 * @date    22.06.2012
 *
 * @brief   Implements the applications entry point for windows.
 */

#include "main.h"
#include "app/FWApplication.h"
#include "app/Configuration.h"
#include "app/GLWindow.h"

#include <fstream>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <FreeImage.h>

/**
 * Handler for FreeImage debug messages.
 * @param fif the free image format
 * @param message the message
 */
void FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message)
{
    LOG(ERROR) << L"FreeImage Error occured:";
    LOG(ERROR) << L"***";
    if (fif != FIF_UNKNOWN) {
        LOG(ERROR) << FreeImage_GetFormatFromFIF(fif) << L" Format";
    }
    LOG(ERROR) << message;
    LOG(ERROR) << L"***";
}

/**
 * @brief Window main.
 *
 * @author  Sebastian Maisch
 * @date    22.06.2012
 *
 * @param   hInstance       The instance of the process.
 * @param   hPrevInstance   The previous instance.
 * @param   lpCmdLine       The command line.
 * @param   nCmdShow        Controls how the window is to be shown.
 *
 * @return The applications return code.
 */
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

    g2LogWorker g2log("application", "./", LOG_USE_TIMESTAMPS);
    g2::initializeLogging(&g2log);

    LOG(INFO) << L"Log created.";

    FreeImage_Initialise();
    FreeImage_SetOutputMessage(FreeImageErrorHandler);

    LOG(DEBUG) << L"Trying to load configuration.";
    cgu::Configuration config;
    std::ifstream configFile(configFileName, std::ios::in);
    if (configFile.is_open()) {
        boost::archive::xml_iarchive ia(configFile);
        ia >> BOOST_SERIALIZATION_NVP(config);
    } else {
        LOG(DEBUG) << L"Configuration file not found. Using standard config.";
    }
    LOG(DEBUG) << L"Starting window initialization.";
    // GLWindow win(hInstance, nCmdShow, L"", config);
    cgu::GLWindow win(hInstance, nCmdShow, "", config);
    // FWApplication app(*pwin);
    cguFrameworkApp::FWApplication app(win);

    LOG(DEBUG) << L"Starting main loop.";
    app.StartRun();
    MSG msg = {nullptr, 0, 0, 0, 0, 0, 0};
    auto done = false;
    while (app.IsRunning() && !done) {
        while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
            if (WM_QUIT == msg.message) {
                done = true;
            }
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        try {
            app.Step();
        } catch (std::runtime_error e) {
            LOG(ERROR) << L"Could not process frame step: " << e.what() << std::endl << L"Exiting.";
            done = true;
        }
    }
    app.EndRun();
    LOG(DEBUG) << L"Main loop ended (" << static_cast<int>(msg.wParam) << L"). Message: " << msg.message;

    LOG(DEBUG) << L"Exiting application. Saving configuration to file.";
    std::ofstream ofs(configFileName, std::ios::out);
    boost::archive::xml_oarchive oa(ofs);
    oa << BOOST_SERIALIZATION_NVP(config);

    FreeImage_DeInitialise();

    return 0;
}


text:
#include "nao_auto_bridge.h"

#include <boost/algorithm/string/join.hpp>
#include <iostream>
#include <vector>

#include <ros/ros.h>
#include <actionlib/server/simple_action_server.h>
#include <naoqi_bridge_msgs/SpeechWithFeedbackAction.h>
#include <naoqi_bridge_msgs/SetSpeechVocabularyAction.h>
#include <naoqi_bridge_msgs/WordRecognized.h>
#include <std_msgs/String.h>
#include <std_srvs/Empty.h>

using std::string;

void SimulatedNao::OnSpeechActionGoal(const string& text) {
    //Note: We could replicate behaviour
    ROS_INFO("Nao said: %s", text.c_str());
}

void SimulatedNao::OnSpeechVocabularyAction(const std::vector<string>& words) {
    //Note: We could replicate behaviour
    const string joined = boost::algorithm::join(words, ",");
    ROS_INFO("Words recognized set: %s", joined.c_str());
}

void SimulatedNao::OnSpeech(const string& text) {
    //Note: We could replicate behaviour
    ROS_INFO("Nao said: %s", text.c_str());
}

void SimulatedNao::OnReconfigure() {
    //Note: We could replicate behaviour
    ROS_INFO("Speech reconfigured");
}

void SimulatedNao::OnStartRecognition() {
    //Note: We could replicate behaviour
    if (!this->speech_data.recognition_started) {
        ROS_INFO("Recognition started");
        this->speech_data.recognition_started = true;
    }
    else {
        ROS_INFO("Tried to start recognition, but it was already started by another node");
    }
}

void SimulatedNao::OnStopRecognition() {
    //Note: We could replicate behaviour
    if (this->speech_data.recognition_started) {
        ROS_INFO("Recognition stopped");
        this->speech_data.recognition_started = false;
    }
    else {
        ROS_INFO("Tried top stop recognition, but it is already stopped");
    }
}

namespace BridgeNaoSpeech {
    std::unique_ptr<actionlib::SimpleActionServer<naoqi_bridge_msgs::SpeechWithFeedbackAction>> act_srv_speech_action_goal;
    std::unique_ptr<actionlib::SimpleActionServer<naoqi_bridge_msgs::SetSpeechVocabularyAction>> act_srv_speech_vocabulary_action;

    ros::Subscriber sub_speech;
    ros::ServiceServer srv_reconfigure,
                       srv_start_recognition,
                       srv_stop_recognition;

    void on_speech_action_goal(
        const naoqi_bridge_msgs::SpeechWithFeedbackGoalConstPtr &goal
    ) {
        nao_connection.OnSpeechActionGoal(goal->say);
        naoqi_bridge_msgs::SpeechWithFeedbackResult result;
        act_srv_speech_action_goal->setSucceeded(result);
    }

    void on_speech_vocabulary_action(
        const naoqi_bridge_msgs::SetSpeechVocabularyGoalConstPtr &goal
    ) {
        nao_connection.OnSpeechVocabularyAction(goal->words);
        naoqi_bridge_msgs::SetSpeechVocabularyResult result;
        act_srv_speech_vocabulary_action->setSucceeded(result);
    }

    void on_speech(
        const std_msgs::StringConstPtr &msg
    ) {
        nao_connection.OnSpeech(msg->data);
    }

    bool on_reconfigure(
        std_srvs::Empty::Request &req,
        std_srvs::Empty::Response &resp
    ){
        nao_connection.OnReconfigure();
        return true;
    }

    bool on_start_recognition(
        std_srvs::Empty::Request &req,
        std_srvs::Empty::Response &resp
    ){
        nao_connection.OnStartRecognition();
        return true;
    }

    bool on_stop_recognition(
        std_srvs::Empty::Request &req,
        std_srvs::Empty::Response &resp
    ){
        nao_connection.OnStopRecognition();
        return true;
    }

    void init(ros::NodeHandle &n) {
        std::string voice, language;
        float volume;
        std::vector<std::string> vocabulary;
        bool enable_audio_expression, enable_visual_expression, word_spoting;

        n.param("voice", voice, std::string(""));
        n.param("language", language, std::string(""));
        n.param("volume", volume, 0.0f);
        n.param("vocabulary", vocabulary, std::vector<std::string>());
        n.param("enable_audio_expression", enable_audio_expression, false);
        n.param("enable_visual_expression", enable_visual_expression, false);
        n.param("word_spoting", word_spoting, false);

        act_srv_speech_action_goal =
        std::unique_ptr<actionlib::SimpleActionServer<naoqi_bridge_msgs::SpeechWithFeedbackAction>>(
            new actionlib::SimpleActionServer<naoqi_bridge_msgs::SpeechWithFeedbackAction>(n, "speech_action/goal", on_speech_action_goal, true));
        act_srv_speech_vocabulary_action =
        std::unique_ptr<actionlib::SimpleActionServer<naoqi_bridge_msgs::SetSpeechVocabularyAction>>(
            new actionlib::SimpleActionServer<naoqi_bridge_msgs::SetSpeechVocabularyAction>(n, "/speech_vocabulary_action/goal", on_speech_vocabulary_action, true));

        sub_speech = n.subscribe("speech", 1000, on_speech);

        srv_reconfigure = n.advertiseService("reconfigure", on_reconfigure);
        srv_start_recognition = n.advertiseService("start_recognition", on_start_recognition);
        srv_stop_recognition = n.advertiseService("stop_recognition", on_stop_recognition);
    }
}


text:
#include <fstream>
#include <boost/ref.hpp>
#include <boost/python.hpp>
#include <boost/python/make_constructor.hpp>
#include <boost/python/raw_function.hpp>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/ndarrayobject.h>
#include "picpac.h"
#include "picpac-cv.h"
using namespace boost::python;
using namespace picpac;

namespace {

template <typename T>
T *get_ndarray_data (object &o) {
    PyArrayObject *nd = reinterpret_cast<PyArrayObject *>(o.ptr());
    return reinterpret_cast<T*>(PyArray_DATA(nd));
}

class NumpyBatchImageStream: public BatchImageStream {
public:
    NumpyBatchImageStream (std::string const &path, Config const &c)
        : BatchImageStream(fs::path(path), c) {
        import_array();
    }
    tuple next () {
        vector<npy_intp> images_dims;
        vector<npy_intp> labels_dims;
        next_shape(&images_dims, &labels_dims);
        object images = object(boost::python::handle<>(PyArray_SimpleNew(images_dims.size(), &images_dims[0], NPY_FLOAT)));
        CHECK(images.ptr());
        float *images_buf = get_ndarray_data<float>(images);
        object labels = object(boost::python::handle<>(PyArray_SimpleNew(labels_dims.size(), &labels_dims[0], NPY_FLOAT)));
        CHECK(labels.ptr());
        float *labels_buf = get_ndarray_data<float>(labels);
        unsigned padding;
        next_fill(images_buf, labels_buf, &padding);
        return make_tuple(images, labels, padding);
    }
};

object create_image_stream (tuple args, dict kwargs) {
    object self = args[0];
    CHECK(len(args) > 1);
    string path = extract<string>(args[1]);
    NumpyBatchImageStream::Config config;
    /*
    bool train = extract<bool>(kwargs.get("train", true));
    unsigned K = extract<unsigned>(kwargs.get("K", 1));
    unsigned fold = extract<unsigned>(kwargs.get("fold", 0));
    if (K <= 1) {
        if (!train) {
            config.loop = false;
            config.reshuffle = false;
        }
    }
    else {
        config.kfold(K, fold, train);
    }
    */
#define PICPAC_CONFIG_UPDATE(C, P) \
    C.P = extract<decltype(C.P)>(kwargs.get(#P, C.P))
    PICPAC_CONFIG_UPDATE_ALL(config);
#undef PICPAC_CONFIG_UPDATE
    return self.attr("__init__")(path, config);
};

object return_iterator (tuple args, dict kwargs) {
    object self = args[0];
    self.attr("reset")();
    return self;
};

class Writer: public FileWriter {
public:
    Writer (string const &path): FileWriter(fs::path(path)) {
    }
    void append (float label, string const &buf) {
        Record record(label, buf);
        FileWriter::append(record);
    }

    void append (string const &buf1, string const &buf2) {
        Record record(0, buf1, buf2);
        FileWriter::append(record);
    }

};

void serialize_raw_ndarray (object &obj, std::ostream &os) {
    PyArrayObject *image = reinterpret_cast<PyArrayObject *>(obj.ptr());
    int nd = PyArray_NDIM(image);
    CHECK(nd == 2 || nd == 3);
    auto desc = PyArray_DESCR(image);
    CHECK(desc);
    CHECK(PyArray_EquivByteorders(desc->byteorder, NPY_NATIVE)
            || desc->byteorder == '|') << "Only support native/little endian";
    int elemSize = desc->elsize;
    CHECK(elemSize > 0) << "Flex type not supported.";
    int ch = (nd == 2) ? 1 : PyArray_DIM(image, 2);
    elemSize *= ch; // opencv elements includes all channels
    //CHECK(image->strides[1] == elemSize) << "Image cols must be consecutive";
    int rows = PyArray_DIM(image, 0);
    int cols = PyArray_DIM(image, 1);
    int t = PyArray_TYPE(image);
    int type = 0;
    switch (t) {
        case NPY_UINT8: type = CV_MAKETYPE(CV_8U, ch); break;
        case NPY_INT8: type = CV_MAKETYPE(CV_8S, ch); break;
        case NPY_UINT16: type = CV_MAKETYPE(CV_16U, ch); break;
        case NPY_INT16: type = CV_MAKETYPE(CV_16S, ch); break;
        case NPY_INT32: type = CV_MAKETYPE(CV_32S, ch); break;
        case NPY_FLOAT32: type = CV_MAKETYPE(CV_32F, ch); break;
        case NPY_FLOAT64: type = CV_MAKETYPE(CV_64F, ch); break;
        default: CHECK(0) << "type not supported: " << t;
    }
    int stride = PyArray_STRIDE(image, 0);
    CHECK(stride == cols * elemSize) << "bad stride";
    os.write(reinterpret_cast<char const *>(&type), sizeof(type));
    os.write(reinterpret_cast<char const *>(&rows), sizeof(rows));
    os.write(reinterpret_cast<char const *>(&cols), sizeof(cols));
    os.write(reinterpret_cast<char const *>(&elemSize), sizeof(elemSize));
    char const *off = PyArray_BYTES(image);
    for (int i = 0; i < rows; ++i) {
        os.write(off, cols * elemSize);
        off += stride;
    }
}

string encode_raw_ndarray (object &obj) {
    std::ostringstream ss;
    serialize_raw_ndarray(obj, ss);
    return ss.str();
}

void write_raw_ndarray (string const &path, object &obj) {
    std::ofstream os(path.c_str(), std::ios::binary);
    serialize_raw_ndarray(obj, os);
}

void (Writer::*append1) (float, string const &) = &Writer::append;
void (Writer::*append2) (string const &, string const &) = &Writer::append;

void translate_eos (EoS const &)
{
    // Use the Python 'C' API to set up an exception object
    PyErr_SetNone(PyExc_StopIteration);
}

}

BOOST_PYTHON_MODULE(_picpac)
{
    scope().attr("__doc__") = "PicPoc Python API";
    register_exception_translator<EoS>(&translate_eos);
    class_<NumpyBatchImageStream::Config>("ImageStreamParams", init<>());
    class_<NumpyBatchImageStream, boost::noncopyable>("ImageStream", no_init)
        .def("__init__", raw_function(create_image_stream), "exposed ctor")
        .def("__iter__", raw_function(return_iterator))
        .def(init<string, NumpyBatchImageStream::Config const&>()) // C++ constructor not exposed
        .def("next", &NumpyBatchImageStream::next)
        .def("size", &NumpyBatchImageStream::size)
        .def("reset", &NumpyBatchImageStream::reset)
        .def("categories", &NumpyBatchImageStream::categories)
    ;
    class_<Writer>("Writer", init<string>())
        .def("append", append1)
        .def("append", append2)
    ;
    def("encode_raw", ::encode_raw_ndarray);
    def("write_raw", ::write_raw_ndarray);
}


text:
#include <bits/stdc++.h>
#include <boost/asio.hpp>
#include <functional>
using boost::asio::ip::tcp;
class Socket_Core
{
private:
    /* data */

    void first_accept()
    {
        acceptor_->async_accept(
            [this](boost::system::error_code ec, tcp::socket _socket) {
                if (!ec)
                {
                    this->socket_ = new tcp::socket(std::move(_socket));
                    this->do_regist();
                    this->do_accept();
                }
                else
                {
                    // std::cout << ec.value() << std::endl;
                }
            });
    }
    void do_accept()
    {
        acceptor_->async_accept(
            [this](boost::system::error_code ec, tcp::socket _socket) {
                if (!ec)
                {
                    delete this->socket_;
                    this->socket_ = new tcp::socket(std::move(_socket));
                    this->do_regist();
                }
                else
                {
                    // std::cout << ec << std::endl;
                    // std::cout << ec.value() << std::endl;
                }
            });
    }

    void do_read_len()
    {
        boost::asio::async_read(*this->socket_, boost::asio::buffer(this->rcv_len, 10),
                                [this](boost::system::error_code ec, std::size_t /*length*/) {
                                    if (!ec)
                                    {
                                        int len = atoi(this->rcv_len);
                                        this->message_remain_to_read = len;

                                        this->do_read();
                                    }
                                    else
                                    {
                                        if (ec.value() == 2)
                                        {
                                            printf("断开连接");
                                        }

                                        // std::cout << ec.value() << std::endl;
                                    }
                                });
    }
    void do_read()
    {
        int len_to_read = this->one_socket_len;
        if (len_to_read > this->message_remain_to_read)
        {
            len_to_read = this->message_remain_to_read;
        }

        boost::asio::async_read(*this->socket_, boost::asio::buffer(this->message_read, len_to_read),
                                [this](boost::system::error_code ec, std::size_t /*length*/) {
                                    this->message_remain_to_read -= this->one_socket_len;

                                    if (!ec)
                                    {
                                        if (this->message_remain_to_read > 0)
                                        {

                                            this->message_read += this->one_socket_len;
                                            this->do_read();
                                        }
                                        else
                                        {
                                            this->message_read = this->message_read_head;
                                            // std::cout << this->message_read << std::endl;
                                            //读完了,在这里放回调,先别急着清空鸭
                                            // std::cout<<"为啥来了的消息不进回调?"<<std::endl;
                                            this->Recive_Callback(this->message_read);
                                            // std::cout<<"为啥来了的消息不进回调?"<<std::endl;
                                            memset(this->message_read, 0, this->max_len);
                                            this->message_remain_to_read = 0;
                                            this->do_read_len();
                                        }
                                    }
                                    else
                                    {
                                        if (ec.value() == 2)
                                        {
                                            printf("断开连接");
                                        }

                                        std::cout << ec.value() << std::endl;
                                    }
                                });
    }
    void do_write_len()
    {
        char msg_len[11];
        sprintf(msg_len, "%10d", this->message_remain_to_write);
        boost::asio::async_write(*socket_, boost::asio::buffer(msg_len, 10),
                                 [this](boost::system::error_code ec, std::size_t /*length*/) {
                                     if (!ec)
                                     {
                                         do_write();
                                     }

                                     else
                                     {
                                        //  std::cout << ec.value() << std::endl;
                                     }
                                 });
    }
    void do_write()
    {
        int len_to_write = this->one_socket_len;
        if (len_to_write > this->message_remain_to_write)
        {
            len_to_write = this->message_remain_to_write;
        }

        boost::asio::async_write(*socket_,
                                 boost::asio::buffer(this->message_write, len_to_write),
                                 [this](boost::system::error_code ec, std::size_t /*length*/) {
                                     this->message_remain_to_write -= this->one_socket_len;
                                     if (!ec)
                                     {
                                         if (this->message_remain_to_write > 0)
                                         {
                                             this->message_write += this->one_socket_len;
                                             do_write(); //继续写
                                         }
                                         else
                                         {
                                             this->message_remain_to_write = 0;
                                             this->message_write = this->message_write_head;
                                             memset(this->message_write, 0, this->max_len);
                                         }
                                     }

                                     else
                                     {
                                        //  std::cout << ec.value() << std::endl;
                                     }
                                 });
    }

    void do_regist()
    {
        do_read_len();
    }
    char *message_write_head = NULL;
    char *message_read_head = NULL;
    char rcv_len[11];
    boost::asio::io_context *io_context_ = NULL;
    tcp::socket *socket_ = NULL;
    tcp::acceptor *acceptor_ = NULL;

    char *message_write = NULL;
    char *message_read = NULL;
    int message_remain_to_write = 0;
    int message_remain_to_read = 0;

public:
    const int max_len = 1000000;
    const int one_socket_len = 2048;
    Socket_Core(const char *host, const char *port);
    Socket_Core(int port);
    Socket_Core(const char *port);
    ~Socket_Core();
    std::function<void(const char *)> Recive_Callback;
    void RegistCallback( std::function<void(const char *)> Recive_Callback)
    {
        this->Recive_Callback=Recive_Callback;
    }
    void Write(char *msg)
    {
        int len = strnlen(msg, max_len);
        this->message_remain_to_write = len;

        strncpy(this->message_write, msg, len);
        if (this->socket_ == NULL)
        {
            printf("NO Socket Available!");
        }
        else
        {
            do_write_len();
        }
    }
};

//客户端构造
Socket_Core::Socket_Core(const char *host, const char *port)
{
    this->io_context_ = new boost::asio::io_context();
    this->message_read = (char *)malloc(max_len);
    this->message_write = (char *)malloc(max_len);
    this->message_write_head = this->message_write;
    this->message_read_head = this->message_read;

    tcp::resolver resolver = tcp::resolver(*this->io_context_);

    this->socket_ = new tcp::socket(*this->io_context_);

    boost::asio::connect(*this->socket_, resolver.resolve(host, port));

    do_regist();
    std::thread *t = new std::thread([this]() { this->io_context_->run(); });
}

//服务器构造
Socket_Core::Socket_Core(int port)
{
    this->io_context_ = new boost::asio::io_context();
    this->message_read = (char *)malloc(max_len);
    this->message_write = (char *)malloc(max_len);
    this->message_write_head = this->message_write;
    this->message_read_head = this->message_read;

    this->acceptor_ = new tcp::acceptor(*this->io_context_, tcp::endpoint(tcp::v4(), port));
    first_accept();

    std::thread *t = new std::thread([this]() { this->io_context_->run(); });
}

Socket_Core::Socket_Core(const char*port):Socket_Core(atoi(port))
{

}

Socket_Core::~Socket_Core()
{
    //还没写析构
}

max_stars_repo_name: I-Rinka/Socket-Long-Connect

max_issues_repo_name: I-Rinka/eXecutive-Socket

max_forks_repo_name: I-Rinka/eXecutive-Socket


text:
#include "memory.h"

#include <array>

#ifdef __EMSCRIPTEN__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-constant-out-of-range-compare"
#include <boost/interprocess/mapped_region.hpp>
#pragma clang diagnostic pop
#else
#include <boost/interprocess/mapped_region.hpp>
#endif

#include <cmath>
#include <cstdint>
#include <functional>
#include <iostream>
#include <string>

#ifdef _DEBUG
thread_local bool debug_ = false;
auto operator new(size_t size) -> void * {
  auto *address = malloc(size);
  if (debug_) {
    std::cout << address << " - malloc " << size << "bytes" << std::endl;
  }
  return address;
}

void operator delete(void *address) noexcept {
  if (debug_) {
    std::cout << address << " - free" << std::endl;
  }
  free(address);
}
#endif

namespace utils {

#ifdef _DEBUG
void set_debug(bool debug) { debug_ = debug; }
#endif

using std::cout;
using std::endl;

void display_sizeof_values() {
  cout << "Size of char : " << sizeof(char) << " byte" << endl;
  cout << "Size of int : " << sizeof(int) << " bytes" << endl;
  cout << "Size of short int : " << sizeof(short int) << " bytes" << endl;
  cout << "Size of long int : " << sizeof(long int) << " bytes" << endl;
  cout << "Size of signed long int : " << sizeof(signed long int) << " bytes"
       << endl;
  cout << "Size of unsigned long int : " << sizeof(unsigned long int)
       << " bytes" << endl;
  cout << "Size of float : " << sizeof(float) << " bytes" << endl;
  cout << "Size of double : " << sizeof(double) << " bytes" << endl;
  cout << "Size of wchar_t : " << sizeof(wchar_t) << " bytes" << endl;
  cout << "Size of size_t : " << sizeof(size_t) << " bytes" << endl;
}

auto getTotalSystemMemory() -> size_t {
  //  auto pages = sysconf(_SC_PHYS_PAGES);
  //  std::cout << "pages=" << pages << std::endl;

  size_t size = boost::interprocess::mapped_region::get_page_size();

  auto page_size = sysconf(_SC_PAGE_SIZE);
  return page_size;
  //  std::cout << "page_size=" << page_size << std::endl;
  //  return pages * page_size;
}

auto prettyBytes(size_t bytes) -> std::string {
  std::array<std::string, 7> suffixes{
      "B", "KB", "MB", "GB", "TB", "PB", "EB",
  };

  uint32_t s = 0;  // which suffix to use
  double count = bytes;
  while (count >= 1024 && s < 7) {
    s++;
    count /= 1024;
  }

  int whole = int(count);
  if (count - floor(count) == 0.0) {
    return std::to_string(whole) + suffixes.at(s);
  } else {
    return std::to_string(count / 100) + suffixes.at(s);
  }
}

}  // namespace utils

max_stars_repo_name: jsonxr/blockworld

max_issues_repo_name: jsonxr/blockworld

max_forks_repo_name: jsonxr/blockworld


text:
#include <huaweicloud/sis/v1/SisClient.h>
#include <huaweicloud/core/utils/MultipartFormData.h>

#include <unordered_set>

#include <boost/algorithm/string/replace.hpp>

template <typename T>
std::string toString(const T value)
{
    std::ostringstream out;
    out << std::setprecision(std::numeric_limits<T>::digits10) << std::fixed << value;
    return out.str();
}

namespace HuaweiCloud {
namespace Sdk {
namespace Sis {
namespace V1 {

using namespace HuaweiCloud::Sdk::Sis::V1::Model;

SisClient::SisClient()
{
}

SisClient::~SisClient()
{
}

ClientBuilder<SisClient> SisClient::newBuilder()
{
    return ClientBuilder<SisClient>("");
}
std::shared_ptr<CollectTranscriberJobResponse> SisClient::collectTranscriberJob(CollectTranscriberJobRequest &request)
{
    std::string localVarPath = "/v1/{project_id}/asr/transcriber/jobs/{job_id}";

    std::map<std::string, std::string> localVarQueryParams;
    std::map<std::string, std::string> localVarHeaderParams;
    std::map<std::string, std::string> localVarFormParams;
    std::map<std::string, std::string> localVarPathParams;
    std::map<std::string, std::shared_ptr<HttpContent>> localVarFileParams;

    localVarPathParams["job_id"] = parameterToString(request.getJobId());

    bool isJson = false;
    bool isMultiPart = false;
    std::string contentType = getContentType("application/json", isJson, isMultiPart);
    localVarHeaderParams["Content-Type"] = contentType;

    std::string localVarHttpBody;

    std::unique_ptr<HttpResponse> res = callApi("GET", localVarPath, localVarPathParams, localVarQueryParams, localVarHeaderParams, localVarHttpBody);

    std::shared_ptr<CollectTranscriberJobResponse> localVarResult = std::make_shared<CollectTranscriberJobResponse>();

    if (!res->getHttpBody().empty()) {
        utility::string_t localVarResponse = utility::conversions::to_string_t(res->getHttpBody());
        web::json::value localVarJson = web::json::value::parse(localVarResponse);
        localVarResult->fromJson(localVarJson);
    }
    localVarResult->setStatusCode(res->getStatusCode());
    localVarResult->setHeaderParams(res->getHeaderParams());
    localVarResult->setHttpBody(res->getHttpBody());

    return localVarResult;
}
std::shared_ptr<CreateVocabularyResponse> SisClient::createVocabulary(CreateVocabularyRequest &request)
{
    std::string localVarPath = "/v1/{project_id}/asr/vocabularies";

    std::map<std::string, std::string> localVarQueryParams;
    std::map<std::string, std::string> localVarHeaderParams;
    std::map<std::string, std::string> localVarFormParams;
    std::map<std::string, std::string> localVarPathParams;
    std::map<std::string, std::shared_ptr<HttpContent>> localVarFileParams;

    bool isJson = false;
    bool isMultiPart = false;
    std::string contentType = getContentType("application/json;charset=UTF-8", isJson, isMultiPart);
    localVarHeaderParams["Content-Type"] = contentType;

    std::string localVarHttpBody;
    if (isJson) {
        web::json::value localVarJson;
        localVarJson = ModelBase::toJson(request.getBody());
        localVarHttpBody = utility::conversions::to_utf8string(localVarJson.serialize());
    }

    std::unique_ptr<HttpResponse> res = callApi("POST", localVarPath, localVarPathParams, localVarQueryParams, localVarHeaderParams, localVarHttpBody);

    std::shared_ptr<CreateVocabularyResponse> localVarResult = std::make_shared<CreateVocabularyResponse>();

    if (!res->getHttpBody().empty()) {
        utility::string_t localVarResponse = utility::conversions::to_string_t(res->getHttpBody());
        web::json::value localVarJson = web::json::value::parse(localVarResponse);
        localVarResult->fromJson(localVarJson);
    }
    localVarResult->setStatusCode(res->getStatusCode());
    localVarResult->setHeaderParams(res->getHeaderParams());
    localVarResult->setHttpBody(res->getHttpBody());

    return localVarResult;
}
std::shared_ptr<DeleteVocabularyResponse> SisClient::deleteVocabulary(DeleteVocabularyRequest &request)
{
    std::string localVarPath = "/v1/{project_id}/asr/vocabularies/{vocabulary_id}";

    std::map<std::string, std::string> localVarQueryParams;
    std::map<std::string, std::string> localVarHeaderParams;
    std::map<std::string, std::string> localVarFormParams;
    std::map<std::string, std::string> localVarPathParams;
    std::map<std::string, std::shared_ptr<HttpContent>> localVarFileParams;

    localVarPathParams["vocabulary_id"] = parameterToString(request.getVocabularyId());

    bool isJson = false;
    bool isMultiPart = false;
    std::string contentType = getContentType("application/json", isJson, isMultiPart);
    localVarHeaderParams["Content-Type"] = contentType;

    std::string localVarHttpBody;

    std::unique_ptr<HttpResponse> res = callApi("DELETE", localVarPath, localVarPathParams, localVarQueryParams, localVarHeaderParams, localVarHttpBody);

    std::shared_ptr<DeleteVocabularyResponse> localVarResult = std::make_shared<DeleteVocabularyResponse>();

    if (!res->getHttpBody().empty()) {
        utility::string_t localVarResponse = utility::conversions::to_string_t(res->getHttpBody());
        web::json::value localVarJson = web::json::value::parse(localVarResponse);
        localVarResult->fromJson(localVarJson);
    }
    localVarResult->setStatusCode(res->getStatusCode());
    localVarResult->setHeaderParams(res->getHeaderParams());
    localVarResult->setHttpBody(res->getHttpBody());

    return localVarResult;
}
std::shared_ptr<PushTranscriberJobsResponse> SisClient::pushTranscriberJobs(PushTranscriberJobsRequest &request)
{
    std::string localVarPath = "/v1/{project_id}/asr/transcriber/jobs";

    std::map<std::string, std::string> localVarQueryParams;
    std::map<std::string, std::string> localVarHeaderParams;
    std::map<std::string, std::string> localVarFormParams;
    std::map<std::string, std::string> localVarPathParams;
    std::map<std::string, std::shared_ptr<HttpContent>> localVarFileParams;

    bool isJson = false;
    bool isMultiPart = false;
    std::string contentType = getContentType("application/json;charset=UTF-8", isJson, isMultiPart);
    localVarHeaderParams["Content-Type"] = contentType;

    std::string localVarHttpBody;
    if (isJson) {
        web::json::value localVarJson;
        localVarJson = ModelBase::toJson(request.getBody());
        localVarHttpBody = utility::conversions::to_utf8string(localVarJson.serialize());
    }

    std::unique_ptr<HttpResponse> res = callApi("POST", localVarPath, localVarPathParams, localVarQueryParams, localVarHeaderParams, localVarHttpBody);

    std::shared_ptr<PushTranscriberJobsResponse> localVarResult = std::make_shared<PushTranscriberJobsResponse>();

    if (!res->getHttpBody().empty()) {
        utility::string_t localVarResponse = utility::conversions::to_string_t(res->getHttpBody());
        web::json::value localVarJson = web::json::value::parse(localVarResponse);
        localVarResult->fromJson(localVarJson);
    }
    localVarResult->setStatusCode(res->getStatusCode());
    localVarResult->setHeaderParams(res->getHeaderParams());
    localVarResult->setHttpBody(res->getHttpBody());

    return localVarResult;
}
std::shared_ptr<RecognizeFlashAsrResponse> SisClient::recognizeFlashAsr(RecognizeFlashAsrRequest &request)
{
    std::string localVarPath = "/v1/{project_id}/asr/flash";

    std::map<std::string, std::string> localVarQueryParams;
    std::map<std::string, std::string> localVarHeaderParams;
    std::map<std::string, std::string> localVarFormParams;
    std::map<std::string, std::string> localVarPathParams;
    std::map<std::string, std::shared_ptr<HttpContent>> localVarFileParams;

    bool isJson = false;
    bool isMultiPart = false;
    std::string contentType = getContentType("application/json", isJson, isMultiPart);
    localVarHeaderParams["Content-Type"] = contentType;

    if (request.propertyIsSet()) {
        localVarQueryParams["property"] = parameterToString(request.getProperty());
    }
    if (request.audioFormatIsSet()) {
        localVarQueryParams["audio_format"] = parameterToString(request.getAudioFormat());
    }
    if (request.addPuncIsSet()) {
        localVarQueryParams["add_punc"] = parameterToString(request.getAddPunc());
    }
    if (request.digitNormIsSet()) {
        localVarQueryParams["digit_norm"] = parameterToString(request.getDigitNorm());
    }
    if (request.needWordInfoIsSet()) {
        localVarQueryParams["need_word_info"] = parameterToString(request.getNeedWordInfo());
    }
    if (request.vocabularyIdIsSet()) {
        localVarQueryParams["vocabulary_id"] = parameterToString(request.getVocabularyId());
    }
    if (request.obsBucketNameIsSet()) {
        localVarQueryParams["obs_bucket_name"] = parameterToString(request.getObsBucketName());
    }
    if (request.obsObjectKeyIsSet()) {
        localVarQueryParams["obs_object_key"] = parameterToString(request.getObsObjectKey());
    }
    if (request.firstChannelOnlyIsSet()) {
        localVarQueryParams["first_channel_only"] = parameterToString(request.getFirstChannelOnly());
    }

    std::string localVarHttpBody;

    std::unique_ptr<HttpResponse> res = callApi("POST", localVarPath, localVarPathParams, localVarQueryParams, localVarHeaderParams, localVarHttpBody);

    std::shared_ptr<RecognizeFlashAsrResponse> localVarResult = std::make_shared<RecognizeFlashAsrResponse>();

    if (!res->getHttpBody().empty()) {
        utility::string_t localVarResponse = utility::conversions::to_string_t(res->getHttpBody());
        web::json::value localVarJson = web::json::value::parse(localVarResponse);
        localVarResult->fromJson(localVarJson);
    }
    localVarResult->setStatusCode(res->getStatusCode());
    localVarResult->setHeaderParams(res->getHeaderParams());
    localVarResult->setHttpBody(res->getHttpBody());

    return localVarResult;
}
std::shared_ptr<RecognizeShortAudioResponse> SisClient::recognizeShortAudio(RecognizeShortAudioRequest &request)
{
    std::string localVarPath = "/v1/{project_id}/asr/short-audio";

    std::map<std::string, std::string> localVarQueryParams;
    std::map<std::string, std::string> localVarHeaderParams;
    std::map<std::string, std::string> localVarFormParams;
    std::map<std::string, std::string> localVarPathParams;
    std::map<std::string, std::shared_ptr<HttpContent>> localVarFileParams;

    bool isJson = false;
    bool isMultiPart = false;
    std::string contentType = getContentType("application/json;charset=UTF-8", isJson, isMultiPart);
    localVarHeaderParams["Content-Type"] = contentType;

    std::string localVarHttpBody;
    if (isJson) {
        web::json::value localVarJson;
        localVarJson = ModelBase::toJson(request.getBody());
        localVarHttpBody = utility::conversions::to_utf8string(localVarJson.serialize());
    }

    std::unique_ptr<HttpResponse> res = callApi("POST", localVarPath, localVarPathParams, localVarQueryParams, localVarHeaderParams, localVarHttpBody);

    std::shared_ptr<RecognizeShortAudioResponse> localVarResult = std::make_shared<RecognizeShortAudioResponse>();

    if (!res->getHttpBody().empty()) {
        utility::string_t localVarResponse = utility::conversions::to_string_t(res->getHttpBody());
        web::json::value localVarJson = web::json::value::parse(localVarResponse);
        localVarResult->fromJson(localVarJson);
    }
    localVarResult->setStatusCode(res->getStatusCode());
    localVarResult->setHeaderParams(res->getHeaderParams());
    localVarResult->setHttpBody(res->getHttpBody());

    return localVarResult;
}
std::shared_ptr<RunAudioAssessmentResponse> SisClient::runAudioAssessment(RunAudioAssessmentRequest &request)
{
    std::string localVarPath = "/v1/{project_id}/assessment/audio";

    std::map<std::string, std::string> localVarQueryParams;
    std::map<std::string, std::string> localVarHeaderParams;
    std::map<std::string, std::string> localVarFormParams;
    std::map<std::string, std::string> localVarPathParams;
    std::map<std::string, std::shared_ptr<HttpContent>> localVarFileParams;

    bool isJson = false;
    bool isMultiPart = false;
    std::string contentType = getContentType("application/json;charset=UTF-8", isJson, isMultiPart);
    localVarHeaderParams["Content-Type"] = contentType;

    std::string localVarHttpBody;
    if (isJson) {
        web::json::value localVarJson;
        localVarJson = ModelBase::toJson(request.getBody());
        localVarHttpBody = utility::conversions::to_utf8string(localVarJson.serialize());
    }

    std::unique_ptr<HttpResponse> res = callApi("POST", localVarPath, localVarPathParams, localVarQueryParams, localVarHeaderParams, localVarHttpBody);

    std::shared_ptr<RunAudioAssessmentResponse> localVarResult = std::make_shared<RunAudioAssessmentResponse>();

    if (!res->getHttpBody().empty()) {
        utility::string_t localVarResponse = utility::conversions::to_string_t(res->getHttpBody());
        web::json::value localVarJson = web::json::value::parse(localVarResponse);
        localVarResult->fromJson(localVarJson);
    }
    localVarResult->setStatusCode(res->getStatusCode());
    localVarResult->setHeaderParams(res->getHeaderParams());
    localVarResult->setHttpBody(res->getHttpBody());

    return localVarResult;
}
std::shared_ptr<RunMultiModalAssessmentResponse> SisClient::runMultiModalAssessment(RunMultiModalAssessmentRequest &request)
{
    std::string localVarPath = "/v1/{project_id}/assessment/video";

    std::map<std::string, std::string> localVarQueryParams;
    std::map<std::string, std::string> localVarHeaderParams;
    std::map<std::string, std::string> localVarFormParams;
    std::map<std::string, std::string> localVarPathParams;
    std::map<std::string, std::shared_ptr<HttpContent>> localVarFileParams;

    bool isJson = false;
    bool isMultiPart = false;
    std::string contentType = getContentType("application/json;charset=UTF-8", isJson, isMultiPart);
    localVarHeaderParams["Content-Type"] = contentType;

    std::string localVarHttpBody;
    if (isJson) {
        web::json::value localVarJson;
        localVarJson = ModelBase::toJson(request.getBody());
        localVarHttpBody = utility::conversions::to_utf8string(localVarJson.serialize());
    }

    std::unique_ptr<HttpResponse> res = callApi("POST", localVarPath, localVarPathParams, localVarQueryParams, localVarHeaderParams, localVarHttpBody);

    std::shared_ptr<RunMultiModalAssessmentResponse> localVarResult = std::make_shared<RunMultiModalAssessmentResponse>();

    if (!res->getHttpBody().empty()) {
        utility::string_t localVarResponse = utility::conversions::to_string_t(res->getHttpBody());
        web::json::value localVarJson = web::json::value::parse(localVarResponse);
        localVarResult->fromJson(localVarJson);
    }
    localVarResult->setStatusCode(res->getStatusCode());
    localVarResult->setHeaderParams(res->getHeaderParams());
    localVarResult->setHttpBody(res->getHttpBody());

    return localVarResult;
}
std::shared_ptr<RunTtsResponse> SisClient::runTts(RunTtsRequest &request)
{
    std::string localVarPath = "/v1/{project_id}/tts";

    std::map<std::string, std::string> localVarQueryParams;
    std::map<std::string, std::string> localVarHeaderParams;
    std::map<std::string, std::string> localVarFormParams;
    std::map<std::string, std::string> localVarPathParams;
    std::map<std::string, std::shared_ptr<HttpContent>> localVarFileParams;

    bool isJson = false;
    bool isMultiPart = false;
    std::string contentType = getContentType("application/json;charset=UTF-8", isJson, isMultiPart);
    localVarHeaderParams["Content-Type"] = contentType;

    std::string localVarHttpBody;
    if (isJson) {
        web::json::value localVarJson;
        localVarJson = ModelBase::toJson(request.getBody());
        localVarHttpBody = utility::conversions::to_utf8string(localVarJson.serialize());
    }

    std::unique_ptr<HttpResponse> res = callApi("POST", localVarPath, localVarPathParams, localVarQueryParams, localVarHeaderParams, localVarHttpBody);

    std::shared_ptr<RunTtsResponse> localVarResult = std::make_shared<RunTtsResponse>();

    if (!res->getHttpBody().empty()) {
        utility::string_t localVarResponse = utility::conversions::to_string_t(res->getHttpBody());
        web::json::value localVarJson = web::json::value::parse(localVarResponse);
        localVarResult->fromJson(localVarJson);
    }
    localVarResult->setStatusCode(res->getStatusCode());
    localVarResult->setHeaderParams(res->getHeaderParams());
    localVarResult->setHttpBody(res->getHttpBody());

    return localVarResult;
}
std::shared_ptr<ShowVocabulariesResponse> SisClient::showVocabularies(ShowVocabulariesRequest &request)
{
    std::string localVarPath = "/v1/{project_id}/asr/vocabularies";

    std::map<std::string, std::string> localVarQueryParams;
    std::map<std::string, std::string> localVarHeaderParams;
    std::map<std::string, std::string> localVarFormParams;
    std::map<std::string, std::string> localVarPathParams;
    std::map<std::string, std::shared_ptr<HttpContent>> localVarFileParams;

    bool isJson = false;
    bool isMultiPart = false;
    std::string contentType = getContentType("application/json;charset=UTF-8", isJson, isMultiPart);
    localVarHeaderParams["Content-Type"] = contentType;

    std::string localVarHttpBody;
    if (isJson) {
        web::json::value localVarJson;
        localVarJson = ModelBase::toJson(request.getBody());
        localVarHttpBody = utility::conversions::to_utf8string(localVarJson.serialize());
    }

    std::unique_ptr<HttpResponse> res = callApi("GET", localVarPath, localVarPathParams, localVarQueryParams, localVarHeaderParams, localVarHttpBody);

    std::shared_ptr<ShowVocabulariesResponse> localVarResult = std::make_shared<ShowVocabulariesResponse>();

    if (!res->getHttpBody().empty()) {
        utility::string_t localVarResponse = utility::conversions::to_string_t(res->getHttpBody());
        web::json::value localVarJson = web::json::value::parse(localVarResponse);
        localVarResult->fromJson(localVarJson);
    }
    localVarResult->setStatusCode(res->getStatusCode());
    localVarResult->setHeaderParams(res->getHeaderParams());
    localVarResult->setHttpBody(res->getHttpBody());

    return localVarResult;
}
std::shared_ptr<ShowVocabularyResponse> SisClient::showVocabulary(ShowVocabularyRequest &request)
{
    std::string localVarPath = "/v1/{project_id}/asr/vocabularies/{vocabulary_id}";

    std::map<std::string, std::string> localVarQueryParams;
    std::map<std::string, std::string> localVarHeaderParams;
    std::map<std::string, std::string> localVarFormParams;
    std::map<std::string, std::string> localVarPathParams;
    std::map<std::string, std::shared_ptr<HttpContent>> localVarFileParams;

    localVarPathParams["vocabulary_id"] = parameterToString(request.getVocabularyId());

    bool isJson = false;
    bool isMultiPart = false;
    std::string contentType = getContentType("application/json", isJson, isMultiPart);
    localVarHeaderParams["Content-Type"] = contentType;

    std::string localVarHttpBody;

    std::unique_ptr<HttpResponse> res = callApi("GET", localVarPath, localVarPathParams, localVarQueryParams, localVarHeaderParams, localVarHttpBody);

    std::shared_ptr<ShowVocabularyResponse> localVarResult = std::make_shared<ShowVocabularyResponse>();

    if (!res->getHttpBody().empty()) {
        utility::string_t localVarResponse = utility::conversions::to_string_t(res->getHttpBody());
        web::json::value localVarJson = web::json::value::parse(localVarResponse);
        localVarResult->fromJson(localVarJson);
    }
    localVarResult->setStatusCode(res->getStatusCode());
    localVarResult->setHeaderParams(res->getHeaderParams());
    localVarResult->setHttpBody(res->getHttpBody());

    return localVarResult;
}
std::shared_ptr<UpdateVocabularyResponse> SisClient::updateVocabulary(UpdateVocabularyRequest &request)
{
    std::string localVarPath = "/v1/{project_id}/asr/vocabularies/{vocabulary_id}";

    std::map<std::string, std::string> localVarQueryParams;
    std::map<std::string, std::string> localVarHeaderParams;
    std::map<std::string, std::string> localVarFormParams;
    std::map<std::string, std::string> localVarPathParams;
    std::map<std::string, std::shared_ptr<HttpContent>> localVarFileParams;

    localVarPathParams["vocabulary_id"] = parameterToString(request.getVocabularyId());

    bool isJson = false;
    bool isMultiPart = false;
    std::string contentType = getContentType("application/json;charset=UTF-8", isJson, isMultiPart);
    localVarHeaderParams["Content-Type"] = contentType;

    std::string localVarHttpBody;
    if (isJson) {
        web::json::value localVarJson;
        localVarJson = ModelBase::toJson(request.getBody());
        localVarHttpBody = utility::conversions::to_utf8string(localVarJson.serialize());
    }

    std::unique_ptr<HttpResponse> res = callApi("PUT", localVarPath, localVarPathParams, localVarQueryParams, localVarHeaderParams, localVarHttpBody);

    std::shared_ptr<UpdateVocabularyResponse> localVarResult = std::make_shared<UpdateVocabularyResponse>();

    if (!res->getHttpBody().empty()) {
        utility::string_t localVarResponse = utility::conversions::to_string_t(res->getHttpBody());
        web::json::value localVarJson = web::json::value::parse(localVarResponse);
        localVarResult->fromJson(localVarJson);
    }
    localVarResult->setStatusCode(res->getStatusCode());
    localVarResult->setHeaderParams(res->getHeaderParams());
    localVarResult->setHttpBody(res->getHttpBody());

    return localVarResult;
}
#if defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
std::string SisClient::parameterToString(utility::string_t value)
{
    return utility::conversions::to_utf8string(value);
}
#endif
std::string SisClient::parameterToString(std::string value)
{
    return value;
}

std::string SisClient::parameterToString(int64_t value)
{
    std::stringstream valueAsStringStream;
    valueAsStringStream << value;
    return valueAsStringStream.str();
}

std::string SisClient::parameterToString(int32_t value)
{
    std::stringstream valueAsStringStream;
    valueAsStringStream << value;
    return valueAsStringStream.str();
}

std::string SisClient::parameterToString(float value)
{
    return toString(value);
}

std::string SisClient::parameterToString(double value)
{
    return toString(value);
}

std::string SisClient::parameterToString(const utility::datetime &value)
{
    return utility::conversions::to_utf8string(value.to_string(utility::datetime::ISO_8601));
}
}
}
}
}


text:
#include <iostream>
#include <boost/algorithm/string/replace.hpp>

#ifdef _MSC_VER
    #pragma warning(disable : 4505) // disable "unreferenced local function has been removed" warning
#endif

#include <session_reflection.h>
#include <session_comm.h>

#include "transport_list.h"
#include <bond/comm/layers.h>
#include <bond/comm/timeout.h>
#include <bond/comm/thread_pool.h>

#include <boost/mpl/for_each.hpp>

// TODO: move unit_test_framework.h to cpp/test/inc
#include "../core/unit_test_framework.h"
#include "bonded_cast.h"
#include "test_utils_comm.h"
#include <boost/chrono.hpp>
#include <string.h>
#include <atomic>

using namespace unittest::comm;

template <typename T>
class SessionTransportTests
{
    typedef T Transport;

    class Session_ServiceImpl
        : public SessionService
    {
        void GetInstance(const bond::comm::payload<void>& /* input */,
                         const std::function<void (const bond::comm::message<Result>&)>& callback)
        override
        {
            Result r;
            r.z = m_instance;
            callback(boost::cref(r));
        }

        uint32_t m_instance;

    public:

        Session_ServiceImpl()
            : m_instance()
        {}

        explicit
        Session_ServiceImpl(uint32_t instance)
            : m_instance(instance)
        {}
    };

    static
    void Server1Service1Session2()
    {
        //
        // use two Session_ServiceImpl instances in two separate sessions
        // invoke methods of different instances via two proxies.
        //

        uint32_t instance = 0;
        bond::comm::SocketAddress serverAddress("127.0.0.1", TEST_PORT_1);

        //
        // Start transport.
        //
        Transport transport;
        bond::comm::Server server = transport.Bind(serverAddress,
                                             [&instance](typename Transport::ConnectionContext) mutable
                                             {
                                                const int32_t sessionId = ++instance;
                                                return bond::comm::ServiceTable().Register(boost::make_shared<Session_ServiceImpl>(sessionId), bond::comm::FastWireProtocol());
                                             });

        SessionService::Proxy proxy1(transport.Connect(serverAddress));
        LOOP("Server1Service1Session2 -- First Loop")
        {
            {
                Result result;

                WaitForResponse<Result> syncMessage;
                proxy1.GetInstance(syncMessage);

                syncMessage.Deserialize(result);
                UT_AssertAreEqual(instance, result.z);
            }
        }

        SessionService::Proxy proxy2(transport.Connect(serverAddress));
        LOOP("Server1Service1Session2 -- Second Loop")
        {
            {
                Result result;

                WaitForResponse<Result> syncMessage;
                proxy2.GetInstance(syncMessage);

                syncMessage.Deserialize(result);
                UT_AssertAreEqual(instance, result.z);
            }
        }
    }

    static
    void Server1Service1Session1()
    {
        //
        // share single Session_ServiceImpl instance between two sessions
        // invoke methods of same instance via two proxies.
        //

        const uint32_t instance = 3;

        //
        // Instantiate service tobe shared.
        boost::shared_ptr<Session_ServiceImpl> firstService(new Session_ServiceImpl(instance));
        bond::comm::SocketAddress serverAddress("127.0.0.1", TEST_PORT_1);

        //
        // Start transport.
        //
        Transport transport;

        bond::comm::Server server = transport.Bind(serverAddress,
                                             [firstService](typename Transport::ConnectionContext)
                                             {
                                                return bond::comm::ServiceTable().Register(firstService,
                                                                                bond::comm::FastWireProtocol());
                                             });

        SessionService::Proxy proxy1(transport.Connect(serverAddress));
        SessionService::Proxy proxy2(transport.Connect(serverAddress));

        LOOP("Server1Service1Session1")
        {
            {
                Result result;

                WaitForResponse<Result> syncMessage;
                proxy1.GetInstance(syncMessage);

                syncMessage.Deserialize(result);
                UT_AssertAreEqual(instance, result.z);
            }

            {
                Result result;

                WaitForResponse<Result> syncMessage;
                proxy2.GetInstance(syncMessage);

                syncMessage.Deserialize(result);
                UT_AssertAreEqual(instance, result.z);
            }
        }
    }

public:

    static
    void Initialize()
    {
        std::string name = typeid(Transport).name();

        // Shorten the name.
        boost::algorithm::replace_all(name, "struct ", "");
        boost::algorithm::replace_all(name, "class ", "");
        boost::algorithm::replace_all(name, "bond::transport::", "");
        boost::algorithm::replace_all(name, "bond::", "");

        UnitTestSuite suite(name.c_str());

        suite.AddTestCase(Server1Service1Session1, "Server1Service1Session1");

        suite.AddTestCase(Server1Service1Session2, "Server1Service1Session2");
    }
};

bool init_unit_test()
{
    InitializeTests<SessionTransportTests, bond::comm::FastWireProtocol>();
    return true;
}

max_stars_repo_name: grisharav/bond

max_issues_repo_name: grisharav/bond

max_forks_repo_name: grisharav/bond


text:
#include <iosfwd>

/*
 * avrgo.cpp
 *
 *  Created on: Jul 29, 2011
 *      Author: danny
 */
#define BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS
#define BOOST_MPL_LIMIT_VECTOR_SIZE 50

#include <iostream>
#include <fstream>
#include <typeinfo>
#include <boost/cstdint.hpp>
#include <boost/timer/timer.hpp>

#include "avrsim/avr_instruction_set.hpp"
#include "avrsim/decoder.hpp"
#include "avrsim/avr_core.hpp"
#include "avrsim/instruction_names.hpp"
#include "avrsim/list_parser.hpp"
#include "avrsim/avr_emulator.hpp"
#include "avrsim/precompiled_emulator.hpp"

using boost::uint16_t;
#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/adapted/mpl.hpp>
#include <boost/fusion/include/mpl.hpp>

/**
 * Simple disassembler class.
 *
 * This class, when given an instruction word to 'execute', will print the instruction mnemonic and operands to std::cout.
 */
struct simple_disassembler
{
    template<typename tag>
    void execute( const tag &)
    {
        using avrsim::instructions::instruction_name;
        std::cout << instruction_name<tag>::get() << "\n";
    }
    template<typename tag>
    void execute( const tag &, uint16_t op)
    {
        using avrsim::instructions::instruction_name;
        std::cout << instruction_name<tag>::get() << " " << op << "\n";
    }
    template<typename tag>
    void execute( const tag &, uint16_t op1, uint16_t op2)
    {
        using avrsim::instructions::instruction_name;
        std::cout << instruction_name<tag>::get() << " " << op1 << "," << op2 <<"\n";
    }
};

void decode_and_execute( boost::uint16_t word)
{
    using namespace avrsim;
    simple_disassembler impl;
    typedef  find_decoder<simple_disassembler, avrsim::instructions::list>::type decoder;
    decoder::decode_and_execute( impl, word);
}

/**
 * This class prints a single unpacking instruction and can be used with fusions for_each to print a list of
 * unpacking instructions.
 */
struct unpack_printer
{
    template<int times>
    void operator()( const avrsim::unpacking::bits<times, false> &) const
    {
        std::cout << "shift " << times << "\n";
    }

    template<int times>
    void operator()(const avrsim::unpacking::bits<times, true> &) const
    {
        std::cout << "mask " << times << "\n";
    }
};

int main(int argc, char *argv[])
{
    using namespace avrsim;

    try
    {
        if (argc ==2)
        {
            std::cout << "executing " << argv[1] << '\n';
            std::ifstream assemblyfile{ argv[1]};
            auto listing = parse_listing( assemblyfile);
            precompiled_emulator<avr_core> emulator{16*1024};
            //avr_emulator<avr_core> emulator{16*1024};
            emulator.fillRom( listing.rom);
            {
                boost::timer::auto_cpu_timer t;
                emulator.run( 1000000000); // run for 100M cycles
            }
            std::cout << "ready\n";
            std::cout << emulator.getState().clock_ticks << '\n';
            return 0;

        }
        else
        {
            return -3;
        }
    }
    catch (std::exception &e)
    {
        std::cerr << "something went wrong: " << e.what() << '\n';
        return -2;
    }
}

max_stars_repo_name: DannyHavenith/avrgo

max_issues_repo_name: DannyHavenith/avrgo

max_forks_repo_name: DannyHavenith/avrgo