text:
#include <iostream>

#ifdef EIGEN_DEVELOP
#include <Eigen/Dense>
#endif

#ifdef CERES_DEVELOP
#include <ceres/ceres.h>
#endif

#ifdef OPENCV_DEVELOP
#include <opencv2/core.hpp>
#endif

#ifdef PCL_DEVELOP
#include <pcl/pcl_base.h>
#include <pcl/pcl_config.h>
#endif

#ifdef GTSAM_DEVELOP
#include <gtsam/global_includes.h>
#endif

#ifdef SPDLOG_DEVELOP
#include <fstream>
#include <json/nlohmann/json.hpp>
#include <log/csv.h>
#include <spdlog/version.h>
#endif

int main()
{
    std::cout << "Hello World!" << std::endl;

#ifdef OPENCV_DEVELOP
    std::cout << "OpenCV Version: " << CV_VERSION << std::endl;
#endif

#ifdef EIGEN_DEVELOP
    std::cout << "Eigen Version: " << EIGEN_WORLD_VERSION << "." << EIGEN_MAJOR_VERSION << "." << EIGEN_MINOR_VERSION << std::endl;
#endif

#ifdef PCL_DEVELOP
    std::cout << "PCL(Point Cloud Libarry) Version: " << PCL_VERSION_PRETTY << std::endl;
#endif

#ifdef CERES_DEVELOP
    std::cout << "Ceres-solver Version: " << CERES_VERSION_STRING << std::endl;
#endif

#ifdef GTSAM_DEVELOP
    std::cout << "GTSAM Version: " << GTSAM_VERSION_STRING << std::endl;
#endif

#ifdef SPDLOG_DEVELOP
    std::cout << "spdlog Version: " << SPDLOG_VER_MAJOR << "." << SPDLOG_VER_MINOR << "." << SPDLOG_VER_PATCH << std::endl;

    io::CSVReader<3> reader("./resource/sampleCSV.csv");
    std::string first, second, third;
    while (reader.read_row(first, second, third))
        std::cout << first << second << " " << third << std::endl;

    std::ifstream file("./resource/sampleJSON.json");
    nlohmann::json j;
    file >> j;
    std::vector<std::string> keys = { "first", "second", "third" };
    std::string str;
    for (const auto& key : keys)
        str += j[key];
    std::cout << str << std::endl;
#endif

    return 0;
}

ext: cpp


