text:
//  Copyright 2000 John Maddock (john@johnmaddock.co.uk)
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).
//
//  See http://www.boost.org/libs/type_traits for most recent version including documentation.

#ifndef BOOST_TT_FUNCTION_TRAITS_HPP_INCLUDED
#define BOOST_TT_FUNCTION_TRAITS_HPP_INCLUDED

#include <boost/config.hpp>
#include <boost/type_traits/is_function.hpp>
#include <boost/type_traits/add_pointer.hpp>

namespace boost {

#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
namespace detail {

template<typename Function> struct function_traits_helper;

template<typename R>
struct function_traits_helper<R (*)(void)>
{
  BOOST_STATIC_CONSTANT(unsigned, arity = 0);
  typedef R result_type;
};

template<typename R, typename T1>
struct function_traits_helper<R (*)(T1)>
{
  BOOST_STATIC_CONSTANT(unsigned, arity = 1);
  typedef R result_type;
  typedef T1 arg1_type;
  typedef T1 argument_type;
};

template<typename R, typename T1, typename T2>
struct function_traits_helper<R (*)(T1, T2)>
{
  BOOST_STATIC_CONSTANT(unsigned, arity = 2);
  typedef R result_type;
  typedef T1 arg1_type;
  typedef T2 arg2_type;
  typedef T1 first_argument_type;
  typedef T2 second_argument_type;
};

template<typename R, typename T1, typename T2, typename T3>
struct function_traits_helper<R (*)(T1, T2, T3)>
{
  BOOST_STATIC_CONSTANT(unsigned, arity = 3);
  typedef R result_type;
  typedef T1 arg1_type;
  typedef T2 arg2_type;
  typedef T3 arg3_type;
};

template<typename R, typename T1, typename T2, typename T3, typename T4>
struct function_traits_helper<R (*)(T1, T2, T3, T4)>
{
  BOOST_STATIC_CONSTANT(unsigned, arity = 4);
  typedef R result_type;
  typedef T1 arg1_type;
  typedef T2 arg2_type;
  typedef T3 arg3_type;
  typedef T4 arg4_type;
};

template<typename R, typename T1, typename T2, typename T3, typename T4,
         typename T5>
struct function_traits_helper<R (*)(T1, T2, T3, T4, T5)>
{
  BOOST_STATIC_CONSTANT(unsigned, arity = 5);
  typedef R result_type;
  typedef T1 arg1_type;
  typedef T2 arg2_type;
  typedef T3 arg3_type;
  typedef T4 arg4_type;
  typedef T5 arg5_type;
};

template<typename R, typename T1, typename T2, typename T3, typename T4,
         typename T5, typename T6>
struct function_traits_helper<R (*)(T1, T2, T3, T4, T5, T6)>
{
  BOOST_STATIC_CONSTANT(unsigned, arity = 6);
  typedef R result_type;
  typedef T1 arg1_type;
  typedef T2 arg2_type;
  typedef T3 arg3_type;
  typedef T4 arg4_type;
  typedef T5 arg5_type;
  typedef T6 arg6_type;
};

template<typename R, typename T1, typename T2, typename T3, typename T4,
         typename T5, typename T6, typename T7>
struct function_traits_helper<R (*)(T1, T2, T3, T4, T5, T6, T7)>
{
  BOOST_STATIC_CONSTANT(unsigned, arity = 7);
  typedef R result_type;
  typedef T1 arg1_type;
  typedef T2 arg2_type;
  typedef T3 arg3_type;
  typedef T4 arg4_type;
  typedef T5 arg5_type;
  typedef T6 arg6_type;
  typedef T7 arg7_type;
};

template<typename R, typename T1, typename T2, typename T3, typename T4,
         typename T5, typename T6, typename T7, typename T8>
struct function_traits_helper<R (*)(T1, T2, T3, T4, T5, T6, T7, T8)>
{
  BOOST_STATIC_CONSTANT(unsigned, arity = 8);
  typedef R result_type;
  typedef T1 arg1_type;
  typedef T2 arg2_type;
  typedef T3 arg3_type;
  typedef T4 arg4_type;
  typedef T5 arg5_type;
  typedef T6 arg6_type;
  typedef T7 arg7_type;
  typedef T8 arg8_type;
};

template<typename R, typename T1, typename T2, typename T3, typename T4,
         typename T5, typename T6, typename T7, typename T8, typename T9>
struct function_traits_helper<R (*)(T1, T2, T3, T4, T5, T6, T7, T8, T9)>
{
  BOOST_STATIC_CONSTANT(unsigned, arity = 9);
  typedef R result_type;
  typedef T1 arg1_type;
  typedef T2 arg2_type;
  typedef T3 arg3_type;
  typedef T4 arg4_type;
  typedef T5 arg5_type;
  typedef T6 arg6_type;
  typedef T7 arg7_type;
  typedef T8 arg8_type;
  typedef T9 arg9_type;
};

template<typename R, typename T1, typename T2, typename T3, typename T4,
         typename T5, typename T6, typename T7, typename T8, typename T9,
         typename T10>
struct function_traits_helper<R (*)(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)>
{
  BOOST_STATIC_CONSTANT(unsigned, arity = 10);
  typedef R result_type;
  typedef T1 arg1_type;
  typedef T2 arg2_type;
  typedef T3 arg3_type;
  typedef T4 arg4_type;
  typedef T5 arg5_type;
  typedef T6 arg6_type;
  typedef T7 arg7_type;
  typedef T8 arg8_type;
  typedef T9 arg9_type;
  typedef T10 arg10_type;
};

} // end namespace detail

template<typename Function>
struct function_traits :
   public detail::function_traits_helper<typename boost::add_pointer<Function>::type>
{
};

#else

namespace detail {

template<unsigned N>
struct type_of_size
{
  char elements[N];
};

template<typename R>
type_of_size<1> function_arity_helper(R (*f)());

template<typename R, typename T1>
type_of_size<2> function_arity_helper(R (*f)(T1));

template<typename R, typename T1, typename T2>
type_of_size<3> function_arity_helper(R (*f)(T1, T2));

template<typename R, typename T1, typename T2, typename T3>
type_of_size<4> function_arity_helper(R (*f)(T1, T2, T3));

template<typename R, typename T1, typename T2, typename T3, typename T4>
type_of_size<5> function_arity_helper(R (*f)(T1, T2, T3, T4));

template<typename R, typename T1, typename T2, typename T3, typename T4,
         typename T5>
type_of_size<6> function_arity_helper(R (*f)(T1, T2, T3, T4, T5));

template<typename R, typename T1, typename T2, typename T3, typename T4,
         typename T5, typename T6>
type_of_size<7> function_arity_helper(R (*f)(T1, T2, T3, T4, T5, T6));

template<typename R, typename T1, typename T2, typename T3, typename T4,
         typename T5, typename T6, typename T7>
type_of_size<8> function_arity_helper(R (*f)(T1, T2, T3, T4, T5, T6, T7));

template<typename R, typename T1, typename T2, typename T3, typename T4,
         typename T5, typename T6, typename T7, typename T8>
type_of_size<9> function_arity_helper(R (*f)(T1, T2, T3, T4, T5, T6, T7, T8));

template<typename R, typename T1, typename T2, typename T3, typename T4,
         typename T5, typename T6, typename T7, typename T8, typename T9>
type_of_size<10> function_arity_helper(R (*f)(T1, T2, T3, T4, T5, T6, T7, T8,
                                              T9));

template<typename R, typename T1, typename T2, typename T3, typename T4,
         typename T5, typename T6, typename T7, typename T8, typename T9,
         typename T10>
type_of_size<11> function_arity_helper(R (*f)(T1, T2, T3, T4, T5, T6, T7, T8,
                                              T9, T10));
} // end namespace detail

// Won't work with references
template<typename Function>
struct function_traits
{
  BOOST_STATIC_CONSTANT(unsigned, arity = (sizeof(detail::function_arity_helper((Function*)0))-1));
};

#endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
}

#endif // BOOST_TT_FUNCTION_TRAITS_HPP_INCLUDED

ext: hpp

max_issues_repo_name: foxostro/CheeseTesseract

max_forks_repo_name: qwazer/GrammarEngine


text:
/*Copyright (c) 2021 James Gayvert

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/*
 * qchem_interface.cpp
 */

#include "qchem_interface.h"

#include <algorithm>
#include <chrono>
#include <Eigen/Dense>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

#include "gto_ordering.h"
#include "opencap_exception.h"
#include "utils.h"

void qchem_parse_fchk_dms(std::string dmat_filename,std::vector<std::vector<Eigen::MatrixXd>> &alpha_opdms,
		std::vector<std::vector<Eigen::MatrixXd>> &beta_opdms, size_t nstates, size_t ntdm, BasisSet &bs,
		bool symmetric_rdm, bool do_spin)
{
	alpha_opdms = std::vector< std::vector<Eigen::MatrixXd>>(nstates, std::vector<Eigen::MatrixXd> (nstates));
	beta_opdms = std::vector< std::vector<Eigen::MatrixXd>>(nstates, std::vector<Eigen::MatrixXd> (nstates));
	int lt_number = bs.Nbasis*(bs.Nbasis+1)/2;
	int lt_tdm = nstates*(nstates+1)/2 - nstates;
	std::ifstream is(dmat_filename);
	std::vector<Eigen::MatrixXd> alpha_tdms;
	std::vector<Eigen::MatrixXd> beta_tdms;
    if (is.good())
    {
    	std::string line, rest;
    	std::getline(is, line);
    	auto start = std::chrono::high_resolution_clock::now();
    	for (size_t i=0;i<nstates;i++)
    	{
    			//alpha first, then beta
    			for(size_t spin=0;spin<=do_spin;spin++)
    			{
					while(line.find("State Density")== std::string::npos)
					{
						std::getline(is,line);
	    	    		if (is.peek()==EOF)
	    	    			opencap_throw("Error: Reached end of file before densities for "+
	    	    					std::to_string(nstates) + " states were found.");
					}
					//last part of line should be number of elements to read
					int num_elements = stoi(split(line,' ').back());
					if(sqrt(num_elements)!=bs.Nbasis && num_elements!=lt_number)
						opencap_throw("Error: dimensions of TDMs do not match specified basis set.");
					size_t lines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;
					std::vector<double> matrix_elements;
					for (size_t k=1;k<=lines_to_read;k++)
					{
						std::getline(is,line);
						std::vector<std::string> tokens = split(line,' ');
						for (auto token:tokens)
							matrix_elements.push_back(std::stod(token));
					}
					Eigen::MatrixXd st_opdm(bs.Nbasis,bs.Nbasis);
					if(symmetric_rdm)
						fill_LT<double>(matrix_elements,st_opdm);
					else
						fill_mat<double>(matrix_elements,st_opdm);
					to_opencap_ordering(st_opdm,bs,get_qchem_ids(bs));
					if(spin==0)
					{
						alpha_opdms[i][i]=st_opdm;
						if(!do_spin)
							beta_opdms[i][i]=st_opdm;
					}
					else
						beta_opdms[i][i]=st_opdm;
    			}
		}
        is.seekg (0, ios::beg);
    	for(size_t i=0;i<ntdm;i++)
    	{
			//alpha first, then beta
			for (size_t spin=0;spin<=do_spin;spin++)
			{
				while(line.find("Transition DM")== std::string::npos)
				{
					std::getline(is,line);
					if (is.peek()==EOF)
						opencap_throw("Error: Reached end of file before densities for "+
								std::to_string(nstates) + " states were found.");
				}
				//last part of line should be number of elements to read
				size_t num_elements = stoi(split(line,' ').back());
				if(sqrt(num_elements)!=bs.Nbasis && num_elements!=lt_number)
					opencap_throw("Error: dimensions of TDMs do not match specified basis set.");
				size_t lines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;
				std::vector<double> matrix_elements;
				for (size_t k=1;k<=lines_to_read;k++)
				{
					std::getline(is,line);
					std::vector<std::string> tokens = split(line,' ');
					for (auto token:tokens)
						matrix_elements.push_back(std::stod(token));
				}
				Eigen::MatrixXd st_opdm(bs.Nbasis,bs.Nbasis);
				fill_mat<double>(matrix_elements,st_opdm);
				to_opencap_ordering(st_opdm,bs,get_qchem_ids(bs));
				if(spin==0)
				{
					alpha_tdms.push_back(st_opdm);
					if(!do_spin)
						beta_tdms.push_back(st_opdm);
				}
				else
					beta_tdms.push_back(st_opdm);
			}
    	}
    }
    is.close();
    if(ntdm == lt_tdm)
    {
        std::cout << "Warning: TDM M-->N is assumed to be conjugate transpose of "
        << "TDM N-->M where M>N" << std::endl;
    	size_t dm_idx = 0;
    	for(size_t i=0;i<nstates;i++)
    	{
    		for(size_t j=i+1;j<nstates;j++)
    		{
    			alpha_opdms[i][j] = alpha_tdms[dm_idx];
    			alpha_opdms[j][i] = alpha_tdms[dm_idx].adjoint();
    			beta_opdms[i][j] = beta_tdms[dm_idx].adjoint();
    			beta_opdms[j][i] = beta_tdms[dm_idx];
				dm_idx++;
    		}
    	}
    }
    else
    {
    	size_t dm_idx = 0;
    	for(size_t i=0;i<nstates;i++)
    	{
    		for(size_t j=0;j<nstates;j++)
    		{
    			if(i!=j)
    			{
    				alpha_opdms[i][j] = alpha_tdms[dm_idx];
    				beta_opdms[i][j] = beta_tdms[dm_idx];
    				dm_idx++;
    			}
    		}
    	}
    }
}

