text:
//  (C) Copyright Edward Diener 2011-2015
//  Use, modification and distribution are subject to 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 <boost/vmd/elem.hpp>
#include <boost/vmd/equal.hpp>
#include <boost/vmd/get_type.hpp>
#include <boost/vmd/not_equal.hpp>
#include <boost/detail/lightweight_test.hpp>

int main()
  {

#if BOOST_PP_VARIADICS

 #define BOOST_VMD_REGISTER_UDEF_CIRCLE (UDEF_CIRCLE)
 #define BOOST_VMD_REGISTER_UDEF_SQUARE (UDEF_SQUARE)
 #define BOOST_VMD_REGISTER_UDEF_TRIANGLE (UDEF_TRIANGLE)
 #define BOOST_VMD_REGISTER_UDEF_HEXAGON (UDEF_HEXAGON)

 #define BOOST_VMD_DETECT_UDEF_CIRCLE_UDEF_CIRCLE
 #define BOOST_VMD_DETECT_UDEF_SQUARE_UDEF_SQUARE
 #define BOOST_VMD_DETECT_UDEF_TRIANGLE_UDEF_TRIANGLE
 #define BOOST_VMD_DETECT_UDEF_HEXAGON_UDEF_HEXAGON

 #define BOOST_VMD_REGISTER_BOOST_VMD_TYPE_UDEF_SHAPES (BOOST_VMD_TYPE_UDEF_SHAPES)

 #define BOOST_VMD_DETECT_BOOST_VMD_TYPE_UDEF_SHAPES_BOOST_VMD_TYPE_UDEF_SHAPES

 #define BOOST_VMD_SUBTYPE_REGISTER_UDEF_CIRCLE (BOOST_VMD_TYPE_UDEF_SHAPES,UDEF_CIRCLE)
 #define BOOST_VMD_SUBTYPE_REGISTER_UDEF_SQUARE (BOOST_VMD_TYPE_UDEF_SHAPES,UDEF_SQUARE)
 #define BOOST_VMD_SUBTYPE_REGISTER_UDEF_TRIANGLE (BOOST_VMD_TYPE_UDEF_SHAPES,UDEF_TRIANGLE)
 #define BOOST_VMD_SUBTYPE_REGISTER_UDEF_HEXAGON (BOOST_VMD_TYPE_UDEF_SHAPES,UDEF_HEXAGON)

 #define BOOST_VMD_SUBTYPE_REGISTER_BOOST_VMD_TYPE_UDEF_SHAPES (BOOST_VMD_TYPE_TYPE,BOOST_VMD_TYPE_UDEF_SHAPES)

 #define A_SEQUENCE UDEF_SQUARE
 #define A_SEQUENCE2 217
 #define A_SEQUENCE3 BOOST_VMD_TYPE_UDEF_SHAPES
 #define A_SEQUENCE4 BOOST_VMD_TYPE_NUMBER

 BOOST_TEST(BOOST_VMD_EQUAL(BOOST_VMD_GET_TYPE(A_SEQUENCE),BOOST_VMD_TYPE_UDEF_SHAPES));
 BOOST_TEST(BOOST_VMD_EQUAL(BOOST_VMD_GET_TYPE(A_SEQUENCE2),BOOST_VMD_TYPE_NUMBER));
 BOOST_TEST(BOOST_VMD_EQUAL(BOOST_VMD_GET_TYPE(A_SEQUENCE3),BOOST_VMD_TYPE_TYPE));
 BOOST_TEST(BOOST_VMD_EQUAL(BOOST_VMD_GET_TYPE(A_SEQUENCE4),BOOST_VMD_TYPE_TYPE));

 #define A_SEQUENCE5 (1,2) UDEF_TRIANGLE

 BOOST_TEST(BOOST_VMD_EQUAL(BOOST_VMD_ELEM(1,A_SEQUENCE5,BOOST_VMD_RETURN_TYPE),(BOOST_VMD_TYPE_UDEF_SHAPES,UDEF_TRIANGLE)));
 BOOST_TEST(BOOST_VMD_EQUAL(BOOST_VMD_ELEM(0,A_SEQUENCE5,BOOST_VMD_RETURN_TYPE),(BOOST_VMD_TYPE_TUPLE,(1,2))));

 #define A_SEQUENCE6 UDEF_CIRCLE
 #define A_SEQUENCE7 168

 BOOST_TEST(BOOST_VMD_EQUAL(A_SEQUENCE6,UDEF_CIRCLE,BOOST_VMD_TYPE_UDEF_SHAPES));
 BOOST_TEST(BOOST_VMD_NOT_EQUAL(A_SEQUENCE6,UDEF_CIRCLE,BOOST_VMD_TYPE_LIST));
 BOOST_TEST(BOOST_VMD_EQUAL(A_SEQUENCE7,168,BOOST_VMD_TYPE_NUMBER));
 BOOST_TEST(BOOST_VMD_NOT_EQUAL(A_SEQUENCE7,168,BOOST_VMD_TYPE_SEQ));

#else

BOOST_ERROR("No variadic macro support");

#endif

  return boost::report_errors();

  }

ext: cxx


text:
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.

/**
 * csv_writer_test.cc
 * Mich, 2015-11-16
 * Copyright (c) 2015 mldb.ai inc. All rights reserved.
 **/

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>
#include "mldb/arch/timers.h"
#include "mldb/utils/testing/fixtures.h"
#include "mldb/vfs/fs_utils.h"
#include "mldb/soa/utils/csv_writer.h"

using namespace std;

struct FileHolder{
    string filename;
    FileHolder(string filename) : filename(filename){}
    ~FileHolder(){
            remove(filename.c_str());
        }
};

BOOST_AUTO_TEST_CASE( test_csv_writer )
{
    stringstream ss;
    CsvWriter csv(ss);
    (csv << "a" << "b" << "cde").endl();
    (csv << 4 << 2 << 345).endl();
    BOOST_REQUIRE_EQUAL(ss.str(), "a,b,cde\n"
                                  "4,2,345\n");
}

BOOST_AUTO_TEST_CASE( test_csv_writer_quote_delimiter )
{
    stringstream ss;
    CsvWriter csv(ss, ';', 'o');
    (csv << "a" << "b" << "cod").endl();
    (csv << 4 << 2 << 345).endl();
    BOOST_REQUIRE_EQUAL(ss.str(), "a;b;ocoodo\n"
                                  "4;2;345\n");
}

ext: cc

max_stars_repo_name: kstepanmpmg/mldb

max_issues_repo_name: tomzhang/mldb

max_forks_repo_name: matebestek/mldb


text: #include <boost/graph/graph_stats.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include "lib/function.hpp"

#include "lib/eval.hpp"
#include "lib/parse.hpp"
#include "util.hpp"
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>

using namespace afct;

class TimesBy : public INativeFunction
{
public:
  explicit TimesBy(int n) : _n(n)
  {}

  Expr call(List& args, std::shared_ptr<Env>) final
  {
    AFCT_ARG_CHECK(
        args.size() == 1 && args[0].is_double(), "Expected 1 double arg");

    return Expr{args[0].get_double() * _n};
  }

private:
  int _n;
};

class IsDefined : public INativeFunction
{
public:
  Expr call(List& args, std::shared_ptr<Env> env) final
  {
    AFCT_ARG_CHECK(
        args.size() == 1 && args[0].is_string(), "Expected 1 string arg");

    return Expr{env->find(args[0].get_string()).has_value()};
  }
};

BOOST_AUTO_TEST_CASE(native_functions)
{
  auto env = Prelude();

  env->set("times2", NativeFunctionToExpr<TimesBy>("times2", 2));
  BOOST_TEST(Eval(std::string("(times2 2.0)"), env) == Expr{4.0});
  BOOST_CHECK_THROW(Eval(std::string("(times2 lambda)"), env), Exception);

  env->set("isdef", NativeFunctionToExpr<IsDefined>("isdef"));
  BOOST_TEST(Eval(std::string(R"((isdef "times2"))"), env) == Expr{true});
  BOOST_TEST(Eval(std::string(R"((isdef "times3"))"), env) == Expr{false});
}

ext: cpp

max_stars_repo_name: intephom/artifact

max_issues_repo_name: intephom/artifact

max_forks_repo_name: intephom/artifact


text:
#include <cmath>
#include <array>
#include <vector>
#include <fstream>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <memory>
#include <boost/program_options.hpp>

#include "TFile.h"
#include "TH2F.h"

namespace cluster_shape_filter {

  static constexpr size_t n_dim = 2;

  using Position = std::array<double, n_dim>;

  struct Limits {
    double down, up;
    Limits() : down(-std::numeric_limits<double>::infinity()), up(std::numeric_limits<double>::infinity()) {}
    Limits(double _down, double _up) : down(_down), up(_up) {}
    double size() const { return std::abs(down - up); }
  };

  using BoxLimits = std::array<Limits, n_dim>;

  struct Point {
    Position x;
    int weight;
    int cluster_index;
  };

  struct Center {
    Position x;
    int n_clusters;
    BoxLimits limits;

    double distance2(const Point& p) const {
      double d = 0;
      for (size_t n = 0; n < x.size(); ++n)
        d += std::pow(x[n] - p.x[n], 2);
      return d;
    }

    double area() const {
      double s = 1;
      for (size_t n = 0; n < limits.size(); ++n)
        s *= limits[n].size();
      return s;
    }
  };

  using AsymmetricCut = std::array<Center, 2>;

  std::ostream& operator<<(std::ostream& os, const AsymmetricCut& c) {
    for (size_t b = 0; b < c.size(); ++b) {
      for (size_t d = 0; d < c[b].limits.size(); ++d) {
        os << " " << c[b].limits[d].down << " " << c[b].limits[d].up;
      }
    }

    for (size_t b = 0; b < c.size(); ++b) {
      const double v = c[b].area() > 0 ? c[b].n_clusters / c[b].area() : 0.;
      os << " " << v << " " << c[b].n_clusters;
    }
    return os;
  }

  template <typename Object>
  Object* ReadObject(TFile& file, const std::string& name) {
    auto object = dynamic_cast<Object*>(file.Get(name.c_str()));
    if (!object) {
      std::ostringstream ss;
      ss << "Object '" << name << "' with type '" << typeid(Object).name() << "' not found in '" << file.GetName()
         << "'.";
      throw std::runtime_error(ss.str());
    }
    return object;
  }

  struct Arguments {
    std::string input, output, map_output;
    double loss{0.005};
    size_t minEntries{100};
    int exMax{10}, eyMax{15};
    bool verbose{false};
  };

  class ClusterAnalyzer {
  public:
    ClusterAnalyzer(const Arguments& _args) : args(_args) {}

