text:
/*
Copyright (C) 2012 Mathias Eitz and Ronald Richter.
All rights reserved.

This file is part of the imdb library and is made available under
the terms of the BSD license (see the LICENSE file).
*/

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <direct.h>
#include <io.h>

#include <boost/algorithm/string.hpp>

#include <opencv2/highgui/highgui.hpp>

//util/
#include <types.hpp>
#include <quantizer.hpp>
#include <kmeans.hpp>
//io/
#include <property_reader.hpp>
#include <cmdline.hpp>
#include <filelist.hpp>
//descriptors/
#include <generator.hpp>
//search/
#include <linear_search.hpp>
#include <bof_search_manager.hpp>
#include <linear_search_manager.hpp>
#include <distance.hpp>
//myIO/
//#include "myIO.h"

//#define SHOW_RESULT
#define SAVE_SCORE

using namespace imdb;

template <class search_t>
void image_search(const anymap_t& data, const search_t& search, size_t num_results, vector<dist_idx_t>& results)
{
    typedef typename search_t::descr_t descr_t;
    descr_t descr = get<descr_t>(data, "features");
    search.query(descr, num_results, results);
}

class command_search : public Command
{
public:

    command_search()
        : Command("image_search [options]")
        , _co_query_image("queryimage"        , "q", "filename of images filelist to be used as the query [required]")
        , _co_search_ptree("searchptree"      , "s", "filename of the JSON file containing parameters for the search manager [optional, if not provided, --searchparams must be given]")
        , _co_search_params("searchparams"    , "m", "parameters for the search manager [optional, if not provided, --searchptree must be given]")
        , _co_vocabulary("vocabulary"         , "v", "filename of vocabulary used for quantization [optional, only required with bag-of-features search]")
        , _co_filelist("filelist"             , "l", "filename of images filelist [required]")
        , _co_generator_name("generatorname"  , "g", "name of generator [optional, if given, we will use generator's default parameters and ignore --generatorptree]")
        , _co_generator_ptree("generatorptree", "p", "filename of the JSON file containing generator name and parameters [optional, if not provided, generator's default values are used']")
        , _co_num_results  ("numresults"      , "n", "number of results to search for [optional, if not provided all distances get computed]")
		, _co_wkdir("working dir"             , "r", "directory path of the query [required]")
		, _co_outdir("saving dir"             , "o", "the path of the retrieval list saved in [optional, if not provided, will be set as \"retrieval_list\"]")
    {
        add(_co_query_image);
        add(_co_search_ptree);
        add(_co_search_params);
        add(_co_vocabulary);
        add(_co_filelist);
        add(_co_generator_ptree);
        add(_co_num_results);
        add(_co_generator_name);
		add(_co_wkdir);
		add(_co_outdir);
    }

    bool run(const std::vector<std::string>& args)
    {
        if (args.size() == 0)
        {
            print();
            return false;
        }

        warn_for_unknown_option(args);

        string in_queryimage;
        string in_searchptree;
        string in_filelist;
        string in_generatorptree;
        string in_generatorname;
        string in_vocabulary;
		string in_wkdir;
		string in_outdir;

        // this default value will make the search managers search
        // for all images if the user does not provide a value
        size_t in_numresults = std::numeric_limits<size_t>::max();

        // check that the required options are available
        if (!_co_query_image.parse_single<string>(args, in_queryimage) || !_co_filelist.parse_single<string>(args, in_filelist) || !_co_wkdir.parse_single(args, in_wkdir))
        {
            print();
            return false;
        }

        // -----------------------------------------------------------------------------------
        // either searchptree or searchparams must be given
        ptree search_params;
        vector<string> in_searchparams;
        if (_co_search_ptree.parse_single<string>(args, in_searchptree))
        {
            boost::property_tree::read_json(in_searchptree, search_params);
        }
        else if (_co_search_params.parse_multiple<string>(args, in_searchparams))
        {
            for (size_t i = 0; i < in_searchparams.size(); i++)
            {
                vector<string> pv;
                boost::algorithm::split(pv, in_searchparams[i], boost::algorithm::is_any_of("="));

                if (pv.size() != 1 && pv.size() != 2)
                {
                    std::cerr << "image_search: cannot parse search manager parameter: " << in_searchparams[i] << std::endl;
                    return false;
                }
                search_params.put(pv[0], (pv.size() == 2) ? pv[1] : "");
            }

        }
        else
        {
            print();
            return false;
        }
        // -----------------------------------------------------------------------------------

        // try to parse the optional num_results parameter
        _co_num_results.parse_single<size_t>(args, in_numresults);
		// try to parse the optional outdir parameter
		if (!_co_outdir.parse_single<string>(args, in_outdir)) {
			in_outdir = "retrieval_list";
		}

        // -----------------------------------------------------------------
        // create the generator; we have the following rule:
        // a) if the user provides a generator name, we use this and ignore an additional generator ptree
        // b) if no generator name but ptree is provided, we use this
        shared_ptr<Generator> gen;
        if (_co_generator_name.parse_single<string>(args, in_generatorname))
        {
            gen = Generator::from_default_parameters(in_generatorname);
        }
        else if (_co_generator_ptree.parse_single<string>(args, in_generatorptree))
        {
            gen = Generator::from_parameters_file(in_generatorptree);
        }
        else
        {
            std::cerr << "image_search: must provide either generator name or ptree" << std::endl;
            std::cerr << "received args: generatorname=" << in_generatorname << "; generatorptree=" << in_generatorptree << std::endl;

            print();
            return false;
        }
        // -----------------------------------------------------------------

		// load img set file list
        FileList imageFiles;
        imageFiles.load(in_filelist);
		// load query img set file list
		FileList queryFiles;

		queryFiles.set_root_dir(in_wkdir);
		queryFiles.load(in_queryimage);

		// -----------------------------------------------------------------
		// processing
		// -----------------------------------------------------------------
		std::cout << "----------------------------" << std::endl;
		std::cout << "image_search: now processing..." << std::endl;
		std::cout << "image_search: working dir is " << in_wkdir << std::endl;
		for (int i = 0; i < queryFiles.size(); i++)
		{
			std::cout << "image_search: progress " << i + 1 << '/' << queryFiles.size() << std::endl;

			std::istringstream sin(queryFiles.get_relative_filename(i));
			string retrievalClass;
			string retrievalFile;
			std::getline(sin, retrievalClass, '/');
			std::getline(sin, retrievalFile, '.');
			string outRetrievalListDir = in_outdir + '/' + retrievalClass;
			string outRetrievalListPath = in_outdir + '/' + retrievalClass + '/' + retrievalFile;
			if ((_access(outRetrievalListPath.c_str(), 0)) != -1) {
				std::cout << "image_search: progress " << i + 1 << " skipped" << std::endl;
				continue;
			}

			string each_queryimg = queryFiles.get_filename(i);
			mat_8uc3_t image = cv::imread(each_queryimg, 1);
			anymap_t data;
			data["image"] = image;

			gen->compute(data);

			vector<dist_idx_t> results;

			if (search_params.get<std::string>("search_type") == "BofSearch")
			{

				// parameter --vocabulary must be given
				if (!_co_vocabulary.parse_single<string>(args, in_vocabulary))
				{
					std::cerr << "image_search: when using bag-of-features search, you must also provide the --vocabulary commandline option" << std::endl;
					print();
					return false;
				}

				vec_vec_f32_t vocabulary;
				read_property(vocabulary, in_vocabulary);

				// quantize
				quantize_fn quantizer = quantize_hard<vec_f32_t, imdb::l2norm_squared<vec_f32_t> >();
				vec_vec_f32_t quantized_samples;

				const vec_vec_f32_t& samples = boost::any_cast<vec_vec_f32_t>(data["features"]);
				quantize_samples_parallel(samples, vocabulary, quantized_samples, quantizer);

				vec_f32_t histvw;
				build_histvw(quantized_samples, vocabulary.size(), histvw, false);

				// initialize search manager and run query
				BofSearchManager bofSearch(search_params);
				bofSearch.query(histvw, in_numresults, results);
			}

			else if (search_params.get<std::string>("search_type") == "LinearSearch")
			{
				// Tensor descriptor is a bit of a special case as we additionally
				// need to pass a 'mask' to the distance function, so we replicate
				// most of the functionality implemented in LinearSearchManager
				if (gen->parameters().get<string>("name") == "tensor")
				{
					string filename = search_params.get<string>("descriptor_file");
					vec_vec_f32_t features;
					read_property(features, filename);

					const vec_f32_t& descr = get<vec_f32_t>(data, "features");
					const vector<bool>& mask = get<vector<bool> >(data, "mask");
					std::cout << "mask size=" << mask.size() << std::endl;
					dist_frobenius<vec_f32_t> distfn;
					distfn.mask = &mask;
					linear_search(descr, features, results, in_numresults, distfn);

				}
				else
				{
					LinearSearchManager search(search_params);
					image_search(data, search, in_numresults, results);
				}
			}
			else
			{
				std::cerr << "unsupported search type" << std::endl;
			}

#ifdef SHOW_RESULT
			// output results on the console
			// use piping to store in a text file (for now)
			std::cout << "----------------------------" << std::endl;
			std::cout << "-idx--score--filename-------" << std::endl;
			std::cout << "----------------------------" << std::endl;
			for (size_t i = 0; i < results.size(); i++) {
				string filename = imageFiles.get_relative_filename(results[i].second);
				std::cout.precision(9);
				std::cout << i << " " << (float)results[i].first << " " << filename << std::endl;
			}
#endif // SHOW_RESULT

			// store as csv
			// mkdir outdir/class
			if (_mkdir(in_outdir.c_str()) != -1) {
				printf("\nCreate Dir: %s\n", in_outdir.c_str());
			}
			if (_mkdir(outRetrievalListDir.c_str()) != -1) {
				printf("\nCreate Dir: %s\n", outRetrievalListDir.c_str());
			}

			std::ofstream str;
			str.open(outRetrievalListPath.c_str());
			if (str.is_open()) {
				for (size_t i = 0; i < results.size(); i++) {
					string filename = imageFiles.get_relative_filename(results[i].second);
					std::istringstream sin1(filename);
					std::getline(sin1, filename, '.');
#ifdef SAVE_SCORE
					double score = results[i].first;
					str << std::to_string(score) << ' ' << filename << '\n';
#else
					str << filename << '\n';
#endif
				}
			}
		}

        return true;
    }

private:

