text:
#include "qlearner/qlearner.hpp"
#include "qlearner/stats.h"
#include "qlearner/action.h"
#include <iostream>
#include <fstream>
#include <thread>
#include <mutex>
#include <atomic>
#include <chrono>
#include <vector>
#include <boost/lexical_cast.hpp>
#include <limits.h>

#include "config.h"
#include "net/fc_layer.hpp"
#include "net/relu_layer.hpp"
#include "net/tanh_layer.hpp"
#include "net/solver.hpp"
#include "net/rmsprop.hpp"
#include "net/network.hpp"

#include "dt.h"

#include "pole.h"

#include "uct-agent.h"

#include <random>

using namespace net;
using namespace qlearn;

const float BAT_SIZE = 0.05;

typedef boost::tuples::tuple<double, double, double, double> polestate;

Vector dconv(float val, float min, float max, int steps, Vector result)
{
	float p = (val - min) / (max - min);
	int rp = std::min(steps-1, std::max(0, int(steps * p)));
	result = Matrix::Zero(steps, 1);
	result[rp] = 1;
	return std::move(result);
}

struct PongGame
{
	float ballx;
	float bally;
	float bvx;
	float bvy;
	float posy;

	PongGame()
	{

	}

	void reset()
	{
		ballx = 0.6;
		bally = (rand() % 101) / 100.f;
		bvx = 1;
		bvy = (rand() % 101 - 50) / 20.f;
		posy = (rand() % 101) / 100.f;
	}

	float step( int ac )
	{
		ballx += 0.01*bvx;
		bally += 0.01*bvy;

		if( ac == 1 )
			posy += 0.025;
		else if(ac == 2)
			posy -= 0.025;

		if(bally > 1)
		{
			bally = 2 - bally;
			bvy *= -1;
		}

		if(bally < 0)
		{
			bally = -bally;
			bvy *= -1;
		}

		if( ballx > 1.0 )
		{
			if( std::abs(bally - posy) < BAT_SIZE )
				return 1;
			else
				return -1;
		}

		return 0;
	}

	const Vector& data() const
	{
		vec.resize (5);
		vec[0] = ballx;
		vec[1] = bally;
		vec[2] = posy;
		vec[3] = bvx;
		vec[4] = bvy;
		/*vec.resize(30);
		auto d1 = dconv(bally, 0, 1, 15, std::move(dccache1));
		auto d2 = dconv(posy, 0, 1, 15, std::move(dccache2));
		vec << d1, d2;
		dccache1 = std::move(d1);
		dccache2 = std::move(d2);*/
		return vec;
	}

private:
	mutable Vector vec;
	mutable Vector dccache1;
	mutable Vector dccache2;
};

Vector vec;

// Encode game state using vector
const Vector& data(boost::tuples::tuple<double, double, double, double> cpst)
{
	vec.resize (4);
	vec[0] = cpst.get<0>();
	vec[1] = cpst.get<1>();
	vec[2] = cpst.get<2>();
	vec[3] = cpst.get<3>();
	return vec;
}

void display(boost::tuples::tuple<double, double, double, double> cpst)
{
	std::cout << cpst.get<0>() << "," << cpst.get<1>() << ","
		<< cpst.get<2>() << "," << cpst.get<3>() << "\n";
}

void display(boost::tuples::tuple<double, double, double, double> cpst, int ac)
{
	std::cout << cpst.get<0>() << "," << cpst.get<1>() << ","
		<< cpst.get<2>() << "," << cpst.get<3>() << " : " << ac << "\n";
}

void render(std::fstream& out, boost::tuples::tuple<double, double, double, double> cpst, int ac)
{
	out << cpst.get<0>() << "," << cpst.get<1>() << ","
		<< cpst.get<2>() << "," << cpst.get<3>() << ",";

	if (ac == 0)
		out << "Left\n";
	else if (ac == 2)
		out << "Right\n";
	else
		out << "Stay\n";
}

void build_image(const qlearn::QLearner& l);

std::mutex mTargetNet;
std::atomic<bool> evaluate(false);
std::atomic<bool> run(true);

void learn_thread( Network& target_net, ComputationGraph& graph )
{
	Config config(4, 3, 2000000);
	config.epsilon_steps(2000000).update_interval(10000).batch_size(32).init_memory_size(10000).init_epsilon_time(100000)
		.discount_factor(0.98);

	Network network;
	network << FcLayer(Matrix::Random(10, 4).array() / 5);
	network << ReLULayer(Matrix::Zero(10, 1));
	network << FcLayer(Matrix::Random(10, 10).array() / 5);
	network << ReLULayer(Matrix::Zero(10, 1));
	network << FcLayer(Matrix::Random(3, 10).array() / 5);
	//network << TanhLayer(Matrix::Zero(3, 1));

	qlearn::QLearner learner( config, std::move(network) );

	auto prop = std::unique_ptr<RMSProp>(new RMSProp(0.9, 0.0005, 0.001));
	RMSProp* rmsprop = prop.get();
	Solver solver( std::move(prop) );

	std::fstream rewf("reward.txt", std::fstream::out);

	Pole game;
	game.reset ();
	game.perturbation ();

	int ac = 1;
	int games = 0;
	auto last_time = std::chrono::high_resolution_clock::now();
//	bool run = true;

	learner.setCallback( [&](const QLearner& learner, const Stats& stats )
	{
		std::cout << games << ": " << learner.getCurrentEpsilon() << "\n";
		std::cout << stats.getSmoothReward() << " (" <<  stats.getSmoothQVal() << ", " << stats.getSmoothMSE() << ")\n";
		rewf << stats.getSmoothReward() << "\t" <<  stats.getSmoothQVal() << "\t" << stats.getSmoothMSE() << " " << learner.getCurrentEpsilon()  << "\n";
		rewf.flush();
//		std::cout << learner.getNumberLearningSteps() << "\n";
		build_image(learner);
		std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(
					std::chrono::high_resolution_clock::now() - last_time).count() << " ms\n";
		last_time = std::chrono::high_resolution_clock::now();
//		std::cout << Eigen::internal::malloc_counter() << "\n";
		std::cout << " - - - - - - - - - - \n";
		std::lock_guard<std::mutex> lck(mTargetNet);
		target_net = learner.network().clone();
		graph = ComputationGraph(target_net);
		evaluate = true;
	} );

	while(run)
	{
		/*if(games < 1000)
		{
			rmsprop->setRate(0.001);
		} else if ( games < 5000 )
		{
			rmsprop->setRate(0.005);
		} else
		{
			rmsprop->setRate(0.0001);
		}*/

		game.step(ac-1);
		float r = 0;
		bool failed = game.fail();
		if (failed) r = -1;

		ac = learner.learn_step( data (game.getState()), r, failed, solver );
		if( failed )
		{
			game.reset();
			game.perturbation ();
			games++;
		}
	}
}