    void analyze() {
      static const std::vector<std::string> subName = {"barrel", "endcap"};

      TFile resFile(args.input.c_str(), "READ");
      if (resFile.IsZombie())
        throw std::runtime_error("Input file not opened.");

      std::ofstream outFile;
      outFile.exceptions(std::ofstream::failbit | std::ofstream::badbit);
      outFile.open(args.output);
      std::shared_ptr<std::ofstream> mapFile;
      if (!args.map_output.empty()) {
        mapFile = std::make_shared<std::ofstream>();
        mapFile->exceptions(std::ofstream::failbit | std::ofstream::badbit);
        mapFile->open(args.map_output);
      }

      for (size_t is = 0; is < subName.size(); ++is) {
        for (int ix = 0; ix <= args.exMax; ++ix) {
          std::cout << " " << subName.at(is) << " dx= " << ix << " ";
          for (int iy = 0; iy <= args.eyMax; ++iy) {
            std::ostringstream histName;
            //                    histName << "hrpc_" << is << "_" << ix << "_" << iy;
            histName << "hspc_" << is << "_" << ix << "_" << iy;
            auto histo = ReadObject<TH2F>(resFile, histName.str());

            std::cout << ".";

            // Initial guess
            AsymmetricCut c;
            c[0].n_clusters = 0;
            c[0].x[0] = ix + 1;
            c[0].x[1] = iy + 1;

            c[1].n_clusters = 0;
            c[1].x[0] = -ix - 1;
            c[1].x[1] = -iy - 1;

            std::ostringstream flag;
            flag << subName.at(is) << "_" << ix << "_" << iy;
            process(*histo, c, flag.str());

            if (histo->Integral() >= args.minEntries) {
              // Fix barrel_0_0
              if (is == 0 && ix == 0 && iy == 0) {
                c[0].limits[1].down = 0.;
                c[1].limits[1].up = 0.;
              }

              outFile << is << " " << ix << " " << iy << c << std::endl;
            }

            if (mapFile)
              *mapFile << ix << " " << iy << " " << histo->Integral() << std::endl;
          }
          outFile << std::endl;
          std::cout << std::endl;
          if (mapFile)
            *mapFile << ix << " " << args.eyMax + 1 << " " << 0 << "\n" << std::endl;
        }

        if (mapFile) {
          for (int iy = 0; iy <= args.eyMax + 1; ++iy)
            *mapFile << args.exMax + 1 << " " << iy << " " << 0 << std::endl;
          *mapFile << std::endl << std::endl;
        }

        outFile << std::endl;
      }
    }

  private:
    using HistArray = std::array<std::array<TH1D*, 2>, 2>;

    HistArray CreateHistArray(const std::vector<Point>& points, const TH1D& line) const {
      HistArray x;
      for (size_t n = 0; n < x.size(); ++n) {
        for (size_t d = 0; d < x[n].size(); ++d) {
          std::ostringstream name;
          name << n << "_" << d;
          x[n][d] = dynamic_cast<TH1D*>(line.Clone(name.str().c_str()));
        }
      }

      for (const auto& point : points) {
        for (size_t d = 0; d < x[point.cluster_index].size(); ++d) {
          x[point.cluster_index][d]->Fill(point.x[d], point.weight);
        }
      }
      return x;
    }

    static double getFraction(const TH1D& line, double fraction) {
      double n = line.Integral();
      double s = 0;

      for (int i = 0; i <= line.GetNbinsX() + 1; ++i) {
        s += line.GetBinContent(i);
        if (s > n * fraction) {
          return line.GetXaxis()->GetBinUpEdge(i) -
                 (s - n * fraction) / line.GetBinContent(i) * line.GetXaxis()->GetBinWidth(i);
        }
      }

      throw std::runtime_error("Unable to determine a point for the given fraction.");
    }

    void kMeans(std::vector<Point>& points, AsymmetricCut& c, const TH1D& line) const {
      int changes;
      do {
        changes = 0;

        // Sort point into clusters
        for (auto& point : points) {
          const int n = c[0].distance2(point) < c[1].distance2(point) ? 0 : 1;
          if (n != point.cluster_index) {
            point.cluster_index = n;
            ++changes;
          }
        }

        if (changes != 0) {
          // Re-compute centers
          auto x = CreateHistArray(points, line);

          for (size_t n = 0; n < c.size(); ++n) {
            for (size_t d = 0; d < c[n].x.size(); ++d) {
              c[n].n_clusters = std::ceil(x[n][d]->Integral());
              if (x[n][d]->Integral() > 0)
                c[n].x[d] = getFraction(*x[n][d], 0.5);
            }
          }
        }
      } while (changes != 0);
    }

    void findLimits(const std::vector<Point>& points, AsymmetricCut& c, const TH1D& line) const {
      auto x = CreateHistArray(points, line);

      for (size_t b = 0; b < x.size(); ++b) {
        for (size_t d = 0; d < x[b].size(); ++d) {
          if (x[b][d]->Integral() <= 0)
            continue;
          Limits best_limits;
          for (double f = (args.loss / 2) / 100; f < args.loss / 2 - (args.loss / 2) / 200;
               f += (args.loss / 2) / 100) {
            const Limits limits(getFraction(*x[b][d], f), getFraction(*x[b][d], 1 - (args.loss / 2 - f)));
            if (limits.size() < best_limits.size())
              best_limits = limits;
          }
          c[b].limits[d] = best_limits;
        }
      }
    }

    static void printOut(const TH2F& histo, const AsymmetricCut& c, const std::string& flag) {
      printToFile(histo, "points_" + flag + ".dat");

      std::ofstream limitsFile("limits_" + flag + ".par");
      for (size_t b = 0; b < c.size(); ++b) {
        for (size_t d = 0; d < c[b].limits.size(); ++d) {
          limitsFile << " l" << b << d << "=" << c[b].limits[d].down << std::endl;
          limitsFile << " h" << b << d << "=" << c[b].limits[d].up << std::endl;
        }
      }

      std::ofstream centersFile("centers_" + flag + ".dat");
      for (size_t b = 0; b < c.size(); ++b)
        centersFile << " " << c[b].x[0] << " " << c[b].x[1] << std::endl;
    }

    void process(const TH2F& histo, AsymmetricCut& c, const std::string& flag) {
      std::vector<Point> points;
      points.reserve(histo.GetNbinsX() * histo.GetNbinsY());

      for (int i = 1; i <= histo.GetNbinsX(); ++i) {
        for (int j = 1; j <= histo.GetNbinsY(); ++j) {
          if (histo.GetBinContent(i, j) <= 0)
            continue;
          Point p;
          p.x[0] = histo.GetXaxis()->GetBinCenter(i);
          p.x[1] = histo.GetYaxis()->GetBinCenter(j);
          p.weight = std::ceil(histo.GetBinContent(i, j));
          points.push_back(p);
        }
      }

      auto line = histo.ProjectionY("_py", 0, 0);
      line->Reset();

      kMeans(points, c, *line);
      findLimits(points, c, *line);
      if (args.verbose)
        printOut(histo, c, flag);
    }

    static void printToFile(const TH2F& h2, const std::string& fileName) {
      std::ofstream file;
      file.exceptions(std::ofstream::failbit | std::ofstream::badbit);
      file.open(fileName);

      for (int i = 1; i <= h2.GetNbinsX(); i++) {
        for (int j = 1; j <= h2.GetNbinsY(); j++)
          file << " " << h2.GetXaxis()->GetBinLowEdge(i) << " " << h2.GetYaxis()->GetBinLowEdge(j) << " "
               << h2.GetBinContent(i, j) << "\n";

        file << " " << h2.GetXaxis()->GetBinLowEdge(i) << " " << h2.GetYaxis()->GetXmax() << " 0\n\n";
      }

      for (int j = 1; j <= h2.GetNbinsY(); j++) {
        file << " " << h2.GetXaxis()->GetXmax() << " " << h2.GetYaxis()->GetBinLowEdge(j) << " 0\n";
      }

      file << " " << h2.GetXaxis()->GetXmax() << " " << h2.GetYaxis()->GetXmax() << " 0" << std::endl;
    }

  private:
    const Arguments args;
  };

}  // namespace cluster_shape_filter

int main(int argc, char* argv[]) {
  namespace po = boost::program_options;
  using namespace cluster_shape_filter;

  Arguments args;
  po::options_description desc("Cluster shape filter analyzer");
  std::ostringstream ss_loss;
  ss_loss << std::setprecision(4) << args.loss;
  // clang-format off
  desc.add_options()
      ("help", "print help message")
      ("input", po::value<std::string>(&args.input)->required(), "input file with extracted cluster shapes")
      ("output", po::value<std::string>(&args.output)->required(), "output calibration file")
      ("map-output", po::value<std::string>(&args.map_output)->default_value(""), "output calibration file")
      ("loss",
       po::value<double>(&args.loss)->default_value(args.loss, ss_loss.str()),
       "(1 - efficiency) threshold for the WP definition")
      ("min-entries", po::value<size_t>(&args.minEntries)->default_value(args.minEntries), "")
      ("ex-max", po::value<int>(&args.exMax)->default_value(args.exMax), "")
      ("ey-max", po::value<int>(&args.eyMax)->default_value(args.eyMax), "")
      ("verbose", po::bool_switch(&args.verbose));
  // clang-format on

  try {
    po::variables_map variables;
    po::store(po::command_line_parser(argc, argv).options(desc).run(), variables);
    if (variables.count("help")) {
      std::cout << desc << std::endl;
      return 0;
    }
    po::notify(variables);

    cluster_shape_filter::ClusterAnalyzer analyzer(args);
    analyzer.analyze();

  } catch (po::error& e) {
    std::cerr << "ERROR: " << e.what() << ".\n\n" << desc << std::endl;
  } catch (std::exception& e) {
    std::cerr << "\nERROR: " << e.what() << std::endl;
  }

  return 0;
}

max_stars_repo_name: ckamtsikis/cmssw

max_issues_repo_name: ckamtsikis/cmssw

max_forks_repo_name: ckamtsikis/cmssw


text:
#ifndef ASYNC_STRAND_HPP
#define ASYNC_STRAND_HPP

#include "blub/async/predecl.hpp"
#include "blub/core/globals.hpp"

#include <boost/asio/strand.hpp>

namespace blub
{
namespace async
{

class strand
{
public:
    strand(dispatcher& disp);

    template<typename CompletionHandler>
    void dispatch(CompletionHandler handler)
    {
        m_service.dispatch(handler);
    }

    template<typename CompletionHandler>
    void post(CompletionHandler handler)
    {
        m_service.post(handler);
    }

    bool isRunningInThisThread() const
    {
        return m_service.running_in_this_thread();
    }

    const dispatcher &getDispatcher() const;

private:
    dispatcher &m_dispatcher;

    boost::asio::strand m_service;

};

}
}

#endif // ASYNC_STRAND_HPP


text:
//          Copyright Gavin Band 2008 - 2012.
// 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 <string>
#include <map>
#include <algorithm>
#include <boost/unordered_map.hpp>
#include <boost/bimap.hpp>
#include "appcontext/CmdLineOptionProcessor.hpp"
#include "appcontext/ApplicationContext.hpp"
#include "appcontext/get_current_time_as_string.hpp"
#include "genfile/MissingValue.hpp"
#include "genfile/string_utils/string_utils.hpp"
#include "components/SNPSummaryComponent/GenomeSequence.hpp"
#include "components/SNPSummaryComponent/DBOutputter.hpp"
#include "qcdb/Storage.hpp"
#include "qcdb/FlatTableDBOutputter.hpp"
#include "qcdb/FlatFileOutputter.hpp"

// #define DEBUG_SELFMAP 1

namespace globals {
	std::string const program_name = "selfmap" ;
	std::string const program_version = "dev" ;
}

namespace {
	double const NA = std::numeric_limits< double >::quiet_NaN() ;
	namespace impl {
		char complement_allele( char a ) {
			switch( a ) {
				case 'A': a = 'T'; break ;
				case 'G': a = 'C'; break ;
				case 'C': a = 'G'; break ;
				case 'T': a = 'A'; break ;
			}
			return a ;
		}