    CmdOption _co_query_image;
    CmdOption _co_search_ptree;
    CmdOption _co_search_params;
    CmdOption _co_vocabulary;
    CmdOption _co_filelist;
    CmdOption _co_generator_name;
    CmdOption _co_generator_ptree;
    CmdOption _co_num_results;
	CmdOption _co_wkdir;
	CmdOption _co_outdir;
};

int main(int argc, char *argv[])
{

    command_search cmd;
    bool okay = cmd.run(argv_to_strings(argc-1, &argv[1]));
    return okay ? 0:1;
}


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

#include <boost/range/adaptor/reversed.hpp>

#include "chainparams.h"
#include "checkpoints.h"
#include "uint256.h"

namespace Checkpoints
{
    bool CheckHardened(int nHeight, const uint256& hash)
    {
        const MapCheckpoints& checkpoints = Params().Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    CBlockIndex* GetLastCheckpoint(const BlockMap& mapBlockIndex)
    {
        const MapCheckpoints& checkpoints = Params().Checkpoints().mapCheckpoints;

        for (auto const& i : boost::adaptors::reverse(checkpoints))
        {
            const uint256& hash = i.second;
            BlockMap::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return nullptr;
    }
}

ext: cpp

max_stars_repo_name: nathanielcwm/Gridcoin-Research

max_issues_repo_name: nathanielcwm/Gridcoin-Research

max_forks_repo_name: cyrossignol/Gridcoin-Research


text:
/*
  Copyright (c) 2012 by Procera Networks, Inc. ("PROCERA")

  Permission to use, copy, modify, and/or distribute this software for
  any purpose with or without fee is hereby granted, provided that the
  above copyright notice and this permission notice appear in all
  copies.

  THE SOFTWARE IS PROVIDED "AS IS" AND PROCERA DISCLAIMS ALL WARRANTIES
  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL PROCERA BE LIABLE FOR
  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "koi.hpp"

#include "file.hpp"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include "stringutil.hpp"

using namespace std;
using namespace boost;

namespace {
	template <typename T>
	T clamp(T val, const T& lo, const T& hi) {
		if (val < lo)
			val = lo;
		else if (val > hi)
			val = hi;
		return val;
	}
}

namespace koi {
	bool debug_mode = false;

	net::endpoint parse_endpoint(const char* str, uint16_t default_port) {
		boost::system::error_code err;
		uint16_t port = default_port;
		net::ipaddr ip;
		try {
			regex v4matcher("^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]+\\:[0-9]{1,5}$");
			regex v6matcher("^\\[[0-9a-f:]+\\]\\:[0-9]{1,5}$");

			if (regex_match(str, v4matcher)) {
				const char* portsplit = strrchr(str, ':');
				if (portsplit == 0) {
					LOG_ERROR("Error in regex: %s matched", str);
					return net::endpoint();
				}
				string sport(portsplit+1);
				string ipa(str, portsplit);
				port = lexical_cast<uint16_t>(sport);
				ip = net::ipaddr::from_string(ipa, err);
			} else if (regex_match(str, v6matcher)) {
				const char* portsplit = strrchr(str, ':');
				if (portsplit == 0) {
					LOG_ERROR("Error in regex: %s matched", str);
				}
				string sport(portsplit+1);
				string ipa(str+1, portsplit-1);
				port = lexical_cast<uint16_t>(sport);
				ip = net::ipaddr::from_string(ipa, err);
			}
			else {
				ip = net::ipaddr::from_string(str, err);
			}
		}
		catch(bad_lexical_cast& e) {
			LOG_TRACE("Caught bad lexical cast: %s", e.what());
			return net::endpoint();
		}
		if (err) {
			return net::endpoint();
		}
		else {
			return net::endpoint(ip, port);
		}
	}

	string to_string(const net::endpoint& ep) {
		stringstream ss;
		ss << ep;
		return ss.str();
	}

	std::ostream & operator<<(std::ostream & o, const net::endpoint& ep) {
		const net::ipaddr& addr = ep.address();
		if (addr.is_v6()) {
			o << "[" << addr << "]:";
		}
		else {
			o << addr << ":";
		}
		o << ep.port();
		return o;
	}

	const char* state_to_string(State s) {
		static const char* state_trans[] = {
			"Failed",
			"Disconnected",
			"Stopped", // not running/not voting
			"Live", // running/not voting
			"Slave", // running slave/not voting
			"Master",// running master/not voting
			"Elector", // voting but not executing services
			"Other" // non-elector, non-voting cluster member
		};
		if (s >= 0 && s < (int)ASIZE(state_trans))
			return state_trans[s];
		return "Unknown";
	}

	const char* mode_to_string(RunnerMode m) {
		static const char* mode_trans[] = {
			"Passive",
			"Active"
		};
		if (m >= 0 && m < (int)ASIZE(mode_trans))
			return mode_trans[m];
		return "Unknown";
	}

	void readtime(const boost::property_tree::ptree& tr, uint64_t& t, const char* s) {
		string val = tr.get<string>(s, lexical_cast<string>((uint32_t)(t/units::milli))+"ms");
		if (endswith(val, "ms")) {
			t = lexical_cast<uint64_t>(val.substr(0, val.length()-2))*units::micro/units::milli;
		}
		else if (endswith(val, "m")) {
			t = lexical_cast<uint64_t>(val.substr(0, val.length()-1))*60*units::micro;
		}
		else if (endswith(val, "h")) {
			t = lexical_cast<uint64_t>(val.substr(0, val.length()-1))*60*60*units::micro;
		}
		else if (endswith(val, "s")) {
			t = lexical_cast<uint64_t>(val.substr(0, val.length()-1))*units::micro;
		}
		else { // default is ms
			t = lexical_cast<uint64_t>(val)*units::micro/units::milli;
		}
	}

	settings::settings() :
		_starttime(),
		_uuid(uuids::nil_uuid()),
		_name(),
		_elector(true),
		_runner(false),
		_force_restart(false),
		_port(KOI_DEFAULT_CLUSTER_PORT),
		_cluster_maintenance(false),
		_boot_count(0),

		_reuse_address(true),
		_incremental_port(false),

		_loglevel(logging::Trace),
		_cluster_id(13),
		_cluster_quorum(0),

		_pass("secret"),
		_transport(),

		_services_folder(KOI_CONFIG_SERVICES),
		_services_workingdir(KOI_CONFIG_SERVICES),

		// time units are in microseconds
		_on_none("none", 1*units::micro),
		_on_start("start", uint64_t(360)*units::micro),
		     _on_stop("stop", uint64_t(360)*units::micro),
		     _on_status("status", uint64_t(120)*units::micro),
		     _on_promote("promote", 30*units::micro),
		     _on_demote("demote", 30*units::micro),
		     _on_failed("failed", 20*units::micro),

		     _status_interval(10*units::micro),
		     _cluster_update_interval(units::micro),
		     _state_update_interval(units::micro/3),
		     _runner_tick_interval(1*units::micro),
		     _elector_tick_interval(1*units::micro),
		     _runner_elector_lost_time(3*units::micro),
		     _runner_elector_gone_time(60*8*units::micro), //8 minutes
		     _quorum_demote_time(10*units::micro), // 10 seconds
		     _mainloop_sleep_time(units::micro/3),
		     _master_dead_time(5*units::micro),
		     _elector_startup_tolerance(5*units::micro),
		     _elector_initial_promotion_delay(60*units::micro),
		     _service_auto_recover(120),
		     _auto_recover_time(10*units::micro),
		     _auto_recover_wait_factor(1),
		     _service_failcount_reset_time(60L*30L*units::micro),
		     _runner_failure_promotion_timeout(60L*units::micro) {
	}

	service_event::service_event(const char* name, uint64_t t) : _name(name), _timeout(t) {
	}

	const service_event* settings::svc(const char* name) const {
		/*
		  if (strcmp(name, "none") == 0) {
		  return &_on_none;
		  }
		  else if (strcmp(name, "start") == 0) {
		  return &_on_start;
		  }
		  else if (strcmp(name, "stop") == 0) {
		  return &_on_stop;
		  }
		  else if (strcmp(name, "status") == 0) {
		  return &_on_status;
		  }
		  else if (strcmp(name, "promote") == 0) {
		  return &_on_promote;
		  }
		  else if (strcmp(name, "demote") == 0) {
		  return &_on_demote;
		  }
		  else if (strcmp(name, "failed") == 0) {
		  return &_on_failed;
		  }
		  else {
		  return &_on_none;
		  }
		*/
		switch (name[3]) {
		case 'e': return &_on_none;
		case 'r': return &_on_start;
		case 'p': return &_on_stop;
		case 't': return &_on_status;
		case 'm': return &_on_promote;
		case 'o': return &_on_demote;
		case 'l': return &_on_failed;
		default: break;
		}
		return &_on_none;
	}