extern int status;
void agentPlay (std::string filename);
void networkToJson (std::string filename);
void abstraction_check (std::string filename);
void cegis_train();
int main(int argc, char** argv)
{
	// Network network;
	// network << FcLayer(Matrix::Random(10, 4).array() / 5);
	// network << ReLULayer(Matrix::Zero(10, 1));
	// network << FcLayer(Matrix::Random(10, 10).array() / 5);
	// network << ReLULayer(Matrix::Zero(10, 1));
	// network << FcLayer(Matrix::Random(3, 10).array() / 5);

	// ComputationGraph graph(network);

	// Vector vec;
	// vec.resize(4);
	// vec[0] = -0.469213;
	// vec[1] = -0.0971917;
	// vec[2] = -0.00305836;
	// vec[3] = 0.0654995;

	// auto prop = std::unique_ptr<RMSProp>(new RMSProp(0.9, 0.0005, 0.001));
	// RMSProp* rmsprop = prop.get();
	// Solver solver( std::move(prop) );
	// int error;
	// do {
	// 	error = 0;
	// 	const auto& result = graph.forward(vec);
	// 	int row, col;
	// 	result.maxCoeff(&row,&col);
	// 	error += (row == 2? 0 : 1);
	// 	std::cout << "Its original behavior on this is: " << row  << "\n";
	// 	for (int k = 0; k < result.size(); k ++)
	// 		std::cout << result[k] << " ";
	// 	std::cout << "\n";
	// 	Vector errorCache = Vector::Zero( result.size() );

	// 	//float delta = result[i->second] - target_value;
	// 	//errorCache[i->second] = delta;
	// 	for (int k = 0; k < result.size(); k++) {
	// 		if (k == 2)
	// 			errorCache[k] = result[k] - 1.0;
	// 		else
	// 			errorCache[k] = result[k] - (-1.0);
	// 	}

	// 	graph.backpropagate(errorCache, solver);
	// 	network.update(solver);
	// } while (error > 0);

	if (argc > 1) {
		std::string param(argv[1]);

		if (param.compare ("uct") == 0) {
			UCTPoleSimulator* sim = new UCTPoleSimulator ();
		    UCTPoleSimulator* sim2 = new UCTPoleSimulator ();
		    UCT::UCTPlanner uct (sim2, -1, 1000, 1, 0.95);
		    int numGames = 1;

		    for (int i = 0; i < numGames; ++i) {
		        int steps = 0;
		        double r = 0;
		        sim->getState()->print(); cout << endl;
		        while (! sim->isTerminal()) {
		            steps++; //std::cout << "step : " << steps << "\n";
		            uct.setRootNode(sim->getState(), sim->getActions(), r, sim->isTerminal());
		            uct.plan();
		            UCT::SimAction* action = uct.getAction();

					uct.testTreeStructure();

		            r = sim->act(action);
		            sim->getState()->print(); cout << endl;
		        }
		        sim->reset();
		        cout << "Game:" << i << "  steps: " << steps << "  r: " << r << endl;
			}
		}
		else if (param.compare ("cegis") == 0) {
			cegis_train();
		}
		else {
			//Network agent;
			//agent.load (agentfile);
			//ComputationGraph graph(agent);

			//vec.resize (4);
			//vec[0] = -0.189315;
			//vec[1] = -0.00291353;
			//vec[2] = 0.00289438;
			//vec[3] = 0.00875231;

			//auto ac = getAction(graph, vec);
			//std::cout << "decision : " << ac.id-1 << "\n";

			//agentPlay (param);
			//networkToJson(agentfile);

			// -- doing abstraction refinement --
			abstraction_check (param);
		}
		return 0;
	}

	Network network;
	ComputationGraph graph(network);
	std::thread learner( learn_thread, std::ref(network), std::ref(graph));
	learner.detach();

	int games = 0;

	std::fstream evl("test.txt", std::fstream::out);

	int step = 0;
	while(true)
	{
		if(evaluate)
		{
			Network copy = network.clone();
			ComputationGraph graph(copy);
			float reward = 0;
			int ts = 0;
			for(int g = 0; g < 200; ++g)
			{
				Pole game;
				game.reset();
				game.perturbation();
				for(int s = 0; s < 200; ++s)
				{
					auto ac = getAction(graph, data(game.getState()));
					game.step(ac.id-1);
					float currReward = 0;
					bool failed = game.fail();
					if (failed) currReward = -1;
					reward += currReward;
					ts ++;
					if( failed ) break;
				}
			}
			std::cout << (ts / 200.0) << "\n";
			if (ts / 200.0 == 200.0) {
				copy.save ("agent" + std::to_string(step) + ".network");
			}
			evl << reward << "\n";
			evl.flush();
			evaluate = false;
			step ++;
			sleep (10);
		}
	}
	run = false;
	return 0;
}

void build_image(const QLearner& l)
{

}

//===================  Test and Verification of learned neural model ===================
// Collect samples for each class.
void agentSample (ComputationGraph& graph, int acts, std::vector<std::pair<polestate,int>>& keyset) {
	Pole game;
	game.reset();
	game.perturbation();
	int s = 0;
	int th = 0;
	int c = 0;
	while (1) {
		polestate st = game.getState();
		auto ac = getAction(graph, data(st));
		if (ac.id == th) {
			keyset.push_back(std::make_pair (st, ac.id));
			th++;
			c++;
		}
		game.step(ac.id-1);
		if (c == acts) break;
		bool failed = game.fail();
		s++;
		if( failed ) break;
	}
}

// test a learn model in file.
void agentPlay (std::string filename) {
	Network agent;
	agent.load (filename);
	ComputationGraph graph(agent);
	float reward = 0;
	int ts = 0;

	std::fstream evl("c5.data", std::fstream::out);

	for(int g = 0; g < 100; ++g)
	{
		Pole game;
		game.reset();
		game.perturbation();
		display(game.getState());
		int s = 0;
		while(true)
		{
			auto ac = getAction(graph, data(game.getState()));
			//std::cout << s << ": "; display (game.getState(), ac.id-1);
			game.step(ac.id-1);
			render (evl, game.getState(), ac.id);
			evl.flush ();
			float currReward = 0;
			bool failed = game.fail();
			if (failed) currReward = -1;
			reward += currReward;
			ts ++;
			s ++;
			if( failed ) {
				std::cout << "Maintained in " << s << " steps\n";
				break;
			}
		}
	}
	evl.close();
	std::cout << (ts / 100.0) << "\n";
}

bool agentPlay (Pole& game, ComputationGraph& graph, int bound) {
	int s = 0;
	while (s < bound) {
		auto ac = getAction(graph, data(game.getState()));
		game.step(ac.id-1);
		bool failed = game.fail();
		s++;
		if( failed ) break;
	}
	//std::cout << "agent played " << s << " step\n";
	return (s == bound);
}

// export a learned model
void networkToJson (std::string filename) {
	Network agent;
	agent.load (filename);
	agent.saveJson (filename + ".json");
}

// UCT advisor
int uct_advise (polestate st, bool terminal, ComputationGraph& graph) {
    UCTPoleSimulator* sim2 = new UCTPoleSimulator (&graph);
    UCT::UCTPlanner uct (sim2, -1, 1000, 1, 0.95);

    UCTPoleState* current = new UCTPoleState (st);
    uct.setRootNode (current, sim2->getActions(), 0, terminal);
    uct.plan();
    UCT::SimAction* action = uct.getAction();
    const UCTPoleAction* act = dynamic_cast<const UCTPoleAction*> (action);
    return (act->id)+1;
}

