text:
#include <simplechain/chain_rpc.h>
#include <simplechain/contract_helper.h>
#include <simplechain/operations.h>
#include <simplechain/transaction.h>
#include <simplechain/block.h>
#include <simplechain/blockchain.h>
#include <simplechain/contract.h>
#include <uvm/uvm_lib.h>
#include <streambuf>
#include <istream>
#include <ostream>
#include <boost/asio.hpp>
#include <fc/io/json.hpp>
#include <cbor_diff/cbor_diff.h>
#include <fc/crypto/hex.hpp>
#include <fc/crypto/sha256.hpp>
#include <fc/crypto/base58.hpp>
#include <fc/crypto/elliptic.hpp>
#include <fc/crypto/ripemd160.hpp>

#include <uvm/lauxlib.h>

namespace simplechain {
	namespace rpc {

		static void params_assert(bool cond, const std::string& msg = "") {
			if (!cond) {
				throw uvm::core::UvmException(msg.empty() ? "params invalid" : msg);
			}
		}

		RpcResultType get_account(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			const auto& addr = params.at(0).as_string();
			const auto& pubkey_hex = chain->get_address_pubkey_hex(addr);
			fc::mutable_variant_object result;
			result["address"] = addr;
			result["pubkey"] = pubkey_hex;
			return result;
		}

		RpcResultType register_account(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			const auto& addr = params.at(0).as_string();
			const auto& pubkey_hex = params.at(1).as_string();
			auto tx = std::make_shared<transaction>();
			auto op = operations_helper::register_account(addr, pubkey_hex);
			tx->tx_time = fc::time_point_sec(fc::time_point::now());
			tx->operations.push_back(op);
			chain->evaluate_transaction(tx);
			chain->accept_transaction_to_mempool(*tx);
			return tx->tx_hash();
		}

		RpcResultType mint(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			const auto& caller_addr = params.at(0).as_string();
			auto asset_id = (asset_id_t) params.at(1).as_uint64();
			auto amount = params.at(2).as_int64();
			auto tx = std::make_shared<transaction>();
			auto op = operations_helper::mint(caller_addr, asset_id, amount);
			tx->tx_time = fc::time_point_sec(fc::time_point::now());
			tx->operations.push_back(op);

			chain->evaluate_transaction(tx);
			chain->accept_transaction_to_mempool(*tx);

			return tx->tx_hash();
		}

		RpcResultType add_asset(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			asset a;
			a.symbol = params.at(0).as_string();
			a.precision = (asset_id_t)params.at(1).as_uint64();
			fc::mutable_variant_object res;

			if (chain->get_asset_by_symbol(a.symbol) != nullptr) {
				res["result"] = false;
				return res;
			}
			chain->add_asset(a);
			res["result"] = true;
			return res;
		}

		RpcResultType transfer(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			const auto& from_addr = params.at(0).as_string();
			const auto& to_addr = params.at(1).as_string();
			auto asset_id = (asset_id_t)params.at(2).as_uint64();
			auto amount = (share_type)params.at(3).as_int64();
			auto tx = std::make_shared<transaction>();
			auto op = operations_helper::transfer(from_addr, to_addr, asset_id, amount);
			tx->tx_time = fc::time_point_sec(fc::time_point::now());
			tx->operations.push_back(op);

			chain->evaluate_transaction(tx);
			chain->accept_transaction_to_mempool(*tx);

			return tx->tx_hash();
		}

		RpcResultType create_contract_from_file(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			auto caller_addr = params.at(0).as_string();
			auto contract_filepath = params.at(1).as_string();
			auto gas_limit = params.at(2).as_uint64();
			auto gas_price = params.at(3).as_uint64();
			auto tx = std::make_shared<transaction>();
			auto op = operations_helper::create_contract_from_file(caller_addr, contract_filepath, gas_limit, gas_price);
			tx->operations.push_back(op);
			tx->tx_time = fc::time_point_sec(fc::time_point::now());
			const auto& contract_addr = op.calculate_contract_id();

			chain->evaluate_transaction(tx);
			chain->accept_transaction_to_mempool(*tx);

			fc::mutable_variant_object res;
			res["contract_address"] = contract_addr;
			res["txid"] = tx->tx_hash();
			return res;
		}

		RpcResultType create_native_contract(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			auto caller_addr = params.at(0).as_string();
			auto contract_type = params.at(1).as_string();
			auto gas_limit = params.at(2).as_uint64();
			auto gas_price = params.at(3).as_uint64();
			UNUSED(gas_limit);
			UNUSED(gas_price);
			auto tx = std::make_shared<transaction>();
			auto op = operations_helper::create_native_contract(caller_addr, contract_type);
			tx->operations.push_back(op);
			tx->tx_time = fc::time_point_sec(fc::time_point::now());
			const auto& contract_addr = op.calculate_contract_id();

			chain->evaluate_transaction(tx);
			chain->accept_transaction_to_mempool(*tx);

			fc::mutable_variant_object res;
			res["contract_address"] = contract_addr;
			res["txid"] = tx->tx_hash();
			return res;
		}
		RpcResultType create_contract(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			auto caller_addr = params.at(0).as_string();
			auto contract_base64 = params.at(1).as_string();
			auto gas_limit = params.at(2).as_uint64();
			auto gas_price = params.at(3).as_uint64();

			auto tx = std::make_shared<transaction>();

			const auto& contract_str = fc::base64_decode(contract_base64);
			std::vector<char> contract_buf(contract_str.size());
			memcpy(contract_buf.data(), contract_str.data(), contract_str.size());

			boost::asio::streambuf contract_stream;
			std::ostream os(&contract_stream);
			os.write(contract_buf.data(), contract_buf.size());
			std::istream contract_istream(&contract_stream);
			StreamFileWrapper sfw(&contract_istream);
			const auto& code = ContractHelper::load_contract_from_common_stream_and_close(&sfw, (int) contract_buf.size());

			auto op = operations_helper::create_contract(caller_addr, code, gas_limit, gas_price);
			tx->operations.push_back(op);
			tx->tx_time = fc::time_point_sec(fc::time_point::now());
			const auto& contract_addr = op.calculate_contract_id();

			chain->evaluate_transaction(tx);
			chain->accept_transaction_to_mempool(*tx);

			fc::mutable_variant_object res;
			res["contract_address"] = contract_addr;
			res["txid"] = tx->tx_hash();
			return res;
		}

		RpcResultType invoke_contract(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			auto caller_addr = params.at(0).as_string();
			auto contract_address = params.at(1).as_string();
			auto api_name = params.at(2).as_string();
			params_assert(params.at(3).is_array());
			auto api_args_json = params.at(3).as<fc::variants>();

			//cbor::CborArrayValue api_args;
			//convertArgs2Cbor(api_args_json, api_args);

			std::vector<std::string> api_args;
			for (const auto& api_arg_json : api_args_json) {
				params_assert(api_arg_json.is_string(), "api arguments must be string");
				api_args.push_back(api_arg_json.as_string());
			}
			auto deposit_asset_id = params.at(4).as_uint64();
			auto deposit_amount = params.at(5).as_uint64();
			auto gas_limit = params.at(6).as_uint64();
			auto gas_price = params.at(7).as_uint64();

			auto tx = std::make_shared<transaction>();
			auto op = operations_helper::invoke_contract(caller_addr, contract_address, api_name, api_args_json, gas_limit, gas_price);
			op.deposit_amount = deposit_amount;
			op.deposit_asset_id = (asset_id_t)deposit_asset_id;
			tx->operations.push_back(op);
			tx->tx_time = fc::time_point_sec(fc::time_point::now());

			auto op_result = chain->evaluate_transaction(tx);
			fc::mutable_variant_object res;
			res["txid"] = tx->tx_hash();
			if (op_result) {
				contract_invoke_result* contract_result = (contract_invoke_result*)op_result.get();
				res["api_result"] = contract_result->api_result;
				res["exec_succeed"] = contract_result->exec_succeed;
				res["gas_used"] = contract_result->gas_used;
				if (!contract_result->exec_succeed)
					res["error"] = contract_result->error;
			}
			chain->accept_transaction_to_mempool(*tx);
			return res;
		}

		RpcResultType invoke_contract_offline(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			auto caller_addr = params.at(0).as_string();
			auto contract_address = params.at(1).as_string();
			auto api_name = params.at(2).as_string();
			params_assert(params.at(3).is_array());
			auto api_args_json = params.at(3).as<fc::variants>();
			auto deposit_asset_id = (asset_id_t)params.at(4).as_uint64();
			auto deposit_amount = params.at(5).as_uint64();

			//cbor::CborArrayValue api_args;
			//convertArgs2Cbor(api_args_json, api_args);

			auto tx = std::make_shared<transaction>();
			auto op = operations_helper::invoke_contract(caller_addr, contract_address, api_name, api_args_json, 10000000);
			op.deposit_amount = deposit_amount;
			op.deposit_asset_id = (asset_id_t)deposit_asset_id;
			tx->operations.push_back(op);
			tx->tx_time = fc::time_point_sec(fc::time_point::now());

			auto op_result = chain->evaluate_transaction(tx);
			fc::mutable_variant_object res;
			res["txid"] = tx->tx_hash();
			if (op_result) {
				contract_invoke_result* contract_result = (contract_invoke_result*)op_result.get();
				res["api_result"] = contract_result->api_result;
				res["exec_succeed"] = contract_result->exec_succeed;
			}
			return res;
		}

		RpcResultType generate_block(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			int count = 1;
			if (!params.empty()) {
				count = (int)params.at(0).as_int64();
				if (count <= 0) {
					throw uvm::core::UvmException("need generate at least 1 block");
				}
			}
			fc::variants block_ids;
			for (int i = 0; i < count; i++) {
				chain->generate_block();
				block_ids.push_back(chain->head_block_hash());
			}
			return block_ids;
		}

		RpcResultType get_block_by_height(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			const auto& block_height = params.at(0).as_uint64();
			auto block = chain->get_block_by_number(block_height);
			if (block) {
				return block->to_json();
			}
			else {
				return nullptr;
			}
		}

		RpcResultType get_tx(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			const auto& tx_id = params.at(0).as_string();
			auto tx = chain->get_trx_by_hash(tx_id);
			if (tx) {
				return tx->to_json();
			}
			else {
				return nullptr;
			}
		}

		RpcResultType get_tx_receipt(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			const auto& tx_id = params.at(0).as_string();
			const auto& receipt = chain->get_tx_receipt(tx_id);
			if (receipt) {
				return receipt->to_json();
			}
			else {
				return nullptr;
			}
		}

		RpcResultType exit_chain(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			server->stop();
			return true;
		}

		RpcResultType get_chain_state(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			const auto& state = chain->get_state();
			return state;
		}