void qchem_read_dms(std::vector<std::vector<Eigen::MatrixXd>> &alpha_dms,
		std::vector<std::vector<Eigen::MatrixXd>> &beta_dms,
		std::string fchk_filename, BasisSet &bs,size_t num_states)
{
	std::ifstream is(fchk_filename);
	size_t nstates = 0;
	size_t num_tdm = 0;
	bool sep_alpha_beta;
	bool symmetric_rdm = false;
	bool symmetric_tdm = false;
	std::string line, rest;
	if (is.good())
	{
		while(is.peek() != EOF )
		{
			std::getline(is, line);
			if(line.find("State Density")!= std::string::npos)
			{
				if(line.find("Alpha")!=std::string::npos)
				{
					sep_alpha_beta=true;
					int num_elements = stoi(split(line,' ').back());
					if(sqrt(num_elements)!=bs.Nbasis)
					{
						int lt_number = bs.Nbasis*(bs.Nbasis+1)/2;
						if(lt_number == num_elements)
							symmetric_rdm = true;
						else
							opencap_throw("Error: dimensions of DMs do not match specified basis set.");
					}
					break;
				}
				else
				{
					sep_alpha_beta=false;
					int num_elements = stoi(split(line,' ').back());
					if(sqrt(num_elements)!=bs.Nbasis)
					{
						int lt_number = bs.Nbasis*(bs.Nbasis+1)/2;
						if (lt_number == num_elements)
							symmetric_rdm = true;
						else
							opencap_throw("Error: dimensions of DMs do not match specified basis set.");
					}
					break;
				}
			}
		}
		is.seekg (0, ios::beg);
		while(is.peek()!=EOF)
		{
			std::getline(is, line);
			if((line.find("Alpha")!= std::string::npos && line.find("State Density")!= std::string::npos) && sep_alpha_beta)
				nstates++;
			else if(line.find("State Density")!= std::string::npos && !sep_alpha_beta)
				nstates++;
			if((line.find("Alpha")!= std::string::npos && line.find("Transition DM")!= std::string::npos) && sep_alpha_beta)
				num_tdm++;
			else if(line.find("Transition DM")!= std::string::npos && !sep_alpha_beta)
				num_tdm++;
		}
		is.close();
		if(nstates==0)
		{
			opencap_throw("Error: Unable to find any densities in:" +fchk_filename);
		}
		else if(nstates!=num_states)
		{
			opencap_throw("Error: number of states found: " + std::to_string(nstates) + ", does not match "
					"number of states specified in the input: " + std::to_string(num_states)+ ". Exiting...");
		}
		qchem_parse_fchk_dms(fchk_filename,alpha_dms,beta_dms,nstates,num_tdm,bs,symmetric_rdm,sep_alpha_beta);
	}
	else
	    opencap_throw("Error: I couldn't read:" + fchk_filename);
}

Eigen::MatrixXd qchem_read_overlap(std::string dmat_filename, BasisSet bs)
{
	size_t num_bf = bs.Nbasis;
    std::ifstream is(dmat_filename);
	Eigen::MatrixXd smat(num_bf,num_bf);
	smat=Eigen::MatrixXd::Zero(num_bf,num_bf);
    if (is.good())
    {
    	std::string line, rest;
    	while (line.find("Overlap Matrix")== std::string::npos)
    	{
        	std::getline(is, line);
    		if (is.peek()==EOF)
    			opencap_throw("Error: Reached end of file before Overlap Matrix was found.");
    	}
    	size_t num_elements = stoi(split(line,' ').back());
    	int lt_number = bs.Nbasis*(bs.Nbasis+1)/2;
    	if(num_elements!=lt_number)
    		opencap_throw("Error: Dimensions of overlap matrix do not match basis.");
		size_t lines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;
		std::vector<double> matrix_elements;
		for (size_t k=1;k<=lines_to_read;k++)
		{
			std::getline(is,line);
			std::vector<std::string> tokens = split(line,' ');
			for (auto token:tokens)
				matrix_elements.push_back(std::stod(token));
		}
		fill_LT<double>(matrix_elements,smat);
		to_opencap_ordering(smat,bs,get_qchem_ids(bs));
    }
    else
    	opencap_throw("Error: I couldn't read:" + dmat_filename);
    return smat;
}

Eigen::MatrixXd read_qchem_tddft_energies(size_t nstates,std::string output_file)
{
	Eigen::MatrixXd ZERO_ORDER_H(nstates,nstates);
	ZERO_ORDER_H=Eigen::MatrixXd::Zero(nstates,nstates);
	std::ifstream is(output_file);
    if (is.good())
    {
    	std::string line, rest;
    	std::getline(is, line);
    	size_t state_idx = 1;
    	while (state_idx<nstates)
    	{
    		if (is.peek()==EOF)
    			opencap_throw("Error: Reached end of file before "+ std::to_string(nstates) + " energies were found. "
    					"Only " + std::to_string(state_idx) + " states were found. Exiting...");
    		if (line.find("Total energy in the final basis set")!= std::string::npos)
    			ZERO_ORDER_H(0,0) = std::stod(split(line,' ')[8]);
			if (line.find("Total energy for state")!= std::string::npos)
			{
					ZERO_ORDER_H(state_idx,state_idx) = std::stod(split(line,' ')[5]);
					state_idx++;
					std::getline(is,line);
			}
    		else
    			std::getline(is,line);
    	}
    }
    else
    	opencap_throw("Error: I couldn't read:" + output_file);
    return ZERO_ORDER_H;
}

Eigen::MatrixXd read_qchem_eom_energies(size_t nstates,std::string output_file)
{
	Eigen::MatrixXd ZERO_ORDER_H(nstates,nstates);
	ZERO_ORDER_H=Eigen::MatrixXd::Zero(nstates,nstates);
	std::ifstream is(output_file);
    if (is.good())
    {
    	std::string line, rest;
    	std::getline(is, line);
    	size_t state_idx = 1;
    	while (state_idx<=nstates)
    	{
    		if (is.peek()==EOF)
    			opencap_throw("Error: Reached end of file before "+ std::to_string(nstates) + " energies were found. "
    					"Only " + std::to_string(state_idx) + " states were found. Exiting...");
			if (line.find("Total energy")!= std::string::npos && line.find("Excitation energy")!= std::string::npos)
			{
					ZERO_ORDER_H(state_idx-1,state_idx-1) = std::stod(split(line,' ')[3]);
					state_idx++;
					std::getline(is,line);
			}
    		else
    			std::getline(is,line);
    	}
    }
    else
    	opencap_throw("Error: I couldn't read:" + output_file);
    return ZERO_ORDER_H;
}

std::vector<Atom> read_geometry_from_fchk(std::string fchk_filename)
{
	std::vector<Atom> atoms;
	std::vector<size_t> atom_nums;
	std::vector<double> coords;
	std::ifstream is(fchk_filename);
    if (is.good())
    {
    	std::string line, rest;
    	std::getline(is, line);
		while(line.find("Atomic numbers")== std::string::npos)
		{
			std::getline(is,line);
    		if (is.peek()==EOF)
    			opencap_throw("Error: Reached end of file before atomic numbers were found.");
		}
		size_t num_elements = stoi(split(line,' ').back());
		size_t lines_to_read = num_elements%6==0 ? (num_elements/6) : num_elements/6+1;
		for (size_t k=1;k<=lines_to_read;k++)
		{
			std::getline(is,line);
			std::vector<std::string> tokens = split(line,' ');
			for (auto token:tokens)
				atom_nums.push_back(std::stoi(token));
		}
		while(line.find("Current cartesian coordinates")== std::string::npos)
		{
			std::getline(is,line);
    		if (is.peek()==EOF)
    			opencap_throw("Error: Reached end of file before Current Cartesian Coordinates were found.");
		}
		num_elements = stoi(split(line,' ').back());
		lines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;
		for (size_t k=1;k<=lines_to_read;k++)
		{
			std::getline(is,line);
			std::vector<std::string> tokens = split(line,' ');
			for (auto token:tokens)
				coords.push_back(std::stod(token));
		}
		//ok now lets populate our atoms
		for(size_t i=0;i<atom_nums.size();i++)
			atoms.push_back(Atom(atom_nums[i],coords[i*3],coords[i*3+1],coords[i*3+2]));
    }
    else
    	opencap_throw("Error: I couldn't read:" + fchk_filename);
    return atoms;
}

BasisSet read_basis_from_fchk(std::string fchk_filename, std::vector<Atom> atoms)
{
	auto start = std::chrono::high_resolution_clock::now();
	std::vector<int> shell_types;
	std::vector<int> prims_per_shell;
	std::vector<int> atom_ids;
	std::vector<double> exps;
	std::vector<double> coeffs;
	// needed for SP specification
	std::vector<double> p_coeffs;
	bool SP_basis_function = true;
	BasisSet bs;
	for(auto atm:atoms)
		bs.centers.push_back(atm.coords);
	std::vector<shell_id> ids;
	std::ifstream is(fchk_filename);
    if (is.good())
    {
    	std::string line, rest;
    	std::getline(is, line);
    	//First lets figure out if there are SP functions
    	//shell types
		while(line.find("Shell types")== std::string::npos)
		{
			std::getline(is,line);
    		if (is.peek()==EOF)
    			opencap_throw("Error: Reached end of file before shell types were found.");
		}
		size_t num_elements = stoi(split(line,' ').back());
		size_t lines_to_read = num_elements%6==0 ? (num_elements/6) : num_elements/6+1;
		for (size_t k=1;k<=lines_to_read;k++)
		{
			std::getline(is,line);
			std::vector<std::string> tokens = split(line,' ');
			for (auto token:tokens)
			{
				shell_types.push_back(std::stoi(token));
			}
		}
		//prims per shell
		while(line.find("Number of primitives per shell")== std::string::npos)
		{
			std::getline(is,line);
    		if (is.peek()==EOF)
    			opencap_throw("Error: Reached end of file before Number of primitives per shell were found.");
		}
		num_elements = stoi(split(line,' ').back());
		lines_to_read = num_elements%6==0 ? (num_elements/6) : num_elements/6+1;
		for (size_t k=1;k<=lines_to_read;k++)
		{
			std::getline(is,line);
			std::vector<std::string> tokens = split(line,' ');
			for (auto token:tokens)
				prims_per_shell.push_back(std::stoi(token));
		}
		//atom ids
		while(line.find("Shell to atom map")== std::string::npos)
		{
			std::getline(is,line);
    		if (is.peek()==EOF)
    			opencap_throw("Error: Reached end of file before Shell to atom map was found.");
		}
		num_elements = stoi(split(line,' ').back());
		lines_to_read = num_elements%6==0 ? (num_elements/6) : num_elements/6+1;
		for (size_t k=1;k<=lines_to_read;k++)
		{
			std::getline(is,line);
			std::vector<std::string> tokens = split(line,' ');
			for (auto token:tokens)
				atom_ids.push_back(std::stoi(token));
		}
		//prims
		while(line.find("Primitive exponents")== std::string::npos)
		{
			std::getline(is,line);
    		if (is.peek()==EOF)
    			opencap_throw("Error: Reached end of file before Primitive exponents were found.");
		}
		num_elements = stoi(split(line,' ').back());
		lines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;
		for (size_t k=1;k<=lines_to_read;k++)
		{
			std::getline(is,line);
			std::vector<std::string> tokens = split(line,' ');
			for (auto token:tokens)
				exps.push_back(std::stod(token));
		}
		//coeffs
		while(line.find("Contraction coefficients")== std::string::npos)
		{
			std::getline(is,line);
    		if (is.peek()==EOF)
    			opencap_throw("Error: Reached end of file before Contraction coefficients were found.");
		}
		num_elements = stoi(split(line,' ').back());
		lines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;
		for (size_t k=1;k<=lines_to_read;k++)
		{
			std::getline(is,line);
			std::vector<std::string> tokens = split(line,' ');
			for (auto token:tokens)
				coeffs.push_back(std::stod(token));
		}
		while(line.find("P(S=P) Contraction coefficients")== std::string::npos)
		{
			std::getline(is,line);
    		if (is.peek()==EOF)
    		{
    			SP_basis_function = false;
    			break;
    		}
		}
		if (SP_basis_function)
		{
			num_elements = stoi(split(line,' ').back());
			lines_to_read = num_elements%5==0 ? (num_elements/5) : num_elements/5+1;
			for (size_t k=1;k<=lines_to_read;k++)
			{
				std::getline(is,line);
				std::vector<std::string> tokens = split(line,' ');
				for (auto token:tokens)
					p_coeffs.push_back(std::stod(token));
			}
		}
    }
    else
    	opencap_throw("Error: I couldn't read:" + fchk_filename);
    size_t prim_idx=0;
    for(size_t i=0;i<shell_types.size();i++)
    {
    	//SP
    	if(shell_types[i]==-1)
    	{
    		if(p_coeffs.size()==0)
    			opencap_throw("Error: missing section P(S=P) Contraction coefficients.");
    		Shell s_shell(0,atoms[atom_ids[i]-1].coords);
    		Shell p_shell(1,atoms[atom_ids[i]-1].coords);
			int num_prims = prims_per_shell[i];
			for(int j=1;j<=num_prims;j++)
			{
				s_shell.add_primitive(exps[prim_idx],coeffs[prim_idx]);
				p_shell.add_primitive(exps[prim_idx],p_coeffs[prim_idx]);
				prim_idx++;
			}
			bs.add_shell(s_shell);
			bs.add_shell(p_shell);
    	}
    	else
    	{
			Shell new_shell(abs(shell_types[i]),atoms[atom_ids[i]-1].coords);
			if(shell_types[i]>0 && new_shell.l>1)
				new_shell.pure=false;
			int num_prims = prims_per_shell[i];
			for(int j=1;j<=num_prims;j++)
			{
				new_shell.add_primitive(exps[prim_idx],coeffs[prim_idx]);
				prim_idx++;
			}
			bs.add_shell(new_shell);
    	}
    }
    bs.normalize();
	auto stop = std::chrono::high_resolution_clock::now();
	auto total_time = std::chrono::duration<double>(stop-start).count();
    return bs;
}