	bool settings::read_config(const vector<string>& configs, bool verbose) {
		using namespace property_tree;
		ptree pt;

		try {
			string cfgerr = "";
			bool cfgfound = false;
			for (size_t i = 0; i < configs.size(); ++i) {
				try {
					info_parser::read_info(configs[i], pt);
					cfgfound=true;
				}
				catch (const ptree_error& e) {
					if (cfgerr.length())
						cfgerr += ", ";
					cfgerr += e.what();
				}
			}
			if (!cfgfound && verbose) {
				LOG_TRACE("No config file found: %s", cfgerr.c_str());
			}

			boost::system::error_code err;

			_elector = pt.get<bool>("node.elector", _elector);
			_runner = pt.get<bool>("node.runner", _runner);
			_force_restart = pt.get<bool>("node.force_restart", _force_restart);

			_port = pt.get<uint16_t>("node.port", _port);

			_cluster_maintenance = pt.get<bool>("node.maintenance", _cluster_maintenance);

			_reuse_address = pt.get<bool>("node.reuse_address", _reuse_address);
			_incremental_port = pt.get<bool>("node.increment_port", _incremental_port);

			{
				const char* loglevels[] = {"trace", "info", "warn", "error"};
				string loglevel_name = pt.get<string>("node.loglevel", loglevels[logging::Trace]);
				transform(loglevel_name.begin(), loglevel_name.end(), loglevel_name.begin(), ::tolower);
				for (size_t i = 0; i < ASIZE(loglevels); ++i)
					if (loglevel_name == loglevels[i])
						_loglevel = (LogLevel)i;
			}

			_cluster_id = pt.get<int32_t>("cluster.id", _cluster_id);
			_cluster_quorum = pt.get<int32_t>("cluster.quorum", _cluster_quorum);

			readtime(pt, _on_start._timeout, "service.start_timeout");
			readtime(pt, _on_stop._timeout, "service.stop_timeout");
			readtime(pt, _on_status._timeout, "service.status_timeout");
			readtime(pt, _on_promote._timeout, "service.promote_timeout");
			readtime(pt, _on_demote._timeout, "service.demote_timeout");
			_service_auto_recover = pt.get<uint32_t>("service.auto_recover", (uint32_t)_service_auto_recover);
			_auto_recover_wait_factor = pt.get<int>("service.auto_recover_wait_factor", _auto_recover_wait_factor);
			if (_auto_recover_wait_factor < 1 || _auto_recover_wait_factor > AUTO_RECOVER_MAX_FACTOR) {
				LOG_WARN("Auto recover wait factor clamped %d <= f <= %d",
				         1, AUTO_RECOVER_MAX_FACTOR);
				_auto_recover_wait_factor = clamp(_auto_recover_wait_factor,
				                                  1, AUTO_RECOVER_MAX_FACTOR);
			}

			_pass = pt.get<string>("cluster.password", _pass);
			_transport = pt.get<string>("cluster.transport", _transport);

			_services_folder = pt.get<string>("service.folder", _services_folder);
			_services_workingdir = pt.get<string>("service.workingdir", _services_workingdir);

			readtime(pt, _status_interval, "time.status_interval");
			readtime(pt, _cluster_update_interval, "time.cluster_update_interval");
			readtime(pt, _state_update_interval, "time.state_update_interval");
			readtime(pt, _elector_tick_interval, "time.elector_tick_interval");
			readtime(pt, _runner_tick_interval, "time.runner_tick_interval");
			readtime(pt, _runner_elector_lost_time, "time.elector_lost_time");
			readtime(pt, _runner_elector_gone_time, "time.elector_gone_time");
			readtime(pt, _quorum_demote_time, "time.quorum_demote_time");
			readtime(pt, _mainloop_sleep_time, "time.mainloop_sleep_time");
			readtime(pt, _master_dead_time, "time.master_dead_time");
			readtime(pt, _elector_startup_tolerance, "time.elector_startup_tolerance");
			readtime(pt, _elector_initial_promotion_delay, "time.initial_promotion_delay");

			readtime(pt, _auto_recover_time, "time.auto_recover_time");
			readtime(pt, _service_failcount_reset_time, "time.failcount_reset");
			readtime(pt, _runner_failure_promotion_timeout, "time.failure_promotion_timeout");

			logging::set_log_level(_loglevel);
		}
		catch (const ptree_error& e) {
			LOG_ERROR("Configuration error: %s", e.what());
			return false;
		}

		return true;
	}

	bool settings::boot(vector<string> const& configs, bool verbose) {
		// load initial config
		// setup basic environment
		// verify machine
		if (_starttime == posix_time::ptime(posix_time::not_a_date_time)) {
			_starttime = posix_time::microsec_clock::universal_time();
		}

		_uuid = boost::uuids::random_generator()();
		if (_name == "")
			_name = asio::ip::host_name();

		if (configs.size() && read_config(configs, verbose)) {
			if (verbose) {
				LOG_INFO("Name: %s", _name.c_str());
				stringstream suid;
				suid << _uuid;
				LOG_INFO("UUID: %s", suid.str().c_str());
			}

			if (verbose) {
				LOG_INFO("Local: 0.0.0.0:%d", (int)_port);
				LOG_INFO("Elector: %s", _elector ? "Yes" : "No");
				LOG_INFO("Runner: %s", _runner ? "Yes" : "No");
			}
			return true;
		}
		else {
			LOG_ERROR("Failed to read config, terminating.");
		}
		return false;
	}
}

max_stars_repo_name: yogarajbaskaravel/koi

max_issues_repo_name: yogarajbaskaravel/koi

max_forks_repo_name: yogarajbaskaravel/koi


text:
#include <iostream>

#include <cstdlib>
#include <cstring>

#include <boost/program_options.hpp>

#include <Task/Task.hpp>
#include <Util/Hash.hpp>

namespace po = boost::program_options;

Knock::TaskResult onHashFile( Knock::CmdLineContext& cmdLine )
{
    static const char* funcName( "onHashFile" );

    if ( !cmdLine.has( Knock::HashFileCmd ) ) {
        return Knock::TaskResult::Continue;
    }

    if ( !cmdLine.has( Knock::InputCmd ) ) {
        std::cout << "[Knock] please specify input via --input=xxx\n";
        return Knock::TaskResult::Failed;
    }

    std::string digest = Knock::Hash::fileSha256(
        cmdLine.getOptionValue<std::string>( Knock::InputCmd, "" ) );
    std::cout << "SHA256: " << digest << std::endl;

    return Knock::TaskResult::Done;
}

int main( int argc, char* argv[] )
{
    using namespace std;
    using namespace Knock;

    try {
        po::options_description desc( "Allowed options" );
        desc.add_options()
            ( HelpCmd,
              "Show help message" )
            ( InputCmd,
              po::value<std::string>(),
              "Used with other commands to specify the input" )
            ( OutputCmd,
              po::value<std::string>(),
              "Used with other command to specify the output file/directory/..." )
            ( HashFileCmd,
              po::value<std::string>(),
              "Show hash digest of specified file. [sha256]" );

        if ( 1 == argc ) {
            cout << desc << endl;
            return 0;
        }

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

        if ( vm.count( HelpCmd ) ) {
            cout << desc << endl;
            return 0;
        }

        struct CmdDispatchTable {
            const char* cmd;
            CmdHandler  handler;
        } table[] = {
            { Knock::HashFileCmd, &onHashFile }
        };

        Knock::CmdLineContext   cmdLine( vm );
        for ( auto& item : table ) {
            if ( !vm.count( item.cmd ) ) {
                continue;
            }

            if ( Knock::TaskResult::Continue == item.handler( cmdLine ) ) {
                break;
            }
        }
    }
    catch ( std::exception& ex ) {
        cout << "Exception: " << ex.what() << endl;;
    }

    return 0;
}

max_stars_repo_name: WCChou/Knock

max_issues_repo_name: WCChou/Knock

max_forks_repo_name: WCChou/Knock


text:
#ifndef PDDL_PLANNER_H
#define PDDL_PLANNER_H

#include <string>
#include <stdexcept>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <boost/thread/mutex.hpp>
#include <boost/thread.hpp>

#include "representation/Problem.hpp"
#include "PDDLPlannerTypes.hpp"