		RpcResultType list_accounts(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			const auto& accounts = chain->get_account_addresses();
			fc::variant account_addresses;
			fc::to_variant(accounts, account_addresses);
			return account_addresses;
		}
		RpcResultType list_assets(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			const auto& assets = chain->get_assets();
			fc::variant assets_obj;
			fc::to_variant(assets, assets_obj);
			return assets_obj;
		}
		RpcResultType list_contracts(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			const auto& contracts = chain->get_contracts();
			fc::variants contract_ids;
			for (const auto& contract : contracts) {
				contract_ids.push_back(contract.contract_address);
			}
			return contract_ids;
		}
		RpcResultType get_contract_info(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			const auto& contract_address = params.at(0).as_string();
			auto contract = chain->get_contract_by_address(contract_address);
			if (!contract) {
				throw uvm::core::UvmException(std::string("Can't find contract ") + contract_address);
			}
			fc::variant obj;
			fc::to_variant(*contract, obj);
			return obj;
		}
		RpcResultType get_account_balances(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			const auto& addr = params.at(0).as_string();
			const auto& balances = chain->get_account_balances(addr);
			fc::variant res;
			fc::to_variant(balances, res);
			return res;
		}
		RpcResultType get_contract_storages(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			const auto& addr = params.at(0).as_string();
			const auto& storages = chain->get_contract_storages(addr);
			fc::mutable_variant_object storages_json;

			//auto scope = std::make_shared < uvm::lua::lib::UvmStateScope>();
			for (const auto& p : storages) {
				auto storage_value = cbor_diff::cbor_decode(p.second.storage_data);
				//const auto& uvm_storage_data = cbor_to_uvm_storage_value(scope->L(), storage_value.get());
				//const auto& storage_json = simplechain::uvm_storage_value_to_json(uvm_storage_data);
				//auto res = storage_json;
				//return res;

				//const auto& s = p.second.as<StorageStringType>();
				//auto a = cbor::CborObject::from_bytes(p.second.storage_data);
				storages_json[p.first] = storage_value->to_json();
			}
			return storages_json;
		}
		RpcResultType get_storage(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			const auto& addr = params.at(0).as_string();
			const auto& storage_name = params.at(1).as_string();
			const auto& storage = chain->get_storage(addr, storage_name);
			auto storage_value = cbor_diff::cbor_decode(storage.storage_data);
			auto scope = std::make_shared < uvm::lua::lib::UvmStateScope>();
			auto uvm_storage_data = cbor_to_uvm_storage_value(scope->L(), storage_value.get());
			auto storage_json = simplechain::uvm_storage_value_to_json(uvm_storage_data);
			auto res = storage_json;
			return res;
		}

		//---------------add debug rpc ----------------------------------------------------------
		RpcResultType set_breakpoint(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			//fc::variant res;
			fc::mutable_variant_object res;

			auto contract_address = params.at(0).as_string();
			auto line = params.at(1).as_uint64();
			chain->add_breakpoint_in_last_debugger_state(contract_address, (uint32_t) line);

			res["result"] = true;

			return res;
		}

		RpcResultType get_breakpoints_in_last_debugger_state(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			//fc::variant res;
			fc::mutable_variant_object res;
			auto breaks = chain->get_breakpoints_in_last_debugger_state();
			std::map<std::string, std::list<uint32_t>>::iterator iter;

			for (iter = breaks.begin(); iter != breaks.end(); iter++)
			{
				fc::variant temp;
				auto li = iter->second;
				std::vector<uint32_t> vc;
				std::copy(li.begin(), li.end(), std::back_inserter(vc));
				fc::to_variant(vc, temp);
				res[iter->first] = temp;
			}

			return res;
		}

		RpcResultType remove_breakpoint_in_last_debugger_state(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			//fc::variant res;
			fc::mutable_variant_object res;
			auto contract_address = params.at(0).as_string();
			auto line = params.at(1).as_uint64();
			chain->remove_breakpoint_in_last_debugger_state(contract_address, line);
			res["result"] = true;
			return res;
		}

		RpcResultType clear_breakpoints_in_last_debugger_state(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			//fc::variant res;
			fc::mutable_variant_object res;
			chain->clear_breakpoints_in_last_debugger_state();
			res["result"] = true;
			return res;
		}

		RpcResultType debugger_invoke_contract(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			auto caller_addr = params.at(0).as_string();
			auto contract_address = params.at(1).as_string();
			auto api_name = params.at(2).as_string();
			params_assert(params.at(3).is_array());
			auto api_args_json = params.at(3).as<fc::variants>();

			//cbor::CborArrayValue api_args;
			//convertArgs2Cbor(api_args_json, api_args);

			auto deposit_asset_id = params.at(4).as_uint64();
			auto deposit_amount = params.at(5).as_uint64();
			auto gas_limit = params.at(6).as_uint64();
			auto gas_price = params.at(7).as_uint64();

			chain->clear_debugger_state();

			auto tx = std::make_shared<transaction>();
			auto op = operations_helper::invoke_contract(caller_addr, contract_address, api_name, api_args_json, gas_limit, gas_price);
			op.deposit_amount = deposit_amount;
			op.deposit_asset_id = deposit_asset_id;
			tx->operations.push_back(op);
			tx->tx_time = fc::time_point_sec(fc::time_point::now());

			auto op_result = chain->evaluate_transaction(tx);
			fc::mutable_variant_object res;
			res["txid"] = tx->tx_hash();
			if (op_result) {
				contract_invoke_result* contract_result = (contract_invoke_result*)op_result.get();
				res["api_result"] = contract_result->api_result;
				res["exec_succeed"] = contract_result->exec_succeed;
			}
			//chain->accept_transaction_to_mempool(*tx);
			return res;
		}

		RpcResultType view_localvars_in_last_debugger_state(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			const auto& localvars = chain->view_localvars_in_last_debugger_state();
			fc::variant locs;
			fc::to_variant(localvars, locs);
			return locs;
		}

		RpcResultType view_upvalues_in_last_debugger_state(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			const auto& upvalues = chain->view_upvalues_in_last_debugger_state();
			fc::variant res;

			fc::to_variant(upvalues, res);
			return res;
		}

		RpcResultType view_debug_info(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			fc::mutable_variant_object res;
			auto line = chain->view_current_line_number_in_last_debugger_state();
			res["line"] = line;
			const auto stack = chain->view_current_contract_stack_item_in_last_debugger_state();
			res["contractid"] = stack.first;
			res["apiname"] = stack.second;
			return res;
		}

		RpcResultType debugger_step_out(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			fc::mutable_variant_object res;
			chain->debugger_step_out();
			res["result"] = true;
			return res;
		}

		RpcResultType debugger_step_over(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			fc::mutable_variant_object res;
			chain->debugger_step_over();
			res["result"] = true;
			return res;
		}

		RpcResultType debugger_step_into(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			fc::mutable_variant_object res;
			chain->debugger_step_into();
			res["result"] = true;
			return res;
		}

		RpcResultType debugger_go_resume(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			fc::mutable_variant_object res;
			chain->debugger_go_resume();
			res["result"] = true;
			return res;
		}

		//input params: storage_name,fast_map_key,is_fast_map
		RpcResultType view_current_contract_storage_value(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			fc::variant res;
			auto storage_name = params.at(0).as_string();
			auto fast_map_key = params.at(1).as_string();
			auto is_fast_map = params.at(2).as_bool();
			std::map<std::string, TValue> result;
			auto value = chain->view_contract_storage_value(storage_name.c_str(), fast_map_key.c_str(), is_fast_map);
			std::string storagekey = storage_name;
			if (is_fast_map) {
				storagekey = storagekey.append("[").append(fast_map_key).append("]");
			}
			result[storagekey] = value;
			fc::to_variant(result, res);
			return res;
		}

		RpcResultType view_current_contract_storage_value_batch(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			fc::variant res;
			std::map<std::string, TValue> result;
			const auto& batch = params.at(0).as<fc::variants>();
			for (const auto& item : batch) {
				const auto& item_param = item.as<fc::variants>();
				auto storage_name = item_param.at(0).as_string();
				auto fast_map_key = item_param.at(1).as_string();
				auto is_fast_map = item_param.at(2).as_bool();
				auto value = chain->view_contract_storage_value(storage_name.c_str(), fast_map_key.c_str(), is_fast_map);
				std::string storagekey = storage_name;
				if (is_fast_map) {
					storagekey = storagekey.append("[").append(fast_map_key).append("]");
				}
				result[storagekey] = value;
			}
			fc::to_variant(result, res);
			return res;
		}

		RpcResultType view_call_stack(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			fc::variant res;
			auto result = chain->view_call_stack();
			fc::to_variant(result, res);
			return res;
		}

		using uvm::lua::api::global_uvm_chain_api;
		RpcResultType generate_key(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			fc::mutable_variant_object res;
			try {
				auto prik = fc::ecc::private_key::generate();
				auto pubk = prik.get_public_key();
				auto pubk_base58 = pubk.to_base58();

				auto address_str = global_uvm_chain_api->pubkey_to_address_string(pubk);

				auto private_key_str = prik.get_secret().str();
				auto ss = pubk.serialize();
				auto hex_pubkey = fc::to_hex(ss.data, ss.size());

				res["prik"] = private_key_str;
				res["public_key_base58"] = pubk_base58;
				res["hex_pubkey"] = hex_pubkey;
				res["addr"] = address_str;

			}
			catch (fc::exception e) {
				res["exec_succeed"] = false;
				res["error"] = e.to_string();
				return res;
			}
			return res;
		}

		RpcResultType sign_info(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			fc::mutable_variant_object res;
			try{
				const auto& private_key_str = params.at(0).as_string();
				const auto& infostr = params.at(1).as_string();
				/*std::string infostr;
				if (fc::json::is_valid(info)) {
					auto v = fc::json::from_string(info); //map items order
					infostr = fc::json::to_string(v);
				}
				else {
					infostr = info;
				}*/

				auto private_key = fc::ecc::private_key::regenerate(fc::sha256(private_key_str));

				auto orderinfoDigest = fc::sha256::hash(infostr);
				auto sig = private_key.sign_compact(orderinfoDigest);

				std::vector<char> chars(sig.size());
				memcpy(chars.data(), sig.data, sig.size());
				auto sig_hex = fc::to_hex(chars);

				auto temp = infostr + sig_hex;
				auto orderID = fc::sha256::hash(temp);
				//fc::sha256 orderID(temp);
				auto id = orderID.str();

				res["digest_hex"] = orderinfoDigest.str();
				res["sig_hex"] = sig_hex;
				res["id"] = id;
				res["exec_succeed"] = true;
			}
			catch (const fc::exception& e) {
				res["exec_succeed"] = false;
				res["error"] = e.to_string();
				return res;

			}
			return res;
		}