ext: cpp

max_stars_repo_name: SoubhikM/opencap

max_issues_repo_name: SoubhikM/opencap

max_forks_repo_name: SoubhikM/opencap


text: #include <boost/geometry/core/ring_type.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// ----------------------------------------------------------------------------
// Copyright (C) 2002-2006 Marcin Kalicinski
//
// 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)
//
// For more information, see www.boost.org
// ----------------------------------------------------------------------------
#ifndef BOOST_PROPERTY_TREE_DETAIL_PROPERTIES_PARSER_READ_HPP_INCLUDED
#define BOOST_PROPERTY_TREE_DETAIL_PROPERTIES_PARSER_READ_HPP_INCLUDED

#include "boost/property_tree/detail/properties_parser_error.hpp"
#include "boost/property_tree/ptree.hpp"
//#include "boost/property_tree/detail/properties_parser_utils.hpp"

#include <sample/action/properties_action.hpp>
#include <sample/encoding/encoding.hpp>

#include <boost/spirit/include/classic_position_iterator.hpp>
#include <boost/spirit/include/lex_lexertl.hpp>
#include <boost/spirit/include/support_multi_pass.hpp>

#include <cctype>
#include <fstream>
#include <iterator>
#include <stack>
#include <string>

// define macro for callback member function
#define CALL_MEMBER_FN(member_function) ((*this).*(member_function))

namespace boost {
namespace property_tree {
namespace properties_parser {

/*!
 * in this example the struct 'properties_actor' is used as a functor
 * collecting all key-value properties in the analyzed input sequence by
 * identifying the matched tokens as passed from the lexer.
 */
template <class Ptree, class Ch> class properties_actor {
public:
  // type of properties container output
  typedef Ptree properties_type;
  // type of a key-value property
  typedef std::pair<std::basic_string<Ch>, std::basic_string<Ch>> property_type;

  properties_actor(properties_type &properties_reference)
      : properties(properties_reference), property(none), current_reference(&properties_actor::allocate) {}

  ~properties_actor() {
    // add last property when it is only a key without eol
    if (current_reference == &properties_actor::get) {
      push_back();
    }
  }

  /*!
   * store the current property and change state to prepare
   * the next property read.
   */
  void push_back() {
    current_reference = &properties_actor::allocate;
    properties.push_back(std::make_pair(property.first, Ptree(property.second)));
  }

  /*!
   * create the current property pair to populate and change state to
   * return the current reference.
   */
  property_type &current() { return CALL_MEMBER_FN(current_reference)(); }

private:
  property_type &get() { return property; };

  property_type &allocate() {
    current_reference = &properties_actor::get;
    property = std::make_pair(std::string(), std::string());
    return property;
  };

  // the property container to populate
  properties_type &properties;

  // default reference
  property_type none;

  // the temporary property
  property_type property;

  // callback for lazy initialization of current property pair
  typedef property_type &(properties_actor::*current_reference_callback)();
  // the callback to retrieve the current property reference
  current_reference_callback current_reference;
};

namespace detail {
template <typename Ch> struct basic_file_iterator {
  typedef boost::spirit::classic::position_iterator2<boost::spirit::multi_pass<std::istreambuf_iterator<Ch>>> type;
};

template <typename Ch>
typename basic_file_iterator<Ch>::type make_file_iterator(std::basic_istream<Ch> &input, const std::string &filename) {
  return typename basic_file_iterator<Ch>::type(spirit::make_default_multi_pass(std::istreambuf_iterator<Ch>(input)),
                                                spirit::multi_pass<std::istreambuf_iterator<Ch>>(), filename);
}

template <class Ch> struct properties_parser {
  template <class ForwardTraversalIterator, class Lexer, class Ptree>
  static bool parse(ForwardTraversalIterator first, ForwardTraversalIterator last, const Lexer &lexer,
                    Ptree &cpp_properties) {
    properties_actor<Ptree, Ch> actor(cpp_properties);
    auto action = std::move(make_action(actor));

    return tokenize(first, last, lexer, [&action](auto token) { return action(token); });
  }
};

} // namespace detail

// Build ptree from properties stream
template <class Ptree, class Ch>
void read_properties_internal(std::basic_istream<Ch> &stream, Ptree &pt, const std::string &filename,
                              int include_depth) {
  namespace lexertl = boost::spirit::lex::lexertl;
  using boost::spirit::lex::tokenize;
  using cpp_properties::cpp_properties_lexer;

  typedef typename detail::basic_file_iterator<Ch>::type token_iterator_type;

  // create the token definition instance needed to invoke the lexical analyzer
  typedef lexertl::token<token_iterator_type, mpl::vector0<>, mpl::true_, std::size_t> token_t;
  cpp_properties_lexer<lexertl::lexer<token_t>> lexer;

  typedef typename detail::properties_parser<Ch> properties_parser;

  Ptree cpp_properties;
  token_iterator_type first(detail::make_file_iterator(stream, filename));
  token_iterator_type last;
  bool success = properties_parser::parse(first, last, lexer, cpp_properties);

  if (success) {
    pt.swap(cpp_properties);
  }
}

} // namespace properties_parser
} // namespace property_tree
} // namespace boost

#endif


text:
/*
    Copyright (c) 2022 Xavier Leclercq
    Released under the MIT License
    See https://github.com/ishiko-cpp/time/blob/main/LICENSE.txt
*/

#ifndef _ISHIKO_CPP_TIME_TIMEOFDAY_HPP_
#define _ISHIKO_CPP_TIME_TIMEOFDAY_HPP_

#include <boost/date_time.hpp>

namespace Ishiko
{

class TimeOfDay
{
public:
    TimeOfDay(unsigned char hours, unsigned char minutes, unsigned char seconds);
    TimeOfDay(boost::posix_time::time_duration timeOfDay);

    unsigned char hours() const;
    unsigned char minutes() const;
    unsigned char seconds() const;

private:
    boost::posix_time::time_duration m_timeOfDay;
};

}

#endif

max_stars_repo_name: ishiko-cpp/time

max_issues_repo_name: ishiko-cpp/time

max_forks_repo_name: ishiko-cpp/time


text:
#include <boost/python/module.hpp>
#include <boost/python/class.hpp>
#include <boost/python/def.hpp>
#include <boost/python/args.hpp>

#include <simtbx/gpu/structure_factors.h>
#include <simtbx/gpu/detector.h>
#include <simtbx/gpu/simulation.h>

namespace simtbx { namespace gpu {

  struct gpu_instance_wrapper
  {
    static void
    wrap()
    {
      using namespace boost::python;
      class_<simtbx::gpu::gpu_instance>("gpu_instance",init<>() )
        .def(init< const int& >(( arg("deviceId"))))
        .def("get_deviceID", &simtbx::gpu::gpu_instance::get_deviceID)
        ;
    }
  };

  struct structure_factor_wrapper
  {
    static void
    wrap()
    {
      using namespace boost::python;
      class_<simtbx::gpu::gpu_energy_channels>("gpu_energy_channels",init<>() )
        .def(init< const int& >(( arg("deviceId"))))
        .def("get_deviceID",
             &simtbx::gpu::gpu_energy_channels::get_deviceID
            )
        .def("get_nchannels",
             &simtbx::gpu::gpu_energy_channels::get_nchannels
            )
        .def("structure_factors_to_GPU_direct",
             &simtbx::gpu::gpu_energy_channels::structure_factors_to_GPU_direct,
             (arg_("dummy_int"), arg_("indices"), arg_("amplitudes"))
            )
        ;
    }
  };

  struct detector_wrapper
  {
    static void
    wrap()
    {
      using namespace boost::python;
      class_<simtbx::gpu::gpu_detector>("gpu_detector",init<>() )
        .def(init<int const&, const simtbx::nanoBragg::nanoBragg&>(
            ( arg("deviceId"),arg("nanoBragg")),
             "Single panel constructor with data taken from nanoBragg instance\n"
             "The deviceId is mandatory for CUDA."))
        .def(init<int const&, dxtbx::model::Detector const &, dxtbx::model::Beam const &>(
            ( arg("deviceId"),arg("detector"),arg("beam")),
             "Multipanel constructor with data taken from dxtbx objects\n"
             "The deviceId is mandatory for CUDA."))
        .def("get_deviceID", &simtbx::gpu::gpu_detector::get_deviceID
            )
        .def("show_summary",&simtbx::gpu::gpu_detector::show_summary)
        .def("each_image_allocate",
              &simtbx::gpu::gpu_detector::each_image_allocate,
             "Allocate large pixel arrays")
        .def("scale_in_place", &simtbx::gpu::gpu_detector::scale_in_place,
             "Apply a scale factor directly on the GPU")
        .def("write_raw_pixels",&simtbx::gpu::gpu_detector::write_raw_pixels,
             "Update raw_pixels on host with array from GPU")
        .def("get_raw_pixels",&simtbx::gpu::gpu_detector::get_raw_pixels,
             "return multipanel detector raw pixels as a flex array")
        .def("get_whitelist_raw_pixels",
              (af::shared<double> (simtbx::gpu::gpu_detector::*)(af::shared<std::size_t>))
              &simtbx::gpu::gpu_detector::get_whitelist_raw_pixels,
             "return only those raw pixels requested by the whitelist selection, as a 1D flex array")
        .def("each_image_free", &simtbx::gpu::gpu_detector::each_image_free)
        ;
    }
  };