/**
 * \mainpage PDDL based planning
 * This library provides a somewhat generalized interface for planning and allow to embed a selection of
 * PDDL planners.
 *
 * While by default it includes integration for the LAMA planner and the FDSS planners, additional planners can be added dynamically
 * using the pddl_planner::Planning::registerPlanner function.
 *
 * \verbatim
   #include <pddl_planner/Planning.hpp>
   ...
   using namespace pddl_planner;
   Planning planning;

   // Option 1 -- directly adding the domain and problem description
   std::string domainDescription = "(define (domain rimres)\n(:requirements :strips :equality :typing :conditional-effects)\n(:types location physob_id physob_type)\n(:constants sherpa crex payload - physob_type)\n(:predicates ( at ?x - physob_id ?l - location)\n( is_a ?x - physob_id ?r - physob_type)\n( connected ?x ?y - physob_id)\n( cannot_move ?x - physob_id)\n)\n\n(:action move\n :parameters (?obj - physob_id ?m ?l - location)\n:precondition ( and (at ?obj ?m) (not (= ?m ?l)) (not (cannot_move ?obj) ))\n :effect (and (at ?obj ?l) (not (at ?obj ?m))\n (forall (?z)\n (when (and (connected ?z ?obj) (not (= ?z ?obj)))\n (and (at ?z ?l) (not (at ?z ?m)))\n)))\n)\n (:action move_into_range\n :parameters (?x ?y - physob_id ?m ?l - location)\n :precondition (and (not (cannot_move ?x)) (at ?x ?m) (at ?y ?l) )\n :effect (and (at ?x ?l) (at ?y ?l) (not (at ?x ?m)))\n)\n (:action connect\n :parameters (?x ?y - physob_id ?l - location)\n :precondition (and (at ?x ?l) (at ?y ?l))\n :effect (and (connected ?x ?y) (cannot_move ?y))\n)\n(:action disconnect\n :parameters (?x ?y - physob_id)\n :precondition (and (not (= ?x ?y)) (connected ?x ?y)) \n :effect (and (not (connected ?x ?y)) (not (cannot_move ?y)))\n)\n)\n";

   std::string problemDescription = "(define (problem rimres-1)\n (:domain rimres)\n (:objects\n sherpa_0 crex_0 pl_0 - physob_id\n location_s0 location_c0 location_p0 - location\n mission1 - location\n)\n (:init \n (is_a sherpa_0 sherpa)\n (is_a crex_0 crex)\n (is_a pl_0 payload)\n (at sherpa_0 location_s0)\n (at crex_0 location_c0)\n (at pl_0 location_p0)\n (cannot_move pl_0)\n)\n (:goal (and \n (connected sherpa_0 crex_0) \n (connected sherpa_0 pl_0)\n (at sherpa_0 mission1)\n)\n)\n)\n";

   planning.setDomainDescription("rimres",domainDescription);
   PlanCandidates planCandidates = planning.plan(problemDescription);

   // Option 2 -- using a programmatic approach to create the domain and problem description
   using namespace pddl_planner;

   Domain domain("rimres");
   domain.addRequirement("strips");
   domain.addRequirement("equality");
   domain.addRequirement("typing");
   domain.addRequirement("conditional-effects");

   domain.addType("location");
   domain.addType("physob_id");
   domain.addType("physob_type");

   domain.addConstant( Constant("sherpa","physob_type") );
   domain.addConstant( Constant("crex","physob_type") );
   domain.addConstant( Constant("payload","physob_type") );

   domain.addPredicate( Predicate("at", TypedItem("?x","physob_id"),TypedItem("?l","physob_id")) );
   domain.addPredicate( Predicate("is_a", TypedItem("?x","physob_id"),TypedItem("?r","physob_type")) );
   domain.addPredicate( Predicate("connected", TypedItem("?x","physob_id"),TypedItem("?y","physob_id")) ) ;
   domain.addPredicate( Predicate("cannot_move", TypedItem("?x","physob_id")) );

   // Action move
   representation::Action move("move", TypedItem("?obj","physob_id"), TypedItem("?m","location"), TypedItem("?l","location"));

   Expression precondition("and", Expression("at", "?obj", "?m"), Expression("not", Expression("=", "?m", "?l")), Expression("not", Expression("cannot_move","?obj")));

   Expression effect("and", Expression("at","?obj","?l"), Expression("not", Expression("at","?obj","?m")), Expression("forall", Expression("?z"), Expression("when", Expression("and", Expression("connected","?z","?obj"), Expression("not", Expression("=","?z","?obj"))), Expression("and", Expression("at","?z","?l"), Expression("not", Expression("at","?z","?m"))))));

   move.addPrecondition(precondition);
   move.addEffect(effect);
   domain.addAction(move);

   // Action move
   representation::Action move("move", TypedItem("?obj","physob_id"), TypedItem("?m","location"), TypedItem("?l","location"));
   {
       Expression precondition("and", Expression("at", "?obj", "?m"), Expression("not", Expression("=", "?m", "?l")), Expression("not", Expression("cannot_move","?obj")));

       Expression effect("and", Expression("at","?obj","?l"), Expression("not", Expression("at","?obj","?m")), Expression("forall", Expression("?z"), Expression("when", Expression("and", Expression("connected","?z","?obj"), Expression("not", Expression("=","?z","?obj"))), Expression("and", Expression("at","?z","?l"), Expression("not", Expression("at","?z","?m"))))));

       move.addPrecondition(precondition);
       move.addEffect(effect);
       domain.addAction(move);
   }

   // Action move_into_range
   representation::Action move_into_range("move_into_range", TypedItem("?x","physob_id"), TypedItem("?y","physob_id"), TypedItem("?m","location"), TypedItem("?l","location"));
   {
       Expression precondition("and", Expression("not", Expression("cannot_move","?x")), Expression("at","?x","?m"), Expression("at","?y","?l"));
       Expression effect("and", Expression("at","?x","?l"), Expression("at","?y","?l"), Expression("not", Expression("at","?x","?m")));
       move_into_range.addPrecondition(precondition);
       move_into_range.addEffect(effect);
       domain.addAction(move_into_range);
   }

   // Action connect
   representation::Action connect("connect", TypedItem("?x","physob_id"), TypedItem("?y","physob_id"), TypedItem("?l","location"));
   {
       Expression precondition("and", Expression("at","?x","?l"), Expression("at","?y","?l"));
       Expression effect("and", Expression("connected","?x","?y"), Expression("cannot_move","?y"));
       connect.addPrecondition(precondition);
       connect.addEffect(effect);
       domain.addAction(connect);
   }

   // Action connect
   representation::Action disconnect("disconnect", TypedItem("?x","physob_id"), TypedItem("?y","physob_id"));
   {
       Expression precondition("and", Expression("not", Expression("=","?x","?y")), Expression("connected","?x","?y"));
       Expression effect("and", Expression("not", Expression("connected","?x","?y")), Expression("not", Expression("cannot_move","?x")));
       disconnect.addPrecondition(precondition);
       disconnect.addEffect(effect);
       domain.addAction(disconnect);
   }

   representation::Problem problem("rimres-1",domain);
   problem.addObject( Constant("sherpa_0","physob_id"));
   problem.addObject( Constant("crex_0","physob_id"));
   problem.addObject( Constant("pl_0","physob_id"));
   problem.addObject( Constant("location_s0","location"));
   problem.addObject( Constant("location_c0","location"));
   problem.addObject( Constant("location_p0","location"));
   problem.addObject( Constant("mission1","location"));

   problem.addInitialStatus( Expression("is_a","sherpa_0","sherpa") );
   problem.addInitialStatus( Expression("is_a","crex_0","crex") );
   problem.addInitialStatus( Expression("is_a","pl_0","payload") );
   problem.addInitialStatus( Expression("at","sherpa_0","location_s0") );
   problem.addInitialStatus( Expression("at","crex_0","location_c0") );
   problem.addInitialStatus( Expression("at","pl_0","location_p0") );
   problem.addInitialStatus( Expression("cannot_move", "pl_0") );

   Expression subgoal0("connected","sherpa_0","crex_0");
   Expression subgoal1("connected","sherpa_0","pl_0");
   Expression subgoal2("at","sherpa_0","mission1");
   problem.setGoal(Expression("and", subgoal0, subgoal1, subgoal2));

   Planning planning;
   PlanCandidates planCandidates = planning.plan(problem);
 \endverbatim
 *
 * \section sec Weblinks and Resources
 * Further information available at:
 *     - http://ipc.informatik.uni-freiburg.de/PddlResources
 *     - http://www.plg.inf.uc3m.es/ipc2011-deterministic/
 *         - for a BNF description of PDDL 3.1
 *             - http://www.plg.inf.uc3m.es/ipc2011-deterministic/attachments/Resources/kovacs-pddl-3.1-2011.pdf
 */

namespace pddl_planner
{
    class PDDLPlannerInterface;
    typedef std::string PlannerName;
    typedef std::map<std::string, std::string> ActionDescriptions;
    typedef std::map<std::string, std::string> DomainDescriptions;
    typedef std::map<std::string, PDDLPlannerInterface*> PlannerMap;
    typedef std::vector<PDDLPlannerInterface*> PlannerList;
    typedef std::pair<PlannerName, PlanCandidates> PlanResult;
    typedef std::vector< PlanResult > PlanResultList;

    /**
     * \class Planning
     * \brief Planning provides the main infrastructure to perform planning with different
     * planner implementations
     */
    class Planning
    {

    public:
        /**
         * \brief Default constructor for planning
         * It will instanciate all associated planners at construction time
         */
        Planning();

        /**
         * Deconstructor deleting all internal instances of associated planners
         */
        ~Planning();

        static size_t DEFAULT_TIMEOUT_IN_S;

        /**
         * Retrieve the map of all registered planners
         * \return map of registered planners
         */
        PlannerMap getPlanners() const { return mPlanners; }

        /**
         * Retrieves available planners
         * \return list of available planners names
         */
        std::set<std::string> getAvailablePlanners() const;

        /**
         * Register an implementation of a pddl planner
         */
        void registerPlanner(PDDLPlannerInterface* planner);

        /**
         * Retrieve all registered planners
         * \return list of registered planners
         */
        PlannerList getRegisteredPlanners() const;

        /**
         * Check if there is a planner of the given name
         */
        bool isRegistered(const std::string& name) const { return mPlanners.count(name); }

        /**
         * Retrieve planner by name
         * \throw std::runtime_error if planner interface does not exist
         */
        PDDLPlannerInterface* getPlanner(const std::string& name) const;

        /**
         * Set the description for a specific action
         */
        void setActionDescription(const std::string& action, const std::string& description);

        /**
         * Set the description for a specific domain
         */
        void setDomainDescription(const std::string& domain, const std::string& description);

        /**
         * Generate the domain description for
         * all available domain
         * \return Domain descriptions
         */
        std::string getDomainDescriptions() const;

        /**
         * Retrieve the action description for
         * all available actions
         * \return Action descriptions
         */
        std::string getActionDescriptions() const;

        /**
         * Plan towards a given goal
         * \return List of solutions, i.e. plans
         * \throws PlanGenerationException on failure
         */
        PlanResultList plan(const std::string& problem, const std::set<std::string>& planners, bool sequential = false, double timeoutInS = DEFAULT_TIMEOUT_IN_S);

        /**
         * Plan towards a given goal
         * \return List of solutions, i.e. plans
         * \throws PlanGenerationException on failure
         */
        PlanCandidates plan(const std::string& problem, const std::string& plannerName = "LAMA", double timeoutInS = DEFAULT_TIMEOUT_IN_S);

        /**
         * Generate a plan for a given problem -- the problem definition here already contains
         * the domain description
         * \param domain Planning domain to be used
         * \param problem Planning problem
         * \param planners List of planners that will be used for planning
         * \param sequential Set to true if planners should be called one after
         * another, false will execute all planners in parallel
         * \param timeoutInS Timeout in seconds -- will apply to each planner call
         * individually when using with sequential
         * \throws PlanGenerationException on failure
         */
        PlanResultList plan(const representation::Problem& problem, const std::set<std::string>& planners, bool sequential = false, double timeoutInS = DEFAULT_TIMEOUT_IN_S);

        /**
         * Generate a plan for a given domain and problem -- the domain associated with the problem will be overriden
         * \param domain Planning domain to be used
         * \param problem Planning problem
         * \param planners List of planners that will be used for planning
         * \param sequential Set to true if planners should be called one after
         * another, false will execute all planners in parallel
         * \param timeoutInS Timeout in seconds -- will apply to each planner call
         * individually when using with sequential
         * \throws PlanGenerationException on failure
         */
        PlanResultList plan(const representation::Domain& domain, const representation::Problem& problem, const std::set<std::string>& planners, bool sequential = false, double timeoutInS = DEFAULT_TIMEOUT_IN_S);

        /**
         * Generate a plan for a given problem -- the problem definition here already contains
         * the domain description
         * \throws PlanGenerationException on failure
         */
        PlanCandidates plan(const representation::Problem& problem, const std::string& plannerName = "LAMA", double timeoutInS = DEFAULT_TIMEOUT_IN_S);

        /**
         * Generate a plan for a given domain and problem -- the domain associated with the problem will be overriden
         */
        PlanCandidates plan(const representation::Domain& domain, const representation::Problem& problem, const std::string& plannerName = "LAMA", double timeoutInS = DEFAULT_TIMEOUT_IN_S);

    private:
        PlannerMap mPlanners;
        ActionDescriptions mActionDescriptions;
        DomainDescriptions mDomainDescriptions;
        std::vector<boost::thread *> mPlanRunners;
    public:
        PlanResultList     mPlanResultList;
        boost::mutex  mResultMutex;
        boost::mutex mPlannerMutex;
    };

}
#endif // PDDL_PLANNER_H