		RpcResultType load_contract_state(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			fc::mutable_variant_object res;
			try {
				auto contract_addr = params.at(0).as_string();
				auto contract_state_json_string = params.at(1).as_string();
				chain->load_contract_state(contract_addr, contract_state_json_string);
				res["exec_succeed"] = true;
				res["result"] = true;
			}
			catch (const fc::exception& e) {
				res["exec_succeed"] = false;
				res["error"] = e.to_string();
				return res;
			}
			catch (const std::exception& e) {
				res["exec_succeed"] = false;
				res["error"] = e.what();
				return res;
			}
			return res;
		}

		RpcResultType load_new_contract_from_json(blockchain* chain, HttpServer* server, const RpcRequestParams& params) {
			fc::mutable_variant_object res;
			try {
				auto contract_info_json_string = params.at(0).as_string();
				auto contract_id = chain->load_new_contract_from_json(contract_info_json_string);
				res["exec_succeed"] = true;
				res["result"] = contract_id;
			}
			catch (const fc::exception& e) {
				res["exec_succeed"] = false;
				res["error"] = e.to_string();
				return res;
			}
			catch (const std::exception& e) {
				res["exec_succeed"] = false;
				res["error"] = e.what();
				return res;
			}
			return res;
		}

	}
}

max_stars_repo_name: BlockLink/uvm

max_issues_repo_name: BlockLink/uvm

max_forks_repo_name: BlockLink/uvm


text:
/**
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*
* Copyright (c) 2016 LIBSCAPI (http://crypto.biu.ac.il/SCAPI)
* This file is part of the SCAPI project.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* 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.
*
* We request that any publication and/or code referring to and/or based on SCAPI contain an appropriate citation to SCAPI, including a reference to
* http://crypto.biu.ac.il/SCAPI.
*
* Libscapi uses several open source libraries. Please see these projects for any further licensing issues.
* For more information , See https://github.com/cryptobiu/libscapi/blob/master/LICENSE.MD
*
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*
*/

#pragma once

#include <boost/thread/thread.hpp>
#include "../../include/comm/Comm.hpp"
#define AES_KEY BC_AES_KEY // AES_KEY is defined both in GarbledBooleanCircuit and in OTSemiHonestExtension
//#include "../../include/circuits/FastGarbledBooleanCircuit.hpp"
#include "../../include/circuits/GarbledBooleanCircuit.h"
#include "../../include/interactive_mid_protocols/OTExtensionBristol.hpp"
#undef AES_KEY
#define AES_KEY OT_AES_KEY
#undef AES_KEY
#include <thread>
#include "../../include/infra/Scanner.hpp"
#include "../../include/infra/ConfigFile.hpp"

/**
* This is an implementation of party one of Yao protocol.
*/
class PartyOne {
private:
	OTBatchSender * otSender;			//The OT object that used in the protocol.
	GarbledBooleanCircuit * circuit;	//The garbled circuit used in the protocol.
	CommParty * channel;				//The channel between both parties.
	tuple<block*, block*, vector<byte> > values;//this tuple includes the input and output keys (block*) and the translation table (vector)
														 //to be used after filled by garbling the circuit

	/**
	* Sends p1 input keys to p2.
	* @param ungarbledInput The boolean input of each wire.
	* @param bs The keys for each wire.
	*/
	void sendP1Inputs(byte* ungarbledInput);
public:
	/**
	* Constructor that sets the parameters of the OT protocol and creates the garbled circuit.
	* @param channel The channel between both parties.
	* @param bc The boolean circuit that should be garbled.
	* @param mes The encryption scheme to use in the garbled circuit.
	* @param otSender The OT object to use in the protocol.
	* @param inputForTest
	*/
	PartyOne(CommParty * channel, OTBatchSender * otSender, GarbledBooleanCircuit * circuit) {
		this->channel = channel;
		this->otSender = otSender;
		this->circuit = circuit;
	};
	/**
	* Runs the protocol.
	* @param ungarbledInput The input for the circuit, each p1's input wire gets 0 or 1.
	*/
	void run(byte* ungarbledInput);
	/**
	* Runs OT protocol in order to send p2 the necessary keys without revealing any other information.
	* @param allInputWireValues The keys for each wire.
	*/
	void runOTProtocol();
};

/**
* This is an implementation of party one of Yao protocol.
*/
class PartyTwo {
private:
	OTBatchReceiver * otReceiver;			//The OT object that used in the protocol.
	GarbledBooleanCircuit * circuit;	//The garbled circuit used in the protocol.
	CommParty * channel;				//The channel between both parties.
	byte* p1Inputs;
	int p1InputsSize;

	/**
	* Compute the garbled circuit.
	* @param otOutput The output from the OT protocol, which are party two inputs.
	*/
	byte* computeCircuit(OTBatchROutput * otOutput);

public:
	/**
	* Constructor that sets the parameters of the OT protocol and creates the garbled circuit.
	* @param channel The channel between both parties.
	* @param bc The boolean circuit that should be garbled.
	* @param mes The encryption scheme to use in the garbled circuit.
	* @param otSender The OT object to use in the protocol.
	* @param inputForTest
	*/
	PartyTwo(CommParty * channel, OTBatchReceiver * otReceiver, GarbledBooleanCircuit * circuit) {
		this->channel = channel;
		this->otReceiver = otReceiver;
		this->circuit = circuit;
	};

	/**
	* Runs the protocol.
	* @param ungarbledInput The input for the circuit, each p1's input wire gets 0 or 1.
	*/
	void run(byte * ungarbledInput, int inputSize, bool print_output=false);
	/**
	* Receive the circuit's garbled tables and translation table.
	*/
	void receiveCircuit();
	/**
	* Receives party one input.
	*/
	void receiveP1Inputs();
	/**
	* Run OT protocol in order to get party two input without revealing any information.
	* @param sigmaArr Contains a byte indicates for each input wire which key to get.
	* @return The output from the OT protocol, party tw oinputs.
	*/
	shared_ptr<OTBatchROutput> runOTProtocol(byte* sigmaArr, int arrSize) {
		//Create an OT input object with the given sigmaArr.
		vector<byte> sigma;
		copy_byte_array_to_byte_vector(sigmaArr, arrSize, sigma, 0);
		int elementSize = 128;
		OTBatchRInput * input = new OTExtensionGeneralRInput(sigma, elementSize);
		//Run the Ot protocol.
		return otReceiver->transfer(input);
	};
};

ext: hpp

max_stars_repo_name: zpleefly/libscapi

max_issues_repo_name: zpleefly/libscapi

max_forks_repo_name: zpleefly/libscapi


text:
#include "LumiMask.h"

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

#include <iostream>

LumiMask LumiMask::fromJSON(const std::string& file, LumiMask::Run firstRun, LumiMask::Run lastRun)
{
  const bool noRunFilter = ( firstRun == 0 ) && ( lastRun == 0 );
  boost::property_tree::ptree ptree;
  boost::property_tree::read_json(file, ptree);

  std::vector<LumiMask::LumiBlockRange> accept;
  for ( const auto& runEntry : ptree ) {
    const LumiMask::Run run = std::stoul(runEntry.first);
    if ( noRunFilter || ( ( firstRun <= run ) && ( run <= lastRun ) ) ) {
      for ( const auto& lrEntry : runEntry.second ) {
        const auto lrNd = lrEntry.second;
        if ( lrNd.size() != 2 ) {
	  std::cout << "ERROR: format should be run : list-of-lists, where each sublist has exactly two entries" << std::endl;
        } else {
          const LumiMask::LumiBlock firstLumi = std::stoul(lrNd.begin()->second.data());
          const LumiMask::LumiBlock lastLumi  = std::stoul((++lrNd.begin())->second.data());
          // std::cout << run << " : "<< firstLumi << "-" << lastLumi << std::endl;
          accept.emplace_back(run, firstLumi, lastLumi);
        }
      }
      // } else {
      //   std::cout << "Excluding run " << run << " (out of range " << firstRun << "-" << lastRun << ")" << std::endl;
    }
  }
  return LumiMask(accept);
}

ext: cc

max_stars_repo_name: NJManganelli/FourTopNAOD

max_issues_repo_name: NJManganelli/FourTopNAOD

max_forks_repo_name: NJManganelli/FourTopNAOD


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

#ifndef InpaintingVisitorConcept_HPP
#define InpaintingVisitorConcept_HPP

#include <boost/graph/graph_concepts.hpp>
#include <boost/concept_check.hpp>

/**
 * This concept-check class defines the functions that a visitor must have in order to be
 * used by the inpainting algorithms.
 *
 * Required concepts:
 *
 *  The visitor should be copy-constructible.
 *
 * \tparam TInpaintingVisitor The visitor whose compliance to this concept is to be assessed.
 * \tparam TVertexListGraph The type of the graph on which the visitor will be applied.
 */
template <typename TInpaintingVisitor, typename TVertexListGraph>
struct InpaintingVisitorConcept
{

  typedef typename boost::graph_traits<TVertexListGraph>::vertex_descriptor Vertex;
  Vertex u;
  TVertexListGraph graph;
  TInpaintingVisitor visitor;

  BOOST_CONCEPT_ASSERT((boost::CopyConstructibleConcept<TInpaintingVisitor>));

  BOOST_CONCEPT_USAGE(InpaintingVisitorConcept)
  {
    visitor.InitializeVertex(u);  //function called on all vertices during the initialization phase.
    visitor.DiscoverVertex(u);  //function called when a live vertex is taken out of the priority-queue.
    const Vertex& target = u;
    const Vertex& source = u;

    // Function called when a source vertex has been found that matches well to the
    // current target-vertex (the same vertex that was just discovered).
    visitor.PotentialMatchMade(target, source);

    // Function called to paint the value of a target vertex with the value of the source vertex.
    // Ideally we would like to do this, but PatchInpainter::PaintPatch cannot be a template (c++ rules say so)
    // vis.PaintVertex(target, source);

    // Function called to check if the match that was determined should be accepted.
    bool was_successfully_painted = visitor.AcceptMatch(target, source);
    boost::ignore_unused_variable_warning(was_successfully_painted);

    // Function called when a vertex has been inpainted and removed from the set of target pixels.
    visitor.FinishVertex(u, u);
  }

};

#endif

max_stars_repo_name: jingtangliao/ff

max_issues_repo_name: jingtangliao/ff

max_forks_repo_name: jingtangliao/ff