		void reverse_complement( std::string* sequence ) {
			std::reverse( sequence->begin(), sequence->end() ) ;
			std::transform( sequence->begin(), sequence->end(), sequence->begin(), &impl::complement_allele ) ;
		}
	}
}

struct SelfMapOptions: public appcontext::CmdLineOptionProcessor {
	std::string get_program_name() const { return globals::program_name ; }

	void declare_options( appcontext::OptionProcessor& options ) {
		options.set_help_option( "-help" ) ;

		{
			options.declare_group( "Input data options" ) ;
			options[ "-sequence" ]
				.set_description( "Specify the path of a file containing sequence to load." )
				.set_is_required()
				.set_takes_single_value() ;
			;
		}
		{
			options.declare_group( "Analysis options" ) ;
			options[ "-range" ]
				.set_description( "Specify one or more ranges of SNPs to operate on. "
					"Each range should be in the format CC:xxxx-yyyy where CC is the chromosome and xxxx and yyyy are the "
					"start and end coordinates, or just xxxx-yyyy which matches that range from all chromosomes. "
					"You can also omit either of xxxx or yyyy to get all SNPs from the start or to the end of a chromosome." )
				.set_takes_values_until_next_option()
				.set_is_required() ;
			options[ "-kmer-size" ]
				.set_is_required()
				.set_takes_single_value()
				.set_description( "Specify the size of kmer to compute using." )
			;
			options[ "-analysis-name" ]
				.set_description( "Specify a name to label results from this analysis with.  (This applies to modules which store their results in a qcdb file.)" )
				.set_takes_single_value()
				.set_default_value( "qctool analysis" ) ;
			options[ "-analysis-chunk" ]
				.set_description( "Specify a name denoting the current genomic region or chunk on which this is run.  This is intended for use in parallel environments." )
				.set_takes_single_value()
				.set_default_value( genfile::MissingValue() ) ;
			options[ "-table-name" ]
				.set_description( "Specify a name for the table to use when using -flat-table." )
				.set_takes_single_value() ;
		}
		{
			options.declare_group( "Options affecting output" ) ;
			options[ "-o" ]
				.set_description( "Specify the path to the output file." )
				.set_is_required()
				.set_takes_single_value() ;
			options[ "-include-diagonal" ]
				.set_description( "Specify whether selfmap should include uniquely-mapping kmers in the output. "
					"To reduce the size of the output, these are not output by default." )
				;
			options[ "-log" ]
				.set_description( "Specify the path of a log file; all screen output will be copied to the file." )
				.set_takes_single_value() ;
		}

		{
			options.declare_group( "Analysis options" ) ;
		}
	}
} ;

struct SelfMapApplication: public appcontext::ApplicationContext {
public:
	typedef std::map< std::string, std::vector< std::string > > GroupDefinition ;
	typedef std::map< std::string, std::vector< std::string > > ValueListSet ;

public:
	SelfMapApplication( int argc, char **argv ):
		appcontext::ApplicationContext(
			globals::program_name,
			globals::program_version,
			std::auto_ptr< appcontext::OptionProcessor >( new SelfMapOptions ),
			argc,
			argv,
			"-log"
		),
		m_sequence( GenomeSequence::create( options().get< std::string >( "-sequence" ), get_ui_context().get_progress_context( "Reading sequence" ) ) ),
		m_kmer_size( options().get< std::size_t >( "-kmer-size" ) ),
		m_ranges( parse_ranges( options().get_values< std::string >( "-range" ) ) )
	{
	}

    std::vector< genfile::GenomePositionRange > parse_ranges( std::vector< std::string > const& spec ) {
        std::vector< genfile::GenomePositionRange > result ;
        result.reserve( spec.size() ) ;
        for( std::size_t i = 0; i < spec.size(); ++i ) {
            result.push_back( genfile::GenomePositionRange::parse( spec[i] ) ) ;
        }
        return result ;
    }

public:
	void pre_summarise() {
		get_ui_context().logger() << "SelfMapApplication: running with the following parameters:\n"
			<< "Sequence: " << m_sequence->get_summary( "  " ) << "\n"
			<< "Ranges: " ;
            for( std::size_t i = 0; i < m_ranges.size(); ++i ) {
                get_ui_context().logger() << ( i > 0 ? " " : "" ) << m_ranges[i] ;
            }

			get_ui_context().logger() << "\n" << "kmer size: " << m_kmer_size << "bp.\n" ;
	}
	void run() {
		try {
			unsafe_run() ;
		}
		catch( genfile::InputError const& e ) {
			get_ui_context().logger() << "!! (" << e.what() << "): " << e.format_message() << ".\n" ;
			throw appcontext::HaltProgramWithReturnCode( -1 ) ;
		}
		catch( db::StatementPreparationError const& e ) {
			get_ui_context().logger() << "!! (" << e.what() << "): " << e.description() << ".\n" ;
			throw appcontext::HaltProgramWithReturnCode( -1 ) ;
		}
	}
	void post_summarise() {
	}
private:
	GenomeSequence::UniquePtr m_sequence ;
	std::size_t m_kmer_size ;
	std::vector< genfile::GenomePositionRange > m_ranges ;

	typedef std::map< std::string, std::vector< std::pair< genfile::GenomePosition, char > > > KmerMap ;
	//typedef boost::unordered_map< std::string, std::vector< std::pair< genfile::Position, char > > > KmerMap ;
	typedef boost::bimap< std::string, std::pair< genfile::GenomePosition, char > > KmerBimap ;

private:

	void unsafe_run() {
		KmerMap kmerMap ;
        for( std::size_t i = 0; i < m_ranges.size(); ++i ) {
            process_range( m_ranges[i], &kmerMap ) ;
        }
		write_output( kmerMap, open_storage() ) ;
    }

    void process_range(
        genfile::GenomePositionRange const& genomeRange,
        KmerMap* result
    ) {
        using genfile::string_utils::to_string ;

        genfile::GenomePosition const& start = genomeRange.start() ;
        genfile::GenomePosition const& end = genomeRange.end() ;
		if( end.position() <= start.position() + m_kmer_size ) {
			get_ui_context().logger() << "!! No kmers of length " << m_kmer_size << " in the range (of length " << ( end.position() - start.position() + 1 ) << ")\n" ;
			throw appcontext::HaltProgramWithReturnCode( -1 ) ;
		}
		std::string kmer ;

		GenomeSequence::PhysicalSequenceRange range = m_sequence->get_sequence( start.chromosome(), start.position(), end.position() ) ;
		genfile::Position rangePosition = range.first.start().position() ;
		GenomeSequence::ConstSequenceIterator kmer_start = range.second.first ;
		GenomeSequence::ConstSequenceIterator kmer_end = kmer_start + m_kmer_size ;

		{
			appcontext::UIContext::ProgressContext progress_context = get_ui_context().get_progress_context( "Processing kmers (" + to_string( genomeRange ) + ")" ) ;

			for( ; kmer_end != range.second.second; ++kmer_start, ++kmer_end, ++rangePosition ) {
				progress_context.notify_progress( rangePosition, range.first.end().position() - m_kmer_size ) ;
	#if DEBUG_SELFMAP
				std::cerr << "SelfMapApplication:run(): looking at kmer: " << kmer << "...\n" ;
	#endif
				kmer.assign( kmer_start, kmer_end ) ;
				genfile::string_utils::to_upper( &kmer ) ;
				if( kmer.find( 'N' ) == std::string::npos ) {
					(*result)[ kmer ].push_back(
                        std::make_pair(
                            genfile::GenomePosition( start.chromosome(), rangePosition ),
                            '+'
                        )
                    ) ;
					impl::reverse_complement( &kmer ) ;
					(*result)[ kmer ].push_back(
                        std::make_pair(
                            genfile::GenomePosition( start.chromosome(), rangePosition + m_kmer_size ),
                            '-'
                        )
                    ) ;
				}
			}
			progress_context.notify_progress( rangePosition, range.first.end().position() - m_kmer_size ) ;
		}

#if DEBUG_SELFMAP
			std::cerr << "SelfMapApplication:run(): kmerMap.size() = " << result->size() << ".\n" ;
#endif
	}

	qcdb::Storage::SharedPtr open_storage() const {
		qcdb::Storage::SharedPtr storage ;
		std::string const& filename = options().get< std::string >( "-o" ) ;

		if( filename.size() > 7 && filename.substr( filename.size() - 7, 7 ) == ".sqlite" ) {
			snp_summary_component::DBOutputter::SharedPtr outputter = snp_summary_component::DBOutputter::create_shared(
				options().get< std::string >( "-o" ),
				options().get< std::string >( "-analysis-name" ),
				options().get< std::string >( "-analysis-chunk" ),
				options().get_values_as_map()
			) ;
			if( options().check( "-table-name" )) {
				outputter->set_table_name( options().get< std::string >(  "-table-name" )) ;
			}
			storage = outputter ;
		} else {
			storage = qcdb::FlatFileOutputter::create_shared(
				options().get< std::string >( "-o" ),
				options().get< std::string >( "-analysis-name" ),
				options().get_values_as_map()
			) ;
		}
		return storage ;
	}

	void write_output( KmerMap const& kmerMap, qcdb::Storage::SharedPtr storage ) {
		appcontext::UIContext::ProgressContext progress_context = get_ui_context().get_progress_context( "Storing results" ) ;

		storage->add_variable( "orientation" ) ;
		storage->add_variable( "other_chromosome" ) ;
		storage->add_variable( "other_position" ) ;
		storage->add_variable( "other_orientation" ) ;

		bool const include_diagonal = options().check( "-include-diagonal" ) ;
		using genfile::string_utils::to_string ;
		//genfile::GenomePosition position ( m_range.start().chromosome(), 0 ) ;
		KmerMap::const_iterator i = kmerMap.begin() ;
		KmerMap::const_iterator end_i = kmerMap.end() ;
		std::size_t count = 0 ;
		for( ; i != end_i; ++i, ++count ) {
			genfile::GenomePosition const& position = i->second[0].first ;
			genfile::VariantIdentifyingData snp(
				to_string( position ),
				".",
				position,
				i->first, "."
			) ;
			for( std::size_t j = 0; j < i->second.size(); ++j ) {
				if( i->second[j].second == '+' ) {
					snp.set_position( i->second[j].first ) ;
					for( std::size_t k = ( j + ( include_diagonal ? 0 : 1 ) ); k < i->second.size(); ++k ) {
						storage->create_new_variant( snp ) ;
						storage->store_per_variant_data(
							snp,
							"orientation",
							std::string( 1, i->second[j].second )
						) ;
						storage->store_per_variant_data(
							snp,
							"other_chromosome",
							i->second[k].first.chromosome()
						) ;

						storage->store_per_variant_data(
							snp,
							"other_position",
							genfile::VariantEntry::Integer( i->second[k].first.position() )
						) ;

						storage->store_per_variant_data(
							snp,
							"other_orientation",
							std::string( 1, i->second[k].second )
						) ;
					}
				}
			}
			progress_context.notify_progress( count+1, kmerMap.size() ) ;
		}

		storage->finalise() ;
	}
} ;

int main( int argc, char** argv ) {
	try {
		SelfMapApplication app( argc, argv ) ;
		app.pre_summarise() ;
		app.run() ;
		app.post_summarise() ;
	}
	catch( appcontext::HaltProgramWithReturnCode const& e ) {
		return e.return_code() ;
	}
	return 0 ;
}

max_stars_repo_name: CreRecombinase/qctool

max_issues_repo_name: CreRecombinase/qctool

