text:
/** Copyright 2020 Alibaba Group Holding Limited.

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 "test/giraph_runner.h"

#include <dlfcn.h>
#include <unistd.h>
#include <memory>
#include <string>
#include <utility>

#include <boost/leaf/error.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include "gflags/gflags.h"
#include "gflags/gflags_declare.h"
#include "glog/logging.h"

#include "grape/config.h"

DEFINE_string(vertex_input_format_class, "",
              "java class defines the vertex input format");
DEFINE_string(edge_input_format_class, "",
              "java class defines the edge input format");
DEFINE_string(vertex_output_format_class, "",
              "java class defines the output format");
DEFINE_string(user_app_class, "", "app class to run");
DEFINE_string(vertex_output_path, "", "output file path");
DEFINE_string(master_compute_class, "", "master compute class");
DEFINE_string(aggregator_class, "", "aggregator class");
DEFINE_string(message_combiner_class, "", "combiner for message processing");
DEFINE_string(resolver_class, "", "resolver for graph loading");
DEFINE_string(worker_context_class, "", "worker context");
DEFINE_string(lib_path, "",
              "path for dynamic lib where the desired entry function exists");
DEFINE_string(loading_thread_num, "1",
              "number of threads will be used in loading the graph");
DEFINE_string(efile, "", "path to efile");
DEFINE_string(vfile, "", "path to vfile");
DEFINE_string(giraph_driver_class,
              "com.alibaba.graphscope.app.GiraphComputationAdaptor",
              "the driver app used in java");
// DEFINE_string(java_driver_context,
//              "com.alibaba.graphscope.context.GiraphComputationAdaptorContext",
//              "the driver context used in java");
DEFINE_bool(serialize, false, "whether to serialize loaded graph.");
DEFINE_bool(deserialize, false, "whether to deserialize graph while loading.");
DEFINE_string(serialize_prefix, "",
              "where to load/store the serialization files");
DEFINE_bool(grape_loader, false,
            "whether to use grape loader rather than udf loader");
DEFINE_bool(directed, true, "load direct graph or indirect graph");
DEFINE_string(ipc_socket, "/tmp/vineyard.sock", "vineyard socket");
DEFINE_string(jar_name, "", "user jar name,full path");
DEFINE_string(edge_manager, "default",
              "type of edge manager, default, eager or laze.");
DEFINE_int32(query_times, 1, "How many times to repeat");
DEFINE_string(frag_ids, "", "concatenation of frag strings");
DEFINE_int32(concurrency, 1, "How many thread to invoke when computing");

// put all flags in a json str
std::string flags2JsonStr() {
  boost::property_tree::ptree pt;
  pt.put("vertex_input_format_class", FLAGS_vertex_input_format_class);
  pt.put("edge_input_format_class", FLAGS_edge_input_format_class);
  pt.put("vertex_output_format_class", FLAGS_vertex_output_format_class);
  pt.put("app_class", FLAGS_giraph_driver_class);  // giraph driver class
  pt.put("user_app_class", FLAGS_user_app_class);
  pt.put("vertex_output_path", FLAGS_vertex_output_path);
  pt.put("master_compute_class", FLAGS_master_compute_class);
  pt.put("aggregator_class", FLAGS_aggregator_class);
  pt.put("message_combiner_class", FLAGS_message_combiner_class);
  pt.put("resolver_class", FLAGS_resolver_class);
  pt.put("worker_context_class", FLAGS_worker_context_class);
  pt.put("lib_path", FLAGS_lib_path);
  pt.put("loading_thread_num", FLAGS_loading_thread_num);
  pt.put("efile", FLAGS_efile);
  pt.put("vfile", FLAGS_vfile);
  pt.put("serialize", FLAGS_serialize);
  pt.put("deserialize", FLAGS_deserialize);
  pt.put("serialize_prefix", FLAGS_serialize_prefix);
  pt.put("grape_loader", FLAGS_grape_loader);
  pt.put("directed", FLAGS_directed);
  pt.put("ipc_socket", FLAGS_ipc_socket);
  pt.put("jar_name", FLAGS_jar_name);
  pt.put("edge_manager", FLAGS_edge_manager);
  pt.put("query_times", FLAGS_query_times);
  pt.put("frag_ids", FLAGS_frag_ids);
  pt.put("concurrency", FLAGS_concurrency);

  std::stringstream ss;
  boost::property_tree::json_parser::write_json(ss, pt);
  return std::move(ss.str());
}

int main(int argc, char* argv[]) {
  FLAGS_stderrthreshold = 0;

  grape::gflags::SetUsageMessage(
      "Usage: mpiexec [mpi_opts] ./giraph_runner [options]");
  if (argc == 1) {
    gflags::ShowUsageWithFlagsRestrict(argv[0], "giraph-runner");
    exit(1);
  }
  grape::gflags::ParseCommandLineFlags(&argc, &argv, true);
  grape::gflags::ShutDownCommandLineFlags();

  google::InitGoogleLogging("giraph-runner");
  google::InstallFailureSignalHandler();

  VLOG(1) << "Finish option parsing";

  std::string params = flags2JsonStr();
  gs::Init(params);
  gs::CreateAndQuery(params);
  gs::Finalize();
  VLOG(1) << "Finish Querying.";

  google::ShutdownGoogleLogging();
}

max_stars_repo_name: wuyueandrew/GraphScope

max_issues_repo_name: lnfjpt/GraphScope

max_forks_repo_name: lnfjpt/GraphScope


text:
#define BOOST_TEST_MODULE MyTest
#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>
#include "pose.h"
#include <cmath>
#include <iostream>

using namespace std;

BOOST_AUTO_TEST_CASE( test_pose )
{
    Pose p = Pose (2,4,40,5,30) ;
    Pose p2 = Pose (1,3,50,6,20);

    cout << "check creation of a pose" << endl;
    BOOST_CHECK_EQUAL( p.getX(), 2 );
    BOOST_CHECK_EQUAL(p.getY(),4);
    BOOST_CHECK_EQUAL(p.getOrientation(),40);
    BOOST_CHECK_EQUAL(p.getR(), 5);
    BOOST_CHECK_EQUAL(p.getPhi(), 30);

    cout << "check distance" << endl ;
    BOOST_CHECK_EQUAL(p.getDistance(p2),sqrt(2));
}

// EVERYTHING WORK LIKE A CHARM

ext: cpp


text:
#pragma once // header guard

#include <Eigen/Sparse>
#include <Eigen/Eigenvalues>

#include <cmath>

//! Shortcut for container vector of nodes/weights
using vector = Eigen::VectorXd;

//! Structure containing a Quadrature rule on [-1,1], comprised of weights and nodes
struct QuadRule {
    vector weights;
    vector nodes;
};

//! \brief Golub-Welsh implementation 5.3.35
//! \param[in] n number of Gauss nodes
//! \return structure QuadRule containing nodes and wights of gauss Quadrature
QuadRule gauleg(unsigned int n);

ext: hpp

max_stars_repo_path: Nummerical Methods for CSE/PS11/templates_ps11/gauleg.hpp

max_stars_repo_name: valentinjacot/backupETHZ

max_issues_repo_name: valentinjacot/backupETHZ

max_forks_repo_name: valentinjacot/backupETHZ


text:
#include "mongodb_store/message_store.h"
#include "geometry_msgs/Pose.h"
#include <boost/foreach.hpp>

#include <sstream>
#include <cassert>

using namespace geometry_msgs;
using namespace mongodb_store;
using namespace std;
/**
 * This tutorial demonstrates simple sending of messages over the ROS system.
 */
int main(int argc, char **argv)
{
	ros::init(argc, argv, "example_mongodb_store_cpp_client");
	ros::NodeHandle nh;

	//Create object which does the work for us.
	MessageStoreProxy messageStore(nh);

	//This is the message we want to store
	Pose p;
	string name("my pose");
	//Insert something with a name, storing id too
	string id(messageStore.insertNamed(name, p));
	cout<<"Pose \""<<name<<"\" inserted with id "<<id<<endl;

	p.position.z = 666;
	messageStore.updateID(id, p);

	// now test it worked
	assert(messageStore.queryID<Pose>(id).first->position.z == 666);

	vector< boost::shared_ptr<Pose> > results;

	//Get it back, by default get one
	if(messageStore.queryNamed<Pose>(name, results)) {

		BOOST_FOREACH( boost::shared_ptr<Pose> p,  results)
		{
			ROS_INFO_STREAM("Got by name: " << *p);
		}
	}

	if(messageStore.queryID<Pose>(id, results)) {

		BOOST_FOREACH( boost::shared_ptr<Pose> p,  results)
		{
			ROS_INFO_STREAM("Got by ID: " << *p);
		}

	}

	p.position.x = 999;
	messageStore.updateNamed(name, p);

	results.clear();
	// try to get it back with an incorrect name, so get None instead
	messageStore.queryNamed<Pose>("my favourite position", results);
	BOOST_FOREACH( boost::shared_ptr<Pose> p,  results)
	{
		ROS_INFO_STREAM("Got: " << *p);
	}

	results.clear();
	// get all poses, should show updated named position
	messageStore.query<Pose>(results);
	BOOST_FOREACH( boost::shared_ptr<Pose> p,  results)
	{
		ROS_INFO_STREAM("Got: " << *p);
	}

        messageStore.query<Pose>(results, mongo::BSONObj(), mongo::BSONObj(),mongo::BSONObj(), false, 2); // limit=2
        ROS_INFO_STREAM("Got: " << results.size() << " messages.");

	messageStore.deleteID(id);

	results.clear();
	if(messageStore.queryID<Pose>(id, results)) {

		BOOST_FOREACH( boost::shared_ptr<Pose> p,  results)
		{
			ROS_INFO_STREAM("Got by ID: " << *p);
		}

	}
	return 0;
}


text:
/*
@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#include <boost/hana/detail/assert.hpp>
#include <boost/hana/integer_list.hpp>
#include <boost/hana/integral.hpp>
#include <boost/hana/list/instance.hpp>
using namespace boost::hana;

int main() {
    //! [main]
    BOOST_HANA_CONSTANT_ASSERT(to<List>(integer_list<int, 0, 1, 2>) == list(int_<0>, int_<1>, int_<2>));
    BOOST_HANA_CONSTANT_ASSERT(head(integer_list<int, 0, 1, 2>) == int_<0>);
    //! [main]
}

max_stars_repo_name: rbock/hana

max_issues_repo_name: rbock/hana

max_forks_repo_name: rbock/hana


text:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <tuple>
#include <random>
#include <iterator>
#include <numeric>

#include <boost/numeric/ublas/storage.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/io.hpp>

#include "VNS.hpp"
#include "MODI.hpp"
#include "Solution.hpp"
#include "Helper.hpp"

using namespace std;
using namespace t_simplex;
namespace ublas = boost::numeric::ublas;

/*********************************************************************************/
/*                            UPDATE XIJ PROCEDURES                              */
/*********************************************************************************/