// Train NN with key points
bool key_gen (Pole& game, ComputationGraph& graph, int bound, std::vector<std::pair<polestate,int>>& keyset) {
	if (bound == 0)
		return true;

	// game should be in the very initial state.
	game.reset();
	game.perturbation();

	std::vector<std::pair<polestate,int>> path;
	int s = 0;
	while(s < bound)
	{
		//boost::tuples::tuple<double, double, double, double>
		polestate st = game.getState();
		auto ac = getAction(graph, data(game.getState()));
		path.push_back (std::make_pair(st, ac.id));
		game.step(ac.id-1);
		display (st, ac.id-1);
		bool failed = game.fail();
		s ++;
		if( failed ) break;
	}
	std::cout << "how well is the trained network: " << s << " steps\n";
	if (s == bound) {
		// neural network is good enough so there is no need to improve it.
		return true;
	}
	else {
		for (std::vector<std::pair<polestate,int>>::reverse_iterator i = path.rbegin(); i != path.rend(); ++i) {
			// Check how mc thinks about the best move.
			//std::cout << "from the " << s << " step in the counterexample\n";
			int ac = uct_advise(i->first, game.fail(), graph);
			if (ac == i->second) {
				// The mc and neural net agrees with each other.
			} else {
				std::vector<std::pair<polestate,int>> local_keyset;
				polestate st = i->first;
				game.setState (st);
				int i = 1;
				bool res = false;
				while (i <= bound - s) {
					local_keyset.push_back (std::make_pair (st, ac));
					game.step(ac-1);
					if (game.fail()) break;
					st = game.getState();
					//std::cout << "agent needs to play " << bound - s - i << " steps from "; display (st);
					res = agentPlay (game, graph, bound - s - i);
					game.setState(st);
					if (res) break;
					ac = uct_advise(st, game.fail(), graph);
					i++;
				}

				if (res) {
					std::cout << "we can fix the the counterexample path\n";
					keyset.insert(keyset.end(), local_keyset.begin(), local_keyset.end());
					return true;
				}
			}
			s--;
		}
		std::cout << "we cannot fix the counterexample path\n";
		return false;
	}
}

// CEGIS based training for controller synthesis.
void cegis_train() {
	Network network;
	network << FcLayer(Matrix::Random(10, 4).array() / 5);
	network << ReLULayer(Matrix::Zero(10, 1));
	network << FcLayer(Matrix::Random(10, 10).array() / 5);
	network << ReLULayer(Matrix::Zero(10, 1));
	network << FcLayer(Matrix::Random(3, 10).array() / 5);
	network << TanhLayer(Matrix::Zero(3, 1));

	ComputationGraph graph(network);

	Pole game;

	int bound = 200;

	std::vector<std::pair<polestate,int>> keyset;

	int g = 0;
	do {
		int size = keyset.size();
		bool fixable = key_gen (game, graph, bound, keyset);
		if (!fixable) {
			std::cout << "Should go back to reinforcement learning?\n";
			return;
		}
		if (keyset.size() == size) {
			g++;
		} else {
			g = 0;
			// Supervised learning to train the controller.
			auto prop = std::unique_ptr<RMSProp>(new RMSProp(0.9, 0.005, 0.001));
			RMSProp* rmsprop = prop.get();
			Solver solver( std::move(prop) );
			// First learn on the new keypoints
			int error;
			int currSize = keyset.size() - size;
			std::cout << "---------------------------------------------------------------\n";
			int iteri = 0;
			do {
				error = 0;
				int index = 0;
				for (std::vector<std::pair<polestate,int>>::reverse_iterator i = keyset.rbegin();
						i != keyset.rend() && index < currSize; ++i) {
					//std::cout << "Enforcing the neural network to behave as: \n";
					//display (i->first, i->second-1);

					//float target_value = 1.0;

					const auto& result = graph.forward(data(i->first));
					int row, col;
					result.maxCoeff(&row,&col);
					error += (row == i->second? 0 : 1);
					//std::cout << "Its original behavior on this is: " << row - 1 << "\n";
					//for (int k = 0; k < result.size(); k ++)
					//	std::cout << result[k] << " ";
					//std::cout << "\n";
					Vector errorCache = Vector::Zero( result.size() );

					//float delta = result[i->second] - target_value;
					//errorCache[i->second] = delta;
					for (int k = 0; k < result.size(); k++) {
						if (k == i->second)
							errorCache[k] = result[k] - 1.0;
						else
							errorCache[k] = result[k] - (-1.0);
					}

					graph.backpropagate(errorCache, solver);

					index ++;
				}
				network.update( solver );
				iteri ++;
				if (iteri % 10000 == 0)
					std::cout << "temporaral fix training error number: " << error << "\n";
			} while (error > 0 && iteri < 100000);
			std::cout << "fix training with error number: " << error << "\n";
			std::cout << "---------------------------------------------------------------\n";
			// Second learn on the whole keypoints
			iteri = 0;
			do {
				error = 0;
				for (std::vector<std::pair<polestate,int>>::iterator i = keyset.begin();
						i != keyset.end(); ++i) {

					//float target_value = 1.0;

					const auto& result = graph.forward(data(i->first));
					int row, col;
					result.maxCoeff(&row,&col);
					error += (row == i->second? 0 : 1);

					Vector errorCache = Vector::Zero( result.size() );

					//float delta = result[i->second] - target_value;
					//errorCache[i->second] = delta;
					for (int k = 0; k < result.size(); k++) {
						if (k == i->second)
							errorCache[k] = result[k] - 1.0;
						else
							errorCache[k] = result[k] - (-1.0);
					}

					graph.backpropagate(errorCache, solver);
				}
				network.update( solver );
				iteri++;
				//std::cout << "error number: " << error << "\n";
			} while (error > 0 && iteri < 10000);
			std::cout << "batch training error number: " << error << "\n";
		}
	} while (g < 5);
	network.save ("supervised_agent.network");
	std::cout << "Trained Successfully!\n";
}

// Verify an abstraction
bool ce_gen (Pole& game, ComputationGraph& graph, DT& dt, int bound, std::vector<std::pair<polestate,int>>& keyset, bool rec_flag) {
	if (bound == 0)
		return true;

	std::vector<std::pair<polestate,int>> path;
	int s = 0;
	while(s < bound)
	{
		//boost::tuples::tuple<double, double, double, double>
		polestate st = game.getState();
		double*  dtst = new double[4];
		dtst[0] = st.get<0>();dtst[1] = st.get<1>();dtst[2] = st.get<2>();dtst[3] = st.get<3>();
		int ac = dt.predict (dtst, 4);
		delete [] dtst;
		path.push_back (std::make_pair(st, ac));
		game.step(ac-1);

		bool failed = game.fail();
		s ++;
		if( failed ) break;
	}
	if (!rec_flag)
		std::cout << "how well is the abstraction: " << s << " steps\n";
	if (s == bound) {
		// abstraction is fine so there is no counterexample
		return true;
	}
	else {
		for (std::vector<std::pair<polestate,int>>::reverse_iterator i = path.rbegin(); i != path.rend(); ++i) {
			game.setState (i->first);
			// Check how neural net works.
			auto ac = getAction(graph, data(i->first));
			if (ac.id == i->second) {
				// The abstraction and neural net agrees with each other.
			} else {
				// Check if neural net's decision is good.
				bool res = agentPlay (game, graph, bound - s);
				game.setState(i->first);
				if (res) {
					keyset.push_back (std::make_pair (i->first, ac.id));
					game.step(ac.id-1);
					return ce_gen (game, graph, dt, bound - s - 1, keyset, true);
				}
			}
			s--;
		}
		return false;
	}
}