text:
// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
/*

	This example program shows how to find frontal human faces in an image and
	estimate their pose.  The pose takes the form of 68 landmarks.  These are
	points on the face such as the corners of the mouth, along the eyebrows, on
	the eyes, and so forth.

	This example is essentially just a version of the face_landmark_detection_ex.cpp
	example modified to use OpenCV's VideoCapture object to read from a camera instead
	of files.

	Finally, note that the face detector is fastest when compiled with at least
	SSE2 instructions enabled.  So if you are using a PC with an Intel or AMD
	chip then you should enable at least SSE2 instructions.  If you are using
	cmake to compile this program you can enable them by using one of the
	following commands when you create the build project:
		cmake path_to_dlib_root/examples -DUSE_SSE2_INSTRUCTIONS=ON
		cmake path_to_dlib_root/examples -DUSE_SSE4_INSTRUCTIONS=ON
		cmake path_to_dlib_root/examples -DUSE_AVX_INSTRUCTIONS=ON
	This will set the appropriate compiler options for GCC, clang, Visual
	Studio, or the Intel compiler.  If you are using another compiler then you
	need to consult your compiler's manual to determine how to enable these
	instructions.  Note that AVX is the fastest but requires a CPU from at least
	2011.  SSE4 is the next fastest and is supported by most current machines.
*/

#include <dlib/opencv.h>
#include <opencv2/highgui/highgui.hpp>
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing/render_face_detections.h>
#include <dlib/image_processing.h>
#include <dlib/gui_widgets.h>
#include <detection.h>
#include <cmath>

using namespace dlib;
using namespace nlohmann;

FacialLandmarkDetector* FacialLandmarkDetector::facialLandmarkDetector = nullptr;

/*
Helper funtions
From https://github.com/HTTdesu/SimpleFacerig
*/
double meter(double A, double B, double C, double x, double y)
{
	double diversion = A * x + B * y + C;
	return diversion / sqrt(pow(A, 2) + pow(B, 2));
}

double eyebrow_move(dlib::point& p1, dlib::point& p2, double slope, double last, double rate)
{
	double bias = p1.y() - slope * p1.x();
	double distance = sqrt(pow(p1.x() - p2.x(), 2) + pow(p1.y() - p2.y(), 2));
	double diversion = meter(slope, -1, bias, p2.x(), p2.y());
	double result = (diversion / distance - 0.45) * 6;
	result = last * (1 - rate) + result * rate;
	return result;
}

double eye_open(dlib::point& p1, dlib::point& p2, dlib::point& v11, dlib::point& v12, dlib::point& v21, dlib::point& v22, double last, double rate)
{
	double distance = sqrt(pow(p1.x() - p2.x(), 2) + pow(p1.y() - p2.y(), 2));
	double slope = (double)(p2.y() - p1.y()) / (double)(p2.x() - p1.x());
	double bias = p2.y() - slope * p2.x();
	double d1 = abs(meter(slope, -1, bias, v11.x(), v11.y()));
	double d2 = abs(meter(slope, -1, bias, v12.x(), v12.y()));
	double diversion = d1 > d2 ? d1 : d2;
	d1 = abs(meter(slope, -1, bias, v21.x(), v21.y()));
	d2 = abs(meter(slope, -1, bias, v22.x(), v22.y()));
	diversion += d1 > d2 ? d1 : d2;
	double ratio = (diversion / distance - 0.18) * 8;
	ratio = ((int)(ratio * 10.0)) / 10.0;
	ratio = last * (1 - rate) + ratio * rate;
	return ratio;
}
/*
Helper funtions end
*/

/**
 * @description: Main detection loop
 * Interpetation of facial landmark point from https://github.com/HTTdesu/SimpleFacerig
 * Modified
 */
void FacialLandmarkDetector::detection()
{
	dlib::frontal_face_detector detector;//facial regonition
	dlib::shape_predictor pose_model;//landmark detection
	cv::CascadeClassifier haarcascade_eye_tree_eyeglasses;//Iris detection
	// live2d parameters
	float x_rotate = 0.0f;
	float y_rotate = 0.0f;
	float z_rotate = 0.0f;

	float left_eye = 1.0f;
	float right_eye = 1.0f;

	float eyebrow_left = 0.0f;
	float eyebrow_right = 0.0f;

	float eyeBallX = 0.0f;
	float eyeBallY = 0.0f;

	float mouth_open = 0.0f;
	//Eyes positions
	int leftEyeMaxX = 0;
	int leftEyeMinX = 0;
	int leftEyeMinY = 0;
	int leftEyeMaxY = 0;
	int rightEyeMaxX = 0;
	int rightEyeMinX = 0;
	int rightEyeMinY = 0;
	int rightEyeMaxY = 0;
	try
	{
		cv::VideoCapture camera(0);
		if (!camera.isOpened())
		{
			std::cerr << "Unable to connect to camera" << std::endl;
			return;
		}

		//image_window win;

		// Load face detection and pose estimation models.
		frontal_face_detector detector = get_frontal_face_detector();
		shape_predictor pose_model;
		haarcascade_eye_tree_eyeglasses.load("..\\..\\res\\haarcascade_eye_tree_eyeglasses.xml");//OpenCV Model
		deserialize("..\\..\\res\\shape_predictor_68_face_landmarks.dat") >> pose_model; //dlib model

		// Grab and process frames until the main window is closed by the user.
		while (camera.isOpened())
		{
			cv::Mat buff, frame;
			camera.read(frame);
			//cv::GaussianBlur(temp, buff, cv::Size(5, 5), 5, 5);
			cv::flip(frame, frame, 1);

//The result of following Process is process facial landmark points and get positions
//Copy from https://github.com/HTTdesu/SimpleFacerig. Authorized by author
			dlib::cv_image<dlib::bgr_pixel> cimg(frame);
			std::vector<dlib::rectangle> faces = detector(cimg);//get faces
			std::vector<dlib::full_object_detection> shapes;

			for (unsigned long i = 0; i < faces.size(); ++i)
				shapes.push_back(pose_model(cimg, faces[i]));

			if (!shapes.empty()) {
				for (int i = 0; i < 68; i++) {
					cv::circle(frame, cvPoint(shapes[0].part(i).x(), shapes[0].part(i).y()), 2, cv::Scalar(0, 0, 255), -1);
				}

				int div_x = shapes[0].part(16).x() - shapes[0].part(0).x();
				int div_y = shapes[0].part(16).y() - shapes[0].part(0).y();
				double center_x = shapes[0].part(0).x() + div_x / 2.0;
				double center_y = shapes[0].part(0).y() + div_y / 2.0;
				double slope = (double)(div_y) / (double)(div_x);
				double bias = center_y - slope * center_x;
				double x_proj = (slope * (shapes[0].part(30).y() - bias) + shapes[0].part(30).x()) / (1 + pow(slope, 2));
				double y_proj = slope * x_proj + bias;
				double diversion = sqrt(pow(x_proj - shapes[0].part(0).x(), 2) + pow(y_proj - shapes[0].part(0).y(), 2));
				double distance = sqrt(pow(shapes[0].part(16).x() - shapes[0].part(0).x(), 2) + pow(shapes[0].part(16).y() - shapes[0].part(0).y(), 2));

				double rate = 0.5;
				// Ax+By+C/sqrt(A^2+B^2)
				x_rotate = x_rotate * (1 - rate) + asin(diversion / distance - 0.5) * 3.14 * 40.0 * rate;

				// nose to eye around 1/6 head
				diversion = meter(slope, -1, bias, shapes[0].part(30).x(), shapes[0].part(30).y());
				diversion = diversion + 1.0 / 6 * distance;
				y_rotate = y_rotate * (1 - rate) + asin(diversion / distance) * 3.14 * 40.0 * rate;

				z_rotate = z_rotate * (1 - rate) + atan(slope) * 3.14 * 40 * rate;

				// eye
				left_eye = eye_open(shapes[0].part(36), shapes[0].part(39), shapes[0].part(37), shapes[0].part(38), shapes[0].part(40), shapes[0].part(41), left_eye, rate);
				right_eye = eye_open(shapes[0].part(42), shapes[0].part(45), shapes[0].part(43), shapes[0].part(44), shapes[0].part(46), shapes[0].part(47), right_eye, rate);

				// eyebrow
				eyebrow_left = eyebrow_move(shapes[0].part(17), shapes[0].part(19), slope, eyebrow_left, rate);
				eyebrow_right = eyebrow_move(shapes[0].part(26), shapes[0].part(24), slope, eyebrow_right, rate);

				// mouth
				diversion = sqrt(pow(shapes[0].part(62).x() - shapes[0].part(66).x(), 2) + pow(shapes[0].part(62).y() - shapes[0].part(66).y(), 2));
				distance = sqrt(pow(shapes[0].part(60).x() - shapes[0].part(64).x(), 2) + pow(shapes[0].part(60).y() - shapes[0].part(64).y(), 2));
				mouth_open = (diversion / distance - 0.15) * 2;

//process facial landmark points end

				dlib::full_object_detection& firstFace = shapes[0];//only proces one face, don't support multiple faces
				// Left eye range
				{

					int minX = INT_MAX, maxX = 0, minY = INT_MAX, maxY = 0;
					for (unsigned long i = 37; i <= 41; ++i) {
						minX = minX < firstFace.part(i).x() ? minX : firstFace.part(i).x();
						maxX = maxX > firstFace.part(i).x() ? maxX : firstFace.part(i).x();
						minY = minY < firstFace.part(i).y() ? minY : firstFace.part(i).y();
						maxY = maxY > firstFace.part(i).y() ? maxY : firstFace.part(i).y();
					}
					leftEyeMaxX = maxX;
					leftEyeMinX = minX;
					leftEyeMinY = minY;
					leftEyeMaxY = maxY;

				}

				// Right eye range
				{
					int minX = INT_MAX, maxX = 0, minY = INT_MAX, maxY = 0;
					for (unsigned long i = 43; i <= 47; ++i) {
						minX = minX < firstFace.part(i).x() ? minX : firstFace.part(i).x();
						maxX = maxX > firstFace.part(i).x() ? maxX : firstFace.part(i).x();
						minY = minY < firstFace.part(i).y() ? minY : firstFace.part(i).y();
						maxY = maxY > firstFace.part(i).y() ? maxY : firstFace.part(i).y();
					}
					rightEyeMaxX = maxX;
					rightEyeMinX = minX;
					rightEyeMinY = minY;
					rightEyeMaxY = maxY;
				}

				try {
					std::vector<cv::Rect> eyes;
					cv::Mat eyesRaw;
					camera.read(eyesRaw);
					cv::flip(eyesRaw, eyesRaw, 1);
					cv::cvtColor(eyesRaw, eyesRaw, cv::COLOR_BGR2GRAY);//灰度
					equalizeHist(eyesRaw, eyesRaw);//直方图均化
					haarcascade_eye_tree_eyeglasses.detectMultiScale(eyesRaw, eyes,
						1.1, 2, 0
						//|CV_HAAR_FIND_BIGGEST_OBJECT
						//|CV_HAAR_DO_ROUGH_SEARCH
						| cv::CASCADE_SCALE_IMAGE
						,
						cv::Size(30, 30));

					for (std::vector<cv::Rect>::const_iterator r = eyes.begin(); r != eyes.end(); r++)
					{
						cv::Point center;
						int radius;
						//center可以作为瞳孔的坐标
						center.x = cvRound(r->x + r->width * 0.5);
						center.y = cvRound(r->y + r->height * 0.5);
						//radius = (int)(cvRound(r->width + r->height)*0.25);
						radius = 2;
						//cv::imshow("eyesRaw", eyesRaw);
						int margin = 10;
						//Calaulate relative position of iris
						if (center.x < rightEyeMaxX + margin && center.x > rightEyeMinX - margin && center.y < rightEyeMaxY + margin && center.y > rightEyeMinY - margin) {
							eyeBallX = (center.x - ((rightEyeMaxX - rightEyeMinX) / 2.0f + rightEyeMinX)) / (rightEyeMaxX - rightEyeMinX) * 2;
							eyeBallY = (center.y - ((rightEyeMaxY - rightEyeMinY) / 2.0f + rightEyeMinY)) / (rightEyeMaxY - rightEyeMinY) * 2;
							cv::circle(frame, center, radius, cv::Scalar(255, 0, 0), 3, 8, 0);

						}
						else if (center.x < leftEyeMaxX + margin && center.x > leftEyeMinX - margin && center.y < leftEyeMaxY + margin && center.y > leftEyeMinY - margin) {
							eyeBallX = (center.x - ((leftEyeMaxX - leftEyeMinX) / 2.0f + leftEyeMinX)) / (leftEyeMaxX - leftEyeMinX) * 2;
							eyeBallY = (center.y - ((leftEyeMaxY - leftEyeMinY) / 2.0f + leftEyeMinY)) / (leftEyeMaxY - leftEyeMinY) * 2;
							cv::circle(frame, center, radius, cv::Scalar(255, 0, 0), 3, 8, 0);

						}
						else {
							cv::circle(frame, center, radius, cv::Scalar(0, 255, 0), 3, 8, 0);
						}

					}
				}
				catch (std::exception e) {
					qDebug() << e.what();//Usually catch fail to load model
				}

				//Idea from
				//版权声明：本文为博主原创文章，遵循 CC 4.0 BY-SA 版权协议，转载请附上原文出处链接和本声明。
				//本文链接：https://blog.csdn.net/computerme/article/details/38142125

				//Finalize and put into Json
				{
					json data;
					data["head"]["ParamAngleZ"] = z_rotate;
					data["head"]["ParamAngleX"] = x_rotate;
					data["head"]["ParamAngleY"] = y_rotate;
					data["eye"]["ParamEyeLOpen"] = left_eye;
					data["eye"]["ParamEyeROpen"] = right_eye;
					data["eye"]["ParamEyeBallX"] = eyeBallX;
					data["eye"]["ParamEyeBallY"] = eyeBallY;
					data["brow"]["ParamBrowLY"] = eyebrow_left;
					data["brow"]["ParamBrowRY"] = eyebrow_right;
					data["ParamMouthOpenY"] = mouth_open;

					Network_QT::getInstance()->updateMotion(data);

					emit NewDetection();
				}

			}
			else
			{
				x_rotate = 0.0f;
				y_rotate = 0.0f;
				z_rotate = 0.0f;
				left_eye = 1.0f;
				right_eye = 1.0f;
				eyebrow_left = 0.0f;
				eyebrow_right = 0.0f;
				mouth_open = 0.0f;
				eyeBallX = 0.0f;
				eyeBallY = 0.0f;
			}

			//double t = (live2d::UtSystem::getUserTimeMSec() / 1000.0) * 2 * 3.14;
			//live2DModel->setParamFloat("PARAM_ANGLE_Z", (float)(30 * sin(t / 3.0)));

			//cv::waitKey(30);
			//Display it all on the screen
			//
			// Display it all on the screen
			if (debug) {
				system("cls");
				qDebug() << "x_rotate" << x_rotate << "\n"
					<< "y_rotate" << y_rotate << "\n"
					<< "z_rotate" << z_rotate << "\n"
					<< "left_eye" << left_eye << "\n"
					<< "right_eye" << right_eye << "\n"
					<< "eyebrow_left" << eyebrow_left << "\n"
					<< "eyebrow_right" << eyebrow_right << "\n"
					<< "mouth_open" << mouth_open << "\n"
					<< "eyeBallX" << eyeBallX << "\n"
					<< "eyeBallY" << eyeBallY << "\n";
			}
			if (Setting::getSetting()->ShowFR) {
				cv::imshow("Feature points", frame);
				cv::waitKey(30);
			}

		}

	}catch (serialization_error & e)
	{//When fail to load dlib model
		std::cerr << "Fail to load model" << std::endl;
		qDebug().noquote() << "Fail to load model";
		this->ModelLoadError = true;
		return;
	}
	catch (std::exception & e)
	{
		std::cerr << e.what() << std::endl;
		return;
	}
}