// CFLP with Modi procedure (gets optimal solution in deterministic time)
bool VNS::updateXij(
	ublas::matrix<double> &cij,
	const vector<double> &dj,
	const vector<double> &bi,
	const vector<bool> &yi,
	const unsigned int &update_xij_mode,
	double &fx)
{
	if (!canUpdateXij(bi, yi, m_sum_dj))
		return false;

	unsigned int open_facilities = 0, i_out = 0, flow_vars = 0;
	double transportation_cost = 0.0, gap = 0.0, sum_bi = 0.0;
	bool check = false;

	open_facilities = accumulate(yi.begin(), yi.end(), 0);

	ublas::matrix<double> custom_cij(open_facilities, m_customerNumber, 0.0);

	int *customers = new int[m_customerNumber];
	double *demand = new double[m_customerNumber];
	int *facilities = new int[open_facilities];
	double *capacity = new double[open_facilities];

	for (size_t j = 0; j != cij.size2(); ++j)
	{
		customers[j] = j;
		demand[j] = dj[j];
	}

	for (size_t i = 0; i != cij.size1(); ++i)
	{
		if (yi[i] == 1)
		{
			facilities[i_out] = i;
			capacity[i_out] = bi[i];
			sum_bi += bi[i];

			ublas::matrix_row<ublas::matrix<double>> row_custom_cij(custom_cij, i_out);
			ublas::matrix_row<ublas::matrix<double>> row_cij(cij, i);
			row_custom_cij = row_cij;

			i_out++;
		}
	}

	// Signature of Facilities and Customers
	TsSignature *facility = new TsSignature(open_facilities, facilities, capacity);
	TsSignature *customer = new TsSignature(m_customerNumber, customers, demand);
	// Save Stepping Stone Path
	TsFlow *flow = new TsFlow[open_facilities + m_customerNumber - 1];

	// Result value
	transportation_cost = t_simplex::transportSimplex(update_xij_mode, custom_cij, flow,
		&flow_vars, facility, customer ,m_sum_dj, sum_bi, dj);

	// f(x) and Return Value
	fx = f(yi, m_fi, transportation_cost);

	// Flow Xij for checkSolution
	m_flow_tpl.resize(flow_vars);
	for (size_t i = 0; i < flow_vars; ++i)
		m_flow_tpl[i] = make_tuple(facilities[flow[i].from], flow[i].to, flow[i].amount);

	check = checkSolution(yi, m_flow_tpl, flow_vars, cij, bi, dj, m_sum_dj);

	delete[] capacity;
	capacity = NULL;
	delete[] demand;
	demand = NULL;
	delete[] facilities;
	facilities = NULL;
	delete[] customers;
	customers = NULL;
	delete facility;
	facility = NULL;
	delete customer;
	customer = NULL;

	return check;
}


text:
#ifndef BOOST_METAPARSE_V1_TRANSFORM_HPP
#define BOOST_METAPARSE_V1_TRANSFORM_HPP

// Copyright Abel Sinkovics (abel@sinkovics.hu)  2009 - 2010.
// 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 <boost/metaparse/v1/accept.hpp>
#include <boost/metaparse/v1/get_result.hpp>
#include <boost/metaparse/v1/get_remaining.hpp>
#include <boost/metaparse/v1/get_position.hpp>
#include <boost/metaparse/v1/unless_error.hpp>

#include <boost/mpl/eval_if.hpp>

namespace boost
{
  namespace metaparse
  {
    namespace v1
    {
      template <class P, class T>
      struct transform
      {
      private:
        template <class S, class Pos>
        struct no_error :
          accept<
            typename T::template apply<
              typename get_result<typename P::template apply<S, Pos> >::type
            >::type,
            get_remaining<typename P::template apply<S, Pos> >,
            get_position<typename P::template apply<S, Pos> >
          >
        {};
      public:
        typedef transform type;

        template <class S, class Pos>
        struct apply :
          unless_error<typename P::template apply<S, Pos>, no_error<S, Pos> >
        {};
      };
    }
  }
}

#endif

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
#include <iostream>
#include <vector>
#include <utility>
#include <iterator>
#include <cstdlib>
#include <limits>
#include <cerrno>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/graph_concepts.hpp>
#include <boost/concept_check.hpp>
#include <boost/operators.hpp>
#include <boost/iterator.hpp>
#include <boost/multi_array.hpp>
#include <boost/random.hpp>

#include <sys/time.h>
#include "../src/edmonds_optimum_branching.hpp"

using namespace std;
using namespace boost;

const char *PNAME =  "test";

// global random number generator
boost::mt19937 g_generator;

// definitions of a complete graph that implements the EdgeListGraph
// concept of Boost's graph library.
namespace boost {
    struct complete_graph {
        complete_graph(int n_vertices) : n_vertices(n_vertices) {}
        int n_vertices;

        struct edge_iterator : public input_iterator_helper<edge_iterator, int, std::ptrdiff_t, int const *, int>
        {
            int edge_idx, n_vertices;

            edge_iterator() : edge_idx(0), n_vertices(-1) {}
            edge_iterator(int n_vertices, int edge_idx) : edge_idx(edge_idx), n_vertices(n_vertices) {}
            edge_iterator &operator++()
            {
                if (edge_idx >= n_vertices * n_vertices)
                    return *this;
                ++edge_idx;
                if (edge_idx / n_vertices == edge_idx % n_vertices)
                    ++edge_idx;
                return *this;
            }
            int operator*() const {return edge_idx;}
            bool operator==(const edge_iterator &iter) const
            {
                return edge_idx == iter.edge_idx;
            }
        };
    };

    template<>
    struct graph_traits<complete_graph> {
        typedef int                             vertex_descriptor;
        typedef int                             edge_descriptor;
        typedef directed_tag                    directed_category;
        typedef disallow_parallel_edge_tag      edge_parallel_category;
        typedef edge_list_graph_tag             traversal_category;
        typedef complete_graph::edge_iterator   edge_iterator;
        typedef unsigned                        edges_size_type;

        static vertex_descriptor null_vertex() {return -1;}
    };

    pair<complete_graph::edge_iterator, complete_graph::edge_iterator>
    edges(const complete_graph &g)
    {
        return make_pair(complete_graph::edge_iterator(g.n_vertices, 1),
                         complete_graph::edge_iterator(g.n_vertices, g.n_vertices*g.n_vertices));
    }

    unsigned
    num_edges(const complete_graph &g)
    {
        return (g.n_vertices - 1) * (g.n_vertices - 1);
    }

    int
    source(int edge, const complete_graph &g)
    {
        return edge / g.n_vertices;
    }

    int
    target(int edge, const complete_graph &g)
    {
        return edge % g.n_vertices;
    }
}

typedef graph_traits<complete_graph>::edge_descriptor Edge;
typedef graph_traits<complete_graph>::vertex_descriptor Vertex;

// is_cyclic()
//
// returns true if the choice of parents for the vertices creates a
// cycle, i.e. if 'parent' does not represent a branching
bool
is_cyclic(const vector<Vertex> &parent)
{
    unsigned size = parent.size();
    vector<bool> visited(size, false);

    for (unsigned i = 0; i < size; ++i)
    {
        if (visited[i])
            continue;

        vector<bool> visited_this_iteration(size, false);
        visited[i] = true;
        visited_this_iteration[i] = true;
        Vertex v = i;
        while (parent[v] != v)
        {
            v = parent[v];
            if (visited_this_iteration[v])
                return true;
            visited_this_iteration[v] = true;
            if (visited[v])
                break;
        }
    }
    return false;
}

// next_parent()
//
// Creates the next lexicographical parent vector. Returns true if the
// the parent returned is not the lexicographically first parent vector.
bool
next_parent(vector<Vertex> &parent)
{
    unsigned size = parent.size();

    bool carry = true;
    unsigned i = 0;
    while (carry && i < size)
    {
        parent[i] += 1;
        if (parent[i] < size)
        {
            carry = false;
        }
        else
        {
            parent[i] = 0;
        }
        ++i;
    }

    return !carry;
}

int
main(int argc, char *argv[])
{
    // Parse and read the command line arguments.
    if (argc != 5)
    {
        cerr << "Usage: " << PNAME
             << " <min-weight> <max-weight> <#vertices> <#tests>\n";
        exit(1);
    }

    long int min_weight = strtol(argv[1], 0, 0);
    long int max_weight = strtol(argv[2], 0, 0);
    long int n_vertices = strtol(argv[3], 0, 0);
    long int n_tests = strtol(argv[4], 0, 0);

    if (errno)
    {
        cerr << "Bad arguments\n";
        exit(1);
    }

    // Check consistency of command line arguments.
    if (n_tests < 0)
    {
        cerr << "the number of tests must be a positive integer\n";
        exit(1);
    }

    if (n_vertices > numeric_limits<unsigned>::digits)
    {
        cerr << "Too many vertices\n"
             << "Maximum n.o. vertices is "
             << numeric_limits<unsigned>::digits << "\n";
        exit(1);
    }

    if (n_vertices < 2)
    {
        cerr << "Too few vertices\n"
             << "must be at least two\n";
        exit(1);
    }

    if (min_weight > max_weight)
    {
        cerr << "min weight must be greater than max weight\n";
        exit(1);
    }

    if (abs(max_weight) >= numeric_limits<int>::max() / n_vertices ||
        abs(min_weight) >= numeric_limits<int>::max() / n_vertices)
    {
        cerr << "weights too large\n";
        exit(1);
    }

    // Initialize the random number generator.
    timeval tv;
    gettimeofday(&tv, 0);
    g_generator.seed(tv.tv_sec * 1000000 + tv.tv_usec);
    boost::uniform_int<int> uniform_int_dist(min_weight, max_weight);
    boost::variate_generator<mt19937, uniform_int<int> > rng_i(g_generator, uniform_int_dist);

    // Perform the tests.
    enum {MAX_SPAN_0, MAX_SPAN_1, MAX_SPAN_2,
          MAX_NOSPAN_0, MAX_NOSPAN_1, MAX_NOSPAN_2,
          MIN_SPAN_0, MIN_SPAN_1, MIN_SPAN_2,
          MIN_NOSPAN_0, MIN_NOSPAN_1, MIN_NOSPAN_2,
          N_CASES};
    string case_names[] = {
        "MAX_SPAN_0", "MAX_SPAN_1", "MAX_SPAN_2",
        "MAX_NOSPAN_0", "MAX_NOSPAN_1", "MAX_NOSPAN_2",
        "MIN_SPAN_0", "MIN_SPAN_1", "MIN_SPAN_2",
        "MIN_NOSPAN_0", "MIN_NOSPAN_1", "MIN_NOSPAN_2"
    };

    complete_graph      g(n_vertices);
    multi_array<int, 2> weights(extents[n_vertices][n_vertices]);
    vector<Vertex>      parent(n_vertices);
    Vertex              roots[] = {0, 1};

    vector<Edge>        branching;
    vector< vector< Edge > > all_branchings(N_CASES);
    vector<int>         ans(N_CASES);

    while (n_tests--)
    {
        // Clear all the branchings from previous iteration.
        BOOST_FOREACH (vector<Edge> &vec, all_branchings)
        {
            vec.clear();
        }

        // create new weights
        int *end = weights.origin() + n_vertices * n_vertices;
        for (int *ip = weights.origin(); ip != end; ++ip)
        {
            *ip = rng_i();
        }

        // run edmonds algorithm for a few cases. The cases will be
        // the cross product of the following properties:
        // optimum-is-maximum x attempt-to-span x num-specified-roots
        // where num-specified roots is either 0, 1, or 2. Also the
        // specified roots are either none, the vertex 0, or the
        // vertices 0 and 1.
        edmonds_optimum_branching<true, true, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 0, back_inserter(all_branchings[MAX_SPAN_0]));
        edmonds_optimum_branching<true, true, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 1, back_inserter(all_branchings[MAX_SPAN_1]));
        edmonds_optimum_branching<true, true, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 2, back_inserter(all_branchings[MAX_SPAN_2]));
        edmonds_optimum_branching<true, false, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 0, back_inserter(all_branchings[MAX_NOSPAN_0]));
        edmonds_optimum_branching<true, false, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 1, back_inserter(all_branchings[MAX_NOSPAN_1]));
        edmonds_optimum_branching<true, false, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 2, back_inserter(all_branchings[MAX_NOSPAN_2]));
        edmonds_optimum_branching<false, true, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 0, back_inserter(all_branchings[MIN_SPAN_0]));
        edmonds_optimum_branching<false, true, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 1, back_inserter(all_branchings[MIN_SPAN_1]));
        edmonds_optimum_branching<false, true, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 2, back_inserter(all_branchings[MIN_SPAN_2]));
        edmonds_optimum_branching<false, false, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 0, back_inserter(all_branchings[MIN_NOSPAN_0]));
        edmonds_optimum_branching<false, false, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 1, back_inserter(all_branchings[MIN_NOSPAN_1]));
        edmonds_optimum_branching<false, false, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 2, back_inserter(all_branchings[MIN_NOSPAN_2]));

        for (int i = 0; i < N_CASES; ++i)
        {
            ans[i] = 0;
            BOOST_FOREACH (Edge e, all_branchings[i])
            {
                ans[i] += weights[source(e, g)][target(e, g)];
            }
        }

        // Exhaustively test all branchings and check if the answers
        // from edmonds's algorithm is optimal.
        int bad_case = -1;
        fill(parent.begin(), parent.end(), 0);
        do
        {
            if (is_cyclic(parent))
                continue;

            int weight = 0;
            for (int i = 0; i < n_vertices; ++i)
            {
                if (parent[i] == i)
                    continue;

                weight += weights[parent[i]][i];
            }

            int num_roots = 0;
            for (int i = 0; i < n_vertices; ++i)
            {
                num_roots += parent[i] == i ? 1 : 0;
            }

            bad_case = MAX_NOSPAN_0;
            if (weight > ans[bad_case])
                break;

            bad_case = MIN_NOSPAN_0;
            if (weight < ans[bad_case])
                break;

            bad_case = MAX_NOSPAN_1;
            if (parent[0] == 0 && weight > ans[bad_case])
                break;

            bad_case = MIN_NOSPAN_1;
            if (parent[0] == 0 && weight < ans[bad_case])
                break;

            bad_case = MAX_NOSPAN_2;
            if (parent[0] == 0 && parent[1] == 1 && weight > ans[bad_case])
                break;

            bad_case = MIN_NOSPAN_2;
            if (parent[0] == 0 && parent[1] == 1 && weight < ans[bad_case])
                break;

            bad_case = MAX_SPAN_0;
            if (num_roots == 1 && weight > ans[bad_case])
                break;

            bad_case = MIN_SPAN_0;
            if (num_roots == 1 && weight < ans[bad_case])
                break;

            bad_case = MAX_SPAN_1;
            if (num_roots == 1 && parent[0] == 0 && weight > ans[bad_case])
                break;

            bad_case = MIN_SPAN_1;
            if (num_roots == 1 && parent[0] == 0 && weight < ans[bad_case])
                break;

            bad_case = MAX_SPAN_2;
            if (num_roots == 1 && parent[0] == 0 && parent[1] == 1 &&
                weight > ans[bad_case])
                break;

            bad_case = MIN_SPAN_2;
            if (num_roots == 1 && parent[0] == 0 && parent[1] == 1 &&
                weight < ans[bad_case])
                break;

            bad_case = -1;
        } while (next_parent(parent));

        // If we broke out of the loop prematurely, then something was
        // wrong.
        if (bad_case > 0)
        {
            cout << "\ntest failed.\n";

            cout << "weights:\n";
            for (int i = 0; i < n_vertices; ++i)
            {
                for (int j = 0; j < n_vertices; ++j)
                {
                    cout << weights[i][j] << " ";
                }
                cout << "\n";
            }
            cout << "\n";

            int weight = 0;
            for (int i = 0; i < n_vertices; ++i)
            {
                if (parent[i] == i)
                    continue;

                weight += weights[parent[i]][i];
            }

            cout << "counter example (weight = " << weight << "):\n";
            for (int i = 0; i < n_vertices; ++i)
            {
                if (parent[i] == i)
                    continue;
                cout << "(" << parent[i] << ", " << i << ")\t";
            }
            cout << "\n";

            weight = 0;
            cout << "case: " << case_names[bad_case] << ":\n";
            BOOST_FOREACH (Edge e, all_branchings[bad_case])
            {
                cout << "(" << source(e, g) << ", " << target(e, g) << ")\t";
                weight += weights[source(e, g)][target(e, g)];
            }
            cout << "\n";
            cout << "weight:\t" << weight << "\n";

            exit(1);
        }
        cerr << ".";
    }
    cerr << "\n";

    return EXIT_SUCCESS;
}