max_forks_repo_name: CreRecombinase/qctool


text:
#include <frovedis.hpp>
#include <frovedis/matrix/sliced_vector.hpp>
#include <frovedis/matrix/sliced_matrix.hpp>
#include <frovedis/matrix/pblas_wrapper.hpp>

#define BOOST_TEST_MODULE FrovedisTest
#include <boost/test/unit_test.hpp>

using namespace frovedis;
using namespace std;

BOOST_AUTO_TEST_CASE( frovedis_test )
{
    int argc = 1;
    char** argv = NULL;
    use_frovedis use(argc, argv);

    auto bm = make_blockcyclic_matrix_load<float> ("./sample_6x6");

    // creating slice matrix from blockcyclic matrix (error, invalid range)
    bool error_in_slice_matrix_creation = false;
    sliced_blockcyclic_matrix<float> sm;
    try {
      sm = make_sliced_blockcyclic_matrix<float>(bm,1,1,6,6);
    }
    catch (std::exception& e) {
      error_in_slice_matrix_creation = true;
    }

    // creating slice matrix from blockcyclic matrix (OK)
    sm = make_sliced_blockcyclic_matrix<float>(bm,1,1,4,4);

    // creating slice vectors from slice matrix
    bool error_in_row_vector_creation = false;
    sliced_blockcyclic_vector<float> sv;
    try {
      sv = make_row_vector(sm,4); // error, invalid row-id
    }
    catch (std::exception& e) {
      error_in_row_vector_creation = true;
    }

    // confirming if above expected exceptions occur
    BOOST_CHECK (error_in_slice_matrix_creation);
    BOOST_CHECK (error_in_row_vector_creation);
}

max_stars_repo_name: XpressAI/frovedis

max_issues_repo_name: XpressAI/frovedis

max_forks_repo_name: XpressAI/frovedis


text:
#include "bencher.hpp"
#include "stats.hpp"
#include <boost/scope_exit.hpp>

#include <fcntl.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/tcp.h>

extern std::unique_ptr<moros::Stats> requests;
extern std::unique_ptr<moros::Stats> latency;

namespace moros {

Bencher::Bencher(struct addrinfo addr, std::size_t nconn,
                 const std::string& host, const std::string& req,
                 const SslContext* ssl_ctx, Plugin& plugin)
    : ev_loop_(nconn), addr_(addr), plugin_(plugin) {
    for (std::size_t i = 0; i < nconn; ++i) {
        std::shared_ptr<Connection> c =
            ssl_ctx ? std::make_shared<SslConnection>(ev_loop_, *this, host, req, Ssl(*ssl_ctx), plugin)
                    : std::make_shared<Connection>(ev_loop_, *this, host, req, Ssl(), plugin);
        c->connect();
    }

    start_ = std::chrono::steady_clock::now();
    requests_ = 0;
    ev_loop_.addTimerEvent(std::chrono::milliseconds(100), [this]() {
        if (requests_ > 0) {
            const auto elapsed =
                std::chrono::duration_cast<std::chrono::milliseconds>(
                    std::chrono::steady_clock::now() - start_);
            const double qps = 1000.0 * requests_ / elapsed.count();
            requests->record(qps);

            requests_ = 0;
            start_ = std::chrono::steady_clock::now();
        }
    });

    plugin_.init();
}

void Bencher::run() noexcept {
    ev_loop_.run();
}

void Bencher::stop() noexcept {
    ev_loop_.stop();
}

const struct addrinfo& Bencher::addr() const noexcept {
    return addr_;
}

void Bencher::countReq() noexcept {
    ++requests_;
}

void Bencher::summary() {
    plugin_.summary();
}

Connection::Connection(EventLoop& ev_loop, Bencher& b, const std::string& host,
                       const std::string& req, Ssl ssl, Plugin& plugin)
    : ev_loop_(ev_loop),
      bencher_(b),
      ssl_(std::move(ssl)),
      host_(host),
      req_(req),
      written_(0),
      plugin_(plugin) {
    http_parser_init(&parser_, HTTP_RESPONSE);
    parser_.data = this;

    http_parser_settings_init(&parser_settings_);
    parser_settings_.on_message_complete = [](http_parser* parser) {
        auto c = static_cast<Connection*>(parser->data);

        const unsigned status = parser->status_code;

        Metrics::getInstance().count(Metrics::Kind::COMPLETES);
        c->bencher_.countReq();

        if (status > 399) {
            Metrics::getInstance().count(Metrics::Kind::ESTATUS);
        }

        const auto elapsed =
            std::chrono::duration_cast<std::chrono::milliseconds>(
                std::chrono::steady_clock::now() - c->start_);
        if (!latency->record(elapsed.count())) {
            Metrics::getInstance().count(Metrics::Kind::ETIMEOUT);
        }

        c->plugin_.response(status, std::move(c->headers_), std::move(c->body_));

        if (!http_should_keep_alive(parser)) {
            c->reconnect();
        } else {
            c->written_ = 0;
            c->body_.clear();
            c->headers_.clear();
            c->header_state_ = HeaderState::FIELD;
            http_parser_init(parser, HTTP_RESPONSE);
        }

        return 0;
    };

    if (plugin.wantResponseHeaders()) {
        parser_settings_.on_header_field = [](http_parser* parser,
                                              const char* s, std::size_t len) {
            auto c = static_cast<Connection*>(parser->data);
            if (c->header_state_ == HeaderState::VALUE) {
                c->headers_.push_back('\x01');
                c->header_state_ = HeaderState::FIELD;
            }
            c->headers_.append(s, len);

            return 0;
        };

        parser_settings_.on_header_value = [](http_parser* parser,
                                              const char* s, std::size_t len) {
            auto c = static_cast<Connection*>(parser->data);
            if (c->header_state_ == HeaderState::FIELD) {
                c->headers_.push_back(':');
                c->header_state_ = HeaderState::VALUE;
            }
            c->headers_.append(s, len);

            return 0;
        };
    }

    if (plugin.wantResponseBody()) {
        parser_settings_.on_body = [](http_parser* parser, const char* s,
                                      std::size_t len) {
            auto c = static_cast<Connection*>(parser->data);
            c->body_.append(s, len);

            return 0;
        };
    }
}

void Connection::reconnect() {
    // 延长生命周期，delEvent 会删除 Connection 的拷贝
    auto self = shared_from_this();

    ev_loop_.delEvent(fd_, Mask::READABLE | Mask::WRITABLE);

    close();
    ::close(fd_);
    connect();
}

void Connection::connect() {
    bool dismiss = false;
    BOOST_SCOPE_EXIT_ALL(&) {
        if (!dismiss) {
            Metrics::getInstance().count(Metrics::Kind::ECONNECT);
        }
    };

    int fd = ::socket(bencher_.addr().ai_family,
                      bencher_.addr().ai_socktype | O_NONBLOCK,
                      bencher_.addr().ai_protocol);
    if (fd == -1) {
        return;
    }

    if (::connect(fd, bencher_.addr().ai_addr, bencher_.addr().ai_addrlen) == -1) {
        if (errno != EINPROGRESS) {
            ::close(fd);
            return;
        }
    }

    const int flags = 1;
    ::setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &flags, sizeof(flags));

    auto self = shared_from_this();
    if (!ev_loop_.addEvent(fd, Mask::WRITABLE, [self] { self->connected(); }) ||
        !ev_loop_.addEvent(fd, Mask::READABLE, [self] { self->response(); })) {
        return;
    }

    dismiss = true;

    fd_ = fd;
    written_ = 0;
    body_.clear();
    headers_.clear();
    header_state_ = HeaderState::FIELD;
    http_parser_init(&parser_, HTTP_RESPONSE);
}

void Connection::connected() {
    auto self = shared_from_this();
    if (!ev_loop_.addEvent(fd_, Mask::WRITABLE, [self] { self->request(); })) {
        return;
    }

    request();
}

void Connection::request() {
    if (written_ == 0) {
        plugin_.request(req_);

        start_ = std::chrono::steady_clock::now();
    }

    while (written_ < req_.size()) {
        const char* buf = req_.data() + written_;
        const std::size_t len = req_.size() - written_;

        const ssize_t n = write(buf, len);
        if (n >= 0) {
            written_ += static_cast<std::size_t>(n);
        } else if (errno == EAGAIN) {
            break;
        } else {
            Metrics::getInstance().count(Metrics::Kind::EWRITE);
            reconnect();
        }
    }
}

void Connection::response() {
    ssize_t n = 0;
    while ((n = read(buf_, sizeof(buf_))) > 0) {
        Metrics::getInstance().count(Metrics::Kind::BYTES, n);

        if (http_parser_execute(&parser_, &parser_settings_, buf_, n) != static_cast<std::size_t>(n)) {
            Metrics::getInstance().count(Metrics::Kind::EREAD);
            reconnect();
            return;
        }
    }

    if (n == 0) {
        if (!http_body_is_final(&parser_)) {
            Metrics::getInstance().count(Metrics::Kind::EREAD);
        }
        reconnect();
    } else if (errno != EAGAIN) {
        Metrics::getInstance().count(Metrics::Kind::EREAD);
        reconnect();
    }
}

int Connection::read(char buf[], std::size_t len) noexcept {
    return ::read(fd_, buf, len);
}

int Connection::write(const char buf[], std::size_t len) noexcept {
    return ::write(fd_, buf, len);
}

int Connection::close() noexcept {
    return 0;
}

void SslConnection::connected() {
    auto self = shared_from_this();
    if (!ev_loop_.addEvent(fd_, Mask::WRITABLE, [self]() { self->request(); })) {
        return;
    }

    ssl_.fd(fd_);
    ssl_.sni(host_.c_str());
    ssl_.connect();
}

int SslConnection::read(char buf[], std::size_t len) noexcept {
    return ssl_.read(buf, len);
}

int SslConnection::write(const char buf[], std::size_t len) noexcept {
    return ssl_.write(buf, len);
}

int SslConnection::close() noexcept {
    return ssl_.close();
}

}


text:
#include <appbase/application.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <cstdlib>
#include <filesystem>
#include <iostream>

struct database {};

class chain_plugin : public appbase::plugin<chain_plugin> {
public:
  APPBASE_PLUGIN_REQUIRES();

  void set_program_options(CLI::App& config) override {
    // Create subsection `chain` in TOML config file by add_section.
    auto chain_options = config.add_section("chain", "Chain configuration");

    // Can be called with commandline or set by config file.
    chain_options->add_option("--readonly", "open the database in read only mode");

    // Call group("") not to be listed in commandline options. (config file only options)
    chain_options->add_option("--dbsize", "Minimum size MB of database shared memory file")
      ->default_val(8 * 1024ULL)
      ->group("");

    // A command-line option that doesn't have leading dashes `-` is considered
    // as a positional argument. Refer to CLI11 documentation.

    // Call configurable(false) not to be listed in config file. (commandline only options)
    chain_options->add_flag("--replay", "clear chain database and replay all blocks")->configurable(false);
    chain_options->add_flag("--reset", "clear chain database and block log")->configurable(false);
  }

  void plugin_initialize(const CLI::App& config) {
    std::cout << "initialize chain plugin\n";
  }
  void plugin_startup() {
    std::cout << "starting chain plugin \n";
  }
  void plugin_shutdown() {
    std::cout << "shutdown chain plugin \n";
  }

  database& db() {
    return _db;
  }

private:
  database _db;
};