ext: cpp


text: #include <boost/iostreams/device/null.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//
// server_main.cpp: Main server implementation
//
// Eli Bendersky (eliben@gmail.com)
// This code is in the public domain
//
#include <iostream>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include "db_server.h"
#include "packedmessage.h"
#include "stringdb.pb.h"

using namespace std;
namespace asio = boost::asio;

int main(int argc, const char* argv[])
{
    unsigned port = 4050;
    if (argc > 1)
        port = atoi(argv[1]);
    cout << "Serving on port " << port << endl;

    try {
        asio::io_service io_service;
        DbServer server(io_service, 4050);
        io_service.run();
    }
    catch (std::exception& e) {
        cerr << e.what() << endl;
    }

    return 0;
}


text:
/**
 * @file
 * $Revision: 6513 $
 * $Date: 2016-01-14 16:04:44 -0700 (Thu, 14 Jan 2016) $
 * $Id: AssetSidebarStrategy.cpp 6513 2016-01-14 23:04:44Z kbecker@GS.DOI.NET $
 *
 *   Unless noted otherwise, the portions of Isis written by the USGS are
 *   public domain. See individual third-party library and package descriptions
 *   for intellectual property information, user agreements, and related
 *   information.
 *
 *   Although Isis has been used by the USGS, no warranty, expressed or
 *   implied, is made by the USGS as to the accuracy and functioning of such
 *   software and related material nor shall the fact of distribution
 *   constitute any such warranty, and no responsibility is assumed by the
 *   USGS in connection therewith.
 *
 *   For additional information, launch
 *   $ISISROOT/doc//documents/Disclaimers/Disclaimers.html
 *   in a browser or see the Privacy & Disclaimers page on the Isis website,
 *   http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on
 *   http://www.usgs.gov/privacy.html.
 */
#include "AssetSidebarStrategy.h"

// boost library
#include <boost/foreach.hpp>

// other ISIS
#include "Application.h"
#include "PvlFlatMap.h"
#include "PvlObject.h"
#include "Resource.h"

using namespace std;

namespace Isis {

  /**
   * Default constructor
   *
   * Note: This method is not called by isisminer
   * or any of it's support classes so it is not covered
   * by appTests.  It is not possible to get full test
   * coverage unless isisminer implementation changes
   * or this class is moved to an objs directory with a unitTest.
   */
  AssetSidebarStrategy::AssetSidebarStrategy() : SidebarStrategy(),
                        m_asset(), m_create(false), m_removeEmpties(true),
                        m_source(FromCopy) {
    setName("AssetSidebar");
    setType("AssetSidebar");
  }

  /**
   * @brief Constructor loads from a Strategy object AssetSidebar definition
   *
   * This constructor loads and retains processing parameters from the AssetSidebar
   * Strategy object definition as (typically) read from the configuration file.
   *
   * @author 2012-07-15 Kris Becker
   *
   * @param definition AssetSidebar Strategy PVL object definition
   * @param globals Global Resource of keywords
   */
  AssetSidebarStrategy::AssetSidebarStrategy(const PvlObject &definition,
                                             const ResourceList &globals) :
                                             SidebarStrategy(definition, globals),
                                             m_asset(), m_create(false),
                                             m_removeEmpties(true),
                                             m_source(FromCopy) {

    PvlFlatMap parms(getDefinitionMap());
    m_asset         = parms.get("Asset");
    m_create        = ("create" == parms.get("Operation", "process").toLower());
    m_removeEmpties = toBool(parms.get("ClearOnEmpty", "true"));

    QString source = parms.get("CreateSource", "copy").toLower();
    if ( "clone" == source ) { m_source = FromClone; }
    else if ( "none" == source ) { m_source = FromNone; }
    else { m_source = FromCopy; }

    return;
  }

  /**
   * Destructor
   */
  AssetSidebarStrategy::~AssetSidebarStrategy() { }

  /** Remove existing asset if create option is invoked */
  int AssetSidebarStrategy::preRunProcess(ResourceList &resources,
                                     const ResourceList &globals) {

    //  Count current active ones whilst incrementing the counter
    BOOST_FOREACH ( SharedResource resource, resources ) {
      if ( !resource->isDiscarded() ) {
        processed();
        // If creating a an existing one of the complete resource list by
        // default. Either a copy or a clone.
        if ( true == m_create ) {
          if ( FromCopy == m_source ) {
            QVariant asset(QVariant::fromValue(copyList(resources)));
            resource->addAsset(m_asset, asset);
          }
          else if ( FromClone == m_source ) {
            QVariant asset(QVariant::fromValue(cloneList(resources)));
            resource->addAsset(m_asset, asset);
          }
          else {
            resource->removeAsset( m_asset );
          }
        }
      }
    }

    return (totalProcessed());
  }