max_stars_repo_name: atofigh/edmonds-alg

max_issues_repo_name: atofigh/edmonds-alg

max_forks_repo_name: atofigh/edmonds-alg


text:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Regression

#include <fstream>
#include <iostream>

#include <boost/test/unit_test.hpp>

#include <xolotl/core/diffusion/Diffusion1DHandler.h>
#include <xolotl/core/network/PSIReactionNetwork.h>
#include <xolotl/options/Options.h>
#include <xolotl/test/CommandLine.h>
#include <xolotl/util/MPIUtils.h>

using namespace std;
using namespace xolotl;
using namespace core;
using namespace diffusion;

using Kokkos::ScopeGuard;
BOOST_GLOBAL_FIXTURE(ScopeGuard);

/**
 * This suite is responsible for testing the Diffusion1DHandler.
 */
BOOST_AUTO_TEST_SUITE(Diffusion1DHandler_testSuite)

/**
 * Method checking the initialization of the off-diagonal part of the Jacobian,
 * and the compute diffusion methods.
 */
BOOST_AUTO_TEST_CASE(checkDiffusion)
{
	// Create the option to create a network
	xolotl::options::Options opts;
	// Create a good parameter file
	std::string parameterFile = "param.txt";
	std::ofstream paramFile(parameterFile);
	paramFile << "netParam=8 0 0 1 0" << std::endl;
	paramFile.close();

	// Create a fake command line to read the options
	test::CommandLine<2> cl{{"fakeXolotlAppNameForTests", parameterFile}};
	util::mpiInit(cl.argc, cl.argv);
	opts.readParams(cl.argc, cl.argv);

	std::remove(parameterFile.c_str());

	// Create a grid
	std::vector<double> grid;
	std::vector<double> temperatures;
	for (int l = 0; l < 5; l++) {
		grid.push_back((double)l);
		temperatures.push_back(1000.0);
	}

	// Create the network
	using NetworkType =
		network::PSIReactionNetwork<network::PSIFullSpeciesList>;
	NetworkType::AmountType maxV = opts.getMaxV();
	NetworkType::AmountType maxI = opts.getMaxI();
	NetworkType::AmountType maxHe = opts.getMaxImpurity();
	NetworkType::AmountType maxD = opts.getMaxD();
	NetworkType::AmountType maxT = opts.getMaxT();
	NetworkType network({maxHe, maxD, maxT, maxV, maxI}, grid.size(), opts);
	network.syncClusterDataOnHost();
	network.getSubpaving().syncZones(plsm::onHost);
	// Get its size
	const int dof = network.getDOF();

	// Create the diffusion handler
	Diffusion1DHandler diffusionHandler(opts.getMigrationThreshold());

	// Create a collection of advection handlers
	std::vector<advection::IAdvectionHandler*> advectionHandlers;

	// Create ofill
	network::IReactionNetwork::SparseFillMap ofill;

	// Initialize it
	diffusionHandler.initializeOFill(network, ofill);
	diffusionHandler.initializeDiffusionGrid(advectionHandlers, grid, 5, 0);

	// Test which cluster diffuses
	BOOST_REQUIRE_EQUAL(ofill[1][0], 1); // He_1
	BOOST_REQUIRE_EQUAL(ofill[3][0], 3); // He_2
	BOOST_REQUIRE_EQUAL(ofill[5][0], 5); // He_3
	BOOST_REQUIRE_EQUAL(ofill[7][0], 7); // He_4
	BOOST_REQUIRE_EQUAL(ofill[9][0], 9); // He_5
	BOOST_REQUIRE_EQUAL(ofill[11][0], 11); // He_6
	BOOST_REQUIRE_EQUAL(ofill[13][0], 13); // He_7
	BOOST_REQUIRE_EQUAL(ofill[0][0], 0); // V_1

	// Check the total number of diffusing clusters
	BOOST_REQUIRE_EQUAL(diffusionHandler.getNumberOfDiffusing(), 8);

	// The size parameter in the x direction
	double hx = 1.0;

	// The arrays of concentration
	double concentration[3 * dof];
	double newConcentration[3 * dof];

	// Initialize their values
	for (int i = 0; i < 3 * dof; i++) {
		concentration[i] = (double)i * i;
		newConcentration[i] = 0.0;
	}

	// Set the temperature to 1000K to initialize the diffusion coefficients
	network.setTemperatures(temperatures);
	network.syncClusterDataOnHost();

	// Get pointers
	double* conc = &concentration[0];
	double* updatedConc = &newConcentration[0];

	// Get the offset for the grid point in the middle
	// Supposing the 3 grid points are laid-out as follow:
	// 0 | 1 | 2
	double* concOffset = conc + dof;
	double* updatedConcOffset = updatedConc + dof;

	// Fill the concVector with the pointer to the middle, left, and right grid
	// points
	double* concVector[3]{};
	concVector[0] = concOffset; // middle
	concVector[1] = conc; // left
	concVector[2] = conc + 2 * dof; // right

	// Compute the diffusion at this grid point
	diffusionHandler.computeDiffusion(
		network, concVector, updatedConcOffset, hx, hx, 0);

	// Check the new values of updatedConcOffset
	BOOST_REQUIRE_CLOSE(updatedConcOffset[1], 3.7081e+12, 0.01);
	BOOST_REQUIRE_CLOSE(updatedConcOffset[3], 1.8160e+12, 0.01);
	BOOST_REQUIRE_CLOSE(updatedConcOffset[5], 7.3065e+11, 0.01);
	BOOST_REQUIRE_CLOSE(updatedConcOffset[7], 9.6476e+11, 0.01);
	BOOST_REQUIRE_CLOSE(updatedConcOffset[9], 7.1800e+11, 0.01);
	BOOST_REQUIRE_CLOSE(updatedConcOffset[11], 1.7783e+10, 0.01);
	BOOST_REQUIRE_CLOSE(updatedConcOffset[13], 2.7860e+09, 0.01);
	BOOST_REQUIRE_CLOSE(
		updatedConcOffset[15], 0.0, 0.01); // He_8 does not diffuse
	BOOST_REQUIRE_CLOSE(updatedConcOffset[0], 2.9207e+08, 0.01);

	// Initialize the indices and values to set in the Jacobian
	int nDiff = diffusionHandler.getNumberOfDiffusing();
	IdType indices[nDiff];
	double val[3 * nDiff];
	// Get the pointer on them for the compute diffusion method
	IdType* indicesPointer = &indices[0];
	double* valPointer = &val[0];

	// Compute the partial derivatives for the diffusion a the grid point 1
	diffusionHandler.computePartialsForDiffusion(
		network, valPointer, indicesPointer, hx, hx, 0);

	// Check the values for the indices
	BOOST_REQUIRE_EQUAL(indices[0], 0);
	BOOST_REQUIRE_EQUAL(indices[1], 1);
	BOOST_REQUIRE_EQUAL(indices[2], 3);
	BOOST_REQUIRE_EQUAL(indices[3], 5);
	BOOST_REQUIRE_EQUAL(indices[4], 7);
	BOOST_REQUIRE_EQUAL(indices[5], 9);
	BOOST_REQUIRE_EQUAL(indices[6], 11);
	BOOST_REQUIRE_EQUAL(indices[7], 13);

	// Check some values
	BOOST_REQUIRE_CLOSE(val[1], 505312, 0.01);
	BOOST_REQUIRE_CLOSE(val[4], 6415444736, 0.01);
	BOOST_REQUIRE_CLOSE(val[5], 6415444736, 0.01);
	BOOST_REQUIRE_CLOSE(val[6], -6283827232, 0.01);
	BOOST_REQUIRE_CLOSE(val[9], -2528210084, 0.01);

	// Finalize MPI
	MPI_Finalize();
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: ORNL-Fusion/xolotl

max_issues_repo_name: ORNL-Fusion/xolotl

max_forks_repo_name: ORNL-Fusion/xolotl


text:
#include <NTL/pair_ZZX_long.h>

#include <NTL/new.h>

NTL_START_IMPL

NTL_pair_impl(ZZX,long,pair_ZZX_long)
NTL_pair_io_impl(ZZX,long,pair_ZZX_long)
NTL_pair_eq_impl(ZZX,long,pair_ZZX_long)

NTL_vector_impl(pair_ZZX_long,vec_pair_ZZX_long)
NTL_io_vector_impl(pair_ZZX_long,vec_pair_ZZX_long)
NTL_eq_vector_impl(pair_ZZX_long,vec_pair_ZZX_long)

NTL_END_IMPL

max_stars_repo_name: vshesh/RUNEtag

max_issues_repo_name: vshesh/RUNEtag

max_forks_repo_name: vshesh/RUNEtag


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

#include <gtest/gtest.h>
#include <thrift/lib/cpp2/test/gen-cpp/TestService.h>
#include <thrift/lib/cpp2/test/gen-cpp2/TestService.h>
#include <thrift/lib/cpp2/server/ThriftServer.h>
#include <thrift/lib/cpp2/async/HeaderClientChannel.h>
#include <thrift/lib/cpp2/async/RequestChannel.h>

#include <thrift/lib/cpp/util/ScopedServerThread.h>
#include <thrift/lib/cpp/async/TEventBase.h>
#include <thrift/lib/cpp/async/TAsyncSocket.h>
#include <thrift/lib/cpp/async/TAsyncServerSocket.h>
#include <thrift/lib/cpp/transport/THeader.h>

#include <thrift/lib/cpp2/async/StubSaslClient.h>
#include <thrift/lib/cpp2/async/StubSaslServer.h>
#include <thrift/lib/cpp2/TestServer.h>

#include <folly/experimental/fibers/FiberManagerMap.h>
#include <wangle/concurrent/GlobalExecutor.h>

#include <boost/cast.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>

using namespace apache::thrift;
using namespace apache::thrift::test::cpp2;
using namespace apache::thrift::util;
using namespace apache::thrift::async;
using namespace apache::thrift::transport;
using apache::thrift::protocol::TBinaryProtocolT;
using apache::thrift::test::TestServiceClient;

DECLARE_int32(thrift_cpp2_protocol_reader_string_limit);

class TestInterface : public TestServiceSvIf {
  void sendResponse(std::string& _return, int64_t size) override {
    if (size >= 0) {
      usleep(size);
    }

    EXPECT_NE("", getConnectionContext()->getPeerAddress()->describe());

    _return = "test" + boost::lexical_cast<std::string>(size);
  }

  void noResponse(int64_t size) override { usleep(size); }

  void echoRequest(std::string& _return,
                   std::unique_ptr<std::string> req) override {
    _return = *req + "ccccccccccccccccccccccccccccccccccccccccccccc";
  }

  typedef apache::thrift::HandlerCallback<std::unique_ptr<std::string>>
      StringCob;
  void async_tm_serializationTest(std::unique_ptr<StringCob> callback,
                                  bool inEventBase) override {
    std::unique_ptr<std::string> sp(new std::string("hello world"));
    callback->result(std::move(sp));
  }

  void async_eb_eventBaseAsync(std::unique_ptr<StringCob> callback) override {
    std::unique_ptr<std::string> hello(new std::string("hello world"));
    callback->result(std::move(hello));
  }

  void async_tm_notCalledBack(
      std::unique_ptr<apache::thrift::HandlerCallback<void>> cb) override {}
};

std::shared_ptr<TestServiceClient> getThrift1Client(
    const folly::SocketAddress& address) {
  // Create Thrift1 clients
  std::shared_ptr<TSocket> socket = std::make_shared<TSocket>(address);
  socket->open();
  std::shared_ptr<TFramedTransport> transport =
      std::make_shared<TFramedTransport>(socket);
  std::shared_ptr<TBinaryProtocolT<TBufferBase>> protocol =
      std::make_shared<TBinaryProtocolT<TBufferBase>>(transport);
  return std::make_shared<TestServiceClient>(protocol);
}

void AsyncCpp2Test(bool enable_security) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  TEventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  auto client_channel = HeaderClientChannel::newChannel(socket);
  if (enable_security) {
    client_channel->setSecurityPolicy(THRIFT_SECURITY_PERMITTED);
    client_channel->setSaslClient(std::unique_ptr<SaslClient>(
      new StubSaslClient(socket->getEventBase())
    ));
  }
  TestServiceAsyncClient client(std::move(client_channel));

  boost::polymorphic_downcast<HeaderClientChannel*>(
    client.getChannel())->setTimeout(10000);
  client.sendResponse([&](ClientReceiveState&& state) {
    std::string response;
    try {
      TestServiceAsyncClient::recv_sendResponse(
          response, state);
    } catch(const std::exception& ex) {
    }
    EXPECT_EQ(response, "test64");
  }, 64);
  base.loop();
}