// abstract-refine checking of a neural model
void abstraction_check (std::string filename) {
	Network agent;
	agent.load (filename);
	std::string modelname = filename + ".json";
	agent.saveJson (modelname);
	ComputationGraph graph(agent);
	int g = 0;

	// Load abstraction from decision tree
	DT dt(modelname);
	std::vector<std::pair<polestate,int>> keyset;
	// Use keyset to refine the abstraction
	std::string datafile = filename+".data";
	std::remove(datafile.c_str());

	// Fixme. Should ask reluplex to generate at least one sample for each class.
	//std::fstream out(datafile, std::fstream::out);
	//out << -1.70586e-01 << "," << 5.38879e-02 << ","
	//	<< -6.72141e-03 << "," << -3.10080e-02  << ",";
	//out << "Left\n";
	//out << -3.28355e-01 << "," << -1.09655e-01 << ","
	//	<< -3.96630e-03 << "," << 3.00918e-02 << ",";
	//out << "Stay\n";
	//out << -4.21625e-01 << "," << -2.76742e-01 << ","
	//	<< -1.65369e-02 << "," << 1.37284e-01 << ",";
	//out << "Right\n";
	//out.flush ();
	//out.close ();

	agentSample (graph, 3, keyset);

	// Iterative buidling an abstraction of a neuron controller.
	do {
		// Execute the abstraction
		Pole game;
		game.reset();
		game.perturbation();

		int size = keyset.size();
		std::cout << "before ce-gen keyset.size() == " << keyset.size() << "\n";
		bool res = ce_gen (game, graph, dt, 200, keyset, false);
		std::cout << "after  ce-gen keyset.size() == " << keyset.size() << "\n";
		if (!res) {
			// We found a counterexample to the neural net.
			std::cout << "A real counterexample is found!\n";
			// Should terminate reporting the counterexample.
		} else {
			if (keyset.size() == size) {
				g++;
			} else {
				g = 0;
				std::fstream evl(datafile, std::fstream::out);

				for (std::vector<std::pair<polestate,int>>::iterator i = keyset.begin();
						i != keyset.end(); ++i) {
					render (evl, i->first, i->second);
					evl.flush ();
				}
				evl.close();
				if (keyset.size() > 200) {
					std::cout << "keyset.size() == " << keyset.size() << "\n";
					dt.learn(datafile);
				}
			}
		}
	} while (g < 10); // Verification converges after consecutive success in several rounds.
	std::cout << "Verifed!\n";

	int ts = 0;
	for(int g = 0; g < 100; ++g)
	{
		Pole game;
		game.reset();
		game.perturbation();
		display(game.getState());
		int s = 0;
		while(true)
		{
			polestate st = game.getState();
			double*  dtst = new double[4];
			dtst[0] = st.get<0>();dtst[1] = st.get<1>();dtst[2] = st.get<2>();dtst[3] = st.get<3>();
			int ac = dt.predict (dtst, 4);
			delete [] dtst;
			game.step(ac-1);

			bool failed = game.fail();
			s ++;
			ts ++;
			if( failed ) {
				std::cout << "Maintained in " << s << " steps\n";
				break;
			}
		}
	}
	std::cout << (ts / 100.0) << "\n";
}

ext: cpp

max_stars_repo_name: rowangithub/FastRL

max_issues_repo_name: rowangithub/FastRL

max_forks_repo_name: rowangithub/FastRL


text:
/*************************************************************************
 * jenkins-vr
 *************************************************************************
 * @file    CSphinxRecognizer.cpp
 * @date    14.06.16
 * @author  Hlieb Romanov
 * @brief   Speech recognizer class implementation
 ************************************************************************/
#include <gst/gst.h>
#include <glib.h>
#include <boost/format.hpp>
#include <boost/thread.hpp>

#include "imp/recognizer/CSphinxRecognizer.hpp"
#include "imp/recognizer/private/CGstRecognizerPipeline.hpp"
#include "imp/recognizer/private/CDecoder.hpp"
#include "imp/logger/CLogger.hpp"

using namespace api::asr;

/**
 * TODO: create IConfigurable interface
 */
static const char* DEFAULT_LANG_DIR = "lang";
static const char* DEFAULT_LANGUAGE = "ru-RU";
static const char* KEY_FILE_EXTENSION = ".key";
static const char* DICT_FILE_EXTENSION = ".dic";
static const char* GRAMMAR_FILE_EXTENSION = ".jsgf";
static const char* RECOGNIZER_ERROR_MSG = "Recognizer may be in inconsistent state. Aborting.";
static const char* RECOGNIZER_KWS_ERROR_MSG = "Unable to configure key word recognition. Aborting.";
static const char* RECOGNIZER_VR_ERROR_MSG = "Unable to configure voice recognition. Aborting.";

/**
 * TODO: make common hpp and cpp files and move utility functions to it.
 */
static void THROW_FATAL( const std::string&  message )
{
   CLogger::fatal() << message;
   throw std::runtime_error( message );
}

static void RUN_CHECKED( bool operationResult, const std::string& errorMessage )
{
   if ( !operationResult )
   {
      THROW_FATAL( errorMessage );
   }
}

CSphinxRecognizer::CSphinxRecognizer( void )
   : mLanguage( DEFAULT_LANGUAGE )
   , mMode( RecognizerMode::KEY_WORD_SEARCH )
{
   reinit();
}

void CSphinxRecognizer::reinit( void )
{
   std::string langDir( DEFAULT_LANG_DIR );
   langDir += "\\" + mLanguage;
   std::string dictDir = langDir + "\\" + mLanguage + std::string( DICT_FILE_EXTENSION );
   std::string keyFile = langDir + "\\" + mLanguage + std::string( KEY_FILE_EXTENSION );
   std::string grammarFile = langDir + "\\" + mLanguage + std::string( GRAMMAR_FILE_EXTENSION );
   mRecognizerPipeline.reset( new CGstRecognizerPipeline( langDir, dictDir ) );
   DecoderPtr decoder = mRecognizerPipeline->getDecoder();
   RUN_CHECKED( decoder->setKeyFile( keyFile ), RECOGNIZER_KWS_ERROR_MSG );
   RUN_CHECKED( decoder->setGrammarFile( grammarFile ), RECOGNIZER_VR_ERROR_MSG );
   RUN_CHECKED( decoder->activateMode( mMode ), RECOGNIZER_VR_ERROR_MSG );
}

api::asr::RecognizerPtr CSphinxRecognizer::create( void )
{
   return RecognizerPtr( new CSphinxRecognizer() );
}

CSphinxRecognizer::~CSphinxRecognizer( void )
{
}

std::string CSphinxRecognizer::getLanguage( void ) const
{
   return mLanguage;
}

void CSphinxRecognizer::setLanguage( const std::string& language )
{
   mLanguage = language;
   reinit();
}

api::asr::RecognizerMode::eRecognizerMode CSphinxRecognizer::getMode( void ) const
{
   return mMode;
}

bool CSphinxRecognizer::setMode( api::asr::RecognizerMode::eRecognizerMode mode )
{
   bool result = false;
   if ( !mRecognizerPipeline->isListening() )
   {
      DecoderPtr decoder = mRecognizerPipeline->getDecoder();
      if ( decoder )
      {
         result = decoder->activateMode( mode );
      }
   }
   return result;
}

bool CSphinxRecognizer::listen( void )
{
   bool result = false;
   if ( !mRecognizerPipeline->isListening() && mMode != RecognizerMode::NONE )
   {
      result = mRecognizerPipeline->startListening();
      mStartListening( StartListeningData( mMode, result ) );
   }
   return result;
}

bool CSphinxRecognizer::isListening( void ) const
{
   return mRecognizerPipeline->isListening();
}

void CSphinxRecognizer::stopListening( void )
{
   if ( mRecognizerPipeline->isListening() )
   {
      mRecognizerPipeline->stopListening();
      mStopListening( api::asr::StopListeningData() );
   }
}

