text:
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Zen Enterprise Framework
//
// Copyright (C) 2001 - 2016 Raymond A. Richards
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#ifndef ZEN_ENTERPRISE_I_Response_HPP_INCLUDED
#define ZEN_ENTERPRISE_I_Response_HPP_INCLUDED

#include "Configuration.hpp"

#include <memory>

#include <Zen/Enterprise/I_Message.hpp>

#include <boost/noncopyable.hpp>
#include <boost/cstdint.hpp>

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Zen {
namespace Enterprise {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~

class ENTERPRISE_DLL_LINK I_Response
:   public virtual I_Message
{
    /// @name Types
    /// @{
public:
    /// @}

    /// @name I_Response interface.
    /// @{
public:
    /// Get the message Id associated with the request that
    /// resulted in this response.
    virtual boost::uint64_t getRequestMessageId() const = 0;
    /// @}

    /// @name Events
    /// @{
public:
    /// @}

    /// @name 'Structors
    /// @{
protected:
             I_Response() = default;
    virtual ~I_Response() = default;
    /// @}

};  // interface I_Response

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
}   // namespace Enterprise
}   // namespace Zen
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~

#endif // ZEN_ENTERPRISE_I_RESPONSE_HPP_INCLUDED

ext: hpp

max_stars_repo_name: indie-zen/zen-enterprise

max_issues_repo_name: indie-zen/zen-enterprise

max_forks_repo_name: indie-zen/zen-enterprise


text:
// Copyright (c) 2012-2014 Bitcoin developers
// Copyright (c) 2014-2015 Dash developers
// Copyright (c) 2015-2018 PIVX developers
// Copyright (c) 2018-2019 Chronon developers

// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "wallet/wallet.h"

#include <set>
#include <stdint.h>
#include <utility>
#include <vector>

#include <boost/test/unit_test.hpp>
#include "test_chronon.h"

// how many times to run all the tests to have a chance to catch errors that only show up with particular random shuffles
#define RUN_TESTS 100

// some tests fail 1% of the time due to bad luck.
// we repeat those tests this many times and only complain if all iterations of the test fail
#define RANDOM_REPEATS 5

typedef std::set<std::pair<const CWalletTx*,unsigned int> > CoinSet;

BOOST_FIXTURE_TEST_SUITE(wallet_tests, TestingSetup)

static CWallet wallet;
static std::vector<COutput> vCoins;

static void add_coin(const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = false, int nInput=0)
{
    static int nextLockTime = 0;
    CMutableTransaction tx;
    tx.nLockTime = nextLockTime++;        // so all transactions get different hashes
    tx.vout.resize(nInput+1);
    tx.vout[nInput].nValue = nValue;
    if (fIsFromMe) {
        // IsFromMe() returns (GetDebit() > 0), and GetDebit() is 0 if vin.empty(),
        // so stop vin being empty, and cache a non-zero Debit to fake out IsFromMe()
        tx.vin.resize(1);
    }
    CWalletTx* wtx = new CWalletTx(&wallet, tx);
    if (fIsFromMe)
    {
        wtx->fDebitCached = true;
        wtx->nDebitCached = 1;
    }
    COutput output(wtx, nInput, nAge, true);
    vCoins.push_back(output);
}

static void empty_wallet(void)
{
    for (COutput output : vCoins)
        delete output.tx;
    vCoins.clear();
}

static bool equal_sets(CoinSet a, CoinSet b)
{
    std::pair<CoinSet::iterator, CoinSet::iterator> ret = mismatch(a.begin(), a.end(), b.begin());
    return ret.first == a.end() && ret.second == b.end();
}