TEST(ThriftServer, InsecureAsyncCpp2Test) {
  AsyncCpp2Test(false);
}

TEST(ThriftServer, SecureAsyncCpp2Test) {
  AsyncCpp2Test(true);
}

TEST(ThriftServer, GetLoadTest) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  auto serv = factory.create();
  ScopedServerThread sst(serv);
  TEventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  TestServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    apache::thrift::async::TDelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  auto header_channel = boost::polymorphic_downcast<HeaderClientChannel*>(
    client.getChannel());
  RpcOptions rpcOptions;
  rpcOptions.setWriteHeader("load", "thrift.active_requests");
  auto callback = std::unique_ptr<RequestCallback>(
      new FunctionReplyCallback([&](ClientReceiveState&& state) {
    std::string response;
    auto headers = state.header()->getHeaders();
    auto load = headers.find("load");
    EXPECT_NE(load, headers.end());
    EXPECT_EQ(load->second, "0");
    TestServiceAsyncClient::recv_wrapped_sendResponse(response, state);
    EXPECT_EQ(response, "test64");
  }));
  client.sendResponse(rpcOptions, std::move(callback), 64);
  base.loop();

  serv->setGetLoad([&](std::string counter){
    EXPECT_EQ(counter, "thrift.active_requests");
    return 1;
  });

  rpcOptions.setWriteHeader("load", "thrift.active_requests");
  callback = std::unique_ptr<RequestCallback>(
      new FunctionReplyCallback([&](ClientReceiveState&& state) {
    std::string response;
    auto headers = state.header()->getHeaders();
    auto load = headers.find("load");
    EXPECT_NE(load, headers.end());
    EXPECT_EQ(load->second, "1");
    TestServiceAsyncClient::recv_wrapped_sendResponse(response, state);
    EXPECT_EQ(response, "test64");
  }));
  client.sendResponse(rpcOptions, std::move(callback), 64);
  base.loop();
}

TEST(ThriftServer, SerializationInEventBaseTest) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  TEventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  auto channel =
      std::unique_ptr<HeaderClientChannel,
                      apache::thrift::async::TDelayedDestruction::Destructor>(
                          new HeaderClientChannel(socket));
  channel->setTimeout(10000);

  TestServiceAsyncClient client(std::move(channel));

  std::string response;
  client.sync_serializationTest(response, true);
  EXPECT_EQ("hello world", response);
}

TEST(ThriftServer, HandlerInEventBaseTest) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  TEventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  auto channel =
    std::unique_ptr<HeaderClientChannel,
                    apache::thrift::async::TDelayedDestruction::Destructor>(
                        new HeaderClientChannel(socket));
  channel->setTimeout(10000);

  TestServiceAsyncClient client(std::move(channel));

  std::string response;
  client.sync_eventBaseAsync(response);
  EXPECT_EQ("hello world", response);

}

TEST(ThriftServer, LargeSendTest) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  TEventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  TestServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    apache::thrift::async::TDelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  std::string response;
  std::string request;
  boost::polymorphic_downcast<HeaderClientChannel*>(
    client.getChannel())->setTimeout(5000);
  request.reserve(0x3fffffff);
  for (uint32_t i = 0; i < 0x3fffffd0 / 30; i++) {
    request += "cccccccccccccccccccccccccccccc";
  }

  try {
    // should timeout
    client.sync_echoRequest(response, request);
  } catch (const TTransportException& e) {
    EXPECT_EQ(int(TTransportException::TIMED_OUT), int(e.getType()));
    sleep(1); // Wait for server to timeout also - otherwise other tests fail
    return;
  }
  ADD_FAILURE();
}

TEST(ThriftServer, OverloadTest) {
  const int numThreads = 1;
  const int queueSize = 10;
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  {
    auto tm = concurrency::ThreadManager::newSimpleThreadManager(
        numThreads, 0, false, queueSize);
    tm->threadFactory(std::make_shared<concurrency::PosixThreadFactory>());
    tm->start();
    factory.useSimpleThreadManager(false).useThreadManager(tm);
  }
  ScopedServerThread sst(factory.create());
  TEventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  TestServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    apache::thrift::async::TDelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  std::string response;
  boost::polymorphic_downcast<HeaderClientChannel*>(
    client.getChannel())->setTimeout(500);

  auto tval = 10000;
  int too_full = 0;
  int exception_headers = 0;
  auto lambda = [&](ClientReceiveState&& state) {
      std::string response;
      auto headers = state.header()->getHeaders();
      if (headers.size() > 0) {
        EXPECT_EQ(headers["ex"], kQueueOverloadedErrorCode);
        exception_headers++;
      }
      auto ew = TestServiceAsyncClient::recv_wrapped_sendResponse(response,
                                                                  state);
      if (ew) {
        usleep(tval); // Wait for large task to finish
        too_full++;
      }
  };

  // Fill up the server's request buffer
  client.sendResponse(lambda, tval);
  for (int i = 0; i < numThreads + queueSize; i++) {
    client.sendResponse(lambda, 0);
  }
  base.loop();

  // We expect one 'too full' exception (queue size is 2, one being worked on)
  // And three timeouts
  EXPECT_EQ(too_full, 1);
  EXPECT_EQ(exception_headers, 1);
}

TEST(ThriftServer, OnewaySyncClientTest) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  TEventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  TestServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    apache::thrift::async::TDelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  client.sync_noResponse(0);
}

TEST(ThriftServer, OnewayClientConnectionCloseTest) {
  static std::atomic<bool> done(false);

  class OnewayTestInterface: public TestServiceSvIf {
    void noResponse(int64_t size) override {
        usleep(size);
        done = true;
    }
  };

  apache::thrift::TestThriftServerFactory<OnewayTestInterface> factory2;
  ScopedServerThread st(factory2.create());

  {
    TEventBase base;
    std::shared_ptr<TAsyncSocket> socket(
      TAsyncSocket::newSocket(&base, *st.getAddress()));
    TestServiceAsyncClient client(
        std::unique_ptr<HeaderClientChannel,
            apache::thrift::async::TDelayedDestruction::Destructor>(
            new HeaderClientChannel(socket)));

    client.sync_noResponse(10000);
  } // client out of scope

  usleep(50000);
  EXPECT_TRUE(done);
}

TEST(ThriftServer, CompactClientTest) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  TEventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  TestServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    apache::thrift::async::TDelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  // Set the client to compact
  boost::polymorphic_downcast<HeaderClientChannel*>(
    client.getChannel())->setProtocolId(
      ::apache::thrift::protocol::T_COMPACT_PROTOCOL);

  std::string response;
  client.sync_sendResponse(response, 64);
  EXPECT_EQ(response, "test64");
}