text:
/*
 * The MIT License (MIT)
 *
 * Copyright (c) <2016> <Stephan Gatzka>
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE state / method access tests

#include <boost/test/unit_test.hpp>
#include <list>

#include <stdio.h>

#include "authenticate.h"
#include "compiler.h"
#include "element.h"
#include "eventloop.h"
#include "fetch.h"
#include "json/cJSON.h"
#include "parse.h"
#include "table.h"

#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))

enum event {
	UNKNOWN_EVENT,
	ADD_EVENT,
	CHANGE_EVENT,
	REMOVE_EVENT
};

static struct io_event *timer_ev;
static struct eventloop loop;

static const char users[] = "users";
static const char admins[] = "admin";

static cJSON *user_auth;

static struct peer fetch_peer;

static std::list<cJSON*> fetch_events;

extern "C" {
	const cJSON *credentials_ok(const char *user_name, char *passwd)
	{
		(void)passwd;

		if (std::strcmp(user_name, "user") == 0) {
			return user_auth;
		}

		return NULL;
	}

	cJSON *change_password(const struct peer *p, const cJSON *request, const char *user, char *passwd)
	{
		(void)p;
		(void)request;
		(void)user;
		(void)passwd;
		return NULL;
	}

	cjet_ssize_t socket_read(socket_type sock, void *buf, size_t count)
	{
		(void)sock;
		(void)count;
		uint64_t number_of_timeouts = 1;
		::memcpy(buf, &number_of_timeouts, sizeof(number_of_timeouts));
		return 8;
	}

	int socket_close(socket_type sock)
	{
		(void)sock;
		return 0;
	}
}

static cJSON *parse_send_buffer(const char *json)
{
	const char *end_parse;
	cJSON *root = cJSON_ParseWithOpts(json, &end_parse, 0);
	return root;
}

static int send_message(const struct peer *p, char *rendered, size_t len)
{
	(void)len;
	if (p == &fetch_peer) {
		cJSON *fetch_event = parse_send_buffer(rendered);
		fetch_events.push_back(fetch_event);
	}

	return 0;
}

static enum eventloop_return fake_add(const void *this_ptr, const struct io_event *ev)
{
	(void)this_ptr;
	timer_ev = (struct io_event *)ev;
	return EL_CONTINUE_LOOP;
}

static void fake_remove(void *this_ptr, const struct io_event *ev)
{
	(void)this_ptr;
	(void)ev;
	timer_ev = NULL;
	return;
}

static cJSON *create_fetch(const char *path_equals_string)
{
	cJSON *params = cJSON_CreateObject();
	BOOST_REQUIRE(params != NULL);
	cJSON_AddStringToObject(params, "id", "fetch_id_1");
	cJSON *fetch_path = cJSON_CreateObject();
	BOOST_REQUIRE(fetch_path != NULL);
	cJSON_AddItemToObject(params, "path", fetch_path);
	if (strlen(path_equals_string)) {
		cJSON_AddStringToObject(fetch_path, "equals", path_equals_string);
	}

	cJSON *root = cJSON_CreateObject();
	cJSON_AddItemToObject(root, "params", params);
	cJSON_AddStringToObject(root, "id", "fetch_request_1");
	cJSON_AddStringToObject(root, "method", "fetch");
	return root;
}

static enum event get_event_from_json(cJSON *json)
{
	cJSON *params = cJSON_GetObjectItem(json, "params");
	if (params == NULL) return UNKNOWN_EVENT;
	cJSON *event = cJSON_GetObjectItem(params, "event");
	if (event == NULL) return UNKNOWN_EVENT;
	if (event->type != cJSON_String) return UNKNOWN_EVENT;
	if (std::strcmp(event->valuestring, "add") == 0) return ADD_EVENT;
	if (std::strcmp(event->valuestring, "change") == 0) return CHANGE_EVENT;
	if (std::strcmp(event->valuestring, "remove") == 0) return REMOVE_EVENT;
	return UNKNOWN_EVENT;
}

static bool response_is_error(const cJSON *response)
{
	const cJSON *error = cJSON_GetObjectItem(response, "error");
	return (error != NULL);
}

static void perform_fetch(const char *fetch_path)
{
	struct fetch *f = NULL;
	cJSON *request = create_fetch(fetch_path);
	cJSON *response;
	int ret = add_fetch_to_peer(&fetch_peer, request, &f, &response);
	BOOST_REQUIRE_MESSAGE(ret == 0, "add_fetch_to_peer() failed!");
	response = add_fetch_to_states(&fetch_peer, request, f);
	BOOST_REQUIRE_MESSAGE(response != NULL, "add_fetch_to_states() had no response!");
	BOOST_CHECK_MESSAGE(!response_is_error(response), "add_fetch_to_states() failed!");
	cJSON_Delete(response);
	cJSON_Delete(request);
}

static cJSON *create_add_with_access(const char *path, cJSON *access)
{
	cJSON *params = cJSON_CreateObject();
	BOOST_REQUIRE(params != NULL);
	cJSON_AddStringToObject(params, "path", path);
	cJSON_AddItemToObject(params, "value", cJSON_CreateNumber(1234));
	cJSON_AddItemToObject(params, "access", access);

	cJSON *root = cJSON_CreateObject();
	cJSON_AddItemToObject(root, "params", params);
	cJSON_AddStringToObject(root, "id", "add_request_1");
	cJSON_AddStringToObject(root, "method", "add");
	return root;
}

static cJSON *create_authentication_with_params(cJSON *params)
{

	cJSON *root = cJSON_CreateObject();
	if (params != NULL) {
		cJSON_AddItemToObject(root, "params", params);
	}

	cJSON_AddStringToObject(root, "id", "auth_request");
	cJSON_AddStringToObject(root, "method", "authenticate");
	return root;
}

static cJSON *create_authentication()
{
	cJSON *params = cJSON_CreateObject();
	BOOST_REQUIRE(params != NULL);
	cJSON_AddStringToObject(params, "user", "user");
	cJSON_AddStringToObject(params, "password", "password");
	return create_authentication_with_params(params);
}

char *extract_error_message(const cJSON *request_error)
{

	const cJSON *error = cJSON_GetObjectItem(request_error, "error");
	BOOST_REQUIRE_MESSAGE(error != NULL, "No error object given!");

	const cJSON *error_data = cJSON_GetObjectItem(error, "data");
	BOOST_REQUIRE_MESSAGE(error_data != NULL, "No data object within given error message!");

	const cJSON *error_string_reason = cJSON_GetObjectItem(error_data, "reason");
	if (error_string_reason != NULL) {
		BOOST_REQUIRE_MESSAGE(error_string_reason->type == cJSON_String, "Given reason is no string!");
		return error_string_reason->valuestring;
	} else {
		const cJSON *error_string_auth = cJSON_GetObjectItem(error_data, "fetched before authenticate");
		if (error_string_auth == NULL) {
			BOOST_FAIL("no object reason given within error message");
			return NULL;
		} else {
			return error_string_auth->string;
		}
	}
}

struct F {
	F()
	{
		timer_ev = NULL;
		loop.this_ptr = NULL;
		loop.init = NULL;
		loop.destroy = NULL;
		loop.run = NULL;
		loop.add = fake_add;
		loop.remove = fake_remove;

		init_parser();
		element_hashtable_create();
		init_peer(&owner_peer, false, &loop);
		owner_peer.send_message = send_message;
		init_peer(&fetch_peer, false, &loop);
		fetch_peer.send_message = send_message;

		cJSON *groups = cJSON_CreateArray();
		cJSON_AddItemToArray(groups, cJSON_CreateString(admins));
		cJSON_AddItemToArray(groups, cJSON_CreateString(users));
		cJSON_AddItemToArray(groups, cJSON_CreateString("operators"));
		cJSON_AddItemToArray(groups, cJSON_CreateString("viewers"));
		create_groups();

		add_groups(groups);
		cJSON_Delete(groups);

		user_auth = cJSON_CreateObject();
		cJSON *fetch_groups = cJSON_CreateArray();
		cJSON_AddItemToArray(fetch_groups, cJSON_CreateString(users));
		cJSON_AddItemToObject(user_auth, "fetchGroups", fetch_groups);
		cJSON *set_groups = cJSON_CreateArray();
		cJSON_AddItemToArray(set_groups, cJSON_CreateString(users));
		cJSON_AddItemToObject(user_auth, "setGroups", set_groups);
		cJSON *call_groups = cJSON_CreateArray();
		cJSON_AddItemToArray(call_groups, cJSON_CreateString(users));
		cJSON_AddItemToObject(user_auth, "callGroups", call_groups);

		password = ::strdup("password");
	}

	~F()
	{
		::free(password);

		while (!fetch_events.empty()) {
			cJSON *ptr = fetch_events.front();
			fetch_events.pop_front();
			cJSON_Delete(ptr);
		}
		cJSON_Delete(user_auth);
		free_groups();
		free_peer_resources(&fetch_peer);
		free_peer_resources(&owner_peer);
		element_hashtable_delete();
	}

	char *password;
	struct peer owner_peer;
};
BOOST_FIXTURE_TEST_CASE(authenticate_without_param, F)
{
	cJSON *auth = create_authentication_with_params(NULL);

	cJSON *response = handle_authentication(&fetch_peer, auth);
	BOOST_REQUIRE_MESSAGE(response != NULL, "Fetch peer authentication had no response!");
	BOOST_CHECK_MESSAGE(response_is_error(response), "No error returned and successfully authenticated, even without giving any parameters.");
	char *error_message = extract_error_message(response);
	BOOST_CHECK_MESSAGE(!std::strcmp(error_message, "no params found"), "The expected error is: \"no params found\", but was: \"" << error_message << "\".");

	cJSON_Delete(response);
	response = handle_change_password(&fetch_peer, auth);
	error_message = extract_error_message(response);
	BOOST_CHECK_MESSAGE(!std::strcmp(error_message, "no params found"), "The expected error is: \"no params found\", but was: \"" << error_message << "\".");

	cJSON_Delete(auth);
	cJSON_Delete(response);
}

BOOST_FIXTURE_TEST_CASE(authenticate_without_param_user, F)
{
	cJSON *params = cJSON_CreateObject();
	BOOST_REQUIRE(params != NULL);
	cJSON_AddStringToObject(params, "password", "password");

	cJSON *auth = create_authentication_with_params(params);

	cJSON *response = handle_authentication(&fetch_peer, auth);
	BOOST_REQUIRE_MESSAGE(response != NULL, "fetch peer authentication had no response!");
	BOOST_CHECK_MESSAGE(response_is_error(response), "No error returned and successfully authenticated, even without providing a username.");
	char *error_message = extract_error_message(response);
	BOOST_CHECK_MESSAGE(!std::strcmp(error_message, "no user given"), "The expected error is: \"no user given\", but was: \"" << error_message << "\".");

	cJSON_Delete(response);
	response = handle_change_password(&fetch_peer, auth);
	error_message = extract_error_message(response);
	BOOST_CHECK_MESSAGE(!std::strcmp(error_message, "no user given"), "The expected error is: \"no user given\", but was: \"" << error_message << "\".");

	cJSON_Delete(auth);
	cJSON_Delete(response);
}

BOOST_FIXTURE_TEST_CASE(authenticate_with_param_int_user, F)
{
	cJSON *params = cJSON_CreateObject();
	BOOST_REQUIRE(params != NULL);
	cJSON_AddNumberToObject(params, "user", 42);
	cJSON_AddStringToObject(params, "password", "password");

	cJSON *auth = create_authentication_with_params(params);

	cJSON *response = handle_authentication(&fetch_peer, auth);
	BOOST_REQUIRE_MESSAGE(response != NULL, "fetch peer authentication had no response!");
	BOOST_CHECK_MESSAGE(response_is_error(response), "No error returned and successfully authenticated, even with int as username");
	char *error_message = extract_error_message(response);
	BOOST_CHECK_MESSAGE(!std::strcmp(error_message, "user is not a string"), "The expected error is: \"user is not a string\", but was: \"" << error_message << "\".");

	cJSON_Delete(response);
	response = handle_change_password(&fetch_peer, auth);
	error_message = extract_error_message(response);
	BOOST_CHECK_MESSAGE(!std::strcmp(error_message, "user is not a string"), "The expected error is: \"user is not a string\", but was: \"" << error_message << "\".");

	cJSON_Delete(auth);
	cJSON_Delete(response);
}

BOOST_FIXTURE_TEST_CASE(authenticate_without_param_password, F)
{
	cJSON *params = cJSON_CreateObject();
	BOOST_REQUIRE(params != NULL);
	cJSON_AddStringToObject(params, "user", "user");

	cJSON *auth = create_authentication_with_params(params);

	cJSON *response = handle_authentication(&fetch_peer, auth);
	BOOST_REQUIRE_MESSAGE(response != NULL, "fetch peer authentication had no response!");
	BOOST_CHECK_MESSAGE(response_is_error(response), "No error returned and successfully authenticated, even without providing a password.");
	char *error_message = extract_error_message(response);
	BOOST_CHECK_MESSAGE(!std::strcmp(error_message, "no password given"), "The expected error is: \"no password given\", but was: \"" << error_message << "\".");

	cJSON_Delete(response);
	response = handle_change_password(&fetch_peer, auth);
	error_message = extract_error_message(response);
	BOOST_CHECK_MESSAGE(!std::strcmp(error_message, "no password given"), "The expected error is: \"no password given\", but was: \"" << error_message << "\".");

	cJSON_Delete(auth);
	cJSON_Delete(response);
}

BOOST_FIXTURE_TEST_CASE(authenticate_with_param_int_password, F)
{
	cJSON *params = cJSON_CreateObject();
	BOOST_REQUIRE(params != NULL);
	cJSON_AddStringToObject(params, "user", "user");
	cJSON_AddNumberToObject(params, "password", 42);

	cJSON *auth = create_authentication_with_params(params);

	cJSON *response = handle_authentication(&fetch_peer, auth);
	BOOST_REQUIRE_MESSAGE(response != NULL, "fetch peer authentication had no response!");
	BOOST_CHECK_MESSAGE(response_is_error(response), "No error returned and successfully authenticated, even with int as password");

	char *error_message = extract_error_message(response);
	BOOST_CHECK_MESSAGE(!std::strcmp(error_message, "password is not a string"), "The expected error is: \"password is not a string\", but was: \"" << error_message << "\".");

	cJSON_Delete(response);
	response = handle_change_password(&fetch_peer, auth);
	error_message = extract_error_message(response);
	BOOST_CHECK_MESSAGE(!std::strcmp(error_message, "password is not a string"), "The expected error is: \"password is not a string\", but was: \"" << error_message << "\".");

	cJSON_Delete(auth);
	cJSON_Delete(response);
}

BOOST_FIXTURE_TEST_CASE(authenticate_after_fetch, F)
{
	struct fetch *f = NULL;
	cJSON *request = create_fetch("foo/bar");
	cJSON *response;
	int ret = add_fetch_to_peer(&fetch_peer, request, &f, &response);
	BOOST_REQUIRE_MESSAGE(ret == 0, "add_fetch_to_peer() failed!");

	cJSON *auth = create_authentication();

	response = handle_authentication(&fetch_peer, auth);
	BOOST_REQUIRE_MESSAGE(response != NULL, "fetch peer authentication had no response!");

	BOOST_CHECK_MESSAGE(response_is_error(response), "No error returned and successfully authenticated, even after peer added fetches.");
	char *error_message = extract_error_message(response);
	BOOST_CHECK_MESSAGE(!std::strcmp(error_message, "fetched before authenticate"), "The expected error is: \"fetched before authenticate\", but was: \"" << error_message << "\".");

	cJSON_Delete(request);
	cJSON_Delete(auth);
	cJSON_Delete(response);
}

BOOST_FIXTURE_TEST_CASE(fetch_state_allowed, F)
{
	const char path[] = "/foo/bar/";

	cJSON *access = cJSON_CreateObject();
	cJSON *fetch_groups = cJSON_CreateArray();
	cJSON_AddItemToArray(fetch_groups, cJSON_CreateString(users));
	cJSON_AddItemToObject(access, "fetchGroups", fetch_groups);

	cJSON *request = create_add_with_access(path, access);

	cJSON *response = add_element_to_peer(&owner_peer, request);
	BOOST_REQUIRE_MESSAGE(response != NULL, "add_element_to_peer() had no response!");
	BOOST_CHECK_MESSAGE(!response_is_error(response), "add_element_to_peer() failed!");
	cJSON_Delete(request);
	cJSON_Delete(response);

	request = create_authentication();
	response = handle_authentication(&fetch_peer, request);
	BOOST_REQUIRE_MESSAGE(response != NULL, "fetch peer authentication had no response!");
	BOOST_CHECK_MESSAGE(!response_is_error(response), "fetch peer authentication failed!");
	cJSON_Delete(request);
	cJSON_Delete(response);

	perform_fetch(path);
	BOOST_REQUIRE_MESSAGE(fetch_events.size() == 1, "Number of emitted events != 1!");
	cJSON *json = fetch_events.front();
	fetch_events.pop_front();
	event event = get_event_from_json(json);
	BOOST_CHECK_MESSAGE(event == ADD_EVENT, "Emitted event is not an ADD event!");
	cJSON_Delete(json);
	remove_all_fetchers_from_peer(&fetch_peer);
}

BOOST_FIXTURE_TEST_CASE(fetch_state_not_allowed, F)
{
	const char path[] = "/foo/bar/";

	cJSON *access = cJSON_CreateObject();
	cJSON *fetch_groups = cJSON_CreateArray();
	cJSON_AddItemToArray(fetch_groups, cJSON_CreateString(admins));
	cJSON_AddItemToObject(access, "fetchGroups", fetch_groups);

	cJSON *request = create_add_with_access(path, access);

	cJSON *response = add_element_to_peer(&owner_peer, request);
	BOOST_REQUIRE_MESSAGE(response != NULL, "add_element_to_peer() had no response!");
	BOOST_CHECK_MESSAGE(!response_is_error(response), "add_element_to_peer() failed!");
	cJSON_Delete(request);
	cJSON_Delete(response);

	request = create_authentication();
	response = handle_authentication(&fetch_peer, request);
	BOOST_REQUIRE_MESSAGE(response != NULL, "fetch peer authentication had no response!");
	BOOST_CHECK_MESSAGE(!response_is_error(response), "fetch peer authentication failed!");
	cJSON_Delete(request);
	cJSON_Delete(response);

	perform_fetch(path);
	BOOST_REQUIRE_MESSAGE(fetch_events.size() == 0, "Number of emitted events != 0!");
	remove_all_fetchers_from_peer(&fetch_peer);
}

BOOST_AUTO_TEST_CASE(add_group_twice)
{
	cJSON *groups = cJSON_CreateArray();
	cJSON_AddItemToArray(groups, cJSON_CreateString("viewers"));
	cJSON_AddItemToArray(groups, cJSON_CreateString("viewers"));
	create_groups();
	int ret = add_groups(groups);
	cJSON_Delete(groups);
	BOOST_CHECK_MESSAGE(ret == 0, "adding a group twice failed!");
	free_groups();
}

BOOST_AUTO_TEST_CASE(add_too_many_groups)
{
	create_groups();

	cJSON *groups = cJSON_CreateArray();
	for (unsigned int i = 0; i <= sizeof(group_t) * 8; i++) {
		char buffer[10];
		::sprintf(buffer, "%s%d", "viewer", i);
		cJSON_AddItemToArray(groups, cJSON_CreateString(buffer));
	}

	int ret = add_groups(groups);
	cJSON_Delete(groups);
	BOOST_CHECK_MESSAGE(ret == -1, "adding lots of groups did not fail!");
	free_groups();
}

BOOST_AUTO_TEST_CASE(add_non_array_group)
{
	create_groups();

	cJSON *groups = cJSON_CreateFalse();
	int ret = add_groups(groups);
	cJSON_Delete(groups);
	BOOST_CHECK_MESSAGE(ret == -1, "adding a non-array group did not fail!");
	free_groups();
}

BOOST_AUTO_TEST_CASE(add_no_string_in_group)
{
	create_groups();

	cJSON *groups = cJSON_CreateArray();
	cJSON_AddItemToArray(groups, cJSON_CreateFalse());
	int ret = add_groups(groups);
	cJSON_Delete(groups);
	BOOST_CHECK_MESSAGE(ret == -1, "adding a non string group member did not fail!");
	free_groups();
}

max_stars_repo_name: mloy/cjet

max_issues_repo_name: mloy/cjet

max_forks_repo_name: mloy/cjet


text:
/**
 *          Copyright Springbeats Sarl 2013.
 * 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 "TcpRpcServer.hpp"
#include "ThreadSafeMap.hpp"
#include <boost/bind.hpp>
#include <sstream>

using std::ostringstream;

namespace pbrpcpp {
    TcpRpcServer::ClientData::ClientData( int clientId, boost::asio::io_service& io_service )
    : clientId_(clientId),
    clientSock_(io_service)
    {

    }

    TcpRpcServer::ClientData::~ClientData() {
        boost::system::error_code ec;
        GOOGLE_LOG( INFO ) << "TcpRpcServer::ClientData::~ClientData";
        clientSock_.cancel( ec );
        clientSock_.shutdown( tcp::socket::shutdown_both, ec );
        clientSock_.close( ec );
    }

    bool TcpRpcServer::ClientData::extractMessage(string& msg) {
        try {
            return RpcMessage::extractNetPacket( receivedMsg_, msg );
        } catch (...) {
            boost::system::error_code ec;

            clientSock_.close(ec);
        }
        return false;
    }

    TcpRpcServer::TcpRpcServer( const string& listenAddr, const string& listenPort)
    :listenAddr_( listenAddr ),
    listenPort_( listenPort ),
    nextClientId_( 0 ),
    io_service_stopped_( true ),
    clientDataMgr_( new ThreadSafeMap< int, shared_ptr<ClientData> >() )
    {
    }

    TcpRpcServer::~TcpRpcServer() {
        Shutdown();
    }

    void TcpRpcServer::Run() {
        boost::system::error_code ec;

        tcp::resolver resolver(io_service_ );
        tcp::resolver::query query( listenAddr_, listenPort_ );
        tcp::resolver::iterator iter = resolver.resolve(query, ec );

        if( ec ) {
            GOOGLE_LOG( FATAL ) << "fail to resolve listening address " << listenAddr_ << ":" << listenPort_;
        } else {
            GOOGLE_LOG( INFO ) << "start to accept TCP connection";

            acceptor_.reset( new tcp::acceptor( io_service_, *iter ));
            acceptor_->set_option( tcp::socket::reuse_address(true), ec );
            startAccept();

            io_service_stopped_ = false;
            io_service_.run( ec );
            io_service_stopped_ = true;
        }
    }

    void TcpRpcServer::Shutdown() {
        if( io_service_stopped_ ) {
            return;
        }

        if( acceptor_ ) {
            boost::system::error_code ec;
            acceptor_->cancel( ec );
            acceptor_->close( ec );
        }

        while( getProcessingRequests() > 0 ) {
            boost::this_thread::yield();
        }

        clientDataMgr_->erase_all();

        io_service_.stop();

        while( !io_service_stopped_ ) {
            boost::this_thread::yield();
        }
    }

    bool TcpRpcServer::getLocalEndpoint( tcp::endpoint& ep ) const {
            shared_ptr<tcp::acceptor> tmp = acceptor_;
            if( tmp ) {
                boost::system::error_code ec;
                ep = tmp->local_endpoint( ec );
                return !ec;
            } else {
                return false;
            }
        }

    bool TcpRpcServer::getLocalEndpoint( string& addr, string& port ) const {
        tcp::endpoint ep;

        if( getLocalEndpoint( ep )) {
            addr = ep.address().to_string();
            ostringstream out;

            out << ep.port();
            port = out.str();
            return true;
        }
        return false;
    }

    void TcpRpcServer::sendResponse( int clientId, const string& msg ) {
        shared_ptr< ClientData > clientData = clientDataMgr_->get( clientId );
        if( clientData ) {

            shared_ptr<string> s( new string( RpcMessage::serializeNetPacket( msg )) );

            GOOGLE_LOG( INFO ) << "send response to client with " << s->length() << " bytes";

            boost::asio::async_write( clientData->clientSock_,
                    boost::asio::buffer( s->data(), s->length() ),
                    boost::asio::transfer_all(),
                    boost::bind( &TcpRpcServer::messageSent, this, _1, _2, s ) );
        } else {
            GOOGLE_LOG( ERROR ) << "fail to send response because the client is already disconnected";
        }
    }

    void TcpRpcServer::startAccept() {
        shared_ptr<ClientData> clientData( new ClientData( nextClientId_++, io_service_ ) );
        acceptor_->async_accept( clientData->clientSock_, boost::bind( &TcpRpcServer::connAccepted, this, clientData, _1 ));
    }

    void TcpRpcServer::connAccepted( shared_ptr<ClientData> clientData, const boost::system::error_code& ec ) {
        if( ec || stop_ ) {
            GOOGLE_LOG( ERROR ) << "fail to accept connection from client";
        } else {
            GOOGLE_LOG( INFO ) << "a client connection is accepted";
            boost::system::error_code error;
            clientData->clientSock_.set_option(tcp::socket::reuse_address(true), error );
            clientDataMgr_->insert( clientData->clientId_, clientData );
            startRead( clientData );
            startAccept();
        }
    }

    void TcpRpcServer::startRead( shared_ptr<ClientData> clientData ) {
        if( clientData ) {
            boost::asio::async_read( clientData->clientSock_,
                    boost::asio::buffer( clientData->msgBuffer_, sizeof( clientData->msgBuffer_ ) ),
                    boost::asio::transfer_at_least(1),
                    boost::bind( &TcpRpcServer::clientDataReceived, this, _1, _2, clientData ) );
        }
    }

    void TcpRpcServer::clientDataReceived( const boost::system::error_code& ec,
                        std::size_t bytes_transferred,
                        shared_ptr<ClientData> clientData ) {
        if( ec ) {
            GOOGLE_LOG( ERROR ) << "fail to receive data from client";
            clientDataMgr_->erase( clientData->clientId_ );
            return;
        }

        try {
            GOOGLE_LOG( INFO ) << bytes_transferred << " bytes received from client";
            clientData->receivedMsg_.append( clientData->msgBuffer_, bytes_transferred );
            string msg;
            while( clientData->extractMessage( msg ) ) {
                GOOGLE_LOG(INFO) << "a message is received";
                messageReceived( clientData->clientId_, msg );
            }

            startRead( clientData );
        }catch( ... ) {
        }
    }

    void TcpRpcServer::messageSent( const boost::system::error_code& ec,
                        std::size_t bytes_transferred,
                        shared_ptr<string> buf ) {
        if( ec ) {
            GOOGLE_LOG( ERROR ) << "fail to send message to client";
        } else {
            GOOGLE_LOG( INFO ) << "success to send " << bytes_transferred << " bytes message to client";
        }
    }

}//end name space pbrpcpp

max_stars_repo_name: adanselm/pbRPCpp

max_issues_repo_name: adanselm/pbRPCpp

max_forks_repo_name: adanselm/pbRPCpp


text:
#include "session.h"
#include <cstdlib>
#include <memory>
#include <utility>
#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/system/error_code.hpp>
#include <spdlog_easy.hpp>

namespace asio = boost::asio;
using io_context_t = asio::io_context;
using error_code_t = boost::system::error_code;
using acceptor_t = asio::ip::tcp::acceptor;
using socket_t = asio::ip::tcp::socket;
using yield_context_t = asio::yield_context;
using endpoint_t = asio::ip::tcp::endpoint;
using address_t = asio::ip::address;
using strand_t = asio::strand<boost::asio::io_context::executor_type>;

using namespace std;

session_t::session_t(io_context_t& io_context)
    :_socket(io_context), _strand(io_context.get_executor())
{
}

session_t::~session_t()
{
    auto remote_endpoint = _socket.remote_endpoint();
    auto address = remote_endpoint.address().to_string();
    auto port = remote_endpoint.port();
    LOG(info, "address:{0} port:{1}", address, port);
}

socket_t& session_t::socket()
{
    return _socket;
}

buffer_t& session_t::read_buffer()
{
    return _read_buffer;
}

buffer_t& session_t::write_buffer()
{
    return _write_buffer;
}

strand_t& session_t::strand()
{
    return _strand;
}

std::size_t async_read(
    session_t& session,
    std::size_t size,
    boost::system::error_code& ec,
    boost::asio::yield_context& yield)
{
    auto& socket = session.socket();
    auto& read_buffer = session.read_buffer();
    auto& read_offset = session.read_buffer().offset();
    if (read_offset + size > read_buffer.size())
    {
        read_buffer.resize(read_offset + size);
    }
    auto read_size = socket.async_read_some(asio::buffer(read_buffer.data() + read_offset, size), yield[ec]);
    if (!ec)
    {
        read_offset += read_size;
    }
    return read_size;
}

std::size_t async_write(
    session_t& session,
    std::size_t size,
    boost::system::error_code& ec,
    boost::asio::yield_context& yield)
{
    auto& socket = session.socket();
    auto& write_buffer = session.write_buffer();
    auto& write_offset = session.write_buffer().offset();
    if (write_offset + size > write_buffer.size())
    {
        write_buffer.resize(write_offset + size);
    }
    auto write_size = socket.async_write_some(asio::buffer(write_buffer.data() + write_offset, size), yield[ec]);
    if (!ec)
    {
        write_offset += write_size;
    }
    return write_size;
}

max_stars_repo_name: gwankyun/asio-spawn-echo-server

max_issues_repo_name: gwankyun/asio-spawn-echo-server

max_forks_repo_name: gwankyun/asio-spawn-echo-server


text:
#include <boost/math/special_functions/erf.hpp>

extern "C" {
  double cpp_erf(double p) {
    return boost::math::erf(p);
  }

  double cpp_erf_inv(double p) {
    return boost::math::erf_inv(p);
  }
}

max_stars_repo_name: Etdescamps/MlFortran

max_issues_repo_name: Etdescamps/MlFortran

max_forks_repo_name: Etdescamps/MlFortran


text:
#include <glib.h>
#include "cmake.h"
#include "project_build.h"
#include "config.h"
#include <boost/filesystem.hpp>
#include "process.hpp"

#include <iostream>
using namespace std;

int main() {
  auto tests_path=boost::filesystem::canonical(JUCI_TESTS_PATH);
  {
    auto project_path=boost::filesystem::canonical(tests_path/"..");

    {
      CMake cmake(project_path);
      TinyProcessLib::Process process("cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ..", (project_path/"build").string(), [](const char *bytes, size_t n) {});
      g_assert(process.get_exit_status()==0);

      g_assert(cmake.get_executable(project_path/"build", project_path)=="");
      g_assert(cmake.get_executable(project_path/"build"/"non_existing_file.cc", project_path)=="");
    }
    {
      CMake cmake(project_path/"src");
      g_assert(cmake.get_executable(project_path/"build", project_path/"src")==project_path/"build"/"src"/"juci");
      g_assert(cmake.get_executable(project_path/"build", project_path/"src"/"cmake.cc")==project_path/"build"/"src"/"juci");
      g_assert(cmake.get_executable(project_path/"build", project_path/"src"/"juci.cc")==project_path/"build"/"src"/"juci");
      g_assert(cmake.get_executable(project_path/"build", project_path/"src"/"non_existing_file.cc")==project_path/"build"/"src"/"juci");
    }
    {
      CMake cmake(tests_path);

      g_assert(cmake.project_path==project_path);

      auto functions_parameters=cmake.get_functions_parameters("project");
      g_assert(functions_parameters.at(0).second.at(0)=="juci");

      g_assert(cmake.get_executable(project_path/"build", tests_path).parent_path()==project_path/"build"/"tests");
      g_assert(cmake.get_executable(project_path/"build", tests_path/"cmake_build_test.cc")==project_path/"build"/"tests"/"cmake_build_test");
      g_assert(cmake.get_executable(project_path/"build", tests_path/"non_existing_file.cc").parent_path()==project_path/"build"/"tests");
    }

    auto build=Project::Build::create(tests_path);
    g_assert(dynamic_cast<Project::CMakeBuild*>(build.get()));

    build=Project::Build::create(tests_path/"stubs");
    g_assert(dynamic_cast<Project::CMakeBuild*>(build.get()));
    g_assert(build->project_path==project_path);

    Config::get().project.default_build_path="./build";
    g_assert(build->get_default_path()==project_path/"build");

    Config::get().project.debug_build_path="<default_build_path>/debug";
    g_assert(build->get_debug_path()==project_path/"build/debug");

    auto project_path_filename=project_path.filename();
    Config::get().project.debug_build_path="../debug_<project_directory_name>";
    g_assert(build->get_debug_path()==project_path.parent_path()/("debug_"+project_path_filename.string()));

    Config::get().project.default_build_path="../build_<project_directory_name>";
    g_assert(build->get_default_path()==project_path.parent_path()/("build_"+project_path_filename.string()));
  }
  {
    auto project_path=tests_path/"source_clang_test_files";
    CMake cmake(project_path);

    g_assert(cmake.project_path==project_path);

    g_assert(cmake.get_executable(project_path/"build", project_path/"main.cpp")==boost::filesystem::path(".")/"test");
    g_assert(cmake.get_executable(project_path/"build", project_path/"non_existing_file.cpp")==boost::filesystem::path(".")/"test");
    g_assert(cmake.get_executable(project_path/"build", project_path)==boost::filesystem::path(".")/"test");
  }
}

ext: cc

max_stars_repo_name: MegaApuTurkUltra/jucipp

max_issues_repo_name: fikarzlf/jucipp

max_forks_repo_name: fikarzlf/jucipp


text:
// This file is part of the dune-xt-common project:
//   https://github.com/dune-community/dune-xt-common
// Copyright 2009-2018 dune-xt-common developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Andreas Buhr    (2014)
//   Felix Schindler (2009, 2012 - 2017)
//   René Fritze     (2009 - 2016, 2018)
//   Sven Kaulmann   (2011 - 2012)
//   Tobias Leibner  (2014, 2018)

#ifndef DUNE_XT_COMMON_MISC_HH
#define DUNE_XT_COMMON_MISC_HH

#include <cstring>
#include <map>
#include <assert.h>
#include <algorithm>
#include <dune/common/version.hh>
#include <dune/common/exceptions.hh>

#include <cstddef>
#include <fstream>
#include <iostream>
#include <ostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <cerrno>
#include <limits>
#include <string.h>
#include <stdexcept>
#include <sys/stat.h>
#include <sys/types.h>

#include <dune/xt/common/disable_warnings.hh>
#include <boost/algorithm/string.hpp>
#include <dune/xt/common/reenable_warnings.hh>
#include <boost/filesystem/fstream.hpp>

#include <dune/xt/common/exceptions.hh>
#include <dune/xt/common/logging.hh>
#include <dune/xt/common/deprecated.hh>

namespace Dune {
namespace XT {
namespace Common {

//! element-index-in-container search
template <class StlSequence>
inline int get_idx(const StlSequence& ct, const typename StlSequence::value_type& val)
{
  const auto result = std::find(ct.begin(), ct.end(), val);
  if (result == ct.end())
    return -1;
  return std::distance(ct.begin(), result);
} // get_idx

/** this allows subscription indices to wrap around
 * \example N=4: WraparoundArray[4] == WraparoundArray[0] && WraparoundArray[-1] == WraparoundArray[3]
 **/