  struct simulation_wrapper
  {
    static void
    wrap()
    {
      using namespace boost::python;
      using namespace simtbx::gpu;
      class_<simtbx::gpu::exascale_api>("exascale_api",no_init )
        .def(init<const simtbx::nanoBragg::nanoBragg&>(
            ( arg("nanoBragg"))))
        .def("allocate",&simtbx::gpu::exascale_api::allocate,
             "Allocate and transfer input data on the GPU")
        .def("add_energy_channel_from_gpu_amplitudes",
             &simtbx::gpu::exascale_api::add_energy_channel_from_gpu_amplitudes,
             "Point to Fhkl at a new energy channel on the GPU, and accumulate Bragg spot contributions to the detector's accumulator array")
        .def("add_energy_channel_mask_allpanel",
             static_cast<void (exascale_api::*)(int const&, gpu_energy_channels&, gpu_detector&, af::shared<int> const) >
             (&exascale_api::add_energy_channel_mask_allpanel),
             (arg_("channel_number"), arg_("gpu_amplitudes"), arg_("gpu_detector"), arg_("pixel_active_list_ints")),
             "Point to Fhkl at a new energy channel on the GPU, and accumulate Bragg spots on mask==True pixels")
        .def("add_energy_channel_mask_allpanel",
             static_cast<void (exascale_api::*)(int const&, gpu_energy_channels&, gpu_detector&, af::shared<bool>) >
             (&exascale_api::add_energy_channel_mask_allpanel),
             (arg_("channel_number"), arg_("gpu_amplitudes"), arg_("gpu_detector"), arg_("pixel_active_mask_bools")),
             "Point to Fhkl at a new energy channel on the GPU, and accumulate Bragg spots on mask==True pixels")
        .def("add_background", &simtbx::gpu::exascale_api::add_background,
             (arg_("detector"), arg_("override_source")=-1),
             "Add a background field directly on the GPU")
        .def("show",&simtbx::gpu::exascale_api::show)
        ;
    }
  };

  } // namespace gpu

  BOOST_PYTHON_MODULE(simtbx_gpu_ext)
  {
    simtbx::gpu::gpu_instance_wrapper::wrap();
    simtbx::gpu::structure_factor_wrapper::wrap();
    simtbx::gpu::detector_wrapper::wrap();
    simtbx::gpu::simulation_wrapper::wrap();
  }
} // namespace simtbx


text:
#include <iostream>
#include <armadillo>

using namespace arma;
using std::cout;
using std::endl;

void cxmatLoad(cx_mat& uMat, int &size, char* file)
{
	cx_mat uTest;
	int uCheck;
	uTest.load(file);

	if(uMat.n_rows !=  uMat.n_cols)
	{
		cout << "[Error] : Input matrix is non square" << endl;
		exit(1);
	}
	else
	{
		size = uMat.n_rows;
	}

	uCheck = static_cast<int>(real(trace(uMat * uMat.t())));

	if(uCheck != size)
	{
		cout << "[Error] : Input matrix is non-unitary " << endl;
		exit(1);
	}
	else
	{
		uMat = uTest;
	}
}

max_stars_repo_name: Swaddle/qGeod

max_issues_repo_name: Swaddle/qGeod

max_forks_repo_name: Swaddle/qGeod


text:
//
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/boostorg/beast
//

#ifndef BOOST_BEAST_DETAIL_BIND_HANDLER_HPP
#define BOOST_BEAST_DETAIL_BIND_HANDLER_HPP

#include <boost/beast/core/detail/integer_sequence.hpp>
#include <boost/asio/handler_alloc_hook.hpp>
#include <boost/asio/handler_continuation_hook.hpp>
#include <boost/asio/handler_invoke_hook.hpp>
#include <boost/core/ignore_unused.hpp>
#include <functional>
#include <utility>

namespace boost {
namespace beast {
namespace detail {

/*  Nullary handler that calls Handler with bound arguments.

    The bound handler provides the same io_service execution
    guarantees as the original handler.
*/
template<class Handler, class... Args>
class bound_handler
{
private:
    using args_type = std::tuple<
        typename std::decay<Args>::type...>;

    Handler h_;
    args_type args_;

    template<class Arg, class Vals>
    static
    typename std::enable_if<
        std::is_placeholder<typename
            std::decay<Arg>::type>::value == 0,
    Arg&&>::type
    extract(Arg&& arg, Vals& vals)
    {
        boost::ignore_unused(vals);
        return arg;
    }

    template<class Arg, class Vals>
    static
    typename std::enable_if<
        std::is_placeholder<typename
            std::decay<Arg>::type>::value != 0,
    typename std::tuple_element<
        std::is_placeholder<
            typename std::decay<Arg>::type>::value - 1,
    Vals>::type&&>::type
    extract(Arg&&, Vals&& vals)
    {
        return std::get<std::is_placeholder<
            typename std::decay<Arg>::type>::value - 1>(
                std::forward<Vals>(vals));
    }

    template<
        class ArgsTuple,
        std::size_t... S>
    static
    void
    invoke(
        Handler& h,
        ArgsTuple& args,
        std::tuple<>&&,
        index_sequence<S...>)
    {
        boost::ignore_unused(args);
        h(std::get<S>(args)...);
    }

    template<
        class ArgsTuple,
        class ValsTuple,
        std::size_t... S>
    static
    void
    invoke(
        Handler& h,
        ArgsTuple& args,
        ValsTuple&& vals,
        index_sequence<S...>)
    {
        boost::ignore_unused(args);
        boost::ignore_unused(vals);
        h(extract(std::get<S>(args),
            std::forward<ValsTuple>(vals))...);
    }

public:
    using result_type = void;

    bound_handler(bound_handler&&) = default;
    bound_handler(bound_handler const&) = default;

    template<class DeducedHandler>
    explicit
    bound_handler(
            DeducedHandler&& handler, Args&&... args)
        : h_(std::forward<DeducedHandler>(handler))
        , args_(std::forward<Args>(args)...)
    {
    }

    template<class... Values>
    void
    operator()(Values&&... values)
    {
        invoke(h_, args_,
            std::forward_as_tuple(
                std::forward<Values>(values)...),
            index_sequence_for<Args...>());
    }

    template<class... Values>
    void
    operator()(Values&&... values) const
    {
        invoke(h_, args_,
            std::forward_as_tuple(
                std::forward<Values>(values)...),
            index_sequence_for<Args...>());
    }

    friend
    void*
    asio_handler_allocate(
        std::size_t size, bound_handler* h)
    {
        using boost::asio::asio_handler_allocate;
        return asio_handler_allocate(
            size, std::addressof(h->h_));
    }

    friend
    void
    asio_handler_deallocate(
        void* p, std::size_t size, bound_handler* h)
    {
        using boost::asio::asio_handler_deallocate;
        asio_handler_deallocate(
            p, size, std::addressof(h->h_));
    }

    friend
    bool
    asio_handler_is_continuation(bound_handler* h)
    {
        using boost::asio::asio_handler_is_continuation;
        return asio_handler_is_continuation(std::addressof(h->h_));
    }

    template<class F>
    friend
    void
    asio_handler_invoke(F&& f, bound_handler* h)
    {
        using boost::asio::asio_handler_invoke;
        asio_handler_invoke(
            f, std::addressof(h->h_));
    }
};

} // detail
} // beast
} // boost

namespace std {
template<class Handler, class... Args>
void
bind(boost::beast::detail::bound_handler<
    Handler, Args...>, ...) = delete;
} // std

#endif


text:
#include <Eigen/Dense>
//#include <dart/collision/bullet/BulletCollisionDetector.hpp>
#include <dart/dynamics/Skeleton.hpp>
#include <dart/dynamics/DegreeOfFreedom.hpp>
#include <dart/dynamics/FreeJoint.hpp>
#include <dart/dynamics/WeldJoint.hpp>
#include <dart/dynamics/SphereShape.hpp>
#include <dart/simulation/World.hpp>
#include <dart/utils/urdf/DartLoader.hpp>
#include <dart/constraint/ConstraintSolver.hpp>
#include <dart/gui/osg/osg.hpp>
#include <dart/gui/osg/TrackballManipulator.hpp>

#include <Nomad/MessageTypes/sim_data_t.hpp>
#include <Nomad/MessageTypes/joint_control_cmd_t.hpp>
#include <condition_variable>
#include <vector>
#include "../include/NomadRobot.h"

// Third Party Includes
#include <zcm/zcm-cpp.hpp>

using namespace dart::dynamics;
using namespace dart::simulation;

WorldPtr g_world;
std::shared_ptr<NomadRobot> g_nomad;
Eigen::VectorXd joint_torques_cmd = Eigen::VectorXd::Zero(18);

std::mutex mtx;
std::condition_variable cv;

bool b_first = true;

class NomadSimWorldNode : public dart::gui::osg::RealTimeWorldNode
{

public:
  explicit NomadSimWorldNode(WorldPtr world, const std::shared_ptr<NomadRobot> nomad)
      : dart::gui::osg::RealTimeWorldNode(world), nomad_(nomad), world_(world)
  {
    // World gets saved as -> mWorld if ever needed.  Also ->getWorld()
    Eigen::Isometry3d tf = Eigen::Isometry3d::Identity();

    // TODO: Pass IP Address as a parameter
    context_ = std::make_unique<zcm::ZCM>("udpm://239.255.76.67:7667?ttl=0");

    std::cout << "Nomad DART Sim connecting." << std::endl;

    context_->subscribe("nomad.sim.joint_cmd", &NomadSimWorldNode::OnJointControlMsg, this);

    // TODO: Publish state back
    pub_context_ = std::make_unique<zcm::ZCM>("udpm://239.255.76.67:7667?ttl=0");

    sequence_num_ = 0;

    step_iter = 0;
  }

  void ReceiveCommand()
  {
    context_->handle();
  }

  void customPreStep()
  {
    if(step_iter < 10)
    {
      return;
    }
    if(b_first)
    {
      PublishState();
      b_first = false;
    }

    ReceiveCommand();

   nomad_->Skeleton()->setForces(joint_torques_cmd);
  }

  void customPostStep()
  {
    PublishState();

    //joint_torques = Eigen::VectorXd::Zero(18);
    step_iter++;
  }

  void OnJointControlMsg(const zcm::ReceiveBuffer *rbuf, const std::string &chan, const joint_control_cmd_t *msg)
  {
    // Read Input

    Eigen::VectorXd tau_cmd(12);

    tau_cmd[0] = msg->tau_ff[0];
    tau_cmd[1] = msg->tau_ff[1];
    tau_cmd[2] = msg->tau_ff[2];
    tau_cmd[3] = msg->tau_ff[3];
    tau_cmd[4] = msg->tau_ff[4];
    tau_cmd[5] = msg->tau_ff[5];
    tau_cmd[6] = msg->tau_ff[6];
    tau_cmd[7] = msg->tau_ff[7];
    tau_cmd[8] = msg->tau_ff[8];
    tau_cmd[9] = msg->tau_ff[9];
    tau_cmd[10] = msg->tau_ff[10];
    tau_cmd[11] = msg->tau_ff[11];

    joint_torques_cmd.tail(12) = tau_cmd;
  }

  void PublishState()
  {
    sim_data_t sim_data;

    uint64_t time_now = sequence_num_;

    // Get Relevant State Data
    Eigen::Quaterniond body_orientation = nomad_->GetBaseOrientation();
    Eigen::Vector3d body_pos = nomad_->GetBasePosition(); // World
    Eigen::Vector3d accel_body = nomad_->GetBaseLinearAcceleration(); // Body
    Eigen::Vector3d angular_body = nomad_->GetBaseAngularVelocity(); // Body
    Eigen::Vector3d vel_body = nomad_->GetBaseLinearVelocity(); // Body

    // Cheater Orientation
    sim_data.timestamp = time_now;
    sim_data.sequence_num = sequence_num_;

    // Copy Body World Position
    Eigen::Map<Eigen::VectorXd>(sim_data.com_pos, 3) = body_pos;

    // Copy Body World Velocity
    Eigen::Map<Eigen::VectorXd>(sim_data.com_vel, 3) = body_orientation.toRotationMatrix() * vel_body;

    // Copy Body Orientation
    sim_data.com_orientation[0] = body_orientation.x();
    sim_data.com_orientation[1] = body_orientation.y();
    sim_data.com_orientation[2] = body_orientation.z();
    sim_data.com_orientation[3] = body_orientation.w();

    // Copy Body Angular Velocity (World)
    Eigen::Map<Eigen::VectorXd>(sim_data.com_omega, 3) = body_orientation.toRotationMatrix() * angular_body;

    // IMU Orientation
    // Copy Body Orientation
    sim_data.imu_orientation[0] = body_orientation.x();
    sim_data.imu_orientation[1] = body_orientation.y();
    sim_data.imu_orientation[2] = body_orientation.z();
    sim_data.imu_orientation[3] = body_orientation.w();

    // IMU Linear Acceleration
    // Accelerometer (Local)
    Eigen::Map<Eigen::VectorXd>(sim_data.imu_accel, 3) = accel_body;

    // Gyro
    // Copy Body Angular Velocity (Local)
    Eigen::Map<Eigen::VectorXd>(sim_data.imu_omega, 3) = angular_body;

    // Copy Joint State "Estimates"
    Eigen::VectorXd joint_pos = nomad_->Skeleton()->getPositions();
    Eigen::VectorXd joint_vel = nomad_->Skeleton()->getVelocities();
    Eigen::VectorXd joint_tau = nomad_->Skeleton()->getForces();

    sim_data.q[0] = joint_pos[6];
    sim_data.q[1] = joint_pos[7];
    sim_data.q[2] = joint_pos[8];
    sim_data.q[3] = joint_pos[9];
    sim_data.q[4] = joint_pos[10];
    sim_data.q[5] = joint_pos[11];
    sim_data.q[6] = joint_pos[12];
    sim_data.q[7] = joint_pos[13];
    sim_data.q[8] = joint_pos[14];
    sim_data.q[9] = joint_pos[15];
    sim_data.q[10] = joint_pos[16];
    sim_data.q[11] = joint_pos[17];

    sim_data.q_dot[0] = joint_vel[6];
    sim_data.q_dot[1] = joint_vel[7];
    sim_data.q_dot[2] = joint_vel[8];
    sim_data.q_dot[3] = joint_vel[9];
    sim_data.q_dot[4] = joint_vel[10];
    sim_data.q_dot[5] = joint_vel[11];
    sim_data.q_dot[6] = joint_vel[12];
    sim_data.q_dot[7] = joint_vel[13];
    sim_data.q_dot[8] = joint_vel[14];
    sim_data.q_dot[9] = joint_vel[15];
    sim_data.q_dot[10] = joint_vel[16];
    sim_data.q_dot[11] = joint_vel[17];

    sim_data.tau[0] = joint_tau[6];
    sim_data.tau[1] = joint_tau[7];
    sim_data.tau[2] = joint_tau[8];
    sim_data.tau[3] = joint_tau[9];
    sim_data.tau[4] = joint_tau[10];
    sim_data.tau[5] = joint_tau[11];
    sim_data.tau[6] = joint_tau[12];
    sim_data.tau[7] = joint_tau[13];
    sim_data.tau[8] = joint_tau[14];
    sim_data.tau[9] = joint_tau[15];
    sim_data.tau[10] = joint_tau[16];
    sim_data.tau[11] = joint_tau[17];

    sequence_num_++;

    // Publish
    int rc = pub_context_->publish("nomad.sim.data", &sim_data);
    //pub_context_->flush();
  }

protected:
  std::shared_ptr<NomadRobot> nomad_;
  WorldPtr world_;