TEST(ThriftServer, CompressionClientTest) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  TEventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  TestServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    apache::thrift::async::TDelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  // Set the client to compact
  auto channel = boost::polymorphic_downcast<HeaderClientChannel*>(
    client.getChannel());
  channel->setTransform(
    apache::thrift::transport::THeader::ZLIB_TRANSFORM);
  channel->setMinCompressBytes(1);

  std::string response;
  client.sync_sendResponse(response, 64);
  EXPECT_EQ(response, "test64");

  auto trans = channel->getWriteTransforms();
  EXPECT_EQ(trans.size(), 1);
  for (auto& tran : trans) {
    EXPECT_EQ(tran, apache::thrift::transport::THeader::ZLIB_TRANSFORM);
  }
}

TEST(ThriftServer, ClientTimeoutTest) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  auto server = factory.create();
  ScopedServerThread sst(server);
  TEventBase base;

  auto getClient = [&base, &sst] () {
    std::shared_ptr<TAsyncSocket> socket(
      TAsyncSocket::newSocket(&base, *sst.getAddress()));

    return std::make_shared<TestServiceAsyncClient>(
      std::unique_ptr<HeaderClientChannel,
                      apache::thrift::async::TDelayedDestruction::Destructor>(
                        new HeaderClientChannel(socket)));
  };

  int cbCtor = 0;
  int cbCall = 0;

  auto callback = [&cbCall, &cbCtor] (
      std::shared_ptr<TestServiceAsyncClient> client,
      bool& timeout) {
    cbCtor++;
    return std::unique_ptr<RequestCallback>(
      new FunctionReplyCallback(
        [&cbCall, client, &timeout] (ClientReceiveState&& state) {
          cbCall++;
          if (state.exception()) {
            timeout = true;
            try {
              std::rethrow_exception(state.exception());
            } catch (const TTransportException& e) {
              EXPECT_EQ(int(TTransportException::TIMED_OUT),
                        int(e.getType()));

            }
            return;
          }
          try {
            std::string resp;
            client->recv_sendResponse(resp, state);
          } catch (const TApplicationException& e) {
            timeout = true;
            EXPECT_EQ(int(TApplicationException::TIMEOUT),
                      int(e.getType()));
            return;
          }
          timeout = false;
        }));
  };

  // Set the timeout to be 9 milliseconds, but the call will take 10 ms.
  // The server should send a timeout after 9 milliseconds
  RpcOptions options;
  options.setTimeout(std::chrono::milliseconds(9));
  auto client1 = getClient();
  bool timeout1;
  client1->sendResponse(options, callback(client1, timeout1), 10000);
  base.loop();
  EXPECT_TRUE(timeout1);
  usleep(10000);

  // This time we set the timeout to be 11 millseconds.  The server
  // should not time out
  options.setTimeout(std::chrono::milliseconds(11));
  client1->sendResponse(options, callback(client1, timeout1), 10000);
  base.loop();
  EXPECT_FALSE(timeout1);
  usleep(10000);

  // This time we set server timeout to be 1 millsecond.  However, the
  // task should start processing within that millisecond, so we should
  // not see an exception because the client timeout should be used after
  // processing is started
  server->setTaskExpireTime(std::chrono::milliseconds(1));
  client1->sendResponse(options, callback(client1, timeout1), 10000);
  base.loop();
  usleep(10000);

  // The server timeout stays at 1 ms, but we put the client timeout at
  // 9 ms.  We should timeout even though the server starts processing within
  // 1ms.
  options.setTimeout(std::chrono::milliseconds(9));
  client1->sendResponse(options, callback(client1, timeout1), 10000);
  base.loop();
  EXPECT_TRUE(timeout1);
  usleep(50000);

  // And finally, with the server timeout at 50 ms, we send 2 requests at
  // once.  Because the first request will take more than 50 ms to finish
  // processing (the server only has 1 worker thread), the second request
  // won't start processing until after 50ms, and will timeout, despite the
  // very high client timeout.
  // We don't know which one will timeout (race conditions) so we just check
  // the xor
  auto client2 = getClient();
  bool timeout2;
  server->setTaskExpireTime(std::chrono::milliseconds(50));
  options.setTimeout(std::chrono::milliseconds(110));
  client1->sendResponse(options, callback(client1, timeout1), 100000);
  client2->sendResponse(options, callback(client2, timeout2), 100000);
  base.loop();
  EXPECT_TRUE(timeout1 || timeout2);
  EXPECT_FALSE(timeout1 && timeout2);

  EXPECT_EQ(cbCall, cbCtor);
}

TEST(ThriftServer, ConnectionIdleTimeoutTest) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  auto server = factory.create();
  server->setIdleTimeout(std::chrono::milliseconds(20));
  apache::thrift::util::ScopedServerThread st(server);

  TEventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *st.getAddress()));

  TestServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    apache::thrift::async::TDelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  std::string response;
  client.sync_sendResponse(response, 200);
  EXPECT_EQ(response, "test200");
  base.loop();
}

TEST(ThriftServer, Thrift1OnewayRequestTest) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  auto cpp2Server = factory.create();
  cpp2Server->setNWorkerThreads(1);
  cpp2Server->setIsOverloaded([](const THeader* header) { return true; });
  apache::thrift::util::ScopedServerThread st(cpp2Server);

  std::shared_ptr<TestServiceClient> client = getThrift1Client(
    *st.getAddress());
  std::string response;
  // Send a oneway request. Server doesn't send error back
  client->noResponse(1);
  // Send a twoway request. Server sends overloading error back
  try {
    client->sendResponse(response, 0);
  } catch (apache::thrift::TApplicationException& ex) {
    EXPECT_STREQ(ex.what(), "loadshedding request");
  } catch (...) {
    ADD_FAILURE();
  }

  cpp2Server->setIsOverloaded([](const THeader* header) { return false; });
  // Send another twoway request. Client should receive a response
  // with correct seqId
  client->sendResponse(response, 0);
}

class Callback : public RequestCallback {
  void requestSent() override { ADD_FAILURE(); }
  void replyReceived(ClientReceiveState&& state) override { ADD_FAILURE(); }
  void requestError(ClientReceiveState&& state) override {
    try {
      std::rethrow_exception(state.exception());
    } catch(const apache::thrift::transport::TTransportException& ex) {
      // Verify we got a write and not a read error
      // Comparing substring because the rest contains ips and ports
      std::string expected = "transport is closed in write()";
      std::string actual = std::string(ex.what()).substr(0, expected.size());
      EXPECT_EQ(expected, actual);
    } catch (...) {
      ADD_FAILURE();
    }
  }
};

TEST(ThriftServer, BadSendTest) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  TEventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  TestServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    apache::thrift::async::TDelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  client.sendResponse(
    std::unique_ptr<RequestCallback>(new Callback), 64);

  socket->shutdownWriteNow();
  base.loop();

  std::string response;
  EXPECT_THROW(client.sync_sendResponse(response, 64), TTransportException);
}

TEST(ThriftServer, ResetStateTest) {
  TEventBase base;

  // Create a server socket and bind, don't listen.  This gets us a
  // port to test with which is guaranteed to fail.
  auto ssock = std::unique_ptr<
    TAsyncServerSocket,
    apache::thrift::async::TDelayedDestruction::Destructor>(
      new TAsyncServerSocket);
  ssock->bind(0);
  EXPECT_FALSE(ssock->getAddresses().empty());

  // We do this loop a bunch of times, because the bug which caused
  // the assertion failure was a lost race, which doesn't happen
  // reliably.
  for (int i = 0; i < 1000; ++i) {
    std::shared_ptr<TAsyncSocket> socket(
      TAsyncSocket::newSocket(&base, ssock->getAddresses()[0]));

    // Create a client.
    TestServiceAsyncClient client(
      std::unique_ptr<HeaderClientChannel,
      apache::thrift::async::TDelayedDestruction::Destructor>(
        new HeaderClientChannel(socket)));

    std::string response;
    // This will fail, because there's no server.
    EXPECT_THROW(client.sync_sendResponse(response, 64), TTransportException);
    // On a failed client object, this should also throw an exception.
    // In the past, this would generate an assertion failure and
    // crash.
    EXPECT_THROW(client.sync_sendResponse(response, 64), TTransportException);
  }
}

TEST(ThriftServer, FailureInjection) {
  enum ExpectedFailure {
    NONE = 0,
    ERROR,
    TIMEOUT,
    DISCONNECT,
    END
  };

  std::atomic<ExpectedFailure> expected(NONE);

  using apache::thrift::transport::TTransportException;

  class Callback : public RequestCallback {
   public:
    explicit Callback(const std::atomic<ExpectedFailure>* expected)
      : expected_(expected) { }

   private:
    void requestSent() override {}

    void replyReceived(ClientReceiveState&& state) override {
      std::string response;
      try {
        TestServiceAsyncClient::recv_sendResponse(response, state);
        EXPECT_EQ(NONE, *expected_);
      } catch (const apache::thrift::TApplicationException& ex) {
        EXPECT_EQ(ERROR, *expected_);
      } catch (...) {
        ADD_FAILURE() << "Unexpected exception thrown";
      }

      // Now do it again with exception_wrappers.
      auto ew = TestServiceAsyncClient::recv_wrapped_sendResponse(response,
                                                                  state);
      if (ew) {
        EXPECT_TRUE(
          ew.is_compatible_with<apache::thrift::TApplicationException>());
        EXPECT_EQ(ERROR, *expected_);
      } else {
        EXPECT_EQ(NONE, *expected_);
      }
    }

    void requestError(ClientReceiveState&& state) override {
      try {
        std::rethrow_exception(state.exception());
      } catch (const TTransportException& ex) {
        if (ex.getType() == TTransportException::TIMED_OUT) {
          EXPECT_EQ(TIMEOUT, *expected_);
        } else {
          EXPECT_EQ(DISCONNECT, *expected_);
        }
      } catch (...) {
        ADD_FAILURE() << "Unexpected exception thrown";
      }
    }

    const std::atomic<ExpectedFailure>* expected_;
  };

  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  TEventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  TestServiceAsyncClient client(
      std::unique_ptr<HeaderClientChannel,
                      apache::thrift::async::TDelayedDestruction::Destructor>(
          new HeaderClientChannel(socket)));

  auto server = std::dynamic_pointer_cast<ThriftServer>(
      sst.getServer().lock());
  CHECK(server);
  SCOPE_EXIT {
    server->setFailureInjection(ThriftServer::FailureInjection());
  };

  RpcOptions rpcOptions;
  rpcOptions.setTimeout(std::chrono::milliseconds(100));
  for (int i = 0; i < END; ++i) {
    auto exp = static_cast<ExpectedFailure>(i);
    ThriftServer::FailureInjection fi;

    switch (exp) {
    case NONE:
      break;
    case ERROR:
      fi.errorFraction = 1;
      break;
    case TIMEOUT:
      fi.dropFraction = 1;
      break;
    case DISCONNECT:
      fi.disconnectFraction = 1;
      break;
    case END:
      LOG(FATAL) << "unreached";
      break;
    }

    server->setFailureInjection(std::move(fi));

    expected = exp;

    auto callback = folly::make_unique<Callback>(&expected);
    client.sendResponse(rpcOptions, std::move(callback), 1);
    base.loop();
  }
}

TEST(ThriftServer, useExistingSocketAndExit) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  auto server = factory.create();
  TAsyncServerSocket::UniquePtr serverSocket(new TAsyncServerSocket);
  serverSocket->bind(0);
  server->useExistingSocket(std::move(serverSocket));
  // In the past, this would cause a SEGV
}

TEST(ThriftServer, useExistingSocketAndConnectionIdleTimeout) {
  // This is ConnectionIdleTimeoutTest, but with an existing socket
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  auto server = factory.create();
  TAsyncServerSocket::UniquePtr serverSocket(new TAsyncServerSocket);
  serverSocket->bind(0);
  server->useExistingSocket(std::move(serverSocket));

  server->setIdleTimeout(std::chrono::milliseconds(20));
  apache::thrift::util::ScopedServerThread st(server);

  TEventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *st.getAddress()));

  TestServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    apache::thrift::async::TDelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  std::string response;
  client.sync_sendResponse(response, 200);
  EXPECT_EQ(response, "test200");
  base.loop();
}