class net_plugin : public appbase::plugin<net_plugin> {
public:
  APPBASE_PLUGIN_REQUIRES((chain_plugin));

  void set_program_options(CLI::App& config) override {
    auto net_options = config.add_section("net", "Net configuration");

    net_options->add_option("--listen-endpoint", "The local IP address and port to listen for incoming connections.")
      ->default_str("127.0.0.1:9876");
    net_options->add_option("--remote-endpoint", "The IP address and port of a remote peer to sync with.")->take_all();
    net_options->add_option("--public-endpoint", "The public IP address and port that should be advertized to peers.")
      ->default_str("0.0.0.0:9876");
  }

  void plugin_initialize(const CLI::App& config) {
    std::cout << "initialize net plugin\n";
  }
  void plugin_startup() {
    std::cout << "starting net plugin \n";
  }
  void plugin_shutdown() {
    std::cout << "shutdown net plugin \n";
  }
};

int main(int argc, char** argv) {
  try {
    appbase::application app{};
    if (auto arg = std::getenv("HOME")) {
      std::filesystem::path home_dir = arg;
      app.set_home_dir(home_dir / ".app");
    }
    app.set_config_file("app.toml");
    app.register_plugin<net_plugin>();
    app.parse_config(argc, argv);
    if (!app.initialize())
      return -1;
    app.startup();
    app.exec();
  } catch (const boost::exception& e) {
    std::cerr << boost::diagnostic_information(e) << "\n";
  } catch (const std::exception& e) {
    std::cerr << e.what() << "\n";
  } catch (...) {
    std::cerr << "unknown exception\n";
  }
  std::cout << "exited cleanly\n";
  return 0;
}

max_stars_repo_name: noir-protocol/appbase

max_issues_repo_name: noir-protocol/appbase

max_forks_repo_name: noir-protocol/appbase


text:
// Copyright 2016 Glyn Matthews.
// 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 <gtest/gtest.h>
#include <boost/network/protocol/http/client/response.hpp>

using client_response = boost::network::http::client_response;

TEST(http_client_response, construct) {
  ASSERT_NO_THROW(client_response());
}

max_stars_repo_name: yhager/cpp-netlib

max_issues_repo_name: yhager/cpp-netlib

max_forks_repo_name: yhager/cpp-netlib


text:
/* Copyright (C) 2011 Uni Osnabrück
 * This file is part of the LAS VEGAS Reconstruction Toolkit,
 *
 * LAS VEGAS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * LAS VEGAS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
 */

 /*
 * Options.h
 *
 *  Created on: Nov 21, 2010
 *      Author: Thomas Wiemann
 */

#ifndef OPTIONS_H_
#define OPTIONS_H_

#include <iostream>
#include <string>
#include <vector>
#include <boost/program_options.hpp>

using std::ostream;
using std::cout;
using std::endl;
using std::string;
using std::vector;

namespace slam2hdf5
{

using namespace boost::program_options;

/**
 * @brief A class to parse the program options for the reconstruction
 * 		  executable.
 */
class Options {
public:

	/**
	 * @brief 	Ctor. Parses the command parameters given to the main
	 * 		  	function of the program
	 */
	Options(int argc, char** argv);
    virtual ~Options() {};

    string inputDir() const { return m_variables["inputDir"].as<string>(); }

private:

    /// The internally used variable map
    variables_map                   m_variables;

    /// The internally used option description
    options_description             m_descr;

    /// The internally used positional option desription
    positional_options_description  m_pdescr;

};

/// Overlaoeded outpur operator
inline ostream& operator<<(ostream& os, const Options &o)
{
	cout << "##### Program options: " 	<< endl;
    cout << "##### Input dir \t\t: "  << o.inputDir() << endl;
	return os;
}

} // namespace reconstruct

#endif /* OPTIONS_H_ */

max_stars_repo_name: uos/lvr


text:
#include <list>
#include <boost/smart_ptr.hpp>

#include "gtest/gtest.h"

#include "json.hpp"

using boost::shared_ptr;
using std::cout;
using std::endl;
using std::string;
using std::map;
using std::list;
using std::set;

using nlohmann::json;

TEST( JSON, ParseEmpty )
{
  json j = "{}"_json ;
  ASSERT_TRUE( j.empty() );
  ASSERT_FALSE( j.is_null() );
  ASSERT_TRUE( j.is_object() );
}

TEST( JSON, Null )
{
  json j;
  ASSERT_TRUE( j.empty() );
  ASSERT_TRUE( j.is_null() );
  ASSERT_FALSE( j.is_object() );
}

TEST( JSON, Array )
{
  json j = std::vector<int>{} ;
  ASSERT_TRUE( j.empty() );
  ASSERT_FALSE( j.is_null() );
  ASSERT_TRUE( j.is_array() );
  ASSERT_TRUE( j.size() == 0 );
}

TEST( JSON, ParseArray )
{
  json j = "[]"_json ;
  ASSERT_TRUE( j.empty() );
  ASSERT_FALSE( j.is_null() );
  ASSERT_TRUE( j.is_array() );
  ASSERT_TRUE( j.size() == 0 );
}

TEST( JSON, Object )
{
  json j = R"foo(
{ "a": 10,
  "b": "bar"
}
)foo"_json ;

  json j2 = { { "a", 10 }, { "b", "bar" } } ;
  ASSERT_TRUE( j == j2) ;
}

TEST( JSON, Object2 )
{
  json j = R"foo(
{ "1": 10,
  "2": "bar"
}
)foo"_json ;

  ASSERT_TRUE( j.is_object()) ;
}

TEST( JSON, Object2StringException )
{
  json j = "{}"_json ;
  ASSERT_THROW ( j.get<string>() , std::exception ) ;
}

TEST( JSON, NumericLimits )
{
  json j ;
  j = std::numeric_limits<int32_t>::max() ;
  ASSERT_EQ(j.get<int32_t>(), std::numeric_limits<int32_t>::max()) ;

  j = 1ll + (int64_t)std::numeric_limits<int32_t>::max() ;
  ASSERT_EQ(j.get<int64_t>(), 1ll + (int64_t)std::numeric_limits<int32_t>::max()) ;
  ASSERT_NE(j.get<int32_t>(), 1ll + (int64_t)std::numeric_limits<int32_t>::max()) ;
}

max_stars_repo_name: chetmurthy/thrift-nicejson

max_issues_repo_name: chetmurthy/thrift-nicejson

max_forks_repo_name: chetmurthy/thrift-nicejson


text:
#pragma once

#include <JsonhlDeserializer.hpp>
#include <exception>
#include <list>
#include <unordered_map>
#include <stdexcept>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>

namespace dbHL {

    class CommandLauncher {
        private:
            std::unordered_map<std::string, jsonhl::Deserializer> _collections;

        public:
            void dumpFromCollection(const char *collection, const char *path) const;

            void dumpFromCollection(const char *collection) const;

            void dumpFromCollection(const std::string& collection) const;
            void dumpFromCollection(const std::string& collection, const std::string& path) const;

            void collectionsHead() const;

            void loadCollection(const std::string& name, const std::string& file);

            void saveDB(std::string& path);
            void loadDB(std::string& path);

            void RenameCollection(std::string& oldName, std::string& newName);

            void DeleteCollection(std::string& collectionName);

            CommandLauncher();
            ~CommandLauncher();
    };

    class CommandHandler : public CommandLauncher {
        private:
            std::string _bufferInput;
            std::vector<std::string> _bufferInputSplitted;
            bool _inExitstate = false;

        public:
            CommandHandler();
            ~CommandHandler();

        public:
            void HandlerLoaderUsage();
            void HandlerLoaderDB();
            void HandlerLoaderFile();
            void HandlerLoaderMemory();

            void HandlerDumpUsage();
            void HandlerDump();

            void HandlerCollectionUsage();
            void HandlerCollection();

            void HandlerCMD();

            void HandlerRename();
            void HandlerRenameUsage();

            void HandlerSaveUsage();
            void HandlerSave();

            void HandlerDeleteUsage();
            void HandlerDelete();

            void HandlerExit();

            void HandlerUsage();

        public:
            void launchDB();
    };

    void ____MCommandHandlerLauncherLoaderDB(CommandHandler& self);
    void ____MCommandHandlerLauncherLoaderUsage(CommandHandler& self);
    void ____MCommandHandlerLauncherLoaderFile(CommandHandler& self);
    void ____MCommandHandlerLauncherLoaderMemory(CommandHandler& self);
    void ____MCommandHandlerLauncherDump(CommandHandler& self);
    void ____MCommandHandlerLauncherCollection(CommandHandler& self);
    void ____MCommandHandlerLauncherHelp(CommandHandler& self);
    void ____MCommandHandlerLauncherRename(CommandHandler& self);
    void ____MCommandHandlerLauncherDelete(CommandHandler& self);
    void ____MCommandHandlerLauncherExit(CommandHandler& self);
    void ____MCommandHandlerLauncherSave(CommandHandler& self);

    void ____MCommandHandlerLauncher(std::string& buf, CommandHandler& self);
};

max_stars_repo_name: Heliferepo/myDB

max_issues_repo_name: Heliferepo/myDB

max_forks_repo_name: Heliferepo/myDB


text:
// Copyright (C) 2015 Vicente Botet
//
//  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)

#define BOOST_THREAD_VERSION 4
#include <boost/config.hpp>
#if ! defined  BOOST_NO_CXX11_DECLTYPE
#define BOOST_RESULT_OF_USE_DECLTYPE
#endif

#include <boost/thread/future.hpp>
#include <boost/static_assert.hpp>

struct TestCallback
{
  typedef boost::future<void> result_type;

  result_type operator()(boost::future<void> future) const
  {
    future.get();
    return boost::make_ready_future();
  }

  result_type operator()(boost::future<boost::future<void> > future) const
  {
    future.get();
    return boost::make_ready_future();
  }
};

void p1()
{
}

int main()
{
#if ! defined  BOOST_NO_CXX11_DECLTYPE && ! defined  BOOST_NO_CXX11_AUTO_DECLARATIONS
  std::cout << __FILE__ << "[" << __LINE__ << "]" << std::endl;
  {
    auto f1 = boost::make_ready_future().then(TestCallback());
    BOOST_STATIC_ASSERT(std::is_same<decltype(f1), boost::future<boost::future<void> > >::value);
    f1.wait();
  }
  std::cout << __FILE__ << "[" << __LINE__ << "]" << std::endl;
  {
    auto f1 = boost::make_ready_future().then(TestCallback());
    BOOST_STATIC_ASSERT(std::is_same<decltype(f1), boost::future<boost::future<void> > >::value);
    auto f2 = f1.unwrap();
    BOOST_STATIC_ASSERT(std::is_same<decltype(f2), boost::future<void> >::value);
    f2.wait();
  }
  std::cout << __FILE__ << "[" << __LINE__ << "]" << std::endl;
  {
    auto f1 = boost::make_ready_future().then(TestCallback());
    BOOST_STATIC_ASSERT(std::is_same<decltype(f1), boost::future<boost::future<void> > >::value);
    auto f2 = f1.unwrap();
    BOOST_STATIC_ASSERT(std::is_same<decltype(f2), boost::future<void> >::value);
    auto f3 = f2.then(TestCallback());
    BOOST_STATIC_ASSERT(std::is_same<decltype(f1), boost::future<boost::future<void> > >::value);
    f3.wait();
  }
  std::cout << __FILE__ << "[" << __LINE__ << "]" << std::endl;
  {
        boost::make_ready_future().then(
            TestCallback()).unwrap().then(TestCallback()).get();
  }
  std::cout << __FILE__ << "[" << __LINE__ << "]" << std::endl;
  {
    boost::future<void> f = boost::async(p1);
    f.then(
            TestCallback()).unwrap().then(TestCallback()).get();
  }
#endif
  return 0;
}