bool CSphinxRecognizer::phonetize( const std::string& group, const GraphemePhonemeList& g2pList )
{
   return false;
}

signals::connection CSphinxRecognizer::onStartListening( const api::asr::StartListeningSignal_t::slot_type& slot )
{
   return mStartListening.connect( slot );
}

signals::connection CSphinxRecognizer::onRecognitionResult( const api::asr::RecognitionResultSignal_t::slot_type& slot )
{
   return mRecognitionResult.connect( slot );
}

signals::connection CSphinxRecognizer::onStopListening( const api::asr::StopListeningSignal_t::slot_type& slot )
{
   return mStopListening.connect( slot );
}

max_stars_repo_name: Glebka/jenkins-vr

max_issues_repo_name: Glebka/jenkins-vr

max_forks_repo_name: Glebka/jenkins-vr


text:
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// test_traits_pass.cpp: test implementation level trait

// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// 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)

// compile test for traits
#include "test_tools.hpp"
#include <boost/preprocessor/stringize.hpp>
#include BOOST_PP_STRINGIZE(BOOST_ARCHIVE_TEST)

#include <boost/serialization/level.hpp>
#include <boost/serialization/tracking.hpp>
#include <boost/serialization/version.hpp>

class B
{
};

BOOST_CLASS_IMPLEMENTATION(B, boost::serialization::object_class_info)
BOOST_CLASS_VERSION(B, 2)
BOOST_CLASS_TRACKING(B, boost::serialization::track_always)

int
test_main( int argc, char* argv[] )
{
    return EXIT_SUCCESS;
}

// EOF

max_stars_repo_name: spxuw/RFIM

max_issues_repo_name: spxuw/RFIM

max_forks_repo_name: spxuw/RFIM


text:
#include <NTL/config.h>

#if (defined(NTL_CXX_ONLY) && !defined(__cplusplus))
#error "CXX_ONLY flag set...must use C++ compiler"
#endif

#include <sys/time.h>
#include <sys/resource.h>

#if (defined(__cplusplus))
extern "C"
#else
extern
#endif
int getrusage(int, struct rusage*);

#if (defined(__cplusplus) && !defined(NTL_CXX_ONLY))
extern "C" double _ntl_GetTime();
#endif

double _ntl_GetTime(void)
{
   struct rusage used;

   getrusage(RUSAGE_SELF, &used);
   return (used.ru_utime.tv_sec + used.ru_stime.tv_sec +
      (used.ru_utime.tv_usec + used.ru_stime.tv_usec) / 1e6);
}

max_stars_repo_name: vshesh/RUNEtag

max_issues_repo_name: vshesh/RUNEtag

max_forks_repo_name: vshesh/RUNEtag


text:
/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2008, Willow Garage, Inc.
 *  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 Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 */

#include "ros/connection.h"
#include "ros/transport/transport.h"
#include "ros/file_log.h"

#include <ros/assert.h>

#include <boost/shared_array.hpp>
#include <boost/bind.hpp>