TEST(ThriftServer, FreeCallbackTest) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  TEventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  TestServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    apache::thrift::async::TDelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  RpcOptions options;
  options.setTimeout(std::chrono::milliseconds(1));

  try {
    client.sync_notCalledBack(options);
  } catch (...) {
    // Expect timeout
    return;
  }
  ADD_FAILURE();
}

class TestServerEventHandler
    : public server::TServerEventHandler
    , public TProcessorEventHandler
    , public TProcessorEventHandlerFactory
    , public std::enable_shared_from_this<TestServerEventHandler> {
 public:
  std::shared_ptr<TProcessorEventHandler> getEventHandler() override {
    return shared_from_this();
  }

  void check() {
    EXPECT_EQ(8, count);
  }
  void preServe(const folly::SocketAddress* addr) override {
    EXPECT_EQ(0, count++);
  }
  void newConnection(TConnectionContext* ctx) override {
    EXPECT_EQ(1, count++);
  }
  void connectionDestroyed(TConnectionContext* ctx) override {
    EXPECT_EQ(7, count++);
  }

  void* getContext(const char* fn_name, TConnectionContext* c) override {
    EXPECT_EQ(2, count++);
    return nullptr;
  }
  void freeContext(void* ctx, const char* fn_name) override {
    EXPECT_EQ(6, count++);
  }
  void preRead(void* ctx, const char* fn_name) override {
    EXPECT_EQ(3, count++);

  }
  void onReadData(void* ctx,
                  const char* fn_name,
                  const SerializedMessage& msg) override {
    EXPECT_EQ(4, count++);
  }

  void postRead(void* ctx,
                const char* fn_name,
                THeader* header,
                uint32_t bytes) override {
    EXPECT_EQ(5, count++);
  }

 private:
  std::atomic<int> count{0};
};

TEST(ThriftServer, CallbackOrderingTest) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  auto server = factory.create();
  auto serverHandler = std::make_shared<TestServerEventHandler>();

  TProcessorBase::addProcessorEventHandlerFactory(serverHandler);
  server->setServerEventHandler(serverHandler);

  ScopedServerThread sst(server);
  TEventBase base;
  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  TestServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    apache::thrift::async::TDelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  client.noResponse([](ClientReceiveState&& state){}, 10000);
  base.tryRunAfterDelay([&](){
    socket->closeNow();
  }, 1);
  base.tryRunAfterDelay([&](){
    base.terminateLoopSoon();
  }, 20);
  base.loopForever();
  serverHandler->check();
  TProcessorBase::removeProcessorEventHandlerFactory(serverHandler);
}

class ReadCallbackTest : public TAsyncTransport::ReadCallback {
 public:
  void getReadBuffer(void** bufReturn, size_t* lenReturn) override {}
  void readDataAvailable(size_t len) noexcept override {}
  void readEOF() noexcept override { eof = true; }

  void readError(const transport::TTransportException& ex) noexcept override {
    eof = true;
  }

  bool eof = false;
};

TEST(ThriftServer, ShutdownSocketSetTest) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  auto server = factory.create();
  ScopedServerThread sst(server);
  TEventBase base;
  ReadCallbackTest cb;

  std::shared_ptr<TAsyncSocket> socket2(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));
  socket2->setReadCallback(&cb);

  base.tryRunAfterDelay([&](){
      server->immediateShutdown(true);
    }, 10);
  base.tryRunAfterDelay([&](){
      base.terminateLoopSoon();
    }, 30);
  base.loopForever();
  EXPECT_EQ(cb.eof, true);
}

TEST(ThriftServer, ShutdownDegenarateServer) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  auto server = factory.create();
  server->setMaxRequests(1);
  server->setNWorkerThreads(1);
  ScopedServerThread sst(server);
}

TEST(ThriftServer, ModifyingIOThreadCountLive) {
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  auto server = factory.create();
  auto iothreadpool = std::make_shared<wangle::IOThreadPoolExecutor>(0);
  server->setIOThreadPool(iothreadpool);

  ScopedServerThread sst(server);
  // If there are no worker threads, generally the server event base
  // will stop loop()ing.  Create a timeout event to make sure
  // it continues to loop for the duration of the test.
  server->getServeEventBase()->runInEventBaseThread([&](){
    server->getServeEventBase()->tryRunAfterDelay([](){}, 5000);
  });

  server->getServeEventBase()->runInEventBaseThreadAndWait([=](){
    iothreadpool->setNumThreads(0);
  });

  TEventBase base;

  std::shared_ptr<TAsyncSocket> socket(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  TestServiceAsyncClient client(
    std::unique_ptr<HeaderClientChannel,
                    apache::thrift::async::TDelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket)));

  std::string response;

  boost::polymorphic_downcast<HeaderClientChannel*>(
    client.getChannel())->setTimeout(100);

  // This should fail as soon as it connects:
  // since AsyncServerSocket has no accept callbacks installed,
  // it should close the connection right away.
  ASSERT_ANY_THROW(
  client.sync_sendResponse(response, 64));

  server->getServeEventBase()->runInEventBaseThreadAndWait([=](){
    iothreadpool->setNumThreads(30);
  });

  std::shared_ptr<TAsyncSocket> socket2(
    TAsyncSocket::newSocket(&base, *sst.getAddress()));

  // Can't reuse client since the channel has gone bad
  TestServiceAsyncClient client2(
    std::unique_ptr<HeaderClientChannel,
                    apache::thrift::async::TDelayedDestruction::Destructor>(
                      new HeaderClientChannel(socket2)));

  client2.sync_sendResponse(response, 64);
}

TEST(ThriftServer, ThriftServerSizeLimits) {
  google::FlagSaver flagSaver;
  FLAGS_thrift_cpp2_protocol_reader_string_limit = 1024 * 1024;

  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  ScopedServerThread sst(factory.create());
  TEventBase eb;

  TestServiceAsyncClient client(
      HeaderClientChannel::newChannel(
        TAsyncSocket::newSocket(
          &eb, *sst.getAddress())));

  std::string response;

  try {
    // make a largest possible input which should not throw an exception
    std::string smallInput(1 << 19, '1');
    client.sync_echoRequest(response, smallInput);
    SUCCEED();
  } catch(const std::exception& ex) {
    ADD_FAILURE();
  }

  // make an input that is too large by 1 byte
  std::string largeInput(1 << 21, '1');
  EXPECT_THROW(client.sync_echoRequest(response, largeInput), std::exception);
}

class MyExecutor : public folly::Executor {
 public:
  void add(std::function<void()> f) override {
    calls++;
    f();
  }

  std::atomic<int> calls{0};
};

TEST(ThriftServer, poolExecutorTest) {
  auto exe = std::make_shared<MyExecutor>();
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  factory
    .useSimpleThreadManager(false)
    .useThreadManager(std::make_shared<
        apache::thrift::concurrency::ThreadManagerExecutorAdapter>(exe));
  ScopedServerThread sst(factory.create());
  TEventBase eb;

  TestServiceAsyncClient client(
      HeaderClientChannel::newChannel(
        TAsyncSocket::newSocket(
          &eb, *sst.getAddress())));

  std::string response;

  client.sync_echoRequest(response, "test");
  eb.loop();
  EXPECT_EQ(1, exe->calls);
}

class FiberExecutor : public folly::Executor {
 public:
  void add(std::function<void()> f) override {
    folly::fibers::getFiberManager(
      *wangle::getEventBase()).add(f);
  }
};

TEST(ThriftServer, fiberExecutorTest) {
  auto exe =
    std::make_shared<apache::thrift::concurrency::ThreadManagerExecutorAdapter>(
      std::make_shared<FiberExecutor>());
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  factory
    .useSimpleThreadManager(false)
    .useThreadManager(exe);
  ScopedServerThread sst(factory.create());
  TEventBase eb;

  TestServiceAsyncClient client(
      HeaderClientChannel::newChannel(
        TAsyncSocket::newSocket(
          &eb, *sst.getAddress())));

  std::string response;

  client.sync_sendResponse(response, 1);
  eb.loop();
  EXPECT_EQ("test1", response);
}

TEST(ThriftServer, setIOThreadPool) {
  auto exe = std::make_shared<wangle::IOThreadPoolExecutor>(1);
  apache::thrift::TestThriftServerFactory<TestInterface> factory;
  factory.useSimpleThreadManager(false);
  auto server = factory.create();

  // Set the exe, this used to trip various calls like
  // CHECK(ioThreadPool->numThreads() == 0).
  server->setIOThreadPool(exe);
  EXPECT_EQ(1, server->getNWorkerThreads());
}

class ExtendedTestServiceAsyncProcessor : public TestServiceAsyncProcessor {
  public:
   explicit ExtendedTestServiceAsyncProcessor(TestServiceSvIf* serviceInterface)
       : TestServiceAsyncProcessor(serviceInterface) {}

      folly::Optional<std::string> getCacheKeyTest() {
        folly::IOBuf emptyBuffer;
        return getCacheKey(
            &emptyBuffer,
            apache::thrift::protocol::PROTOCOL_TYPES::T_BINARY_PROTOCOL);
      }
};
TEST(ThriftServer, CacheAnnotation) {
  // We aren't parsing anything just want this to compile
  auto testInterface = std::unique_ptr<TestInterface>(new TestInterface);
  ExtendedTestServiceAsyncProcessor processor(testInterface.get());
  EXPECT_FALSE(processor.getCacheKeyTest().hasValue());
}

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);

  return RUN_ALL_TESTS();
}

max_stars_repo_name: reddit/fbthrift

max_issues_repo_name: reddit/fbthrift

max_forks_repo_name: reddit/fbthrift


text:
// Copyright 2018 Linus Klöckner

#include "YoutubeListDownloader/sql/dbs.h"

#include "YoutubeListDownloader/youtube/channel.h"
#include "YoutubeListDownloader/youtube/playlist.h"

#include <SQLiteCpp/Transaction.h>
#include <boost/algorithm/string.hpp>
#include <string>
#include <vector>

void SQL::CreateTables() {
    SQLite::Transaction transaction{m_database};

    m_database.exec(
        "CREATE TABLE IF NOT EXISTS videos ("
        "id TEXT NOT NULL,"
        "title TEXT NOT NULL,"
        "description TEXT NOT NULL,"
        "channelId TEXT NOT NULL,"
        "PRIMARY KEY(id))");

    m_database.exec(
        "CREATE TABLE IF NOT EXISTS lists("
        "id TEXT NOT NULL,"
        "userId TEXT NOT NULL,"
        "title TEXT NOT NULL,"
        "description TEXT,"
        "type TEXT NOT NULL,"
        "playlistId TEXT NOT NULL,"
        "channelId TEXT NOT NULL,"
        "PRIMARY KEY(id))");

    m_database.exec(
        "CREATE TABLE IF NOT EXISTS videoLists("
        "listId TEXT NOT NULL,"
        "videoId TEXT NOT NULL,"
        "position INTEGER NOT NULL,"
        "PRIMARY KEY(listId, videoId, position),"
        "FOREIGN KEY(listId) REFERENCES lists(id),"
        "FOREIGN KEY(videoId) REFERENCES videos(id))");

    m_database.exec(
        "CREATE TABLE IF NOT EXISTS thumbnails("
        "id TEXT NOT NULL,"
        "thumbnail BLOB,"
        "PRIMARY KEY(id))");

    transaction.commit();
}