max_stars_repo_name: Abce/boost

max_issues_repo_name: Abce/boost

max_forks_repo_name: Abce/boost


text:
// Copyright 2021 Peter Dimov.
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt

#include <boost/system/result.hpp>
#include <boost/core/lightweight_test.hpp>
#include <vector>
#include <string>

using namespace boost::system;

struct X
{
    int a;
};

struct Y
{
    int a, b;
};

struct E
{
    std::string v;
};

result<X> fx0()
{
    return {};
}

result<X> fx1()
{
    return {{ 1 }};
}

result<Y> fy0()
{
    return {};
}

result<Y> fy2()
{
    return {{ 1, 2 }};
}

result<X, E> fxe0()
{
    return {};
}

result<X, E> fxe1()
{
    return {{ 1 }};
}

result<std::vector<int>> fv0()
{
    return {};
}

result<std::vector<int>> fv1()
{
    return {{ 1 }};
}

result<std::vector<int>> fv2()
{
    return {{ 1, 2 }};
}

int main()
{
    {
        result<X> r = fx0();

        BOOST_TEST( r.has_value() );

        BOOST_TEST_EQ( r->a, 0 );
    }

    {
        result<X> r = fx1();

        BOOST_TEST( r.has_value() );

        BOOST_TEST_EQ( r->a, 1 );
    }

    {
        result<Y> r = fy0();

        BOOST_TEST( r.has_value() );

        BOOST_TEST_EQ( r->a, 0 );
        BOOST_TEST_EQ( r->b, 0 );
    }

    {
        result<Y> r = fy2();

        BOOST_TEST( r.has_value() );

        BOOST_TEST_EQ( r->a, 1 );
        BOOST_TEST_EQ( r->b, 2 );
    }

    {
        result<X, E> r = fxe0();

        BOOST_TEST( r.has_value() );

        BOOST_TEST_EQ( r->a, 0 );
    }

    {
        result<X, E> r = fxe1();

        BOOST_TEST( r.has_value() );

        BOOST_TEST_EQ( r->a, 1 );
    }

    {
        result<std::vector<int>> r = fv0();

        BOOST_TEST( r.has_value() );

        BOOST_TEST_EQ( r->size(), 0 );
    }

    {
        result<std::vector<int>> r = fv1();

        BOOST_TEST( r.has_value() );

        BOOST_TEST_EQ( r->size(), 1 );
        BOOST_TEST_EQ( r->at(0), 1 );
    }

    {
        result<std::vector<int>> r = fv2();

        BOOST_TEST( r.has_value() );

        BOOST_TEST_EQ( r->size(), 2 );
        BOOST_TEST_EQ( r->at(0), 1 );
        BOOST_TEST_EQ( r->at(1), 2 );
    }

    return boost::report_errors();
}


text:
// Copyright (c) 2019 fortiss GmbH, Julian Bernhard, Klemens Esterle, Patrick
// Hart, Tobias Kessler
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.

#ifndef MODULES_WORLD_WORLD_HPP_
#define MODULES_WORLD_WORLD_HPP_

#include <map>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include <boost/geometry/index/rtree.hpp>
#include "modules/world/evaluation/base_evaluator.hpp"
#include "modules/world/map/roadgraph.hpp"
#include "modules/world/objects/agent.hpp"
#include "modules/world/objects/object.hpp"
#include "modules/world/opendrive/opendrive.hpp"
#include "modules/commons/transformation/frenet.hpp"

namespace modules {
namespace world {

using world::evaluation::EvaluatorPtr;
using world::objects::Agent;
using world::objects::AgentId;
using world::objects::AgentPtr;
using world::objects::ObjectPtr;
using world::map::LaneCorridorPtr;
using modules::commons::transformation::FrenetPosition;

typedef std::map<AgentId, AgentPtr> AgentMap;
typedef std::map<AgentId, ObjectPtr> ObjectMap;
typedef std::map<std::string, modules::world::evaluation::EvaluationReturn>
    EvaluationMap;

using rtree_agent_model =
    boost::geometry::model::box<modules::geometry::Point2d>;
using rtree_agent_id = AgentId;
using rtree_agent_value = std::pair<rtree_agent_model, rtree_agent_id>;
using rtree_agent =
    boost::geometry::index::rtree<rtree_agent_value,
                                  boost::geometry::index::linear<16, 4> >;

typedef std::pair<AgentPtr, FrenetPosition> AgentFrenetPair;

struct FrontRearAgents {
  AgentFrenetPair front;
  AgentFrenetPair rear;
};

class World : public commons::BaseType {
 public:
  explicit World(const commons::ParamsPtr& params);
  explicit World(const std::shared_ptr<World>& world);
  virtual ~World() {}

  //! Getter
  double GetWorldTime() const { return world_time_; }
  world::map::MapInterfacePtr GetMap() const { return map_; }
  AgentMap GetAgents() const { return agents_; }
  AgentPtr GetAgent(AgentId id) const {
    auto agent_it = agents_.find(id);
    if (agent_it != agents_.end()) {
      return agents_.at(id);
    } else {
      return AgentPtr(nullptr);
    }
  }
  ObjectMap GetObjects() const { return objects_; }
  std::map<std::string, EvaluatorPtr> GetEvaluators() const {
    return evaluators_;
  }

  bool GetRemoveAgents() const { return remove_agents_; }

  AgentMap GetNearestAgents(const modules::geometry::Point2d& position,
                            const unsigned int& num_agents) const;

  AgentMap GetAgentsIntersectingPolygon(
      const modules::geometry::Polygon& polygon) const;

  //! Function will yield the front and rear agent (and their frenet
  //! coordinates) in a respective lane_corridor in relation to a given agent.
  //! Agent specified by agent_id might be outside the lane_corridor.
  FrontRearAgents GetAgentFrontRearForId(
      const AgentId& agent_id, const LaneCorridorPtr& lane_corridor) const;

  //! Setter
  void SetMap(const world::map::MapInterfacePtr& map) { map_ = map; }

  std::pair<modules::geometry::Point2d, modules::geometry::Point2d>
  BoundingBox() const {
    return map_->BoundingBox();
  }

  void AddAgent(const AgentPtr& agent);

  void AddObject(const ObjectPtr& object);

  void AddEvaluator(const std::string& name, const EvaluatorPtr& evaluator);

  //! Functions
  void ClearEvaluators() { evaluators_.clear(); }
  void ClearAgents() { agents_.clear(); }
  void ClearObjects() { objects_.clear(); }
  void ClearAll() {
    ClearAgents();
    ClearObjects();
    ClearEvaluators();
  }

  EvaluationMap Evaluate() const;

  bool Valid() const;
  std::vector<ObservedWorld> Observe(const std::vector<AgentId>& agent_ids);
  void Step(const float& delta_time);

  void DoPlanning(const float& delta_time);
  void DoExecution(const float& delta_time);

  void UpdateAgentRTree();
  void RemoveOutOfMapAgents();

  virtual std::shared_ptr<World> Clone() const;
  std::shared_ptr<World> WorldExecutionAtTime(
      const float& execution_time) const;

 private:
  world::map::MapInterfacePtr map_;
  AgentMap agents_;
  ObjectMap objects_;
  std::map<std::string, EvaluatorPtr> evaluators_;
  double world_time_;
  rtree_agent rtree_agents_;
  bool remove_agents_;
};

typedef std::shared_ptr<world::World> WorldPtr;

inline WorldPtr World::Clone() const {
  WorldPtr new_world = std::make_shared<World>(*this);
  new_world->ClearAll();
  for (auto agent = agents_.begin(); agent != agents_.end(); ++agent) {
    new_world->AddAgent(
        std::dynamic_pointer_cast<Agent>(agent->second->Clone()));
  }
  for (auto object = objects_.begin(); object != objects_.end(); ++object) {
    new_world->AddObject(object->second->Clone());
  }
  for (const auto& evaluator : evaluators_) {
    new_world->AddEvaluator(evaluator.first, evaluator.second);
  }
  return new_world;
}

}  // namespace world
}  // namespace modules

#endif  // MODULES_WORLD_WORLD_HPP_

max_stars_repo_name: tom-doerr/bark

max_issues_repo_name: tom-doerr/bark

max_forks_repo_name: tom-doerr/bark


text:
/*!
 * Copyright (C) tkornuta, IBM Corporation 2015-2019
 *
 * 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.
 */
/*!
 * @file: MatrixTests.cpp
 * @Author: Tomasz Kornuta <tkornut@us.ibm.com>
 * @Date:   Nov 22, 2016
 *
 * Copyright (c) 2016, IBM Corporation. All rights reserved.
 *
 */

#include <gtest/gtest.h>

#include <fstream>
// Include headers that implement a archive in simple text format
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

// Redefine word "public" so every class field/method will be accessible for tests.
#define private public
#include <types/Matrix.hpp>

/*!
 * Tests whether matrix has proper dimensions (2x5).
 */
TEST(Matrix, Dimensions2x5) {
	// Default sizes of matrices.
	const size_t N = 2;
	const size_t M = 5;

	mic::types::Matrix<float> nm(N, M);

	ASSERT_EQ(nm.rows(), N);
	ASSERT_EQ(nm.cols(), M);

}

/*!
 * Tests matrix serialization.
 */
TEST(Matrix, Serialization) {
	// Default sizes of matrices.
	const size_t N = 2;
	const size_t M = 5;

	mic::types::Matrix<float> nm(N, M);
	nm.randn();

	const char* fileName = "saved.txt";
	// Save data
	{
		// Create an output archive
		std::ofstream ofs(fileName);
		boost::archive::text_oarchive ar(ofs);
		// Write data
		ar & nm;
//		std::cout << "Saved matrix = " << nm << std::endl;
	}

	// Restore data
	mic::types::Matrix<float> restored_mat;
	restored_mat.randn();

	{
		// Create and input archive
		std::ifstream ifs(fileName);
		boost::archive::text_iarchive ar(ifs);
		// Load data
		ar & restored_mat;
//		std::cout << "Restored matrix = " << restored_mat << std::endl;
	}

	for (size_t i =0; i< (size_t)nm.size(); i++)
		ASSERT_EQ(nm(i), restored_mat(i));

}

/*!
 * Tests assignment operator.
 */
TEST(Matrix, OperatorAssignmentFloat) {
	// Default sizes of matrices.
	const size_t N = 2;
	const size_t M = 5;

	mic::types::Matrix<float> nm(N, M);
	for (size_t i= 0; i<N; i++)
		for (size_t j= 0; j<M; j++)
			nm(i,j) = i*j;

	mic::types::Matrix<float> nm2 = nm;
	for (size_t i= 0; i<N; i++)
		for (size_t j= 0; j<M; j++)
			ASSERT_EQ(nm2(i,j), i*j);

}

/*!
 * Tests enumeration.
 */