namespace ros
{

Connection::Connection()
: is_server_(false)
, dropped_(false)
, read_filled_(0)
, read_size_(0)
, reading_(false)
, has_read_callback_(0)
, write_sent_(0)
, write_size_(0)
, writing_(false)
, has_write_callback_(0)
, sending_header_error_(false)
{
}

Connection::~Connection()
{
  ROS_DEBUG_NAMED("superdebug", "Connection destructing, dropped=%s", dropped_ ? "true" : "false");

  drop(Destructing);
}

void Connection::initialize(const TransportPtr& transport, bool is_server, const HeaderReceivedFunc& header_func)
{
  ROS_ASSERT(transport);

  transport_ = transport;
  header_func_ = header_func;
  is_server_ = is_server;

  transport_->setReadCallback(boost::bind(&Connection::onReadable, this, _1));
  transport_->setWriteCallback(boost::bind(&Connection::onWriteable, this, _1));
  transport_->setDisconnectCallback(boost::bind(&Connection::onDisconnect, this, _1));

  if (header_func)
  {
    read(4, boost::bind(&Connection::onHeaderLengthRead, this, _1, _2, _3, _4));
  }
}

boost::signals2::connection Connection::addDropListener(const DropFunc& slot)
{
  boost::recursive_mutex::scoped_lock lock(drop_mutex_);
  return drop_signal_.connect(slot);
}

void Connection::removeDropListener(const boost::signals2::connection& c)
{
  boost::recursive_mutex::scoped_lock lock(drop_mutex_);
  c.disconnect();
}

void Connection::onReadable(const TransportPtr& transport)
{
  (void)transport;
  ROS_ASSERT(transport == transport_);

  readTransport();
}

void Connection::readTransport()
{
  boost::recursive_mutex::scoped_try_lock lock(read_mutex_);

  if (!lock.owns_lock() || dropped_ || reading_)
  {
    return;
  }

  reading_ = true;

  while (!dropped_ && has_read_callback_)
  {
    ROS_ASSERT(read_buffer_);
    uint32_t to_read = read_size_ - read_filled_;
    if (to_read > 0)
    {
      int32_t bytes_read = transport_->read(read_buffer_.get() + read_filled_, to_read);
      ROS_DEBUG_NAMED("superdebug", "Connection read %d bytes", bytes_read);
      if (dropped_)
      {
        return;
      }
      else if (bytes_read < 0)
      {
        // Bad read, throw away results and report error
        ReadFinishedFunc callback;
        callback = read_callback_;
        read_callback_.clear();
        read_buffer_.reset();
        uint32_t size = read_size_;
        read_size_ = 0;
        read_filled_ = 0;
        has_read_callback_ = 0;

        if (callback)
        {
          callback(shared_from_this(), read_buffer_, size, false);
        }

        break;
      }

      read_filled_ += bytes_read;
    }

    ROS_ASSERT((int32_t)read_size_ >= 0);
    ROS_ASSERT((int32_t)read_filled_ >= 0);
    ROS_ASSERT_MSG(read_filled_ <= read_size_, "read_filled_ = %d, read_size_ = %d", read_filled_, read_size_);

    if (read_filled_ == read_size_ && !dropped_)
    {
      ReadFinishedFunc callback;
      uint32_t size;
      boost::shared_array<uint8_t> buffer;

      ROS_ASSERT(has_read_callback_);

      // store off the read info in case another read() call is made from within the callback
      callback = read_callback_;
      size = read_size_;
      buffer = read_buffer_;
      read_callback_.clear();
      read_buffer_.reset();
      read_size_ = 0;
      read_filled_ = 0;
      has_read_callback_ = 0;

      ROS_DEBUG_NAMED("superdebug", "Calling read callback");
      callback(shared_from_this(), buffer, size, true);
    }
    else
    {
      break;
    }
  }

  if (!has_read_callback_)
  {
    transport_->disableRead();
  }

  reading_ = false;
}

void Connection::writeTransport()
{
  boost::recursive_mutex::scoped_try_lock lock(write_mutex_);

  if (!lock.owns_lock() || dropped_ || writing_)
  {
    return;
  }

  writing_ = true;
  bool can_write_more = true;

  while (has_write_callback_ && can_write_more && !dropped_)
  {
    uint32_t to_write = write_size_ - write_sent_;
    ROS_DEBUG_NAMED("superdebug", "Connection writing %d bytes", to_write);
    int32_t bytes_sent = transport_->write(write_buffer_.get() + write_sent_, to_write);
    ROS_DEBUG_NAMED("superdebug", "Connection wrote %d bytes", bytes_sent);

    if (bytes_sent < 0)
    {
      writing_ = false;
      return;
    }

    write_sent_ += bytes_sent;

    if (bytes_sent < (int)write_size_ - (int)write_sent_)
    {
      can_write_more = false;
    }

    if (write_sent_ == write_size_ && !dropped_)
    {
      WriteFinishedFunc callback;

      {
        boost::mutex::scoped_lock lock(write_callback_mutex_);
        ROS_ASSERT(has_write_callback_);
        // Store off a copy of the callback in case another write() call happens in it
        callback = write_callback_;
        write_callback_ = WriteFinishedFunc();
        write_buffer_ = boost::shared_array<uint8_t>();
        write_sent_ = 0;
        write_size_ = 0;
        has_write_callback_ = 0;
      }

      ROS_DEBUG_NAMED("superdebug", "Calling write callback");
      callback(shared_from_this());
    }
  }

  {
    boost::mutex::scoped_lock lock(write_callback_mutex_);
    if (!has_write_callback_)
    {
      transport_->disableWrite();
    }
  }

  writing_ = false;
}

void Connection::onWriteable(const TransportPtr& transport)
{
  (void)transport;
  ROS_ASSERT(transport == transport_);

  writeTransport();
}

void Connection::read(uint32_t size, const ReadFinishedFunc& callback)
{
  if (dropped_ || sending_header_error_)
  {
    return;
  }

  {
    boost::recursive_mutex::scoped_lock lock(read_mutex_);

    ROS_ASSERT(!read_callback_);

    read_callback_ = callback;
    read_buffer_ = boost::shared_array<uint8_t>(new uint8_t[size]);
    read_size_ = size;
    read_filled_ = 0;
    has_read_callback_ = 1;
  }

  transport_->enableRead();

  // read immediately if possible
  readTransport();
}

void Connection::write(const boost::shared_array<uint8_t>& buffer, uint32_t size, const WriteFinishedFunc& callback, bool immediate)
{
  if (dropped_ || sending_header_error_)
  {
    return;
  }

  {
    boost::mutex::scoped_lock lock(write_callback_mutex_);

    ROS_ASSERT(!write_callback_);

    write_callback_ = callback;
    write_buffer_ = buffer;
    write_size_ = size;
    write_sent_ = 0;
    has_write_callback_ = 1;
  }

  transport_->enableWrite();

  if (immediate)
  {
    // write immediately if possible
    writeTransport();
  }
}

void Connection::onDisconnect(const TransportPtr& transport)
{
  (void)transport;
  ROS_ASSERT(transport == transport_);

  drop(TransportDisconnect);
}

void Connection::drop(DropReason reason)
{
  ROSCPP_LOG_DEBUG("Connection::drop(%u)", reason);
  bool did_drop = false;
  {
    boost::recursive_mutex::scoped_lock lock(drop_mutex_);
    if (!dropped_)
    {
      dropped_ = true;
      did_drop = true;
    }
  }

  if (did_drop)
  {
    drop_signal_(shared_from_this(), reason);
    transport_->close();
  }
}

bool Connection::isDropped()
{
  boost::recursive_mutex::scoped_lock lock(drop_mutex_);
  return dropped_;
}

void Connection::writeHeader(const M_string& key_vals, const WriteFinishedFunc& finished_callback)
{
  ROS_ASSERT(!header_written_callback_);
  header_written_callback_ = finished_callback;

  if (!transport_->requiresHeader())
  {
    onHeaderWritten(shared_from_this());
    return;
  }

  boost::shared_array<uint8_t> buffer;
  uint32_t len;
  Header::write(key_vals, buffer, len);

  uint32_t msg_len = len + 4;
  boost::shared_array<uint8_t> full_msg(new uint8_t[msg_len]);
  memcpy(full_msg.get() + 4, buffer.get(), len);
  *((uint32_t*)full_msg.get()) = len;

  write(full_msg, msg_len, boost::bind(&Connection::onHeaderWritten, this, _1), false);
}

void Connection::sendHeaderError(const std::string& error_msg)
{
  M_string m;
  m["error"] = error_msg;

  writeHeader(m, boost::bind(&Connection::onErrorHeaderWritten, this, _1));
  sending_header_error_ = true;
}

void Connection::onHeaderLengthRead(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success)
{
  (void)size;
  ROS_ASSERT(conn.get() == this);
  ROS_ASSERT(size == 4);

  if (!success)
    return;

  uint32_t len = *((uint32_t*)buffer.get());

  if (len > 1000000000)
  {
    ROS_ERROR("a header of over a gigabyte was " \
                "predicted in tcpros. that seems highly " \
                "unlikely, so I'll assume protocol " \
                "synchronization is lost.");
    conn->drop(HeaderError);
  }

  read(len, boost::bind(&Connection::onHeaderRead, this, _1, _2, _3, _4));
}

void Connection::onHeaderRead(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success)
{
  ROS_ASSERT(conn.get() == this);

  if (!success)
    return;

  std::string error_msg;
  if (!header_.parse(buffer, size, error_msg))
  {
    drop(HeaderError);
  }
  else
  {
    std::string error_val;
    if (header_.getValue("error", error_val))
    {
      ROSCPP_LOG_DEBUG("Received error message in header for connection to [%s]: [%s]", transport_->getTransportInfo().c_str(), error_val.c_str());
      drop(HeaderError);
    }
    else
    {
      ROS_ASSERT(header_func_);

      transport_->parseHeader(header_);

      header_func_(conn, header_);
    }
  }

}

void Connection::onHeaderWritten(const ConnectionPtr& conn)
{
  ROS_ASSERT(conn.get() == this);
  ROS_ASSERT(header_written_callback_);

  header_written_callback_(conn);
  header_written_callback_ = WriteFinishedFunc();
}

void Connection::onErrorHeaderWritten(const ConnectionPtr& conn)
{
  (void)conn;
  drop(HeaderError);
}

void Connection::setHeaderReceivedCallback(const HeaderReceivedFunc& func)
{
  header_func_ = func;

  if (transport_->requiresHeader())
    read(4, boost::bind(&Connection::onHeaderLengthRead, this, _1, _2, _3, _4));
}

std::string Connection::getCallerId()
{
  std::string callerid;
  if (header_.getValue("callerid", callerid))
  {
    return callerid;
  }

  return std::string("unknown");
}

std::string Connection::getRemoteString()
{
  std::stringstream ss;
  ss << "callerid=[" << getCallerId() << "] address=[" << transport_->getTransportInfo() << "]";
  return ss.str();
}

}


text:
#ifndef BOOST_STATECHART_TEST_TU_TEST_HPP_INCLUDED
#define BOOST_STATECHART_TEST_TU_TEST_HPP_INCLUDED
//////////////////////////////////////////////////////////////////////////////
// Copyright 2005-2006 Andreas Huber Doenni
// Distributed under the Boost Software License, Version 1.0. (See accompany-
// ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//////////////////////////////////////////////////////////////////////////////

#include <boost/statechart/event.hpp>
#include <boost/statechart/state_machine.hpp>

#include <boost/config.hpp>

#ifdef BOOST_STATECHART_TEST_DYNAMIC_LINK
  #ifdef BOOST_STATECHART_TEST_DLL_EXPORT
    #define BOOST_STATECHART_DECL BOOST_SYMBOL_EXPORT
  #else
    #define BOOST_STATECHART_DECL BOOST_SYMBOL_IMPORT
  #endif
#endif