void SQL::InsertVideo(const Youtube::Video& p_video) {
    boost::unique_lock<boost::shared_mutex> lock{m_mutex_videos};

    SQLite::Statement insert_video{m_database, R"(INSERT OR IGNORE INTO videos VALUES (?, ?, ?, ?))"};

    insert_video.bind(1, p_video.GetId());
    insert_video.bind(2, p_video.GetTitle());
    insert_video.bind(3, p_video.GetDescription());
    insert_video.bind(4, p_video.GetChannelId());

    insert_video.exec();
}

void SQL::InsertChannel(const Youtube::Channel& p_channel) {
    boost::unique_lock<boost::shared_mutex> lock{m_mutex_lists};

    SQLite::Statement insert_channel{m_database, R"(INSERT OR IGNORE INTO lists VALUES (?,?,?,?,?,?,?))"};

    std::string user_id = p_channel.GetTitle();
    boost::algorithm::to_lower(user_id);

    insert_channel.bind(1, p_channel.GetId());
    insert_channel.bind(2, user_id);
    insert_channel.bind(3, p_channel.GetTitle());
    insert_channel.bind(4, p_channel.GetDescription());
    insert_channel.bind(5, "channel");
    insert_channel.bind(6, p_channel.GetPlaylistId());
    insert_channel.bind(7, p_channel.GetId());

    insert_channel.exec();
}

void SQL::InsertPlaylist(const Youtube::Playlist& p_playlist) {
    boost::unique_lock<boost::shared_mutex> lock{m_mutex_lists};

    SQLite::Statement insert_playlist{m_database, R"(INSERT OR IGNORE INTO lists VALUES (?,?,?,?,?,?,?))"};

    insert_playlist.bind(1, p_playlist.GetId());
    insert_playlist.bind(2, p_playlist.GetTitle());
    insert_playlist.bind(4, "playlist");
    insert_playlist.bind(5, p_playlist.GetPlaylistId());
    insert_playlist.bind(6, p_playlist.GetChannelId());

    insert_playlist.exec();
}

void SQL::InsertVideoList(const std::string& p_video_id, const std::string& p_list_id, int p_position) {
    boost::unique_lock<boost::shared_mutex> lock{m_mutex_video_lists};

    SQLite::Statement insert_video_list{m_database, R"(INSERT OR IGNORE INTO videoLists VALUES (?, ?, ?))"};

    insert_video_list.bind(1, p_list_id);
    insert_video_list.bind(2, p_video_id);
    insert_video_list.bind(3, p_position);

    insert_video_list.exec();
}

void SQL::InsertThumbnail(const std::string& p_id, const std::string& p_image) {
    boost::unique_lock<boost::shared_mutex> lock{m_mutex_thumbnails};

    SQLite::Statement insert_thumbnail{m_database, R"(INSERT OR IGNORE INTO thumbnails VALUES (?, ?))"};

    insert_thumbnail.bind(1, p_id);
    insert_thumbnail.bind(2, p_image);

    insert_thumbnail.exec();
}

json SQL::QueryVideo(const std::string& p_video_id) {
    boost::shared_lock<boost::shared_mutex> lock{m_mutex_videos};

    SQLite::Statement query_video{m_database, R"(SELECT * FROM videos WHERE id = ?)"};
    query_video.bind(1, p_video_id);

    std::vector<json> videos;

    while (query_video.executeStep()) {
        json json_video = {
            {"id", query_video.getColumn(0).getText()},
            {"snippet",
             {{"title", query_video.getColumn(1).getText()},
              {"description", query_video.getColumn(2).getText()},
              {"channelId", query_video.getColumn(3).getText()}}}};

        videos.push_back(json_video);
    }

    return {{"items", json(videos)}};
}

json SQL::QueryChannel(const std::string& p_channel_id) {
    boost::shared_lock<boost::shared_mutex> lock{m_mutex_lists};

    SQLite::Statement query_channel{m_database, R"(SELECT * FROM lists WHERE id = ? and type = "channel")"};
    query_channel.bind(1, p_channel_id);

    std::vector<json> channels;

    while (query_channel.executeStep()) {

        json json_channel = {
            {"id", query_channel.getColumn(0).getText()},
            {"snippet",
             {{"title", query_channel.getColumn(1).getText()},
              {"description", query_channel.getColumn(2).getText()}}},
            {"contentDetails",
             {{"relatedPlaylists",
               {{"uploads", query_channel.getColumn(5).getText()}}}}}};

        channels.push_back(json_channel);
    }

    return {{"items", json(channels)}};
}

json SQL::QueryUser(const std::string& p_user_name) {
    boost::shared_lock<boost::shared_mutex> lock{m_mutex_lists};

    SQLite::Statement query_channel{m_database, R"(SELECT * FROM lists WHERE userId = ? and type = "channel")"};

    std::string user_name_low{p_user_name};
    boost::algorithm::to_lower(user_name_low);

    query_channel.bind(1, user_name_low);

    std::vector<json> channels;

    while (query_channel.executeStep()) {

        json json_channel = {
            {"id", query_channel.getColumn(0).getText()},
            {"snippet",
             {{"title", query_channel.getColumn(2).getText()},
              {"description", query_channel.getColumn(3).getText()}}},
            {"contentDetails",
             {{"relatedPlaylists",
               {{"uploads", query_channel.getColumn(5).getText()}}}}}};

        channels.push_back(json_channel);
    }

    return {{"items", json(channels)}};
}

json SQL::QueryPlaylist(const std::string& p_playlist_id) {
    boost::shared_lock<boost::shared_mutex> lock{m_mutex_lists};

    SQLite::Statement query_playlist{m_database, R"(SELECT * FROM lists WHERE id = ? and type = "playlist")"};
    query_playlist.bind(1, p_playlist_id);

    std::vector<json> playlists;

    while (query_playlist.executeStep()) {

        json json_playlist = {
            {"id", query_playlist.getColumn(0).getText()},
            {"snippet",
             {{"title", query_playlist.getColumn(1).getText()},
              {"channelId", query_playlist.getColumn(5).getText()}}}};

        playlists.push_back(json_playlist);
    }

    return {{"items", json(playlists)}};
}

std::vector<std::string> SQL::QueryVideoList(const std::string& p_list_id) {
    boost::shared_lock<boost::shared_mutex> lock{m_mutex_lists};

    SQLite::Statement query_video_list{
        m_database,
        R"(SELECT videos.id FROM videos INNER JOIN videoLists ON (videos.id = videoLists.videoId) WHERE videoLists.listId = ? ORDER BY videoLists.position)"};
    query_video_list.bind(1, p_list_id);

    std::vector<std::string> videos;

    while (query_video_list.executeStep()) {
        videos.push_back(query_video_list.getColumn(0).getText());
    }

    return videos;
}

bool SQL::ExistsThumbnail(const std::string& p_video_id) {
    boost::shared_lock<boost::shared_mutex> lock{m_mutex_thumbnails};

    SQLite::Statement query_thumbnail{m_database, R"(SELECT * FROM thumbnails WHERE id = ?)"};
    query_thumbnail.bind(1, p_video_id);

    return query_thumbnail.executeStep();
}


text:
/**
 * @copyright Copyright (c) 2017 B-com http://www.b-com.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 "xpcf/xpcf.h"
#include "api/input/devices/ICamera.h"
#include "api/solver/map/IMapper.h"
#include "api/reloc/IKeyframeRetriever.h"
#include "api/storage/ICovisibilityGraph.h"
#include "api/storage/IKeyframesManager.h"
#include "api/storage/IPointCloudManager.h"
#include "api/loop/ILoopClosureDetector.h"
#include "api/geom/I3DTransform.h"
#include "api/display/I3DPointsViewer.h"
#include "core/Log.h"
#include <boost/log/core.hpp>

using namespace SolAR;
using namespace SolAR::datastructure;
using namespace SolAR::api;

namespace xpcf  = org::bcom::xpcf;

int main(int argc,char** argv)
{
#if NDEBUG
    boost::log::core::get()->set_logging_enabled(false);
#endif

    LOG_ADD_LOG_TO_CONSOLE();
	/* instantiate component manager*/
	/* this is needed in dynamic mode */
	SRef<xpcf::IComponentManager> xpcfComponentManager = xpcf::getComponentManagerInstance();

    if (xpcfComponentManager->load("SolARTest_ModuleTools_LoopClosureDetection_conf.xml") != org::bcom::xpcf::_SUCCESS)
	{
        LOG_ERROR("Failed to load the configuration file SolARTest_ModuleTools_LoopClosureDetection_conf.xml")
			return -1;
	}

	// declare and create components
	LOG_INFO("Start creating components");

	// storage components
    auto pointCloudManager = xpcfComponentManager->resolve<storage::IPointCloudManager>();
    auto keyframesManager = xpcfComponentManager->resolve<storage::IKeyframesManager>();
    auto covisibilityGraph = xpcfComponentManager->resolve<storage::ICovisibilityGraph>();
    auto keyframeRetriever = xpcfComponentManager->resolve<reloc::IKeyframeRetriever>();
	auto mapper = xpcfComponentManager->resolve<solver::map::IMapper>();
	auto loopDetector = xpcfComponentManager->resolve<loop::ILoopClosureDetector>();
	auto camera = xpcfComponentManager->resolve<input::devices::ICamera>();
	auto transform3D = xpcfComponentManager->resolve<geom::I3DTransform>();
	auto viewer3DPoints = xpcfComponentManager->resolve<display::I3DPointsViewer>();

	loopDetector->setCameraParameters(camera->getIntrinsicsParameters(), camera->getDistortionParameters());

	// Load map from file
	if (mapper->loadFromFile() != FrameworkReturnCode::_SUCCESS) {
		LOG_INFO("Cannot load map");
		return 0;
	}

	LOG_INFO("Number of keyframes: {}", keyframesManager->getNbKeyframes());
	LOG_INFO("Number of cloud points: {}", pointCloudManager->getNbPoints());

	// get all keyframes and point cloud to display
	std::vector<Transform3Df> keyframePoses;
	std::vector<SRef<Keyframe>> allKeyframes;
	keyframesManager->getAllKeyframes(allKeyframes);
	for (auto const &it : allKeyframes)
		keyframePoses.push_back(it->getPose());
	std::vector<SRef<CloudPoint>> pointCloud;
	pointCloudManager->getAllPoints(pointCloud);

    // test loop closure with all keyframes
    // SRef<Keyframe> lastKeyframe = allKeyframes[allKeyframes.size() - 1];
    std::vector<SRef<CloudPoint>> localPointCloudTrans;
    bool loopDetected = false;
    SRef<Keyframe> requestedLoopKeyframe, detectedLoopKeyframe;
    for (SRef<Keyframe> currentKeyframe : allKeyframes)
    {
        uint32_t currentKeyframeId = currentKeyframe->getId();
        LOG_DEBUG("Current keyframe id: {}", currentKeyframeId);
        Transform3Df sim3Transform;
        std::vector<std::pair<uint32_t, uint32_t>> duplicatedPointsIndices;
        if (loopDetector->detect(currentKeyframe, detectedLoopKeyframe, sim3Transform, duplicatedPointsIndices) == FrameworkReturnCode::_SUCCESS) {
            // try to transform local point cloud of current keyframe to the detected loop keyframe
            std::vector<SRef<CloudPoint>> localPointCloud;
            std::vector<Point3Df> localPoint3D, localPoint3DTrans;
            mapper->getLocalPointCloud(currentKeyframe, 10, localPointCloud);
            for (auto it : localPointCloud)
                localPoint3D.push_back(Point3Df(it->getX(), it->getY(), it->getZ()));
            transform3D->transform(localPoint3D, sim3Transform, localPoint3DTrans);
            for (auto it : localPoint3DTrans)
                localPointCloudTrans.push_back(xpcf::utils::make_shared<CloudPoint>(it.getX(), it.getY(), it.getZ()));

            // detected loop keyframe
            LOG_INFO("Requested loop keyframe id: {}", currentKeyframe->getId());
            LOG_INFO("Detected loop keyframe id: {}", detectedLoopKeyframe->getId());
            LOG_INFO("Number of duplicated points: {}", duplicatedPointsIndices.size());
            LOG_INFO("Transform 3D from last keyframe and best detected loop keyframe: \n{}", sim3Transform.matrix());
            // display point cloud
            requestedLoopKeyframe = currentKeyframe;
            loopDetected = true;
        }
        if (loopDetected)
            break;
    }
    if (loopDetected)
        while (viewer3DPoints->display(localPointCloudTrans, requestedLoopKeyframe->getPose(), { detectedLoopKeyframe->getPose() }, {}, pointCloud, keyframePoses) == FrameworkReturnCode::_SUCCESS);
    else
        LOG_INFO("Cannot detect a loop closure");

    return 0;
}