ext: hpp


text:
/*

Copyright (c) 2010--2011, Stephane Magnenat, ASL, ETHZ, Switzerland
You can contact the author at <stephane at magnenat dot net>

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 <organization> 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 ETH-ASL 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 "stdafx.h"
#include "nabo.h"
#include "nabo_private.h"
#include "index_heap.h"
#include <limits>
#include <algorithm>
#include <stdexcept>
#include <boost/format.hpp>

/*!	\file nabo.cpp
	\brief implementation of public interface
	\ingroup private
*/

namespace Nabo
{
	using namespace std;

	template<typename T, typename CloudType>
	NearestNeighbourSearch<T, CloudType>::NearestNeighbourSearch(const CloudType& cloud, const Index dim, const unsigned creationOptionFlags):
		cloud(cloud),
		dim(min(dim, int(cloud.rows()))),
		creationOptionFlags(creationOptionFlags),
		minBound(Vector::Constant(this->dim, numeric_limits<T>::max())),
		maxBound(Vector::Constant(this->dim, numeric_limits<T>::min()))
	{
		if (cloud.cols() == 0)
			throw runtime_error("Cloud has no points");
		if (cloud.rows() == 0)
			throw runtime_error("Cloud has 0 dimensions");
	}

	template<typename T, typename CloudType>
	unsigned long NearestNeighbourSearch<T, CloudType>::knn(const Vector& query, IndexVector& indices, Vector& dists2, const Index k, const T epsilon, const unsigned optionFlags, const T maxRadius) const
	{
#ifdef EIGEN3_API
		const Eigen::Map<const Matrix> queryMatrix(&query.coeff(0,0), dim, 1);
#else // EIGEN3_API
		const Eigen::Map<Matrix> queryMatrix(&query.coeff(0,0), dim, 1);
#endif // EIGEN3_API
		// note: this is inefficient, because we copy memory, due to the template-
		// based abstraction of Eigen. High-performance implementation should
		// take care of knnM and then implement knn on top of it.
		// C++0x should solve this with rvalue
		IndexMatrix indexMatrix(k, 1);
		Matrix dists2Matrix(k, 1);
		const unsigned long stats = knn(queryMatrix, indexMatrix, dists2Matrix, k, epsilon, optionFlags, maxRadius);
		indices = indexMatrix.col(0);
		dists2 = dists2Matrix.col(0);
		return stats;
	}

	template<typename T, typename CloudType>
	void NearestNeighbourSearch<T, CloudType>::checkSizesKnn(const Matrix& query, const IndexMatrix& indices, const Matrix& dists2, const Index k, const unsigned optionFlags, const Vector* maxRadii) const
	{
		const bool allowSelfMatch(optionFlags & NearestNeighbourSearch<T, CloudType>::ALLOW_SELF_MATCH);
		if (allowSelfMatch)
		{
			if (k > cloud.cols())
				throw runtime_error((boost::format("Requesting more points (%1%) than available in cloud (%2%)") % k % cloud.cols()).str());
		}
		else
		{
			if (k > cloud.cols()-1)
				throw runtime_error((boost::format("Requesting more points (%1%) than available in cloud minus 1 (%2%) (as self match is forbidden)") % k % (cloud.cols()-1)).str());
		}
		if (query.rows() < dim)
			throw runtime_error((boost::format("Query has less dimensions (%1%) than requested for cloud (%2%)") % query.rows() % dim).str());
		if (indices.rows() != k)
			throw runtime_error((boost::format("Index matrix has a different number of rows (%1%) than k (%2%)") % indices.rows() % k).str());
		if (indices.cols() != query.cols())
			throw runtime_error((boost::format("Index matrix has a different number of columns (%1%) than query (%2%)") % indices.rows() % query.cols()).str());
		if (dists2.rows() != k)
			throw runtime_error((boost::format("Distance matrix has a different number of rows (%1%) than k (%2%)") % dists2.rows() % k).str());
		if (dists2.cols() != query.cols())
			throw runtime_error((boost::format("Distance matrix has a different number of columns (%1%) than query (%2%)") % dists2.rows() % query.cols()).str());
		if (maxRadii && (maxRadii->size() != query.cols()))
			throw runtime_error((boost::format("Maximum radii vector has not the same length (%1%) than query has columns (%2%)") % maxRadii->size() % k).str());
		const unsigned maxOptionFlagsValue(ALLOW_SELF_MATCH|SORT_RESULTS);
		if (optionFlags > maxOptionFlagsValue)
			throw runtime_error((boost::format("OR-ed value of option flags (%1%) is larger than maximal valid value (%2%)") % optionFlags % maxOptionFlagsValue).str());
	}

	template<typename T, typename CloudType>
	NearestNeighbourSearch<T, CloudType>* NearestNeighbourSearch<T, CloudType>::create(const CloudType& cloud, const Index dim, const SearchType preferedType, const unsigned creationOptionFlags, const Parameters& additionalParameters)
	{
		if (dim <= 0)
			throw runtime_error("Your space must have at least one dimension");
		switch (preferedType)
		{
			case BRUTE_FORCE: return new BruteForceSearch<T, CloudType>(cloud, dim, creationOptionFlags);
			case KDTREE_LINEAR_HEAP: return new KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<T, IndexHeapBruteForceVector<int,T>, CloudType>(cloud, dim, creationOptionFlags, additionalParameters);
			case KDTREE_TREE_HEAP: return new KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<T, IndexHeapSTL<int,T>, CloudType>(cloud, dim, creationOptionFlags, additionalParameters);
			#ifdef HAVE_OPENCL
			case KDTREE_CL_PT_IN_NODES: return new KDTreeBalancedPtInNodesStackOpenCL<T, CloudType>(cloud, dim, creationOptionFlags, CL_DEVICE_TYPE_GPU);
			case KDTREE_CL_PT_IN_LEAVES: return new KDTreeBalancedPtInLeavesStackOpenCL<T, CloudType>(cloud, dim, creationOptionFlags, CL_DEVICE_TYPE_GPU);
			case BRUTE_FORCE_CL: return new BruteForceSearchOpenCL<T, CloudType>(cloud, dim, creationOptionFlags, CL_DEVICE_TYPE_GPU);
			#else // HAVE_OPENCL
			case KDTREE_CL_PT_IN_NODES: throw runtime_error("OpenCL not found during compilation");
			case KDTREE_CL_PT_IN_LEAVES: throw runtime_error("OpenCL not found during compilation");
			case BRUTE_FORCE_CL: throw runtime_error("OpenCL not found during compilation");
			#endif // HAVE_OPENCL
			default: throw runtime_error("Unknown search type");
		}
	}

	template<typename T, typename CloudType>
	NearestNeighbourSearch<T, CloudType>* NearestNeighbourSearch<T, CloudType>::createBruteForce(const CloudType& cloud, const Index dim, const unsigned creationOptionFlags)
	{
		if (dim <= 0)
			throw runtime_error("Your space must have at least one dimension");
		return new BruteForceSearch<T, CloudType>(cloud, dim, creationOptionFlags);
	}

	template<typename T, typename CloudType>
	NearestNeighbourSearch<T, CloudType>* NearestNeighbourSearch<T, CloudType>::createKDTreeLinearHeap(const CloudType& cloud, const Index dim, const unsigned creationOptionFlags, const Parameters& additionalParameters)
	{
		if (dim <= 0)
			throw runtime_error("Your space must have at least one dimension");
		return new KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<T, IndexHeapBruteForceVector<int,T>, CloudType>(cloud, dim, creationOptionFlags, additionalParameters);
	}

	template<typename T, typename CloudType>
	NearestNeighbourSearch<T, CloudType>* NearestNeighbourSearch<T, CloudType>::createKDTreeTreeHeap(const CloudType& cloud, const Index dim, const unsigned creationOptionFlags, const Parameters& additionalParameters)
	{
		if (dim <= 0)
			throw runtime_error("Your space must have at least one dimension");
		return new KDTreeUnbalancedPtInLeavesImplicitBoundsStackOpt<T, IndexHeapSTL<int,T>, CloudType>(cloud, dim, creationOptionFlags, additionalParameters);
	}

	template struct NearestNeighbourSearch<float>;
	template struct NearestNeighbourSearch<double>;
	template struct NearestNeighbourSearch<float, Eigen::Matrix3Xf>;
	template struct NearestNeighbourSearch<double, Eigen::Matrix3Xd>;
	template struct NearestNeighbourSearch<float, Eigen::Map<const Eigen::Matrix3Xf, Eigen::Aligned> >;
	template struct NearestNeighbourSearch<double, Eigen::Map<const Eigen::Matrix3Xd, Eigen::Aligned> >;
}

max_stars_repo_name: foreee/CPCA

max_issues_repo_name: foreee/CPCA

max_forks_repo_name: foreee/CPCA


text:
#define BOOST_TEST_MODULE SolutionTest

#include "solution.hpp"

//#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(SolutionSuite)