BOOST_AUTO_TEST_CASE(coin_selection_tests)
{
    CoinSet setCoinsRet, setCoinsRet2;

    LOCK(wallet.cs_wallet);

    empty_wallet();
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: robinadaptor/chronon

max_issues_repo_name: robinadaptor/chronon

max_forks_repo_name: robinadaptor/chronon


text:
//------------------------------------------------------------------------------------------------
// Copyright (c) 2012  Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome).
// All rights reserved.
//------------------------------------------------------------------------------------------------

/*******************************************************************************************************************************************************************************************
*    LICENSE NOTICE
********************************************************************************************************************************************************************************************
*    By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change
*    this code.
********************************************************************************************************************************************************************************************
*    1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at
*       g.iannello@unicampus.it for further details.
*    2. You agree to appropriately cite this work in your related studies and publications.
*
*       Bria, A., Iannello, G., "TeraStitcher - A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Microscopy Images", (2012) BMC Bioinformatics, 13 (1), art. no. 316.
*
*    3. This material is provided by  the copyright holders (Alessandro Bria  and  Giulio Iannello),  University Campus Bio-Medico and contributors "as is" and any express or implied war-
*       ranties, including, but  not limited to,  any implied warranties  of merchantability,  non-infringement, or fitness for a particular purpose are  disclaimed. In no event shall the
*       copyright owners, University Campus Bio-Medico, 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;reasonable royalties; or business interruption) however caused  and on any theory of liabil-
*       ity, 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.
*    4. Neither the name of University  Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or  promote products  derived from this software without
*       specific prior written permission.
********************************************************************************************************************************************************************************************/

/******************
*    CHANGELOG    *
*******************
* 2015-08-24. Giulio.     @FIXED memory leak in loadImageStack
* 2015-02-28. Giulio.     @ADDED saving of fields N_CHANS and N_BYTESxCHAN in the xml files
* 2015-02-26. Giulio.     @ADDED initialization of fields N_CHANS and N_BYTESxCHAN in constructor; this information is NOT saved in mdata.bin and xml files
* 2015-01-17. Alessandro. @ADDED constructor for initialization from XML.
* 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only).
* 2014-09-12. Alessandro. @FIXED 'init()' method to deal with non-empty tiles.
* 2014-09-05. Alessandro. @ADDED 'z_end' parameter in 'loadXML()' method to support sparse data feature.
* 2014-09-03. Alessandro. @ADDED 'Z_RANGES' attribute in the xml node.
* 2014-09-01. Alessandro. @FIXED 'binarizeInto()' and 'unbinarizeFrom()' to support sparse tiles.
* 2014-08-30. Alessandro. @ADDED 'hasValidImageData()' method.
* 2014-08-25. Alessandro. @REMOVED unused 'entry_k' variable declared in 'init()'.
*/

#ifdef _WIN32
    #include "dirent_win.h"
#else
    #include <dirent.h>
#endif
#include <iostream>
#include <string>
#include <list>
#include <sstream>
#include <boost/xpressive/xpressive.hpp>
#include "vmStackedVolume.h"
#include "vmStack.h"
#include "StackStitcher.h"
#include "Displacement.h"
#include "IOPluginAPI.h"

using namespace std;
using namespace vm;
using namespace iom;

//CONSTRUCTOR WITH ARGUMENTS
Stack::Stack(StackedVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, const char* _DIR_NAME) throw (iom::exception)
	: VirtualStack()
{
	#if VM_VERBOSE > 3
	printf("\t\t\t\tin Stack::Stack(StackedVolume* _CONTAINER, int _ROW_INDEX=%d, int _COL_INDEX=%d, char* _DIR_NAME=%s)\n",
		_ROW_INDEX, _COL_INDEX, _DIR_NAME);
	#endif

    CONTAINER = _CONTAINER;
    DIR_NAME = new char[strlen(_DIR_NAME)+1];
    strcpy(DIR_NAME, _DIR_NAME);
    ROW_INDEX = _ROW_INDEX;
    COL_INDEX = _COL_INDEX;

	init();
}

// 2015-01-17. Alessandro. @ADDED constructor for initialization from XML.
Stack::Stack(StackedVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, TiXmlElement* stack_node, int z_end) throw (iom::exception)
	: VirtualStack()
{
	#if VM_VERBOSE > 3
	printf("\t\t\t\tin Stack::Stack(StackedVolume* _CONTAINER, int _ROW_INDEX=%d, int _COL_INDEX=%d, TiXmlElement*, int z_end=%d)\n",
		_ROW_INDEX, _COL_INDEX, z_end);
	#endif

	// check for valid stack node
	if(!stack_node)
		throw iom::exception("not an xml node", __iom__current__function__);
	if( strcmp(stack_node->ToElement()->Value(), "Stack") != 0)
		throw iom::exception(iom::strprintf("invalid xml node name: expected \"Stack\", found \"%s\"", stack_node->ToElement()->Value()), __iom__current__function__);

	CONTAINER = _CONTAINER;
	DIR_NAME = new char[strlen(stack_node->Attribute("DIR_NAME"))+1];
	strcpy(DIR_NAME, stack_node->Attribute("DIR_NAME"));
	ROW_INDEX = _ROW_INDEX;
	COL_INDEX = _COL_INDEX;

	// first read image regex field (if any) from xml node
	readImgRegex(stack_node);

	// then scan folder for images
	init();

	// finally load other xml attributes
	loadXML(stack_node, z_end);
}

Stack::Stack(StackedVolume* _CONTAINER, int _ROW_INDEX, int _COL_INDEX, FILE* bin_file) throw (iom::exception)
	: VirtualStack()
{
	#if VM_VERBOSE > 3
	printf("\t\t\t\tin Stack::Stack(StackedVolume* _CONTAINER, int _ROW_INDEX=%d, int _COL_INDEX=%d, FILE* bin_file)\n",
		_ROW_INDEX, _COL_INDEX);
	#endif

	CONTAINER = _CONTAINER;
	ROW_INDEX = _ROW_INDEX;
	COL_INDEX = _COL_INDEX;

	unBinarizeFrom(bin_file);
}

Stack::~Stack()
{
	#if VM_VERBOSE > 3
	printf("\t\t\t\tin Stack[%d,%d]::~Stack()\n",ROW_INDEX, COL_INDEX);
	#endif

	NORTH.clear();
	EAST.clear();
	SOUTH.clear();
	WEST.clear();

    if(FILENAMES)
    {
		for(int z=0; z<DEPTH; z++)
			if(FILENAMES[z])
				delete[] FILENAMES[z];
		delete[] FILENAMES;
	}
	if(STACKED_IMAGE)
		delete[] STACKED_IMAGE;
	if(DIR_NAME)
		delete[] DIR_NAME;
}

void Stack::init() throw (iom::exception)
{
	#if VM_VERBOSE > 3
	printf("\t\t\t\tin Stack[%d,%d]::init()\n",ROW_INDEX, COL_INDEX);
	#endif

	//LOCAL variables
	string tmp;
	DIR *cur_dir_lev3;
	dirent *entry_lev3;
    list<string> entries_lev3;
	string entry;

	//opening stack directory
	char abs_path[S_STATIC_STRINGS_SIZE];
	sprintf(abs_path,"%s/%s", CONTAINER->getSTACKS_DIR(), DIR_NAME);
	cur_dir_lev3 = opendir(abs_path);
	if (!cur_dir_lev3)
	{
		char errMsg[S_STATIC_STRINGS_SIZE];
		sprintf(errMsg, "in Stack::init(): can't open directory \"%s\"", abs_path);
		throw iom::exception(errMsg);
	}

	//scanning third level of hierarchy which entries need to be ordered alphabetically. This is done using STL.
	while ((entry_lev3=readdir(cur_dir_lev3)))
	{
		tmp = entry_lev3->d_name;

		// 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only).
        if(img_regex.empty())
        {
			if(tmp.compare(".") != 0 && tmp.compare("..") != 0 && tmp.find(".") != string::npos)
                entries_lev3.push_back(tmp);
        }
        else
        {
            boost::xpressive::sregex rex = boost::xpressive::sregex::compile(img_regex.c_str());
            boost::xpressive::smatch what;
            if(boost::xpressive::regex_match(tmp, what, rex))
                entries_lev3.push_back(tmp);
        }
	}
	entries_lev3.sort();
    DEPTH = (int)entries_lev3.size();

    // close dir
	closedir(cur_dir_lev3);

	// 2014-08-30. Alessandro. @FIXED to deal with sparse data.
    // if stack is empty...
    if(DEPTH == 0)
	{
        // ...and SPARSE_DATA option is active, then exit
        if(vm::SPARSE_DATA)
            return;
        // ...otherwise throw an exception
        else
        {
            if(img_regex.empty())
                throw iom::exception(vm::strprintf("in Stack[%s]::init(): stack is empty. If that was your intent, please use the 'sparse data' option", DIR_NAME).c_str());
            else
                throw iom::exception(vm::strprintf("in Stack[%s]::init(): no files found that match regular expression \"%s\"", DIR_NAME, img_regex.c_str()).c_str());
        }
	}

    // convert filenames_list (STL list of <string> objects) into FILENAMES (1-D array of C-strings)
    FILENAMES = new char*[DEPTH];
    for(int z=0; z<DEPTH; z++)
	{
		entry = entries_lev3.front();
		FILENAMES[z] = new char[entry.size()+1];
		strcpy(FILENAMES[z], entry.c_str());
		entries_lev3.pop_front();
	}
    entries_lev3.clear();

    // extract HEIGHT and WIDTH attributes from first slice
	iom::IOPluginFactory::getPlugin2D(iom::IMIN_PLUGIN)->readMetadata(vm::strprintf("%s/%s/%s", CONTAINER->getSTACKS_DIR(), DIR_NAME, FILENAMES[0]), WIDTH, HEIGHT, N_BYTESxCHAN, N_CHANS);

	// 2014-09-12. Alessandro. @FIXED 'init()' method to deal with non-empty tiles.
	// add to 'z_ranges' the full range
	z_ranges.clear();
	z_ranges.push_back(vm::interval<int>(0, DEPTH));
}

//binarizing-unbinarizing methods
void Stack::binarizeInto(FILE* file) throw (iom::exception)
{
	#if VM_VERBOSE > 3
	printf("\t\t\t\tin Stack[%d,%d]::binarizeInto(...)\n",ROW_INDEX, COL_INDEX);
	#endif

	//LOCAL VARIABLES
	uint16 str_size=0;
	int i=0;

	fwrite(&HEIGHT, sizeof(int), 1, file);
	fwrite(&WIDTH, sizeof(int), 1, file);
	fwrite(&DEPTH, sizeof(int), 1, file);
	fwrite(&ABS_V, sizeof(int), 1, file);
	fwrite(&ABS_H, sizeof(int), 1, file);
	fwrite(&ABS_D, sizeof(int), 1, file);
	str_size = (uint16)strlen(DIR_NAME) + 1;
	fwrite(&str_size, sizeof(uint16), 1, file);
	fwrite(DIR_NAME, str_size, 1, file);
	for(i = 0; i < DEPTH; i++)
	{
		// 2014-09-01. Alessandro. @FIXED: added support for sparse tiles
		str_size = static_cast<uint16>( FILENAMES[i] ? strlen(FILENAMES[i]) + 1 : 0);
		fwrite(&str_size, sizeof(uint16), 1, file);
		if(FILENAMES[i])
			fwrite(FILENAMES[i], str_size, 1, file);
	}
}

void Stack::unBinarizeFrom(FILE* file) throw (iom::exception)
{
	#if VM_VERBOSE > 3
	printf("\t\t\t\tin Stack[%d,%d]::unBinarizeFrom(...)\n",ROW_INDEX, COL_INDEX);
	#endif

	//LOCAL VARIABLES
	uint16 str_size;
	int i;
	size_t fread_return_val;

	fread_return_val = fread(&HEIGHT, sizeof(int), 1, file);
	if(fread_return_val != 1) {
		fclose(file);
		throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file");
	}
	fread_return_val = fread(&WIDTH, sizeof(int), 1, file);
	if(fread_return_val != 1) {
		fclose(file);
		throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file");
	}
	fread_return_val = fread(&DEPTH, sizeof(int), 1, file);
	if(fread_return_val != 1) {
		fclose(file);
		throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file");
	}
	fread_return_val = fread(&ABS_V, sizeof(int), 1, file);
	if(fread_return_val != 1) {
		fclose(file);
		throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file");
	}
	fread_return_val = fread(&ABS_H, sizeof(int), 1, file);
	if(fread_return_val != 1) {
		fclose(file);
		throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file");
	}
	fread_return_val = fread(&ABS_D, sizeof(int), 1, file);
	if(fread_return_val != 1) {
		fclose(file);
		throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file");
	}
	fread_return_val = fread(&str_size, sizeof(uint16), 1, file);
	if(fread_return_val != 1) {
		fclose(file);
		throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file");
	}
	DIR_NAME = new char[str_size];
	fread_return_val = fread(DIR_NAME, str_size, 1, file);
	FILENAMES = new char*[DEPTH];
	for(i = 0; i < DEPTH; i++)
	{
		fread_return_val = fread(&str_size, sizeof(uint16), 1, file);
		if(fread_return_val != 1) {
			fclose(file);
			throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file");
		}

		// 2014-09-01. Alessandro. @FIXED: added support for sparse tiles.
		FILENAMES[i] = str_size ? new char[str_size] : 0;
		if(str_size)
		{
			fread_return_val = fread(FILENAMES[i], str_size, 1, file);
			if(fread_return_val != 1) {
				fclose(file);
				throw iom::exception("in Stack::unBinarizeFrom(...): error while reading binary metadata file");
			}
		}
	}

	// 2014-09-01. Alessandro. @ADDED support for sparse data.
	compute_z_ranges();
}

//XML methods
TiXmlElement* Stack::getXML()
{
	#if VM_VERBOSE > 3
	printf("......in Stack[%d,%d]::getXML()\n",ROW_INDEX, COL_INDEX);
	#endif

	TiXmlElement *xml_representation = new TiXmlElement("Stack");
	xml_representation->SetAttribute("N_CHANS",N_CHANS);
	xml_representation->SetAttribute("N_BYTESxCHAN",N_BYTESxCHAN);
	xml_representation->SetAttribute("ROW",ROW_INDEX);
	xml_representation->SetAttribute("COL",COL_INDEX);
	xml_representation->SetAttribute("ABS_V",ABS_V);
	xml_representation->SetAttribute("ABS_H",ABS_H);
	xml_representation->SetAttribute("ABS_D",ABS_D);
	xml_representation->SetAttribute("STITCHABLE",stitchable ? "yes" : "no");
	xml_representation->SetAttribute("DIR_NAME",DIR_NAME);

	// 2014-09-03. Alessandro. @ADDED 'Z_RANGES' attribute in the xml node
	std::string z_ranges_string;
	for(int k=0; k<z_ranges.size(); k++)
		z_ranges_string += vm::strprintf("[%d,%d)%s", z_ranges[k].start, z_ranges[k].end, k == z_ranges.size()-1 ? "" : ";");
	xml_representation->SetAttribute("Z_RANGES",z_ranges_string.c_str());
	writeImgRegex(xml_representation);

	vector<Displacement*>::iterator i;
	TiXmlElement *NORTH_displacements = new TiXmlElement("NORTH_displacements");
	for(i = NORTH.begin(); i != NORTH.end(); i++)
		NORTH_displacements->LinkEndChild((*i)->getXML());
	TiXmlElement *EAST_displacements = new TiXmlElement("EAST_displacements");
	for(i = EAST.begin(); i != EAST.end(); i++)
		EAST_displacements->LinkEndChild((*i)->getXML());
	TiXmlElement *SOUTH_displacements = new TiXmlElement("SOUTH_displacements");
	for(i = SOUTH.begin(); i != SOUTH.end(); i++)
		SOUTH_displacements->LinkEndChild((*i)->getXML());
	TiXmlElement *WEST_displacements = new TiXmlElement("WEST_displacements");
	for(i = WEST.begin(); i != WEST.end(); i++)
		WEST_displacements->LinkEndChild((*i)->getXML());
	xml_representation->LinkEndChild(NORTH_displacements);
	xml_representation->LinkEndChild(EAST_displacements);
	xml_representation->LinkEndChild(SOUTH_displacements);
	xml_representation->LinkEndChild(WEST_displacements);

	return xml_representation;
}

void Stack::loadXML(
	TiXmlElement *stack_node,
	int z_end)					// 2014-09-05. Alessandro. @ADDED 'z_end' parameter to support sparse data feature
	//										   Here 'z_end' identifies the range [0, z_end) that slices can span
throw (iom::exception)
{
	#if VM_VERBOSE > 3
	printf("\t\t\t\tin Stack[%d,%d]::loadXML(TiXmlElement *stack_node)\n",ROW_INDEX, COL_INDEX);
	#endif

	stack_node->QueryIntAttribute("N_CHANS",&N_CHANS);
	stack_node->QueryIntAttribute("N_BYTESxCHAN",&N_BYTESxCHAN);
	if ( N_CHANS == -1 ||N_BYTESxCHAN == -1 ) {
		iom::warning(iom::strprintf("old xml file: missing N_CHANS and N_BYTESxCHAN tags; class data members set to 1.").c_str(), __iom__current__function__);
		// data members set to 1 assuming that there is only one 8bits channel
		N_CHANS = 1;
		N_BYTESxCHAN = 1;
	}

	stack_node->QueryIntAttribute("ABS_V", &ABS_V);
	stack_node->QueryIntAttribute("ABS_H", &ABS_H);
	stack_node->QueryIntAttribute("ABS_D", &ABS_D);
	stitchable = strcmp(stack_node->Attribute("STITCHABLE"),"yes")==0 ? true : false;
	if(strcmp(stack_node->Attribute("DIR_NAME"), DIR_NAME) != 0)
	{
		char errMsg[2000];
		sprintf(errMsg, "in Stack[%s]::loadXML(...): Mismatch between xml file and %s in <DIR_NAME> field.", DIR_NAME, vm::BINARY_METADATA_FILENAME.c_str());
		throw iom::exception(errMsg);
	}

	// 2015-01-17. Alessandro. @ADDED support for all-in-one-folder data (import from xml only).
	readImgRegex(stack_node);

	// 2014-09-03. Alessandro. @ADDED 'Z_RANGES' attribute in the xml node
	const char* z_ranges_c = stack_node->Attribute("Z_RANGES");
	if( z_ranges_c )	// field is present: we can run 'sparse data' code
	{
		// nonempty tile
		if ( strlen(z_ranges_c) != 0 )
		{
			// parse 'Z_RANGES' field
			z_ranges.clear();
			std::string z_ranges_c_str = z_ranges_c;
			std::string z_ranges_string = vm::cls(z_ranges_c_str);
			std::vector<std::string> tokens;
			vm::split(z_ranges_string, ";", tokens);
			for(int i=0; i<tokens.size(); i++)
			{
				// ignore empty tokens
				if(tokens[i].empty())
					continue;

				// parse [start, end) interval
				std::vector<std::string> extremes;
				vm::split(tokens[i].substr(1, tokens[i].size()-2), ",", extremes);

				// check correct parsing
				if(extremes.size() != 2)
					throw iom::exception(vm::strprintf("in Stack(%s)::loadXML(): cannot parse 'Z_RANGES' subentry \"%s\"", DIR_NAME, tokens[i].c_str()).c_str());

				// get integral range
				int start = vm::str2num<int>(extremes[0]);
				int end   = vm::str2num<int>(extremes[1]);

				// check valid range
				if(start < 0 ||  start >= end ||  end > z_end)
					throw iom::exception(vm::strprintf("in Stack(%s)::loadXML(): 'Z_RANGES' subentry \"%s\" is out of range [%d,%d) ", DIR_NAME, tokens[i].c_str(), 0, z_end).c_str());

				// push range
				z_ranges.push_back(vm::interval<int>(start, end));
			}

			// check precondition: z_ranges should contain consecutive but not contiguous intervals [a_1,b_1), [a_2,b_2), ... such that a_n > b_(n-1)
			for(int i=1; i<z_ranges.size(); i++)
				if(z_ranges[i].start <= z_ranges[i-1].end)
					throw iom::exception(vm::strprintf("in Stack(%s)::loadXML(): wrong sequence in 'Z_RANGES' attribute. 'Z-RANGES' should contain "
					"consecutive but not contiguous intervals [a_1,b_1), [a_2,b_2), ... such that a_n > b_(n-1). "
					"Found a_%d(%d) <= b_%d(%d)", DIR_NAME, i, z_ranges[i].start, i-1, z_ranges[i-1].end).c_str());

			// if 'FILENAMES' is not a sparse list...
			if(DEPTH != z_end)
			{
				// make 'FILENAMES' a sparse list
				char **FILENAMES_sparse = new char*[z_end];
				for(int z=0; z<z_end; z++)
					FILENAMES_sparse[z] = 0;
				int i=0;
				for(int k=0; k<z_ranges.size(); k++)
					for(int z=z_ranges[k].start; z<z_ranges[k].end; z++)
					{
						// if we have used all the available slices and the current 'z_range' asks for others, throw an exception
						if(i >= DEPTH)
							throw iom::exception(vm::strprintf("in Stack(%s)::loadXML(): no more slices available to cover z-range [%d,%d)",
							DIR_NAME, z_ranges[k].start, z_ranges[k].end).c_str());

						FILENAMES_sparse[z] = FILENAMES[i++];
					}

				// substitute list of filenames with its sparse version
				if(FILENAMES)
					delete[] FILENAMES;
				FILENAMES = FILENAMES_sparse;
				DEPTH = z_end;
			}
			// ...otherwise check if the sparse list matches with z_ranges
			else
			{
				for(int i=0; i<DEPTH; i++)
					if(FILENAMES[i] && isEmpty(i,i))
						throw iom::exception(vm::strprintf("in Stack(%s)::loadXML(): mismatch between sparse list loaded from mdata.bin and 'Z_RANGES' loaded from xml. Please delete mdata.bin and re-load the xml.", DIR_NAME));
					else if(FILENAMES[i] == 0 && isComplete(i,i))
						throw iom::exception(vm::strprintf("in Stack(%s)::loadXML(): mismatch between sparse list loaded from mdata.bin and 'Z_RANGES' loaded from xml. Please delete mdata.bin and re-load the xml.", DIR_NAME));
			}
		}
		// 'Z_RANGES' field is present, but is empty: assume empty tile
		else
		{
			// make 'FILENAMES' a sparse list
			if(FILENAMES)
				delete[] FILENAMES;
			FILENAMES = new char*[z_end];
			for(int z=0; z<z_end; z++)
				FILENAMES[z] = 0;
			DEPTH = z_end;
		}
	}
	// no 'Z_RANGES' field (old or incomplete XML)
	else
	{
		// if 'sparse data' option is active, 'Z_RANGES' must be provided (then throw an exception)
		if(SPARSE_DATA)
			throw iom::exception(vm::strprintf("in Stack::loadXML(): cannot find 'Z_RANGES' attribute in stack \"%s\" xml node ('sparse data' option is active). "
			"Please edit your XML file accordingly or disable 'sparse data' option.", DIR_NAME).c_str());

		// 'sparse data' option is not active and 'Z_RANGES' field is not present, but DEPTH does not match with z_end: throw an exception
		if(DEPTH != z_end)
			throw iom::exception(vm::strprintf("in Stack::loadXML(): stack %s has %d slices, but volume has %d. If that was your intent, please use "
			"'sparse data' option.", DIR_NAME, DEPTH, z_end).c_str());

		// all checks were successful: assume tile is not sparse
        z_ranges.clear();
        z_ranges.push_back(vm::interval<int>(0, DEPTH));
	}

	TiXmlElement *NORTH_displacements = stack_node->FirstChildElement("NORTH_displacements");
	for(TiXmlElement *displ_node = NORTH_displacements->FirstChildElement("Displacement"); displ_node; displ_node = displ_node->NextSiblingElement())
		NORTH.push_back(Displacement::getDisplacementFromXML(displ_node));
	TiXmlElement *EAST_displacements = stack_node->FirstChildElement("EAST_displacements");
	for(TiXmlElement *displ_node = EAST_displacements->FirstChildElement("Displacement"); displ_node; displ_node = displ_node->NextSiblingElement())
		EAST.push_back(Displacement::getDisplacementFromXML(displ_node));
	TiXmlElement *SOUTH_displacements = stack_node->FirstChildElement("SOUTH_displacements");
	for(TiXmlElement *displ_node = SOUTH_displacements->FirstChildElement("Displacement"); displ_node; displ_node = displ_node->NextSiblingElement())
		SOUTH.push_back(Displacement::getDisplacementFromXML(displ_node));
	TiXmlElement *WEST_displacements = stack_node->FirstChildElement("WEST_displacements");
	for(TiXmlElement *displ_node = WEST_displacements->FirstChildElement("Displacement"); displ_node; displ_node = displ_node->NextSiblingElement())
		WEST.push_back(Displacement::getDisplacementFromXML(displ_node));

}

//loads image stack from <first_file> to <last_file> extremes included, if not specified loads entire Stack
iom::real_t* Stack::loadImageStack(int first_file, int last_file) throw (iom::exception)
{
	#if VM_VERBOSE > 3
	printf("\t\t\t\tin Stack[%d,%d](%s, empty = %s)::loadImageStack(first_file = %d, last_file = %d)\n",ROW_INDEX, COL_INDEX, DIR_NAME, isEmpty() ? "true": "false", first_file, last_file);
	#endif

	//// if stack is empty in the given range, just return a black image
	//if(isEmpty(first_file, last_file))
	//{
	//	// check and adjust file selection
	//	first_file = (first_file == -1 ? 0 : first_file);
	//	last_file  = (last_file  == -1 ? DEPTH - 1 : last_file );
	//	first_file = min(first_file, DEPTH-1);
	//	last_file = min(last_file, DEPTH-1);

	//	// allocate and initialize a black stack
	//	uint64 image_size = static_cast<uint64>(WIDTH) * static_cast<uint64>(HEIGHT) * static_cast<uint64>(last_file-first_file+1);
	//	STACKED_IMAGE = new iom::real_t[image_size];
	//	for(uint64 k=0; k<image_size; k++)
	//		STACKED_IMAGE[k] = 0;
	//}
	//else
	//{
	//	STACKED_IMAGE = iom::IOPluginFactory::getPlugin2D(iom::IMIN_PLUGIN)->readData(FILENAMES, DEPTH,
	//	(std::string(CONTAINER->getSTACKS_DIR()) + "/" + DIR_NAME).c_str(), first_file, last_file, isSparse());
	//}

	uint64 image_stack_width=0, image_stack_height=0, z=0;
 	iom::real_t *raw_data;

	unsigned char *data;
	int img_width;
	int img_height;
	int img_bytes_x_chan;
	int img_chans;

	// check and adjust file selection
	first_file = (first_file == -1 ? 0 : first_file);
	last_file  = (last_file  == -1 ? DEPTH - 1 : last_file );
	first_file = min(first_file, DEPTH-1);
	last_file = min(last_file, DEPTH-1);

	if(isEmpty(first_file, last_file))
	{
		// allocate and initialize a black stack
		uint64 image_size = static_cast<uint64>(WIDTH) * static_cast<uint64>(HEIGHT) * static_cast<uint64>(last_file-first_file+1);
		STACKED_IMAGE = new iom::real_t[image_size];
		for(uint64 k=0; k<image_size; k++)
			STACKED_IMAGE[k] = 0;

		return STACKED_IMAGE;
	}

	// build absolute image path of first file in the stack
	int i = first_file;
	while ( isSparse() && i<=last_file && FILENAMES[i]==0 ) // look for existing file
		i++;
	if ( i > last_file )
		throw iom::exception("unexpected exception: substack is entirely empty", __iom__current__function__);

	std::string image_path = std::string(CONTAINER->getSTACKS_DIR()) + "/" + DIR_NAME + "/" + FILENAMES[i];

	iom::IOPluginFactory::getPlugin2D(iom::IMIN_PLUGIN)->readMetadata(image_path,img_width,img_height,img_bytes_x_chan,img_chans);

	// allocate buffer
	data = new unsigned char[img_width * img_height * img_bytes_x_chan * img_chans];

	// loop over files
	for(int file_i = first_file; file_i <= last_file; file_i++, z++) {

		// skip missing slices if stack is sparse
		if(isSparse() && !FILENAMES[file_i])
			continue;

		// if stack is not sparse, a missing slice must throw an iom::exception
		if(!FILENAMES[file_i])
			throw iom::exception("invalid slice filename in non-sparse tile", __iom__current__function__);

		// build absolute image path
		image_path = std::string(CONTAINER->getSTACKS_DIR()) + "/" + DIR_NAME + "/" + FILENAMES[file_i];

		iom::IOPluginFactory::getPlugin2D(iom::IMIN_PLUGIN)->readData(image_path,img_width,img_height,img_bytes_x_chan,img_chans,data);

		// initialize output data and image dimensions
		if(!STACKED_IMAGE)
		{
			image_stack_height = (uint64) img_height;
			image_stack_width  = (uint64) img_width;
			uint64 image_stack_size = image_stack_width * image_stack_height * (last_file - first_file + 1);
			STACKED_IMAGE = new iom::real_t[image_stack_size];
			for(uint64 j=0; j < image_stack_size; j++)
				STACKED_IMAGE[j] = 0;		// default is 0 (black)
		}
		else if(image_stack_width != (uint64)img_width || image_stack_height != (uint64)img_height)
			throw iom::exception("images in stack have not the same dimensions", __iom__current__function__);

		int offset;

		// convert image to [0.0,1.0]-valued array
		if ( img_chans == 1 ) {
			raw_data = &STACKED_IMAGE[z*img_height*img_width];
			if ( img_bytes_x_chan == 1 ) {
				for(int i = 0; i < (img_height * img_width); i++)
					raw_data[i] = (iom::real_t) data[i]/255.0f;
			}
			else { // img_bytes_x_chan == 2
				for(int i = 0; i < (img_height * img_width); i++)
					raw_data[i] = (iom::real_t) ((uint16 *)data)[i]/65535.0f; // data must be interpreted as a uint16 array
			}
		}
		else { // conversion to an intensity image
			// test how channel are stored in the returned buffer 'data'
			if ( iom::IOPluginFactory::getPlugin2D(iom::IMIN_PLUGIN)->isChansInterleaved() ) {
				if ( CHANS == iom::ALL ) {
					throw iom::exception("conversion from multi-channel to intensity images not supported.", __iom__current__function__);
				}
				else if ( CHANS == iom::R ) {
					offset = 0;
				}
				else if ( CHANS == iom::G ) {
					offset = 1;
				}
				else if ( CHANS == iom::B ) {
					offset = 2;
				}
				else {
					throw iom::exception("wrong value for parameter iom::CHANNEL_SELECTION.", __iom__current__function__);
				}
				raw_data = &STACKED_IMAGE[z*img_height*img_width];
				if ( img_bytes_x_chan == 1 )
					for(int i = 0; i < (img_height * img_width); i++)
						raw_data[i] = (iom::real_t) data[3*i + offset]/255.0f;
				else // img_bytes_x_chan == 2
					for(int i = 0; i < (img_height * img_width); i++)
						raw_data[i] = (iom::real_t) ((uint16 *)data)[3*i + offset]/65535.0f; // data must be interpreted as a uint16 array
			}
			else {
				throw iom::exception("channels are not interleaved in the returned buffer 'data', conversion to intensity images not supported yet.");
			}
		}
	}

	// 2015-08-24. Giulio. data must be released
	delete [] data;

	return STACKED_IMAGE;
}

//deallocates memory used by STACKED_IMAGE
void Stack::releaseImageStack()
{
	if(STACKED_IMAGE)
		delete[] STACKED_IMAGE;
    STACKED_IMAGE=0;
}

// compute 'z_ranges'
void
	Stack::compute_z_ranges(
	std::set<std::string> const * z_coords /*= 0*/)	// set of z-coordinates where at least one slice (of a certain stack) is available
	throw (iom::exception)								// if null, 'z_ranges' will be compute based on 'FILENAMES' vector
{
	// if 'z_coords' has been provided, we use it to associate each file in 'FILENAMES' to the correspondent z-coordinate
	if(z_coords)
	{
		// check for nonempty 'z_coords'
		if(z_coords->empty())
			throw iom::exception("in Stack::compute_z_ranges(): z_coords is empty");

		// associate each file to the correspondent z-coordinate
		char **FILENAMES_sparse = new char*[z_coords->size()];
		int DEPTH_sparse = 0;
		int k=0;
        for(std::set<std::string>::const_iterator it = z_coords->begin(); it != z_coords->end(); it++)
		{
			if(k<DEPTH && it->compare(VirtualVolume::name2coordZ(FILENAMES[k])) == 0)
				FILENAMES_sparse[DEPTH_sparse++] = FILENAMES[k++];
			else
				FILENAMES_sparse[DEPTH_sparse++] = 0;
		}

		// substitute list of filenames with its sparse version
		if(FILENAMES)
			delete[] FILENAMES;
		FILENAMES = FILENAMES_sparse;
		DEPTH = DEPTH_sparse;
	}

	// compute 'z_range' from 'FILENAMES'
	bool interval_start = true;
	bool interval_stop = false;
    z_ranges.clear();
	for(int k=0; k<DEPTH; k++)
	{
		// valid slice found
		if(FILENAMES[k] && interval_start)
		{
			interval_start = false;
			interval_stop  = true;
			z_ranges.push_back(vm::interval<int>(k, -1));
		}
		if(FILENAMES[k] == 0 && interval_stop)
		{
			interval_start = true;
			interval_stop  = false;
			z_ranges.back().end = k;
		}
	}
	if(!z_ranges.empty() && z_ranges.back().end == -1)
		z_ranges.back().end = DEPTH;
}


text:
#include <Eigen/Core>
#include <cmath>
#include <fstream>
#include <iostream>
#include <mathtoolbox/gaussian-process-regression.hpp>
#include <random>
#include <string>
#include <timer.hpp>
#include <vector>

using Eigen::MatrixXd;
using Eigen::VectorXd;

namespace
{
    std::random_device                     seed;
    std::default_random_engine             engine(seed());
    std::uniform_real_distribution<double> uniform_dist(0.0, 1.0);
    std::normal_distribution<double>       normal_dist(0.0, 1.0);

    double CalculateFunction(double x) { return x * std::sin(10.0 * x); }
} // namespace

int main(int argc, char** argv)
{
    // Set a output directory path
    const std::string output_directory_path = (argc < 2) ? "." : argv[1];

    // Define the scene setting
    constexpr int    number_of_samples = 20;
    constexpr double noise_intensity   = 0.010;

    // Generate (and export) scattered data
    std::ofstream scattered_data_stream(output_directory_path + "/scattered_data.csv");
    scattered_data_stream << "x,y" << std::endl;
    MatrixXd X(1, number_of_samples);
    VectorXd y(number_of_samples);
    for (int i = 0; i < number_of_samples; ++i)
    {
        X(0, i) = uniform_dist(engine);
        y(i)    = CalculateFunction(X(0, i)) + noise_intensity * normal_dist(engine);

        scattered_data_stream << X(0, i) << "," << y(i) << std::endl;
    }
    scattered_data_stream.close();

    // Define the kernel type
    const auto kernel_type = mathtoolbox::GaussianProcessRegressor::KernelType::ArdMatern52;

    // Instantiate the interpolation object
    mathtoolbox::GaussianProcessRegressor regressor(X, y, kernel_type);

    // Perform hyperparameter estimation
    const Eigen::Vector2d default_kernel_hyperparams{0.50, 0.50};
    {
        timer::Timer t("maximum likelihood estimation");
        regressor.PerformMaximumLikelihood(default_kernel_hyperparams, 0.010);
    }

    // Define constants for export
    constexpr int    resolution       = 200;
    constexpr double percentile_point = 1.95996398454005423552;

    // Calculate (and export) predictive distribution
    std::ofstream estimated_data_stream(output_directory_path + "/estimated_data.csv");
    estimated_data_stream << "x,mean,standard deviation,95-percent upper,95-percent lower" << std::endl;
    for (int i = 0; i <= resolution; ++i)
    {
        const double x = (1.0 / static_cast<double>(resolution)) * i;
        const double y = regressor.PredictMean(VectorXd::Constant(1, x));
        const double s = regressor.PredictStdev(VectorXd::Constant(1, x));

        estimated_data_stream << x << "," << y << "," << s << "," << y + percentile_point * s << ","
                              << y - percentile_point * s << std::endl;
    }
    estimated_data_stream.close();

    return 0;
}

max_stars_repo_name: yuki-koyama/mathtoolbox


text:
//
//	FILE NAME:	$HeadURL$
//
//	DESCRIPTION:
//
//	REVISION:		$Revision$
//
//	COPYRIGHT:	(c) 2007 Advertising.com All Rights Reserved.
//
//	LAST UPDATED:	$Date$
//	UPDATED BY:	$Author$

#include "DataProxyServiceSystest.hpp"
#include "TempDirectory.hpp"
#include "FileUtilities.hpp"
#include "NetworkUtilities.hpp"
#include "ShellExecutor.hpp"
#include "RESTClient.hpp"
#include "AssertThrowWithMessage.hpp"
#include <fstream>
#include <vector>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>

CPPUNIT_TEST_SUITE_REGISTRATION( DataProxyServiceSystest );

#define VERIFY_ACCESS( i_Method, i_Endpoint, i_Parameters, i_Allowed ) \
{ \
	std::ostringstream result; \
	i_Parameters.SetMethod( i_Method ); \
	if( !i_Allowed ) \
	{ \
		CPPUNIT_ASSERT_THROW_WITH_MESSAGE( RESTClient().Execute( i_Endpoint, result, i_Parameters ), HttpBaseException, \
			".*:\\d+: Server returned HTTP code 403: .* Incoming request cannot be satisfied because requesting client is not in the access whitelist .*" ); \
	} \
	else \
	{ \
		CPPUNIT_ASSERT_NO_THROW( RESTClient().Execute( i_Endpoint, result, i_Parameters ) ); \
	} \
}

DataProxyServiceSystest::DataProxyServiceSystest( void )
:   m_pTempDir(NULL)
{
}

DataProxyServiceSystest::~DataProxyServiceSystest( void )
{
}

void DataProxyServiceSystest::setUp( void )
{
	m_pTempDir.reset( new TempDirectory() );
}

void DataProxyServiceSystest::tearDown( void )
{
	m_pTempDir.reset( NULL );
}

void DataProxyServiceSystest::testHappyPath( void )
{
	std::string nodeDir( m_pTempDir->GetDirectoryName() + "/nodeDir" );
	CPPUNIT_ASSERT_NO_THROW( FileUtilities::CreateDirectory( nodeDir ) );

	std::string loadWhitelistFile( m_pTempDir->GetDirectoryName() + "/load_whitelist" );
	std::string storeWhitelistFile( m_pTempDir->GetDirectoryName() + "/store_whitelist" );
	std::string deleteWhitelistFile( m_pTempDir->GetDirectoryName() + "/delete_whitelist" );
	std::string pingWhitelistFile( m_pTempDir->GetDirectoryName() + "/ping_whitelist" );

	std::string dplConfigFileSpec = m_pTempDir->GetDirectoryName() + "/dplConfig.xml";
	std::ofstream file( dplConfigFileSpec.c_str() );
	file << "<DplConfig>" << std::endl
		 << "  <DataNode name=\"/my/path\" type=\"local\" location=\"" << nodeDir << "\" />" << std::endl
		 << "</DplConfig>" << std::endl;
	file.close();

	uint port = NetworkUtilities::FindEmptyPort();

	std::stringstream procPath;
	procPath << "/proc/" << ::getpid() << "/exe";
	std::string dirSpec( FileUtilities::GetDirName( FileUtilities::GetActualPath( procPath.str() ) ) );

	std::stringstream cmd;
	cmd << dirSpec << "/dplService "
		<< " --dpl_config " << dplConfigFileSpec
		<< " --port " << port
		<< " --instance_id systemtest_instance"
		<< " --num_threads 4"
		<< " --load_whitelist_file " << loadWhitelistFile
		<< " --store_whitelist_file " << storeWhitelistFile
		<< " --delete_whitelist_file " << deleteWhitelistFile
		<< " --ping_whitelist_file " << pingWhitelistFile;

	ShellExecutor exe( cmd.str() );
	std::stringstream out;
	std::stringstream err;

	exe.RunInBackground( out, err );

	::usleep( 100000 );

	std::stringstream base;
	base << "http://localhost:" << port;

	// PING the service
	std::ostringstream results;
	RESTParameters params;
	params.SetMethod( std::string("HEAD") );
	RESTClient client;
	CPPUNIT_ASSERT_NO_THROW( client.Execute( base.str() + "/my/path/?mode=rwd", results, params ) );
	CPPUNIT_ASSERT_EQUAL( std::string(), results.str() );

	std::stringstream endpoint;
	endpoint << base.str() << "/my/path/?query1=value1&query2=value2";

	// POST data to the service
	std::istringstream data( "This is some data that will eventually be returned via GET" );
	params.SetCompression( IDENTITY );
	params.SetMethod( std::string( "POST" ) );
	CPPUNIT_ASSERT_NO_THROW( client.Execute( endpoint.str(), data, params ) );

	// now GET it back
	results.str("");
	params.SetMethod( std::string( "GET" ) );
	CPPUNIT_ASSERT_NO_THROW( client.Execute( endpoint.str(), results, params ) );
	CPPUNIT_ASSERT_EQUAL( data.str(), results.str() );

	results.str("");
	params.SetCompression( DEFLATE );
	CPPUNIT_ASSERT_NO_THROW( client.Execute( endpoint.str(), results, params ) );
	CPPUNIT_ASSERT_EQUAL( data.str(), results.str() );

	results.str("");
	params.SetCompression( GZIP );
	CPPUNIT_ASSERT_NO_THROW( client.Execute( endpoint.str(), results, params ) );
	CPPUNIT_ASSERT_EQUAL( data.str(), results.str() );

	// DELETE the file
	results.str("");
	params.SetMethod( std::string( "DELETE" ) );
	params.SetCompression( IDENTITY );
	CPPUNIT_ASSERT_NO_THROW( client.Execute( endpoint.str(), results, params ) );
	CPPUNIT_ASSERT_EQUAL( std::string(""), results.str() );
	CPPUNIT_ASSERT( !FileUtilities::DoesFileExist( nodeDir + "/query1~value1^query2~value2" ) );

	// DELETE the file again
	results.str("");
	CPPUNIT_ASSERT_NO_THROW( client.Execute( endpoint.str(), results, params ) );
	CPPUNIT_ASSERT_EQUAL( std::string(""), results.str() );
	CPPUNIT_ASSERT( !FileUtilities::DoesFileExist( nodeDir + "/query1~value1^query2~value2" ) );

	// verify load whitelist behavior
	FileUtilities::Touch( nodeDir + "/query1~value1^query2~value2" );
	VERIFY_ACCESS( std::string("HEAD"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("GET"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("POST"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("DELETE"), endpoint.str(), params, true );
	FileUtilities::Touch( loadWhitelistFile );
	FileUtilities::Touch( nodeDir + "/query1~value1^query2~value2" );
	VERIFY_ACCESS( std::string("HEAD"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("GET"), endpoint.str(), params, false );
	VERIFY_ACCESS( std::string("POST"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("DELETE"), endpoint.str(), params, true );
	FileUtilities::Remove( loadWhitelistFile );
	FileUtilities::Touch( nodeDir + "/query1~value1^query2~value2" );
	VERIFY_ACCESS( std::string("HEAD"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("GET"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("POST"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("DELETE"), endpoint.str(), params, true );

	// verify store whitelist behavior
	FileUtilities::Touch( nodeDir + "/query1~value1^query2~value2" );
	VERIFY_ACCESS( std::string("HEAD"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("GET"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("POST"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("DELETE"), endpoint.str(), params, true );
	FileUtilities::Touch( storeWhitelistFile );
	FileUtilities::Touch( nodeDir + "/query1~value1^query2~value2" );
	VERIFY_ACCESS( std::string("HEAD"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("GET"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("POST"), endpoint.str(), params, false );
	VERIFY_ACCESS( std::string("DELETE"), endpoint.str(), params, true );
	FileUtilities::Remove( storeWhitelistFile );
	FileUtilities::Touch( nodeDir + "/query1~value1^query2~value2" );
	VERIFY_ACCESS( std::string("HEAD"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("GET"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("POST"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("DELETE"), endpoint.str(), params, true );

	// verify delete whitelist behavior
	FileUtilities::Touch( nodeDir + "/query1~value1^query2~value2" );
	VERIFY_ACCESS( std::string("HEAD"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("GET"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("POST"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("DELETE"), endpoint.str(), params, true );
	FileUtilities::Touch( deleteWhitelistFile );
	FileUtilities::Touch( nodeDir + "/query1~value1^query2~value2" );
	VERIFY_ACCESS( std::string("HEAD"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("GET"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("POST"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("DELETE"), endpoint.str(), params, false );
	FileUtilities::Remove( deleteWhitelistFile );
	FileUtilities::Touch( nodeDir + "/query1~value1^query2~value2" );
	VERIFY_ACCESS( std::string("HEAD"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("GET"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("POST"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("DELETE"), endpoint.str(), params, true );

	// verify ping whitelist behavior
	FileUtilities::Touch( nodeDir + "/query1~value1^query2~value2" );
	VERIFY_ACCESS( std::string("HEAD"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("GET"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("POST"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("DELETE"), endpoint.str(), params, true );
	FileUtilities::Touch( pingWhitelistFile );
	FileUtilities::Touch( nodeDir + "/query1~value1^query2~value2" );
	VERIFY_ACCESS( std::string("HEAD"), endpoint.str(), params, false );
	VERIFY_ACCESS( std::string("GET"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("POST"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("DELETE"), endpoint.str(), params, true );
	FileUtilities::Remove( pingWhitelistFile );
	FileUtilities::Touch( nodeDir + "/query1~value1^query2~value2" );
	VERIFY_ACCESS( std::string("HEAD"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("GET"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("POST"), endpoint.str(), params, true );
	VERIFY_ACCESS( std::string("DELETE"), endpoint.str(), params, true );
}

max_stars_repo_name: aol/DataProxyLibrary

max_issues_repo_name: aol/DataProxyLibrary

max_forks_repo_name: aol/DataProxyLibrary


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

#include <Eigen/Eigenvalues>

#include "SurgSim/Collision/CollisionPair.h"
#include "SurgSim/Collision/Representation.h"
#include "SurgSim/DataStructures/DataGroupBuilder.h"
#include "SurgSim/DataStructures/DataStructuresConvert.h"
#include "SurgSim/Framework/FrameworkConvert.h"
#include "SurgSim/Input/InputComponent.h"
#include "SurgSim/Input/OutputComponent.h"
#include "SurgSim/Math/MathConvert.h"
#include "SurgSim/Math/Matrix.h"
#include "SurgSim/Math/Quaternion.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Physics/RigidRepresentation.h"
#include "SurgSim/Physics/VirtualToolCoupler.h"

using SurgSim::Math::makeSkewSymmetricMatrix;
using SurgSim::Math::Vector3d;
using SurgSim::Math::Vector6d;
using SurgSim::Math::Matrix33d;
using SurgSim::Math::Matrix66d;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Quaterniond;
using SurgSim::Framework::checkAndConvert;

namespace SurgSim
{

namespace Physics
{
SURGSIM_REGISTER(SurgSim::Framework::Component, SurgSim::Physics::VirtualToolCoupler, VirtualToolCoupler);

VirtualToolCoupler::VirtualToolCoupler(const std::string& name) :
	SurgSim::Framework::Behavior(name),
	m_poseName(SurgSim::DataStructures::Names::POSE),
	m_linearStiffness(std::numeric_limits<double>::quiet_NaN()),
	m_linearDamping(std::numeric_limits<double>::quiet_NaN()),
	m_angularStiffness(std::numeric_limits<double>::quiet_NaN()),
	m_angularDamping(std::numeric_limits<double>::quiet_NaN()),
	m_localAttachmentPoint(Vector3d(std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN(),
									std::numeric_limits<double>::quiet_NaN())),
	m_calculateInertialTorques(false),
	m_initializeRigidWithInputPose(true),
	m_logger(SurgSim::Framework::Logger::getLogger("Physics/VirtualToolCoupler")),
	m_hapticOutputOnlyWhenColliding(false),
	m_previousInputPose(Math::RigidTransform3d::Identity()),
	m_poseIndex(-1),
	m_linearVelocityIndex(-1),
	m_angularVelocityIndex(-1),
	m_forceIndex(-1),
	m_torqueIndex(-1),
	m_inputLinearVelocityIndex(-1),
	m_inputAngularVelocityIndex(-1),
	m_inputPoseIndex(-1),
	m_springJacobianIndex(-1),
	m_damperJacobianIndex(-1)
{
	SURGSIM_ADD_SERIALIZABLE_PROPERTY(VirtualToolCoupler, SurgSim::DataStructures::OptionalValue<double>,
									  LinearStiffness, getOptionalLinearStiffness, setOptionalLinearStiffness);
	SURGSIM_ADD_SERIALIZABLE_PROPERTY(VirtualToolCoupler, SurgSim::DataStructures::OptionalValue<double>,
									  LinearDamping, getOptionalLinearDamping, setOptionalLinearDamping);
	SURGSIM_ADD_SERIALIZABLE_PROPERTY(VirtualToolCoupler, SurgSim::DataStructures::OptionalValue<double>,
									  AngularStiffness, getOptionalAngularStiffness, setOptionalAngularStiffness);
	SURGSIM_ADD_SERIALIZABLE_PROPERTY(VirtualToolCoupler, SurgSim::DataStructures::OptionalValue<double>,
									  AngularDamping, getOptionalAngularDamping, setOptionalAngularDamping);
	SURGSIM_ADD_SERIALIZABLE_PROPERTY(VirtualToolCoupler,
									  SurgSim::DataStructures::OptionalValue<SurgSim::Math::Vector3d>, AttachmentPoint,
									  getOptionalAttachmentPoint, setOptionalAttachmentPoint);
	SURGSIM_ADD_SERIALIZABLE_PROPERTY(VirtualToolCoupler, bool, CalculateInertialTorques,
									  getCalculateInertialTorques, setCalculateInertialTorques);
	SURGSIM_ADD_SERIALIZABLE_PROPERTY(VirtualToolCoupler, bool, HapticOutputOnlyWhenColliding,
									  isHapticOutputOnlyWhenColliding, setHapticOutputOnlyWhenColliding);

	SURGSIM_ADD_SERIALIZABLE_PROPERTY(VirtualToolCoupler, std::shared_ptr<SurgSim::Framework::Component>,
									  Input, getInput, setInput);
	SURGSIM_ADD_SERIALIZABLE_PROPERTY(VirtualToolCoupler, std::shared_ptr<SurgSim::Framework::Component>,
									  Output, getOutput, setOutput);
	SURGSIM_ADD_SERIALIZABLE_PROPERTY(VirtualToolCoupler, std::shared_ptr<SurgSim::Framework::Component>,
									  Representation, getRepresentation, setRepresentation);

	SURGSIM_ADD_SERIALIZABLE_PROPERTY(VirtualToolCoupler, bool, IntializeRigidWithInputPose,
									  isInitializingRigidWithInputPose, setInitializeRigidWithInputPose);
}

VirtualToolCoupler::~VirtualToolCoupler()
{
}

const std::shared_ptr<SurgSim::Framework::Component> VirtualToolCoupler::getInput()
{
	return m_input;
}

void VirtualToolCoupler::setInput(const std::shared_ptr<SurgSim::Framework::Component> input)
{
	m_input = checkAndConvert<SurgSim::Input::InputComponent>(input, "SurgSim::Input::InputComponent");
}

const std::shared_ptr<SurgSim::Framework::Component> VirtualToolCoupler::getOutput()
{
	return m_output;
}

void VirtualToolCoupler::setOutput(const std::shared_ptr<SurgSim::Framework::Component> output)
{
	m_output = checkAndConvert<SurgSim::Input::OutputComponent>(output, "SurgSim::Input::OutputComponent");
}

const std::shared_ptr<SurgSim::Framework::Component> VirtualToolCoupler::getRepresentation()
{
	return m_rigid;
}

void VirtualToolCoupler::setRepresentation(const std::shared_ptr<SurgSim::Framework::Component> rigid)
{
	m_rigid = std::dynamic_pointer_cast<SurgSim::Physics::RigidRepresentation>(rigid);
}

const std::string& VirtualToolCoupler::getPoseName()
{
	return m_poseName;
}

void VirtualToolCoupler::setPoseName(const std::string& poseName)
{
	m_poseName = poseName;
}

void VirtualToolCoupler::update(double dt)
{
	DataStructures::DataGroup inputData;
	m_input->getData(&inputData);
	inputData.poses().cacheIndex(m_poseName, &m_poseIndex);
	inputData.vectors().cacheIndex(DataStructures::Names::LINEAR_VELOCITY, &m_linearVelocityIndex);
	if (m_linearVelocityIndex < 0)
	{
		SURGSIM_LOG_ONCE(m_logger, WARNING) << getFullName() << " is receiving an input DataGroup that does not "
			<< "contain a linear velocity vector named " << DataStructures::Names::LINEAR_VELOCITY
			<< ", so it will be estimated.";
	}
	inputData.vectors().cacheIndex(DataStructures::Names::ANGULAR_VELOCITY, &m_angularVelocityIndex);
	if (m_angularVelocityIndex < 0)
	{
		SURGSIM_LOG_ONCE(m_logger, WARNING) << getFullName() << " is receiving an input DataGroup that does not "
			<< "contain an angular velocity vector named " << DataStructures::Names::ANGULAR_VELOCITY
			<< ") so it will be estimated.";
	}

	RigidTransform3d inputPose;
	if (inputData.poses().get(m_poseIndex, &inputPose))
	{
		Vector3d inputLinearVelocity(Vector3d::Zero());
		const bool gotInputLinearVelocity = inputData.vectors().get(m_linearVelocityIndex, &inputLinearVelocity);
		if (!gotInputLinearVelocity)
		{
			inputLinearVelocity = (inputPose.translation() - m_previousInputPose.translation()) / dt;
		}

		Vector3d inputAngularVelocity(Vector3d::Zero());
		const bool gotInputAngularVelocity = inputData.vectors().get(m_angularVelocityIndex, &inputAngularVelocity);
		if (!gotInputAngularVelocity)
		{
			Math::computeRotationVector(inputPose, m_previousInputPose, &inputAngularVelocity);
			inputAngularVelocity /= dt;
		}
		m_previousInputPose = inputPose;

		RigidTransform3d inputAlignment = m_input->getLocalPose();
		inputPose = inputAlignment * inputPose;
		if (m_initializeRigidWithInputPose)
		{
			m_initializeRigidWithInputPose = false;
			setInitialInputPose(inputPose);
		}
		inputLinearVelocity = inputAlignment.linear() * inputLinearVelocity;
		inputAngularVelocity = inputAlignment.rotation() * inputAngularVelocity;

		RigidState objectState(m_rigid->getCurrentState());
		RigidTransform3d objectPose(objectState.getPose());
		Vector3d objectPosition = objectPose * m_rigid->getMassCenter();
		Vector3d attachmentPoint = objectPose * m_localAttachmentPoint;
		Vector3d leverArm = attachmentPoint - objectPosition;
		Vector3d attachmentPointVelocity = objectState.getLinearVelocity();
		attachmentPointVelocity += objectState.getAngularVelocity().cross(leverArm);

		Vector3d force = m_linearStiffness * (inputPose.translation() - attachmentPoint);
		force += m_linearDamping * (inputLinearVelocity - attachmentPointVelocity);

		Vector3d rotationVector;
		SurgSim::Math::computeRotationVector(inputPose, objectPose, &rotationVector);
		Vector3d torque = m_angularStiffness * rotationVector;
		torque += m_angularDamping * (inputAngularVelocity - objectState.getAngularVelocity());

		Vector6d generalizedForce;
		generalizedForce << force, torque;

		const Matrix33d identity3x3 = Matrix33d::Identity();
		const Matrix33d zero3x3 = Matrix33d::Zero();
		Matrix66d generalizedStiffness;
		generalizedStiffness << m_linearStiffness* identity3x3, zero3x3,
							 zero3x3, m_angularStiffness* identity3x3;
		Matrix66d generalizedDamping;
		generalizedDamping << m_linearDamping* identity3x3, zero3x3,
						   zero3x3, m_angularDamping* identity3x3;

		if (m_calculateInertialTorques)
		{
			SurgSim::DataStructures::Location location;
			location.rigidLocalPosition.setValue(m_localAttachmentPoint);
			m_rigid->addExternalGeneralizedForce(location, generalizedForce, generalizedStiffness, generalizedDamping);
		}
		else
		{
			m_rigid->addExternalGeneralizedForce(generalizedForce, generalizedStiffness, generalizedDamping);
		}

		if (m_output != nullptr)
		{
			RigidTransform3d outputAlignment = m_output->getLocalPose().inverse();
			Matrix33d outputAlignmentUnScaled = outputAlignment.rotation();

			bool output = true;
			if (m_hapticOutputOnlyWhenColliding)
			{
				auto collision = m_rigid->getCollisionRepresentation();
				output = (collision == nullptr) || (collision->getCollisions().unsafeGet().size() > 0);
			}

			if (output)
			{
				m_outputData.vectors().set(m_forceIndex, outputAlignmentUnScaled * (-force));
				m_outputData.vectors().set(m_torqueIndex, outputAlignmentUnScaled * (-torque));
				if (gotInputLinearVelocity && gotInputAngularVelocity)
				{
					m_outputData.matrices().set(m_springJacobianIndex, -generalizedStiffness);
					m_outputData.matrices().set(m_damperJacobianIndex, -generalizedDamping);
				}
				else
				{
					m_outputData.matrices().reset(m_springJacobianIndex);
					m_outputData.matrices().reset(m_damperJacobianIndex);
				}
			}
			else
			{
				m_outputData.vectors().set(m_forceIndex, Vector3d::Zero());
				m_outputData.vectors().set(m_torqueIndex, Vector3d::Zero());
				m_outputData.matrices().reset(m_springJacobianIndex);
				m_outputData.matrices().reset(m_damperJacobianIndex);
			}

			if (gotInputLinearVelocity)
			{
				m_outputData.vectors().set(m_inputLinearVelocityIndex, outputAlignment.linear() * inputLinearVelocity);
			}
			else
			{
				m_outputData.vectors().reset(m_inputLinearVelocityIndex);
			}

			if (gotInputAngularVelocity)
			{
				m_outputData.vectors().set(m_inputAngularVelocityIndex, outputAlignmentUnScaled * inputAngularVelocity);
			}
			else
			{
				m_outputData.vectors().reset(m_inputAngularVelocityIndex);
			}
			m_outputData.poses().set(m_inputPoseIndex, outputAlignment * inputPose);
			m_output->setData(m_outputData);
		}
	}
}

bool VirtualToolCoupler::doInitialize()
{
	m_outputData = buildOutputData();

	m_forceIndex = m_outputData.vectors().getIndex(SurgSim::DataStructures::Names::FORCE);
	m_torqueIndex = m_outputData.vectors().getIndex(SurgSim::DataStructures::Names::TORQUE);
	m_inputLinearVelocityIndex = m_outputData.vectors().getIndex(SurgSim::DataStructures::Names::INPUT_LINEAR_VELOCITY);
	m_inputAngularVelocityIndex =
		m_outputData.vectors().getIndex(SurgSim::DataStructures::Names::INPUT_ANGULAR_VELOCITY);
	m_inputPoseIndex = m_outputData.poses().getIndex(SurgSim::DataStructures::Names::INPUT_POSE);
	m_springJacobianIndex = m_outputData.matrices().getIndex(SurgSim::DataStructures::Names::SPRING_JACOBIAN);
	m_damperJacobianIndex = m_outputData.matrices().getIndex(SurgSim::DataStructures::Names::DAMPER_JACOBIAN);

	return true;
}

SurgSim::DataStructures::DataGroup VirtualToolCoupler::buildOutputData()
{
	SurgSim::DataStructures::DataGroupBuilder builder;
	builder.addVector(SurgSim::DataStructures::Names::FORCE);
	builder.addVector(SurgSim::DataStructures::Names::TORQUE);
	builder.addMatrix(SurgSim::DataStructures::Names::SPRING_JACOBIAN);
	builder.addPose(SurgSim::DataStructures::Names::INPUT_POSE);
	builder.addMatrix(SurgSim::DataStructures::Names::DAMPER_JACOBIAN);
	builder.addVector(SurgSim::DataStructures::Names::INPUT_LINEAR_VELOCITY);
	builder.addVector(SurgSim::DataStructures::Names::INPUT_ANGULAR_VELOCITY);
	return builder.createData();
}

bool VirtualToolCoupler::doWakeUp()
{
	if (m_input == nullptr)
	{
		SURGSIM_LOG_SEVERE(m_logger) <<
									 "VirtualToolCoupler named " << getName() << " does not have an Input Component.";
		return false;
	}
	if (m_rigid == nullptr)
	{
		SURGSIM_LOG_SEVERE(m_logger) << "VirtualToolCoupler named " << getName() << " does not have a Representation.";
		return false;
	}

	if (m_optionalAttachmentPoint.hasValue())
	{
		m_localAttachmentPoint = m_optionalAttachmentPoint.getValue();
	}
	else
	{
		m_localAttachmentPoint = m_rigid->getMassCenter();
	}

	// Provide sensible defaults based on the rigid representation.
	// If one or both of the stiffness and damping are not provided, they are
	// calculated to provide a critically damped system (dampingRatio-1.0).
	// For a mass-spring system, the damping ratio is defined as:
	//
	//     dampingRatio = (damping) / (2 * sqrt(mass * stiffness))
	//
	double dampingRatio = 1.0;
	double mass = m_rigid->getMass();
	if (!m_optionalLinearDamping.hasValue())
	{
		if (m_optionalLinearStiffness.hasValue())
		{
			m_linearStiffness = m_optionalLinearStiffness.getValue();
		}
		else
		{
			m_linearStiffness = mass * 100.0;
		}
		m_linearDamping = 2.0 * dampingRatio * sqrt(mass * m_linearStiffness);
	}
	else
	{
		m_linearDamping = m_optionalLinearDamping.getValue();
		if (m_optionalLinearStiffness.hasValue())
		{
			m_linearStiffness = m_optionalLinearStiffness.getValue();
		}
		else
		{
			m_linearStiffness = pow(m_linearDamping / dampingRatio, 2) / (4.0 * mass);
		}
	}

	Matrix33d leverArmMatrix = makeSkewSymmetricMatrix((m_localAttachmentPoint - m_rigid->getMassCenter()).eval());
	const Matrix33d& inertia = m_rigid->getLocalInertia() + mass * leverArmMatrix * leverArmMatrix;
	double maxInertia = inertia.eigenvalues().real().maxCoeff();
	if (!m_optionalAngularDamping.hasValue())
	{
		if (m_optionalAngularStiffness.hasValue())
		{
			m_angularStiffness = m_optionalAngularStiffness.getValue();
		}
		else
		{
			m_angularStiffness = maxInertia * 1000.0;
		}
		m_angularDamping = 2.0 * dampingRatio * sqrt(maxInertia * m_angularStiffness);
	}
	else
	{
		m_angularDamping = m_optionalAngularDamping.getValue();
		if (m_optionalAngularStiffness.hasValue())
		{
			m_angularStiffness = m_optionalAngularStiffness.getValue();
		}
		else
		{
			m_angularStiffness = pow(m_angularDamping / dampingRatio, 2) / (4.0 * maxInertia);
		}
	}

	SURGSIM_LOG_INFO(m_logger) << "VirtualToolCoupler named '" << getName() <<
		"' has linear stiffness " << m_linearStiffness << ", linear damping " << m_linearDamping
		<< ", angular stiffness " << m_angularStiffness << ", and angular damping " << m_angularDamping
		<< ". Its Physics Representation has mass " << m_rigid->getMass();
	return true;
}

int VirtualToolCoupler::getTargetManagerType() const
{
	return SurgSim::Framework::MANAGER_TYPE_PHYSICS;
}

void VirtualToolCoupler::setInitialInputPose(const SurgSim::Math::RigidTransform3d& pose)
{
	RigidState state = m_rigid->getCurrentState();
	state.setPose(pose);
	m_rigid->setInitialState(state);
}

void VirtualToolCoupler::overrideLinearStiffness(double linearStiffness)
{
	SURGSIM_ASSERT(!isInitialized()) << "Cannot override vtc parameter after it has initialized";

	m_optionalLinearStiffness.setValue(linearStiffness);
	m_linearStiffness = linearStiffness;
}

double VirtualToolCoupler::getLinearStiffness()
{
	SURGSIM_ASSERT(isAwake() || m_optionalLinearStiffness.hasValue())
			<< "Vtc parameter has not been initialized";

	return m_linearStiffness;
}

void VirtualToolCoupler::overrideLinearDamping(double linearDamping)
{
	SURGSIM_ASSERT(!isInitialized()) << "Cannot override vtc parameter after it has initialized";

	m_optionalLinearDamping.setValue(linearDamping);
	m_linearDamping = linearDamping;
}

double VirtualToolCoupler::getLinearDamping()
{
	SURGSIM_ASSERT(isAwake() || m_optionalLinearDamping.hasValue())
			<< "Vtc parameter has not been initialized";

	return m_linearDamping;
}

void VirtualToolCoupler::overrideAngularStiffness(double angularStiffness)
{
	SURGSIM_ASSERT(!isInitialized()) << "Cannot override vtc parameter after it has initialized";

	m_optionalAngularStiffness.setValue(angularStiffness);
	m_angularStiffness = angularStiffness;
}

double VirtualToolCoupler::getAngularStiffness()
{
	SURGSIM_ASSERT(isAwake() || m_optionalAngularStiffness.hasValue())
			<< "Vtc parameter has not been initialized";

	return m_angularStiffness;
}

void VirtualToolCoupler::overrideAngularDamping(double angularDamping)
{
	SURGSIM_ASSERT(!isInitialized()) << "Cannot override vtc parameter after it has initialized";

	m_optionalAngularDamping.setValue(angularDamping);
	m_angularDamping = angularDamping;
}

double VirtualToolCoupler::getAngularDamping()
{
	SURGSIM_ASSERT(isAwake() || m_optionalAngularDamping.hasValue())
			<< "Vtc parameter has not been initialized";

	return m_angularDamping;
}

void VirtualToolCoupler::overrideAttachmentPoint(const SurgSim::Math::Vector3d& attachment)
{
	SURGSIM_ASSERT(!isInitialized()) << "Cannot override vtc parameter after it has initialized";

	m_optionalAttachmentPoint.setValue(attachment);
	m_localAttachmentPoint = attachment;
}

const SurgSim::Math::Vector3d& VirtualToolCoupler::getAttachmentPoint()
{
	SURGSIM_ASSERT(isAwake() || m_optionalAttachmentPoint.hasValue())
			<< "Vtc parameter has not been initialized";
	return m_localAttachmentPoint;
}

void VirtualToolCoupler::setOptionalLinearStiffness(
	const SurgSim::DataStructures::OptionalValue<double>& linearStiffness)
{
	m_optionalLinearStiffness = linearStiffness;
}

const SurgSim::DataStructures::OptionalValue<double>& VirtualToolCoupler::getOptionalLinearStiffness() const
{
	return m_optionalLinearStiffness;
}

void VirtualToolCoupler::setOptionalLinearDamping(const SurgSim::DataStructures::OptionalValue<double>& linearDamping)
{
	m_optionalLinearDamping = linearDamping;
}

const SurgSim::DataStructures::OptionalValue<double>& VirtualToolCoupler::getOptionalLinearDamping() const
{
	return m_optionalLinearDamping;
}

void VirtualToolCoupler::setOptionalAngularStiffness(
	const SurgSim::DataStructures::OptionalValue<double>& angularStiffness)
{
	m_optionalAngularStiffness = angularStiffness;
}

const SurgSim::DataStructures::OptionalValue<double>& VirtualToolCoupler::getOptionalAngularStiffness() const
{
	return m_optionalAngularStiffness;
}

void VirtualToolCoupler::setOptionalAngularDamping(
	const SurgSim::DataStructures::OptionalValue<double>& angularDamping)
{
	m_optionalAngularDamping = angularDamping;
}

const SurgSim::DataStructures::OptionalValue<double>& VirtualToolCoupler::getOptionalAngularDamping() const
{
	return m_optionalAngularDamping;
}

void VirtualToolCoupler::setOptionalAttachmentPoint(
	const SurgSim::DataStructures::OptionalValue<SurgSim::Math::Vector3d>& attachmentPoint)
{
	m_optionalAttachmentPoint = attachmentPoint;
}

const SurgSim::DataStructures::OptionalValue<SurgSim::Math::Vector3d>&
VirtualToolCoupler::getOptionalAttachmentPoint() const
{
	return m_optionalAttachmentPoint;
}

void VirtualToolCoupler::setCalculateInertialTorques(bool calculateInertialTorques)
{
	m_calculateInertialTorques = calculateInertialTorques;
}

bool VirtualToolCoupler::getCalculateInertialTorques() const
{
	return m_calculateInertialTorques;
}

void VirtualToolCoupler::setInitializeRigidWithInputPose(bool val)
{
	m_initializeRigidWithInputPose = val;
}

void VirtualToolCoupler::doRetire()
{
	m_outputData.resetAll();
	Behavior::doRetire();
}

void VirtualToolCoupler::setLocalActive(bool val)
{
	m_outputData.resetAll();
	Behavior::setLocalActive(val);
}

bool VirtualToolCoupler::isHapticOutputOnlyWhenColliding() const
{
	return m_hapticOutputOnlyWhenColliding;
}

void VirtualToolCoupler::setHapticOutputOnlyWhenColliding(bool hapticOutputOnlyWhenColliding)
{
	m_hapticOutputOnlyWhenColliding = hapticOutputOnlyWhenColliding;
}

bool VirtualToolCoupler::isInitializingRigidWithInputPose() const
{
	return m_initializeRigidWithInputPose;
}

}; /// Physics
}; /// SurgSim

max_stars_repo_name: dbungert/opensurgsim

max_issues_repo_name: dbungert/opensurgsim

max_forks_repo_name: dbungert/opensurgsim


text:
/*
	Copyright 2005-2007 Adobe Systems Incorporated
	Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
	or a copy at http://stlab.adobe.com/licenses.html)
*/

/*************************************************************************************************/

#include <adobe/config.hpp>

#include <adobe/check_container.hpp>

#include <boost/concept_check.hpp>

#include <adobe/test/check_regular.hpp>
#include <adobe/implementation/swap.hpp>
#include <iostream>

namespace adobe {
/*!
\defgroup testing Misc utilities (Testing, Timer, ignore_unused,...)
\ingroup utility
@{
*/

template <typename T>
void check_container(const T& c)
{
	adobe::check_traversable(c);

// Containers add the requirement that each element visited once to traversable
	BOOST_CHECK_MESSAGE(c.size() == std::distance(c.begin(), c.end()), "container size");
    BOOST_CHECK_MESSAGE(d.size() == std::distance(d.begin(), d.end()), "container size");
}

#if 0
//gcc always instantiates this
BOOST_TEST_CASE_TEMPLATE_FUNCTION(check_containers, T)
{
    check_container(arbitrary_container_value<T>());
}
#endif

//!@}
}

max_stars_repo_name: andyprowl/virtual-concepts

max_issues_repo_name: brycelelbach/asl

max_forks_repo_name: brycelelbach/asl


text:
#include "selectobjectdialog.h"
#include "ui_selectobjectdialog.h"
#include "newobjectdialog.h"

#include <iostream>
#include "QDir"
#include "QTextStream"

#include <sstream>
#include <boost/property_tree/xml_parser.hpp>

using namespace boost::property_tree;

selectObject::selectObject(QWidget *parent, int type) :
    QDialog(parent),
    ui(new Ui::selectObject)
{
    ui->setupUi(this);
    readData(type);
}

selectObject::~selectObject()
{
    delete ui;
}

void selectObject::setObjectList(QStringList listObjects){
    _listOfObjects.clear();
    _listOfObjects = listObjects;
    ui->comboBox->clear();
    ui->comboBox->addItems(_listOfObjects);
}

void selectObject::readData(int type){
    if(type == 2){
        setWindowTitle("Select object to remove");
        ui->objectSelected->setText(QString("Remove"));
    }
    else{
        // read data
        _list_doc = qApp->applicationDirPath();
        _list_doc.remove("bin");
        _list_doc.append("/list_objects.xml");;

        ptree root;
        read_xml(_list_doc.toStdString(), root);

        _listOfObjects.clear();

        ptree& allObjects = root.get_child("List_of_objects");
        for(ptree::iterator it = allObjects.begin(); it != allObjects.end(); it++){
            _listOfObjects += QString::fromStdString(allObjects.get<std::string>("Object"));
            allObjects.pop_front();
        }

        ui->comboBox->clear();
        ui->comboBox->addItems(_listOfObjects);

        if(!type){
            setWindowTitle("Select the object");
            ui->comboBox->insertSeparator(ui->comboBox->count());
            ui->comboBox->addItem(QString("Insert new ..."));
            ui->comboBox->addItem(QString("Remove from the list"));
        }
        else{
            setWindowTitle("Select object to remove");
            ui->objectSelected->setText(QString("Remove"));
        }
    }
}

void selectObject::on_objectSelected_clicked(){
    _objectName = ui->comboBox->currentText();
    hide();
}

QString selectObject::getObjectName(){
    return _objectName;
}

void selectObject::on_comboBox_currentIndexChanged(const QString &arg1){
    if(!arg1.compare(QString("Insert new ..."))){
        chooseObjectDialog choose;
        choose.exec();
        _objectName = choose.getObjectName();

        _listOfObjects += _objectName;

        readWriteXml();

        hide();
    }
    if(!arg1.compare(QString("Remove from the list"))){
        selectObject removeObject(0, 1);
        removeObject.exec();
        QString objectToRemove = removeObject.getObjectName();
        _listOfObjects.removeOne(objectToRemove);

        readWriteXml();
    }
}

void selectObject::readWriteXml(){
    ptree root;
    ptree* node = &root.add("List_of_objects", "");

    // Read
    for(int i = 0; i < _listOfObjects.size(); i++){
        std::string object;
        std::stringstream str;
        str << _listOfObjects.at(i).toStdString() << std::endl;
        str >> object;
        node->add("Object", object);
    }

    xml_writer_settings<char> settings(' ', 3);
    write_xml(_list_doc.toStdString(), root, std::locale(), settings);

    readData(0);
}


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

#include "bc/transaction.hpp"

BOOST_AUTO_TEST_CASE(transaction_constructor1)
{
    bc::Address from = bc::Address(base::generateKeys().first);
    bc::Address to = bc::Address(base::generateKeys().first);
    bc::Balance amount = 1239823409;
    auto time = base::Time::now();
    bc::Balance fee = 42;
    bc::Transaction tx(from, to, amount, fee, time, bc::Transaction::Type::MESSAGE_CALL, base::Bytes{});

    BOOST_CHECK(tx.getFrom().toString() == from.toString());
    BOOST_CHECK(tx.getTo().toString() == to.toString());
    BOOST_CHECK(tx.getTimestamp() == time);
    BOOST_CHECK(tx.getAmount() == amount);
    BOOST_CHECK(tx.getFee() == fee);
}

BOOST_AUTO_TEST_CASE(transaction_constructor_copy)
{
    bc::Address from = bc::Address(base::generateKeys().first);
    bc::Address to = bc::Address(base::generateKeys().first);
    bc::Balance amount = 1239823409;
    auto time = base::Time::now();
    bc::Balance fee = 123;
    bc::Transaction tx1(from, to, amount, fee, time, bc::Transaction::Type::MESSAGE_CALL, base::Bytes{});
    bc::Transaction tx2(tx1);

    BOOST_CHECK(tx2.getFrom().toString() == from.toString());
    BOOST_CHECK(tx2.getTo().toString() == to.toString());
    BOOST_CHECK(tx2.getTimestamp() == time);
    BOOST_CHECK(tx2.getAmount() == amount);
    BOOST_CHECK(tx2.getFee() == fee);
}

BOOST_AUTO_TEST_CASE(transaction_constructor_move)
{
    bc::Address from = bc::Address(base::generateKeys().first);
    bc::Address to = bc::Address(base::generateKeys().first);
    bc::Balance amount = 1239823409;
    auto time = base::Time::now();
    bc::Balance fee = 123;
    bc::Transaction tx1(from, to, amount, fee, time, bc::Transaction::Type::MESSAGE_CALL, base::Bytes{});
    bc::Transaction tx2(std::move(tx1));

    BOOST_CHECK(tx2.getFrom().toString() == from.toString());
    BOOST_CHECK(tx2.getTo().toString() == to.toString());
    BOOST_CHECK(tx2.getTimestamp() == time);
    BOOST_CHECK(tx2.getAmount() == amount);
    BOOST_CHECK(tx2.getFee() == fee);
}

BOOST_AUTO_TEST_CASE(transaction_operator_equal_copy)
{
    bc::Address from = bc::Address(base::generateKeys().first);
    bc::Address to = bc::Address(base::generateKeys().first);
    bc::Balance amount = 1239823409;
    auto time = base::Time::now();
    bc::Balance fee{ 23213213 };
    bc::Transaction tx1(from, to, amount, fee, time, bc::Transaction::Type::MESSAGE_CALL, base::Bytes{});
    bc::Transaction tx2(from, to, 821481368, fee, time, bc::Transaction::Type::MESSAGE_CALL, base::Bytes{});

    BOOST_CHECK(tx1 != tx2);
    tx2 = tx1;
    BOOST_CHECK(tx2.getFrom().toString() == from.toString());
    BOOST_CHECK(tx2.getTo().toString() == to.toString());
    BOOST_CHECK(tx2.getTimestamp() == time);
    BOOST_CHECK(tx2.getAmount() == amount);
    BOOST_CHECK(tx2.getFee() == fee);
}

BOOST_AUTO_TEST_CASE(transaction_operator_equal_move)
{
    bc::Address from = bc::Address(base::generateKeys().first);
    bc::Address to = bc::Address(base::generateKeys().first);
    bc::Balance amount = 1239823409;
    auto time = base::Time::now();
    bc::Balance fee{ 213213 };
    bc::Transaction tx1(from, to, amount, fee, time, bc::Transaction::Type::MESSAGE_CALL, base::Bytes{});
    bc::Transaction tx2(from, to, 821481368, fee, time, bc::Transaction::Type::MESSAGE_CALL, base::Bytes{});

    BOOST_CHECK(tx1 != tx2);
    tx2 = std::move(tx1);
    BOOST_CHECK(tx2.getFrom().toString() == from.toString());
    BOOST_CHECK(tx2.getTo().toString() == to.toString());
    BOOST_CHECK(tx2.getTimestamp() == time);
    BOOST_CHECK(tx2.getAmount() == amount);
    BOOST_CHECK(tx2.getFee() == fee);
}

BOOST_AUTO_TEST_CASE(transaction_sign)
{
    auto [pub_key, priv_key] = base::generateKeys();
    bc::Address from = bc::Address(pub_key);
    bc::Address to = bc::Address(base::generateKeys().first);
    bc::Balance amount = 1239823409;
    auto time = base::Time::now();
    bc::Balance fee = 42;
    bc::Transaction tx(from, to, amount, fee, time, bc::Transaction::Type::MESSAGE_CALL, base::Bytes{});
    tx.sign(pub_key, priv_key);

    BOOST_CHECK(tx.checkSign());
}

BOOST_AUTO_TEST_CASE(transaction_serialization1)
{
    bc::Address from = bc::Address(base::generateKeys().first);
    bc::Address to = bc::Address(base::generateKeys().first);
    bc::Balance amount = 1239823409;
    auto time = base::Time::now();
    bc::Balance fee = 123;
    bc::Transaction tx1(from, to, amount, fee, time, bc::Transaction::Type::MESSAGE_CALL, base::Bytes{});

    base::SerializationOArchive oa;
    oa.serialize(tx1);

    base::SerializationIArchive ia(oa.getBytes());
    auto tx2 = ia.deserialize<bc::Transaction>();
    BOOST_CHECK(tx1 == tx2);
}

BOOST_AUTO_TEST_CASE(transaction_serialization2)
{
    bc::Address from = bc::Address(base::generateKeys().first);
    bc::Address to = bc::Address(base::generateKeys().first);
    bc::Balance amount = 1239823409;
    auto time = base::Time::now();
    bc::Balance fee{ 506 };
    bc::Transaction tx1(from, to, amount, fee, time, bc::Transaction::Type::MESSAGE_CALL, base::Bytes{});

    base::SerializationOArchive oa;
    oa.serialize(tx1);

    base::SerializationIArchive ia(oa.getBytes());
    auto tx2 = ia.deserialize<bc::Transaction>();
    BOOST_CHECK(tx1 == tx2);
}

BOOST_AUTO_TEST_CASE(transaction_builder_set_all1)
{
    bc::Address from = bc::Address(base::generateKeys().first);
    bc::Address to = bc::Address(base::generateKeys().first);
    bc::Balance amount = 1239823409;
    auto time = base::Time::now();
    bc::Balance fee = 150;
    bc::TransactionBuilder txb;

    txb.setFrom(from);
    txb.setTo(to);
    txb.setTimestamp(time);
    txb.setAmount(amount);
    txb.setFee(fee);

    auto tx = std::move(txb).build();

    BOOST_CHECK(tx.getFrom().toString() == from.toString());
    BOOST_CHECK(tx.getTo().toString() == to.toString());
    BOOST_CHECK(tx.getTimestamp() == time);
    BOOST_CHECK(tx.getAmount() == amount);
    BOOST_CHECK(tx.getFee() == fee);
}

BOOST_AUTO_TEST_CASE(transaction_builder_set_all2)
{
    bc::Address from = bc::Address(base::generateKeys().first);
    bc::Address to = bc::Address(base::generateKeys().first);
    bc::Balance amount = 1239823409;
    auto time = base::Time::now();
    bc::Balance fee{ 229 };

    bc::TransactionBuilder txb;
    txb.setFrom(from);
    txb.setTo(to);
    txb.setTimestamp(time);
    txb.setAmount(amount);
    txb.setFee(fee);

    auto tx1 = txb.build();

    BOOST_CHECK(tx1.getFrom().toString() == from.toString());
    BOOST_CHECK(tx1.getTo().toString() == to.toString());
    BOOST_CHECK(tx1.getTimestamp() == time);
    BOOST_CHECK(tx1.getAmount() == amount);
    BOOST_CHECK(tx1.getFee() == fee);
}

max_stars_repo_name: heshu-by/likelib

max_issues_repo_name: heshu-by/likelib

max_forks_repo_name: heshu-by/likelib


text:
#include <iostream>
#include <vector>
#include <string>
#include <utility>
#include <numeric>

#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/scope_exit.hpp>

#include <amgcl/backend/builtin.hpp>
#include <amgcl/solver/runtime.hpp>
#include <amgcl/preconditioner/runtime.hpp>
#include <amgcl/adapter/crs_tuple.hpp>
#include <amgcl/mpi/make_solver.hpp>
#include <amgcl/mpi/block_preconditioner.hpp>
#include <amgcl/profiler.hpp>

#include "domain_partition.hpp"

namespace amgcl { profiler<> prof; }
using amgcl::prof;
using amgcl::precondition;

//---------------------------------------------------------------------------
struct renumbering {
    const domain_partition<2> ∂
    const std::vector<ptrdiff_t> &dom;

    renumbering(
            const domain_partition<2> &p,
            const std::vector<ptrdiff_t> &d
            ) : part(p), dom(d)
    {}

    ptrdiff_t operator()(ptrdiff_t i, ptrdiff_t j) const {
        boost::array<ptrdiff_t, 2> p = {{i, j}};
        std::pair<int,ptrdiff_t> v = part.index(p);
        return dom[v.first] + v.second;
    }
};

//---------------------------------------------------------------------------
template <template <class> class Precond, class Matrix>
std::tuple<size_t, double> solve(
        const amgcl::mpi::communicator &comm,
        const boost::property_tree::ptree &prm,
        const Matrix &A
        )
{
    typedef amgcl::backend::builtin<double> Backend;

    typedef amgcl::mpi::make_solver<
        amgcl::mpi::block_preconditioner< Precond<Backend> >,
        amgcl::runtime::solver::wrapper
        > Solver;

    const size_t n = amgcl::backend::rows(A);

    std::vector<double> rhs(n, 1), x(n, 0);

    prof.tic("setup");
    Solver solve(comm, A, prm);
    prof.toc("setup");

    {
        auto t2 = prof.scoped_tic("solve");
        return solve(rhs, x);
    }
}

//---------------------------------------------------------------------------
int main(int argc, char *argv[]) {
    namespace po = boost::program_options;

    using amgcl::prof;
    using std::vector;
    using std::string;

    po::options_description desc("Options");

    desc.add_options()
        ("help,h", "Show this help.")
        ("prm-file,P",
         po::value<string>(),
         "Parameter file in json format. "
        )
        (
         "prm,p",
         po::value< vector<string> >()->multitoken(),
         "Parameters specified as name=value pairs. "
         "May be provided multiple times. Examples:\n"
         "  -p solver.tol=1e-3\n"
         "  -p precond.coarse_enough=300"
        )
        (
         "size,n",
         po::value<int>()->default_value(1024),
         "The size of the Poisson problem to solve. "
         "Specified as number of grid nodes along each dimension of a unit square. "
         "The resulting system will have n*n unknowns. "
        )
        (
         "single-level,1",
         po::bool_switch()->default_value(false),
         "When specified, the AMG hierarchy is not constructed. "
         "Instead, the problem is solved using a single-level smoother as preconditioner. "
        )
        (
         "initial,x",
         po::value<double>()->default_value(0),
         "Value to use as initial approximation. "
        )
        ;

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

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        return 0;
    }

    boost::property_tree::ptree prm;
    if (vm.count("prm-file")) {
        read_json(vm["prm-file"].as<string>(), prm);
    }

    if (vm.count("prm")) {
        for(const string &v : vm["prm"].as<vector<string> >()) {
            amgcl::put(prm, v);
        }
    }

    MPI_Init(&argc, &argv);
    BOOST_SCOPE_EXIT(void) {
        MPI_Finalize();
    } BOOST_SCOPE_EXIT_END

    amgcl::mpi::communicator world(MPI_COMM_WORLD);

    if (world.rank == 0)
        std::cout << "World size: " << world.size << std::endl;

    const ptrdiff_t n   = vm["size"].as<int>();
    const double    h2i = (n - 1) * (n - 1);

    boost::array<ptrdiff_t, 2> lo = { {0, 0} };
    boost::array<ptrdiff_t, 2> hi = { {n - 1, n - 1} };

    prof.tic("partition");
    domain_partition<2> part(lo, hi, world.size);
    ptrdiff_t chunk = part.size( world.rank );

    std::vector<ptrdiff_t> domain(world.size + 1);
    MPI_Allgather(
            &chunk, 1, amgcl::mpi::datatype<ptrdiff_t>(),
            &domain[1], 1, amgcl::mpi::datatype<ptrdiff_t>(), world);
    std::partial_sum(domain.begin(), domain.end(), domain.begin());

    lo = part.domain(world.rank).min_corner();
    hi = part.domain(world.rank).max_corner();
    prof.toc("partition");

    renumbering renum(part, domain);

    prof.tic("assemble");
    std::vector<ptrdiff_t> ptr;
    std::vector<ptrdiff_t> col;
    std::vector<double>    val;
    std::vector<double>    rhs;

    ptr.reserve(chunk + 1);
    col.reserve(chunk * 5);
    val.reserve(chunk * 5);

    ptr.push_back(0);

    for(ptrdiff_t j = lo[1]; j <= hi[1]; ++j) {
        for(ptrdiff_t i = lo[0]; i <= hi[0]; ++i) {
            if (j > 0)  {
                col.push_back(renum(i,j-1));
                val.push_back(-h2i);
            }

            if (i > 0) {
                col.push_back(renum(i-1,j));
                val.push_back(-h2i);
            }

            col.push_back(renum(i,j));
            val.push_back(4 * h2i);

            if (i + 1 < n) {
                col.push_back(renum(i+1,j));
                val.push_back(-h2i);
            }

            if (j + 1 < n) {
                col.push_back(renum(i,j+1));
                val.push_back(-h2i);
            }

            ptr.push_back( col.size() );
        }
    }
    prof.toc("assemble");

    size_t iters;
    double error;

    bool single_level = vm["single-level"].as<bool>();

    if (single_level)
        prm.put("precond.class", "relaxation");

    std::tie(iters, error) = solve<amgcl::runtime::preconditioner>(
            world, prm, std::tie(chunk, ptr, col, val));

    if (world.rank == 0) {
        std::cout
            << "Iterations: " << iters << std::endl
            << "Error:      " << error << std::endl
            << std::endl
            << prof << std::endl;
    }
}

max_stars_repo_name: moyner/amgcl

max_issues_repo_name: moyner/amgcl

max_forks_repo_name: moyner/amgcl


text:
#include "cplex.h"
#include <cassert>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <numeric>

using namespace std;

int ReadSolution(string solfile,
        vector<double> &solution,
        vector<string> &names,
        double &objval);

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

    CPXENVptr env = CPXopenCPLEX(&status);
    assert(!status);

    cout << "CPLEX version: " <<  CPXversion(env) << endl;

    status = CPXsetintparam(env, CPXPARAM_ScreenOutput, CPX_ON);
    assert(!status);

    CPXLPptr problem = CPXcreateprob(env, &status, "Test problem");
    assert(!status);

    status = CPXreadcopyprob(env,
        problem,
        argv[1],
        NULL);
    assert(!status);

    vector<double> solution;
    vector<string> names;
    double objectivevalue;

    status = ReadSolution(argv[2],
            solution,
            names,
            objectivevalue);
    assert(!status);

    // We sort the solution, according to index in problem
    vector<double> sortedsolution(CPXgetnumcols(env, problem));

    for(int i = 0; i < solution.size(); ++i)
    {
        int idx;
        status = CPXgetcolindex(env,
                problem,
                names[i].c_str(),
                &idx);
        if(&idx != NULL)
        {
            sortedsolution[idx] =solution[i];
            if(idx >= sortedsolution.size())
            {
                cout << "Variable index out of bounds!!" <<  endl;
                exit(1);
            }
        }
        else
        {
            cerr << "Error. Name not found" << endl;
            exit(1);
        }
    }

    vector<int> indices;
    int beg = 0;
    int effortlevel = CPX_MIPSTART_CHECKFEAS;
    for(int i = 0; i < CPXgetnumcols(env, problem); ++i)
        indices.push_back(i);

    status = CPXaddmipstarts(env,
            problem,
            1,
            CPXgetnumcols(env, problem),
            &beg,
            &(indices[0]),
            &(sortedsolution[0]),
            &(effortlevel),
            NULL);
    assert(!status);

    status = CPXsetdblparam(env, CPXPARAM_TimeLimit, 10.0);
    assert(!status);

    status = CPXmipopt(env, problem);

    status = CPXfreeprob(env, &problem);
    assert(!status);

    status = CPXcloseCPLEX(&env);
    assert(!status);

}

int ReadSolution(string solfile,
        vector<double> &solution,
        vector<string> &names,
        double &objval)
{
    int status;

    ifstream infile(solfile.c_str());

    string line;
    vector<string> tokens;

    while(getline(infile, line))
    {
        if(line == "")
            continue;
        boost::algorithm::split(tokens,
                line,
                boost::algorithm::is_space(),
                boost::token_compress_on);
        if(tokens[0] == "=obj=")
        {
            objval = atof(tokens[1].c_str());
        }
        else if(tokens[0] != "#")
        {
            solution.push_back(atof(tokens[1].c_str()));
            names.push_back(tokens[0].c_str());
            //cout << "Variable " << tokens[0] << "= " << atof(tokens[1].c_str()) << endl;
        }
    }

    infile.close();

    return 0;
}

max_stars_repo_name: rocarvaj/mipstart-example

max_issues_repo_name: rocarvaj/mipstart-example

max_forks_repo_name: rocarvaj/mipstart-example


text: #include <boost/config/stdlib/sgi.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#ifndef YANNQ_SUPERVISED_OVERLAPOPTIMZER_HPP
#define YANNQ_SUPERVISED_OVERLAPOPTIMZER_HPP
#include <Eigen/Dense>

#include <tbb/tbb.h>

#include "Machines/RBM.hpp"

namespace yannq
{
template<class Machine, class Target>
class OverlapOptimizer
{
public:
	using Scalar = typename Machine::Scalar;
	using Vector = typename Machine::Vector;
	using Matrix = typename Machine::Matrix;

private:
	int N_;

	const Machine& qs_;
	const Target& target_;

	Matrix dervs_;
	Vector ratios_;
	Scalar ov_;

public:
	explicit OverlapOptimizer(const Machine& qs, const Target& target)
		: N_(qs.getN()), qs_(qs), target_(target)
	{
	}

	template<class SamplingResult>
	void constructFromSampling(SamplingResult&& rs)
	{
		using std::conj;

		dervs_.resize(rs.size(), qs_.getDim());
		ratios_.resize(rs.size());

		dervs_.setZero();
		ratios_.setZero();

		tbb::parallel_for(0u, rs.size(),
			[&](uint32_t idx)
		{
			const auto elt = rs[idx];
			auto smp = construct_state<typename MachineStateTypes<Machine>::StateRef>(qs_, elt);

			dervs_.row(idx) = qs_.logDeriv(elt);
			ratios_(idx) = target_(toValue(smp.getSigma()))/qs_.coeff(elt);
		});
		ov_ = ratios_.mean();
	}

	Vector calcGrad() const
	{
		Vector res = dervs_.colwise().mean();
		res = res.conjugate();
		res -= dervs_.adjoint()*ratios_/ov_/dervs_.rows();
		return res;
	}

	//<\phi|\psi>/Z
	Scalar meanRatio() const
	{
		return ov_;
	}
	Scalar meanRatioSqr() const
	{
		return ratios_.cwiseAbs2().mean();
	}
};
}//namespace yannq
#endif//YANNQ_SUPERVISED_OVERLAPOPTIMZER_HPP

max_stars_repo_name: cecri/yannq

max_issues_repo_name: cecri/yannq

max_forks_repo_name: cecri/yannq


text:
//=======================================================================
// Copyright 2007 Aaron Windsor
//
// 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 <iostream>
#include <vector>

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/properties.hpp>
#include <boost/graph/copy.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/property_map/property_map.hpp>

#include <boost/graph/planar_canonical_ordering.hpp>
#include <boost/graph/is_straight_line_drawing.hpp>
#include <boost/graph/chrobak_payne_drawing.hpp>
#include <boost/graph/boyer_myrvold_planar_test.hpp>
#include <boost/graph/make_connected.hpp>
#include <boost/graph/make_biconnected_planar.hpp>
#include <boost/graph/make_maximal_planar.hpp>

#include "graph.hpp"
#include "range.hpp"

//a class to hold the coordinates of the straight line embedding
struct coord_t {
  std::size_t x;
  std::size_t y;
};

template<class G>
std::vector<coord_t> straight_line_drawing(G const & gIn) {
  using namespace boost;

  typedef adjacency_list<vecS, vecS, undirectedS, property<vertex_index_t, int>,
      property<edge_index_t, int> > Graph;

  Graph g;
  copy_edges(gIn, g);

  //Define the storage type for the planar embedding
  typedef std::vector<std::vector<graph_traits<Graph>::edge_descriptor>> embedding_storage_t;
  typedef iterator_property_map<embedding_storage_t::iterator,
      property_map<Graph, vertex_index_t>::type> embedding_t;

  // Create the planar embedding
  embedding_storage_t embedding_storage(num_vertices(g));
  embedding_t embedding(embedding_storage.begin(), get(vertex_index, g));

  boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,
                               boyer_myrvold_params::embedding = embedding);

  make_connected(g);
  make_biconnected_planar(g, embedding);
  make_maximal_planar(g, embedding);

  // Find a canonical ordering
  std::vector<typename graph_traits<Graph>::vertex_descriptor> ordering;
  planar_canonical_ordering(g, embedding, std::back_inserter(ordering));

  //Set up a property map to hold the mapping from vertices to coord_t's
  typedef std::vector<coord_t> drawing_storage_t;
  typedef boost::iterator_property_map<drawing_storage_t::iterator,
      property_map<Graph, vertex_index_t>::type> drawing_t;

  drawing_storage_t drawing_storage(num_vertices(g));
  drawing_t drawing(drawing_storage.begin(), get(vertex_index, g));

  // Compute the straight line drawing
  chrobak_payne_straight_line_drawing(g, embedding, ordering.begin(),
                                      ordering.end(), drawing);

  return drawing_storage;
}

int main(int argc, char** argv) {
  typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> graph;

  // you can use the functions make_connected, make_biconnected_planar,
  // and make_maximal planar in sequence to add a set of edges
  // to any undirected planar graph to make it maximal planar.

  graph g(7);
  add_edge(0, 1, g);
  add_edge(1, 2, g);
  add_edge(2, 3, g);
  add_edge(3, 0, g);
  //add_edge(3, 4, g);
  add_edge(4, 5, g);
  add_edge(5, 6, g);
  //add_edge(6, 3, g);
  add_edge(0, 4, g);
  add_edge(1, 3, g);
  add_edge(3, 5, g);
  add_edge(2, 6, g);
  add_edge(1, 4, g);
  add_edge(1, 5, g);
  add_edge(1, 6, g);

  auto coords = straight_line_drawing(g);

  std::cout << "The straight line drawing is: " << std::endl;
  for (auto v : ::range(vertices(g))) {
    coord_t coord(coords[v]);
    std::cout << v << " -> (" << coord.x << ", " << coord.y << ")" << std::endl;
  }

  return 0;
}

max_stars_repo_name: arekolek/MaxIST

max_issues_repo_name: arekolek/MaxIST

max_forks_repo_name: arekolek/MaxIST