template <class T, size_t N>
struct WraparoundArray : public std::array<T, N>
{
  typedef std::array<T, N> BaseType;
  WraparoundArray()
  {
    for (size_t i = 0; i < N; ++i)
      this->operator[](i) = T();
  }

  WraparoundArray(const BaseType other)
  {
    for (size_t i = 0; i < N; ++i)
      this->operator[](i) = other[i];
  }

  typename BaseType::reference operator[](std::size_t i)
  {
    return BaseType::operator[](i % N);
  }

  typename BaseType::reference operator[](int i)
  {
    const std::size_t real_index = i < 0 ? static_cast<std::size_t>(N - (((i * -1) % N) + 1)) : std::size_t(i);
    return BaseType::operator[](real_index);
  } // []

  typename BaseType::const_reference operator[](std::size_t i) const
  {
    return BaseType::operator[](i % N);
  }

  typename BaseType::const_reference operator[](int i) const
  {
    const std::size_t real_index = i < 0 ? static_cast<std::size_t>(N - (((i * -1) % N) + 1)) : std::size_t(i);
    return BaseType::operator[](real_index);
  } // []
};

//! type safe (this will not compile for degraded-to-pointer arrays) way of getting array length
template <class T, size_t N>
size_t array_length(T (&/*array*/)[N])
{
  return N;
}

//! get a non-zero initialised std::array
template <class T, size_t N>
std::array<T, N> make_array(const T& v)
{
  std::array<T, N> ret;
  ret.fill(v);
  return ret;
}

template <class T, size_t N>
std::array<T, N> make_array(const std::vector<T>& v)
{
  if (v.size() == 1) {
    return make_array<T, N>(v[0]);
  } else if (v.size() < N) {
    std::array<T, N> error_msg;
    DUNE_THROW(Exceptions::shapes_do_not_match,
               "Trying to create a " << get_typename(error_msg) << " from a " << get_typename(v) << " of size "
                                     << v.size());
  } else {
    std::array<T, N> ret;
    for (size_t nn = 0; nn < N; ++nn) {
      ret[nn] = v[nn];
    }
    return ret;
  }
}

//! writes process environment to file
void dump_environment(boost::filesystem::ofstream& file, std::string csv_sep = ",");

/** abstraction for stdlibs w/o map.emplace
 * This isn't covering the full emplace spec, and the piecewise case potentially improper,
 * but we only need this in an Intel MIC setup with weird lib versioning.
 * Normally we'd depend on the full gcc 4.8 stack atm and do not use the insert fallback
 **/
template <typename Key, typename T, typename MapType>
std::pair<typename MapType::iterator, bool> map_emplace(MapType& map_in, Key key, T value)
{
#if HAVE_MAP_EMPLACE
  return map_in.emplace(key, value);
#else
  DXTC_LOG_DEBUG_0 << "using map.insert fallback instead of emplace\n";
  return map_in.insert(typename MapType::value_type(key, value));
#endif
}

template <typename K, typename V, typename MapType>
DXT_DEPRECATED_MSG("no longer needed with c++14 (2018/03/20)")
std::pair<typename MapType::iterator, bool> map_emplace(MapType& map_in,
                                                        std::piecewise_construct_t pcw,
                                                        K&& keys,
                                                        V&& values)
{
  return map_in.emplace(pcw, keys, values);
}

template <typename T>
struct remove_const_reference
{
  typedef typename std::remove_reference<typename std::remove_const<T>::type>::type type;
};

} // namespace Common
} // namespace XT
} // namespace Dune

#endif // DUNE_XT_COMMON_MISC_HH

ext: hh

max_stars_repo_name: ftschindler-work/dune-xt-common

max_issues_repo_name: ftschindler-work/dune-xt-common

max_forks_repo_name: ftschindler-work/dune-xt-common


text:
#include <boost/test/unit_test.hpp>

#include <network_session.hpp>
#include <platform.hpp>

BOOST_AUTO_TEST_CASE( network_session )
{
	// XXX al - Load from file ...
	const std::string EXPECTED("{\"bpi\":{\"2018-01-01\":13412.44,\"2018-01-02\":14740.7563},\"disclaimer\":\"This data was produced from the CoinDesk Bitcoin Price Index. BPI value data returned as USD.\",\"time\":{\"updated\":\"Jan 3, 2018 00:03:00 UTC\",\"updatedISO\":\"2018-01-03T00:03:00+00:00\"}}");

	boost::asio::io_service io_service;

	auto ctx = bpi::platform::ssl::get_default_context();

	auto session = std::make_shared<bpi::network::session>(io_service, ctx,
		[&](auto ec, auto message)
		{
			if (ec)
			{
				std::cout << "ERROR: " << ec.message() << std::endl;
				return;
			}

			BOOST_CHECK(!ec);
			BOOST_CHECK(message == EXPECTED);
		});

	session->run("api.coindesk.com", "https",
	    "/v1/bpi/historical/close.json?start=2018-01-01&end=2018-01-02");

	io_service.run();
}

max_stars_repo_name: aerilon/bpistats

max_issues_repo_name: aerilon/bpistats

max_forks_repo_name: aerilon/bpistats


text:
/*
 * j2735dump.cpp
 *
 *  Created on: Dec 15, 2016
 *      @author: gmb
 */

#include <boost/property_tree/ptree.hpp>
#include <boost/version.hpp>
#include <cstdio>
#include <tmx/j2735_messages/J2735MessageFactory.hpp>
#include <tmx/messages/message_converter.hpp>
#include <PluginExec.h>
#include <BsmConverter.h>

#ifndef DEFAULT_TREEREPAIR
#define DEFAULT_TREEREPAIR treerepair.xml
#endif

using namespace std;
using namespace tmx;
using namespace tmx::messages;
using namespace tmx::utils;

namespace j2735dump
{

#if BOOST_VERSION < 105800
typedef typename std::string::value_type xml_settings_type;
#else
typedef std::string xml_settings_type;
#endif

class J2735Dump: public Runnable
{
public:
	J2735Dump(): Runnable(), msg("-")
	{
		AddOptions()
			("repair-file,r", boost::program_options::value<string>()->default_value(quoted_attribute_name(DEFAULT_TREEREPAIR)), "XML to JSON repair file.")
			("no-pretty-print", "Do not pretty print the output.  Default is false")
			("no-blobs", "Do not crack the BSM blobs.  Default is false")
			("xml,x", "Write output as XML.  Default is to convert to JSON");
	}

	inline int Main()
	{
		if (msg == "-")
		{
			char buf[4000];
			cin.getline(buf, sizeof(buf));
			msg = string(buf);
		}

		PLOG(logDEBUG) << "Decoding message: " << msg;

		// Figure out if this is a JSON message or just the bytes
		bool jsonMsg = false;

		int i;
		for (i = 0; i < (int)msg.size() && (msg[i] == '\t' || msg[i] == ' '); i++); // Skip white space
		if (msg[i] == '{') jsonMsg = true;

		byte_stream bytes;
		if (jsonMsg)
		{
			routeable_message routeableMsg;
			routeableMsg.set_contents(msg);

			PLOG(logDEBUG) << "Decoding routeable message: " << routeableMsg;

			bytes = routeableMsg.get_payload_bytes();
		}
		else
		{
			bytes = battelle::attributes::attribute_lexical_cast<byte_stream>(msg);
		}

		PLOG(logDEBUG) << "Decoding bytes: " << bytes;

		J2735MessageFactory factory;
		TmxJ2735EncodedMessageBase *tmxMsg = factory.NewMessage(bytes);
		if (!tmxMsg)
		{
			BOOST_THROW_EXCEPTION(factory.get_event());
			exit(-1);
		}

		// Get a copy of the property tree to use and manipulate
		PLOG(logDEBUG) << "Trying to copy message " << *tmxMsg;
		PLOG(logDEBUG) << "Payload: " << tmxMsg->get_payload();

		xml_message msg(tmxMsg->get_payload().get_container());

		// Obtain a copy of the ptree for manipulation
		message_tree_type tree = msg.get_container().get_storage().get_tree();
		PLOG(logDEBUG) << "Copy: " << msg;

		delete tmxMsg;

		// If this is a BSM, then replace the contents of the blob with the decoded information
		if (blobs && tree.count("BasicSafetyMessage"))
		{
			static DecodedBsmMessage crackedBsm;

			// Decode the BSM
			BsmMessage bsmMessage;
			bsmMessage.set_contents(tree);

			PLOG(logDEBUG) << "Cracking BSM " << bsmMessage;
			BsmConverter::ToDecodedBsmMessage(*(bsmMessage.get_j2735_data()), crackedBsm);

			// Reset the blob1 data in the message with the decoded information
			string old_val = tree.get<string>("BasicSafetyMessage.blob1", "?");
			tree.put_child("BasicSafetyMessage.blob1", crackedBsm.get_container().get_storage().get_tree());
			tree.put("BasicSafetyMessage.blob1.Bytes", old_val);
			msg.set_contents(tree);
		}

		if (xml)
		{
			boost::property_tree::xml_writer_settings<xml_settings_type> xmlSettings;
			if (pretty)
				xmlSettings = boost::property_tree::xml_writer_make_settings<xml_settings_type>('\t', 1);
			boost::property_tree::write_xml(cout, msg.get_container().get_storage().get_tree(), xmlSettings);
		}
		else
		{
			tmx::XML ser;
			message_converter *conv;

			try
			{
				PLOG(logDEBUG) << "Trying to open converter file " << converter;
				conv = new message_converter(ser, converter);
			}
			catch (exception &ex)
			{
				PLOG(logDEBUG2) << ex.what();
				conv = 0;
			}

			json_message json(msg, conv);
			boost::property_tree::write_json(cout, json.get_container().get_storage().get_tree(), pretty);
		}

		return (0);
	}

	inline bool ProcessOptions(const boost::program_options::variables_map &opts)
	{
		Runnable::ProcessOptions(opts);

		if (opts.count(INPUT_FILES_PARAM))
		{
			vector<string> files = opts[INPUT_FILES_PARAM].as< vector<string> >();
			if (files.size())
				msg = files[0];
		}

		xml = opts.count("xml");
		pretty = !(opts.count("no-pretty-print"));
		blobs = !(opts.count("no-blobs"));
		converter = opts["repair-file"].as<string>();

		return true;
	}

private:
	string msg;
	string converter;
	bool xml = false;
	bool pretty = true;
	bool blobs = true;
};

} /* End namespace */

int main(int argc, char *argv[])
{
	FILELog::ReportingLevel() = logERROR;

	try
	{
		j2735dump::J2735Dump myExec;
		run("", argc, argv, myExec);
	}
	catch (exception &ex)
	{
		cerr << ExceptionToString(ex) << endl;
		throw;
	}
}


text:
/**
 * \file    signal_handling.cpp
 * \author  Justin Too <too1@llnl.gov>
 * \date    November 16, 2013
 */
#include "sage3basic.h"

#include <iostream>

#include "keep_going.h"
#include "processSupport.h" // ROSE_ASSERT in ROSE/src/util

#include <map>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#ifdef __linux__
#include <utime.h>
#endif
#include <boost/algorithm/string/join.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>

using namespace std;
using namespace boost::interprocess;

namespace Rose {
namespace KeepGoing {
  bool g_keep_going = false;

 bool verbose = false;
 bool enable_ast_tests= false;

 std::string report_filename__fail;
 std::string report_filename__pass;
 std::string expectations_filename__fail;
 std::string expectations_filename__pass;
 std::string path_prefix;

 std::map <SgFile* , std::string> File2StringMap;

#ifndef _MSC_VER
struct sigaction SignalAction;
#endif //_MSC_VER

bool set_signal_handler(SignalHandlerFunction handler)
{
#ifndef _MSC_VER
    SignalAction.sa_flags   = 0;
    SignalAction.sa_handler = handler;

    sigemptyset(&SignalAction.sa_mask);

    sigaction(SIGSEGV, &SignalAction, 0);
    sigaction(SIGABRT, &SignalAction, 0);
#else
    ROSE_ASSERT(! "[FATAL] KeepGoing feature not supported yet on Windows");
#endif //_MSC_VER

    return true;
}

namespace Frontend {
  #ifndef _MSC_VER
    sigjmp_buf jmp_target;
  #endif //_MSC_VER
  void SignalHandler(int sig)
  {
      std::cout
          << "[WARN] "
          << "Caught signal="
#ifndef _MSC_VER
          << "'" << strsignal(sig) << "' "
#else
          << "'" << sig << "' "
#endif
          << "during frontend processing"
          << std::endl;

      #ifndef _MSC_VER
          siglongjmp(Frontend::jmp_target, -1);
      #else
          ROSE_ASSERT(! "[FATAL] KeepGoing feature not supported yet on Windows");
      #endif //_MSC_VER
  }

  namespace Commandline {
    #ifndef _MSC_VER
      sigjmp_buf jmp_target;
    #endif //_MSC_VER
    void SignalHandler(int sig)
    {
        std::cout
            << "[WARN] "
            << "Caught signal="
#ifndef _MSC_VER
          << "'" << strsignal(sig) << "' "
#else
          << "'" << sig << "' "
#endif
            << "during commandline processing in frontend processing"
            << std::endl;

        #ifndef _MSC_VER
            siglongjmp(Frontend::Commandline::jmp_target, -1);
        #else
            ROSE_ASSERT(! "[FATAL] KeepGoing feature not supported yet on Windows");
        #endif //_MSC_VER
    }
  }// ::Rose::KeepGoing::Frontend::Commandline

  namespace SecondaryPass {
    #ifndef _MSC_VER
      sigjmp_buf jmp_target;
    #endif //_MSC_VER
    void SignalHandler(int sig)
    {
        std::cout
            << "[WARN] "
            << "Caught signal="
#ifndef _MSC_VER
          << "'" << strsignal(sig) << "' "
#else
          << "'" << sig << "' "
#endif
            << "during secondary pass in frontend processing"
            << std::endl;

        #ifndef _MSC_VER
            siglongjmp(Frontend::SecondaryPass::jmp_target, -1);
        #else
            ROSE_ASSERT(! "[FATAL] KeepGoing feature not supported yet on Windows");
        #endif //_MSC_VER
    }
  }// ::Rose::KeepGoing::Frontend::SecondaryPass
}// ::Rose::KeepGoing::Frontend

namespace Midend {
  #ifndef _MSC_VER
    sigjmp_buf jmp_target;
  #endif //_MSC_VER
  void SignalHandler(int sig)
  {
      std::cout
          << "[WARN] "
          << "Caught signal="
#ifndef _MSC_VER
          << "'" << strsignal(sig) << "' "
#else
          << "'" << sig << "' "
#endif
          << "during midend processing"
          << std::endl;

      #ifndef _MSC_VER
          siglongjmp(Midend::jmp_target, -1);
      #else
          ROSE_ASSERT(! "[FATAL] KeepGoing feature not supported yet on Windows");
      #endif //_MSC_VER
  }
}// ::Rose::KeepGoing::Midend

namespace Backend
{
  namespace Unparser {
    #ifndef _MSC_VER
      sigjmp_buf jmp_target;
    #endif //_MSC_VER
    void SignalHandler(int sig)
    {
        std::cout
            << "[WARN] "
            << "Caught signal="
#ifndef _MSC_VER
          << "'" << strsignal(sig) << "' "
#else
          << "'" << sig << "' "
#endif
            << "during backend unparser processing"
            << std::endl;

        #ifndef _MSC_VER
            siglongjmp(Backend::Unparser::jmp_target, -1);
        #else
            ROSE_ASSERT(! "[FATAL] KeepGoing feature not supported yet on Windows");
        #endif //_MSC_VER
    }
  }// ::Rose::KeepGoing::Backend::Unparser

  namespace Compiler {
    #ifndef _MSC_VER
      sigjmp_buf jmp_target;
    #endif //_MSC_VER
    void SignalHandler(int sig)
    {
        std::cout
            << "[WARN] "
            << "Caught signal="
#ifndef _MSC_VER
          << "'" << strsignal(sig) << "' "
#else
          << "'" << sig << "' "
#endif
            << "during backend compiler processing"
            << std::endl;

        #ifndef _MSC_VER
            siglongjmp(Backend::Compiler::jmp_target, -1);
        #else
            ROSE_ASSERT(! "[FATAL] KeepGoing feature not supported yet on Windows");
        #endif //_MSC_VER
    }
  }// ::Rose::KeepGoing::Backend::Compiler
}// ::Rose::KeepGoing::Backend
}// ::Rose::KeepGoing
}// Rose

// TOO1 (05/14/2013): Handling for -rose:keep_going
//
// Compile the original source code file if:
//
// 1. Unparsing was skipped
// 2. The frontend encountered any errors, and the user specified to
//    "keep going" with -rose:keep_going.
//
//    Warning: Apparently, a frontend error code <= 3 indicates an EDG
//    frontend warning; however, existing logic says nothing about the
//    other language frontends' exit statuses.
bool
Rose::KeepGoing::Backend::UseOriginalInputFile(SgFile* file)
{
  ROSE_ASSERT(file != NULL);

#if 0
  // DQ (11/10/2016): Debugging information (detected that p_keep_going data member was uninitialized).
     printf ("file->get_unparse_output_filename().empty() = %s \n",file->get_unparse_output_filename().empty() ? "true" : "false");
     printf ("file->get_frontendErrorCode() != 0          = %s \n",(file->get_frontendErrorCode() != 0) ? "true" : "false");
     printf ("file->get_project()->get_midendErrorCode()  = %s \n",(file->get_project()->get_midendErrorCode()) ? "true" : "false");
     printf ("file->get_unparserErrorCode()               = %s \n",(file->get_unparserErrorCode()) ? "true" : "false");
     printf ("file->get_backendCompilerErrorCode() != 0   = %s \n",(file->get_backendCompilerErrorCode() != 0) ? "true" : "false");
     printf ("file->get_project()->get_keep_going()       = %s \n",file->get_project()->get_keep_going() ? "true" : "false");
#endif

  return
    // (1) An ROSE unparsed file was not generated
    file->get_unparse_output_filename().empty() == true ||
    // (2) File has an error and user specified to "keep going"
    (
        (
            file->get_frontendErrorCode() != 0 ||
            file->get_project()->get_midendErrorCode() != 0 ||
            file->get_unparserErrorCode() != 0 ||
            file->get_backendCompilerErrorCode() != 0) &&
        (
            file->get_project()->get_keep_going()
        )
    );
}// ::Rose::KeepGoing::Backend::UseOriginalInputFile

// Move many helper functions here to simplify writing a translator with keep-going logging support, Liao 4/12/2017

//! Processing command line options
void Rose::KeepGoing::commandLineProcessing
                          (int argc, char* argv[],
                           std::vector<std::string> & rose_cmdline
                           )
{
  std::string program_name(argv[0]);
  rose_cmdline.push_back(program_name);
  // wrap the -rose:keep_going option inside of this translator
  rose_cmdline.push_back("-rose:keep_going");

  {// CLI
    std::string cli_list_filenames        = "--list-filenames"; // deprecated 2013-11-2
    std::string cli_report                = "--report="; // deprecated 2013-11-2
    std::string cli_report__fail          = "--report-fail=";
    std::string cli_report__pass          = "--report-pass=";
    std::string cli_expectations__fail    = "--expected-failures=";
    std::string cli_expectations__pass    = "--expected-passes=";
    std::string cli_strip_path_prefix     = "--strip-path-prefix=";
    std::string cli_enable_ast_tests      = "--enable-ast-tests";
    std::string cli_verbose               = "--verbose";
    std::string cli_silent                = "--silent";

    for (int ii = 1; ii < argc; ++ii)
    {
      std::string arg = argv[ii];

      // --help
      if ((arg == "-h") || (arg == "--help"))
      {
        ShowUsage(program_name);
        exit(0);
      }
      // --verbose
      else if (arg.find(cli_verbose) == 0)
      {
        verbose = true;
      }
      // --silent
      else if (arg.find(cli_silent) == 0)
      {
        verbose = false;
      }
      // --list-filenames
      else if (arg.find(cli_list_filenames) == 0)
      {
        arg.replace(0, cli_list_filenames.length(), "");
        {
          std::vector<std::string> filenames =
            GetSourceFilenamesFromCommandline(
                std::vector<std::string>(argv, argv + argc));
          BOOST_FOREACH(std::string filename, filenames)
          {
            std::cout << filename << std::endl;
          }
        }
        exit(0);
      }
      // --report=<filename>
      else if (arg.find(cli_report) == 0)
      {
        arg.replace(0, cli_report.length(), "");
        if (arg.empty())
        {
          std::cerr
            << "[ERROR] "
            << "[" << program_name << "] "
            << "--report requires an argument, see --help"
            << std::endl;
          exit(1);
        }
        else
        {
          report_filename__fail = arg + "-fail";
          report_filename__pass = arg + "-pass";
        }
      }
      // --report-fail=<filename>
      else if (arg.find(cli_report__fail) == 0)
      {
        arg.replace(0, cli_report__fail.length(), "");
        if (arg.empty())
        {
          std::cerr
            << "[ERROR] "
            << "[" << program_name << "] "
            << "--report-fail requires an argument, see --help"
            << std::endl;
          exit(1);
        }
        else
        {
          report_filename__fail = arg;
        }
      }
      // --report-pass=<filename>
      else if (arg.find(cli_report__pass) == 0)
      {
        arg.replace(0, cli_report__pass.length(), "");
        if (arg.empty())
        {
          std::cerr
            << "[ERROR] "
            << "[" << program_name << "] "
            << "--report-pass requires an argument, see --help"
            << std::endl;
          exit(1);
        }
        else
        {
          report_filename__pass = arg;
        }
      }
      // --expected-failures
      else if (arg.find(cli_expectations__fail) == 0)
      {
        arg.replace(0, cli_expectations__fail.length(), "");
        if (arg.empty())
        {
          std::cerr
            << "[ERROR] "
            << "[" << program_name << "] "
            << "--expected-failures requires an argument, see --help"
            << std::endl;
          exit(1);
        }
        else
        {
          expectations_filename__fail = arg;
          if (!boost::filesystem::exists(expectations_filename__fail))
          {
            std::cerr
              << "[FATAL] "
              << "Expected failures file does not exist: "
              << expectations_filename__fail
              << std::endl;
            exit(1);
          }
        }
      }
      // --expected-passes
      else if (arg.find(cli_expectations__pass) == 0)
      {
        arg.replace(0, cli_expectations__pass.length(), "");
        if (arg.empty())
        {
          std::cerr
            << "[ERROR] "
            << "[" << program_name << "] "
            << "--expected-passes requires an argument, see --help"
            << std::endl;
          exit(1);
        }
        else
        {
          expectations_filename__pass = arg;
          if (!boost::filesystem::exists(expectations_filename__pass))
          {
            std::cerr
              << "[FATAL] "
              << "expected passes file does not exist: "
              << expectations_filename__pass
              << std::endl;
            exit(1);
          }
        }
      }
      // --strip-path-prefix
      else if (arg.find(cli_strip_path_prefix) == 0)
      {
        arg.replace(0, cli_strip_path_prefix.length(), "");
        if (arg.empty())
        {
          std::cerr
            << "[ERROR] "
            << "[" << program_name << "] "
            << "--strip-path-prefix requires an argument, see --help"
            << std::endl;
          exit(1);
        }
        else
        {
          path_prefix = arg;
        }
      }
      // --enable-ast-tests
      else if (arg.find(cli_enable_ast_tests) == 0)
      {
        enable_ast_tests = true;
      }
      else
      {
        rose_cmdline.push_back(arg);
      }
    }

    if (verbose)
    {
      std::cout
        << "[INFO] ROSE Commandline: "
        << boost::algorithm::join(rose_cmdline, " ")
        << std::endl;
    }
  }// CLI

}

void Rose::KeepGoing::setMidendErrorCode (SgProject* project, int errorCode)
{
  project->set_midendErrorCode(errorCode);

  SgFilePtrList files = project->get_files();
  BOOST_FOREACH(SgFile* file, files)
  {
    file->set_midendErrorCode(errorCode);
  }
}

void Rose::KeepGoing::generate_reports(SgProject* project,
                     std::vector< std::string> orig_rose_cmdline
                       )
{
  // --------------------------------------------------------------
  SgFilePtrList files_with_errors = project->get_files_with_errors();

  // Convert command line options into a single line string
  std::string orig_command_str;
  for (size_t len= 0; len<orig_rose_cmdline.size(); len++)
  {
    if (len!=0)
      orig_command_str +=" ";
    orig_command_str += orig_rose_cmdline[len];
  }
  orig_command_str +="\n";

  // add original command line into the log file so users can easily reproduce the errors.
  if (files_with_errors.size()>0 && report_filename__fail.size()>0)
  {
    AppendToFile (report_filename__fail, "------------------------\n");
    // add time stamp in the beginning
    std::ostringstream ostamp;
    ostamp << GetTimestamp()  << " " << getpid() << std::endl;
    AppendToFile (report_filename__fail, ostamp.str());

    AppendToFile (report_filename__fail, orig_command_str);

    BOOST_FOREACH(SgFile* file, files_with_errors)
    {
      std::string filename = file->getFileName();
      filename = StripPrefix(path_prefix, filename);

      std::stringstream ss;
      ss <<"Processed File: With Errors " <<  filename << endl; // Help diagnosis , output full file name, even command lines may have partial file paths
      if (verbose)
      {
        std::cout
          << "[ERROR] "
          << "ROSE encountered an error while processing this file: "
          << "'" << path_prefix << filename << "'"
          << std::endl;
      }

      // <file> <frontend> <unparser> <backend>
      // Keep all info. of one file into one line. Users can easily count the total failures.
      if (file->get_frontendErrorCode())
        ss << "\t Frontend Error Code:" << file->get_frontendErrorCode() ;
      if (file->get_midendErrorCode())
        ss << "\t Midend Error Code:" << file->get_midendErrorCode() ;
      if (file->get_javacErrorCode())
        ss << "\t JAVA Error Code:"<< file->get_javacErrorCode();
      if (file->get_unparserErrorCode())
        ss << "\t Unparser Error Code:"<< file->get_unparserErrorCode();
      if (file->get_backendCompilerErrorCode())
        ss << "\t Backend Compiler Error Code: " << file->get_backendCompilerErrorCode();
      if (file->get_unparsedFileFailedCompilation())
        ss << "\t Unparsed File Failed Compilation Code: "<< file->get_unparsedFileFailedCompilation();
      ss<<"\n";
      AppendToFile(report_filename__fail, ss.str());

      //Sometimes even for files failed on backend stage, some analysis results are generated.
      //we still want to output such results.
      // If exists, output the analysis results associated with each file
      std::ostringstream oss;
      oss <<  File2StringMap[file]; // not copyable, not assignable
      if (oss.str().size()>0)
      {
        AppendToFile(report_filename__fail, oss.str());
      }
    }
  }
  // Report successes
  SgFilePtrList files_without_errors = project->get_files_without_errors();
  if (files_without_errors.size()>0 && report_filename__pass.size()>0)
  {
   // full command line , it may has multiple files

    AppendToFile (report_filename__pass, "------------------------\n");
    //AppendToFile (report_filename__pass, orig_command_str);

    // add time stamp in the beginning
    std::ostringstream ostamp ;
    ostamp << GetTimestamp()  << " " << getpid() << std::endl;
    AppendToFile (report_filename__pass, ostamp.str());

    BOOST_FOREACH(SgFile* file, files_without_errors)
    {
      std::string full_filename = file->getFileName();
      std::string filename = StripPrefix(path_prefix, full_filename);

      // output file full path first
      AppendToFile(report_filename__pass, "Processed File: Without Errors:"+full_filename+"\n");
      if (verbose)
      {
        std::cout
          << "[INFO] "
          << "ROSE successfully compiled this file: "
          << "'" << path_prefix << filename << "'"
          << std::endl;
      }

      // If exists, output the analysis results associated with each file
      std::ostringstream oss;
      oss <<  File2StringMap[file]; // not copyable, not assignable
      if (oss.str().size()>0)
      {

        AppendToFile(report_filename__pass, oss.str());
      }
    }
  }

  //Sometimes even for files failed on backend stage, some analysis results are generated.
  //we still want to output such results.
  // If exists, output the analysis results associated with each file
  if (files_with_errors.size()>0 && report_filename__pass.size()>0)
  {
    bool runonce = false;
    // add time stamp in the beginning
    std::ostringstream ostamp;
    ostamp << GetTimestamp()  << " " << getpid() << std::endl;

    BOOST_FOREACH(SgFile* file, files_with_errors)
    {
      std::string filename = file->getFileName();

      //Sometimes even for files failed on backend stage, some analysis results are generated.
      //we still want to output such results.
      // If exists, output the analysis results associated with each file
      std::ostringstream oss;
      oss <<  File2StringMap[file]; // not copyable, not assignable
      if (oss.str().size()>0)
      {
        if (!runonce)
        {
          AppendToFile (report_filename__pass, "------Analysis results for files with backend errors----------------------\n");
          AppendToFile (report_filename__pass, ostamp.str());
          runonce = true;
        }

        AppendToFile(report_filename__pass, "Processed File: With Backend Errors:"+filename+"\n");
        AppendToFile(report_filename__pass, oss.str());
      }
    }
  }

  if (!expectations_filename__fail.empty())
  {
      std::map<std::string, std::string> expected_failures =
          CreateExpectationsMap(expectations_filename__fail);

      // TOO1 (3/5/2014): Only works if all files are processed by this single commandline.
      //if(files_with_errors.size() != expected_failures.size())
      //{
      //    std::cerr
      //        << "[FATAL] "
      //        << "Expected '" << expected_failures.size() << "' failures, but "
      //        << "encountered '" << files_with_errors.size() << "' failures"
      //        << std::endl;
      //    exit(1);
      //}

      BOOST_FOREACH(SgFile* file, files_with_errors)
      {
          std::string filename = file->getFileName();
          filename = StripPrefix(path_prefix, filename);

          std::map<std::string, std::string>::iterator it =
              expected_failures.find(filename);
          if (it == expected_failures.end())
          {
              std::cerr
                  << "[FATAL] "
                  << "File failed unexpectedly: "
                  << "'" << path_prefix << filename << "'"
                  << std::endl;
              exit(1);
          }
          else
          {
              if (verbose)
              {
                  std::cout
                      << "[INFO] "
                      << "File failed as expected: "
                      << "'" << path_prefix << filename << "'"
                      << std::endl;
              }
          }
      }
  }

  if (!expectations_filename__pass.empty())
  {
      std::map<std::string, std::string> expected_passes =
          CreateExpectationsMap(expectations_filename__pass);

      // TOO1 (3/5/2014): Only works if all files are processed by this single commandline.
      //
      //if(files_without_errors.size() != expected_passes.size())
      //{
      //    std::cerr
      //        << "[FATAL] "
      //        << "Expected '" << expected_passes.size() << "' passes, but "
      //        << "encountered '" << files_without_errors.size() << "' passes"
      //        << std::endl;
      //    exit(1);
      //}

      BOOST_FOREACH(SgFile* file, files_without_errors)
      {
          std::string filename = file->getFileName();
          filename = StripPrefix(path_prefix, filename);

          std::map<std::string, std::string>::iterator it =
              expected_passes.find(filename);
          if (it == expected_passes.end())
          {
              std::cerr
                  << "[WARN] "
                  << "File passed unexpectedly: "
                  << "'" << path_prefix << filename << "'"
                  << std::endl;
          }
          else
          {
              if (verbose)
              {
                  std::cout
                      << "[INFO] "
                      << "File passed as expected: "
                      << "'" << path_prefix << filename << "'"
                      << std::endl;
              }
          }
      }
  }
}

void
Rose::KeepGoing::ShowUsage(std::string program_name)
{
  std::cerr
    << "Usage: " << program_name << " [--help] [ROSE Commandline]\n"
    << "Options:\n"
    << "  --list-filenames                Prints the filename(s), computed by the ROSE commandline handling,\n"
    << "                                  onto standard out. Each filename is separated by a new line.\n"
    << "\n"
    << "  --report-pass=<filename>        File to write report of passes\n"
    << "  --report-fail=<filename>        File to write report of failurest\n"
    << "  --expected-failures=<filename>  File containing filenames that are expected to fail\n"
    << "  --expected-passes=<filename>    File containing filenames that are expected to pass\n"
    << "  --strip-path-prefix=<filename>  Normalize filenames by stripping this path prefix from them\n"
    << "\n"
    << "  --enable-ast-tests              Enables the internal ROSE AST consistency tests\n"
    << "\n"
    << "  -h,--help                       Show this help message\n"
    << "  --verbose                       Enables debugging output, e.g. outputs successful files\n"
    << "  --silent                        Disables debugging output\n"
    << std::endl;
}

std::string
Rose::KeepGoing::StripPrefix(const std::string& prefix, const std::string& str)
{
  std::string stripped_str(str);

  size_t index = str.find(prefix, 0);
  if (index != std::string::npos)
  {
      stripped_str.replace(0, prefix.length(), "");
  }

  return stripped_str;
}

std::string
Rose::KeepGoing::GetTimestamp(const std::string& format)
{
  using namespace boost::posix_time;

  //ptime now = second_clock::universal_time();
  // Using local time instead to be user-friendly.
  ptime now = second_clock::local_time();

  static std::locale loc(std::cout.getloc(),
                         new time_facet(format.c_str()));

  std::basic_stringstream<char> ss;
  ss.imbue(loc);
  ss << now;

  return ss.str();
}

void Rose::KeepGoing::touch(const std::string& pathname)
{

#ifdef __linux__  // commented out to pass windows test for now
    int fd = open(pathname.c_str(),
                  O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK,
                  0666);
    if (fd<0) // Couldn't open that path.
    {
        std::cerr
            << __PRETTY_FUNCTION__
            << ": Couldn't open() path \""
            << pathname
            << "\"\n";
        return;
    }

    int rc = utime(pathname.c_str(), 0);

    if (rc)
    {
        std::cerr
            << __PRETTY_FUNCTION__
            << ": Couldn't utime() path \""
            << pathname
            << "\"\n";
        return;
    }
   if (verbose)
   {
    std::clog
        << __PRETTY_FUNCTION__
        << ": Completed touch() on path \""
        << pathname
        << "\"\n";
   }
#endif
}

//! AppendToFile a message
void
Rose::KeepGoing::AppendToFile(const std::string& filename, const std::string& msg)
{
  // if filename is NULL, no action is needed.
  if (filename.size()==0)
    return;
 // use a separated file for the file lock
  string lock_file_name = filename+".lock";
  touch(filename);
  touch(lock_file_name); //this lock file must exist. Or later flock() will fail.

  boost::interprocess::file_lock flock (lock_file_name.c_str());
  // introduce a scope to use the scoped lock, which automatically unlock when existing the scope
  {
    scoped_lock<file_lock> e_lock(flock);
    std::ofstream fout(filename.c_str(), std::ios::app);
    if(!fout.is_open())
    {
      std::cerr
        << "[FATAL] "
        << "Couldn't open "
        << "'" << filename << "'"
        << std::endl;
    }
    else
    {
#if 0
      fout
        << GetTimestamp()  << " "
        << getpid() << " "
        << msg
        << std::endl;
#endif
      fout<<msg;
      fout.flush();
      fout.close();
    }
  } // end scope for the scoped lock
  boost::filesystem::remove (lock_file_name);
}

std::map<std::string, std::string>
Rose::KeepGoing::CreateExpectationsMap(const std::string& filename)
{
  std::map<std::string, std::string> expectations;

  std::ifstream fin(filename.c_str());
  if(!fin.is_open())
  {
      std::cerr
          << "[FATAL] "
          << "Couldn't open "
          << "'" << filename << "'"
          << std::endl;
      exit(1);
  }
  else
  {
      std::string line;
      while (fin.good())
      {
          getline (fin, line);
          if (line.size() > 1)
          {
              expectations[line] = line;
          }
      }
  }

  fin.close();

  return expectations;
}

/**
 * @returns A vector of all filenames from the commandline.
 */
std::vector<std::string>
Rose::KeepGoing::GetSourceFilenamesFromCommandline(const std::vector<std::string>& argv)
{
  std::vector<std::string> filenames =
      CommandlineProcessing::generateSourceFilenames(argv, false);
  return filenames;
}

max_stars_repo_name: mschordan/rose-develop

max_issues_repo_name: mschordan/rose-develop

max_forks_repo_name: mschordan/rose-develop


text:
// This file is part of the dune-xt-common project:
//   https://github.com/dune-community/dune-xt-common
// Copyright 2009-2018 dune-xt-common developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2012, 2014, 2016 - 2017)
//   René Fritze     (2012 - 2018)
//   Tobias Leibner  (2014, 2016)

#include <dune/xt/common/test/main.hxx>

#include <dune/xt/common/validation.hh>
#include <dune/xt/common/type_traits.hh>
#include <dune/xt/common/math.hh>
#include <dune/xt/common/random.hh>
#include <dune/common/tupleutility.hh>
#include <dune/common/exceptions.hh>
#include <dune/common/bigunsignedint.hh>
#include <limits>
#include <iostream>

#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/array.hpp>

using namespace Dune::XT::Common;
using namespace Dune::XT::Test;

constexpr const auto SEED = std::random_device::result_type(0);

struct ValidationTest : public testing::Test
{
  typedef FIELD_TYPE T;
  typedef DefaultRNG<T> RNGType;
  static const T eps;
  typedef VectorAbstraction<T>::S S;
  typedef std::numeric_limits<S> limit;
  const int eps_fac = 4;
  const S scalar_eps = Epsilon<S>::value;

  void all()
  {
    using namespace boost::assign;
    {
      const S lower = S(0);
      const S center = S(3);
      const S upper = S(6);

      test(lower, upper, lower + 1);
      test(lower, upper, center);
      test(lower, upper, upper - 1);

      const auto vl = init_bound<T>(lower);
      const auto vu = init_bound<T>(upper);
      RNGType rng(vl, vu, SEED);
      boost::array<T, 10> ar = list_of<T>().repeat_fun(9, rng);
      ValidateInList<T, boost::array<T, 10>> validator(ar);
      for (T t : ar) {
        EXPECT_TRUE(validator(t));
      }
      std::vector<T> a;
      EXPECT_FALSE(ValidateInList<T>(a)(rng()));
    }
  }

  void test(const S lower, const S upper, const S arg) const
  {
    const auto arg_T = init_bound<T>(arg);
    const auto lower_T = init_bound<T>(lower);
    const auto upper_T = init_bound<T>(upper);
    EXPECT_TRUE(ValidateAny<T>()(arg_T));
    EXPECT_TRUE(ValidateLess<T>(arg_T)(upper_T));
    EXPECT_TRUE(ValidateLessOrEqual<T>(arg_T)(arg_T));
    EXPECT_TRUE(ValidateLessOrEqual<T>(arg_T)(upper_T));
    EXPECT_TRUE(ValidateGreaterOrEqual<T>(arg_T)(arg_T));
    EXPECT_TRUE(ValidateGreaterOrEqual<T>(arg_T)(lower_T));
    EXPECT_TRUE(ValidateGreater<T>(arg_T)(lower_T));
    EXPECT_TRUE(ValidateInterval<T>(lower_T, upper_T)(arg_T));
    EXPECT_FALSE(ValidateNone<T>()(arg_T));
  }
};
const FIELD_TYPE ValidationTest::eps = Epsilon<T>::value;

TEST_F(ValidationTest, All)
{
  this->all();
}


text:
#pragma once

#include "matrix_traits.hpp"
#include <initializer_list>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

template <typename Type, template <typename> typename Traits = matrix_traits>
class matrix {
public:
  MATRIX_DEFINE();

public:
  matrix(row_t, col_t, elem_t = elem_t{});
  matrix(std::initializer_list<elem_t> const&);

private:
  matrix(row_t, col_t, imp_cref_t);
  matrix(row_t, col_t, imp_cref_t, imp_cref_t);

public:
  auto get(row_t, col_t) -> elem_ref_t;
  auto get(row_t, col_t) const -> elem_cref_t;
  auto get(row_t, col_t, row_t, col_t) const -> matrix_t;

  auto set(row_t, col_t, elem_cref_t) -> void;
  auto set(row_t, col_t, matrix_cref_t) -> void;

  auto add(matrix_cref_t) -> void;
  auto sub(matrix_cref_t) -> void;
  auto mul(elem_t) -> void;
  auto dot(matrix_cref_t) const -> matrix_t;

  auto transpose() const -> matrix_t;
  bool equal(matrix_cref_t) const noexcept;

  /*
  template <type_t... Pack>
  static auto array(type_t, type_t... pack) -> matrix_t;

  static auto array(type_t) -> matrix_t
  */

  auto vstack(matrix_cref_t) const -> matrix_t;
  auto hstack(matrix_cref_t) const -> matrix_t;

  template <typename... Pack>
  static auto vstack(matrix_cref_t, Pack... pack) -> matrix_t;
  static auto vstack(matrix_cref_t, matrix_cref_t);

  template <typename... Pack>
  static auto hstack(matrix_cref_t, Pack... pack) -> matrix_t;
  static auto hstack(matrix_cref_t, matrix_cref_t);

  auto size() const noexcept -> size_t { return m_row * m_col; }
  auto row() const noexcept -> row_t { return m_row; }
  auto col() const noexcept -> col_t { return m_col; }

private:
  auto imp() const noexcept -> imp_t { return m_imp; }

private:
  friend class boost::serialization::access;
  template <typename Archive>
  void serialize(Archive & ar, const unsigned int /* file_version */) {
      ar & m_row & m_col & m_imp;
  }

private:
  row_t m_row;
  col_t m_col;
  imp_t m_imp;
};

template <typename Type, template <typename> typename Traits>
  template <typename... Pack>
auto matrix<Type, Traits>::vstack(matrix_cref_t lhs, Pack... pack) -> matrix_t
{
  auto rhs = vstack(pack...);

  return vstack(lhs, rhs);
}

template <typename Type, template <typename> typename Traits>
  template <typename... Pack>
auto matrix<Type, Traits>::hstack(matrix_cref_t lhs, Pack... pack) -> matrix_t
{
  auto rhs = hstack(pack...);

  return hstack(lhs ,rhs);
}

extern template class matrix<double>;
extern template class matrix<float>;

ext: hpp

max_stars_repo_name: mustafagonul/matrix-cpp

max_issues_repo_name: mustafagonul/matrix-cpp

max_forks_repo_name: mustafagonul/matrix-cpp