BOOST_AUTO_TEST_CASE(PlainTest1)
{
    vector<int> nums{-10,-3,0,5,9};
    TreeNode *root = Solution().sortedArrayToBST(nums);
    string result = treeNodeToString(root);

    string expected = "[0,-10,5,null,-3,null,9,null,null,null,null]";

    BOOST_CHECK_EQUAL(result, expected);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: johnhany/leetcode

max_issues_repo_name: johnhany/leetcode

max_forks_repo_name: johnhany/leetcode


text:
// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-

// -- BEGIN LICENSE BLOCK ----------------------------------------------
// Copyright (c) 2018, FZI Forschungszentrum Informatik
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions
//    and the following disclaimer.
//
// 2. 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.
//
// 3. Neither the name of the copyright holder 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 HOLDER 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.
// -- END LICENSE BLOCK ------------------------------------------------

//----------------------------------------------------------------------
/*!\file
 *
 * \author  Julius Ziegler <ziegler@fzi.de>
 * \date    2012-03-06
 *
 */
//----------------------------------------------------------------------

#if !defined(LOCALGEOGRAPHICCS_HPP)
#define LOCALGEOGRAPHICCS_HPP

#include "convert_coordinates.hpp"

#include <boost/tuple/tuple.hpp>

#include <utility>

struct LocalGeographicCS
{
  LocalGeographicCS();
  LocalGeographicCS( double lat0, double lon0 );

  void set_origin( double lat0, double lon0 );

  void ll2xy( double lat, double lon, double& x, double& y ) const;
  void xy2ll( double x, double y, double& lat, double& lon ) const;

  boost::tuple<double, double> ll2xy( double lat, double lon ) const;
  boost::tuple<double, double> xy2ll( double x, double y ) const;

  // operate on containers
  template<class ItIn, class ItOut>
  void ll2xy( const ItIn& lat_begin, const ItIn& lat_end, const ItIn& lon_begin, const ItOut& x_begin, const ItOut& y_begin ) const;

  template<class ItIn, class ItOut>
  void xy2ll( const ItIn& x_begin, const ItIn& x_end, const ItIn& y_begin, const ItOut& lat_begin, const ItOut& lon_begin ) const;

private:
  double _scale;
  double _x0, _y0;
};

inline LocalGeographicCS::LocalGeographicCS( double lat0, double lon0 )
{
  set_origin( lat0, lon0 );
}

inline LocalGeographicCS::LocalGeographicCS()
{}

inline void LocalGeographicCS::set_origin( double lat0, double lon0 )
{
  _scale = convert_coordinates::lat_to_scale( lat0 );
  convert_coordinates::latlon_to_mercator( lat0, lon0, _scale, _x0, _y0 );
}

inline void LocalGeographicCS::ll2xy( double lat, double lon, double& x, double& y ) const
{
  convert_coordinates::latlon_to_mercator( lat, lon, _scale, x, y );
  x -= _x0;
  y -= _y0;
}

inline boost::tuple<double, double> LocalGeographicCS::ll2xy( double lat, double lon ) const
{
  double x, y;
  ll2xy( lat, lon, x, y );
  return boost::make_tuple( x, y );
}

inline void LocalGeographicCS::xy2ll( double x, double y, double& lat, double& lon ) const
{
  x += _x0;
  y += _y0;

  convert_coordinates::mercator_to_latlon( x, y, _scale, lat, lon );
}

inline boost::tuple<double, double> LocalGeographicCS::xy2ll( double x, double y ) const
{
  double lat, lon;
  xy2ll( x, y, lat, lon );
  return boost::make_tuple( lat, lon );
}

// operate on containers
template<class ItIn, class ItOut>
void LocalGeographicCS::ll2xy( const ItIn& lat_begin, const ItIn& lat_end, const ItIn& lon_begin, const ItOut& x_begin, const ItOut& y_begin ) const
{
  ItIn lat = lat_begin;
  ItIn lon = lon_begin;
  ItOut x = x_begin;
  ItOut y = y_begin;

  for( ; lat != lat_end; lat++, lon++, x++, y++ )
    {
      ll2xy( *lat, *lon, *x, *y );
    }
}

template<class ItIn, class ItOut>
void LocalGeographicCS::xy2ll( const ItIn& x_begin, const ItIn& x_end, const ItIn& y_begin, const ItOut& lat_begin, const ItOut& lon_begin ) const
{
  ItIn x = x_begin;
  ItIn y = y_begin;

  ItOut lat = lat_begin;
  ItOut lon = lon_begin;

  for( ; x != x_end; lat++, lon++, x++, y++ )
    xy2ll( *x, *y, *lat, *lon );
}

#endif


text:
/*
 * Copyright (c) 2016 Abhishek Agrawal (abhishek.agrawal@protonmail.com)
 * Distributed under the MIT License.
 * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
 */

#include <cstdlib>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <cmath>
#include <limits>
#include <vector>

#include <boost/numeric/odeint.hpp>

#include "NAOS/constants.hpp"
#include "NAOS/basicMath.hpp"
#include "NAOS/basicAstro.hpp"
#include "NAOS/misc.hpp"
#include "NAOS/ellipsoidGravitationalAcceleration.hpp"

namespace naos
{

//! equations of motion (for a particle around the asteroid modelled as an Ellipsoid)
/*!
 * first order differential equations describing the motion of a particle or spacecraft around a
 * central body modeled as an ellipsoid using ellipsoid gravitational model.
 */
class equationsOfMotionParticleAroundEllipsoid
{
    // declare parameters, gravitational parameter and the semi major axes of the ellipsoid
    const double gravParameter;
    const double alpha;
    const double beta;
    const double gamma;
    const double zRotation;

public:
    // Default constructor with member initializer list
    equationsOfMotionParticleAroundEllipsoid(
               const double aGravParameter,
               const double aAlpha,
               const double aBeta,
               const double aGamma,
               const double aZRotation )
            : gravParameter( aGravParameter ),
              alpha( aAlpha ),
              beta( aBeta ),
              gamma( aGamma ),
              zRotation( aZRotation )
    { }
    void operator() ( const std::vector< double > &stateVector,
                      std::vector< double > &dXdt,
                      const double currentTime )
    {
        // calculate the gravitational accelerations first
        std::vector< double > gravAcceleration( 3, 0.0 );

        computeEllipsoidGravitationalAcceleration( alpha,
                                                   beta,
                                                   gamma,
                                                   gravParameter,
                                                   stateVector[ xPositionIndex ],
                                                   stateVector[ yPositionIndex ],
                                                   stateVector[ zPositionIndex ],
                                                   gravAcceleration );

        // now calculate the derivatives
        dXdt[ xPositionIndex ] = stateVector[ xVelocityIndex ];
        dXdt[ yPositionIndex ] = stateVector[ yVelocityIndex ];
        dXdt[ zPositionIndex ] = stateVector[ zVelocityIndex ];

        dXdt[ xVelocityIndex ] = gravAcceleration[ xPositionIndex ]
                                + 2.0 * zRotation * stateVector[ yVelocityIndex ]
                                + zRotation * zRotation * stateVector[ xPositionIndex ];

        dXdt[ yVelocityIndex ] = gravAcceleration[ yPositionIndex ]
                                - 2.0 * zRotation * stateVector[ xVelocityIndex ]
                                + zRotation * zRotation * stateVector[ yPositionIndex ];

        dXdt[ zVelocityIndex ] = gravAcceleration[ zPositionIndex ];
    }
};

//! Store intermediate state values and time( if needed )
/*!
 * This structure contains members that will save all intermediate state values and times when
 * an object of this structure is passed as an argument to the integrator function.
 */
struct pushBackStateAndTime
{
    // declare containers to store state and time
    std::vector< std::vector< double > > &stateContainer;
    std::vector< double > &timeContainer;

    //member initializer list
    pushBackStateAndTime( std::vector< std::vector< double > > &aState,
                          std::vector< double > &aTime )
                : stateContainer( aState ),
                  timeContainer( aTime )
    { }

    void operator() ( const std::vector< double > &singleStateVector, const double singleTime )
    {
        // store the intermediate state and time values in the containers
        stateContainer.push_back( singleStateVector );
        timeContainer.push_back( singleTime );
    }
};

//! particle around ellipsoid integration
/*!
 * integrate the equations of motion for a particle around an ellipsoid. The gravitational accelerations
 * calculated using the ellipsoid gravitational potential model.
 */
void executeParticleAroundEllipsoid( const double alpha,
                                     const double beta,
                                     const double gamma,
                                     const double gravParameter,
                                     std::vector< double > asteroidRotationVector,
                                     std::vector< double > &initialOrbitalElements,
                                     const double initialStepSize,
                                     const double startTime,
                                     const double endTime,
                                     std::ostringstream &outputFilePath,
                                     const int dataSaveIntervals )
{
    //! open the output csv file to save data. Declare file headers.
    std::ofstream outputFile;
    outputFile.open( outputFilePath.str( ) );
    outputFile << "x" << ",";
    outputFile << "y" << ",";
    outputFile << "z" << ",";
    outputFile << "vx" << ",";
    outputFile << "vy" << ",";
    outputFile << "vz" << ",";
    outputFile << "t" << std::endl;
    outputFile.precision( 16 );

    //! convert the initial orbital elements to cartesian state
    std::vector< double > initialStateInertial( 6, 0.0 );
    initialStateInertial = convertKeplerianElementsToCartesianCoordinates( initialOrbitalElements,
                                                                           gravParameter );

    //! account for non-zero start time value and calculate the initial state in body frame
    double phi = asteroidRotationVector[ zPositionIndex ] * startTime;

    std::vector< double > initialState( 6, 0.0 );

    // get the initial body frame position
    initialState[ xPositionIndex ]
            = initialStateInertial[ xPositionIndex ] * std::cos( phi )
            + initialStateInertial[ yPositionIndex ] * std::sin( phi );

    initialState[ yPositionIndex ]
            = -1.0 * initialStateInertial[ xPositionIndex ] * std::sin( phi )
            + initialStateInertial[ yPositionIndex ] * std::cos( phi );

    initialState[ zPositionIndex ] = initialStateInertial[ zPositionIndex ];

    // get the initial body frame velocity
    std::vector< double > inertialPositionVector = { initialStateInertial[ xPositionIndex ],
                                                     initialStateInertial[ yPositionIndex ],
                                                     initialStateInertial[ zPositionIndex ] };

    std::vector< double > omegaCrossPosition( 3, 0.0 );
    omegaCrossPosition = crossProduct( asteroidRotationVector, inertialPositionVector );

    double xbodyFrameVelocityInertialCoordinates
                = initialStateInertial[ xVelocityIndex ] - omegaCrossPosition[ 0 ];

    double ybodyFrameVelocityInertialCoordinates
                = initialStateInertial[ yVelocityIndex ] - omegaCrossPosition[ 1 ];

    double zbodyFrameVelocityInertialCoordinates
                = initialStateInertial[ zVelocityIndex ] - omegaCrossPosition[ 2 ];

    initialState[ xVelocityIndex ]
            = xbodyFrameVelocityInertialCoordinates * std::cos( phi )
            + ybodyFrameVelocityInertialCoordinates * std::sin( phi );

    initialState[ yVelocityIndex ]
            = -1.0 * xbodyFrameVelocityInertialCoordinates * std::sin( phi )
            + ybodyFrameVelocityInertialCoordinates * std::cos( phi );

    initialState[ zVelocityIndex] = zbodyFrameVelocityInertialCoordinates;

    // set up boost odeint
    const double absoluteTolerance = 1.0e-15;
    const double relativeTolerance = 1.0e-15;
    typedef boost::numeric::odeint::runge_kutta_fehlberg78< std::vector< double > > stepperType;

    // state step size guess (at each step this initial guess will be used)
    double stepSizeGuess = initialStepSize;

    // initialize the ode system
    const double zRotation = asteroidRotationVector[ zPositionIndex ];
    equationsOfMotionParticleAroundEllipsoid particleAroundEllipsoidProblem( gravParameter,
                                                                             alpha,
                                                                             beta,
                                                                             gamma,
                                                                             zRotation );

    // initialize current state vector and time
    std::vector< double > currentStateVector = initialState;
    double currentTime = startTime;
    double intermediateEndTime = currentTime + dataSaveIntervals;

    // save the initial state vector
    outputFile << currentStateVector[ xPositionIndex ] << ",";
    outputFile << currentStateVector[ yPositionIndex ] << ",";
    outputFile << currentStateVector[ zPositionIndex ] << ",";
    outputFile << currentStateVector[ xVelocityIndex ] << ",";
    outputFile << currentStateVector[ yVelocityIndex ] << ",";
    outputFile << currentStateVector[ zVelocityIndex ] << ",";
    outputFile << currentTime << std::endl;

    // start the integration outer loop
    while( intermediateEndTime <= endTime )
    {
        // perform integration, integrated result stored in currentStateVector
        size_t steps = boost::numeric::odeint::integrate_adaptive(
                            make_controlled( absoluteTolerance, relativeTolerance, stepperType( ) ),
                            particleAroundEllipsoidProblem,
                            currentStateVector,
                            currentTime,
                            intermediateEndTime,
                            stepSizeGuess );

        // update the time variables
        currentTime = intermediateEndTime;
        intermediateEndTime = currentTime + dataSaveIntervals;

        // save data
        outputFile << currentStateVector[ xPositionIndex ] << ",";
        outputFile << currentStateVector[ yPositionIndex ] << ",";
        outputFile << currentStateVector[ zPositionIndex ] << ",";
        outputFile << currentStateVector[ xVelocityIndex ] << ",";
        outputFile << currentStateVector[ yVelocityIndex ] << ",";
        outputFile << currentStateVector[ zVelocityIndex ] << ",";
        outputFile << currentTime << std::endl;

    } // end of outer while loop for integration

    outputFile.close( );
}

//! Trajectory calculation for regolith around an asteroid (modelled as ellipsoid here)
/*!
 * Same as the previous function, except that the initial conditions are now given as a cartesian
 * state. The initial cartesian state should be given in body fixed frame of the asteroid.
 */
void singleRegolithTrajectoryCalculator( const double alpha,
                                         const double beta,
                                         const double gamma,
                                         const double gravParameter,
                                         std::vector< double > asteroidRotationVector,
                                         std::vector< double > &initialCartesianStateVector,
                                         const double initialStepSize,
                                         const double startTime,
                                         const double endTime,
                                         std::ostringstream &outputFilePath,
                                         const int dataSaveIntervals )
{
    //! open the output csv file to save data. Declare file headers.
    std::ofstream outputFile;
    outputFile.open( outputFilePath.str( ) );
    outputFile << "x" << ",";
    outputFile << "y" << ",";
    outputFile << "z" << ",";
    outputFile << "vx" << ",";
    outputFile << "vy" << ",";
    outputFile << "vz" << ",";
    outputFile << "t" << std::endl;
    outputFile.precision( 16 );

    //! get the initial cartesian state vector in a seperate container
    std::vector< double > initialState = initialCartesianStateVector;

    // set up boost odeint
    const double absoluteTolerance = 1.0e-15;
    const double relativeTolerance = 1.0e-15;
    typedef boost::numeric::odeint::runge_kutta_fehlberg78< std::vector< double > > stepperType;

    // state step size guess (at each step this initial guess will be used)
    double stepSizeGuess = initialStepSize;

    // initialize the ode system
    const double zRotation = asteroidRotationVector[ zPositionIndex ];
    equationsOfMotionParticleAroundEllipsoid particleAroundEllipsoidProblem( gravParameter,
                                                                             alpha,
                                                                             beta,
                                                                             gamma,
                                                                             zRotation );

    // initialize current state vector and time
    std::vector< double > currentStateVector = initialState;
    double currentTime = startTime;
    double intermediateEndTime = currentTime + dataSaveIntervals;

    // save the initial state vector
    outputFile << currentStateVector[ xPositionIndex ] << ",";
    outputFile << currentStateVector[ yPositionIndex ] << ",";
    outputFile << currentStateVector[ zPositionIndex ] << ",";
    outputFile << currentStateVector[ xVelocityIndex ] << ",";
    outputFile << currentStateVector[ yVelocityIndex ] << ",";
    outputFile << currentStateVector[ zVelocityIndex ] << ",";
    outputFile << currentTime << std::endl;

    // start the integration outer loop
    while( intermediateEndTime <= endTime )
    {
        // save the last know state vector for when the particle is outside the asteroid
        std::vector< double > lastStateVector = currentStateVector;

        // perform integration, integrated result stored in currentStateVector
        size_t steps = boost::numeric::odeint::integrate_adaptive(
                            make_controlled( absoluteTolerance, relativeTolerance, stepperType( ) ),
                            particleAroundEllipsoidProblem,
                            currentStateVector,
                            currentTime,
                            intermediateEndTime,
                            stepSizeGuess );

        //! check if the particle is inside the surface of the asteroid
        double xSquare = currentStateVector[ xPositionIndex ] * currentStateVector[ xPositionIndex ];
        double ySquare = currentStateVector[ yPositionIndex ] * currentStateVector[ yPositionIndex ];
        double zSquare = currentStateVector[ zPositionIndex ] * currentStateVector[ zPositionIndex ];

        double crashCheck = xSquare / ( alpha * alpha )
                            + ySquare / ( beta * beta )
                            + zSquare / ( gamma * gamma )
                            - 1.0;

        if( crashCheck == 0.0 )
        {
            // particle is on the surface of the asteroid, save data and stop integration
            // update the time variables
            currentTime = intermediateEndTime;

            // save data
            outputFile << currentStateVector[ xPositionIndex ] << ",";
            outputFile << currentStateVector[ yPositionIndex ] << ",";
            outputFile << currentStateVector[ zPositionIndex ] << ",";
            outputFile << currentStateVector[ xVelocityIndex ] << ",";
            outputFile << currentStateVector[ yVelocityIndex ] << ",";
            outputFile << currentStateVector[ zVelocityIndex ] << ",";
            outputFile << currentTime << std::endl;

            break;
        }

        if( crashCheck < 0.0 )
        {
            double stepSize = 1.0;
            const double machinePrecision = std::numeric_limits< double >::epsilon( );
            // if the particle is on the surface of the asteroid, then the while condition
            // will be false, for all other cases it will be true. Within the while loop, the
            // inside or outside differnetiation takes place.
            while( std::fabs( crashCheck ) > machinePrecision )
            {
                // std::cout << "crash check value = " << crashCheck << std::endl;
                if( crashCheck < 0.0 ) // particle is still inside the surface
                {
                    // std::cout << "particle inside the surface" << std::endl << std::endl;
                    // particle is inside the surface of the asteroid. restart the integration from last
                    // known state external to the asteroid
                    currentStateVector = lastStateVector;
                    stepSize = 0.5 * stepSize;
                }
                else // particle is outside the asteroid at the end of last integration step
                {
                    // std::cout << "particle outside the surface" << std::endl << std::endl;
                    lastStateVector = currentStateVector;
                    currentTime = intermediateEndTime;
                }

                typedef boost::numeric::odeint::runge_kutta_fehlberg78< std::vector< double > > errorStepperType;
                intermediateEndTime =  boost::numeric::odeint::integrate_n_steps(
                                                errorStepperType( ),
                                                particleAroundEllipsoidProblem,
                                                currentStateVector,
                                                currentTime,
                                                stepSize,
                                                1 );

                xSquare = currentStateVector[ xPositionIndex ] * currentStateVector[ xPositionIndex ];
                ySquare = currentStateVector[ yPositionIndex ] * currentStateVector[ yPositionIndex ];
                zSquare = currentStateVector[ zPositionIndex ] * currentStateVector[ zPositionIndex ];

                crashCheck = xSquare / ( alpha * alpha )
                            + ySquare / ( beta * beta )
                            + zSquare / ( gamma * gamma )
                            - 1.0;
            }

            // particle is on the surface of the asteroid, save data and stop integration
            // update the time variables
            currentTime = intermediateEndTime;

            // save data
            outputFile << currentStateVector[ xPositionIndex ] << ",";
            outputFile << currentStateVector[ yPositionIndex ] << ",";
            outputFile << currentStateVector[ zPositionIndex ] << ",";
            outputFile << currentStateVector[ xVelocityIndex ] << ",";
            outputFile << currentStateVector[ yVelocityIndex ] << ",";
            outputFile << currentStateVector[ zVelocityIndex ] << ",";
            outputFile << currentTime << std::endl;

            break;
        }

        // update the time variables
        currentTime = intermediateEndTime;
        intermediateEndTime = currentTime + dataSaveIntervals;

        // save data
        outputFile << currentStateVector[ xPositionIndex ] << ",";
        outputFile << currentStateVector[ yPositionIndex ] << ",";
        outputFile << currentStateVector[ zPositionIndex ] << ",";
        outputFile << currentStateVector[ xVelocityIndex ] << ",";
        outputFile << currentStateVector[ yVelocityIndex ] << ",";
        outputFile << currentStateVector[ zVelocityIndex ] << ",";
        outputFile << currentTime << std::endl;

    } // end of outer while loop for integration

    outputFile.close( );
}

} // namespace naos

max_stars_repo_name: agrawalabhishek/NAOS

max_issues_repo_name: agrawalabhishek/NAOS

max_forks_repo_name: agrawalabhishek/NAOS


text:
#ifndef CAFFE_SAMPLE_SELECTOR_HPP_
#define CAFFE_SAMPLE_SELECTOR_HPP_

#include <map>
#include <string>
#include <vector>
#include <boost/thread.hpp>
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/internal_thread.hpp"
#include "caffe/util/rng.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
  template <typename Dtype>
  class SampleSelector {
   public:
    explicit SampleSelector(const LayerParameter& param);
    void ProcessLabelSelectParam();
    void ReadLabelProbMappingFile(const string& file_name);
    void ComputeLabelSkipRate();
    bool AcceptGivenLabel(const int label);
    int  GetConvertedLabel(const int label);
    const float*  Get_Label_prob_gpu_data();
	const float*  Get_Label_prob_cpu_data();
	void  Compute_label_prob_fromBlob(Blob<Dtype>* labelBlob);
  protected:
    void InitRand();
    unsigned int PrefetchRand();
    const LayerParameter param_;
    //const LabelSelectParameter param_;
    std::map <int, float> label_prob_map_;
    std::map <int, unsigned int> label_skip_rate_map_;
    std::map <int, int> label_mapping_map_;
    unsigned  int num_labels_;
    unsigned  int num_labels_with_prob_ ;
    bool      balancing_label_;
    unsigned int num_top_label_balance_;
    bool  rest_of_label_mapping_;
    bool  map2order_label_;
    bool  ignore_rest_of_label_;
    int   rest_of_label_mapping_label_;
    float rest_of_label_prob_;
    shared_ptr<Caffe::RNG> rng_;
    Blob<int> label_skip_rate_blob_;
    Blob<float> label_prob_weight_blob_;
  };
}
#endif