  std::unique_ptr<zcm::ZCM> context_;

  std::unique_ptr<zcm::ZCM> pub_context_;

  int step_iter;

  uint64_t sequence_num_;

};

SkeletonPtr CreateGround()
{
  SkeletonPtr ground = Skeleton::create("ground");

  // Give the ground a body
  BodyNodePtr body = ground->createJointAndBodyNodePair<WeldJoint>(nullptr).second;
  double thickness = 0.1;

  ShapePtr groundShape = std::make_shared<BoxShape>(Eigen::Vector3d(4, 4, thickness));
  auto shapeNode = body->createShapeNodeWith<VisualAspect, CollisionAspect, DynamicsAspect>(groundShape);

  shapeNode->getVisualAspect()->setColor(dart::Color::LightGray());

  Eigen::Isometry3d tf(Eigen::Isometry3d::Identity());
  tf.translation() = Eigen::Vector3d(0, 0, -thickness / 2.0);
  body->getParentJoint()->setTransformFromParentBodyNode(tf);

  return ground;
}

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

  // Create dart simulation world
  g_world = World::create();

  // Update Gravity vector to Z down
  Eigen::Vector3d gravity(0.0, 0.0, -9.81);
  //Eigen::Vector3d gravity(0.0, 0.0, 0.0);
  g_world->setGravity(gravity);

  // Create and add ground to world
  SkeletonPtr ground = CreateGround();
  g_world->addSkeleton(ground);

  // Update Collision
  //g_world->getConstraintSolver()->setCollisionDetector(dart::collision::BulletCollisionDetector::create());

  g_nomad = std::make_shared<NomadRobot>(g_world);

  std::string urdf = std::getenv("NOMAD_RESOURCE_PATH");
  urdf.append("/Robot_V2/NOMAD.urdf");

  g_nomad->LoadFromURDF(urdf);
  g_nomad->SetInitialPose();

  // Create osg world node
  ::osg::ref_ptr<NomadSimWorldNode> node = new NomadSimWorldNode(g_world, g_nomad);

  // Create osg Viewer
  dart::gui::osg::Viewer viewer = dart::gui::osg::Viewer();
  viewer.addWorldNode(node);

  // Default with Headlights
  viewer.switchHeadlights(false);

  //Add Grid Attachment
  ::osg::ref_ptr<dart::gui::osg::GridVisual> grid = new dart::gui::osg::GridVisual();

  viewer.addAttachment(grid);

  viewer.addAttachment(
      new dart::gui::osg::SupportPolygonVisual(g_nomad->Skeleton(), 0.025));

  // Print out instructions for the viewer
  std::cout << viewer.getInstructions() << std::endl;

  viewer.setUpViewInWindow(0, 0, 1280, 1024);
  viewer.getCameraManipulator()->setHomePosition(::osg::Vec3(0.0f, -5.0f, 0.0f),
                                                 ::osg::Vec3(0.0f, 0.0f, 0.0f),
                                                 ::osg::Vec3(0.0f, 0.707f, 0.707f), false);

  viewer.setCameraManipulator(viewer.getCameraManipulator());
  viewer.simulate(true);
  viewer.run();

  return 0;
}

max_stars_repo_name: implementedrobotics/Nomad

max_issues_repo_name: implementedrobotics/Nomad

max_forks_repo_name: implementedrobotics/Nomad


text:
#include <iostream>
#include <cmath>

#include <Eigen/Core>
// Eigen 几何模块
#include <Eigen/Geometry>
#include <Eigen/SVD>

#include <chrono>
using namespace std::chrono;
using namespace std;

/****************************
* 本程序演示了 Eigen 几何模块的使用方法
****************************/

// TO-DO: 搞清楚四元数的顺序问题，明天去填下。

int main ( int argc, char** argv )
{
    // Eigen/Geometry 模块提供了各种旋转和平移的表示
    // 3D 旋转矩阵直接使用 Matrix3d 或 Matrix3f
    Eigen::Matrix3d rotation_matrix = Eigen::Matrix3d::Identity();
    // 旋转向量使用 AngleAxis, 它底层不直接是Matrix，但运算可以当作矩阵（因为重载了运算符）
    // 构造函数初始化
    Eigen::AngleAxisd rotation_vector ( M_PI/4, Eigen::Vector3d ( 0,0,1 ) );     //沿 Z 轴旋转 45 度
    // 保留三位小数！
    cout .precision(3);
    // 将旋转向量用矩阵的形式表征出来
    cout<<"rotation matrix =\n"<<rotation_vector.matrix() <<endl;                //用matrix()转换成矩阵
    // 将旋转向量形式转换成旋转矩阵形式
    cout<<"rotation matrix =\n"<<rotation_vector.toRotationMatrix() <<endl;
    rotation_matrix = rotation_vector.toRotationMatrix();

    // 定义了一个待旋转的向量
    Eigen::Vector3d v ( 1,0,0 );
    // 这里应该是重载<<的时候存在顺序的问题，因此需要加上transpose来正确显示想要展示的内容
    cout<<"(1,0,0) before rotation = "<<v.transpose()<<endl;
    // 用 AngleAxis 可以进行坐标变换
    // 里面应该是重载了*运算符
    Eigen::Vector3d v_rotated = rotation_vector * v;
    cout<<"(1,0,0) after rotation = "<<v_rotated.transpose()<<endl;
    // 或者用旋转矩阵，效果一样，同理重载
    v_rotated = rotation_matrix * v;
    cout<<"(1,0,0) after rotation = "<<v_rotated.transpose()<<endl;

    // 欧拉角: 可以将旋转矩阵直接转换成欧拉角
    // 这里的2,1,0分别代指ZYX，表示先后以这三个为轴旋转
    Eigen::Vector3d euler_angles = rotation_matrix.eulerAngles ( 2,1,0 ); // ZYX顺序，即roll pitch yaw顺序
    cout<<"yaw pitch roll = "<<euler_angles.transpose()<<endl;

    // 欧式变换，包括了旋转与平移
    // 欧氏变换矩阵使用 Eigen::Isometry（等距）
    Eigen::Isometry3d T=Eigen::Isometry3d::Identity();    // 虽然称为3d，实质上是4＊4的矩阵
    // 通过调用成员函数的方式来赋值
    T.rotate ( rotation_vector );                         // 按照rotation_vector进行旋转
    // pretranslate函数用于inital position setting
    // Applies on the right the translation matrix represented by the vector
    T.pretranslate ( Eigen::Vector3d ( 1,3,4 ) );         // 把平移向量设成(1,3,4)
    cout << "Transform matrix = \n" << T.matrix() <<endl;

    Eigen::Matrix3d rotation_T = T.rotation();
    cout<<"---- T ---- rotation matrix  =\n"<<rotation_T <<endl;

    Eigen::Quaterniond q_T = Eigen::Quaterniond ( rotation_T );
    cout<<"---- T ---- quaternion = \n"<<q_T.coeffs() <<endl;

    Eigen::Vector3d translation_T = T.translation();
    cout<<"---- T ---- translation = \n"<<translation_T.transpose() <<endl;

    // 用变换矩阵进行坐标变换，v是（1，0，0）
    Eigen::Vector3d v_transformed = T*v;                              // 相当于R*v+t，理解！
    cout<<"v tranformed = "<<v_transformed.transpose()<<endl;         // 结果正确

    // 对于仿射和射影变换，使用 Eigen::Affine3d 和 Eigen::Projective3d 即可，略

    // 四元数
    // 可以直接把AngleAxis赋值给四元数，反之亦然，也就是用角轴转成四元数
    Eigen::Quaterniond q = Eigen::Quaterniond ( rotation_vector );
    cout<<"quaternion = \n"<<q.coeffs() <<endl;   // 请注意coeffs的顺序是(x,y,z,w),w为实部，前三者为虚部，顺序不一样

    Eigen::Quaterniond q1(0.924, 0, 0, 0.383); // 赋值的时候是w,x,y,z
    cout<<"quaternion1 = \n"<<q1.coeffs() <<endl;

    // 也可以把旋转矩阵赋给它，结果一样！
    Eigen::Quaterniond q2 = Eigen::Quaterniond ( rotation_matrix );
    cout<<"quaternion = \n"<<q2.coeffs() <<endl;

    cout<<"--- rotation matrix =\n"<<q2.toRotationMatrix() <<endl;

    // 使用四元数旋转一个向量，使用重载的乘法即可
    v_rotated = q*v; // 注意数学上是qvq^{-1}
    cout<<"(1,0,0) after rotation = "<<v_rotated.transpose()<<endl; //结果正确

    auto t0 = std::chrono::high_resolution_clock::now();
    Eigen::Quaterniond quat = Eigen::Quaterniond ( T.rotation() );
    Eigen::Vector3d pos = T.translation();
    std::cout <<"time is " << std::chrono::duration_cast<std::chrono::nanoseconds> (std::chrono::high_resolution_clock::now() - t0).count()<< '\n';

    Eigen::Matrix4d T_m = Eigen::Matrix4d::Identity();
    T_m.block<3, 3>(0, 0) = rotation_matrix;
    T_m.block<3, 1>(0, 3) = Eigen::Vector3d ( 1,3,4 );
    cout << "Transform matrix = \n" << T_m <<endl;
    cout << "Rotation matrix= \n" << T_m.block<3, 3>(0, 0) << endl;
    cout << "Translation matrix= \n" << T_m.block<3, 1>(0, 3) << endl;

    // Test if Quaterniond only takes normalized rotation matrix
    cout << "Rotation matrix= \n" << rotation_matrix << endl;
    rotation_matrix *= 2.0;
    cout << "Rotation matrix= \n" << rotation_matrix << endl;
    double scale = std::sqrt((rotation_matrix.transpose() * rotation_matrix)(0, 0));
    Eigen::Matrix3d ret = (1. / scale) * rotation_matrix;
    Eigen::Matrix3d rotation_matrix_quat = Eigen::Quaterniond ( ret ).normalized().toRotationMatrix();;
    cout << "Rotation matrix= \n" << rotation_matrix_quat << endl;

    return 0;
}

max_stars_repo_name: billamiable/slambook

max_issues_repo_name: billamiable/slambook

max_forks_repo_name: billamiable/slambook


text:
/*=============================================================================
    Copyright (c) 2001-2007 Joel de Guzman
    Copyright (c) 2015 Kohei Takahashi

    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)
==============================================================================*/

#ifndef BOOST_PHOENIX_CORE_DETAIL_FUNCTION_EVAL_HPP
#define BOOST_PHOENIX_CORE_DETAIL_FUNCTION_EVAL_HPP

#include <boost/phoenix/core/limits.hpp>
#include <boost/phoenix/support/iterate.hpp>
#include <boost/phoenix/core/call.hpp>
#include <boost/phoenix/core/expression.hpp>
#include <boost/phoenix/core/meta_grammar.hpp>
#include <boost/utility/result_of.hpp>

#ifndef BOOST_PHOENIX_NO_VARIADIC_FUNCTION_EVAL
#   include <boost/mpl/if.hpp>
#   include <boost/type_traits/is_reference.hpp>
#endif

#ifdef BOOST_PHOENIX_NO_VARIADIC_EXPRESSION
#   include <boost/phoenix/core/detail/cpp03/function_eval_expr.hpp>
#else
BOOST_PHOENIX_DEFINE_EXPRESSION_VARARG(
    (boost)(phoenix)(detail)(function_eval)
  , (meta_grammar)(meta_grammar)
  , _
)
#endif

namespace boost { namespace phoenix {
    namespace detail
    {
        template <typename T>
        T& help_rvalue_deduction(T& x)
        {
            return x;
        }

        template <typename T>
        T const& help_rvalue_deduction(T const& x)
        {
            return x;
        }

        struct function_eval
        {
            template <typename Sig>
            struct result;

#ifdef BOOST_PHOENIX_NO_VARIADIC_FUNCTION_EVAL
            template <typename This, typename F, typename Context>
            struct result<This(F, Context)>
            {
                typedef typename
                    remove_reference<
                        typename boost::result_of<evaluator(F, Context)>::type
                    >::type
                    fn;

                typedef typename boost::result_of<fn()>::type type;
            };

            template <typename F, typename Context>
            typename result<function_eval(F const&, Context const&)>::type
            operator()(F const & f, Context const & ctx) const
            {
                return boost::phoenix::eval(f, ctx)();
            }

            template <typename F, typename Context>
            typename result<function_eval(F &, Context const&)>::type
            operator()(F & f, Context const & ctx) const
            {
                return boost::phoenix::eval(f, ctx)();
            }

        #include <boost/phoenix/core/detail/cpp03/function_eval.hpp>
#else
            template <typename, typename, typename...> struct result_impl;

            template <typename F, typename... A, typename Head, typename... Tail>
            struct result_impl<F, void(A...), Head, Tail...>
                : result_impl<F, void(A..., Head), Tail...>
            {
            };

            template <typename F, typename... A, typename Context>
            struct result_impl<F, void(A...), Context>
            {
                typedef typename
                    remove_reference<
                        typename boost::result_of<evaluator(F, Context)>::type
                    >::type
                    fn;

                template <typename T>
                struct result_of_evaluator
                {
                    typedef typename boost::add_reference<
                        typename boost::add_const<
                            typename boost::result_of<
                                boost::phoenix::evaluator(T, Context)
                            >::type
                        >::type
                    >::type type;
                };

                typedef typename
                    boost::result_of<
                        fn(typename result_of_evaluator<A>::type...)
                    >::type
                    type;

                static type call(F f, A... a, Context ctx)
                {
                    return boost::phoenix::eval(f, ctx)(help_rvalue_deduction(boost::phoenix::eval(a, ctx))...);
                }
            };

            template <typename This, typename F, typename... A>
            struct result<This(F, A...)>
                : result_impl<F, void(), A...>
            {
            };

            template <typename F, typename... A>
            typename result<
                function_eval(
                    F const &
                  , typename mpl::if_<is_reference<A>, A, A const &>::type...
                )
            >::type
            // 'A &... a, Context const &ctx' doesn't work as intended: type deduction always fail.
            operator()(F && f, A &&... a) const
            {
                return
                    result<
                        function_eval(
                            typename mpl::if_<is_reference<F>, F, F const &>::type
                          , typename mpl::if_<is_reference<A>, A, A const &>::type...
                        )
                    >::call(f, a...);
            }
#endif
        };

    }

    template <typename Dummy>
    struct default_actions::when<detail::rule::function_eval, Dummy>
        : phoenix::call<detail::function_eval>
    {};
}}

#endif


text:
//
//  audio_queue.cpp
//  x2d
//
//  Created by Alex Kremer on 2/13/12.
//  Copyright (c) 2012 godexsoft. All rights reserved.
//

#include "audio_queue.h"
#include "glm.hpp"
#include "exceptions.h"
#include "sound.h"
#include "log.h"
#include <string>
#include <boost/lexical_cast.hpp>

namespace x2d {
namespace snd {

    template<>
    void music_obj<audio_queue_driver>::play()
    {
        LOG("Playback of audio_queue file.");
        is_paused_ = false; // if was paused
        AudioQueueStart(queue_, NULL);
    }

    template<>
    void music_obj<audio_queue_driver>::stop()
    {
        AudioQueueStop(queue_, true);
    }

    template<>
    bool music_obj<audio_queue_driver>::is_playing() const
    {
        UInt32 size, is_running;

        AudioQueueGetPropertySize(queue_, kAudioQueueProperty_IsRunning, &size);
        AudioQueueGetProperty(queue_, kAudioQueueProperty_IsRunning, &is_running, &size);

        return is_running && !is_paused_;
    }

    template<>
    void music_obj<audio_queue_driver>::pause()
    {
        AudioQueuePause(queue_);
        is_paused_ = true;
    }

    template<>
    void music_obj<audio_queue_driver>::resume()
    {
        AudioQueueStart(queue_, NULL);
        is_paused_ = false;
    }

    template<>
    void music_obj<audio_queue_driver>::reset()
    {
        is_paused_ = false;
    }

    template<>
    void music_obj<audio_queue_driver>::volume(float v)
    {
        volume_ = glm::clamp(v, 0.0f, 1.0f);
        AudioQueueSetParameter(queue_, kAudioQueueParam_Volume, volume_);
    }

    template<>
    const float music_obj<audio_queue_driver>::volume() const
    {
        return volume_;
    }

    template<>
    UInt32 music_obj<audio_queue_driver>::read_packets(AudioQueueBufferRef buffer)
    {
        UInt32 num_bytes, num_packets;
        num_packets = num_packets_to_read_;

        AudioFileReadPackets(audio_file_, false, &num_bytes, packet_descriptions_, packet_index_, &num_packets, buffer->mAudioData);
        if (num_packets > 0)
        {
            buffer->mAudioDataByteSize = num_bytes;
            AudioQueueEnqueueBuffer(queue_, buffer, (packet_descriptions_ ? num_packets : 0), packet_descriptions_);
            packet_index_ += num_packets;

            if(stop_packet_index_ != 0 && packet_index_ >= stop_packet_index_) {
                if(loop_)
                    packet_index_ = start_packet_index_;
                else
                    return 0;
            }
        }

        return num_packets;
    }

    template<>
    void music_obj<audio_queue_driver>::calculate_seek(float start, float end)
    {
        bool want_start = start != 0.0f;
        bool want_end   = end != 0.0f;

        total_time_ = 0.0f;

        // variable bitrate requires calculations per packet
        if (data_format_.mBytesPerPacket == 0 || data_format_.mFramesPerPacket == 0)
        {
            UInt32 num_packets = num_packets_to_read_;
            UInt32 num_bytes;

            void* dummy_data = malloc(max_packet_size_*num_packets);

            // read all file
            while(true)
            {
                AudioFileReadPackets(audio_file_, false, &num_bytes, packet_descriptions_, packet_index_, &num_packets, dummy_data);

                if (num_packets > 0)
                {
                    for(int i=0; i<num_packets; ++i) {

                        if(packet_descriptions_[i].mVariableFramesInPacket == 0)
                        {
                            total_time_ += data_format_.mFramesPerPacket / data_format_.mSampleRate;
                        }
                        else
                        {
                            total_time_ += packet_descriptions_[i].mVariableFramesInPacket / data_format_.mSampleRate;
                        }

                        if(want_start && total_time_ >= start)
                        {
                            start_packet_index_ = packet_index_;
                            want_start = false;
                        }

                        if(want_end && total_time_ >= end)
                        {
                            stop_packet_index_ = packet_index_;
                            want_end = false;
                        }

                        packet_index_ += 1;
                    }
                }
                else
                {
                    break; // done
                }
            }

            free(dummy_data);
        }
        else
        {
            UInt32 size = sizeof(UInt64);
            UInt64 total_packets;

            OSStatus err = AudioFileGetProperty(audio_file_, kAudioFilePropertyAudioDataPacketCount, &size, &total_packets);
            if(err != noErr)
            {
                throw sys_exception("audio_queue: Can't get total packet count from CBR audio file. "
                        + boost::lexical_cast<std::string>(err));
            }

            float packet_time =  data_format_.mFramesPerPacket / data_format_.mSampleRate;

            if(want_start)
            {
                start_packet_index_ = start/packet_time;
            }

            if(want_end)
            {
                stop_packet_index_ = end/packet_time;
            }

            total_time_ = total_packets*packet_time;
        }

        LOG("Total length of track: %f", total_time_);
    }

    template<>
    void music_obj<audio_queue_driver>::prime()
    {
        UInt32 i;
        for (i = 0; i < NUM_BUFFERS; ++i)
        {
            AudioQueueAllocateBuffer(queue_, BUFFER_SIZE_BYTES, &buffers_[i]);
            if (read_packets(buffers_[i]) == 0)
            {
                break;
            }
        }

        UInt32 frames_primed;
        AudioQueuePrime(queue_, i, &frames_primed);

        LOG("Primed %d frames", frames_primed);
    }

    template<>
    music_obj<audio_queue_driver>::music_obj(const std::string& file_path, bool loop, float gain,
                                             float start, float end)
    : packet_index_(0)
    , start_packet_index_(0)
    , stop_packet_index_(0)
    , volume_(gain)
    , loop_(loop)
    , is_paused_(false)
    {
        CFURLRef file_url = CFURLCreateFromFileSystemRepresentation(NULL, (const UInt8 *)file_path.c_str(), file_path.size(), false);
        OSStatus res = AudioFileOpenURL(file_url, kAudioFileReadPermission, kAudioFileCAFType, &audio_file_);
        CFRelease(file_url);

        if(res)
        {
            throw sys_exception("audio_queue_driver: couldn't open audio file at '" + file_path + "'");
        }

        UInt32 size = sizeof(data_format_);
        AudioFileGetProperty(audio_file_, kAudioFilePropertyDataFormat, &size, &data_format_);

        AudioQueueNewOutput(&data_format_, &music_obj<audio_queue_driver>::buffer_cb, this, NULL, NULL, 0, &queue_);
        AudioQueueAddPropertyListener(queue_, kAudioQueueProperty_IsRunning, &music_obj<audio_queue_driver>::playback_cb, this);

        if (data_format_.mBytesPerPacket == 0 || data_format_.mFramesPerPacket == 0)
        {
            size = sizeof(max_packet_size_);
            AudioFileGetProperty(audio_file_, kAudioFilePropertyPacketSizeUpperBound, &size, &max_packet_size_);
            if (max_packet_size_ > BUFFER_SIZE_BYTES)
            {
                max_packet_size_ = BUFFER_SIZE_BYTES;
            }

            num_packets_to_read_ = BUFFER_SIZE_BYTES / max_packet_size_;
            packet_descriptions_ = (AudioStreamPacketDescription*)malloc(sizeof(AudioStreamPacketDescription) * num_packets_to_read_);
        }
        else
        {
            num_packets_to_read_ = BUFFER_SIZE_BYTES / data_format_.mBytesPerPacket;
            packet_descriptions_ = NULL;
        }

        AudioFileGetPropertyInfo(audio_file_, kAudioFilePropertyMagicCookieData, &size, NULL);
        if (size > 0)
        {
            char* cookie = (char*)malloc(sizeof(char) * size);
            AudioFileGetProperty(audio_file_, kAudioFilePropertyMagicCookieData, &size, cookie);
            AudioQueueSetProperty(queue_, kAudioQueueProperty_MagicCookie, cookie, size);
            free(cookie);
        }

        calculate_seek(start, end);
        volume(volume_);
        prime();
    }