TEST(Matrix, Enumeration2x3) {
	// Default sizes of matrices.
	const size_t N = 2;
	const size_t M = 3;

	mic::types::Matrix<float> nm(N, M);
	nm.enumerate();

	for (size_t i =0; i< N*M; i++)
		ASSERT_EQ(nm(i), i);

	/*for(size_t row=0; row<N; row++) {
		for(size_t col=0; col<M; col++)
			std::cout << " nm(" << row << "," << col << ") = " << nm(row,col);
		std::cout << std::endl;
	}//: for*/

	ASSERT_EQ(nm(0,0), 0);
	ASSERT_EQ(nm(0,1), 2);
	ASSERT_EQ(nm(0,2), 4);
	ASSERT_EQ(nm(1,0), 1);
	ASSERT_EQ(nm(1,1), 3);
	ASSERT_EQ(nm(1,2), 5);

	nm.resize(M,N);

	/*for(size_t row=0; row<M; row++) {
		for(size_t col=0; col<N; col++)
			std::cout << " nm(" << row << "," << col << ") = " << nm(row,col);
		std::cout << std::endl;
	}//: for*/

}

/*!
 * Tests functions added to make Eigen-derived Matrix as much compatible to Armadillo-derived Matrix as possible.
 */
TEST(Matrix, ArmadilloCompatibilityTest) {
	// Default sizes of matrices.
	const size_t N = 4;
	const size_t M = 5;

	mic::types::Matrix<float> nm(N, M);
	nm.zeros();

	for (size_t i =0; i< N*M; i++)
		ASSERT_EQ(nm[i], 0);
}