#ifndef BOOST_STATECHART_DECL
  #define BOOST_STATECHART_DECL
#endif

namespace sc = boost::statechart;

#ifdef BOOST_MSVC
#  pragma warning( push )
   // class X needs to have dll-interface to be used by clients of class Y
#  pragma warning( disable: 4251 )
   // non dll-interface class X used as base for dll-interface class
#  pragma warning( disable: 4275 )
#endif

struct BOOST_STATECHART_DECL EvX : sc::event< EvX > {};
struct BOOST_STATECHART_DECL EvY : sc::event< EvY > {};

struct Initial;
struct BOOST_STATECHART_DECL TuTest : sc::state_machine< TuTest, Initial >
{
  void initiate();
  void unconsumed_event( const sc::event_base & );
};

#ifdef BOOST_MSVC
#  pragma warning( pop )
#endif

#endif

ext: hpp

max_stars_repo_name: Jackarain/tinyrpc

max_issues_repo_name: avplayer/cxxrpc

max_forks_repo_name: avplayer/cxxrpc


text:
//          Copyright Rein Halbersma 2010-2020.
// 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 <core/board/sequence.hpp>              // nano, micro, checkers, Roman, spantsiretti, international, frisian, ktar<10, 11>,
                                                // ktar<10, 12>, Compact_10_12, Compact_12_10, basic_board<12, 10>, canadian, srilankan, dumm
#include <core/board/transform.hpp>             // is_involution, is_idempotent
#include <dctl/core/board/basic_board.hpp>      // board
#include <dctl/core/board/mask.hpp>             // basic_mask
#include <dctl/core/rules/type_traits.hpp>      // is_empty, is_pushable, is_jumpable, invert
#include <dctl/core/state/color.hpp>
#include <boost/range/irange.hpp>               // irange
#include <boost/test/unit_test.hpp>             // BOOST_AUTO_TEST_SUITE, BOOST_AUTO_TEST_SUITE_END, BOOST_AUTO_TEST_CASE, BOOST_AUTO_TEST_CASE_TEMPLATE
#include <algorithm>                            // all_of
#include <numeric>                              // accumulate
#include <type_traits>                          // is_same

BOOST_AUTO_TEST_SUITE(BoardTraits)

using namespace dctl::core;

BOOST_AUTO_TEST_CASE(IsEmpty)
{
        static_assert( is_placeable_v<basic_board<rectangular<1, 1>>>);
        static_assert( is_placeable_v<basic_board<rectangular<2, 1, 0>>>);
        static_assert( is_placeable_v<basic_board<rectangular<1, 2, 0>>>);
}

BOOST_AUTO_TEST_CASE(IsPushable)
{
        static_assert(!is_pushable_v<basic_board<rectangular<1, 1>>>);
        static_assert(!is_pushable_v<basic_board<rectangular<2, 1>>>);
        static_assert(!is_pushable_v<basic_board<rectangular<1, 2>>>);
        static_assert(    is_pushable_v<basic_board<rectangular<2, 2>>>);
}

BOOST_AUTO_TEST_CASE(IsJumpable)
{
        static_assert(!is_jumpable_v<basic_board<rectangular<2, 2>>>);
        static_assert(!is_jumpable_v<basic_board<rectangular<3, 2>>>);
        static_assert(!is_jumpable_v<basic_board<rectangular<2, 3>>>);
        static_assert(!is_jumpable_v<basic_board<rectangular<3, 3, 0>>>);
        static_assert(    is_jumpable_v<basic_board<rectangular<3, 3>>>);
        static_assert(    is_jumpable_v<basic_board<rectangular<4, 3, 0>>>);
        static_assert(    is_jumpable_v<basic_board<rectangular<3, 4, 0>>>);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(IsRegular, T, BoardSequence)
{
        static_assert(is_placeable_v<T>);
        static_assert(is_pushable_v<T>);
        static_assert(is_jumpable_v<T>);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(SquaresCountEqualsBoardSize, T, BoardSequence)
{
        using mask_type = basic_mask<T>;
        BOOST_CHECK_EQUAL(mask_type::squares.ssize(), T::size());
}

BOOST_AUTO_TEST_CASE_TEMPLATE(ColumnsEquivalencePartitionSquares, T, BoardSequence)
{
        auto const files = boost::irange(0, T::width);
        using mask_type = basic_mask<T>;

        BOOST_CHECK(
                std::all_of(files.begin(), files.end(), [=](auto i) {
                        return mask_type::file(black_c, i) == mask_type::file(white_c, T::width - 1 - i);
                })
        );

        BOOST_CHECK(
                std::all_of(files.begin(), files.end(), [=](auto i) {
                        return std::all_of(files.begin(), files.end(), [=](auto j) {
                                return i == j ? true : is_disjoint(mask_type::file(white_c, i), mask_type::file(white_c, j));
                        });
                })
        );

        BOOST_CHECK(
                std::accumulate(files.begin(), files.end(), set_t<mask_type>{}, [](auto result, auto i) {
                        return result ^ mask_type::file(white_c, i);
                }) == mask_type::squares
        );
}

BOOST_AUTO_TEST_CASE_TEMPLATE(RowsEquivalencePartitionSquares, T, BoardSequence)
{
        auto const rows = boost::irange(0, T::height);
        using mask_type = basic_mask<T>;

        BOOST_CHECK(
                std::all_of(rows.begin(), rows.end(), [=](auto i) {
                        return mask_type::rank(black_c, i) == mask_type::rank(white_c, T::height - 1 - i);
                })
        );

        BOOST_CHECK(
                std::all_of(rows.begin(), rows.end(), [=](auto i) {
                        return std::all_of(rows.begin(), rows.end(), [=](auto j) {
                                return i == j ? true : is_disjoint(mask_type::rank(white_c, i), mask_type::rank(white_c, j));
                        });
                })
        );

        BOOST_CHECK(
                std::accumulate(rows.begin(), rows.end(), set_t<mask_type>{}, [](auto result, auto i) {
                        return result ^ mask_type::rank(white_c, i);
                }) == mask_type::squares
        );
}

BOOST_AUTO_TEST_SUITE_END()


text:
#pragma once
#include <BoostAsioLib/BAIoServiceManager.h>
#include <BoostAsioLib/BATCPConnection.h>
#include <BoostAsioLib/BAConnectionManager.h>
#include <boost/scoped_ptr.hpp>
#include <boost/bind.hpp>
#include <atomic>

class TcpServerSample
{
public:
	TcpServerSample()
		: _manager_ptr(BoostAsioLib::IBAIoServiceManager::Create(4))
		, _is_disposed(0)
	{
		_conn_manager_ptr = BoostAsioLib::IBAConnectionManager::Create();
		_acceptor.reset(new boost::asio::ip::tcp::acceptor(_manager_ptr->GetIoService()));
		boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address_v4::any(), 9661);

		_acceptor->open(ep.protocol());
		_acceptor->bind(ep);
		_acceptor->listen();

		long long socket_id;
		boost::asio::io_service& ios = _manager_ptr->GetIoService(&socket_id);

		_accepted_conn_ptr = BoostAsioLib::IBATCPConnection::Create(ios, socket_id);
		_accepted_conn_ptr->SetOnReceived(boost::bind(&TcpServerSample::OnReceived, this, _1, _2, _3));

		_acceptor->async_accept(_accepted_conn_ptr->GetSocket(), boost::bind(&TcpServerSample::OnAccepted, this,
			_accepted_conn_ptr, boost::asio::placeholders::error));
	}

	~TcpServerSample()
	{
		++_is_disposed;

		_accepted_conn_ptr->Stop();
		_accepted_conn_ptr.reset();

		_acceptor->close();
		_acceptor.reset();

		_manager_ptr.reset();
		_conn_manager_ptr.reset();
	}

private:
	void OnAccepted(BoostAsioLib::IBATCPConnectionPtr conn_ptr, const boost::system::error_code& errcode)
	{
		if (_is_disposed)
		{
			return;
		}

		if (!errcode)
		{
			_conn_manager_ptr->Register(conn_ptr);
			conn_ptr->Start();
		}
		else
		{
			conn_ptr->Stop();
		}

		long long socket_id;
		boost::asio::io_service& ios = _manager_ptr->GetIoService(&socket_id);
		_accepted_conn_ptr = BoostAsioLib::IBATCPConnection::Create(ios, socket_id);
		_accepted_conn_ptr->SetOnReceived(boost::bind(&TcpServerSample::OnReceived, this, _1, _2, _3));

		_acceptor->async_accept(_accepted_conn_ptr->GetSocket(), boost::bind(&TcpServerSample::OnAccepted, this, _accepted_conn_ptr, boost::asio::placeholders::error));
	}

	void OnReceived(long long socket_id, const boost::system::error_code& errcode, size_t bytes_transferred)
	{
		if (bytes_transferred == 0 || errcode)
		{
			// disconnect ?
			_conn_manager_ptr->Unregister(socket_id);
			printf("OnDisconnected (OnReceived) ; id=%I64d, thread=%u\n", socket_id, GetCurrentThreadId());
		}
		else
		{
			// success ?
			BoostAsioLib::IBAConnectionPtr conn = _conn_manager_ptr->Get(socket_id);
			printf("OnReceived ; id=%I64d(%I64d), thread=%u\n", socket_id, conn->GetSocketID(), GetCurrentThreadId());
		}
	}

private:
	BoostAsioLib::IBAIoServiceManagerPtr _manager_ptr;

	boost::scoped_ptr<boost::asio::ip::tcp::acceptor> _acceptor;
	BoostAsioLib::IBATCPConnectionPtr _accepted_conn_ptr;
	BoostAsioLib::IBAConnectionManagerPtr _conn_manager_ptr;

	std::atomic<int> _is_disposed;
};

max_stars_repo_name: Sikuru/CppCodeSamples

max_issues_repo_name: Sikuru/CppCodeSamples

max_forks_repo_name: Sikuru/CppCodeSamples


text:
//==================================================================================================
/*!
  @file

    @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_SIGNNZ_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_SIGNNZ_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

  /*!
    @ingroup group-ieee
    This function object returns the sign of x. I.e. -1 or 1,
    depending on the fact  @c x is negative or positive.

    @par Header <boost/simd/function/signnz.hpp>
    @par Notes:

    - This function never returns @ref Zero (zero is considered positive for integers).

    - For floating point numbers the bit of sign is taken into account and so
    we always have `signnz(-z) == -signnz(z)` except is the entry is a NaN
    (in this later case the result is undefined).

    @see Mzero, sign, is_negative, is_positive

    @par Example:

      @snippet signnz.cpp signnz

    @par Possible output:

      @snippet signnz.txt signnz

  **/
  Value signnz(Value const& x);
} }
#endif