    template<>
    music_obj<audio_queue_driver>::music_obj(const boost::shared_ptr<ifdstream>& ifd, bool loop, float gain,
                                             float start, float end)
    : packet_index_(0)
    , start_packet_index_(0)
    , stop_packet_index_(0)
    , volume_(gain)
    , loop_(loop)
    , is_paused_(false)
    , ifd_(ifd)
    {
        LOG("Got ifdstream from path..");

        OSStatus res = AudioFileOpenWithCallbacks(this, &music_obj::af_read_cb, &music_obj::af_write_cb,
                            &music_obj::af_get_size_cb, &music_obj::af_set_size_cb,
                                kAudioFileCAFType, &audio_file_);

        if(res)
        {
            throw sys_exception("audio_queue_driver: couldn't open audio file in liverpool fs. AudioFile returned "
                                    + boost::lexical_cast<std::string>(res));
        }

        UInt32 size = sizeof(data_format_);
        AudioFileGetProperty(audio_file_, kAudioFilePropertyDataFormat, &size, &data_format_);

        AudioQueueNewOutput(&data_format_, &music_obj<audio_queue_driver>::buffer_cb, this, NULL, NULL, 0, &queue_);
        AudioQueueAddPropertyListener(queue_, kAudioQueueProperty_IsRunning, &music_obj<audio_queue_driver>::playback_cb, this);

        if (data_format_.mBytesPerPacket == 0 || data_format_.mFramesPerPacket == 0)
        {
            size = sizeof(max_packet_size_);
            AudioFileGetProperty(audio_file_, kAudioFilePropertyPacketSizeUpperBound, &size, &max_packet_size_);
            if (max_packet_size_ > BUFFER_SIZE_BYTES)
            {
                max_packet_size_ = BUFFER_SIZE_BYTES;
            }

            num_packets_to_read_ = BUFFER_SIZE_BYTES / max_packet_size_;
            packet_descriptions_ = (AudioStreamPacketDescription*)malloc(sizeof(AudioStreamPacketDescription) * num_packets_to_read_);
        }
        else
        {
            num_packets_to_read_ = BUFFER_SIZE_BYTES / data_format_.mBytesPerPacket;
            packet_descriptions_ = NULL;
        }

        AudioFileGetPropertyInfo(audio_file_, kAudioFilePropertyMagicCookieData, &size, NULL);
        if (size > 0)
        {
            char* cookie = (char*)malloc(sizeof(char) * size);
            AudioFileGetProperty(audio_file_, kAudioFilePropertyMagicCookieData, &size, cookie);
            AudioQueueSetProperty(queue_, kAudioQueueProperty_MagicCookie, cookie, size);
            free(cookie);
        }

        calculate_seek(start, end);
        volume(volume_);
        prime();
    }

    template<>
    music_obj<audio_queue_driver>::~music_obj()
    {
        if (is_playing())
        {
            AudioQueueStop(queue_, true);
        }

        AudioQueueDispose(queue_, true);
		AudioFileClose(audio_file_);

        if(packet_descriptions_ != NULL)
        {
            free(packet_descriptions_);
        }
    }

    template<>
    void music_obj<audio_queue_driver>::buffer_callback(AudioQueueBufferRef buffer)
    {
        if (read_packets(buffer) == 0)
        {
            if(loop_)
            {
                packet_index_ = start_packet_index_;
                read_packets(buffer);
            }
        }
    }

    template<>
    void music_obj<audio_queue_driver>::playback_callback()
    {
        // if the callback is requested
        if(on_playback_)
        {
            if(! is_playing() )
            {
                // stopped
                on_playback_(false);
            }
            else
            {
                // started
                on_playback_(true);
            }
        }
    }

    template<>
    OSStatus music_obj<audio_queue_driver>::af_read_callback(SInt64 pos, UInt32	req_cnt, void *buffer, UInt32 *actual_cnt)
    {
        ifd_->seekg(pos, std::ios_base::beg);
        *actual_cnt = ifd_->read((char*)buffer, req_cnt);

        return noErr;
    }

    template<>
    OSStatus music_obj<audio_queue_driver>::af_write_callback(SInt64 pos, UInt32 req_cnt, const void *buffer, UInt32 *actual_cnt)
    {
        // Should not be called. we are only reading.
        return noErr;
    }

    template<>
    SInt64 music_obj<audio_queue_driver>::af_get_size_callback()
    {
        return ifd_->size();
    }

    template<>
    OSStatus music_obj<audio_queue_driver>::af_set_size_callback(SInt64 sz)
    {
        // Should not be called.
        return noErr;
    }

    template<>
    void music_obj<audio_queue_driver>::on_volume_change()
    {
        AudioQueueSetParameter(queue_, kAudioQueueParam_Volume,
            volume_ * sound_engine::instance().master_volume() * sound_engine::instance().music_volume());
    }

} // namespace snd
namespace snd_driver {

    audio_queue_driver::audio_queue_driver()
    : device_(NULL)
    , context_(NULL)
    {
        LOG("Sound engine initializing..");

        device_ = alcOpenDevice(NULL);

        if (device_)
        {
            context_ = alcCreateContext(device_, NULL);
            alcMakeContextCurrent(context_);

            LOG("Got OpenAL context.");
        }
        else
        {
            throw sys_exception("OpenAL: failed to create device.");
        }

        LOG("Sound engine started.");
    }

    audio_queue_driver::~audio_queue_driver()
    {
        LOG("Sound engine shutting down..");

        alcDestroyContext(context_);
        alcCloseDevice(device_);

        LOG("Sound engine stopped.");
    }

} // namespace snd_driver
} // namespace x2d


text:
// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers
// Copyright (c) 2018-2019, The Qwertycoin Project
// Copyright (c) 2014-2016, XDN developers
// Copyright (c) 2014-2017, The Monero Project
// Copyright (c) 2016-2018, The Karbo developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
//    conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
//    of conditions and the following disclaimer in the documentation and/or other
//    materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
//    used to endorse or promote products derived from this software without specific
//    prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <boost/algorithm/string.hpp>
#include <boost/thread/thread.hpp>

#include <Common/SignalHandler.h>
#include <Common/StringTools.h>

#include <CryptoNoteCore/Currency.h>

#include <Global/CliHeader.h>

#include <Logging/FileLogger.h>
#include <Logging/LoggerManager.h>

#include <NodeRpcProxy/NodeRpcProxy.h>

#include <SimpleWallet/Commands.h>
#include <SimpleWallet/Fusion.h>
#include <SimpleWallet/Open.h>
#include <SimpleWallet/ParseArguments.h>
#include <SimpleWallet/SimpleWallet.h>
#include <SimpleWallet/Sync.h>
#include <SimpleWallet/Tools.h>
#include <SimpleWallet/Transfer.h>

#include <Utilities/ColouredMsg.h>

#ifdef _WIN32
/* Prevents windows.h redefining min/max which breaks compilation */
#define NOMINMAX
#include <windows.h>
#endif

#include <version.h>

int main(int argc, char **argv)
{
#ifdef _WIN32
    SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
#endif

    Config config = parseArguments(argc, argv);

    std::cout << InformationMsg(CryptoNote::getProjectCLIHeader()) << std::endl;

    const auto logManager = std::make_shared<Logging::LoggerManager>();

    if (config.debug) {
        logManager->setMaxLevel(Logging::DEBUGGING);

        Logging::FileLogger fileLogger;

        fileLogger.init(WalletConfig::walletName + ".log");
        logManager->addLogger(fileLogger);
    }

    const CryptoNote::Currency currency = CryptoNote::CurrencyBuilder(logManager).currency();

    System::Dispatcher localDispatcher;
    System::Dispatcher *dispatcher = &localDispatcher;

    /*!
     * Connection to QDaemon
     */
    std::unique_ptr<CryptoNote::INode> node(
        new CryptoNote::NodeRpcProxy(config.host, config.port, 1, logManager)
    );

    std::promise<std::error_code> errorPromise;

    auto callback = [&errorPromise](std::error_code e)
    {
        errorPromise.set_value(e);
    };

    auto initNode = errorPromise.get_future();

    node->init(callback);

    if (initNode.wait_for(std::chrono::seconds(5)) != std::future_status::ready) {
        if (config.host != "127.0.0.1") {
            std::cout << WarningMsg(
                "Unable to connect to remote node, "
                "connection timed out."
            )
                      << std::endl
                      << WarningMsg(
                          "Confirm the remote node is functioning, "
                          "or try a different remote node."
                      )
                      << std::endl << std::endl;
        }
        else {
            std::cout << WarningMsg(
                "Unable to connect to node, "
                "connection timed out."
            )
                      << std::endl << std::endl;
        }
    }

    if (node->feeAmount() != 0 && !node->feeAddress().empty()) {
        std::stringstream feeMsg;

        feeMsg << std::endl << "You have connected to a node that charges " <<
               "a fee to send transactions." << std::endl << std::endl
               << "The fee for sending transactions is: " <<
               formatAmount(node->feeAmount()) <<
               " per transaction." << std::endl << std::endl <<
               "If you don't want to pay the node fee, please " <<
               "relaunch " << WalletConfig::walletName <<
               " and specify a different node or run your own." <<
               std::endl;

        std::cout << WarningMsg(feeMsg.str()) << std::endl;
    }

    CryptoNote::WalletGreen wallet(*dispatcher, currency, *node, logManager);

    run(wallet, *node, config);
}

void run(CryptoNote::WalletGreen &wallet,
         CryptoNote::INode &node,
         Config &config)
{
    auto maybeWalletInfo = Nothing<std::shared_ptr<WalletInfo>>();
    Action action;

    do {
        std::cout
            << InformationMsg(
                WalletConfig::coinName + " v"
                    + std::string(PROJECT_VERSION)
                    + " " + WalletConfig::walletName
            )
            << std::endl;

        /*!
         * Open/import/generate the wallet
         */
        action = getAction(config);
        maybeWalletInfo = handleAction(wallet, action, config);

        /*!
         * Didn't manage to get the wallet info, returning to selection screen
         */
    }
    while (!maybeWalletInfo.isJust);

    auto walletInfo = maybeWalletInfo.x;

    bool alreadyShuttingDown = false;

    /*!
     * This will call shutdown when ctrl+c is hit. This is a lambda function,
     * & means capture all variables by reference
     */
    Tools::SignalHandler::install(
        [&]
        {
            /*!
             * If we're already shutting down let control flow continue as normal
             */
            if (shutdown(walletInfo->wallet, node, alreadyShuttingDown)) {
                exit(0);
            }
        }
    );

    while (node.getLastKnownBlockHeight() == 0) {
        std::cout
            << WarningMsg("It looks like QDaemon isn't open!")
            << std::endl
            << std::endl
            << WarningMsg(
                "Ensure QDaemon is open and has finished "
                "initializing."
            )
            << std::endl
            << WarningMsg(
                "If it's still not working, try restarting "
                "QDaemon. The daemon sometimes gets stuck."
            )
            << std::endl
            << WarningMsg(
                "Alternatively, perhaps QDaemon can't "
                "communicate with any peers."
            )
            << std::endl
            << std::endl
            << WarningMsg(
                "The wallet can't function until it can "
                "communicate with the network."
            )
            << std::endl
            << std::endl;

        bool proceed = false;

        while (true) {
            std::cout
                << "["
                << InformationMsg("T")
                << "]ry again, "
                << "["
                << InformationMsg("E")
                << "]xit, or "
                << "["
                << InformationMsg("C")
                << "]ontinue anyway?: ";

            std::string answer;
            std::getline(std::cin, answer);

            char c = std::tolower(answer[0]);

            /*!
             * Lets people spam enter in the transaction screen
             */
            if (c == 't' || c == '\0') {
                break;
            }
            else if (c == 'e' || c == std::ifstream::traits_type::eof()) {
                shutdown(walletInfo->wallet, node, alreadyShuttingDown);
                return;
            }
            else if (c == 'c') {
                proceed = true;
                break;
            }
            else {
                std::cout
                    << WarningMsg("Bad input: ")
                    << InformationMsg(answer)
                    << WarningMsg(" - please enter either T, E, or C.")
                    << std::endl;
            }
        }

        if (proceed) {
            break;
        }

        std::cout
            << std::endl;
    }

    /*!
     * Scan the chain for new transactions. In the case of an imported
     * wallet, we need to scan the whole chain to find any transactions.
     * If we opened the wallet however, we just need to scan from when we
     * last had it open. If we are generating a wallet, there is no need
     * to check for transactions as there is no way the wallet can have
     * received any money yet.
     */
    if (action != Generate) {
        syncWallet(node, walletInfo);
    }
    else {
        std::cout
            << InformationMsg(
                "Your wallet is syncing with the "
                "network in the background."
            )
            << std::endl
            << InformationMsg(
                "Until this is completed new "
                "transactions might not show up."
            )
            << std::endl
            << InformationMsg("Use bc_height to check the progress.")
            << std::endl
            << std::endl;
    }

    welcomeMsg();

    inputLoop(walletInfo, node);

    shutdown(walletInfo->wallet, node, alreadyShuttingDown);
}