int main(int argc, char **argv) {
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

max_stars_repo_name: kant/mi-algorithms

max_issues_repo_name: kant/mi-algorithms

max_forks_repo_name: kant/mi-algorithms


text:
//[hello

#include <boost/simd/sdk/simd/pack.hpp>
#include <boost/simd/sdk/simd/io.hpp>
#include <boost/simd/include/functions/splat.hpp>
#include <boost/simd/include/functions/plus.hpp>
#include <boost/simd/include/functions/multiplies.hpp>
#include <iostream>

int main()
{
  typedef boost::simd::pack<float> p_t;

  p_t res;
  p_t u(10);
  p_t r = boost::simd::splat<p_t>(11);

  res = (u + r) * 2.f;

  std::cout << res << std::endl;

  return 0;
}
//]


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.
 *
 * @brief unit test for CommonData.*(mainly type covert)
 *
 * @file CommonData.cpp
 * @author: yujiechen
 * @date 2018-08-24
 */
#include <libdevcore/CommonData.h>
#include <libdevcore/Exceptions.h>
#include <libdevcore/vector_ref.h>
#include <test/tools/libutils/TestOutputHelper.h>
#include <boost/test/unit_test.hpp>
#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace dev;
namespace dev
{
namespace test
{
BOOST_FIXTURE_TEST_SUITE(CommonDataTests, TestOutputHelperFixture)

/// test toHex && fromHex && isHex && isHash
BOOST_AUTO_TEST_CASE(testHex)
{
    // toHex && fromHex
    unsigned int round = 10;
    unsigned int size = 10;
    bytes hexVec(size, 0);
    std::string hexStr;
    std::string hexStrWithPrefix;
    std::srand(std::time(nullptr));
    for (unsigned int i = 0; i < round; i++)
    {
        for (unsigned int j = 0; j < size; j++)
        {
            hexVec[j] = std::rand() % 16;
        }
        hexStr = toHex(hexVec);
        hexStrWithPrefix = toHex(hexVec);
        BOOST_CHECK(fromHex(hexStr) == hexVec);
        BOOST_CHECK(fromHex(hexStrWithPrefix) == hexVec);
    }
    // fromHex Exception
    BOOST_REQUIRE_NO_THROW(fromHex("0934xyz", WhenError::DontThrow));
    BOOST_CHECK_THROW(fromHex("0934xyz", WhenError::Throw), BadHexCharacter);
    // isHex && isHash
    BOOST_CHECK(isHex("0934xyz") == false);

    BOOST_CHECK(isHex("0x000abc") == true);
    BOOST_CHECK(isHash<h256>("0x000abc") == false);

    BOOST_CHECK(isHex("000123123") == true);
    BOOST_CHECK(isHash<h256>("000123123") == false);
    BOOST_CHECK(
        isHash<h256>("06d012b348ff19750bd253a1a508064ce7752f0adb8304a4c5bbb63ccc106f0d") == true);
    BOOST_CHECK(
        isHash<h256>("0x06d012b348ff19750bd253a1a508064ce7752f0adb8304a4c5bbb63ccc106f0d") == true);
    BOOST_CHECK(isHash<h128>("b2b4085dcee9c8af9a420fe87dcb7d4b") == true);
    BOOST_CHECK(isHash<h128>("0xb2b4085dcee9c8af9a420fe87dcb7d4b") == true);
}

/// test asString && asBytes
BOOST_AUTO_TEST_CASE(testStringTrans)
{
    std::string tmp_str = "abcdef012343";
    BOOST_CHECK(asString(asBytes(tmp_str)) == tmp_str);
    BOOST_CHECK(asString(asBytes(tmp_str)) == tmp_str);
    // construct random vector
    unsigned int round = 10;
    unsigned int size = 10;
    std::string tmp_str_from_ref;
    bytes tmp_bytes(size, 0);
    for (unsigned int i = 0; i < round; i++)
    {
        for (unsigned int j = 0; j < size; j++)
        {
            tmp_bytes[j] = std::rand();
        }
        tmp_str = asString(tmp_bytes);
        tmp_str_from_ref = asString(ref(tmp_bytes));
        BOOST_CHECK(tmp_str == tmp_str_from_ref);
        BOOST_CHECK(asBytes(tmp_str) == tmp_bytes);
    }
}

/// test asNibbles && toBigEndian && fromBigEndian
BOOST_AUTO_TEST_CASE(testBigEndian)
{
    // check asNibbles
    // asNibbles:Converts a string into the big-endian base-16 stream of integers (NOT ASCII).
    std::string str = "A";
    BOOST_CHECK((asNibbles(bytesConstRef(str))[0]) == 4 && (asNibbles(bytesConstRef(str))[1] == 1));
    // check u256
    u256 number("9832989324908234742342343243243234324324243432432234324");
    u160 number_u160("983298932");
    bytes big_endian_bytes = toBigEndian(number);
    BOOST_CHECK(fromBigEndian<u256>(big_endian_bytes) == number);
    BOOST_CHECK(fromBigEndian<u160>(toBigEndian(number_u160)) == number_u160);
    BOOST_CHECK(fromBigEndian<u256>(toBigEndianString(number)) == number);
    BOOST_CHECK(fromBigEndian<u160>(toBigEndianString(number_u160)) == number_u160);
}
/// test operator+
BOOST_AUTO_TEST_CASE(testOperators)
{
    // test is_pod operator+
    std::string a_str = "abcdef";
    std::string b_str = "01234";
    std::vector<char> a_vec(a_str.begin(), a_str.end());
    std::vector<char> b_vec(b_str.begin(), b_str.end());
    std::vector<char> result = a_vec + b_vec;
    BOOST_CHECK(std::string(result.begin(), result.end()) == (a_str + b_str));
    // test common operator+
    std::vector<std::string> total_array;
    std::vector<std::string> a_str_array;
    a_str_array.push_back("11");
    a_str_array.push_back("22");
    total_array = a_str_array;
    std::vector<std::string> b_str_array;
    b_str_array.push_back("aa");
    b_str_array.push_back("cc");
    total_array.push_back("aa");
    total_array.push_back("cc");
    std::vector<std::string> c_str_array = a_str_array + b_str_array;
    BOOST_CHECK(c_str_array == total_array);

    // test toString
    string32 s_32 = {{'a', 'b', 'c'}};
    std::string s = toString(s_32);
    BOOST_CHECK(s == "abc");
}

BOOST_AUTO_TEST_SUITE_END()
}  // namespace test
}  // namespace dev

max_stars_repo_name: imtypist/FISCO-BCOS

max_issues_repo_name: imtypist/FISCO-BCOS

max_forks_repo_name: imtypist/FISCO-BCOS


text:
#include <boost/cast.hpp>
#include <boost/version.hpp>
#include <gtest/gtest.h>

class TestNumericCast : public ::testing::Test {};

TEST_F(TestNumericCast, ExplicitType) {
    std::vector<double> vs {4.0};
    for(const auto& v : vs) {
        double a = boost::numeric_cast<double>(2)/v;
        EXPECT_DOUBLE_EQ(0.5, a);
    }
}

TEST_F(TestNumericCast, ReceiveAsAuto) {
    std::vector<double> vs {4.0};
    for(const auto& v : vs) {
        auto a = boost::numeric_cast<double>(2)/v;
        EXPECT_DOUBLE_EQ(0.5, a);
    }
}

// These tests cause crashes due to references to temporary objects
// in /usr/include/boost/numeric/conversion/converter_policies.hpp : line 186
#if 0
TEST_F(TestNumericCast, ExplicitRef) {
    std::vector<double> vs {4.0};
    for(const auto& v : vs) {
        double a = boost::numeric_cast<const double&>(2)/v;
        EXPECT_DOUBLE_EQ(0.5, a);
    }
}

TEST_F(TestNumericCast, DeclTypeBoost) {
    std::vector<double> vs {4.0};
    for(const auto& v : vs) {
        auto a = boost::numeric_cast<decltype(v)>(2)/v;
        EXPECT_DOUBLE_EQ(0.5, a);
    }
}

TEST_F(TestNumericCast, DeclTypeStatic) {
    std::vector<double> vs {4.0};
    for(const auto& v : vs) {
        auto a = static_cast<decltype(v)>(2)/v;
        EXPECT_DOUBLE_EQ(0.5, a);
    }
}
#endif

TEST_F(TestNumericCast, RemoveRef) {
    std::vector<double> vs {4.0};
    for(const auto& v : vs) {
        auto a = boost::numeric_cast<std::remove_reference_t<decltype(v)>>(2)/v;
        EXPECT_DOUBLE_EQ(0.5, a);
    }
}

template <typename Target, typename Source,
          std::enable_if_t<
              std::is_arithmetic_v<std::remove_reference_t<Target>>,
              std::nullptr_t> = nullptr>
auto wrap_numeric_cast(Source&& s) {
    return boost::numeric_cast<std::remove_reference_t<Target>>(std::forward<Source>(s));
}

class TestWrapNumericCast : public ::testing::Test {};

TEST_F(TestWrapNumericCast, ExplicitType) {
    std::vector<double> vs {4.0};
    for(const auto& v : vs) {
        double a = wrap_numeric_cast<double>(2)/v;
        EXPECT_DOUBLE_EQ(0.5, a);
    }
}

TEST_F(TestWrapNumericCast, ReceiveAsAuto) {
    std::vector<double> vs {4.0};
    for(const auto& v : vs) {
        auto a = wrap_numeric_cast<double>(2)/v;
        static_assert(std::is_same_v<double, decltype(a)>);
        EXPECT_DOUBLE_EQ(0.5, a);
    }
}

TEST_F(TestWrapNumericCast, ExplicitRef) {
    std::vector<double> vs {4.0};
    for(const auto& v : vs) {
        double a = wrap_numeric_cast<const double&>(2)/v;
        EXPECT_DOUBLE_EQ(0.5, a);
    }
}

TEST_F(TestWrapNumericCast, RefAndAuto) {
    std::vector<double> vs {4.0};
    for(const auto& v : vs) {
        const auto a = wrap_numeric_cast<decltype(v)>(2)/v;
        static_assert(std::is_same_v<const double, decltype(a)>);
        EXPECT_DOUBLE_EQ(0.5, a);
    }
}

int main(int argc, char* argv[]) {
    std::cerr << BOOST_VERSION << std::endl;
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

/*
Local Variables:
mode: c++
coding: utf-8-dos
tab-width: nil
c-file-style: "stroustrup"
End:
*/

max_stars_repo_name: zettsu-t/cPlusPlusFriend

max_issues_repo_name: zettsu-t/cPlusPlusFriend

max_forks_repo_name: zettsu-t/cPlusPlusFriend


text:
// Copyright (c) 2012-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.

#include <sync.h>
#include <test/setup_common.h>

#include <boost/test/unit_test.hpp>

namespace {
template <typename MutexType>
void TestPotentialDeadLockDetected(MutexType& mutex1, MutexType& mutex2)
{
    {
        LOCK2(mutex1, mutex2);
    }
    bool error_thrown = false;
    try {
        LOCK2(mutex2, mutex1);
    } catch (const std::logic_error& e) {
        BOOST_CHECK_EQUAL(e.what(), "potential deadlock detected");
        error_thrown = true;
    }
    #ifdef DEBUG_LOCKORDER
    BOOST_CHECK(error_thrown);
    #else
    BOOST_CHECK(!error_thrown);
    #endif
}
} // namespace

BOOST_FIXTURE_TEST_SUITE(sync_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(potential_deadlock_detected)
{
    #ifdef DEBUG_LOCKORDER
    bool prev = g_debug_lockorder_abort;
    g_debug_lockorder_abort = false;
    #endif

    CCriticalSection rmutex1, rmutex2;
    TestPotentialDeadLockDetected(rmutex1, rmutex2);

    Mutex mutex1, mutex2;
    TestPotentialDeadLockDetected(mutex1, mutex2);

    #ifdef DEBUG_LOCKORDER
    g_debug_lockorder_abort = prev;
    #endif
}

BOOST_AUTO_TEST_CASE(lock_free)
{
    constexpr int num_threads = 10;

    auto testFunc = []() {
        static std::atomic_bool cs_lock;
        static std::atomic_int context(0);
        static std::atomic_int threads(num_threads);

        threads--; // every thread decrements count

        CLockFreeGuard lock(cs_lock);
        context++;
        while (threads > 0); // wait all therads to be here
        BOOST_CHECK_EQUAL(threads.load(), 0); // now they wait for lock
        BOOST_CHECK_EQUAL(context.load(), 1); // but only one operates
        context--;
    };

    std::vector<std::thread> threads;

    for (int i = 0; i < num_threads; i++)
        threads.emplace_back(testFunc);

    for (auto& thread : threads)
        thread.join();
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: kuegi/ain

max_issues_repo_name: kuegi/ain

max_forks_repo_name: kuegi/ain


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

#ifndef OOX_CORE_CONTEXTHANDLER2_HXX
#define OOX_CORE_CONTEXTHANDLER2_HXX

#include <vector>
#include <boost/shared_ptr.hpp>
#include "oox/helper/attributelist.hxx"
#include "oox/helper/binaryinputstream.hxx"
#include "oox/core/contexthandler.hxx"

namespace oox {
namespace core {

// ============================================================================

const sal_Int32 XML_ROOT_CONTEXT    = SAL_MAX_INT32;

// ============================================================================

struct ElementInfo;

/** Helper class that provides a context stack.

    Fragment handlers and context handlers derived from this helper class will
    track the identifiers of the visited elements in a stack. The idea is to
    use the same instance of a fragment handler or context handler to process
    several nested elements in an XML stream. For that, the abstract function
    onCreateContext() has to return 'this' for the passed element.

    Derived classes have to implement the createFastChildContext(),
    startFastElement(), characters(), and endFastElement() functions from the
    com.sun.star.xml.sax.XFastContextHandler interface by simply forwarding
    them to the respective implCreateChildContext(), implStartElement(),
    implCharacters(), and implEndElement() functions of this helper. This is
    implemented already in the classes ContextHandler2 and FragmentHandler2.
    The new abstract functions have to be implemented according to the elements
    to be processed.

    Similarly, for binary import, derived classes have to forward the
    createRecordContext(), startRecord(), and endRecord() functions from the
    ContextHandler class to the implCreateRecordContext(), implStartRecord(),
    and implEndRecord() functions of this helper. Again, this is implemented
    already in the classes ContextHandler2 and FragmentHandler2.
 */
class ContextHandler2Helper
{
public:
    explicit            ContextHandler2Helper( bool bEnableTrimSpace );
    explicit            ContextHandler2Helper( const ContextHandler2Helper& rParent );
    virtual             ~ContextHandler2Helper();

    // allow instances to be stored in ::rtl::Reference
    virtual void SAL_CALL acquire() throw() = 0;
    virtual void SAL_CALL release() throw() = 0;

    // interface --------------------------------------------------------------

    /** Will be called to create a context handler for the passed element.

        Usually 'this' can be returned to improve performance by reusing the
        same instance to process several elements. Used by OOXML import only.
     */
    virtual ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) = 0;

    /** Will be called when a new element has been started.

        This function is called at the context handler returned from
        onCreateContext(), or, for root elements of an XML stream, at the
        fragment handler itself.

        The current element identifier can be accessed with getCurrentElement()
        or isCurrentElement(). Used by OOXML import only.
     */
    virtual void        onStartElement( const AttributeList& rAttribs ) = 0;

    /** Will be called before a new child element starts, or if the current
        element is about to be left.

        This helper function collects all text fragments received by the
        characters() function (such as encoded characters which are passed in
        separate calls to the characters() function), and passes the
        concatenated and trimmed string.

        The current element identifier can be accessed with getCurrentElement()
        or isCurrentElement(). Used by OOXML import only.
     */
    virtual void        onCharacters( const ::rtl::OUString& rChars ) = 0;

    /** Will be called when the current element is about to be left.

        The current element identifier can be accessed with getCurrentElement()
        or isCurrentElement(). Used by OOXML import only.
     */
    virtual void        onEndElement() = 0;

    /** Will be called to create a context handler for the passed record.

        Usually 'this' can be returned to improve performance by reusing the
        same instance to process several records. Used by BIFF import only.
     */
    virtual ContextHandlerRef onCreateRecordContext( sal_Int32 nRecId, SequenceInputStream& rStrm ) = 0;

    /** Will be called when a new record block in a binary stream has been
        started.

        The current record identifier can be accessed with getCurrentElement()
        or isCurrentElement(). Used by BIFF import only.
     */
    virtual void        onStartRecord( SequenceInputStream& rStrm ) = 0;

    /** Will be called when the current record block is about to be left.

        The current record identifier can be accessed with getCurrentElement()
        or isCurrentElement(). Used by BIFF import only.
     */
    virtual void        onEndRecord() = 0;

    // helpers ----------------------------------------------------------------

    /** Returns the identifier of the currently processed element. */
    sal_Int32           getCurrentElement() const;

    /** Returns true, if nElement contains the identifier of the currently
        processed element. */
    inline bool         isCurrentElement( sal_Int32 nElement ) const
                            { return getCurrentElement() == nElement; }

    /** Returns true, if either nElement1 or nElement2 contain the identifier
        of the currently processed element. */
    inline bool         isCurrentElement( sal_Int32 nElement1, sal_Int32 nElement2 ) const
                            { return isCurrentElement( nElement1 ) || isCurrentElement( nElement2 ); }

    /** Returns the identifier of the specified parent element. */
    sal_Int32           getParentElement( sal_Int32 nCountBack = 1 ) const;

    /** Returns true, if nElement contains the identifier of the specified
        parent element. */
    inline sal_Int32    isParentElement( sal_Int32 nElement, sal_Int32 nCountBack = 1 ) const
                            { return getParentElement( nCountBack ) == nElement; }

    /** Returns true, if the element currently processed is the root element of
        the context or fragment handler. */
    bool                isRootElement() const;

    // implementation ---------------------------------------------------------

protected:
    /** Must be called from createFastChildContext() in derived classes. */
    ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler >
                        implCreateChildContext(
                            sal_Int32 nElement,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& rxAttribs );

    /** Must be called from startFastElement() in derived classes. */
    void                implStartElement(
                            sal_Int32 nElement,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& rxAttribs );

    /** Must be called from characters() in derived classes. */
    void                implCharacters( const ::rtl::OUString& rChars );

    /** Must be called from endFastElement() in derived classes. */
    void                implEndElement( sal_Int32 nElement );

    /** Must be called from createRecordContext() in derived classes. */
    ContextHandlerRef   implCreateRecordContext( sal_Int32 nRecId, SequenceInputStream& rStrm );

    /** Must be called from startRecord() in derived classes. */
    void                implStartRecord( sal_Int32 nRecId, SequenceInputStream& rStrm );

    /** Must be called from endRecord() in derived classes. */
    void                implEndRecord( sal_Int32 nRecId );

private:
    ContextHandler2Helper& operator=( const ContextHandler2Helper& );

    ElementInfo&        pushElementInfo( sal_Int32 nElement );
    void                popElementInfo();
    void                processCollectedChars();

private:
    typedef ::std::vector< ElementInfo >        ContextStack;
    typedef ::boost::shared_ptr< ContextStack > ContextStackRef;

    ContextStackRef     mxContextStack;     /// Stack of all processed elements.
    size_t              mnRootStackSize;    /// Stack size on construction time.
    bool                mbEnableTrimSpace;  /// True = trim whitespace in characters().
};

// ============================================================================

class ContextHandler2 : public ContextHandler, public ContextHandler2Helper
{
public:
    explicit            ContextHandler2( ContextHandler2Helper& rParent );
    virtual             ~ContextHandler2();

    // resolve ambiguity from base classes
    virtual void SAL_CALL acquire() throw() { ContextHandler::acquire(); }
    virtual void SAL_CALL release() throw() { ContextHandler::release(); }

    // com.sun.star.xml.sax.XFastContextHandler interface ---------------------

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL
                        createFastChildContext(
                            sal_Int32 nElement,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& rxAttribs )
                            throw(  ::com::sun::star::xml::sax::SAXException,
                                    ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL startFastElement(
                            sal_Int32 nElement,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& rxAttribs )
                            throw(  ::com::sun::star::xml::sax::SAXException,
                                    ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL characters( const ::rtl::OUString& rChars )
                            throw(  ::com::sun::star::xml::sax::SAXException,
                                    ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL endFastElement( sal_Int32 nElement )
                            throw(  ::com::sun::star::xml::sax::SAXException,
                                    ::com::sun::star::uno::RuntimeException );

    // oox.core.ContextHandler interface --------------------------------------

    virtual ContextHandlerRef createRecordContext( sal_Int32 nRecId, SequenceInputStream& rStrm );
    virtual void        startRecord( sal_Int32 nRecId, SequenceInputStream& rStrm );
    virtual void        endRecord( sal_Int32 nRecId );

    // oox.core.ContextHandler2Helper interface -------------------------------

    virtual ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs );
    virtual void        onStartElement( const AttributeList& rAttribs );
    virtual void        onCharacters( const ::rtl::OUString& rChars );
    virtual void        onEndElement();

    virtual ContextHandlerRef onCreateRecordContext( sal_Int32 nRecId, SequenceInputStream& rStrm );
    virtual void        onStartRecord( SequenceInputStream& rStrm );
    virtual void        onEndRecord();
};

// ============================================================================

} // namespace core
} // namespace oox

#endif

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice