text:
#pragma once

#include <cstdint>
#include <string>
#include <vector>

#include <nlohmann/json.hpp>
#include <pre/json/from_json.hpp>
#include <boost/fusion/include/adapt_struct.hpp>

#include <xxhr/xxhr.hpp>

#include <gh/owner.hxx>
#include <gh/auth.hxx>

namespace gh::repos {

  struct label_t {
    uint64_t id;
    std::string url;
    std::string name;
    std::optional<std::string> description;
    std::string color;
    //XXX: impossible is C++ keyword : bool default;
  };
}

BOOST_FUSION_ADAPT_STRUCT(gh::repos::label_t, id, url, name, description, color);

namespace gh::repos {

  struct milestone_t {
    uint64_t id;
    std::string url;
    std::string html_url;
    std::string labels_url;
    uint64_t number;
    std::string state;
    std::string title;
    std::string description;
    owner_t creator;
    uint64_t open_issues;
    uint64_t closed_issues;

    std::optional<std::string> closed_at;
    std::string created_at;
    std::optional<std::string> updated_at;
    std::optional<std::string> due_on;
  };

}

BOOST_FUSION_ADAPT_STRUCT(gh::repos::milestone_t, id, url, html_url, labels_url, number,
 state, title, description, creator, open_issues, closed_issues, closed_at, created_at,
 updated_at, due_on);

namespace gh::repos {

  struct issue_t {
    uint64_t id;
    std::string url;
    std::string repository_url;
    std::string labels_url;
    std::string comments_url;
    std::string events_url;
    std::string html_url;
    uint64_t number;
    std::string state;
    std::string title;
    std::string body;
    owner_t user;

    std::vector<label_t> labels;

    std::optional<owner_t> assignee;
    std::vector<owner_t> assignees;

    std::optional<milestone_t> milestone;

    bool locked;
    std::optional<std::string> active_lock_reason;
    uint64_t comments;

    struct pull_request_t {
      std::string url;
      std::string html_url;
      std::string diff_url;
      std::string patch_url;
    };
    std::optional<pull_request_t> pull_request;

    std::optional<std::string> closed_at;
    std::string created_at;
    std::optional<std::string> updated_at;

  };
}

BOOST_FUSION_ADAPT_STRUCT(gh::repos::issue_t::pull_request_t, url, html_url, diff_url,
 patch_url);

BOOST_FUSION_ADAPT_STRUCT(gh::repos::issue_t, id, url, repository_url, labels_url,
 comments_url, events_url, html_url, number, state, title, body, user, labels,
 assignee, assignees, milestone, locked, active_lock_reason, comments, pull_request,
  closed_at, created_at, updated_at);

namespace gh::repos {

  //! Issues in a repo
  using issues = std::vector<issue_t>;
}

namespace gh {

  using namespace std::string_literals;

  inline void list_issues(std::string owner, std::string repository,
    std::function<void(repos::issues&&)>&& result_handler,
    std::string state = "open",
    std::optional<auth> auth = std::nullopt,
    const std::string& api_endpoint = "https://api.github.com"s ) {

    using namespace xxhr;
    auto url = api_endpoint + "/repos/"s + owner + "/" + repository + "/issues";

    auto response_handler = [&](auto&& resp) {
      if ( (!resp.error) && (resp.status_code == 200) ) {
        result_handler(pre::json::from_json<repos::issues>(resp.text));
      } else {
        throw std::runtime_error( "err : "s + std::string(resp.error) + "status: "s
            + std::to_string(resp.status_code) + " accessing : "s + url );
      }
    };

    if (auth) {
      GET(url,
        Parameters{{"state", state}},
        Authentication{auth->user, auth->pass},
        on_response = response_handler);
    } else {
      GET(url,
        Parameters{{"state", state}},
        on_response = response_handler);
    }

  }

  inline void get_issue(std::string owner, std::string repository, uint64_t issue_number,
    std::function<void(repos::issue_t&&)>&& result_handler,
    std::optional<auth> auth = std::nullopt,
    const std::string& api_endpoint = "https://api.github.com"s ) {

    using namespace xxhr;
    auto url = api_endpoint + "/repos/"s + owner + "/" + repository + "/issues/" + std::to_string(issue_number);

    auto response_handler = [&](auto&& resp) {
      if ( (!resp.error) && (resp.status_code == 200) ) {
        result_handler(pre::json::from_json<repos::issue_t>(resp.text));
      } else {
        throw std::runtime_error( "err : "s + std::string(resp.error) + "status: "s
            + std::to_string(resp.status_code) + " accessing : "s + url );
      }
    };

    if (auth) {
      GET(url,
        Authentication{auth->user, auth->pass},
        on_response = response_handler);
    } else {
      GET(url,
        on_response = response_handler);
    }

  }

}

ext: hxx

max_stars_repo_name: nxxm/gh

max_issues_repo_name: nxxm/gh

max_forks_repo_name: nxxm/gh


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2004-2012. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/container/detail/config_begin.hpp>
#include <algorithm>
#include <memory>
#include <vector>
#include <iostream>
#include <functional>

#include <boost/container/vector.hpp>
#include <boost/move/move.hpp>
#include "check_equal_containers.hpp"
#include "movable_int.hpp"
#include "expand_bwd_test_allocator.hpp"
#include "expand_bwd_test_template.hpp"
#include "dummy_test_allocator.hpp"
#include "propagate_allocator_test.hpp"
#include "vector_test.hpp"

using namespace boost::container;

namespace boost {
namespace container {

//Explicit instantiation to detect compilation errors
template class boost::container::vector<test::movable_and_copyable_int,
   test::simple_allocator<test::movable_and_copyable_int> >;

template class boost::container::vector<test::movable_and_copyable_int,
   test::dummy_test_allocator<test::movable_and_copyable_int> >;

template class boost::container::vector<test::movable_and_copyable_int,
   std::allocator<test::movable_and_copyable_int> >;

}}

int test_expand_bwd()
{
   //Now test all back insertion possibilities

   //First raw ints
   typedef test::expand_bwd_test_allocator<int>
      int_allocator_type;
   typedef vector<int, int_allocator_type>
      int_vector;

   if(!test::test_all_expand_bwd<int_vector>())
      return 1;

   //Now user defined wrapped int
   typedef test::expand_bwd_test_allocator<test::int_holder>
      int_holder_allocator_type;
   typedef vector<test::int_holder, int_holder_allocator_type>
      int_holder_vector;

   if(!test::test_all_expand_bwd<int_holder_vector>())
      return 1;

   //Now user defined bigger wrapped int
   typedef test::expand_bwd_test_allocator<test::triple_int_holder>
      triple_int_holder_allocator_type;

   typedef vector<test::triple_int_holder, triple_int_holder_allocator_type>
      triple_int_holder_vector;

   if(!test::test_all_expand_bwd<triple_int_holder_vector>())
      return 1;

   return 0;
}

class recursive_vector
{
   public:
   int id_;
   vector<recursive_vector> vector_;
};

void recursive_vector_test()//Test for recursive types
{
   vector<recursive_vector> recursive_vector_vector;
}

enum Test
{
   zero, one, two, three, four, five, six
};

int main()
{
   {
      const std::size_t positions_length = 10;
      std::size_t positions[positions_length];
      vector<int> vector_int;
      vector<int> vector_int2(positions_length);
      for(std::size_t i = 0; i != positions_length; ++i){
         positions[i] = 0u;
      }
      for(std::size_t i = 0, max = vector_int2.size(); i != max; ++i){
         vector_int2[i] = i;
      }

      vector_int.insert(vector_int.begin(), 999);

      vector_int.insert_ordered_at(positions_length, positions + positions_length, vector_int2.end());

      for(std::size_t i = 0, max = vector_int.size(); i != max; ++i){
         std::cout << vector_int[i] << std::endl;
      }
   }
   recursive_vector_test();
   {
      //Now test move semantics
      vector<recursive_vector> original;
      vector<recursive_vector> move_ctor(boost::move(original));
      vector<recursive_vector> move_assign;
      move_assign = boost::move(move_ctor);
      move_assign.swap(original);
   }
   typedef vector<int> MyVector;
   typedef vector<test::movable_int> MyMoveVector;
   typedef vector<test::movable_and_copyable_int> MyCopyMoveVector;
   typedef vector<test::copyable_int> MyCopyVector;
   typedef vector<Test> MyEnumVector;

   if(test::vector_test<MyVector>())
      return 1;
   if(test::vector_test<MyMoveVector>())
      return 1;
   if(test::vector_test<MyCopyMoveVector>())
      return 1;
   if(test::vector_test<MyCopyVector>())
      return 1;
   if(test_expand_bwd())
      return 1;

   MyEnumVector v;
   Test t;
   v.push_back(t);
   v.push_back(::boost::move(t));
   v.push_back(Test());

   const test::EmplaceOptions Options = (test::EmplaceOptions)(test::EMPLACE_BACK | test::EMPLACE_BEFORE);
   if(!boost::container::test::test_emplace
      < vector<test::EmplaceInt>, Options>())
      return 1;

   if(!boost::container::test::test_propagate_allocator<vector>())
      return 1;

   return 0;

}
#include <boost/container/detail/config_end.hpp>

ext: cpp


text:
#include "task/task.h"
#include "task/thread_task.h"
#define BOOST_TEST_MODULE TASK_UT
#include <boost/test/included/unit_test.hpp>
using namespace std;
using namespace boost;
using namespace pylon;

class   wait_task2 :    public task
{
	int       _wait_sec;
public:
	wait_task2(int sec):_wait_sec(sec)
	{

	}
	virtual void  stop_execute(bool stop){}
	virtual bool execute(logger* l=NULL)
	{
		//Sleep(_wait_sec* 1000);
		cout<< "wait " << _wait_sec << " sec!" << endl;
		return  true;
	}
};
BOOST_AUTO_TEST_CASE(exe_unit)
{
	task_exec_unit eunit;

	eunit.join_task(task::sptr(new wait_task2(5)));
	eunit.join_task(task::sptr(new wait_task2(5)));
	eunit.join_task(task::sptr(new wait_task2(5)));
	eunit.join_task(task::sptr(new wait_task2(5)));
	eunit.work(NULL,2);
	eunit.wait_idel();
	eunit.stop_work();
	eunit.wait_work_end();
}

/*
class   curl_test_task :    public task
{
public:
	virtual void  stop_execute(bool stop){}
	virtual bool execute(logger* l=NULL)
	{
        char *url ="http://zion.caiyun.cc/live.html";
        stringstream outs;

        curl_accessor curl;
        curl.get(url,outs);
        std::cout << outs.str().c_str();
        return true;
	}
};

BOOST_AUTO_TEST_CASE(muti_curl_test)
{
	task_exec_unit eunit;
    for(int i =0 ; i<10 ; ++i)
        eunit.join_task(task::sptr(new curl_test_task));
	eunit.work(NULL,NULL,2);
	eunit.wait_idel();
	eunit.stop_work();
	eunit.wait_work_end();
}

*/

class echo_task : public task
{
	std::string _msg;
public:
	echo_task(const char * msg)
	{
		_msg = msg;
	}
	virtual void stop_execute(bool stop)
	{

	}
	virtual bool execute(logger* logger=NULL)
	{
		cout << "echo task :"  << _msg.c_str() <<endl;
		return true;
	}
};

BOOST_AUTO_TEST_CASE(test_timed_exit)
{

	timed_task_exec_unit eunit;
	time_t now;
	time(&now);

	eunit.join_task( now+5 ,task::sptr(new echo_task("5")));
	eunit.join_task( now+7 ,task::sptr(new echo_task("7")));
	eunit.work(NULL,1);
	eunit.join_task( now+1 ,task::sptr(new echo_task("1")));
	eunit.join_task( now+8 ,task::sptr(new echo_task("8")));
	eunit.join_task( now+3 ,task::sptr(new echo_task("3")));
	eunit.join_task( now+3 ,task::sptr(new echo_task("3")));
	//eunit.reset();
	eunit.wait_idel();
	eunit.stop_work();
	eunit.wait_work_end();
}

max_stars_repo_name: xcodecraft/youbar

max_issues_repo_name: xcodecraft/youbar

max_forks_repo_name: xcodecraft/youbar


text: #include <boost/mpi/collectives_fwd.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


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

#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <boost/random/uniform_real.hpp>

#include <util/evaluation.h>

#include <mpi2/mpi2.h>

#include <tools/detail/mfdsgd-run.h>
#include <tools/detail/mfdsgd-generated.h>

#include "parse.h"
log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("main"));

int main(int argc, char *argv[]) {
	using namespace std;
	using namespace mf;
	using namespace mpi2;
	using namespace rg;
	using namespace boost::program_options;

	// initialize mf library and mpi2
	boost::mpi::communicator& world = mfInit(argc, argv);

	mfStart();
	bool result = true;

	if (world.rank() == 0) {
		boost::this_thread::sleep(boost::posix_time::milliseconds(100)); // so that arguments are logged nicely
		Args args;

		// parse command line
		options_description desc("Options");
		desc.add_options()
			("help", "produce help message")
			("input-file", value<string>(&args.inputMatrixFile), "filename of data matrix")
			("input-test-file", value<string>(&args.inputTestMatrixFile), "filename of test matrix")
			("input-row-file", value<string>(&args.inputRowFacFile), "filename of initial row factors")
			("input-col-file", value<string>(&args.inputColFacFile), "filename of initial column factors")
			("output-row-file", value<string>(&args.outputRowFacFile), "filename of final row factors")
			("output-col-file", value<string>(&args.outputColFacFile), "filename of final column factors")
			("trace", value<string>(&args.traceFile), "filename of trace [trace.R]")
			("trace-var", value<string>(&args.traceVar), "variable name for trace [traceVar]")
			("epochs", value<mf_size_type>(&args.epochs), "number of epochs to run [10]")
			("tasks-per-rank", value<int>(&args.tasksPerRank), "number of concurrent tasks per rank [1]")
			("sgd-order", value<string>(&args.sgdOrderString), "order of SGD steps [WOR] (e.g., \"SEQ\", \"WR\", \"WOR\")")
			("stratum-order", value<string>(&args.stratumOrderString), "order of strata [COWOR] (e.g., \"SEQ\", \"RSEQ\", \"WR\", \"WOR\", \"COWOR\")")
			("map-reduce", value<bool>(&args.mapReduce), "whether to use the (slower) MapReduce implementation [false])")
			("seed", value<unsigned>(&args.seed), "seed for random number generator (system time if not set)")
			("rank", value<mf_size_type>(&args.rank), "rank of factorization")
			("update", value<string>(&args.updateString), "SGD update function (e.g., \"Sl\", \"Nzsl\", \"GklData\")")
			("regularize", value<string>(&args.regularizeString), "SGD regularization function (e.g., \"None\", \"L2(0.05)\", \"Nzl2(0.05)\")")
			("loss", value<string>(&args.lossString), "loss function (e.g., \"Nzsl\", \"Nzsl_L2(0.5)\"))")
			("abs", "if present, absolute values are taken after every SGD step")
			("truncate", value<string>(&args.truncateString), "if present, truncatation is enabled (e.g., --truncate \"(-1000, 1000)\"")
			("decay", value<string>(&args.decayString), "decay function (constant, bold driver, or auto)")
			("balance", value<string>(&args.balanceString), "Type of balancing (None, L2, Nzl2)")
		;

		positional_options_description pdesc;
		pdesc.add("input-file", 1);
		pdesc.add("input-test-file", 2);
		pdesc.add("input-row-file", 3);
		pdesc.add("input-col-file", 4);
		pdesc.add("output-row-file", 5);
		pdesc.add("output-col-file", 6);

		variables_map vm;
		store(command_line_parser(argc, argv).options(desc).positional(pdesc).run(), vm);
		notify(vm);

		// check required arguments
		if (vm.count("help") || vm.count("input-file") == 0 || vm.count("input-row-file") == 0 ||
			vm.count("input-col-file") == 0 || vm.count("update") == 0 || vm.count("regularize") == 0 ||
			vm.count("loss") == 0 || vm.count("rank") == 0 || vm.count("decay") == 0)
		{
			cerr << "Error: Options input-file, input-row-file, input-col-file, update, regularize, loss, rank, and decay have to be present" << endl;
			cout << "mfsgd [options]" << endl << endl;
			cout << desc << endl;
			exit(1);
		}

		// set default arguments
		if (vm.count("seed") == 0) args.seed = time(NULL);
		if (vm.count("trace") == 0) { args.traceFile = ""; }
		if (vm.count("trace-var") == 0) args.traceVar = "trace";
		if (vm.count("input-test-file") == 0) args.inputTestMatrixFile = "";
		if (vm.count("seed") == 0) args.seed = time(NULL);
		if (vm.count("epochs") == 0) args.epochs = 10;
		if (vm.count("tasks-per-rank") == 0) args.tasksPerRank = 1;
		if (vm.count("sgd-order") == 0) { args.sgdOrderString = "WOR"; args.sgdOrder = SGD_ORDER_WOR; }
		if (vm.count("stratum-order") == 0) { args.stratumOrderString = "COWOR"; args.stratumOrder = STRATUM_ORDER_COWOR; }
		if (vm.count("map-reduce") == 0) { args.mapReduce = false; }
		if (vm.count("output-row-file") == 0) { args.outputRowFacFile = ""; }
		if (vm.count("output-col-file") == 0) { args.outputColFacFile = ""; }
		if (vm.count("balance") == 0) { args.balanceString = "None"; }

		// print some information
		LOG4CXX_INFO(logger, "Input");
		LOG4CXX_INFO(logger, "    Input file: " << args.inputMatrixFile);
		LOG4CXX_INFO(logger, "    Input test file: " << (args.inputTestMatrixFile.length() == 0 ? "Disabled" :args.inputTestMatrixFile));
		LOG4CXX_INFO(logger, "    Input row factors: " << args.inputRowFacFile);
		LOG4CXX_INFO(logger, "    Input column factors: " << args.inputColFacFile);
		LOG4CXX_INFO(logger, "Output");
		LOG4CXX_INFO(logger, "    Output row factors: " << (args.outputRowFacFile.length() == 0 ? "Disabled" :args.outputRowFacFile));
		LOG4CXX_INFO(logger, "    Output column factors: " << (args.outputColFacFile.length() == 0 ? "Disabled" :args.outputColFacFile));
		if (args.traceFile.length() == 0) {
			LOG4CXX_INFO(logger, "    Trace: Disabled");
		} else {
			LOG4CXX_INFO(logger, "    Trace: " << args.traceFile << " (" << args.traceVar << ")");
		}
		LOG4CXX_INFO(logger, "Parallelization");
		LOG4CXX_INFO(logger, "    MPI ranks: " << world.size());
		LOG4CXX_INFO(logger, "    Tasks per rank: " << args.tasksPerRank);
		LOG4CXX_INFO(logger, "DSGD options");
		LOG4CXX_INFO(logger, "    Seed: " << args.seed);
		LOG4CXX_INFO(logger, "    Epochs: " << args.epochs);
		LOG4CXX_INFO(logger, "    Factorization rank: " << args.rank);
		LOG4CXX_INFO(logger, "    Update function: " << args.updateString);
		LOG4CXX_INFO(logger, "    Regularize function: " << args.regularizeString);
		LOG4CXX_INFO(logger, "    Loss function: " << args.lossString);
		LOG4CXX_INFO(logger, "    Decay: " << args.decayString);

		// parse balancing
		args.balanceMethod = BALANCE_SIMPLE;
		if (args.balanceString.compare("None") == 0) {
			LOG4CXX_INFO(logger, "    Balancing: Disabled");
			args.balanceType = BALANCE_NONE;
		} else if (args.balanceString.compare("L2") == 0) {
			LOG4CXX_INFO(logger, "    Balancing: L2");
			args.balanceType = BALANCE_L2;
		} else if (args.balanceString.compare("NZL2") == 0) {
			LOG4CXX_INFO(logger, "    Balancing: Nzl2");
			args.balanceType = BALANCE_NZL2;
		} else {
			cerr << "Invalid arguments for balance; expected \"None\", \"L2\" or \"Nzl2\"" << endl;
			exit(1);
		}

		// parse abs
		if (vm.count("abs") == 0) {
			LOG4CXX_INFO(logger, "    Absolute function: Disabled");
			args.abs = false;
		} else {
			LOG4CXX_INFO(logger, "    Absolute function: Enabled");
			args.abs = true;
		}

		// parse truncate
		if (vm.count("truncate") == 0) {
			args.truncateArgs.resize(2);
			args.truncateArgs[0] = NAN;
			args.truncateArgs[1] = NAN;
			LOG4CXX_INFO(logger, "    Truncation: Disabled");
		} else {
			parse::parseTruncate("truncate", args.truncateString, args);
			LOG4CXX_INFO(logger, "    Truncation: (" << args.truncateArgs[0] << "," << args.truncateArgs[1] << ")");
		}

		// parse sgdOrder
		if (args.sgdOrderString.compare("SEQ") == 0) {
			LOG4CXX_INFO(logger, "    SGD step sequence: SEQ");
			args.sgdOrder = SGD_ORDER_SEQ;
		} else if (args.sgdOrderString.compare("WR") == 0) {
			LOG4CXX_INFO(logger, "    SGD step sequence: WR");
			args.sgdOrder = SGD_ORDER_WR;
		} else if (args.sgdOrderString.compare("WOR") == 0) {
			LOG4CXX_INFO(logger, "    SGD step sequence: WOR");
			args.sgdOrder = SGD_ORDER_WOR;
		} else {
			cerr << "Invalid arguments for sgdOrder; expected \"SEQ\", \"WR\" or \"WOR\"" << endl;
			exit(1);
		}

		// parse stratumOrder
		if (args.stratumOrderString.compare("SEQ") == 0) {
			LOG4CXX_INFO(logger, "    DSGD stratum sequence: SEQ");
			args.stratumOrder = STRATUM_ORDER_SEQ;
		} else if (args.stratumOrderString.compare("RSEQ") == 0) {
			LOG4CXX_INFO(logger, "    DSGD stratum sequence: RSEQ");
			args.stratumOrder = STRATUM_ORDER_RSEQ;
		} else if (args.stratumOrderString.compare("WR") == 0) {
			LOG4CXX_INFO(logger, "    DSGD stratum sequence: WR");
			args.stratumOrder = STRATUM_ORDER_WR;
		} else if (args.stratumOrderString.compare("WOR") == 0) {
			LOG4CXX_INFO(logger, "    DSGD stratum sequence: WOR");
			args.stratumOrder = STRATUM_ORDER_WOR;
		} else if (args.stratumOrderString.compare("COWOR") == 0) {
			LOG4CXX_INFO(logger, "    DSGD stratum sequence: COWOR");
			args.stratumOrder = STRATUM_ORDER_COWOR;
		} else {
			cerr << "Invalid arguments for stratumOrder; expected \"SEQ\", \"RSEQ\", \"WR\", \"WOR\" or \"COWOR\"" << endl;
			exit(1);
		}

		LOG4CXX_INFO(logger, "    Slow MapReduce implementation: " << args.mapReduce);

		// fill fields
		args.random = Random32(args.seed);
		args.world = world;
		args.worldSize = world.size();
		args.worldRank = world.rank();
		args.tries = args.worldSize * args.tasksPerRank;
		while (args.tries < 7) args.tries += args.worldSize;
		args.blocks1 = args.worldSize * args.tasksPerRank;
		args.blocks2 = args.worldSize * args.tasksPerRank;

		// parsing
		parse::parseArg("update", args.updateString, args.updateName, args.updateArgs);
		parse::parseArg("regularize", args.regularizeString, args.regularizeName, args.regularizeArgs);
		parse::parseArg("loss", args.lossString, args.lossName, args.lossArgs);
		parse::parseDecay("decay", args.decayString, args);

		// let's go
		result = runArgs(args);

	}

	mfStop();
	mfFinalize();

	// everything OK
	return result ? 0 : 1;

}

ext: cc

max_stars_repo_name: Hui-Li/DSGDPP

max_issues_repo_name: Hui-Li/DSGDPP

max_forks_repo_name: Hui-Li/DSGDPP


text:
// @COPYRIGHT@
// Licensed under MIT license (LICENSE.txt)

// clxx/app/options/exceptions/with_no_option_name.hpp

/** // doc: clxx/app/options/exceptions/with_no_option_name.hpp {{{
 * \file clxx/app/options/exceptions/with_no_option_name.hpp
 * \todo Write documentation
 */ // }}}
#ifndef CLXX_APP_OPTIONS_EXCEPTIONS_WITH_NO_OPTION_NAME_HPP_INCLUDED
#define CLXX_APP_OPTIONS_EXCEPTIONS_WITH_NO_OPTION_NAME_HPP_INCLUDED

#include <boost/program_options/errors.hpp>

namespace clxx { namespace app { namespace options {
} } } // end namespace clxx::app::options

#endif /* CLXX_APP_OPTIONS_EXCEPTIONS_WITH_NO_OPTION_NAME_HPP_INCLUDED */
// vim: set expandtab tabstop=2 shiftwidth=2:
// vim: set foldmethod=marker foldcolumn=4:

max_stars_repo_name: ptomulik/clxx

max_issues_repo_name: ptomulik/clxx

max_forks_repo_name: ptomulik/clxx


text:
#define BOOST_TEST_MODULE Dynamic-typed OXM field operations testcases

#include <boost/test/unit_test.hpp>
#include <boost/concept/assert.hpp>
#include <boost/concept_check.hpp>

#include "types/bits.hh"
#include "oxm/field.hh"
#include "oxm/openflow_basic.hh"
#include "oxm/errors.hh"

using namespace runos;

struct Fixture {
    oxm::in_port  in_port;
    oxm::eth_src  eth_src;
    oxm::eth_dst  eth_dst;
    oxm::eth_type eth_type;
};

BOOST_FIXTURE_TEST_SUITE( runos_oxm_tests , Fixture )

BOOST_AUTO_TEST_CASE( binop_type_test ) {
    oxm::field<oxm::in_port> f1;
    oxm::field<oxm::eth_src> f2;
    oxm::field<> f3 = oxm::field<>(in_port);
    oxm::value<oxm::in_port> v1(10);
    oxm::value<oxm::eth_src> v2("aa:bb:cc:dd:ee:ff");
    oxm::value<> v3 = oxm::value<oxm::in_port>(20);
    oxm::mask<oxm::in_port> m1;
    oxm::mask<oxm::eth_src> m2;
    oxm::mask<> m3 = oxm::mask<oxm::in_port>(0);

    static_assert(
        std::is_same<
            decltype(oxm::detail::binop_type(f1, f1)),
            oxm::in_port
        >(), "test failed"
    );

    static_assert(
        std::is_same<
            decltype(oxm::detail::binop_type(f1, v1)),
            oxm::in_port
        >(), "test failed"
    );

    static_assert(
        std::is_same<
            decltype(oxm::detail::binop_type(v1, m3)),
            oxm::in_port
        >(), "test failed"
    );

    static_assert(
        std::is_same<
            decltype(oxm::detail::binop_type(f3, v1)),
            oxm::in_port
        >(), "test failed"
    );

    static_assert(
        not std::is_same<
            decltype(oxm::detail::binop_type(f3, m2)),
            oxm::in_port
        >(), "test failed"
    );

    static_assert(
        std::is_same<
            decltype(oxm::detail::binop_type(f3, v3)),
            oxm::type
        >(), "test failed"
    );
}

BOOST_AUTO_TEST_CASE( meta_test ) {
    BOOST_CHECK_EQUAL(in_port.nbits(), 32);
    BOOST_CHECK_EQUAL(in_port.nbytes(), 4);
    BOOST_CHECK(not in_port.maskable());

    BOOST_CHECK_EQUAL(eth_src.nbits(), 48);
    BOOST_CHECK_EQUAL(eth_src.nbytes(), 6);
    BOOST_CHECK(eth_src.maskable());

    BOOST_CHECK_EQUAL(eth_dst.nbits(), 48);
    BOOST_CHECK_EQUAL(eth_dst.nbytes(), 6);
    BOOST_CHECK(eth_dst.maskable());

    BOOST_CHECK_EQUAL(eth_type.nbits(), 16);
    BOOST_CHECK_EQUAL(eth_type.nbytes(), 2);
    BOOST_CHECK(not eth_type.maskable());
}

BOOST_AUTO_TEST_CASE( field_ctor_test ) {
    ////
    BOOST_TEST_MESSAGE( "Constructing some oxm::value`s" );
    ////
    oxm::value<oxm::in_port> v_in_port_10 { 10 };
    oxm::value<oxm::eth_src> v_eth_src_aabb { "aabb.ccdd.eeff" };
    oxm::value<oxm::in_port> v_copy_of_in_port_10 ( v_in_port_10 );
    oxm::value<oxm::eth_src> v_eth_src_aabb_ ( 0xaabbccddeeff );
    oxm::value<oxm::eth_dst> v_eth_dst_aabb =
        eth_dst == 0xaabbccddeeff;
    oxm::value<oxm::eth_src> v_eth_src_ddee =
        eth_src == "dd:ee:11:22:33:44";

    BOOST_CHECK_EQUAL(v_in_port_10, v_copy_of_in_port_10);
    BOOST_CHECK_EQUAL(v_eth_src_aabb, v_eth_src_aabb_);
    BOOST_CHECK_NE(v_eth_src_aabb, v_eth_dst_aabb);
    BOOST_CHECK_NE(v_eth_src_aabb, v_eth_src_ddee);

    BOOST_CHECK_THROW( oxm::value<>(in_port, bits<4>("1100")),
            oxm::bad_bit_length);

    ////
    BOOST_TEST_MESSAGE( "Constructing some oxm::mask`s" );
    ////
    oxm::mask<> m_in_port_wildcard ( in_port,
            bits<>(std::string("00000000000000000000000000000000")) );
    BOOST_CHECK( m_in_port_wildcard.wildcard() );
    BOOST_CHECK_EQUAL( m_in_port_wildcard, ~oxm::mask<oxm::in_port>() );

    oxm::mask<> m_in_port_exact ( in_port,
            bits<>(std::string("11111111111111111111111111111111")) );
    BOOST_CHECK( m_in_port_exact.exact() );

    BOOST_CHECK_THROW( oxm::mask<>( in_port, bits<>(std::string("00")) ),
            oxm::bad_bit_length );
    BOOST_CHECK_THROW( oxm::mask<>( in_port, bits<>(std::string("00000001")) ),
            oxm::bad_bit_length );

    oxm::mask<oxm::eth_src> m_eth_src_1 (eth_src, ethaddr("ff:00:00:00:00:00"));
    oxm::mask<oxm::eth_src> m_eth_src_12 {ethaddr("0f:f0:00:00:00:00")};
    oxm::mask<oxm::eth_src> m_eth_src_2 = eth_src & ethaddr("00:ff:00:00:00:00");

    oxm::mask<> m_eth_dst_3
        = oxm::mask<oxm::eth_dst>(ethaddr("00:00:ff:00:00:00"));
    oxm::mask<oxm::eth_dst> m_eth_dst_34(ethaddr("00:00:0f:f0:00:00"));
    oxm::mask<oxm::eth_dst> m_eth_dst_4(ethaddr("00:00:00:ff:00:00"));

    oxm::mask<> m_copy_of_eth_src_1 ( m_eth_src_1 );

    BOOST_CHECK( m_eth_dst_3.fuzzy() );
    BOOST_CHECK( m_eth_dst_34.fuzzy() );
    BOOST_CHECK( m_eth_dst_4.fuzzy() );
    BOOST_CHECK_EQUAL( m_eth_src_1, m_copy_of_eth_src_1 );

    ////
    BOOST_TEST_MESSAGE( "Constructing some oxm::field`s" );
    ////
    oxm::field<oxm::eth_src> f_eth_src_1 (ethaddr("aa:bb:cc:dd:ee:ff"),
                                          ethaddr("00:ff:00:ff:00:ff"));
    oxm::field<> f_eth_dst_1 (eth_dst, ethaddr("aa:bb:cc:dd:ee:ff").to_bits(),
                                       ethaddr("00:ff:00:ff:00:ff").to_bits());
    oxm::field<> f_copy_of_eth_src_1 (f_eth_src_1);
    oxm::field<oxm::eth_src> f_exact_1 = eth_src == ethaddr("aa:bb:cc:dd:ee:ff");
    oxm::field<oxm::eth_src> f_exact_2
        = (eth_src & ethaddr("ff:ff:ff:ff:ff:ff")) == ethaddr("aa:bb:cc:dd:ee:ff");

    BOOST_CHECK_EQUAL( oxm::value<oxm::eth_src>(f_eth_src_1),
                       oxm::value<oxm::eth_src>(ethaddr("00:bb:00:dd:00:ff")));
    BOOST_CHECK_EQUAL( oxm::mask<oxm::eth_src>(f_eth_src_1),
                       oxm::mask<oxm::eth_src>(ethaddr("00:ff:00:ff:00:ff")));
    BOOST_CHECK_EQUAL( f_eth_src_1.value_bits(), f_eth_dst_1.value_bits() );
    BOOST_CHECK_EQUAL( f_eth_src_1.mask_bits(), f_eth_dst_1.mask_bits() );
    BOOST_CHECK_NE( f_eth_src_1, f_eth_dst_1 );
    BOOST_CHECK_EQUAL( f_eth_src_1, f_copy_of_eth_src_1 );
    BOOST_CHECK_THROW( oxm::field<oxm::eth_type>(0x88cc, 3), oxm::bad_mask );
    BOOST_CHECK_EQUAL( f_exact_1, f_exact_2 );
    BOOST_CHECK( f_exact_1.exact() );

    ////
    BOOST_TEST_MESSAGE( "Casting oxm fields" );
    ////
    BOOST_CHECK_EQUAL( oxm::mask<>(f_eth_src_1),
                       oxm::mask<oxm::eth_src>( ethaddr("00:ff:00:ff:00:ff")) );
    BOOST_CHECK_EQUAL( oxm::value<>(f_eth_src_1),
                       oxm::value<oxm::eth_src>( ethaddr("00:bb:00:dd:00:ff")) );
    BOOST_CHECK_EQUAL( oxm::mask<>(oxm::field<>(
                    oxm::value<oxm::eth_src>(ethaddr("aa:bb:cc:dd:ee:ff")) )),
            oxm::mask<oxm::eth_src>(ethaddr("ff:ff:ff:ff:ff:ff")) );
    BOOST_CHECK_EQUAL( oxm::mask<>(oxm::field<oxm::eth_type>(10)),
                       oxm::mask<oxm::eth_type>(0xffff) );
    BOOST_CHECK_EQUAL( oxm::mask<>(oxm::field<oxm::in_port>(10)),
                       oxm::mask<oxm::in_port>(0xffffffff) );
    BOOST_CHECK( oxm::field<>(eth_src).wildcard());
    BOOST_CHECK( oxm::field<oxm::eth_src>().wildcard());

    ////
    BOOST_TEST_MESSAGE( "Assignments" );
    ////

    oxm::field<> f_copied = f_eth_src_1 = f_exact_1;
    BOOST_CHECK_EQUAL( f_copied, f_exact_1 );
    BOOST_CHECK_EQUAL( f_eth_src_1, f_exact_1 );

    oxm::mask<> m_copied = m_eth_src_1 = m_eth_src_2;
    BOOST_CHECK_EQUAL( m_copied, m_eth_src_2 );
    BOOST_CHECK_EQUAL( m_copied, m_eth_src_2 );

    oxm::value<> v_copied = v_eth_src_aabb = v_eth_src_ddee;
    BOOST_CHECK_EQUAL( v_copied, v_eth_src_ddee );
    BOOST_CHECK_EQUAL( v_copied, v_eth_src_ddee );
}

BOOST_AUTO_TEST_CASE( value_and_mask_test ) {
    BOOST_CHECK_EQUAL(
            oxm::value<oxm::eth_src>(ethaddr("aa:bb:cc:dd:ee:ff")) &
            oxm::mask<oxm::eth_src>(ethaddr("ff:00:ff:ff:00:00")),
            oxm::field<oxm::eth_src>(ethaddr("aa:00:cc:dd:00:00"),
                                     ethaddr("ff:00:ff:ff:00:00")) );

    BOOST_CHECK_EQUAL(
            oxm::mask<oxm::eth_src>(ethaddr("ff:00:ff:ff:00:00")) &
            oxm::value<oxm::eth_src>(ethaddr("aa:bb:cc:dd:ee:ff")),
            oxm::field<oxm::eth_src>(ethaddr("aa:00:cc:dd:00:00"),
                                     ethaddr("ff:00:ff:ff:00:00")) );
    BOOST_CHECK_EQUAL(
            oxm::value<oxm::eth_type>(0x88cc) & oxm::mask<oxm::eth_type>(0xffff),
            oxm::field<oxm::eth_type>(0x88cc) );

    BOOST_CHECK_EQUAL(
            oxm::value<oxm::eth_type>(0x88cc) & oxm::mask<oxm::eth_type>(0),
            oxm::field<oxm::eth_type>(0, 0) );

    BOOST_CHECK_THROW( oxm::value<>(eth_src, ethaddr().to_bits()) &
                       oxm::mask<>(eth_dst, ethaddr().to_bits()),
                       oxm::bad_operands);

    BOOST_CHECK_THROW( oxm::mask<>(eth_src, ethaddr().to_bits()) &
                       oxm::value<>(eth_dst, ethaddr().to_bits()),
                       oxm::bad_operands);
}

BOOST_AUTO_TEST_CASE( match_value_value_test ) {
    BOOST_CHECK( oxm::value<oxm::in_port>(10) & oxm::value<oxm::in_port>(10) );
    BOOST_CHECK( not (oxm::value<oxm::in_port>(10) & oxm::value<oxm::in_port>(5)) );
    BOOST_CHECK_THROW( oxm::value<>(eth_src, ethaddr().to_bits()) &
                       oxm::value<>(eth_dst, ethaddr().to_bits()),
                       oxm::bad_operands );
}

BOOST_AUTO_TEST_CASE( match_value_field_test ) {
    BOOST_CHECK( oxm::value<oxm::in_port>(10) & oxm::field<oxm::in_port>(10) );
    BOOST_CHECK( not (oxm::value<oxm::in_port>(10) & oxm::field<oxm::in_port>(5)) );
    BOOST_CHECK( oxm::value<oxm::in_port>(10) & oxm::field<oxm::in_port>(0, 0) );

    BOOST_CHECK( oxm::value<oxm::eth_src>(ethaddr("aa:bb:cc:dd:ee:ff")) &
                 oxm::field<oxm::eth_src>(ethaddr("aa:11:cc:dd:11:11"),
                                          ethaddr("ff:00:ff:ff:00:00")) );

    BOOST_CHECK( oxm::field<oxm::eth_src>(ethaddr("aa:11:cc:dd:11:11"),
                                          ethaddr("ff:00:ff:ff:00:00")) &
                 oxm::value<oxm::eth_src>(ethaddr("aa:bb:cc:dd:ee:ff")) );

    BOOST_CHECK( not (oxm::field<oxm::eth_src>(ethaddr("a1:11:cc:dd:11:11"),
                                               ethaddr("ff:00:ff:ff:00:00")) &
                      oxm::value<oxm::eth_src>(ethaddr("aa:bb:cc:dd:ee:ff"))) );

    BOOST_CHECK_THROW( oxm::field<>(eth_src, ethaddr().to_bits()) &
                       oxm::value<>(eth_dst, ethaddr().to_bits()),
                       oxm::bad_operands );

    BOOST_CHECK_THROW( oxm::value<>(eth_src, ethaddr().to_bits()) &
                       oxm::field<>(eth_dst, ethaddr().to_bits()),
                       oxm::bad_operands );
}

BOOST_AUTO_TEST_CASE( match_field_field_test ) {
    BOOST_CHECK( oxm::field<oxm::eth_src>(ethaddr("aa:bb:cc:dd:ee:ff"),
                                          ethaddr("ff:00:ff:00:ff:00")) &
                 oxm::field<oxm::eth_src>(ethaddr("11:22:33:44:55:66"),
                                          ethaddr("00:ff:00:ff:00:ff")) );

    BOOST_CHECK( oxm::field<oxm::eth_src>(ethaddr("aa:bb:cc:dd:ee:ff"),
                                          ethaddr("ff:00:ff:00:ff:00")) &
                 oxm::field<oxm::eth_src>(ethaddr("11:22:3c:44:55:66"),
                                          ethaddr("00:ff:0f:ff:00:ff")) );

    BOOST_CHECK( oxm::field<oxm::eth_src>(ethaddr("aa:bb:cc:d4:ee:ff"),
                                          ethaddr("ff:00:ff:0f:ff:00")) &
                 oxm::field<oxm::eth_src>(ethaddr("11:22:33:44:55:66"),
                                          ethaddr("00:ff:00:ff:00:ff")) );

    BOOST_CHECK( not(oxm::field<oxm::eth_src>(ethaddr("aa:bb:cc:dd:ee:ff"),
                                              ethaddr("ff:00:ff:00:ff:00")) &
                     oxm::field<oxm::eth_src>(ethaddr("11:22:33:44:55:66"),
                                              ethaddr("00:ff:0f:ff:00:ff"))) );

    BOOST_CHECK_THROW( oxm::field<>(eth_src, ethaddr().to_bits()) &
                       oxm::field<>(eth_dst, ethaddr().to_bits()),
                       oxm::bad_operands );
}

BOOST_AUTO_TEST_CASE( rewrite_value_value_test ) {
    BOOST_CHECK_EQUAL( oxm::value<oxm::eth_type>(10) >> oxm::value<oxm::eth_type>(20)
                     , oxm::value<oxm::eth_type>(20) );
    BOOST_CHECK_THROW( oxm::value<>(eth_src, ethaddr().to_bits()) >>
                       oxm::value<>(eth_dst, ethaddr().to_bits()),
                       oxm::bad_operands );
}

BOOST_AUTO_TEST_CASE( rewrite_value_field_test ) {
    BOOST_CHECK_EQUAL( oxm::value<oxm::eth_src>(ethaddr("aa:bb:cc:dd:ee:ff")) >>
                       oxm::field<oxm::eth_src>(ethaddr("11:22:33:44:55:66"),
                                                ethaddr("ff:00:ff:00:ff:00")),
                       oxm::value<oxm::eth_src>(ethaddr("11:bb:33:dd:55:ff")) );
}

BOOST_AUTO_TEST_CASE( rewrite_field_field_test ) {
    BOOST_CHECK_EQUAL( oxm::field<oxm::eth_src>(ethaddr("aa:bb:00:00:00:00"),
                                                ethaddr("ff:ff:00:00:00:00")) >>
                       oxm::field<oxm::eth_src>(ethaddr("00:11:22:33:00:00"),
                                                ethaddr("00:ff:ff:ff:00:00"))
                     , oxm::field<oxm::eth_src>(ethaddr("aa:11:22:33:00:00"),
                                                ethaddr("ff:ff:ff:ff:00:00")) );
}

BOOST_AUTO_TEST_SUITE_END( )

max_stars_repo_name: Alexey-Ershov/runos

max_issues_repo_name: Alexey-Ershov/runos

max_forks_repo_name: Alexey-Ershov/runos


text:
#include <QtTest>
#include <Eigen/Dense>
#include <vector>
#include <iostream>
#include "permutationtree.h"
#include "multyrowarray.h"
#include "matrices.h"

//Utility class used to compare generated permutations
struct classcomp {
    //assuming that lhs and rhs have the same size
    bool operator() (const std::vector<int>& lhs, const std::vector<int>& rhs) const{
        int n = lhs.size();

        for(int i = 0; i < n; i++){
            if(lhs[i] < rhs[i])
                return true;
            else if(lhs[i] > rhs[i])
                return false;
        }
        return false;
    }
};

class TestPermutationTree : public QObject
{
    Q_OBJECT

public:
    TestPermutationTree();
    ~TestPermutationTree();

private:
    Eigen::MatrixXd X1;
    Eigen::MatrixXd X2;
    MultyRowArray a1;
    MultyRowArray a2;
    void testLAlgorithmTree(Eigen::MatrixXd& X, MultyRowArray& a);
    void testAllSignFlippingsTree(Eigen::MatrixXd& X, MultyRowArray& a);
    void testAllSignFlippingsAndPermutation(Eigen::MatrixXd& X, MultyRowArray& a);
    void testRandomSwapping(Eigen::MatrixXd& X, MultyRowArray& a, int n);
    void testRandomSignFlipping(Eigen::MatrixXd& X, MultyRowArray& a, int n);
    void computeShuffling(PermutationTree &t, std::set<std::vector<int>, classcomp> &generatedPermutations, int &currentPermutation);

private slots:
    void initTestCase();
    void allSignFlippingsAndPermutationsTest1();
    void allSignFlippingsAndPermutationsTest2();
    //Binary Flippings only need two tests since they don't care about
    //repetitions in the design matrix
    void allSignFlippingsTest1();
    void allSignFlippingsTest2();
    void lAlgorithmtest1();
    void lAlgorithmtest2();
    void lAlgorithmtest3();
    void lAlgorithmtest4();
    void cleanUpTestCase();
};

//--------------PRIVATE METHODS------------------

void TestPermutationTree::testLAlgorithmTree(Eigen::MatrixXd& X, MultyRowArray& a) {

    PermutationTree t(a);
    t.initializeThreeColsArray();
    t.initializeBinaryCounters();
    int numPermutations = t.calculatePermutations(X, true, false);
    std::cout << "Number of possible shufflings:" << numPermutations << std::endl;
    int currentPermutation = 0;
    std::set<std::vector<int>, classcomp> generatedPermutations;
    t.reverseLAlgorithm();
    while(true){
        //std::vector<int> currentPerm = t.getPermutationVector();
        std::vector<int> currentPerm = t.getSignVector();
        if(generatedPermutations.count(currentPerm)){
            std::cout << "Warning! Permutation:" << std::endl;
            for(int a: currentPerm)
                std::cout << a << " ";
            std::cout << std::endl;
            std::cout << " already generated!" << std::endl;
            //the test fails if we generate twice the same permutation
            QCOMPARE(false, true);
        }
        else
            generatedPermutations.insert(currentPerm);
        Eigen::MatrixXd P = buildShufflingMatrix(currentPerm);
        std::cout << currentPermutation << " permutation vector is: " << std::endl;
        for(int a: currentPerm)
            std::cout << a << " ";
        std::cout << std::endl;
        std::cout << currentPermutation++ << " permutation matrix is: " << std::endl;
        std::cout << P << std::endl;
        if(!t.LAlgorithm())
            break;
    }
    QCOMPARE(currentPermutation, numPermutations);

    std::cout << "Finished permutations! Restoring the tree to its original state" << std::endl;
    t.resetTreePermutationState();
    //std::vector<int> currentPerm = t.getPermutationVector();
    std::vector<int> currentPerm = t.getSignVector();
    std::cout << "Original permutation is: " << std::endl;
    for(int a: currentPerm)
        std::cout << a << " ";
    std::cout << std::endl;
    std::cout << "Finished!" << std::endl;
}

void TestPermutationTree::testAllSignFlippingsTree(Eigen::MatrixXd& X, MultyRowArray& a) {

    PermutationTree t(a);
    t.initializeThreeColsArray();
    t.initializeBinaryCounters();
    int numPermutations = t.calculatePermutations(X, false, true);
    std::cout << "Number of possible sign flipping:" << numPermutations << std::endl;
    int currentPermutation = 0;
    std::set<std::vector<int>, classcomp> generatedPermutations;
    while(true){
        //std::vector<int> currentPerm = t.getPermutationVector();
        std::vector<int> currentPerm = t.getSignVector();
        if(generatedPermutations.count(currentPerm)){
            std::cout << "Warning! Sign flipping:" << std::endl;
            for(int a: currentPerm)
                std::cout << a << " ";
            std::cout << std::endl;
            std::cout << " already generated!" << std::endl;
            //the test fails if we generate twice the same permutation
            QCOMPARE(false, true);
        }
        else
            generatedPermutations.insert(currentPerm);
        Eigen::MatrixXd P = buildShufflingMatrix(currentPerm);
        std::cout << currentPermutation << " sign flipping vector is: " << std::endl;
        for(int a: currentPerm)
            std::cout << a << " ";
        std::cout << std::endl;
        std::cout << currentPermutation++ << " sign flipping matrix is: " << std::endl;
        std::cout << P << std::endl;
        if(!t.signFlipping())
            break;
    }
    QCOMPARE(currentPermutation, numPermutations);
    std::cout << "Finished sign flippings! Restoring the tree to its original state" << std::endl;
    t.resetTreeSignState();
    std::vector<int> currentPerm = t.getSignVector();
    std::cout << "Original sign flipping is: " << std::endl;
    for(int a: currentPerm)
        std::cout << a << " ";
    std::cout << std::endl;
    std::cout << "Finished!" << std::endl;

}

void TestPermutationTree::computeShuffling(PermutationTree& t, std::set<std::vector<int>, classcomp>& generatedPermutations, int& currentPermutation)
{
    std::vector<int> currentPerm = t.getSignVector();
    if(generatedPermutations.count(currentPerm)){
        std::cout << "Warning! Shuffling:" << std::endl;
        for(int a: currentPerm)
            std::cout << a << " ";
        std::cout << std::endl;
        std::cout << " already generated!" << std::endl;
        //the test fails if we generate twice the same permutation
        QCOMPARE(false, true);
    }
    else
        generatedPermutations.insert(currentPerm);
    Eigen::MatrixXd P = buildShufflingMatrix(currentPerm);
    std::cout << currentPermutation << " shuffling is: " << std::endl;
    for(int a: currentPerm)
        std::cout << a << " ";
    std::cout << std::endl;
    std::cout << currentPermutation++ << " shuffling matrix is: " << std::endl;
    std::cout << P << std::endl;
}

void TestPermutationTree::testAllSignFlippingsAndPermutation(Eigen::MatrixXd& X, MultyRowArray &a){
    PermutationTree t(a);
    t.initializeThreeColsArray();
    t.initializeBinaryCounters();
    int numPermutations = t.calculatePermutations(X, true, true);
    std::cout << "Number of possible shufflings:" << numPermutations << std::endl;
    int currentPermutation = 0;
    std::set<std::vector<int>, classcomp> generatedPermutations;
    t.reverseLAlgorithm();
    computeShuffling(t, generatedPermutations, currentPermutation);
    while(t.signFlipping()){
        computeShuffling(t, generatedPermutations, currentPermutation);
    }
    t.resetTreeSignState();
    while(t.LAlgorithm()){
        t.resetTreeSignState();
        computeShuffling(t, generatedPermutations, currentPermutation);
        while(t.signFlipping()){
            computeShuffling(t, generatedPermutations, currentPermutation);
        }
    }
    QCOMPARE(currentPermutation, numPermutations);
    std::cout << "Finished all shufflings! Restoring the tree to its original state" << std::endl;
    t.resetTreeSignState();
    t.resetTreePermutationState();
    std::vector<int> currentPerm = t.getSignVector();
    std::cout << "Original shuffling is: " << std::endl;
    for(int a: currentPerm)
        std::cout << a << " ";
    std::cout << std::endl;
    std::cout << "Finished!" << std::endl;
}

void TestPermutationTree::testRandomSwapping(Eigen::MatrixXd& X, MultyRowArray &a, int n){
    PermutationTree t(a);
    t.initializeThreeColsArray();
    t.initializeBinaryCounters();
    int numPermutations = t.calculatePermutations(X, true, false);
    std::cout << "Number of possible permutations:" << numPermutations << std::endl;
    std::vector<int> originalPerm = t.getSignVector();
    Eigen::MatrixXd O = buildShufflingMatrix(originalPerm);
    std::cout << " Original permutation is: " << std::endl;
    for(int a: originalPerm)
        std::cout << a << " ";
    std::cout << std::endl;
    std::cout << "Original shuffling matrix is: " << std::endl;
    std::cout << O << std::endl;
    std::cout << std::endl;
    for(int currentPermutation = 1; currentPermutation <= n; currentPermutation++){
        t.randomShuffle();
        std::vector<int> currentPerm = t.getSignVector();
        Eigen::MatrixXd P = buildShufflingMatrix(currentPerm);
        std::cout << currentPermutation << " Shuffling vector is: " << std::endl;
        for(int a: currentPerm)
            std::cout << a << " ";
        std::cout << std::endl;
        std::cout << currentPermutation << " shuffling matrix is: " << std::endl;
        std::cout << P << std::endl;
    }

    std::cout << "Finished required random shufflings! Restoring the tree to its original state" << std::endl;
    t.resetTreePermutationState();
    std::vector<int> currentPerm = t.getSignVector();
    std::cout << "Original permutation is: " << std::endl;
    for(int a: currentPerm)
        std::cout << a << " ";
    std::cout << std::endl;
    std::cout << "Finished!" << std::endl;
}

void TestPermutationTree::testRandomSignFlipping(Eigen::MatrixXd& X, MultyRowArray &a, int n){
    PermutationTree t(a);
    t.initializeThreeColsArray();
    t.initializeBinaryCounters();
    int numPermutations = t.calculatePermutations(X, false, true);
    std::cout << "Number of possible sign flippings:" << numPermutations << std::endl;
    for(int currentPermutation = 1; currentPermutation <= n; currentPermutation++){
        std::vector<int> currentPerm = t.getSignVector();
        Eigen::MatrixXd P = buildShufflingMatrix(currentPerm);
        std::cout << currentPermutation << " sign flipping vector is: " << std::endl;
        for(int a: currentPerm)
            std::cout << a << " ";
        std::cout << std::endl;
        std::cout << currentPermutation << " sign flipping matrix is: " << std::endl;
        std::cout << P << std::endl;
        t.randomSignFlip();
    }

    std::cout << "Finished required random sign flippings! Restoring the tree to its original state" << std::endl;
    t.resetTreeSignState();
    std::vector<int> currentPerm = t.getSignVector();
    std::cout << "Original permutation is: " << std::endl;
    for(int a: currentPerm)
        std::cout << a << " ";
    std::cout << std::endl;
    std::cout << "Finished!" << std::endl;
}

//----------PUBLIC METHODS-----------------

TestPermutationTree::TestPermutationTree()
{
    //First matrix used for tests, no repetitions at all
    X1 = Eigen::MatrixXd(9, 2);

    X1(0,0) = 1;
    X1(0,1) = 2;
    X1(1,0) = 3;
    X1(1,1) = 4;
    X1(2,0) = 5;
    X1(2,1) = 6;
    X1(3,0) = 7;
    X1(3,1) = 8;
    X1(4,0) = 9;
    X1(4,1) = 10;

    X1(5,0) = 11;
    X1(5,1) = 12;
    X1(6,0) = 13;
    X1(6,1) = 14;
    X1(7,0) = 15;
    X1(7,1) = 16;
    X1(8,0) = 17;
    X1(8,1) = 18;

    //Second matrix used for tests
    //Here there are repetitions, specifically:
    //0 = 6
    //1 = 7
    //2 = 8
    X2 = Eigen::MatrixXd(9, 2);

    X2(0,0) = 1;
    X2(0,1) = 2;
    X2(1,0) = 3;
    X2(1,1) = 4;
    X2(2,0) = 5;
    X2(2,1) = 6;
    X2(3,0) = 7;
    X2(3,1) = 8;
    X2(4,0) = 9;
    X2(4,1) = 10;

    X2(5,0) = 11;
    X2(5,1) = 12;
    X2(6,0) = 1;
    X2(6,1) = 2;
    X2(7,0) = 3;
    X2(7,1) = 4;
    X2(8,0) = 5;
    X2(8,1) = 6;

    a1 = MultyRowArray(9,3);
    a1[0][0] = 1;
    a1[0][1] = 1;
    a1[0][2] = 1;
    a1[0][3] = 1;
    a1[0][4] = 1;
    a1[0][5] = 1;
    a1[0][6] = 1;
    a1[0][7] = 1;
    a1[0][8] = 1;

    a1[1][0] = -1;
    a1[1][1] = -1;
    a1[1][2] = -1;
    a1[1][3] = -2;
    a1[1][4] = -2;
    a1[1][5] = -2;
    a1[1][6] = -3;
    a1[1][7] = -3;
    a1[1][8] = -3;

    a2 = MultyRowArray(9,2);

    a2[0][0] = 1;
    a2[0][1] = 1;
    a2[0][2] = 1;
    a2[0][3] = 1;
    a2[0][4] = 1;
    a2[0][5] = 1;
    a2[0][6] = 1;
    a2[0][7] = 1;
    a2[0][8] = 1;
}

TestPermutationTree::~TestPermutationTree()
{

}

//-----------TEST CASES------------------

void TestPermutationTree::initTestCase(){

}

void TestPermutationTree::lAlgorithmtest1(){
    testLAlgorithmTree(X2, a1);
}

void TestPermutationTree::lAlgorithmtest2(){
    testLAlgorithmTree(X2, a2);
}

void TestPermutationTree::lAlgorithmtest3(){
    testLAlgorithmTree(X1, a1);
}

void TestPermutationTree::lAlgorithmtest4(){
    testLAlgorithmTree(X1, a2);
}

//For both EE and ISE assumptions, we use only multyRowArray1 since
//otherwise exhaustive approach won't end
void TestPermutationTree::allSignFlippingsAndPermutationsTest1(){
    testAllSignFlippingsAndPermutation(X1, a1);
}

void TestPermutationTree::allSignFlippingsAndPermutationsTest2(){
    testAllSignFlippingsAndPermutation(X2, a1);
}

void TestPermutationTree::allSignFlippingsTest1(){
    //We could also have used X2, doesn't really matter for sign flips
    testAllSignFlippingsTree(X1, a1);
}

void TestPermutationTree::allSignFlippingsTest2(){
    //We could also have used X2, doesn't really matter for sign flips
    testAllSignFlippingsTree(X1, a2);
}

void TestPermutationTree::cleanUpTestCase(){

}

QTEST_APPLESS_MAIN(TestPermutationTree)

#include "testpermutationtree.moc"


text: #include <boost/mpl/aux_/preprocessed/bcc_pre590/apply_fwd.hpp>


text:
#include "CMRTGadget.h"
#include "cuNFFT.h"
#include "vector_td_utilities.h"
#include "permutationOperator.h"
#include "hoNDArray_utils.h"
#include "hoNDArray_fileio.h"
#include "cuNDArray_utils.h"
#include "cuNDArray_elemwise.h"
#include "cuNDArray_operators.h"
#include "radial_utilities.h"
#include "vector_td_operators.h"
#include "../../toolboxes/nfft/NFFTOperator.h"
#include "multiplicationOperatorContainer.h"
#include "cuCgSolver.h"
#include "cuTvOperator.h"
#include "lbfgsSolver.h"
#include "cuSbcCgSolver.h"
#include "cuPartialDerivativeOperator.h"
#include "cuPartialDerivativeOperator2.h"
#include <numeric>
#include <functional>
#include "cuNlcgSolver.h"
#include <boost/make_shared.hpp>

#include <ismrmrd/xml.h>
#include <cmath>

namespace Gadgetron{

int CMRTGadget::process_config(ACE_Message_Block* mb)
{
	ISMRMRD::IsmrmrdHeader h;
	ISMRMRD::deserialize(mb->rd_ptr(),h);

	if (h.encoding.size() != 1) {
		GDEBUG("This Gadget only supports one encoding space\n");
		return GADGET_FAIL;
	}

	ISMRMRD::EncodingSpace e_space = h.encoding[0].encodedSpace;
	ISMRMRD::EncodingSpace r_space = h.encoding[0].reconSpace;
	ISMRMRD::EncodingLimits e_limits = h.encoding[0].encodingLimits;

	// Matrix size x is the oversampled readout size : size FH*2 -- not for the hyperplarization?
	// Matrix size y is the AP/RL size

	image_space_dimensions_3D_.push_back(e_space.matrixSize.y);
	image_space_dimensions_3D_.push_back(e_space.matrixSize.y);
	image_space_dimensions_3D_.push_back(e_space.matrixSize.x/*/2*/);

	GDEBUG("Matrix size: %d, %d, %d\n",
			image_space_dimensions_3D_[0],
			image_space_dimensions_3D_[1],
			image_space_dimensions_3D_[2] );

	GDEBUG("Matrix size: %d, %d\n", e_space.matrixSize.x, e_space.matrixSize.y, e_space.matrixSize.z);
	dimensions_.push_back(r_space.matrixSize.x);
	dimensions_.push_back(r_space.matrixSize.y);

	field_of_view_.push_back(e_space.fieldOfView_mm.x);
	field_of_view_.push_back(e_space.fieldOfView_mm.y);
	GDEBUG("FOV: %f, %f\n", r_space.fieldOfView_mm.x, r_space.fieldOfView_mm.y);

	repetitions_ = e_limits.repetition.is_present() ? e_limits.repetition.get().maximum + 1 : 1;
	GDEBUG("#Repetitions: %d\n", repetitions_);

	golden_ratio_ =golden_ratio.value();
	use_TV_ = use_TV.value();
	projections_per_recon_ = projections_per_recon.value();
	iterations_ = iterations.value();

	return GADGET_OK;
}

int CMRTGadget::process(GadgetContainerMessage< ISMRMRD::AcquisitionHeader > *m1,        // header
		GadgetContainerMessage< hoNDArray< std::complex<float> > > *m2,  // data
		GadgetContainerMessage< hoNDArray<float> > *m3 )                 // traj/dcw
{
	// Throw away any noise samples if they have been allowed to pass this far down the chain...
	//

	bool is_noise = m1->getObjectPtr()->isFlagSet(ISMRMRD::ISMRMRD_ACQ_IS_NOISE_MEASUREMENT);
	if (is_noise) {
		m1->release();
		return GADGET_OK;
	}

	// First pass initialization
	//

	if (frame_readout_queue_.empty()) {
		samples_per_readout_ = m1->getObjectPtr()->number_of_samples;
		num_coils_ = m1->getObjectPtr()->active_channels;
		dimensions_.push_back(m1->getObjectPtr()->active_channels);
		dimensions_.push_back(repetitions_);
		num_trajectory_dims_ = m3->getObjectPtr()->get_size(0); // 2 for trajectories only, 3 for both trajectories + dcw
	}

	// Enqueue incoming readouts and trajectories
	//

	frame_readout_queue_.push(std::unique_ptr<ReadoutMessage>(duplicate_array(m2)));

	//Only extract trajectories for first frame. Assume next frames are equal
	if (frames.empty()) frame_traj_queue_.push(std::unique_ptr<TrajectoryMessage>(duplicate_array(m3)));

	// If the last readout for a slice has arrived then perform a reconstruction
	//

	bool is_last_scan_in_repetition =
			m1->getObjectPtr()->isFlagSet(ISMRMRD::ISMRMRD_ACQ_LAST_IN_REPETITION);

	if (is_last_scan_in_repetition) {
		num_frames++;
		GDEBUG("FRAME # %d \n",num_frames);
		// Get samples for frame
		//
		GDEBUG("Extracting samples \n");
		frames.push_back(extract_samples_from_queue(frame_readout_queue_));
		// Get trajectories/dcw for frame - Only for first frame
		//
		if (frames.size() == 1 ){
			extract_trajectory_and_dcw_from_queue(frame_traj_queue_, this->traj, this->dcw);
			GDEBUG("Extracting trajectory \n");
		}

		bool is_last_scan_in_slice= m1->getObjectPtr()->isFlagSet(ISMRMRD::ISMRMRD_ACQ_LAST_IN_SLICE);
		GDEBUG("Last scan in slice %i \n",is_last_scan_in_slice);
		//If we have enough projections, get the show on the road
		if (is_last_scan_in_slice ){
			GDEBUG("Framing %i frames \n",num_frames);

			if (num_frames%projections_per_recon_ != 0) {
				GDEBUG("Number of frames must be divisible by number of projecitons");
				return GADGET_FAIL;
			}
			boost::shared_ptr<cuNDArray<float_complext> > data = get_combined_frames();
			auto data_dims = data->get_dimensions();
			size_t ntimeframes = data_dims->back()/projections_per_recon_;
			data_dims->back() = projections_per_recon_;
			data_dims->push_back(ntimeframes);
			data->reshape(data_dims);
			// Initialize plan
			//
			GDEBUG("Data size: %i %i %i",data->get_size(0),data->get_size(1),data->get_size(2));
			boost::shared_ptr<cuNDArray<floatd2> >cu_traj(new cuNDArray<floatd2>(*traj));

			std::vector<size_t> projection_dims;
			projection_dims.push_back(dimensions_[0]*2);
			projection_dims.push_back(dimensions_[1]);

			projection_dims.push_back(projections_per_recon_);
			projection_dims.push_back(ntimeframes);

			//cuNDArray<float_complext> result(&image_space_dimensions_3D_);
			boost::shared_ptr<CMRTOperator<float> > E(new CMRTOperator<float>);
			E->setup(cu_traj,image_space_dimensions_3D_,projection_dims,0,golden_ratio_);

			auto image_space_dimensions_4D = image_space_dimensions_3D_;
			image_space_dimensions_4D.push_back(ntimeframes);
			E->set_domain_dimensions(&image_space_dimensions_4D);
			E->set_codomain_dimensions(data->get_dimensions().get());

			boost::shared_ptr<cuNDArray<float_complext> > result;
			//cuCgSolver<float_complext> solver;
			//cuNlcgSolver<float_complext> solver;

			if (use_TV_){
				cuSbcCgSolver<float_complext> solver;
				solver.set_encoding_operator(E);
				//solver.set_max_iterations(20);
				solver.set_max_outer_iterations(iterations_);
				solver.get_inner_solver()->set_max_iterations(10);
				solver.set_tc_tolerance(1e-8f);
				auto Rx1_ = boost::make_shared< cuPartialDerivativeOperator<float_complext,4> >(0);

				auto Ry1_ = boost::make_shared< cuPartialDerivativeOperator<float_complext,4> >(1);
				auto Rz1_ = boost::make_shared< cuPartialDerivativeOperator<float_complext,4> >(2);

				auto Rt1_ = boost::make_shared< cuPartialDerivativeOperator2<float_complext,4> >();

				Rx1_->set_domain_dimensions(&image_space_dimensions_4D);
				Rx1_->set_codomain_dimensions(&image_space_dimensions_4D);

				Ry1_->set_domain_dimensions(&image_space_dimensions_4D);
				Ry1_->set_codomain_dimensions(&image_space_dimensions_4D);

				Rz1_->set_domain_dimensions(&image_space_dimensions_4D);
				Rz1_->set_codomain_dimensions(&image_space_dimensions_4D);

				Rt1_->set_domain_dimensions(&image_space_dimensions_4D);
				Rt1_->set_codomain_dimensions(&image_space_dimensions_4D);
				float lambda = 2000;
				float mu = 1000;
				Rx1_ ->set_weight(lambda);
				Ry1_ ->set_weight(lambda);
				Rz1_ ->set_weight(lambda);
				Rt1_->set_weight(lambda);
				E->set_weight(mu);
				solver.add_regularization_group_operator(Rx1_);
				solver.add_regularization_group_operator(Ry1_);
				solver.add_regularization_group_operator(Rz1_);
				solver.add_regularization_group_operator(Rt1_);
				solver.add_group();

				solver.set_output_mode(cuCgSolver<float_complext>::OUTPUT_VERBOSE);

				result = solver.solve(data.get());
			} else {
				cuCgSolver<float_complext> solver;
				solver.set_encoding_operator(E);
				solver.set_max_iterations(iterations_);
				solver.set_tc_tolerance(1e-8f);
				solver.set_output_mode(cuCgSolver<float_complext>::OUTPUT_VERBOSE);

				result = solver.solve(data.get());
			}

			size_t nelements3d = std::accumulate(image_space_dimensions_3D_.begin(),image_space_dimensions_3D_.end(),1,std::multiplies<size_t>());

			for (size_t i = 0; i < ntimeframes; i++){

				// Define the image header
				//

				GadgetContainerMessage<ISMRMRD::ImageHeader> *cm1 =
						new GadgetContainerMessage<ISMRMRD::ImageHeader>();

				GadgetContainerMessage< hoNDArray< std::complex<float> > > *cm2 =
						new GadgetContainerMessage<hoNDArray< std::complex<float> > >();

				cm1->getObjectPtr()->flags = 0;
				cm1->cont(cm2);

				cm1->getObjectPtr()->field_of_view[0]   = field_of_view_[0];
				cm1->getObjectPtr()->field_of_view[1]   = field_of_view_[1];
				cm1->getObjectPtr()->channels           = num_coils_;
				cm1->getObjectPtr()->repetition         = m1->getObjectPtr()->idx.repetition;

				memcpy(cm1->getObjectPtr()->patient_table_position,
						m1->getObjectPtr()->patient_table_position, sizeof(float)*3);

				cm1->getObjectPtr()->data_type = ISMRMRD::ISMRMRD_CXFLOAT;
				cm1->getObjectPtr()->image_index = 0;
				cm1->getObjectPtr()->image_series_index = 0;

				// std::complex<float> and Gadgetron::complext<float> are binary compatible
				cuNDArray<complext<float> > cuView(image_space_dimensions_3D_,result->get_data_ptr()+i*nelements3d);
				boost::shared_ptr< hoNDArray< complext<float> > > host_result = cuView.to_host();
				*cm2->getObjectPtr() = *((hoNDArray< std::complex<float> >*) host_result.get());

				cm1->getObjectPtr()->matrix_size[0] = image_space_dimensions_3D_[0];
				cm1->getObjectPtr()->matrix_size[1] = image_space_dimensions_3D_[1];
				cm1->getObjectPtr()->matrix_size[2] = image_space_dimensions_3D_[2];
				cm1->getObjectPtr()->channels       = 1;
				cm1->getObjectPtr()->image_index    = i+1;

				if (this->next()->putq(cm1) < 0) {
					GDEBUG("Failed to put result image on to queue\n");
					cm1->release();
					return GADGET_FAIL;
				}
			}

			num_frames = 0;
		}

	}

	m1->release();
	return GADGET_OK;
}

template<class T> GadgetContainerMessage< hoNDArray<T> >*
CMRTGadget::duplicate_array( GadgetContainerMessage< hoNDArray<T> > *array )
{
	GadgetContainerMessage< hoNDArray<T> > *copy = new GadgetContainerMessage< hoNDArray<T> >();
	*(copy->getObjectPtr()) = *(array->getObjectPtr());
	return copy;
}

boost::shared_ptr< hoNDArray<float_complext> >
CMRTGadget::extract_samples_from_queue ( std::queue<std::unique_ptr<ReadoutMessage>> &queue )
{
	unsigned int readouts_buffered = queue.size();

	std::vector<size_t> dims;
	dims.push_back(samples_per_readout_);
	dims.push_back(readouts_buffered);
	dims.push_back(num_coils_);

	boost::shared_ptr< hoNDArray<float_complext> > host_samples(new hoNDArray<float_complext>(dims));

	for (unsigned int p=0; p<readouts_buffered; p++) {

            ReadoutMessage *mbq = queue.front().release();
            queue.pop();

            GadgetContainerMessage< hoNDArray< std::complex<float> > > *daq = AsContainerMessage<hoNDArray< std::complex<float> > >(mbq);

            if (!daq) {
                    GDEBUG("Unable to interpret data on message queue\n");
                    throw std::runtime_error("CMRTGadget::extract_samples_from_queue: failed to interpret data");
            }

            for (unsigned int c = 0; c < num_coils_; c++) {

                    float_complext *data_ptr = host_samples->get_data_ptr();
                    data_ptr += c*samples_per_readout_*readouts_buffered+p*samples_per_readout_;

                    std::complex<float> *r_ptr = daq->getObjectPtr()->get_data_ptr();
                    r_ptr += c*daq->getObjectPtr()->get_size(0);

                    memcpy(data_ptr, r_ptr, samples_per_readout_*sizeof(float_complext));
            }

            mbq->release();
	}

	return host_samples;
}

boost::shared_ptr< hoNDArray<float> >
CMRTGadget::extract_trajectory_from_queue ( std::queue<std::unique_ptr<TrajectoryMessage>> &queue )
{
	unsigned int readouts_buffered = queue.size();

	std::vector<size_t> dims;
	dims.push_back(num_trajectory_dims_); // 2 for trajectories only, 3 for both trajectories + dcw
	dims.push_back(samples_per_readout_);
	dims.push_back(readouts_buffered);

	boost::shared_ptr< hoNDArray<float> > host_traj(new hoNDArray<float>(dims));

	for (unsigned int p=0; p<readouts_buffered; p++) {

            TrajectoryMessage *mbq = queue.front().release();
            queue.pop();

            GadgetContainerMessage< hoNDArray<float> > *daq = AsContainerMessage<hoNDArray<float> >(mbq);

            if (!daq) {
                    GDEBUG("Unable to interpret data on message queue\n");
                    throw std::runtime_error("CMRTGadget::extract_trajectory_from_queue: failed to interpret data");
            }

            float *data_ptr = host_traj->get_data_ptr();
            data_ptr += num_trajectory_dims_*samples_per_readout_*p;

            float *r_ptr = daq->getObjectPtr()->get_data_ptr();

            memcpy(data_ptr, r_ptr, num_trajectory_dims_*samples_per_readout_*sizeof(float));

            mbq->release();
	}

	return host_traj;
}

void CMRTGadget::extract_trajectory_and_dcw_from_queue
( std::queue<std::unique_ptr<TrajectoryMessage>> &queue, boost::shared_ptr< hoNDArray<floatd2> > & traj, boost::shared_ptr< hoNDArray<float> > & dcw )
{
	// Extract trajectory and (if present) density compensation weights.
	// They are stored as a float array of dimensions: {2,3} x #samples_per_readout x #readouts.
	// We need
	// - a floatd2 trajectory array
	// - a float dcw array
	//

	if( num_trajectory_dims_ == 2 ){
		//This is an evil, evil hack to get the trajectories out. Ohh the horror.
		boost::shared_ptr<hoNDArray<float> > tmp_traj = extract_trajectory_from_queue( queue );
		std::vector<size_t> dims_1d; dims_1d.push_back(tmp_traj->get_size(1)*tmp_traj->get_size(2));
		traj = boost::shared_ptr<hoNDArray<floatd2> >(new hoNDArray<floatd2>(dims_1d));
		memcpy(traj->get_data_ptr(),tmp_traj->get_data_ptr(),tmp_traj->get_number_of_elements()*sizeof(float));

	}
	else{

		boost::shared_ptr< hoNDArray<float> > host_traj_dcw = extract_trajectory_from_queue( queue );

		std::vector<size_t> order;
		order.push_back(1); order.push_back(2); order.push_back(0);

		auto host_traj_dcw_shifted = permute( *host_traj_dcw, order );

		std::vector<size_t> dims_1d;
		dims_1d.push_back(host_traj_dcw_shifted.get_size(0)*host_traj_dcw_shifted.get_size(1));

		dcw = boost::shared_ptr<hoNDArray<float> > (new hoNDArray<float>(dims_1d, host_traj_dcw_shifted.get_data_ptr()+2*dims_1d[0]));

		std::vector<size_t> dims_2d = dims_1d; dims_2d.push_back(2);
		order.clear(); order.push_back(1); order.push_back(0);

		hoNDArray<float> tmp(dims_2d, host_traj_dcw_shifted.get_data_ptr());

		auto _traj = permute( tmp, order );

		traj = boost::shared_ptr<hoNDArray<floatd2> > (new hoNDArray<floatd2>(dims_1d, (floatd2*)_traj.get_data_ptr()));
	}

	std::vector<size_t >dims_2d;
	dims_2d.push_back(traj->get_number_of_elements());
	dims_2d.push_back(1); // Number of frames

	traj->reshape(&dims_2d);
	if( num_trajectory_dims_ == 3 ) dcw->reshape(&dims_2d);
}

boost::shared_ptr<cuNDArray<float_complext> > CMRTGadget::get_combined_frames(){
    if (frames.size() == 0)
            throw std::runtime_error("No frames received. This should not be possible. Your RAM might be replaced with live salmon, or you may have set the expected number of frames to 0");

    for (unsigned int i = 1; i < frames.size(); i++){
            if (!frames[0]->dimensions_equal(frames[i].get()))
                    throw std::runtime_error("CMRTGadget: Frames received do not have equal size");
    }
    //Get data dimensions. Assume all frames have the same dimensions
    std::vector<size_t> dims = *frames[0]->get_dimensions();
    dims.push_back(frames.size());

    boost::shared_ptr<cuNDArray<float_complext> > combined(new cuNDArray<float_complext>(dims));

    //Copy data into 1 array on device
    size_t offset = 0;
    for (unsigned int i = 0; i < frames.size(); i++){
            cudaMemcpy(combined->get_data_ptr()+offset,frames[i]->get_data_ptr(),frames[i]->get_number_of_elements()*sizeof(float_complext),cudaMemcpyHostToDevice);
            offset += frames[i]->get_number_of_elements();
    }

    frames.clear();
    return combined;
}

GADGET_FACTORY_DECLARE(CMRTGadget)
}

max_stars_repo_name: roopchansinghv/gadgetron


text:
/*
 *  Copyright (c) 2020 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *  Contact: Lukasz Pawelczyk <l.pawelczyk@samsung.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
 */

/**
 * @file    test_rsa.c
 * @author  Lukasz Pawelczyk <l.pawelczyk@samsung.com>
 * @brief   RSA API unit tests.
 */

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

#include <yaca_crypto.h>
#include <yaca_rsa.h>
#include <yaca_key.h>
#include <yaca_error.h>

#include "common.h"

BOOST_AUTO_TEST_SUITE(MOCK_TESTS_RSA)

BOOST_FIXTURE_TEST_CASE(T1401__mock__negative__private_encrypt, InitFixture)
{
	struct rsa_args {
		yaca_padding_e pad;
		yaca_key_bit_length_e bit_len;
		size_t shorter;
	};

	const std::vector<struct rsa_args> rargs = {
		{YACA_PADDING_NONE,         YACA_KEY_LENGTH_512BIT,   0},
		{YACA_PADDING_PKCS1,        YACA_KEY_LENGTH_512BIT,  11},
	};

	for (const auto &ra: rargs) {
		auto test_code = [&ra]()
			{
				int ret;
				yaca_key_h rsa_prv = YACA_KEY_NULL, rsa_pub = YACA_KEY_NULL;
				size_t input_len = ra.bit_len / 8 - ra.shorter;
				char *encrypted = NULL, *decrypted = NULL;
				size_t encrypted_len, decrypted_len;

				ret = yaca_key_generate(YACA_KEY_TYPE_RSA_PRIV, ra.bit_len, &rsa_prv);
				if (ret != YACA_ERROR_NONE) goto exit;
				ret = yaca_key_extract_public(rsa_prv, &rsa_pub);
				if (ret != YACA_ERROR_NONE) goto exit;

				ret = yaca_rsa_private_encrypt(ra.pad, rsa_prv, INPUT_DATA, input_len,
				                               &encrypted, &encrypted_len);
				if (ret != YACA_ERROR_NONE) goto exit;

				ret = yaca_rsa_public_decrypt(ra.pad, rsa_pub, encrypted, encrypted_len,
				                              &decrypted, &decrypted_len);
				if (ret != YACA_ERROR_NONE) goto exit;

			exit:
				yaca_key_destroy(rsa_prv);
				yaca_key_destroy(rsa_pub);
				yaca_free(encrypted);
				yaca_free(decrypted);
				return ret;
			};

		call_mock_test(test_code);
	}
}

BOOST_FIXTURE_TEST_CASE(T1402__mock__negative__public_encrypt, InitFixture)
{
	struct rsa_args {
		yaca_padding_e pad;
		yaca_key_bit_length_e bit_len;
		size_t shorter;
	};

	const std::vector<struct rsa_args> rargs = {
		{YACA_PADDING_NONE,         YACA_KEY_LENGTH_512BIT,   0},
		{YACA_PADDING_PKCS1,        YACA_KEY_LENGTH_1024BIT, 11},
		{YACA_PADDING_PKCS1_OAEP,   YACA_KEY_LENGTH_2048BIT, 42},
	};

	for (const auto &ra: rargs) {
		auto test_code = [&ra]()
			{
				int ret;
				yaca_key_h rsa_prv = YACA_KEY_NULL, rsa_pub = YACA_KEY_NULL;
				size_t input_len = ra.bit_len / 8 - ra.shorter;
				char *encrypted = NULL, *decrypted = NULL;
				size_t encrypted_len, decrypted_len;

				ret = yaca_key_generate(YACA_KEY_TYPE_RSA_PRIV, ra.bit_len, &rsa_prv);
				if (ret != YACA_ERROR_NONE) goto exit;
				ret = yaca_key_extract_public(rsa_prv, &rsa_pub);
				if (ret != YACA_ERROR_NONE) goto exit;

				ret = yaca_rsa_public_encrypt(ra.pad, rsa_pub, INPUT_DATA, input_len,
				                              &encrypted, &encrypted_len);
				if (ret != YACA_ERROR_NONE) goto exit;

				ret = yaca_rsa_private_decrypt(ra.pad, rsa_prv, encrypted, encrypted_len,
				                               &decrypted, &decrypted_len);
				if (ret != YACA_ERROR_NONE) goto exit;

			exit:
				yaca_key_destroy(rsa_prv);
				yaca_key_destroy(rsa_pub);
				yaca_free(encrypted);
				yaca_free(decrypted);
				return ret;
			};

		call_mock_test(test_code);
	}
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: cmanszew/yaca

max_issues_repo_name: cmanszew/yaca

max_forks_repo_name: cmanszew/yaca


text:
/*
 * File:   PERK.hpp
 * Author: Koncord <koncord at rwa.su>
 *
 * Created on 8 Апрель 2015 г., 18:35
 */

#ifndef PERK_HPP
#define	PERK_HPP

#include "../Record.hpp"
#include <boost/variant/variant.hpp>

class RecordPERK: public Record
{
public:

    struct DATA
    {
        std::string edid;
        std::string name;
        std::string description;

        struct Effect
        {
            #pragma pack(push, 1)
            struct Header
            {
                uint8_t type;
                uint8_t rank;
                uint8_t priority;
                enum Type
                {
                    QuestAndStage = 0,
                    Ability = 1,
                    EntryPoint = 2
                };
            } header;
            #pragma pack(pop)

            struct QuestAndStageData
            {
                formid quest;
                int8_t stage;
                int8_t unused[3];
            };

            struct EntryPointData
            {
                uint8_t entryPoint;
                uint8_t function;
                uint8_t perkConditionTabCount;
                enum EntryPointFlag
                {
                    CalculateWeaponDamage = 0,
                    CalculateMyCriticalHitChance,
                    CalculateMyCriticalHitDamage,
                    CalculateWeaponAttackAPCost,
                    CalculateMineExplodeChance,
                    AdjustRangePenalty,
                    AdjustLimbDamage,
                    CalculateWeaponRange,
                    CalculateToHitChance,
                    AdjustExperiencePoints,
                    AdjustGainedSkillPoints,
                    AdjustBookSkillPoints,
                    ModifyRecoveredHealth,
                    CalculateInventoryAPCost,
                    GetDisposition,
                    GetShouldAttack,
                    GetShouldAssist,
                    CalculateBuyPrice,
                    GetBadKarma,
                    GetGoodKarma,
                    IgnoreLockedTerminal,
                    AddLeveledListOnDeath,
                    GetMaxCarryWeight,
                    ModifyAddictionChance,
                    ModifyAddictionDuration,
                    ModifyPositiveChemDuration,
                    AdjustDrinkingRadiation,
                    Activate,
                    MysteriousStranger,
                    HasParalyzingPalm,
                    HackingScienceBonus,
                    IgnoreRunningDuringDetection,
                    IgnoreBrokenLock,
                    HasConcentratedFire,
                    CalculateGunSpread,
                    PlayerKillAPReward,
                    ModifyEnemyCriticalHitChance
                };
            };
            boost::variant<QuestAndStageData, formid, EntryPointData> data;

            struct PerkCondtitionCollection
            {
                int8_t runOn;
                std::vector<CTDA> conditions;
            } condtitionColl;

            uint8_t entryPointFunctionType;
            struct EPFD_2
            {
                float val0, val1;
            };
            struct EPFD_5
            {
                uint32_t actorValue;
                float value;
            };
            boost::variant<std::vector<uint8_t>, float, EPFD_2, formid, EPFD_5> entryPointFunctionData;
            std::string buttonLabel;
            uint16_t scriptFlags;
            enum ScriptFlag
            {
                RunImmediately = 0x0001
            };
            Script script;
        };
        std::vector<Effect> effects;

        #pragma pack(push, 1)
        std::vector<CTDA> conditions;
        struct _DATA
        {
          uint8_t trait; // bool
          int8_t minLevel;
          int8_t ranks;
          uint8_t playable; // bool
          uint8_t hidden;  // bool
        } data;
        #pragma pack(pop)
    } data;

    explicit RecordPERK(const RecHeader &head) : Record(head) { Parse(); }

    RecordPERK() : Record() { Parse(); }
    virtual bool DoParse();
};

#endif	/* PERK_HPP */

max_stars_repo_name: Koncord/ESx-Reader

max_issues_repo_name: Koncord/ESx-Reader

max_forks_repo_name: Koncord/ESx-Reader


text:
#include "byte_counter.hxx"

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <vector>

void output_escaped_string(std::ostream &os, const std::string &s)
{
  for(auto &c : s)
    {
      if(c == '"')
        {
          os << "\\\"\\";
        }
      else
        {
          os << c;
        }
    }
}

size_t write_control(const boost::filesystem::path &output_dir,
                     const size_t &num_blocks,
                     const std::vector<std::string> &command_arguments)
{
  const boost::filesystem::path output_path(output_dir / ("control.json"));

  byte_counter counter;
  {
    boost::iostreams::filtering_ostream output_stream;
    output_stream.push(boost::ref(counter));
    // Use gzip with no compression to get a CRC
    output_stream.push(
      boost::iostreams::gzip_compressor(boost::iostreams::gzip_params(0)));
    output_stream.push(boost::iostreams::file_sink(output_path.string()));
    output_stream << "{\n  \"num_blocks\": " << num_blocks
                  << ",\n  \"command\": \"";
    for(auto argument(command_arguments.begin());
        argument != command_arguments.end(); ++argument)
      {
        if(argument != command_arguments.begin())
          {
            output_stream << " ";
          }
        output_escaped_string(output_stream, *argument);
      }
    output_stream << "\"\n}\n";
    if(!output_stream.good())
      {
        throw std::runtime_error("Error when writing to: "
                                 + output_path.string());
      }
  }
  return counter.num_bytes;
}

ext: cxx

max_stars_repo_name: ChrisPattison/sdpb

max_issues_repo_name: ChrisPattison/sdpb

max_forks_repo_name: ChrisPattison/sdpb


text:
/**
 ** Isaac Genome Alignment Software
 ** Copyright (c) 2010-2017 Illumina, Inc.
 ** All rights reserved.
 **
 ** This software is provided under the terms and conditions of the
 ** GNU GENERAL PUBLIC LICENSE Version 3
 **
 ** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3
 ** along with this program. If not, see
 ** <https://github.com/illumina/licenses/>.
 **
 ** \file IndelLoader.hh
 **
 ** Loads indels from a vcf file.
 **
 ** \author Roman Petrovski
 **/

#ifndef iSAAC_BUILD_INDEL_LOADER_HH
#define iSAAC_BUILD_INDEL_LOADER_HH

#include <boost/filesystem.hpp>

#include "build/gapRealigner/RealignerGaps.hh"
#include "reference/SortedReferenceMetadata.hh"

namespace isaac
{
namespace build
{

build::gapRealigner::Gaps loadIndels(
    const boost::filesystem::path &vcfFilePath,
    const reference::SortedReferenceMetadataList &sortedReferenceMetadataList);

} // namespace build
} // namespace isaac

#endif // #ifndef iSAAC_BUILD_INDEL_LOADER_HH

ext: hh


text:
// [===========================================================================]
// [                                M o n e t a                                ]
// [---------------------------------------------------------------------------]
// [                                                                           ]
// [                          Copyright (C) 2005-2015                          ]
// [                      Rodrigo Madera <madera@acm.org>                      ]
// [                                                                           ]
// [---------------------------------------------------------------------------]
// [         Distributed under the Boost Software License, Version 1.0         ]
// [ Read accompanying LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt ]
// [===========================================================================]

#pragma once
#include "detail/generate_params.hxx"
#include "../../traits/pk_member_names.hxx"
#include "../traits/table_name.hxx"
#include "../traits/field_names.hxx"
#include <boost/algorithm/string/join.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <sstream>

namespace moneta { namespace sql { namespace generators {

	template <class Entity>
	const std::string insert_into_table() {
		const std::vector<std::string> fields = traits::get_field_names<Entity>();

		std::ostringstream oss;
		oss << "INSERT INTO " << traits::get_table_name<Entity>() << " (\n"
		    << '\t' << boost::join(fields, ", ") << '\n'
		    << ") VALUES (\n"
		    << '\t' << detail::generate_parameters<Entity>() << '\n'
		    << ")";
		return oss.str();
	}

}}}

max_stars_repo_name: madera/Moneta

max_issues_repo_name: madera/Moneta

max_forks_repo_name: madera/Moneta


text:
#pragma once

#include <cstdint>

#include "bfloat.hpp"

#ifdef PLATE

#else

  #include "hfloat.hpp"
  #include "128.hpp"

#endif

#ifdef MULTIPRECISION

  #include <boost/multiprecision/cpp_bin_float.hpp>

#endif

namespace plate {

#ifdef PLATE

  using uint8      = std::uint8_t;
  using uint16     = std::uint16_t;
  using uint32     = std::uint32_t;
  using uint64     = std::uint64_t;

  using uintfast8  = std::uint_fast8_t;
  using uintfast16 = std::uint_fast16_t;
  using uintfast32 = std::uint_fast32_t;
  using uintfast64 = std::uint_fast64_t;

  using int8       = std::int8_t;
  using int16      = std::int16_t;
  using int32      = std::int32_t;
  using int64      = std::int64_t;

  using intfast8   = std::int_fast8_t;
  using intfast16  = std::int_fast16_t;
  using intfast32  = std::int_fast32_t;
  using intfast64  = std::int_fast64_t;

  using float32    = float;
  using float64    = double;

  using bfloat16   = plate::bfloat;

  #ifdef MULTIPRECISION
  using uint128    = boost::multiprecision::uint128_t;
  using uint256    = boost::multiprecision::uint256_t;
  using int128     = boost::multiprecision::int128_t;
  using int256     = boost::multiprecision::int256_t;
  using float128   = boost::multiprecision::cpp_bin_float_quad;
  using float256   = boost::multiprecision::cpp_bin_float_oct;
  #endif

  using uints      = std::size_t;
  using ints       = std::make_signed<uints>::type;

#else

  using uint8      = std::uint8_t;
  using uint16     = std::uint16_t;
  using uint32     = std::uint32_t;
  using uint64     = std::uint64_t;
  using uint128    = unsigned __int128;

  using uintfast8  = std::uint_fast8_t;
  using uintfast16 = std::uint_fast16_t;
  using uintfast32 = std::uint_fast32_t;
  using uintfast64 = std::uint_fast64_t;

  using int8       = std::int8_t;
  using int16      = std::int16_t;
  using int32      = std::int32_t;
  using int64      = std::int64_t;
  using int128     = __int128;

  using intfast8   = std::int_fast8_t;
  using intfast16  = std::int_fast16_t;
  using intfast32  = std::int_fast32_t;
  using intfast64  = std::int_fast64_t;

  using float16    = plate::hfloat;
  using float32    = float;
  using float64    = double;
  using float128   = __float128;

  using bfloat16   = plate::bfloat;

  using uints      = std::size_t;
  using ints       = std::make_signed<uints>::type;

  #ifdef MULTIPRECISION
  using uint256  = boost::multiprecision::uint256_t;
  using int256   = boost::multiprecision::int256_t;
  using float256 = boost::multiprecision::cpp_bin_float_oct;
  #endif

#endif

template<class T>
constexpr std::string_view number_type_string() noexcept
{
  if constexpr(std::is_same_v<T, uint8>)    return "uint8";
  if constexpr(std::is_same_v<T, uint16>)   return "uint16";
  if constexpr(std::is_same_v<T, uint32>)   return "uint32";
  if constexpr(std::is_same_v<T, uint64>)   return "uint64";

  if constexpr(std::is_same_v<T, int8>)     return "int8";
  if constexpr(std::is_same_v<T, int16>)    return "int16";
  if constexpr(std::is_same_v<T, int32>)    return "int32";
  if constexpr(std::is_same_v<T, int64>)    return "int64";

  if constexpr(std::is_same_v<T, float32>)  return "float32";
  if constexpr(std::is_same_v<T, float64>)  return "float64";

  #ifndef PLATE
  if constexpr(std::is_same_v<T, bfloat16>) return "bfloat16";
  if constexpr(std::is_same_v<T, float16>)  return "float16";
  if constexpr(std::is_same_v<T, uint128>)  return "uint128";
  if constexpr(std::is_same_v<T, int128>)   return "int128";
  if constexpr(std::is_same_v<T, float128>) return "float128";
  #endif

  #ifdef MULTIPRECISION
  #ifdef PLATE
  if constexpr(std::is_same_v<T, uint128>)  return "uint128";
  if constexpr(std::is_same_v<T, int128>)   return "int128";
  if constexpr(std::is_same_v<T, float128>) return "float128";
  #endif
  if constexpr(std::is_same_v<T, uint256>)  return "uint256";
  if constexpr(std::is_same_v<T, int256>)   return "int256";
  if constexpr(std::is_same_v<T, float256>) return "float256";
  #endif

  return "unknown";
}

}; // namespace plate

max_stars_repo_name: DisQS/AniMolViewer

max_issues_repo_name: DisQS/AniMolViewer

max_forks_repo_name: DisQS/animol-viewer


text:
// Boost.Geometry Index
//
// Copyright (c) 2011-2015 Adam Wulkiewicz, Lodz, Poland.
//
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_INDEX_DETAIL_IS_BOUNDING_GEOMETRY_HPP
#define BOOST_GEOMETRY_INDEX_DETAIL_IS_BOUNDING_GEOMETRY_HPP

#include <boost/geometry/core/tag.hpp>
#include <boost/geometry/core/tags.hpp>

namespace boost { namespace geometry { namespace index { namespace detail {

template
<
    typename Geometry,
    typename Tag = typename geometry::tag<Geometry>::type
>
struct is_bounding_geometry
{
    static const bool value = false;
};

template <typename Box>
struct is_bounding_geometry<Box, box_tag>
{
    static const bool value = true;
};

}}}} // namespave boost::geometry::index::detail

#endif // BOOST_GEOMETRY_INDEX_DETAIL_IS_BOUNDING_GEOMETRY_HPP


text:
#pragma once

#include <boost/endian/conversion.hpp>

namespace lsl {

using lslboost::endian::endian_reverse_inplace;
using byteorder = lslboost::endian::order;

enum Endianness {
	LSL_PORTABLE_ENDIAN = 0,
	LSL_LITTLE_ENDIAN_BUT_BIG_FLOAT = 1,
	LSL_BIG_ENDIAN_BUT_LITTLE_FLOAT = 2,
	LSL_LITTLE_ENDIAN = 1234,
	LSL_BIG_ENDIAN = 4321,
	LSL_PDP11 = 2134 // deprecated, not used nowadays
};

/// the host native byte order
const Endianness LSL_BYTE_ORDER =
	(byteorder::native == byteorder::little) ? LSL_LITTLE_ENDIAN : LSL_BIG_ENDIAN;

inline bool can_convert_endian(Endianness requested, int value_size) {
	if(value_size == 1) return true;
	if (requested != LSL_LITTLE_ENDIAN && requested != LSL_BIG_ENDIAN)
		return false;
	if (LSL_BYTE_ORDER != LSL_LITTLE_ENDIAN && LSL_BYTE_ORDER != LSL_BIG_ENDIAN)
		return false;
	return true;
}
inline bool can_convert_endian(int requested, int value_size) {
	return can_convert_endian(static_cast<Endianness>(requested), value_size);
}

/// Measure the endian conversion performance of this machine.
double measure_endian_performance();

// Determine target byte order / endianness
using byteorder = lslboost::endian::order;
static_assert(byteorder::native == byteorder::little || byteorder::native == byteorder::big,
	"Unsupported byteorder");

} // namespace lsl

max_stars_repo_name: mvidaldp/liblsl-android-builder

max_issues_repo_name: mvidaldp/liblsl-android-builder

max_forks_repo_name: mvidaldp/liblsl-android-builder


text:
////////////////////////////////////////////////////////////////////////////////
//  Copyright (c) 2011 Bryce Lelbach
//
//  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 <pthread.h>

#include <boost/detail/lightweight_test.hpp>

// Based on the example in pthread_setaffinity(3).

int main()
{
    int s;
    cpu_set_t cpuset;
    pthread_t thread;

    thread = pthread_self();

    // Set affinity mask to include CPUs 0 to 7 (if available - otherwise, uses
    // 0 to N where n is the number of cores on the machine.
    CPU_ZERO(&cpuset);
    for (int j = 0; j < 8; ++j)
        CPU_SET(j, &cpuset);

    BOOST_TEST_EQ(pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset), 0);

    // Check the actual affinity mask assigned to the thread.
    BOOST_TEST_EQ(pthread_getaffinity_np(thread, sizeof(cpu_set_t), &cpuset), 0);

    std::cout << "set returned by pthread_getaffinity_np() contained:\n";
    for (int j = 0; j < CPU_SETSIZE; ++j)
        if (CPU_ISSET(j, &cpuset))
            std::cout << "CPU" << j << "\n";

    return boost::report_errors();
}

max_stars_repo_name: akemp/hpx

max_issues_repo_name: akemp/hpx

max_forks_repo_name: akemp/hpx


text:
/**
 * @file
 * @brief Shows how the classes in the namespace lf::io can be used.
 * @author Raffael Casagrande
 * @date   2018-09-02 02:44:15
 * @copyright MIT License
 */

#include <lf/io/io.h>
#include <lf/mesh/hybrid2d/hybrid2d.h>
#include <lf/mesh/utils/utils.h>
#include <boost/filesystem.hpp>
#include "lf/mesh/utils/lambda_mesh_data_set.h"

int main() {
  // Find path to the smiley mesh
  boost::filesystem::path here = __FILE__;
  auto smiley_path = here.parent_path() / "smiley.msh";

  // load the smiley mesh
  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);
  lf::io::GmshReader reader(std::move(mesh_factory), smiley_path.string());

  // print all physical entities:
  std::cout << "Physical Entities in Gmsh File " << std::endl;
  std::cout
      << "---------------------------------------------------------------\n";
  for (lf::base::dim_t codim = 0; codim <= 2; ++codim) {
    for (auto& pair : reader.PhysicalEntities(codim)) {
      std::cout << "codim = " << static_cast<int>(codim) << ": " << pair.first
                << " <=> " << pair.second << std::endl;
    }
  }
  std::cout << std::endl << std::endl;

  // count the number of elements in the eyes:
  int num_eye_elements = 0;
  auto mesh = reader.mesh();
  auto physical_entity_nr_eyes = reader.PhysicalEntityName2Nr("eyes");
  for (auto e : mesh->Entities(0)) {
    if (reader.IsPhysicalEntity(*e, physical_entity_nr_eyes)) {
      ++num_eye_elements;
    }
  }
  std::cout << "Number of eye elements : " << num_eye_elements << std::endl;

  // count the number of edges that form the mouth
  int num_mouth_edges = 0;
  auto physical_entity_nr_mouth = reader.PhysicalEntityName2Nr("mouth");
  for (auto e : mesh->Entities(1)) {
    if (reader.IsPhysicalEntity(*e, physical_entity_nr_mouth)) {
      ++num_mouth_edges;
    }
  }
  std::cout << "Number of mouth edges : " << num_mouth_edges << std::endl;

  // count the total number of elements in the face (including eyes)
  int num_face_elements = 0;
  auto physical_entity_nr_face = reader.PhysicalEntityName2Nr("face");
  for (auto e : mesh->Entities(0)) {
    if (reader.IsPhysicalEntity(*e, physical_entity_nr_face)) {
      ++num_face_elements;
    }
  }
  std::cout << "Number of face elements : " << num_face_elements << std::endl;

  // Start vtk output:
  lf::io::VtkWriter vtk_writer(mesh, "smiley.vtk");

  // write a cell-based function that takes the value 1 on the eyes and 0
  // everywhere else
  vtk_writer.WriteCellData(
      "eyes", *lf::mesh::utils::make_LambdaMeshDataSet([&](const auto& e) {
        return static_cast<int>(
            reader.IsPhysicalEntity(e, physical_entity_nr_eyes));
      }));

  // write nodal data that takes the value 2 on the eyes and 1 on the mouth,
  // zero everywhere else.
  auto mds = lf::mesh::utils::make_CodimMeshDataSet<int>(mesh, 2, 0);
  // mark the eyes
  for (auto e : mesh->Entities(0)) {
    if (reader.IsPhysicalEntity(*e, physical_entity_nr_eyes)) {
      for (auto node : e->SubEntities(2)) {
        mds->operator()(*node) = 2;
      }
    }
  }
  // mark the mouth
  for (auto e : mesh->Entities(1)) {
    if (reader.IsPhysicalEntity(*e, physical_entity_nr_mouth)) {
      for (auto node : e->SubEntities(1)) {
        mds->operator()(*node) = 1;
      }
    }
  }
  vtk_writer.WritePointData("smile", *mds);

  // write a node based, vector valued function that points to the nose:
  auto origin = Eigen::MatrixXd::Zero(0, 1);
  vtk_writer.WritePointData(
      "nose_vec", *lf::mesh::utils::make_LambdaMeshDataSet([&](const auto& n) {
        return Eigen::Vector2d(-n.Geometry()->Global(origin));
      }));
}

max_stars_repo_name: isschoch/lehrfempp

max_issues_repo_name: isschoch/lehrfempp

max_forks_repo_name: isschoch/lehrfempp


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

#include "theia/io/write_colmap_files.h"

#include <Eigen/Core>
#include <Eigen/Geometry>
#include <fstream>  // NOLINT
#include <glog/logging.h>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>

#include "theia/sfm/camera/camera.h"
#include "theia/sfm/camera/camera_intrinsics_model.h"
#include "theia/sfm/camera/pinhole_camera_model.h"
#include "theia/sfm/camera_intrinsics_prior.h"
#include "theia/sfm/reconstruction.h"
#include "theia/sfm/reconstruction_estimator_utils.h"
#include "theia/sfm/track.h"
#include "theia/sfm/types.h"
#include "theia/sfm/view.h"
#include "theia/util/map_util.h"

namespace theia {
namespace {

bool WriteCamerasFile(const Reconstruction& reconstruction,
                      const std::string& cameras_file) {
  std::ofstream ofs_cameras(cameras_file);
  if (!ofs_cameras.is_open()) {
    LOG(ERROR) << "Cannot open the file: " << cameras_file << " for writing.";
    return false;
  }

  const auto& group_ids = reconstruction.CameraIntrinsicsGroupIds();

  for (auto group_id : group_ids) {
    const View* view = reconstruction.View(
        *reconstruction.GetViewsInCameraIntrinsicGroup(group_id).begin());
    const Camera& camera = view->Camera();
    if (camera.GetCameraIntrinsicsModelType() !=
        CameraIntrinsicsModelType::PINHOLE) {
      LOG(ERROR) << "Could not add camera " << view->Name()
                 << " to the COLMAP output file because COLMAP doesn't support "
                    "FOV or fisheye cameras.";
      return false;
    }

    const CameraIntrinsicsModel& intrinsics = *camera.CameraIntrinsics();
    ofs_cameras
        << group_id << " RADIAL " << camera.ImageWidth() << " "
        << camera.ImageHeight() << " " << camera.FocalLength() << " "
        << camera.PrincipalPointX() << " " << camera.PrincipalPointY() << " "
        << intrinsics.GetParameter(PinholeCameraModel::RADIAL_DISTORTION_1)
        << " "
        << intrinsics.GetParameter(PinholeCameraModel::RADIAL_DISTORTION_1)
        << std::endl;
  }
  ofs_cameras.close();

  return true;
}

bool WriteImagesFile(const Reconstruction& reconstruction,
                     const std::string& images_file) {
  std::ofstream ofs_images(images_file);

  if (!ofs_images.is_open()) {
    LOG(ERROR) << "Cannot open the file: " << images_file << " for writing.";
    return false;
  }

  for (auto view_id : reconstruction.ViewIds()) {
    const View* view = reconstruction.View(view_id);
    const Camera& camera = view->Camera();
    const Eigen::Vector3d translation =
        -camera.GetOrientationAsRotationMatrix() * camera.GetPosition();
    const Eigen::Quaterniond orientation(
        camera.GetOrientationAsRotationMatrix());
    ofs_images << view_id << " " << orientation.w() << " " << orientation.x()
               << " " << orientation.y() << " " << orientation.z() << " "
               << translation.x() << " " << translation.y() << " "
               << translation.z() << " "
               << reconstruction.CameraIntrinsicsGroupIdFromViewId(view_id)
               << " " << view->Name() << std::endl;
    const auto& track_ids = view->TrackIds();
    for (auto track_id : track_ids) {
      auto feature = view->GetFeature(track_id);
      ofs_images << feature->point_.x() << " " << feature->point_.y() << " "
                 << track_id << " ";
    }
    ofs_images << std::endl;
  }
  ofs_images.close();
  return true;
}

bool WritePointsFile(const Reconstruction& reconstruction,
                     const std::string& points_file) {
  std::ofstream ofs_points(points_file);
  if (!ofs_points.is_open()) {
    LOG(ERROR) << "Cannot open the file: " << points_file << " for writing.";
    return false;
  }

  for (auto track_id : reconstruction.TrackIds()) {
    const Track* track = reconstruction.Track(track_id);
    const Eigen::Vector3d point = track->Point().hnormalized();
    const auto& color = track->Color();
    ofs_points << track_id << " " << point.x() << " " << point.y() << " "
               << point.z() << " " << static_cast<int>(color[0]) << " "
               << static_cast<int>(color[1]) << " "
               << static_cast<int>(color[2]) << " " << 0.0 << " ";
    for (auto view_id : track->ViewIds()) {
      const View* view = reconstruction.View(view_id);
      const auto& track_ids = view->TrackIds();
      const int point_index =
          std::find(track_ids.begin(), track_ids.end(), track_id) -
          track_ids.begin();
      ofs_points << view_id << " " << point_index << " ";
    }
    ofs_points << std::endl;
  }

  ofs_points.close();
  return true;
}

}  // namespace

bool WriteColmapFiles(const Reconstruction& reconstruction,
                      const std::string& output_directory) {
  Reconstruction estimated_reconstruction;
  CreateEstimatedSubreconstruction(reconstruction, &estimated_reconstruction);

  const std::string& cameras_file = output_directory + "/cameras.txt";
  const std::string& images_file = output_directory + "/images.txt";
  const std::string& points_file = output_directory + "/points3D.txt";

  if (!WriteCamerasFile(estimated_reconstruction, cameras_file)) {
    return false;
  }
  if (!WriteImagesFile(estimated_reconstruction, images_file)) {
    return false;
  }
  if (!WritePointsFile(estimated_reconstruction, points_file)) {
    return false;
  }
  return true;
}

}  // namespace theia

max_stars_repo_name: urbste/TheiaSfM

max_issues_repo_name: urbste/TheiaSfM

max_forks_repo_name: urbste/TheiaSfM