  /**
   * @brief Applies a strategy to assets of active resources.
   *
   * This method applies another strategy to active resources' assets.
   *
   * When the Operation keyword has a value of "create", this method will not try to obtain
   * any assets contained in active resources. This is in order to create new assets to
   * add to active resources. If this operation is not "create", then this method will
   * attempt to obtain assets that are contained in active resources, apply the strategy to
   * these assets, then add the processed assets to the active resources.
   *
   * @author 2012-07-15 Kris Becker
   *
   * @param strategy The strategy to apply to assets
   * @param resources The active resources
   * @param globals Global Resource of keywords
   * @return int The total number of assets processed in the strategy
   */
  int AssetSidebarStrategy::apply(SharedStrategy &strategy,
                                  ResourceList &resources,
                                  const ResourceList &globals) {
    int nassets = 0;
    BOOST_FOREACH ( SharedResource resource, resources ) {
      if ( resource->isActive() ) {
        ResourceList assetList;

        // Obtain assets from the current resource if they exist
        if ( resource->hasAsset(m_asset) ) {
          QVariant asset = resource->asset(m_asset);
          // Note: this conditional will not evaluate as False
          // ResourceList is declared as a Q_METATYPE (QVariant) in Resource.h
          // Thus, the QVariant asset will be converted to ResourceList, another QVariant
          if ( asset.canConvert<ResourceList>() ) {
            assetList = asset.value<ResourceList>();
          }
        }

        //  Apply the strategy to the list of assets
        nassets += strategy->apply( assetList, getGlobals(resource, globals) );

        //  Add the list to the asset
        QVariant v_asset(QVariant::fromValue(assetList));
        resource->addAsset(m_asset, v_asset);
      }
    }

    return (nassets);
  }

/**
 * @brief Post run processing after execution of all strategies
 *
 * This method will be invoked by SidebarStrategy after all the strategies have
 * been ran. This implementation will check for the existance of the named
 * asset and determine if empty lists exists. If the user requests, removed
 * these assets.
 *
 * Note this will only operate on active Resources.
 *
 * The active status of the Resources is unaltered (users can use the
 * ResourceManager to do that).
 *
 * @author 2015-09-15 Kris Becker
 *
 * @param resources List of Resources to check for assets
 * @param globals   Global parameter pool
 *
 * @return int Number of empty Asset resource lists found and removed
 */
  int AssetSidebarStrategy::postRunProcess(ResourceList &resources,
                                          const ResourceList &globals) {

    // Set up incoming asset handling conditions
    int nremoved = 0;
    if ( m_removeEmpties ) {
      BOOST_FOREACH ( SharedResource resource, resources ) {
        if ( resource->isActive() ) {
          if ( resource->hasAsset(m_asset) ) {
            QVariant asset = resource->asset(m_asset);
            // Note: this conditional will not evaluate as False
            // ResourceList is declared as a Q_METATYPE (QVariant) in Resource.h
            // Thus, the QVariant asset will be converted to ResourceList, another QVariant
            if ( asset.canConvert<ResourceList>() ) {
              ResourceList assetList = asset.value<ResourceList>();
              if ( assetList.size() == 0) {
                resource->removeAsset(m_asset);
                nremoved++;
              }
            }
          }
        }
      }
    }
    return ( SidebarStrategy::postRunProcess(resources, globals) );
  }

}  //namespace Isis


text:
// This file is auto-generated, don't edit it. Thanks.

#include <alibabacloud/sts_20150401.hpp>
#include <alibabacloud/endpoint_util.hpp>
#include <alibabacloud/open_api.hpp>
#include <boost/any.hpp>
#include <boost/throw_exception.hpp>
#include <darabonba/core.hpp>
#include <darabonba/util.hpp>
#include <iostream>
#include <map>

using namespace std;

using namespace Alibabacloud_Sts20150401;

Alibabacloud_Sts20150401::Client::Client(const shared_ptr<Alibabacloud_OpenApi::Config>& config) : Alibabacloud_OpenApi::Client(config) {
  _endpointRule = make_shared<string>("regional");
  _endpointMap = make_shared<map<string, string>>(map<string, string>({
    {"ap-northeast-2-pop", "sts.aliyuncs.com"},
    {"cn-beijing-finance-1", "sts.aliyuncs.com"},
    {"cn-beijing-finance-pop", "sts.aliyuncs.com"},
    {"cn-beijing-gov-1", "sts.aliyuncs.com"},
    {"cn-beijing-nu16-b01", "sts.aliyuncs.com"},
    {"cn-edge-1", "sts.aliyuncs.com"},
    {"cn-fujian", "sts.aliyuncs.com"},
    {"cn-haidian-cm12-c01", "sts.aliyuncs.com"},
    {"cn-hangzhou-bj-b01", "sts.aliyuncs.com"},
    {"cn-hangzhou-finance", "sts.aliyuncs.com"},
    {"cn-hangzhou-internal-prod-1", "sts.aliyuncs.com"},
    {"cn-hangzhou-internal-test-1", "sts.aliyuncs.com"},
    {"cn-hangzhou-internal-test-2", "sts.aliyuncs.com"},
    {"cn-hangzhou-internal-test-3", "sts.aliyuncs.com"},
    {"cn-hangzhou-test-306", "sts.aliyuncs.com"},
    {"cn-hongkong-finance-pop", "sts.aliyuncs.com"},
    {"cn-huhehaote-nebula-1", "sts.aliyuncs.com"},
    {"cn-north-2-gov-1", "sts-vpc.cn-north-2-gov-1.aliyuncs.com"},
    {"cn-qingdao-nebula", "sts.aliyuncs.com"},
    {"cn-shanghai-et15-b01", "sts.aliyuncs.com"},
    {"cn-shanghai-et2-b01", "sts.aliyuncs.com"},
    {"cn-shanghai-inner", "sts.aliyuncs.com"},
    {"cn-shanghai-internal-test-1", "sts.aliyuncs.com"},
    {"cn-shenzhen-finance-1", "sts-vpc.cn-shenzhen-finance-1.aliyuncs.com"},
    {"cn-shenzhen-inner", "sts.aliyuncs.com"},
    {"cn-shenzhen-st4-d01", "sts.aliyuncs.com"},
    {"cn-shenzhen-su18-b01", "sts.aliyuncs.com"},
    {"cn-wuhan", "sts.aliyuncs.com"},
    {"cn-yushanfang", "sts.aliyuncs.com"},
    {"cn-zhangbei", "sts.aliyuncs.com"},
    {"cn-zhangbei-na61-b01", "sts.aliyuncs.com"},
    {"cn-zhangjiakou-na62-a01", "sts.aliyuncs.com"},
    {"cn-zhengzhou-nebula-1", "sts.aliyuncs.com"},
    {"eu-west-1-oxs", "sts.aliyuncs.com"},
    {"rus-west-1-pop", "sts.aliyuncs.com"}
  })
);
  checkConfig(config);
  _endpoint = make_shared<string>(getEndpoint(make_shared<string>("sts"), _regionId, _endpointRule, _network, _suffix, _endpointMap, _endpoint));
};

string Alibabacloud_Sts20150401::Client::getEndpoint(shared_ptr<string> productId,
                                                     shared_ptr<string> regionId,
                                                     shared_ptr<string> endpointRule,
                                                     shared_ptr<string> network,
                                                     shared_ptr<string> suffix,
                                                     shared_ptr<map<string, string>> endpointMap,
                                                     shared_ptr<string> endpoint) {
  if (!Darabonba_Util::Client::empty(endpoint)) {
    return *endpoint;
  }
  if (!Darabonba_Util::Client::isUnset<map<string, string>>(endpointMap) && !Darabonba_Util::Client::empty(make_shared<string>((*endpointMap)[regionId]))) {
    return (*endpointMap)[regionId];
  }
  return Alibabacloud_EndpointUtil::Client::getEndpointRules(productId, regionId, endpointRule, network, suffix);
}