max_stars_repo_name: wemap/SolARModuleTools

max_issues_repo_name: wemap/SolARModuleTools

max_forks_repo_name: wemap/SolARModuleTools


text:
// -*- mode: c++; indent-tabs-mode: nil; -*-
//
// Paragraph
// Copyright (c) 2016-2019 Illumina, Inc.
// All rights reserved.
//
// 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
//
//

/**
 * \brief Produces path sequences in fasta format
 *
 * \file paragraph.cpp
 * \author Roman Petrovski
 * \email rpetrovski@illumina.com
 *
 */

#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>

#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

#include "common/Region.hh"
#include "grm/GraphInput.hh"
#include "json/json.h"

#include "common/Error.hh"

namespace po = boost::program_options;

void dumpPath(
    const graphtools::Graph& graph, const std::unordered_map<std::string, const Json::Value&>& nodes,
    const graphtools::Path& path, std::ostream& os, const std::string& file)
{
    std::string path_id = path.encode();
    std::string cigar;
    std::string sequence;
    common::Region lastRegion;
    //    std::string dbg;
    for (const auto& n : path.nodeIds())
    {
        const auto nodeName = graph.nodeName(n);
        //        dbg += nodeName + ' ';
        if ("source" == nodeName || "sink" == nodeName)
        {
            continue;
        }
        const auto& node = nodes.find(nodeName);
        assert(node != nodes.cend());

        const std::string& s = graph.nodeSeq(n);

        sequence += s;
        if (node->second.isMember("reference"))
        {
            const std::string reg = node->second["reference"].asString();
            common::Region region(reg);
            if (region.chrom == lastRegion.chrom)
            {
                if (region.start == lastRegion.end + 1)
                {
                    lastRegion.end = region.end;
                    continue;
                }
                else if (region.start > lastRegion.end + 1)
                {
                    cigar += std::to_string(lastRegion.length()) + "M" + std::to_string(region.start - lastRegion.start)
                        + "D";
                    lastRegion = region;
                    continue;
                }
            }
            else
            {
                if (!lastRegion.chrom.empty())
                {
                    cigar += std::to_string(lastRegion.end + 1 - lastRegion.start) + "M,";
                }
            }
            lastRegion = region;
            cigar += lastRegion.chrom + '+' + std::to_string(lastRegion.start + 1) + '-';
        }
        else
        {
            cigar += std::to_string(lastRegion.length()) + "M" + std::to_string(s.length()) + "I";
        }
    }

    cigar += std::to_string(lastRegion.length()) + "M";
    //    os << '>' << dbg << std::endl;
    os << '>' << path_id << '_' << cigar << "\n" << sequence << std::endl;
    if (!os)
    {
        error("ERROR: Failed to write output to '%s' error: '%s'", file.c_str(), std::strerror(errno));
    }
}

void dumpPathContigs(
    const Json::Value& root, const std::string& referencePath,
    //                     TargetRegion& targetRegion,
    std::ostream& os, const std::string& file)
{
    const Json::Value& pathsIn = root["paths"];
    // Initialize the graph aligner.
    graphtools::Graph graph = grm::graphFromJson(root, referencePath);

    std::unordered_map<std::string, const Json::Value&> nodes;

    for (const auto& n : root["nodes"])
    {
        const std::string nodeName = n["name"].asString();
        assert(!nodes.count(nodeName));
        nodes.emplace(nodeName, n);
    }

    const std::list<graphtools::Path> paths = grm::pathsFromJson(&graph, pathsIn);

    for (const auto& path : paths)
    {
        dumpPath(
            graph, nodes, path,
            // targetRegion,
            os, file);
    }
}

int main(int argc, char const* argv[])
{
    po::options_description desc("Allowed options");
    desc.add_options()("help,h", "produce help message")(
        "graph-spec,g", po::value<std::vector<std::string>>()->multitoken(), "JSON file(s) describing the graph")(
        "output-file,o", po::value<std::string>(),
        "Output file name. "
        "Will output to stdout if '-' or neither of output-file or output-folder provided.")(
        "output-folder,O", po::value<std::string>(),
        "Output folder path. paragraph will attempt to create "
        "the folder but not the entire path. Will output to stdout if neither of output-file or "
        "output-folder provided. If specified, paragraph will produce one output file for each "
        "input file bearing the same name.")("reference,r", po::value<std::string>(), "FASTA with reference genome")(
        "log-level", po::value<std::string>()->default_value("info"), "Set log level (error, warning, info).")(
        "log-file", po::value<std::string>()->default_value(""), "Log to a file instead of stderr.")(
        "log-async", po::value<bool>()->default_value(true), "Enable / disable async logging.");

    po::variables_map vm;
    try
    {
        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);

        if (vm.empty() || (vm.count("help") != 0u))
        {
            std::cerr << desc << std::endl;
            return 1;
        }

        initLogging(
            "paragraph", vm["log-file"].as<std::string>().c_str(), vm["log-async"].as<bool>(),
            vm["log-level"].as<std::string>().c_str());

        std::vector<std::string> graph_spec_paths;
        if (vm.count("graph-spec") != 0u)
        {
            graph_spec_paths = vm["graph-spec"].as<std::vector<std::string>>();
            LOG()->info("Graph spec: {}", boost::join(graph_spec_paths, ","));
            assertFilesExist(graph_spec_paths.begin(), graph_spec_paths.end());
            if (vm.count("output-folder"))
            {
                // If we're to produce individual output files per input, the input file
                // paths must have unique file names.
                assertFileNamesUnique(graph_spec_paths.begin(), graph_spec_paths.end());
            }
        }
        else
        {
            error("ERROR: File with variant specification is missing.");
        }

        std::ofstream outputFileStream;
        std::string output_file_path;
        if (vm.count("output-file") != 0u)
        {
            output_file_path = vm["output-file"].as<std::string>();
        }
        else if (!vm.count("output-folder"))
        {
            output_file_path = "-";
        }
        if (!output_file_path.empty())
        {
            if ("-" != output_file_path)
            {
                LOG()->info("Output file path: {}", output_file_path);
                outputFileStream.open(output_file_path);
                if (!outputFileStream)
                {
                    error(
                        "ERROR: Failed to open output file '%s'. Error: '%s'", output_file_path.c_str(),
                        std::strerror(errno));
                }
            }
            else
            {
                LOG()->info("Output to stdout");
            }
        }

        std::string output_folder_path;
        if (vm.count("output-folder"))
        {
            output_folder_path = vm["output-folder"].as<std::string>();
            LOG()->info("Output folder path: {}", output_folder_path);
            boost::filesystem::create_directory(output_folder_path);
        }

        std::string reference_path;
        if (vm.count("reference") != 0u)
        {
            reference_path = vm["reference"].as<std::string>();
            LOG()->info("Reference: {}", reference_path);
            assertFileExists(reference_path);
        }
        else
        {
            error("ERROR: Reference genome is missing.");
        }

        for (auto graph_spec_path : graph_spec_paths)
        {
            LOG()->info("Loading parameters {}", graph_spec_path);
            Json::Value root;
            std::ifstream graph_desc(graph_spec_path);
            graph_desc >> root;

            if ("-" == output_file_path)
            {
                dumpPathContigs(
                    root, reference_path,
                    // targetRegion,
                    std::cout, "standard output");
            }
            else if (!output_file_path.empty())
            {
                dumpPathContigs(
                    root, reference_path,
                    // targetRegion,
                    std::cout, output_file_path);
            }

            if (!output_folder_path.empty())
            {
                boost::filesystem::path inputPath(graph_spec_path);
                boost::filesystem::path outputPath = boost::filesystem::path(output_folder_path) / inputPath.filename();
                std::ofstream ofs(outputPath.string());
                if (!ofs)
                {
                    error(
                        "ERROR: Failed to open output file '%s'. Error: '%s'", outputPath.string().c_str(),
                        std::strerror(errno));
                }
                dumpPathContigs(
                    root, reference_path,
                    // targetRegion,
                    std::cout, outputPath.string());
            }
        }
    }
    catch (const std::exception& e)
    {
        if (LOG())
        {
            LOG()->critical(e.what());
        }
        else
        {
            std::cerr << e.what() << std::endl;
        }
        return 1;
    }

    return 0;
}

max_stars_repo_name: vb-wayne/paragraph

max_issues_repo_name: vb-wayne/paragraph

max_forks_repo_name: vb-wayne/paragraph


text: #include <boost/assign/std/list.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright Vladimir Prus 2002-2004.
// 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 "navigation.hpp"
#include "snx.hpp"
nav_t nav = {};

#include <boost/program_options.hpp>

using namespace boost;
namespace po = boost::program_options;

#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;

#include <boost/assign/list_inserter.hpp> // for 'insert()'
using namespace boost::assign;

// A helper function to simplify the main part.
template<class T>
ostream& operator<<(ostream& os, const vector<T>& v)
{
    copy(v.begin(), v.end(), ostream_iterator<T>(os, " "));
    return os;
}

int main(int ac, char* av[])
{
    try {
        int opt;
        int portnum;
        po::options_description desc("Allowed options");
        desc.add_options()
            ("help,h", "produce help message")
            ("verbose,v", po::value<int>()->implicit_value(1),
                  "enable verbosity (optionally specify level)")
            ("input-file,f", po::value< vector<string> >(), "input file")
        ;

        po::positional_options_description p;
        p.add("input-file", -1);

        po::variables_map vm;
        po::store(po::command_line_parser(ac, av).
                  options(desc).positional(p).run(), vm);
        po::notify(vm);

        if (vm.count("help")) {
            cout << "Usage: options_description [options]\n";
            cout << desc;
            return 0;
        }

        if (vm.count("input-file"))
        {
            cout << "Input files are: "
                 << vm["input-file"].as< vector<string> >() << "\n";
        }

        if (vm.count("verbose")) {
            cout << "Verbosity enabled.  Level is " << vm["verbose"].as<int>()
                 << "\n";
        }

        if (vm.count("input-file"))
            {
                cout<<vm["input-file"].as< vector<string> >();
                auto test = vm["input-file"].as< vector<string> >();
                // auto test2 = vm["input-file"].as< vector<string> >();
                for (auto it = test.begin(); it != test.end(); it++ )
                {
                    cout <<*it<< endl;
                    //   string filepath ("/data/acs/pea/proc/exs/products/igs19P2062.snx");
                    read_sinex(*it, true);
                    for (auto [index, estimate] : theSinex.map_estimates_primary)
                    {
                        // cout << estimate.sitecode.c_str()<< estimate.refepoch[0] << estimate.type.c_str() << endl;
                        //printf("%s %d:%d:%d %s %f %f\n",
                        //estimate.sitecode.c_str(),
                        //estimate.refepoch[0],
                        //estimate.refepoch[1],
                        //estimate.refepoch[2],
                        //estimate.type.c_str(),
                        //estimate.estimate,
                        //estimate.stddev
                        //);
                    }
                }

            }
        }
    catch(std::exception& e)
    {
        cout << e.what() << "\n";
        return 1;
    }

    return 0;
}