Maybe<std::shared_ptr<WalletInfo>> handleAction(CryptoNote::WalletGreen &wallet,
                                                Action action, Config &config)
{
    if (action == Generate) {
        return Just<std::shared_ptr<WalletInfo>>(generateWallet(wallet));
    }
    else if (action == Open) {
        return openWallet(wallet, config);
    }
    else if (action == Import) {
        return Just<std::shared_ptr<WalletInfo>>(importWallet(wallet));
    }
    else if (action == SeedImport) {
        return Just<std::shared_ptr<WalletInfo>>(mnemonicImportWallet(wallet));
    }
    else if (action == ViewWallet) {
        return Just<std::shared_ptr<WalletInfo>>(createViewWallet(wallet));
    }
    else {
        throw std::runtime_error("Unimplemented action!");
    }
}

Action getAction(Config &config)
{
    if (config.walletGiven || config.passGiven) {
        return Open;
    }

    while (true) {
        std::cout
            << std::endl
            << "Welcome, please choose an option below:"
            << std::endl
            << std::endl

            << "\t["
            << InformationMsg("G")
            << "] - "
            << "Generate a new wallet address"
            << std::endl

            << "\t["
            << InformationMsg("O")
            << "] - "
            << "Open a wallet already on your system"
            << std::endl

            << "\t["
            << InformationMsg("S")
            << "] - "
            << "Regenerate your wallet using a seed phrase of words"
            << std::endl

            << "\t["
            << InformationMsg("I")
            << "] - "
            << "Import your wallet using a View Key and Spend Key"
            << std::endl

            << "\t["
            << InformationMsg("V")
            << "] - "
            << "Import a view only wallet (Unable to send transactions)"
            << std::endl
            << std::endl

            << "or, press CTRL_C to exit: ";

        std::string answer;
        std::getline(std::cin, answer);

        char c = answer[0];
        c = std::tolower(c);

        if (c == 'o') {
            return Open;
        }
        else if (c == 'g') {
            return Generate;
        }
        else if (c == 'i') {
            return Import;
        }
        else if (c == 's') {
            return SeedImport;
        }
        else if (c == 'v') {
            return ViewWallet;
        }
        else {
            std::cout
                << "Unknown command: "
                << WarningMsg(answer)
                << std::endl;
        }
    }
}

void welcomeMsg()
{
    std::cout
        << "Use the "
        << SuggestionMsg("help")
        << " command to see the list of available commands."
        << std::endl
        << "Use "
        << SuggestionMsg("exit")
        << " when closing to ensure your wallet file doesn't get "
        << "corrupted."
        << std::endl
        << std::endl;
}

std::string getInputAndDoWorkWhileIdle(std::shared_ptr<WalletInfo> &walletInfo)
{
    auto lastUpdated = std::chrono::system_clock::now();

    std::future<std::string> inputGetter = std::async(
        std::launch::async, []
        {
            std::string command;
            std::getline(std::cin, command);
            boost::algorithm::trim(command);
            return command;
        }
    );

    while (true) {
        /*!
         * Check if the user has inputted something yet (Wait for zero seconds
         * to instantly return)
         */
        std::future_status status = inputGetter.wait_for(std::chrono::seconds(0));

        /*!
         * User has inputted, get what they inputted and return it
         */
        if (status == std::future_status::ready) {
            return inputGetter.get();
        }

        auto currentTime = std::chrono::system_clock::now();

        /*!
         * Otherwise check if we need to update the wallet cache
         */
        if ((currentTime - lastUpdated) > std::chrono::seconds(5)) {
            lastUpdated = currentTime;
            checkForNewTransactions(walletInfo);
        }

        /*!
         * Sleep for enough for it to not be noticeable when the user enters
         * something, but enough that we're not starving the CPU
         */
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }
}

bool shutdown(CryptoNote::WalletGreen &wallet, CryptoNote::INode &node,
              bool &alreadyShuttingDown)
{
    if (alreadyShuttingDown) {
        std::cout
            << "I do appreciate your patience so far, we're already shutting down!"
            << std::endl;
        return false;
    }
    else {
        alreadyShuttingDown = true;
        std::cout
            << InformationMsg(
                "Saving wallet and shutting down, please "
                "wait..."
            )
            << std::endl;
    }

    bool finishedShutdown = false;

    boost::thread timelyShutdown(
        [&finishedShutdown]
        {
            auto startTime = std::chrono::system_clock::now();

            /*!
             * Has shutdown finished?
             */
            while (!finishedShutdown) {
                auto currentTime = std::chrono::system_clock::now();

                /*!
                 * If not, wait for a max of 20 seconds then force exit.
                 */
                if ((currentTime - startTime) > std::chrono::seconds(20)) {
                    std::cout
                        << WarningMsg(
                            "Wallet took too long to save! "
                            "Force closing."
                        )
                        << std::endl
                        << "Bye."
                        << std::endl;
                    exit(0);
                }

                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
        }
    );

    wallet.save();
    wallet.shutdown();
    node.shutdown();

    finishedShutdown = true;

    /*!
     * Wait for shutdown watcher to finish
     */
    timelyShutdown.join();

    std::cout
        << "Bye."
        << std::endl;

    return true;
}

void inputLoop(std::shared_ptr<WalletInfo> &walletInfo, CryptoNote::INode &node)
{
    while (true) {
        std::cout
            << getPrompt(walletInfo);

        std::string command = getInputAndDoWorkWhileIdle(walletInfo);

        if (command == "") {
            // no-op
        }
        else if (command == "export_keys") {
            exportKeys(walletInfo);
        }
        else if (command == "help") {
            help(walletInfo->viewWallet);
        }
        else if (command == "status") {
            status(node);
        }
        else if (command == "balance") {
            balance(node, walletInfo->wallet, walletInfo->viewWallet);
        }
        else if (command == "address") {
            std::cout
                << SuccessMsg(walletInfo->walletAddress)
                << std::endl;
        }
        else if (command == "incoming_transfers") {
            listTransfers(true, false, walletInfo->wallet, node);
        }
        else if (command == "save_csv") {
            saveCSV(walletInfo->wallet, node);
        }
        else if (command == "exit") {
            return;
        }
        else if (command == "save") {
            std::cout
                << InformationMsg("Saving.")
                << std::endl;
            walletInfo->wallet.save();
            std::cout
                << InformationMsg("Saved.")
                << std::endl;
        }
        else if (command == "bc_height") {
            blockchainHeight(node, walletInfo->wallet);
        }
        else if (command == "reset") {
            reset(node, walletInfo);
        }
        else if (!walletInfo->viewWallet) {
            if (command == "outgoing_transfers") {
                listTransfers(false, true, walletInfo->wallet, node);
            }
            else if (command == "list_transfers") {
                listTransfers(true, true, walletInfo->wallet, node);
            }
            else if (command == "list_messages") {
                listMessages(walletInfo->wallet, node);
            }
            else if (command == "transfer") {
                transfer(walletInfo, node.getLastKnownBlockHeight());
            }
                /*!
                 * String starts with transfer, old transfer syntax
                 */
            else if (command.find("transfer") == 0) {
                std::cout
                    << "This transfer syntax has been removed."
                    << std::endl
                    << "Run just the "
                    << SuggestionMsg("transfer")
                    << " command for a walk through guide to "
                    << "transferring."
                    << std::endl;
            }
            else if (command == "quick_optimize") {
                quickOptimize(walletInfo->wallet);
            }
            else if (command == "full_optimize" || command == "optimize") {
                fullOptimize(walletInfo->wallet);
            }
            else {
                std::cout
                    << "Unknown command: "
                    << WarningMsg(command)
                    << ", use "
                    << SuggestionMsg("help")
                    << " command to list all possible commands."
                    << std::endl;
            }
        }
        else {
            std::cout
                << "Unknown command: "
                << WarningMsg(command)
                << ", use "
                << SuggestionMsg("help")
                << " command to list all possible commands."
                << std::endl
                << "Please note some commands such as transfer are "
                << "unavailable, as you are using a view only wallet."
                << std::endl;
        }
    }
}

max_stars_repo_name: exploshot/qwc-test

max_issues_repo_name: exploshot/qwc-test

max_forks_repo_name: exploshot/qwc-test


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2012 Alexey Korepanov <kaikaikai@yandex.ru>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#define EIGEN_RUNTIME_NO_MALLOC
#include "main.h"
#include <limits>
#include <Eigen/Eigenvalues>

template<typename MatrixType> void real_qz(const MatrixType& m)
{
  /* this test covers the following files:
     RealQZ.h
  */
  using std::abs;
  typedef typename MatrixType::Index Index;
  typedef typename MatrixType::Scalar Scalar;

  Index dim = m.cols();

  MatrixType A = MatrixType::Random(dim,dim),
             B = MatrixType::Random(dim,dim);

  // Regression test for bug 985: Randomly set rows or columns to zero
  Index k=internal::random<Index>(0, dim-1);
  switch(internal::random<int>(0,10)) {
  case 0:
    A.row(k).setZero(); break;
  case 1:
    A.col(k).setZero(); break;
  case 2:
    B.row(k).setZero(); break;
  case 3:
    B.col(k).setZero(); break;
  default:
    break;
  }

  RealQZ<MatrixType> qz(dim);
  // TODO enable full-prealocation of required memory, this probably requires an in-place mode for HessenbergDecomposition
  //Eigen::internal::set_is_malloc_allowed(false);
  qz.compute(A,B);
  //Eigen::internal::set_is_malloc_allowed(true);

  VERIFY_IS_EQUAL(qz.info(), Success);
  // check for zeros
  bool all_zeros = true;
  for (Index i=0; i<A.cols(); i++)
    for (Index j=0; j<i; j++) {
      if (abs(qz.matrixT()(i,j))!=Scalar(0.0))
      {
        std::cerr << "Error: T(" << i << "," << j << ") = " << qz.matrixT()(i,j) << std::endl;
        all_zeros = false;
      }
      if (j<i-1 && abs(qz.matrixS()(i,j))!=Scalar(0.0))
      {
        std::cerr << "Error: S(" << i << "," << j << ") = " << qz.matrixS()(i,j) << std::endl;
        all_zeros = false;
      }
      if (j==i-1 && j>0 && abs(qz.matrixS()(i,j))!=Scalar(0.0) && abs(qz.matrixS()(i-1,j-1))!=Scalar(0.0))
      {
        std::cerr << "Error: S(" << i << "," << j << ") = " << qz.matrixS()(i,j)  << " && S(" << i-1 << "," << j-1 << ") = " << qz.matrixS()(i-1,j-1) << std::endl;
        all_zeros = false;
      }
    }
  VERIFY_IS_EQUAL(all_zeros, true);
  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixS()*qz.matrixZ(), A);
  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixT()*qz.matrixZ(), B);
  VERIFY_IS_APPROX(qz.matrixQ()*qz.matrixQ().adjoint(), MatrixType::Identity(dim,dim));
  VERIFY_IS_APPROX(qz.matrixZ()*qz.matrixZ().adjoint(), MatrixType::Identity(dim,dim));
}

void test_real_qz()
{
  int s = 0;
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1( real_qz(Matrix4f()) );
    s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE/4);
    CALL_SUBTEST_2( real_qz(MatrixXd(s,s)) );

    // some trivial but implementation-wise tricky cases
    CALL_SUBTEST_2( real_qz(MatrixXd(1,1)) );
    CALL_SUBTEST_2( real_qz(MatrixXd(2,2)) );
    CALL_SUBTEST_3( real_qz(Matrix<double,1,1>()) );
    CALL_SUBTEST_4( real_qz(Matrix2d()) );
  }

  TEST_SET_BUT_UNUSED_VARIABLE(s)
}


text:
/*
@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#include <boost/hana/detail/sandbox/hash_map.hpp>

#include <boost/hana/detail/assert.hpp>
#include <boost/hana/detail/constexpr.hpp>
#include <boost/hana/functional.hpp>
#include <boost/hana/integral.hpp>
#include <boost/hana/list/instance.hpp>
#include <boost/hana/pair.hpp>
using namespace boost::hana;

BOOST_HANA_CONSTEXPR_LAMBDA auto check_fold = [](auto ...pairs) {
    auto values = fmap(second, list(pairs...));
    auto result = foldr(hash_map(pairs...), list(), cons);
    BOOST_HANA_CONSTANT_ASSERT(elem(permutations(values), result));
};

template <int k, int v>
BOOST_HANA_CONSTEXPR_LAMBDA auto p = pair(int_<k>, int_<v>);

int main() {
    check_fold();
    check_fold(p<1, 1>);
    check_fold(p<1, 1>, p<2, 2>);
    check_fold(p<1, 1>, p<2, 2>, p<3, 3>);
    check_fold(p<1, 1>, p<2, 2>, p<3, 3>, p<4, 4>);
}

max_stars_repo_name: rbock/hana

max_issues_repo_name: rbock/hana

max_forks_repo_name: rbock/hana


text: #include <boost/compute/algorithm/lower_bound.hpp>