AssumeRoleResponse Alibabacloud_Sts20150401::Client::assumeRoleWithOptions(shared_ptr<AssumeRoleRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return AssumeRoleResponse(doRPCRequest(make_shared<string>("AssumeRole"), make_shared<string>("2015-04-01"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

AssumeRoleResponse Alibabacloud_Sts20150401::Client::assumeRole(shared_ptr<AssumeRoleRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return assumeRoleWithOptions(request, runtime);
}

AssumeRoleWithOIDCResponse Alibabacloud_Sts20150401::Client::assumeRoleWithOIDCWithOptions(shared_ptr<AssumeRoleWithOIDCRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return AssumeRoleWithOIDCResponse(doRPCRequest(make_shared<string>("AssumeRoleWithOIDC"), make_shared<string>("2015-04-01"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

AssumeRoleWithOIDCResponse Alibabacloud_Sts20150401::Client::assumeRoleWithOIDC(shared_ptr<AssumeRoleWithOIDCRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return assumeRoleWithOIDCWithOptions(request, runtime);
}

AssumeRoleWithSAMLResponse Alibabacloud_Sts20150401::Client::assumeRoleWithSAMLWithOptions(shared_ptr<AssumeRoleWithSAMLRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  Darabonba_Util::Client::validateModel(request);
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({
    {"body", boost::any(Darabonba_Util::Client::toMap(request))}
  }));
  return AssumeRoleWithSAMLResponse(doRPCRequest(make_shared<string>("AssumeRoleWithSAML"), make_shared<string>("2015-04-01"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

AssumeRoleWithSAMLResponse Alibabacloud_Sts20150401::Client::assumeRoleWithSAML(shared_ptr<AssumeRoleWithSAMLRequest> request) {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return assumeRoleWithSAMLWithOptions(request, runtime);
}

GetCallerIdentityResponse Alibabacloud_Sts20150401::Client::getCallerIdentityWithOptions(shared_ptr<Darabonba_Util::RuntimeOptions> runtime) {
  shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>();
  return GetCallerIdentityResponse(doRPCRequest(make_shared<string>("GetCallerIdentity"), make_shared<string>("2015-04-01"), make_shared<string>("HTTPS"), make_shared<string>("POST"), make_shared<string>("AK"), make_shared<string>("json"), req, runtime));
}

GetCallerIdentityResponse Alibabacloud_Sts20150401::Client::getCallerIdentity() {
  shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>();
  return getCallerIdentityWithOptions(runtime);
}

max_stars_repo_name: aliyun/alibabacloud-cpp-sdk

max_issues_repo_name: aliyun/alibabacloud-cpp-sdk

max_forks_repo_name: aliyun/alibabacloud-cpp-sdk


text:
// Copyright 2014, Additive Regularization of Topic Models.

#include "artm/core/thread_safe_holder.h"

#include <boost/thread/mutex.hpp>
#include <boost/utility.hpp>

#include "gtest/gtest.h"

using ::artm::core::ThreadSafeHolder;
using ::artm::core::ThreadSafeCollectionHolder;

// To run this particular test:
// artm_tests.exe --gtest_filter=ThreadSafeHolder.*
TEST(ThreadSafeHolder, Basic) {
  ThreadSafeHolder<double> int_holder;
  int_holder.set(std::make_shared<double>(5.0));
  EXPECT_EQ(*int_holder.get(), 5.0);

  ThreadSafeCollectionHolder<int, double> collection_holder;
  int key1 = 2, key2 = 3, key3 = 4;
  collection_holder.set(key1, std::make_shared<double>(7.0));
  collection_holder.set(key2, std::make_shared<double>(8.0));
  EXPECT_EQ(*collection_holder.get(key1), 7.0);
  EXPECT_EQ(*collection_holder.get(key2), 8.0);

  EXPECT_TRUE(collection_holder.has_key(key1));
  EXPECT_FALSE(collection_holder.has_key(key3));
  collection_holder.erase(key1);
  EXPECT_FALSE(collection_holder.has_key(key1));
}

max_stars_repo_name: marinadudarenko/bigartm

max_issues_repo_name: marinadudarenko/bigartm

max_forks_repo_name: marinadudarenko/bigartm


text:
/*
 * algebra.hpp
 *
 *  Created on: 30 Jul 2017
 *      Author: julianporter
 */

#ifndef ALGEBRA_HPP_
#define ALGEBRA_HPP_

#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <cmath>

#define PI 3.14159265359
#define radians(x) (x*PI/180.0)
#define degrees(x) (x*180.0/PI)

namespace mapping {

using Vector = boost::numeric::ublas::vector<double>;
using Zero   = boost::numeric::ublas::zero_vector<double>;
using Matrix = boost::numeric::ublas::matrix<double>;
using ID     = boost::numeric::ublas::identity_matrix<double>;
using ZMatrix= boost::numeric::ublas::zero_matrix<double>;

bool operator==(const Vector &l,const Vector &r);
bool operator!=(const Vector &l,const Vector &r);

bool operator==(const Matrix &l,const Matrix &r);
bool operator!=(const Matrix &l,const Matrix &r);

Matrix transpose(const Matrix &m);

}

#endif /* ALGEBRA_HPP_ */

max_stars_repo_name: EdwardBetts/OSGridConverter

max_issues_repo_name: EdwardBetts/OSGridConverter

max_forks_repo_name: EdwardBetts/OSGridConverter


text:
/***************************************************************************
   Copyright 2015 Ufora Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
****************************************************************************/
#include "CSTValue.hppml"

#include <boost/python.hpp>
#include "../../native/Registrar.hpp"
#include "../../core/python/CPPMLWrapper.hpp"
#include "../../core/python/ValueLikeCPPMLWrapper.hppml"

class CSTValueWrapper :
	public native::module::Exporter<CSTValueWrapper> {
public:
	std::string		getModuleName(void)
		{
		return "FORA";
		}
	static std::string CSTValueToString(CSTValue& v)
		{
		return v.toString();
		}
	static ImplValContainer CSTValueGetIVC(CSTValue& v)
		{
		return ImplValContainer(v.getReference());
		}
	static hash_type CSTValueHash(CSTValue& v)
		{
		return v.hash();
		}
	static CSTValue* constructFromCSTValue(CSTValue& v)
		{
		return new CSTValue(v);
		}
	static CSTValue* constructFromNothing()
		{
		return new CSTValue();
		}
	void exportPythonWrapper()
		{
		using namespace boost::python;

		class_<CSTValue>("CSTValue", init<ImplValContainer>())
			.def("__init__", make_constructor(constructFromCSTValue))
			.def("__init__", make_constructor(constructFromNothing))
			.def("__str__", &CSTValueToString)
			.def("__repr__", &CSTValueToString)
			.add_property("hash", &CSTValueHash)
			.def("getIVC", &CSTValueGetIVC)
			;
		}

};

//explicitly instantiating the registration element causes the linker to need
//this file
template<>
char native::module::Exporter<CSTValueWrapper>::mEnforceRegistration =
	native::module::ExportRegistrar<
	CSTValueWrapper>::registerWrapper();

max_stars_repo_name: ufora/ufora


text:
/*! \file demo_Hoaglin.cpp
  \brief Demonstration of Boxplot quartile options. Boxplots appear different depending the choice of definition for the quartile.

  \details
    "Some Implementations of the Boxplot"
    Michael Frigge, David C. Hoaglin and Boris Iglewicz
    The American Statistician, Vol. 43, No. 1 (Feb., 1989), pp. 50-54
    discusses the design of the boxplot.

    However the plot of their example data shown below shows the considerable variation in the appearance of the same data,
    using different definitions of quartiles used in various popular statistics packages.

    One obvious conclusion is that you should not expect boxplots to look the same when using more than one program.

    Boost.Plot provides 5 popular definitions for the quartiles.
    This should allow the user to produce plots that look similar to boxplots from most statistics plotting program.
    To confuse matter further, most have their own default definition *and* options to chose other definitions:
    these options are shown below as type, method, PCTLDEF.

    The interquartile range is calculated using the 1st \& 3rd sample quartiles,
    but there are various ways to calculate those quartiles, summarised in
    Rob J. Hyndman and Yanan Fan, 1996, "Sample Quantiles in Statistical Packages",
    The American Statistician 50(4):361-365, (1996).

    The interquartile range, often called IQR is quartile 3 (p = 3/4) - quartile 1 (1/4).
    The median is the 2nd quartile (p = 2/4 = 1/2).

    Five of Hyndman and Fan's sample quantile definitions have a particularly simple common form
    selected according to which definition of m is chosen in function quantiles.
    This is implemented in function quantiles by parameter `HF_definition`:

      double quantile(vector<double>& data, double p, int HF_definition = 8);

    The default definition is that recommended by Hyndman and Fan, or
    users can select which definition is used for all boxplots, or individual data series as shown in the example below.

       my_boxplot.quartile_definition(5); // All plots

       my_boxplot.plot.quartile_definition(7); // Just this data series plot.

    Hyndman and Fan definitions 4 to 8 are used by the following packages:

    * #4 SAS (PCTLDEF=1), R (type=4), Maple (method=3)
    * #5 R (type=5), Maple (method=4), Wolfram Mathematica quartiles.
    * #6 Minitab, SPSS, BMDP, JMP, SAS (PCTLDEF=4), R(type=6), Maple (method=5).
    * #7 Excel, S-Plus, R (type=7[default]), Maxima, Maple (method=6).
    * #8 H&F 8: R (type=8), Maple (method=7[default]).

    Some observations on the various options are:

    * #4 Often a moderate interquartile range.

    * #5 Symmetric linear interpolation: a common choice when the data represent a sample
    from a continuous distribution and you want an unbiased estimate of the quartiles of that distribution.

    * #6 This "half" sample excludes the sample median (k observations) for odd n (=2*k+1).
    This will tend to be a better estimate for the population quartiles,
    but will tend to give quartile estimates that are a bit too far
    from the center of the whole sample (too wide an interquartile range).

    * #7 Smallest interquartile range, so flags most outliers.
    For a continuous distribution,
    this will tend to give too narrow an interquartile range,
    since there will tend to be a small fraction of the population beyond the extreme
    sample observations. In particular, for odd n (=2*k+1), Excel calculates the
    1st (3rd) quartile as the median of the lower (upper) "half" of the sample
    including the sample median (k+1 observations).

    * #8 recommended by H&F because it is
    approximately median-unbaised estimate regardless of distribution
    and thus suitable for continuous and discrete distributions.
    which gives quartiles between those reported by Minitab and Excel.
    This approach is approximately median unbiased for continuous distributions.
    Slightly higher interquartile range than definition 7.

    The 'fences' beyond which points are regarded as outliers, or extreme outliers,
    are a multiplying factor, usually called k, and usually 1.5 * interquartile range,
    and 3 * interquartile range as recommended by Hoaglin et al.

  \author Paul A Bristow
*/

// Copyright Jacob Voytko 2007
// Copyright Paul A. Bristow 2008

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

// An example to demonstrate the implementation of boxplot.

// This file is written to be included from a Quickbook .qbk document.
// It can be compiled by the C++ compiler, and run. Any output can
// also be added here as comment or included or pasted in elsewhere.

// Caution: this file contains Quickbook markup as well as code
// and comments: don't change any of the special comment markups!

//[demo_Hoaglin_1

/*`

"Some Implementations of the Boxplot"
Michael Frigge, David C. Hoaglin and Boris Iglewicz
The American Statistician, Vol. 43, No. 1 (Feb., 1989), pp. 50-54
discusses the design of the boxplot.

However the plot of their example data shown below shows the considerable variation in the appearance of the same data,
using different definitions of quartiles used in various popular statistics packages.

One obvious conclusion is that you should not expect boxplots to look the same when using more than one program.

Boost.Plot provides 5 popular definitions for the quartiles.
This should allow the user to produce plots that look similar to boxplots from most statistics plotting program.
To confuse matter further, most have their own default definition *and* options to chose other definitions:
these options are shown below as type, method, PCTLDEF.

The interquartile range is calculated using the 1st & 3rd sample quartiles,
but there are various ways to calculate those quartiles, summarised in
Rob J. Hyndman and Yanan Fan, 1996, "Sample Quantiles in Statistical Packages",
The American Statistician 50(4):361-365, (1996).

The interquartile range, often called IQR is quartile 3 (p = 3/4) - quartile 1 (1/4).
The median is the 2nd quartile (p = 2/4 = 1/2).

Five of Hyndman and Fan's sample quantile definitions have a particularly simple common form
selected according to which definition of m is chosen in function quantiles.
This is implemented in function quantiles by parameter `HF_definition`:

  double quantile(vector<double>& data, double p, int HF_definition = 8);

The default definition is that recommended by Hyndman and Fan, or
users can select which definition is used for all boxplots, or individual data series as shown in the example below.

   my_boxplot.quartile_definition(5); // All plots

   my_boxplot.plot.quartile_definition(7); // Just this data series plot.

Hyndman and Fan definitions 4 to 8 are used by the following packages:

* #4 SAS (PCTLDEF=1), R (type=4), Maple (method=3)
* #5 R (type=5), Maple (method=4), Wolfram Mathematica quartiles.
* #6 Minitab, SPSS, BMDP, JMP, SAS (PCTLDEF=4), R(type=6), Maple (method=5).
* #7 Excel, S-Plus, R (type=7[default]), Maxima, Maple (method=6).
* #8 H&F 8: R (type=8), Maple (method=7[default]).

Some observations on the various options are:

* #4 Often a moderate interquartile range.

* #5 Symmetric linear interpolation: a common choice when the data represent a sample
from a continuous distribution and you want an unbiased estimate of the quartiles of that distribution.

* #6 This "half" sample excludes the sample median (k observations) for odd n (=2*k+1).
This will tend to be a better estimate for the population quartiles,
but will tend to give quartile estimates that are a bit too far
from the center of the whole sample (too wide an interquartile range).

* #7 Smallest interquartile range, so flags most outliers.
For a continuous distribution,
this will tend to give too narrow an interquartile range,
since there will tend to be a small fraction of the population beyond the extreme
sample observations. In particular, for odd n (=2*k+1), Excel calculates the
1st (3rd) quartile as the median of the lower (upper) "half" of the sample
including the sample median (k+1 observations).

* #8 recommended by H&F because it is
approximately median-unbaised estimate regardless of distribution
and thus suitable for continuous and discrete distributions.
which gives quartiles between those reported by Minitab and Excel.
This approach is approximately median unbiased for continuous distributions.
Slightly higher interquartile range than definition 7.

The 'fences' beyond which points are regarded as outliers, or extreme outliers,
are a multiplying factor, usually called k, and usually 1.5 * interquartile range,
and 3 * interquartile range as recommended by Hoaglin et al.

*/

#include <vector>
using std::vector;
#include <cmath>
using ::sin;
//#include <boost/assert.hpp> // for BOOST_ASSERT
#include <boost/svg_plot/svg_boxplot.hpp>

#include <boost/svg_plot/quantile.hpp>
using boost::svg::quantile;

// double boost::svg::quantile(vector<double>& data, double p, int HF_definition);
// Estimate pth quantile of data using one of 5 definitions.
// Default HF_definition is the recommendation of Hyndman and Fan, definition #8.

#include <boost/array.hpp>
  using boost::array;

#include <iostream>
using std::cout;
using std::endl;
//] [demo_Hoaglin_1]

int main()
{
  using namespace boost::svg;
  try
  {
//[demo_Hoaglin_2]
  // 11 values from Hoaglin et al page 50.
  const boost::array<double, 11> Hoaglin_data = {53., 56., 75., 81., 82., 85., 87., 89., 95., 99., 100.};
  //                                                       q1           median           q3

  vector<double> Hoaglin(Hoaglin_data.begin(), Hoaglin_data.end());
  for (int def = 4; def <= 8; def++)
  { // All the F&Y definitions of quartiles.
    double q1 = quantile(Hoaglin, 0.25, def); // 75
    double q2 = quantile(Hoaglin, 0.5, def); // 85
    double q3 = quantile(Hoaglin, 0.75, def); // 95
    cout << "Hoaglin definition #" << def << ", q1 " << q1
      << ", q2 " << q2 << ", q3 " << q3 << ", IQR " << q3 - q1 << endl;
  } // for

  // Same data copied for different data series.
  vector<double> Hoaglin4(Hoaglin_data.begin(), Hoaglin_data.end());
  vector<double> Hoaglin5(Hoaglin_data.begin(), Hoaglin_data.end());
  vector<double> Hoaglin6(Hoaglin_data.begin(), Hoaglin_data.end());
  vector<double> Hoaglin7(Hoaglin_data.begin(), Hoaglin_data.end());
  vector<double> Hoaglin8(Hoaglin_data.begin(), Hoaglin_data.end());

  svg_boxplot H_boxplot;

  /*`Show the quartile definition default.
*/
    cout << "Default boxplot.quartile_definition() = " << H_boxplot.quartile_definition() << endl; // 8

/*` Add title, labels, range etc to the whole boxplot:
*/
  H_boxplot  // Title and axes labels.
    .title("Hoaglin Example Data")
    .x_label("Boxplot")
    .y_label("Value")
    .y_range(45, 115)  // Y-Axis range.
    .y_minor_tick_length(2)
    .y_major_interval(10);

/*`Add a few setting to the plot including setting quartile definition (though is actually same as the default 8),
and show that the value is stored.
*/
    svg_boxplot& b = H_boxplot.median_values_on(true)
    .outlier_values_on(true)
    .extreme_outlier_values_on(true)
    .quartile_definition(8);
/*`Show the quartile definition just assigned:
*/
    cout << "boxplot.quartile_definition() = " << b.quartile_definition() << endl; // 8

/*`Add a data series container, and labels, to the plot using the whole boxplot quartile definition set.
*/
    H_boxplot.plot(Hoaglin_data, "default_8");

/*`Add another data series container, and the labels, to the plot, and select a *different* quartile definition.
*/

    svg_boxplot_series& d4 =
    H_boxplot.plot(Hoaglin4, "def #4")
    .whisker_length(4.)
    .quartile_definition(4);

/*`Show the quartile definition just assigned to the this data series.
*/
  cout << "boxplot_series.quartile_definition() = " << d4.quartile_definition() << endl; // 4

/*`Add yet more data series container, and the labels, to the plot, and select a *different* quartile definition for each.
*/    H_boxplot.plot(Hoaglin5, "def #5")
    .whisker_length(5.)
    .quartile_definition(5);

    H_boxplot.plot(Hoaglin6, "def #6")
    .whisker_length(6.)
    .quartile_definition(6);

    H_boxplot.plot(Hoaglin6, "def #7")
    .whisker_length(7.)
    .quartile_definition(7);

    H_boxplot.plot(Hoaglin6, "def #8")
    .whisker_length(8.)
    .quartile_definition(8);

/*`Write the entire SVG plot to a file.
*/
  H_boxplot.write("demo_Hoaglin.svg");
//] [demo_Hoaglin_2]
  }
  catch(const std::exception& e)
  {
    std::cout <<
      "\n""Message from thrown exception was:\n  " << e.what() << std::endl;
  }
  return 0;
} // int main()

/*

Output:

//[demo_Hoaglin_output

``Autorun "j:\Cpp\SVG\debug\demo_Hoaglin.exe"
Hoaglin definition #4, q1 70.25, q2 83.5, q3 90.5, IQR 20.25
Hoaglin definition #5, q1 76.5, q2 85, q3 93.5, IQR 17
Hoaglin definition #6, q1 75, q2 85, q3 95, IQR 20
Hoaglin definition #7, q1 78, q2 85, q3 92, IQR 14
Hoaglin definition #8, q1 76, q2 85, q3 94, IQR 18
Default boxplot.quartile_definition() = 8
boxplot.quartile_definition() = 8
boxplot_series.quartile_definition() = 4
``
//] [demo_Hoaglin_output]

*/


text:
/*
 * lorenz_gmpxx.cpp
 *
 * This example demonstrates how odeint can be used with arbitrary precision types.
 *
 * Copyright 2011-2012 Karsten Ahnert
 * Copyright 2011-2012 Mario Mulansky
 *
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or
 * copy at http://www.boost.org/LICENSE_1_0.txt)
 */

#include <iostream>
#include <boost/array.hpp>

#include <gmpxx.h>

#include <boost/numeric/odeint.hpp>

using namespace std;
using namespace boost::numeric::odeint;

//[ gmpxx_lorenz
typedef mpf_class value_type;
typedef boost::array< value_type , 3 > state_type;

struct lorenz
{
    void operator()( const state_type &x , state_type &dxdt , value_type t ) const
    {
        const value_type sigma( 10.0 );
        const value_type R( 28.0 );
        const value_type b( value_type( 8.0 ) / value_type( 3.0 ) );

        dxdt[0] = sigma * ( x[1] - x[0] );
        dxdt[1] = R * x[0] - x[1] - x[0] * x[2];
        dxdt[2] = -b * x[2] + x[0] * x[1];
    }
};
//]

struct streaming_observer
{
    std::ostream& m_out;

    streaming_observer( std::ostream &out ) : m_out( out ) { }

    template< class State , class Time >
    void operator()( const State &x , Time t ) const
    {
        m_out << t;
        for( size_t i=0 ; i<x.size() ; ++i ) m_out << "\t" << x[i] ;
        m_out << "\n";
    }
};

int main( int argc , char **argv )
{
    //[ gmpxx_integration
    const int precision = 1024;
    mpf_set_default_prec( precision );

    state_type x = {{ value_type( 10.0 ) , value_type( 10.0 ) , value_type( 10.0 ) }};

    cout.precision( 1000 );
    integrate_const( runge_kutta4< state_type , value_type >() ,
            lorenz() , x , value_type( 0.0 ) , value_type( 10.0 ) , value_type( value_type( 1.0 ) / value_type( 10.0 ) ) ,
            streaming_observer( cout ) );
    //]

    return 0;
}


text:
//
// Copyright (C) 2016 Mirko Maischberger <mirko.maischberger@gmail.com>
//
// This file is part of WavingZ.
//
// WavingZ is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// WavingZ is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
//
// FSK @40000bps, NZR, Separation=40KHz

#include "wavingz.h"

#include <vector>
#include <cstdio>
#include <cstdint>
#include <iomanip>
#include <cassert>
#include <sstream>
#include <iostream>
#include <fstream>
#include <boost/program_options.hpp>

using namespace std;
namespace po = boost::program_options;

int
main(int argc, char* argv[])
{
    std::string payload;
    size_t sample_rate;
    size_t baud_rate;

    po::options_description desc("WavingZ - Wave-out options");
    desc.add_options()
        ("help,h", "Produce this help message")
        ("payload,p", po::value<std::string>(&payload), "Payload in format 01 23 45 67 89 AB CD EF ..")
        ("sample_rate,s", po::value<size_t>(&sample_rate)->default_value(2000000), "Sample rate (default 2M)")
        ("baud_rate,b", po::value<size_t>(&baud_rate)->default_value(40000), "Baudrate (default 40kbaud)")
        ("unsigned,u", "Produce uint8 output instead if int8")
       ;

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

    if (vm.count("help")) {
        cerr << desc << "\n";
        cerr << "\n";
        cerr << "Example:\n";
        cerr << "  HomeId:       0xD6B26208\n";
        cerr << "  SourceId:     0x01\n";
        cerr << "  FrameControl: 0x410F\n";
        cerr << "  Length:       0x0D (13 Bytes)\n";
        cerr << "  DestId:       0x03\n";
        cerr << "  CommandClass: 0x25 (SwitchBinary)\n";
        cerr << "  Payload:      0x01 0xFF 0x6B\n";
        cerr << "\n";
        cerr << "     wave-out -p 'd6 b2 62 08 01 41 0f 0d 03 25 01 ff 6b'\n";
        cerr << "\n";
        cerr << "  The Frame Check Sequence (8bit) is added automatically.\n";
        cerr << "\n";
        return EXIT_SUCCESS;
    }

    std::vector<uint8_t> buffer;
    if (!vm.count("payload"))
    {
        cerr << "Payload is mandatory." << std::endl;
        return EXIT_FAILURE;
    }
    else
    {
        std::stringstream interpreter(payload);
        while (interpreter) {
            int ch;
            interpreter >> std::hex >> ch;
            if(!interpreter) break;
            buffer.push_back((uint8_t)ch);
        }
    }
    buffer.push_back(wavingz::checksum(buffer.begin(), buffer.end()));
    std::ofstream file;
    wavingz::zwave_print(file,std::cerr, &buffer.front(), &buffer.front()+buffer.size()) << std::endl;

    // encode and output wavingz buffer
    if(vm.count("unsigned"))
    {
        wavingz::encoder<uint8_t> waver(sample_rate, baud_rate);
        auto complex_bytes = waver(buffer.begin(), buffer.end());
        for (auto pair : complex_bytes) std::cout << pair.first << pair.second;
    }
    else
    {
        wavingz::encoder<int8_t> waving(sample_rate, baud_rate);
        auto complex_bytes = waving(buffer.begin(), buffer.end());
        for (auto pair : complex_bytes) std::cout << pair.first << pair.second;
    }

    return EXIT_SUCCESS;
}