#include <boost/simd/function/scalar/signnz.hpp>
#include <boost/simd/function/simd/signnz.hpp>

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
/******************************************************************************
 * Author:   Laurent Kneip                                                    *
 * Contact:  kneip.laurent@gmail.com                                          *
 * License:  Copyright (c) 2013 Laurent Kneip, ANU. 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 ANU 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 ANU OR THE 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.                                                               *
 ******************************************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <iomanip>
#include <limits.h>
#include <Eigen/Eigen>
#include <opengv/absolute_pose/methods.hpp>
#include <opengv/absolute_pose/NoncentralAbsoluteMultiAdapter.hpp>
#include <opengv/sac/MultiRansac.hpp>
#include <opengv/sac_problems/absolute_pose/MultiNoncentralAbsolutePoseSacProblem.hpp>
#include <sstream>
#include <fstream>

#include "random_generators.hpp"
#include "experiment_helpers.hpp"
#include "time_measurement.hpp"

using namespace std;
using namespace Eigen;
using namespace opengv;

int main( int argc, char** argv )
{
  //initialize random seed
  initializeRandomSeed();

  //set experiment parameters
  double noise = 0.5;
  double outlierFraction = 0.1;
  size_t pointsPerCam = 25;
  int numberCameras = 4;

  //create a random viewpoint pose
  translation_t position = generateRandomTranslation(2.0);
  rotation_t rotation = generateRandomRotation(0.5);

  //create a random camera-system
  translations_t camOffsets;
  rotations_t camRotations;
  generateRandomCameraSystem( numberCameras, camOffsets, camRotations );

  //derive correspondences based on random point-cloud
  std::vector<std::shared_ptr<points_t> > multiPoints;
  std::vector<std::shared_ptr<bearingVectors_t> > multiBearingVectors;
  std::vector< std::shared_ptr<Eigen::MatrixXd> > gt;
  generateMulti2D3DCorrespondences(
      position, rotation, camOffsets, camRotations,
      pointsPerCam, noise, outlierFraction,
      multiPoints, multiBearingVectors, gt );

  //print the experiment characteristics
  printExperimentCharacteristics(
      position, rotation, noise, outlierFraction );

  //create a non-central absolute adapter
  absolute_pose::NoncentralAbsoluteMultiAdapter adapter(
      multiBearingVectors,
      multiPoints,
      camOffsets,
      camRotations );

  //Create a AbsolutePoseSacProblem and Ransac
  //The method is set to GP3P
  sac::MultiRansac<
      sac_problems::absolute_pose::MultiNoncentralAbsolutePoseSacProblem> ransac;
  std::shared_ptr<
      sac_problems::absolute_pose::MultiNoncentralAbsolutePoseSacProblem> absposeproblem_ptr(
      new sac_problems::absolute_pose::MultiNoncentralAbsolutePoseSacProblem(
      adapter ));

  ransac.sac_model_ = absposeproblem_ptr;
  ransac.threshold_ = 1.0 - cos(atan(sqrt(2.0)*0.5/800.0));
  ransac.max_iterations_ = 50;

  //Run the experiment
  struct timeval tic;
  struct timeval toc;
  gettimeofday( &tic, 0 );
  ransac.computeModel();
  gettimeofday( &toc, 0 );
  double ransac_time = TIMETODOUBLE(timeval_minus(toc,tic));

  //print the results
  std::cout << "the ransac results is: " << std::endl;
  std::cout << ransac.model_coefficients_ << std::endl << std::endl;
  std::cout << "Ransac needed " << ransac.iterations_ << " iterations and ";
  std::cout << ransac_time << " seconds" << std::endl << std::endl;
  size_t numberInliers = 0;
  for(size_t i = 0; i < ransac.inliers_.size(); i++)
    numberInliers += ransac.inliers_[i].size();
  std::cout << "the number of inliers is: " << numberInliers;
  std::cout << std::endl << std::endl;
  std::cout << "the found inliers are: " << std::endl;
  for(size_t i = 0; i < ransac.inliers_.size(); i++)
  {
    for(size_t j = 0; j < ransac.inliers_[i].size(); j++)
      std::cout << ransac.inliers_[i][j] << " ";
  }
  std::cout << std::endl << std::endl;
}