text:
/*
 * Copyright (c) 2011 by Michael Berlin, Zuse Institute Berlin
 *
 * Licensed under the BSD License, see LICENSE file for details.
 *
 */

#include "fuse/fuse_options.h"

#include <csignal>

#include <boost/lexical_cast.hpp>
#include <boost/program_options/cmdline.hpp>
#include <boost/tokenizer.hpp>
#include <iostream>
#include <sstream>

#include "libxtreemfs/helper.h"
#include "libxtreemfs/xtreemfs_exception.h"

using namespace std;

namespace po = boost::program_options;
namespace style = boost::program_options::command_line_style;

namespace xtreemfs {

FuseOptions::FuseOptions() : Options(), fuse_descriptions_("Fuse Options") {
  // Overwrite certain members of Options().
#ifndef __linux
  // Interrupting read calls does not work with Linux Fuse.
  max_read_tries = 0;
#endif

  // Never give up to execute a request as we enabled interruption.
  max_tries = 0;
  max_write_tries = 0;

  async_writes_max_request_size_kb = 128;  // FUSE specific limit.

  // Default Fuse options.
#ifdef __APPLE__
  // We assume that the MacFuse default timeout is 60 seconds on Leopard.
  daemon_timeout = 60;

  // Always enable xattrs for Mac.
  enable_xattrs = true;

  // If we are under Leopard or newer, reduce the timeout values.
  if (GetMacOSXKernelVersion() >= 9) {
    max_tries = 3;
    max_read_tries = 3;
    max_write_tries = 3;

    retry_delay_s = 15;
    connect_timeout_s = 15;
    // The detection of a timeout may take twice the time, i.e. up to 18 seconds
    // resulting in a total time of 3 * 18 (< 60 seconds daemon_timeout default).
    request_timeout_s = 9;
  }
#else
  enable_xattrs = false;
#endif  // __APPLE__
  foreground = false;
  use_fuse_permission_checks = true;
  fuse_permission_checks_explicitly_disabled = false;

  fuse_descriptions_.add_options()
    ("foreground,f", po::value(&foreground)->zero_tokens(),
        "Do not fork into background.")
    ("fuse_option,o",
        po::value< vector<string> >(&fuse_options),
        "Passes -o=<option> to Fuse.")
    ("no-default-permissions",
        po::value(&fuse_permission_checks_explicitly_disabled)->zero_tokens(),
        "Do not pass -o default_permissions to Fuse (disables local Fuse"
        " permissions checks).");
  po::options_description fuse_options_information(
      "ACL and extended attributes Support:\n"
      "  -o xtreemfs_acl Enable the correct evaluation of XtreemFS ACLs.\n"
      "                  (Note that you cannot use the system tools getfattr\n"
      "                   and setfattr; use 'xtfsutil' instead to set and\n"
      "                   retrieve ACLs.)"
#ifndef __APPLE__
      "\n  -o user_xattr   Enable user defined extended attributes.");
#else
      );
#endif  // __APPLE__
  fuse_descriptions_.add(fuse_options_information);

  helptext_usage_ =
      "mount.xtreemfs: Mounts an XtreemFS Volume.\n"
      "\n"
      "Usage: \n"
      "\tmount.xtreemfs [options] [pbrpc[g|s]://]<dir-host>[:port]/<volume-name>"
          " <mount point>\n"
      "\n"
      "  Example: mount.xtreemfs localhost/myVolume ~/xtreemfs\n";
}

void FuseOptions::ParseCommandLine(int argc, char** argv) {
  // Parse general options and retrieve unregistered options for own parsing.
  vector<string> options = Options::ParseCommandLine(argc, argv);

  // Read Volume URL and mount point from command line.
  po::positional_options_description p;
  p.add("dir_volume_url", 1);
  p.add("mount_point", 1);
  po::options_description mount("Mount options");
  mount.add_options()
    ("dir_volume_url", po::value(&xtreemfs_url), "volume to mount")
    ("mount_point", po::value(&mount_point), "where to mount the volume");

  // Parse command line.
  po::options_description all_descriptions_;
  all_descriptions_.add(mount).add(fuse_descriptions_);
  po::variables_map vm;
  try {
    po::store(po::command_line_parser(options)
        .options(all_descriptions_)
        .positional(p)
        .style(style::default_style & ~style::allow_guessing)
        .run(), vm);
    po::notify(vm);
  } catch(const std::exception& e) {
    // Rethrow boost errors due to invalid command line parameters.
    throw InvalidCommandLineParametersException(string(e.what()));
  }

  // Do not check parameters if the help shall be shown.
  if (show_help || empty_arguments_list || show_version) {
    return;
  }

  // Split list of comma separated -o options and add them as extra options.
  list<string> split_options;
  for (int i = 0; i < fuse_options.size(); i++) {
    typedef boost::tokenizer< boost::char_separator<char> > tokenizer;
    boost::char_separator<char> seperator(",");
    tokenizer tokens(fuse_options[i], seperator);

    // Check if there are at least two tokens and they have to be split up
    tokenizer::iterator first_tokens = tokens.begin();
    if (++first_tokens != tokens.end()) {
      // Split tokens and add them to a temporary list.
      for (tokenizer::iterator token = tokens.begin();
           token != tokens.end();
           ++token) {
        split_options.push_back(string(*token));
      }

      // Remove split tokens from fuse_options as they will be readded later.
      fuse_options.erase(fuse_options.begin() + i);
      i--;
    }
  }
  // Readd split options.
  for (list<string>::const_iterator iter = split_options.begin();
       iter != split_options.end();
       ++iter) {
    fuse_options.push_back(*iter);
  }

  // Evaluate certain Fuse options.
  for (int i = 0; i < fuse_options.size(); i++) {
    if (fuse_options[i] == "acl") {
      throw InvalidCommandLineParametersException(
          "The option -o acl is not supported. Specify -o xtreemfs_acl instead."
          "\n\nWe do not allow -o acl because XtreemFS does not support the "
          "getfacl and setfacl tools. You have to use 'xtfs_acl' instead "
          "to set and retrieve ACLs.");
    }
    if (fuse_options[i] == "user_xattr") {
      enable_xattrs = true;
      // Don't send this option to Fuse.
      fuse_options.erase(fuse_options.begin() + i);
      i--;
      continue;
    }
    if (fuse_options[i] == "xtreemfs_acl") {
      // Fuse may prevent operations based on the evaluation of stat records
      // although a user is allowed to due to further ACLs, so we disable this
      // Fuse feature here.
      use_fuse_permission_checks = false;
      // Don't send this option to Fuse.
      fuse_options.erase(fuse_options.begin() + i);
      i--;
      continue;
    }
    if (fuse_options[i] == "intr") {
      // Don't send this option to Fuse.
      fuse_options.erase(fuse_options.begin() + i);
      i--;
      throw InvalidCommandLineParametersException(
          "The option -o intr will be ignored as command line parameter and"
          " not passed through to Fuse. Use --interrupt-signal instead.");
    }
    if (fuse_options[i].substr(0, 12) == "intr_signal=") {
      // Don't send this option to Fuse.
      fuse_options.erase(fuse_options.begin() + i);
      i--;
      throw InvalidCommandLineParametersException(
          "The option -o intr_signal will be ignored as command line "
          "parameter and not passed through to Fuse. Use --interrupt-signal "
          "instead.");
    }
    if (fuse_options[i] == "_netdev") {
      // Don't send this option to Fuse, just ignore it, solves issue 276:
      // https://code.google.com/p/xtreemfs/issues/detail?id=276
      fuse_options.erase(fuse_options.begin() + i);
      i--;
    }
#ifdef __APPLE__
    if (fuse_options[i].substr(0, 15) == "daemon_timeout=") {
      try {
        daemon_timeout = boost::lexical_cast<int>(fuse_options[i].substr(15));
        continue;
      } catch(const boost::bad_lexical_cast& e) {
        throw InvalidCommandLineParametersException(
            "The integer value after daemon_timeout could not be parsed: "
            + fuse_options[i].substr(15));
      }
    }
#endif
  }

  // Extract information from command line.
  Options::ParseURL(kDIR);

  // Check for required parameters.
  if (service_addresses.empty()) {
    throw InvalidCommandLineParametersException("missing DIR host.");
  }
  if (volume_name.empty()) {
    throw InvalidCommandLineParametersException("missing volume name.");
  }
  if (mount_point.empty()) {
    throw InvalidCommandLineParametersException("missing mount point.");
  }
}

std::string FuseOptions::ShowCommandLineUsage() {
  return helptext_usage_
      + "\nFor complete list of options, please specify -h or --help.\n";
}

std::string FuseOptions::ShowCommandLineHelp() {
  ostringstream stream;
  // No help text given in descriptions for positional mount options. Instead
  // the usage is explained here.
  stream << helptext_usage_
         << endl
         // Descriptions of this class.
         << fuse_descriptions_
         // Descriptions of the general options.
         << Options::ShowCommandLineHelp();
  return stream.str();
}

}  // namespace xtreemfs